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>
5 ;;; This file is part of GNU Guix.
7 ;;; GNU Guix is free software; you can redistribute it and/or modify it
8 ;;; under the terms of the GNU General Public License as published by
9 ;;; the Free Software Foundation; either version 3 of the License, or (at
10 ;;; your option) any later version.
12 ;;; GNU Guix is distributed in the hope that it will be useful, but
13 ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
14 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 ;;; GNU General Public License for more details.
17 ;;; You should have received a copy of the GNU General Public License
18 ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
20 (define-module (guix store)
21 #:use-module (guix utils)
22 #:use-module (guix config)
23 #:use-module (guix deprecation)
24 #:use-module (guix memoization)
25 #:use-module (guix serialization)
26 #:use-module (guix monads)
27 #:use-module (guix records)
28 #:use-module (guix base16)
29 #:use-module (guix base32)
30 #:use-module (gcrypt hash)
31 #:use-module (guix profiling)
32 #:autoload (guix build syscalls) (terminal-columns)
33 #:use-module (rnrs bytevectors)
34 #:use-module (ice-9 binary-ports)
35 #:use-module ((ice-9 control) #:select (let/ec))
36 #:use-module (srfi srfi-1)
37 #:use-module (srfi srfi-9)
38 #:use-module (srfi srfi-9 gnu)
39 #:use-module (srfi srfi-11)
40 #:use-module (srfi srfi-26)
41 #:use-module (srfi srfi-34)
42 #:use-module (srfi srfi-35)
43 #:use-module (srfi srfi-39)
44 #:use-module (ice-9 match)
45 #:use-module (ice-9 regex)
46 #:use-module (ice-9 vlist)
47 #:use-module (ice-9 popen)
48 #:use-module (ice-9 threads)
49 #:use-module (ice-9 format)
50 #:use-module (web uri)
51 #:export (%daemon-socket-uri
53 %default-substitute-urls
56 store-connection-version
57 store-connection-major-version
58 store-connection-minor-version
59 store-connection-socket
61 ;; Deprecated forms for 'store-connection'.
64 nix-server-major-version
65 nix-server-minor-version
68 current-store-protocol-version ;for internal use
71 &store-error store-error?
72 &store-connection-error store-connection-error?
73 store-connection-error-file
74 store-connection-error-code
75 &store-protocol-error store-protocol-error?
76 store-protocol-error-message
77 store-protocol-error-status
79 ;; Deprecated forms for '&store-error' et al.
81 &nix-connection-error nix-connection-error?
82 nix-connection-error-file
83 nix-connection-error-code
84 &nix-protocol-error nix-protocol-error?
85 nix-protocol-error-message
86 nix-protocol-error-status
104 add-file-tree-to-store
113 remove-permanent-root
117 substitutable-deriver
118 substitutable-references
119 substitutable-download-size
120 substitutable-nar-size
123 substitutable-path-info
129 path-info-registration-time
134 references/substitutes
143 query-derivation-outputs
151 current-build-output-port
173 store-path-package-name
179 (define %protocol-version #x163)
181 (define %worker-magic-1 #x6e697863) ; "nixc"
182 (define %worker-magic-2 #x6478696f) ; "dxio"
184 (define (protocol-major magic)
185 (logand magic #xff00))
186 (define (protocol-minor magic)
187 (logand magic #x00ff))
188 (define (protocol-version major minor)
189 (logior major minor))
191 (define-syntax define-enumerate-type
193 ((_ name->int (name id) ...)
194 (define-syntax name->int
195 (syntax-rules (name ...)
196 ((_ name) id) ...)))))
198 (define-enumerate-type operation-id
199 ;; operation numbers from worker-protocol.hh
207 (add-text-to-store 8)
211 (add-indirect-root 12)
218 ;;(query-substitutable-path-info 21) ; obsolete as of #x10c
219 (query-derivation-outputs 22)
220 (query-all-valid-paths 23)
221 (query-failed-paths 24)
222 (clear-failed-paths 25)
225 (query-derivation-output-names 28)
226 (query-path-from-hash-part 29)
227 (query-substitutable-path-infos 30)
228 (query-valid-paths 31)
229 (query-substitutable-paths 32)
230 (query-valid-derivers 33)
233 (built-in-builders 80))
235 (define-enumerate-type hash-algo
241 (define-enumerate-type build-mode
247 (define-enumerate-type gc-action
254 (define %default-socket-path
255 (string-append %state-directory "/daemon-socket/socket"))
257 (define %daemon-socket-uri
258 ;; URI or file name of the socket the daemon listens too.
259 (make-parameter (or (getenv "GUIX_DAEMON_SOCKET")
260 %default-socket-path)))
264 ;; Information about a substitutable store path.
265 (define-record-type <substitutable>
266 (substitutable path deriver refs dl-size nar-size)
268 (path substitutable-path)
269 (deriver substitutable-deriver)
270 (refs substitutable-references)
271 (dl-size substitutable-download-size)
272 (nar-size substitutable-nar-size))
274 (define (read-substitutable-path-list p)
275 (let loop ((len (read-int p))
279 (let ((path (read-store-path p))
280 (deriver (read-store-path p))
281 (refs (read-store-path-list p))
282 (dl-size (read-long-long p))
283 (nar-size (read-long-long p)))
285 (cons (substitutable path deriver refs dl-size nar-size)
288 ;; Information about a store path.
289 (define-record-type <path-info>
290 (path-info deriver hash references registration-time nar-size)
292 (deriver path-info-deriver) ;string | #f
293 (hash path-info-hash)
294 (references path-info-references)
295 (registration-time path-info-registration-time)
296 (nar-size path-info-nar-size))
298 (define (read-path-info p)
299 (let ((deriver (match (read-store-path p)
302 (hash (base16-string->bytevector (read-string p)))
303 (refs (read-store-path-list p))
304 (registration-time (read-int p))
305 (nar-size (read-long-long p)))
306 (path-info deriver hash refs registration-time nar-size)))
308 (define-syntax write-arg
309 (syntax-rules (integer boolean bytevector
310 string string-list string-pairs
311 store-path store-path-list base16)
315 (write-int (if arg 1 0) p))
316 ((_ bytevector arg p)
317 (write-bytevector arg p))
319 (write-string arg p))
320 ((_ string-list arg p)
321 (write-string-list arg p))
322 ((_ string-pairs arg p)
323 (write-string-pairs arg p))
324 ((_ store-path arg p)
325 (write-store-path arg p))
326 ((_ store-path-list arg p)
327 (write-store-path-list arg p))
329 (write-string (bytevector->base16-string arg) p))))
331 (define-syntax read-arg
332 (syntax-rules (integer boolean string store-path store-path-list string-list
333 substitutable-path-list path-info base16)
337 (not (zero? (read-int p))))
342 ((_ store-path-list p)
343 (read-store-path-list p))
345 (read-string-list p))
346 ((_ substitutable-path-list p)
347 (read-substitutable-path-list p))
351 (base16-string->bytevector (read-string p)))))
356 (define-record-type* <store-connection> store-connection %make-store-connection
358 (socket store-connection-socket)
359 (major store-connection-major-version)
360 (minor store-connection-minor-version)
362 (buffer store-connection-output-port) ;output port
363 (flush store-connection-flush-output) ;thunk
365 ;; Caches. We keep them per-connection, because store paths build
366 ;; during the session are temporary GC roots kept for the duration of
368 (ats-cache store-connection-add-to-store-cache)
369 (atts-cache store-connection-add-text-to-store-cache)
370 (object-cache store-connection-object-cache
371 (default vlist-null)) ;vhash
372 (built-in-builders store-connection-built-in-builders
373 (default (delay '())))) ;promise
375 (set-record-type-printer! <store-connection>
377 (format port "#<store-connection ~a.~a ~a>"
378 (store-connection-major-version obj)
379 (store-connection-minor-version obj)
380 (number->string (object-address obj)
383 (define-deprecated/alias nix-server? store-connection?)
384 (define-deprecated/alias nix-server-major-version
385 store-connection-major-version)
386 (define-deprecated/alias nix-server-minor-version
387 store-connection-minor-version)
388 (define-deprecated/alias nix-server-socket store-connection-socket)
391 (define-condition-type &store-error &error
394 (define-condition-type &store-connection-error &store-error
395 store-connection-error?
396 (file store-connection-error-file)
397 (errno store-connection-error-code))
399 (define-condition-type &store-protocol-error &store-error
400 store-protocol-error?
401 (message store-protocol-error-message)
402 (status store-protocol-error-status))
404 (define-deprecated/alias &nix-error &store-error)
405 (define-deprecated/alias nix-error? store-error?)
406 (define-deprecated/alias &nix-connection-error &store-connection-error)
407 (define-deprecated/alias nix-connection-error? store-connection-error?)
408 (define-deprecated/alias nix-connection-error-file
409 store-connection-error-file)
410 (define-deprecated/alias nix-connection-error-code
411 store-connection-error-code)
412 (define-deprecated/alias &nix-protocol-error &store-protocol-error)
413 (define-deprecated/alias nix-protocol-error? store-protocol-error?)
414 (define-deprecated/alias nix-protocol-error-message
415 store-protocol-error-message)
416 (define-deprecated/alias nix-protocol-error-status
417 store-protocol-error-status)
420 (define-syntax-rule (system-error-to-connection-error file exp ...)
421 "Catch 'system-error' exceptions and translate them to
422 '&store-connection-error'."
427 (let ((errno (system-error-errno args)))
428 (raise (condition (&store-connection-error
432 (define (open-unix-domain-socket file)
433 "Connect to the Unix-domain socket at FILE and return it. Raise a
434 '&store-connection-error' upon error."
435 (let ((s (with-fluids ((%default-port-encoding #f))
436 ;; This trick allows use of the `scm_c_read' optimization.
437 (socket PF_UNIX SOCK_STREAM 0)))
438 (a (make-socket-address PF_UNIX file)))
440 (system-error-to-connection-error file
444 (define %default-guix-port
445 ;; Default port when connecting to a daemon over TCP/IP.
448 (define (open-inet-socket host port)
449 "Connect to the Unix-domain socket at HOST:PORT and return it. Raise a
450 '&store-connection-error' upon error."
451 (let ((sock (with-fluids ((%default-port-encoding #f))
452 ;; This trick allows use of the `scm_c_read' optimization.
453 (socket PF_UNIX SOCK_STREAM 0))))
456 (if (number? port) (number->string port) port)
458 (logior AI_ADDRCONFIG AI_NUMERICSERV)
460 0 ;any address family
461 SOCK_STREAM)) ;TCP only
463 (let loop ((addresses addresses))
466 (let ((s (socket (addrinfo:fam ai)
468 SOCK_STREAM IPPROTO_IP)))
472 (connect s (addrinfo:addr ai))
474 ;; Setting this option makes a dramatic difference because it
475 ;; avoids the "ACK delay" on our RPC messages.
476 (setsockopt s IPPROTO_TCP TCP_NODELAY 1)
479 ;; Connection failed, so try one of the other addresses.
482 (raise (condition (&store-connection-error
484 (errno (system-error-errno args)))))
487 (define (connect-to-daemon uri)
488 "Connect to the daemon at URI, a string that may be an actual URI or a file
490 (define (not-supported)
491 (raise (condition (&store-connection-error
496 (match (string->uri uri)
497 (#f ;URI is a file name
498 open-unix-domain-socket)
500 (match (uri-scheme uri)
503 (open-unix-domain-socket (uri-path uri))))
506 (open-inet-socket (uri-host uri)
507 (or (uri-port uri) %default-guix-port))))
509 ;; Try to dynamically load a module for SCHEME.
510 ;; XXX: Errors are swallowed.
511 (match (false-if-exception
512 (resolve-interface `(guix store ,scheme)))
514 (match (false-if-exception
515 (module-ref module 'connect-to-daemon))
516 ((? procedure? connect)
519 (x (not-supported))))
520 (#f (not-supported))))
526 (define* (open-connection #:optional (uri (%daemon-socket-uri))
527 #:key port (reserve-space? #t) cpu-affinity)
528 "Connect to the daemon at URI (a string), or, if PORT is not #f, use it as
529 the I/O port over which to communicate to a build daemon.
531 When RESERVE-SPACE? is true, instruct it to reserve a little bit of extra
532 space on the file system so that the garbage collector can still operate,
533 should the disk become full. When CPU-AFFINITY is true, it must be an integer
534 corresponding to an OS-level CPU number to which the daemon's worker process
535 for this connection will be pinned. Return a server object."
536 (guard (c ((nar-error? c)
537 ;; One of the 'write-' or 'read-' calls below failed, but this is
538 ;; really a connection error.
540 (&store-connection-error (file (or port uri))
542 (&message (message "build daemon handshake failed"))))))
543 (let*-values (((port)
544 (or port (connect-to-daemon uri)))
546 (buffering-output-port port
547 (make-bytevector 8192))))
548 (write-int %worker-magic-1 port)
549 (let ((r (read-int port)))
550 (and (eqv? r %worker-magic-2)
551 (let ((v (read-int port)))
552 (and (eqv? (protocol-major %protocol-version)
555 (write-int %protocol-version port)
556 (when (>= (protocol-minor v) 14)
557 (write-int (if cpu-affinity 1 0) port)
559 (write-int cpu-affinity port)))
560 (when (>= (protocol-minor v) 11)
561 (write-int (if reserve-space? 1 0) port))
562 (letrec* ((built-in-builders
563 (delay (%built-in-builders conn)))
565 (%make-store-connection port
569 (make-hash-table 100)
570 (make-hash-table 100)
573 (let loop ((done? (process-stderr conn)))
574 (or done? (process-stderr conn)))
577 (define* (port->connection port
578 #:key (version %protocol-version))
579 "Assimilate PORT, an input/output port, and return a connection to the
580 daemon, assuming the given protocol VERSION.
582 Warning: this procedure assumes that the initial handshake with the daemon has
583 already taken place on PORT and that we're just continuing on this established
584 connection. Use with care."
585 (let-values (((output flush)
586 (buffering-output-port port (make-bytevector 8192))))
588 (%make-store-connection port
589 (protocol-major version)
590 (protocol-minor version)
592 (make-hash-table 100)
593 (make-hash-table 100)
595 (delay (%built-in-builders connection))))
599 (define (store-connection-version store)
600 "Return the protocol version of STORE as an integer."
601 (protocol-version (store-connection-major-version store)
602 (store-connection-minor-version store)))
604 (define-deprecated/alias nix-server-version store-connection-version)
606 (define (write-buffered-output server)
607 "Flush SERVER's output port."
608 (force-output (store-connection-output-port server))
609 ((store-connection-flush-output server)))
611 (define (close-connection server)
612 "Close the connection to SERVER."
613 (close (store-connection-socket server)))
615 (define (call-with-store proc)
616 "Call PROC with an open store connection."
617 (let ((store (open-connection)))
621 (parameterize ((current-store-protocol-version
622 (store-connection-version store)))
625 (false-if-exception (close-connection store))))))
627 (define-syntax-rule (with-store store exp ...)
628 "Bind STORE to an open connection to the store and evaluate EXPs;
629 automatically close the store when the dynamic extent of EXP is left."
630 (call-with-store (lambda (store) exp ...)))
632 (define current-store-protocol-version
633 ;; Protocol version of the store currently used. XXX: This is a hack to
634 ;; communicate the protocol version to the build output port. It's a hack
635 ;; because it could be inaccurrate, for instance if there's code that
636 ;; manipulates several store connections at once; it works well for the
637 ;; purposes of (guix status) though.
640 (define current-build-output-port
641 ;; The port where build output is sent.
642 (make-parameter (current-error-port)))
644 (define* (dump-port in out
646 #:key (buffer-size 16384))
647 "Read LEN bytes from IN (or as much as possible if LEN is #f) and write it
648 to OUT, using chunks of BUFFER-SIZE bytes."
650 (make-bytevector buffer-size))
653 (bytes (get-bytevector-n! in buffer 0
655 (min len buffer-size)
657 (or (eof-object? bytes)
658 (and len (= total len))
659 (let ((total (+ total bytes)))
660 (put-bytevector out buffer 0 bytes)
662 (get-bytevector-n! in buffer 0
664 (min (- len total) buffer-size)
668 ;; Newline characters triggering a flush of 'current-build-output-port'.
669 ;; Unlike Guile's 'line, we flush upon #\return so that progress reports
670 ;; that use that trick are correctly displayed.
671 (char-set #\newline #\return))
673 (define* (process-stderr server #:optional user-port)
674 "Read standard output and standard error from SERVER, writing it to
675 CURRENT-BUILD-OUTPUT-PORT. Return #t when SERVER is done sending data, and
676 #f otherwise; in the latter case, the caller should call `process-stderr'
677 again until #t is returned or an error is raised.
679 Since the build process's output cannot be assumed to be UTF-8, we
680 conservatively consider it to be Latin-1, thereby avoiding possible
681 encoding conversion errors."
683 (store-connection-socket server))
685 ;; magic cookies from worker-protocol.hh
686 (define %stderr-next #x6f6c6d67) ; "olmg", build log
687 (define %stderr-read #x64617461) ; "data", data needed from source
688 (define %stderr-write #x64617416) ; "dat\x16", data for sink
689 (define %stderr-last #x616c7473) ; "alts", we're done
690 (define %stderr-error #x63787470) ; "cxtp", error reporting
692 (let ((k (read-int p)))
693 (cond ((= k %stderr-write)
694 ;; Write a byte stream to USER-PORT.
695 (let* ((len (read-int p))
697 (dump-port p user-port len
698 #:buffer-size (if (<= len 16384) 16384 65536))
700 ;; Consume padding, as for strings.
701 (get-bytevector-n p (- 8 m))))
704 ;; Read a byte stream from USER-PORT.
705 ;; Note: Avoid 'get-bytevector-n' to work around
706 ;; <http://bugs.gnu.org/17591> in Guile up to 2.0.11.
707 (let* ((max-len (read-int p))
708 (data (make-bytevector max-len))
709 (len (get-bytevector-n! user-port data 0 max-len)))
710 (write-bytevector data p len)
713 ;; Log a string. Build logs are usually UTF-8-encoded, but they
714 ;; may also contain arbitrary byte sequences that should not cause
715 ;; this to fail. Thus, use the permissive
716 ;; 'read-maybe-utf8-string'.
717 (let ((s (read-maybe-utf8-string p)))
718 (display s (current-build-output-port))
719 (when (string-any %newlines s)
720 (force-output (current-build-output-port)))
724 (let ((error (read-maybe-utf8-string p))
725 ;; Currently the daemon fails to send a status code for early
726 ;; errors like DB schema version mismatches, so check for EOF.
727 (status (if (and (>= (store-connection-minor-version server) 8)
728 (not (eof-object? (lookahead-u8 p))))
731 (raise (condition (&store-protocol-error
735 ;; The daemon is done (see `stopWork' in `nix-worker.cc'.)
738 (raise (condition (&store-protocol-error
739 (message "invalid error code")
742 (define %default-substitute-urls
743 ;; Default list of substituters. This is *not* the list baked in
744 ;; 'guix-daemon', but it is used by 'guix-service-type' and and a couple of
745 ;; clients ('guix build --log-file' uses it.)
746 (map (if (false-if-exception (resolve-interface '(gnutls)))
747 (cut string-append "https://" <>)
748 (cut string-append "http://" <>))
749 '("ci.guix.gnu.org")))
751 (define (current-user-name)
752 "Return the name of the calling user."
755 (passwd:name (getpwuid (getuid))))
759 (define* (set-build-options server
760 #:key keep-failed? keep-going? fallback?
762 rounds ;number of build rounds
769 (print-build-trace #t)
770 (user-name (current-user-name))
772 ;; When true, provide machine-readable "build
773 ;; traces" for use by (guix status). Old clients
774 ;; are unable to make sense, which is why it's
775 ;; disabled by default.
776 print-extended-build-trace?
778 ;; When true, the daemon prefixes builder output
779 ;; with "@ build-log" traces so we can
780 ;; distinguish it from daemon output, and we can
781 ;; distinguish each builder's output
782 ;; (PRINT-BUILD-TRACE must be true as well.) The
783 ;; latter is particularly useful when
784 ;; MAX-BUILD-JOBS > 1.
785 multiplexed-build-output?
788 (use-substitutes? #t)
790 ;; Client-provided substitute URLs. If it is #f,
791 ;; the daemon's settings are used. Otherwise, it
792 ;; overrides the daemons settings; see 'guix
796 ;; Number of columns in the client's terminal.
797 (terminal-columns (terminal-columns))
799 ;; Locale of the client.
800 (locale (false-if-exception (setlocale LC_ALL))))
801 ;; Must be called after `open-connection'.
804 (store-connection-socket server))
806 (let-syntax ((send (syntax-rules ()
807 ((_ (type option) ...)
809 (write-arg type option socket)
811 (write-int (operation-id set-options) socket)
812 (send (boolean keep-failed?) (boolean keep-going?)
813 (boolean fallback?) (integer verbosity))
814 (when (< (store-connection-minor-version server) #x61)
815 (let ((max-build-jobs (or max-build-jobs 1))
816 (max-silent-time (or max-silent-time 3600)))
817 (send (integer max-build-jobs) (integer max-silent-time))))
818 (when (>= (store-connection-minor-version server) 2)
819 (send (boolean use-build-hook?)))
820 (when (>= (store-connection-minor-version server) 4)
821 (send (integer build-verbosity) (integer log-type)
822 (boolean print-build-trace)))
823 (when (and (>= (store-connection-minor-version server) 6)
824 (< (store-connection-minor-version server) #x61))
825 (let ((build-cores (or build-cores (current-processor-count))))
826 (send (integer build-cores))))
827 (when (>= (store-connection-minor-version server) 10)
828 (send (boolean use-substitutes?)))
829 (when (>= (store-connection-minor-version server) 12)
830 (let ((pairs `(;; This option is honored by 'guix substitute' et al.
831 ,@(if print-build-trace
832 `(("print-extended-build-trace"
833 . ,(if print-extended-build-trace? "1" "0")))
835 ,@(if multiplexed-build-output?
836 `(("multiplexed-build-output"
837 . ,(if multiplexed-build-output? "true" "false")))
840 `(("build-timeout" . ,(number->string timeout)))
842 ,@(if max-silent-time
843 `(("build-max-silent-time"
844 . ,(number->string max-silent-time)))
848 . ,(number->string max-build-jobs)))
851 `(("build-cores" . ,(number->string build-cores)))
853 ,@(if substitute-urls
855 . ,(string-join substitute-urls)))
859 . ,(number->string (max 0 (1- rounds)))))
862 `(("user-name" . ,user-name))
864 ,@(if terminal-columns
865 `(("terminal-columns"
866 . ,(number->string terminal-columns)))
869 `(("locale" . ,locale))
871 (send (string-pairs pairs))))
872 (let loop ((done? (process-stderr server)))
873 (or done? (process-stderr server)))))
875 (define (buffering-output-port port buffer)
876 "Return two value: an output port wrapped around PORT that uses BUFFER (a
877 bytevector) as its internal buffer, and a thunk to flush this output port."
878 ;; Note: In Guile 2.2.2, custom binary output ports already have their own
879 ;; 4K internal buffer.
881 (bytevector-length buffer))
886 (put-bytevector port buffer 0 total)
890 (define (write bv offset count)
891 (if (zero? count) ;end of file
893 (let loop ((offset offset)
896 (cond ((= total size)
898 (loop offset count written))
902 (let ((to-copy (min count (- size total))))
903 (bytevector-copy! bv offset buffer total to-copy)
904 (set! total (+ total to-copy))
905 (loop (+ offset to-copy) (- count to-copy)
906 (+ written to-copy))))))))
908 ;; Note: We need to return FLUSH because the custom binary port has no way
909 ;; to be notified of a 'force-output' call on itself.
910 (values (make-custom-binary-output-port "buffering-output-port"
916 (or (and=> (getenv "GUIX_PROFILING") string-tokenize)
919 "Return true if COMPONENT profiling is active."
920 (member component profiled))))
923 ;; Mapping from RPC names (symbols) to invocation counts.
926 (define* (show-rpc-profile #:optional (port (current-error-port)))
927 "Write to PORT a summary of the RPCs that have been made."
928 (let ((profile (sort (hash-fold alist-cons '() %rpc-calls)
930 (< (cdr rpc1) (cdr rpc2))))))
931 (format port "Remote procedure call summary: ~a RPCs~%"
933 (((names . counts) ...)
934 (reduce + 0 counts))))
935 (for-each (match-lambda
937 (format port " ~30a ... ~5@a~%" rpc count)))
940 (define record-operation
941 ;; Optionally, increment the number of calls of the given RPC.
942 (if (profiled? "rpc")
944 (register-profiling-hook! "rpc" show-rpc-profile)
946 (let ((count (or (hashq-ref %rpc-calls name) 0)))
947 (hashq-set! %rpc-calls name (+ count 1)))))
951 (define-syntax operation
953 "Define a client-side RPC stub for the given operation."
954 ((_ (name (type arg) ...) docstring return ...)
955 (lambda (server arg ...)
957 (let* ((s (store-connection-socket server))
958 (buffered (store-connection-output-port server)))
959 (record-operation 'name)
960 (write-int (operation-id name) buffered)
961 (write-arg type arg buffered)
963 (write-buffered-output server)
965 ;; Loop until the server is done sending error output.
966 (let loop ((done? (process-stderr server)))
967 (or done? (loop (process-stderr server))))
968 (values (read-arg return s) ...))))))
970 (define-syntax-rule (define-operation (name args ...)
971 docstring return ...)
973 (operation (name args ...) docstring return ...)))
975 (define-operation (valid-path? (string path))
976 "Return #t when PATH designates a valid store item and #f otherwise (an
977 invalid item may exist on disk but still be invalid, for instance because it
978 is the result of an aborted or failed build.)
980 A '&store-protocol-error' condition is raised if PATH is not prefixed by the
981 store directory (/gnu/store)."
984 (define-operation (query-path-hash (store-path path))
985 "Return the SHA256 hash of the nar serialization of PATH as a bytevector."
988 (define hash-part->path
989 (let ((query-path-from-hash-part
990 (operation (query-path-from-hash-part (string hash))
993 (lambda (server hash-part)
994 "Return the store path whose hash part is HASH-PART (a nix-base32
995 string). Return the empty string if no such path exists."
996 ;; This RPC is primarily used by Hydra to reply to HTTP GETs of
998 (query-path-from-hash-part server hash-part))))
1000 (define-operation (query-path-info (store-path path))
1001 "Return the info (hash, references, etc.) for PATH."
1004 (define add-data-to-store
1005 ;; A memoizing version of `add-to-store', to avoid repeated RPCs with
1006 ;; the very same arguments during a given session.
1007 (let ((add-text-to-store
1008 (operation (add-text-to-store (string name) (bytevector text)
1009 (string-list references))
1012 (lookup (if (profiled? "add-data-to-store-cache")
1017 (define (show-stats)
1021 (* 100. (/ n lookups))))
1023 (format (current-error-port) "
1024 'add-data-to-store' cache:
1027 .drv files: ~5@a (~,1f%)
1028 Scheme files: ~5@a (~,1f%)~%"
1029 lookups hits (% hits)
1033 (register-profiling-hook! "add-data-to-store-cache"
1035 (lambda (cache args)
1036 (let ((result (hash-ref cache args)))
1037 (set! lookups (+ 1 lookups))
1039 (set! hits (+ 1 hits)))
1042 (cond ((string-suffix? ".drv" name)
1043 (set! drv (+ drv 1)))
1044 ((string-suffix? "-builder" name)
1045 (set! scheme (+ scheme 1)))
1046 ((string-suffix? ".scm" name)
1047 (set! scheme (+ scheme 1))))))
1050 (lambda* (server name bytes #:optional (references '()))
1051 "Add BYTES under file NAME in the store, and return its store path.
1052 REFERENCES is the list of store paths referred to by the resulting store
1054 (let* ((args `(,bytes ,name ,references))
1055 (cache (store-connection-add-text-to-store-cache server)))
1056 (or (lookup cache args)
1057 (let ((path (add-text-to-store server name bytes references)))
1058 (hash-set! cache args path)
1061 (define* (add-text-to-store store name text #:optional (references '()))
1062 "Add TEXT 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
1065 (add-data-to-store store name (string->utf8 text) references))
1068 ;; Define it once and for all since we use it as a default value for
1069 ;; 'add-to-store' and want to make sure two default values are 'eq?' for the
1070 ;; purposes or memoization.
1074 (define add-to-store
1075 ;; A memoizing version of `add-to-store'. This is important because
1076 ;; `add-to-store' leads to huge data transfers to the server, and
1077 ;; because it's often called many times with the very same argument.
1079 (lambda* (server basename recursive? hash-algo file-name
1080 #:key (select? true))
1081 ;; We don't use the 'operation' macro so we can pass SELECT? to
1083 (record-operation 'add-to-store)
1084 (let ((port (store-connection-socket server)))
1085 (write-int (operation-id add-to-store) port)
1086 (write-string basename port)
1087 (write-int 1 port) ;obsolete, must be #t
1088 (write-int (if recursive? 1 0) port)
1089 (write-string hash-algo port)
1090 (write-file file-name port #:select? select?)
1091 (write-buffered-output server)
1092 (let loop ((done? (process-stderr server)))
1093 (or done? (loop (process-stderr server))))
1094 (read-store-path port)))))
1095 (lambda* (server basename recursive? hash-algo file-name
1096 #:key (select? true))
1097 "Add the contents of FILE-NAME under BASENAME to the store. When
1098 RECURSIVE? is false, FILE-NAME must designate a regular file--not a directory
1099 nor a symlink. When RECURSIVE? is true and FILE-NAME designates a directory,
1100 the contents of FILE-NAME are added recursively; if FILE-NAME designates a
1101 flat file and RECURSIVE? is true, its contents are added, and its permission
1102 bits are kept. HASH-ALGO must be a string such as \"sha256\".
1104 When RECURSIVE? is true, call (SELECT? FILE STAT) for each directory entry,
1105 where FILE is the entry's absolute file name and STAT is the result of
1106 'lstat'; exclude entries for which SELECT? does not return true."
1107 ;; Note: We don't stat FILE-NAME at each call, and thus we assume that
1108 ;; the file remains unchanged for the lifetime of SERVER.
1109 (let* ((args `(,file-name ,basename ,recursive? ,hash-algo ,select?))
1110 (cache (store-connection-add-to-store-cache server)))
1111 (or (hash-ref cache args)
1112 (let ((path (add-to-store server basename recursive?
1114 #:select? select?)))
1115 (hash-set! cache args path)
1119 (char-set-complement (char-set #\/)))
1121 (define* (add-file-tree-to-store server tree
1123 (hash-algo "sha256")
1125 "Add the given TREE to the store on SERVER. TREE must be an entry such as:
1127 (\"my-tree\" directory
1128 (\"a\" regular (data \"hello\"))
1129 (\"b\" symlink \"a\")
1131 (\"d\" executable (file \"/bin/sh\"))))
1133 This is a generalized version of 'add-to-store'. It allows you to reproduce
1134 an arbitrary directory layout in the store without creating a derivation."
1136 ;; Note: The format of TREE was chosen to allow trees to be compared with
1137 ;; 'equal?', which in turn allows us to memoize things.
1140 ;; TREE is a single entry.
1147 (define (lookup file)
1148 (let loop ((components (string-tokenize file %not-slash))
1152 (assoc basename tree))
1155 (match (assoc-ref tree head)
1156 (('directory . entries) entries)))))))
1158 (define (file-type+size file)
1159 (match (lookup file)
1160 ((_ (and type (or 'directory 'symlink)) . _)
1162 ((_ type ('file file))
1163 (values type (stat:size (stat file))))
1164 ((_ type ('data (? string? data)))
1165 (values type (string-length data)))
1166 ((_ type ('data (? bytevector? data)))
1167 (values type (bytevector-length data)))))
1169 (define (file-port file)
1170 (match (lookup file)
1171 ((_ (or 'regular 'executable) content)
1173 (('file (? string? file))
1174 (open-file file "r0b"))
1175 (('data (? string? str))
1176 (open-input-string str))
1177 (('data (? bytevector? bv))
1178 (open-bytevector-input-port bv))))))
1180 (define (symlink-target file)
1181 (match (lookup file)
1182 ((_ 'symlink target) target)))
1184 (define (directory-entries directory)
1185 (match (lookup directory)
1186 ((_ 'directory (names . _) ...) names)))
1189 (store-connection-add-to-store-cache server))
1191 (or (hash-ref cache tree)
1193 ;; We don't use the 'operation' macro so we can use 'write-file-tree'
1194 ;; instead of 'write-file'.
1195 (record-operation 'add-to-store/tree)
1196 (let ((port (store-connection-socket server)))
1197 (write-int (operation-id add-to-store) port)
1198 (write-string basename port)
1199 (write-int 1 port) ;obsolete, must be #t
1200 (write-int (if recursive? 1 0) port)
1201 (write-string hash-algo port)
1202 (write-file-tree basename port
1203 #:file-type+size file-type+size
1204 #:file-port file-port
1205 #:symlink-target symlink-target
1206 #:directory-entries directory-entries)
1207 (write-buffered-output server)
1208 (let loop ((done? (process-stderr server)))
1209 (or done? (loop (process-stderr server))))
1210 (let ((result (read-store-path port)))
1211 (hash-set! cache tree result)
1214 (define build-things
1215 (let ((build (operation (build-things (string-list things)
1219 (build/old (operation (build-things (string-list things))
1222 (lambda* (store things #:optional (mode (build-mode normal)))
1223 "Build THINGS, a list of store items which may be either '.drv' files or
1224 outputs, and return when the worker is done building them. Elements of THINGS
1225 that are not derivations can only be substituted and not built locally.
1226 Alternately, an element of THING can be a derivation/output name pair, in
1227 which case the daemon will attempt to substitute just the requested output of
1228 the derivation. Return #t on success."
1229 (let ((things (map (match-lambda
1230 ((drv . output) (string-append drv "!" output))
1233 (parameterize ((current-store-protocol-version
1234 (store-connection-version store)))
1235 (if (>= (store-connection-minor-version store) 15)
1236 (build store things mode)
1237 (if (= mode (build-mode normal))
1238 (build/old store things)
1239 (raise (condition (&store-protocol-error
1240 (message "unsupported build mode")
1241 (status 1)))))))))))
1243 (define-operation (add-temp-root (store-path path))
1244 "Make PATH a temporary root for the duration of the current session.
1248 (define-operation (add-indirect-root (string file-name))
1249 "Make the symlink FILE-NAME an indirect root for the garbage collector:
1250 whatever store item FILE-NAME points to will not be collected. Return #t on
1253 FILE-NAME can be anywhere on the file system, but it must be an absolute file
1254 name--it is the caller's responsibility to ensure that it is an absolute file
1258 (define %gc-roots-directory
1259 ;; The place where garbage collector roots (symlinks) are kept.
1260 (string-append %state-directory "/gcroots"))
1262 (define (add-permanent-root target)
1263 "Add a garbage collector root pointing to TARGET, an element of the store,
1264 preventing TARGET from even being collected. This can also be used if TARGET
1267 Raise an error if the caller does not have write access to the GC root
1269 (let* ((root (string-append %gc-roots-directory "/" (basename target))))
1270 (catch 'system-error
1272 (symlink target root))
1274 ;; If ROOT already exists, this is fine; otherwise, re-throw.
1275 (unless (= EEXIST (system-error-errno args))
1276 (apply throw args))))))
1278 (define (remove-permanent-root target)
1279 "Remove the permanent garbage collector root pointing to TARGET. Raise an
1280 error if there is no such root."
1281 (delete-file (string-append %gc-roots-directory "/" (basename target))))
1284 (operation (query-references (store-path path))
1285 "Return the list of references of PATH."
1288 (define %reference-cache
1289 ;; Brute-force cache mapping store items to their list of references.
1290 ;; Caching matters because when building a profile in the presence of
1291 ;; grafts, we keep calling 'graft-derivation', which in turn calls
1292 ;; 'references/substitutes' many times with the same arguments. Ideally we
1293 ;; would use a cache associated with the daemon connection instead (XXX).
1294 (make-hash-table 100))
1296 (define (references/substitutes store items)
1297 "Return the list of list of references of ITEMS; the result has the same
1298 length as ITEMS. Query substitute information for any item missing from the
1299 store at once. Raise a '&store-protocol-error' exception if reference
1300 information for one of ITEMS is missing."
1301 (let* ((requested items)
1302 (local-refs (map (lambda (item)
1303 (or (hash-ref %reference-cache item)
1304 (guard (c ((store-protocol-error? c) #f))
1305 (references store item))))
1307 (missing (fold-right (lambda (item local-ref result)
1310 (cons item result)))
1314 ;; Query all the substitutes at once to minimize the cost of
1315 ;; launching 'guix substitute' and making HTTP requests.
1316 (substs (if (null? missing)
1318 (substitutable-path-info store missing))))
1319 (when (< (length substs) (length missing))
1320 (raise (condition (&store-protocol-error
1321 (message "cannot determine \
1322 the list of references")
1325 ;; Intersperse SUBSTS and LOCAL-REFS.
1326 (let loop ((items items)
1327 (local-refs local-refs)
1331 (let ((result (reverse result)))
1332 (for-each (cut hash-set! %reference-cache <> <>)
1339 (cons (any (lambda (subst)
1340 (and (string=? (substitutable-path subst) item)
1341 (substitutable-references subst)))
1346 (cons head result)))))))))
1348 (define* (fold-path store proc seed paths
1349 #:optional (relatives (cut references store <>)))
1350 "Call PROC for each of the RELATIVES of PATHS, exactly once, and return the
1351 result formed from the successive calls to PROC, the first of which is passed
1353 (let loop ((paths paths)
1358 (if (vhash-assoc path seen)
1359 (loop rest result seen)
1360 (let ((seen (vhash-cons path #t seen))
1361 (rest (append rest (relatives path)))
1362 (result (proc path result)))
1363 (loop rest result seen))))
1367 (define (requisites store paths)
1368 "Return the requisites of PATHS, including PATHS---i.e., their closures (all
1369 its references, recursively)."
1370 (fold-path store cons '() paths))
1372 (define (topologically-sorted store paths)
1373 "Return a list containing PATHS and all their references sorted in
1376 ;; Do a simple depth-first traversal of all of PATHS.
1377 (let loop ((paths paths)
1378 (visited vlist-null)
1381 (vhash-cons n #t visited))
1383 (define (visited? n)
1384 (vhash-assoc n visited))
1389 (loop tail visited result)
1392 (loop (references store head)
1395 (lambda (visited result)
1398 (cons head result))))))
1400 (values visited result)))))
1402 (call-with-values traverse
1407 (operation (query-referrers (store-path path))
1408 "Return the list of path that refer to PATH."
1411 (define valid-derivers
1412 (operation (query-valid-derivers (store-path path))
1413 "Return the list of valid \"derivers\" of PATH---i.e., all the
1414 .drv present in the store that have PATH among their outputs."
1417 (define query-derivation-outputs ; avoid name clash with `derivation-outputs'
1418 (operation (query-derivation-outputs (store-path path))
1419 "Return the list of outputs of PATH, a .drv file."
1422 (define-operation (has-substitutes? (store-path path))
1423 "Return #t if binary substitutes are available for PATH, and #f otherwise."
1426 (define substitutable-paths
1427 (operation (query-substitutable-paths (store-path-list paths))
1428 "Return the subset of PATHS that is substitutable."
1431 (define substitutable-path-info
1432 (operation (query-substitutable-path-infos (store-path-list paths))
1433 "Return information about the subset of PATHS that is
1434 substitutable. For each substitutable path, a `substitutable?' object is
1435 returned; thus, the resulting list can be shorter than PATHS. Furthermore,
1436 that there is no guarantee that the order of the resulting list matches the
1438 substitutable-path-list))
1440 (define %built-in-builders
1441 (let ((builders (operation (built-in-builders)
1442 "Return the built-in builders."
1445 "Return the names of the supported built-in derivation builders
1446 supported by STORE. The result is memoized for STORE."
1447 ;; Check whether STORE's version supports this RPC and built-in
1448 ;; derivation builders in general, which appeared in Guix > 0.11.0.
1449 ;; Return the empty list if it doesn't. Note that this RPC does not
1450 ;; exist in 'nix-daemon'.
1451 (if (or (> (store-connection-major-version store) #x100)
1452 (and (= (store-connection-major-version store) #x100)
1453 (>= (store-connection-minor-version store) #x60)))
1457 (define (built-in-builders store)
1458 "Return the names of the supported built-in derivation builders
1459 supported by STORE."
1460 (force (store-connection-built-in-builders store)))
1462 (define-operation (optimize-store)
1463 "Optimize the store by hard-linking identical files (\"deduplication\".)
1464 Return #t on success."
1465 ;; Note: the daemon in Guix <= 0.8.2 does not implement this RPC.
1468 (define verify-store
1469 (let ((verify (operation (verify-store (boolean check-contents?)
1473 (lambda* (store #:key check-contents? repair?)
1474 "Verify the integrity of the store and return false if errors remain,
1475 and true otherwise. When REPAIR? is true, repair any missing or altered store
1476 items by substituting them (this typically requires root privileges because it
1477 is not an atomic operation.) When CHECK-CONTENTS? is true, check the contents
1478 of store items; this can take a lot of time."
1479 (not (verify store check-contents? repair?)))))
1481 (define (run-gc server action to-delete min-freed)
1482 "Perform the garbage-collector operation ACTION, one of the
1483 `gc-action' values. When ACTION is `delete-specific', the TO-DELETE is
1484 the list of store paths to delete. IGNORE-LIVENESS? should always be
1485 #f. MIN-FREED is the minimum amount of disk space to be freed, in
1486 bytes, before the GC can stop. Return the list of store paths delete,
1487 and the number of bytes freed."
1488 (let ((s (store-connection-socket server)))
1489 (write-int (operation-id collect-garbage) s)
1490 (write-int action s)
1491 (write-store-path-list to-delete s)
1492 (write-arg boolean #f s) ; ignore-liveness?
1493 (write-long-long min-freed s)
1494 (write-int 0 s) ; obsolete
1495 (when (>= (store-connection-minor-version server) 5)
1496 ;; Obsolete `use-atime' and `max-atime' parameters.
1500 ;; Loop until the server is done sending error output.
1501 (let loop ((done? (process-stderr server)))
1502 (or done? (loop (process-stderr server))))
1504 (let ((paths (read-store-path-list s))
1505 (freed (read-long-long s))
1506 (obsolete (read-long-long s)))
1507 (unless (null? paths)
1508 ;; To be on the safe side, completely invalidate both caches.
1509 ;; Otherwise we could end up returning store paths that are no longer
1511 (hash-clear! (store-connection-add-to-store-cache server))
1512 (hash-clear! (store-connection-add-text-to-store-cache server)))
1514 (values paths freed))))
1516 (define-syntax-rule (%long-long-max)
1517 ;; Maximum unsigned 64-bit integer.
1520 (define (live-paths server)
1521 "Return the list of live store paths---i.e., store paths still
1522 referenced, and thus not subject to being garbage-collected."
1523 (run-gc server (gc-action return-live) '() (%long-long-max)))
1525 (define (dead-paths server)
1526 "Return the list of dead store paths---i.e., store paths no longer
1527 referenced, and thus subject to being garbage-collected."
1528 (run-gc server (gc-action return-dead) '() (%long-long-max)))
1530 (define* (collect-garbage server #:optional (min-freed (%long-long-max)))
1531 "Collect garbage from the store at SERVER. If MIN-FREED is non-zero,
1532 then collect at least MIN-FREED bytes. Return the paths that were
1533 collected, and the number of bytes freed."
1534 (run-gc server (gc-action delete-dead) '() min-freed))
1536 (define* (delete-paths server paths #:optional (min-freed (%long-long-max)))
1537 "Delete PATHS from the store at SERVER, if they are no longer
1538 referenced. If MIN-FREED is non-zero, then stop after at least
1539 MIN-FREED bytes have been collected. Return the paths that were
1540 collected, and the number of bytes freed."
1541 (run-gc server (gc-action delete-specific) paths min-freed))
1543 (define (import-paths server port)
1544 "Import the set of store paths read from PORT into SERVER's store. An error
1545 is raised if the set of paths read from PORT is not signed (as per
1546 'export-path #:sign? #t'.) Return the list of store paths imported."
1547 (let ((s (store-connection-socket server)))
1548 (write-int (operation-id import-paths) s)
1549 (let loop ((done? (process-stderr server port)))
1550 (or done? (loop (process-stderr server port))))
1551 (read-store-path-list s)))
1553 (define* (export-path server path port #:key (sign? #t))
1554 "Export PATH to PORT. When SIGN? is true, sign it."
1555 (let ((s (store-connection-socket server)))
1556 (write-int (operation-id export-path) s)
1557 (write-store-path path s)
1558 (write-arg boolean sign? s)
1559 (let loop ((done? (process-stderr server port)))
1560 (or done? (loop (process-stderr server port))))
1561 (= 1 (read-int s))))
1563 (define* (export-paths server paths port #:key (sign? #t) recursive?)
1564 "Export the store paths listed in PATHS to PORT, in topological order,
1565 signing them if SIGN? is true. When RECURSIVE? is true, export the closure of
1566 PATHS---i.e., PATHS and all their dependencies."
1568 (let ((sorted (topologically-sorted server paths)))
1569 ;; When RECURSIVE? is #f, filter out the references of PATHS.
1572 (filter (cut member <> paths) sorted))))
1574 (let loop ((paths ordered))
1580 (and (export-path server head port #:sign? sign?)
1583 (define-operation (query-failed-paths)
1584 "Return the list of store items for which a build failure is cached.
1586 The result is always the empty list unless the daemon was started with
1587 '--cache-failures'."
1590 (define-operation (clear-failed-paths (store-path-list items))
1591 "Remove ITEMS from the list of cached build failures.
1593 This makes sense only when the daemon was started with '--cache-failures'."
1601 (define-syntax-rule (define-alias new old)
1602 (define-syntax new (identifier-syntax old)))
1604 ;; The store monad allows us to (1) build sequences of operations in the
1605 ;; store, and (2) make the store an implicit part of the execution context,
1606 ;; rather than a parameter of every single function.
1607 (define-alias %store-monad %state-monad)
1608 (define-alias store-return state-return)
1609 (define-alias store-bind state-bind)
1611 ;; Instantiate templates for %STORE-MONAD since it's syntactically different
1612 ;; from %STATE-MONAD.
1613 (template-directory instantiations %store-monad)
1615 (define* (cache-object-mapping object keys result
1616 #:key (vhash-cons vhash-consq))
1617 "Augment the store's object cache with a mapping from OBJECT/KEYS to RESULT.
1618 KEYS is a list of additional keys to match against, for instance a (SYSTEM
1619 TARGET) tuple. Use VHASH-CONS to insert OBJECT into the cache.
1621 OBJECT is typically a high-level object such as a <package> or an <origin>,
1622 and RESULT is typically its derivation."
1627 (object-cache (vhash-cons object (cons result keys)
1628 (store-connection-object-cache store)))))))
1630 (define record-cache-lookup!
1631 (if (profiled? "object-cache")
1635 (register-profiling-hook!
1638 (format (current-error-port) "Store object cache:
1641 hits: ~5@a (~,1f%)~%"
1645 (* 100. (/ hits lookups))))))
1647 (lambda (hit? cache)
1649 (if (eq? cache vlist-null)
1652 (set! lookups (+ 1 lookups))
1653 (set! hits (if hit? (+ hits 1) hits))))
1657 (define* (lookup-cached-object object #:optional (keys '())
1658 #:key (vhash-fold* vhash-foldq*))
1659 "Return the cached object in the store connection corresponding to OBJECT
1660 and KEYS; use VHASH-FOLD* to look for OBJECT in the cache. KEYS is a list of
1661 additional keys to match against, and which are compared with 'equal?'.
1662 Return #f on failure and the cached result otherwise."
1664 (let* ((cache (store-connection-object-cache store))
1666 ;; Escape as soon as we find the result. This avoids traversing
1667 ;; the whole vlist chain and significantly reduces the number of
1669 (value (let/ec return
1670 (vhash-fold* (lambda (item result)
1673 (if (equal? keys keys*)
1678 (record-cache-lookup! value cache)
1679 (values value store))))
1681 (define* (%mcached mthunk object #:optional (keys '())
1683 (vhash-cons vhash-consq)
1684 (vhash-fold* vhash-foldq*))
1685 "Bind the monadic value returned by MTHUNK, which supposedly corresponds to
1686 OBJECT/KEYS, or return its cached value. Use VHASH-CONS to insert OBJECT into
1687 the cache, and VHASH-FOLD* to look it up."
1688 (mlet %store-monad ((cached (lookup-cached-object object keys
1689 #:vhash-fold* vhash-fold*)))
1694 (cache-object-mapping object keys result
1695 #:vhash-cons vhash-cons))))))
1697 (define-syntax mcached
1698 (syntax-rules (eq? equal?)
1699 "Run MVALUE, which corresponds to OBJECT/KEYS, and cache it; or return the
1700 value associated with OBJECT/KEYS in the store's object cache if there is
1702 ((_ eq? mvalue object keys ...)
1703 (%mcached (lambda () mvalue)
1704 object (list keys ...)
1705 #:vhash-cons vhash-consq
1706 #:vhash-fold* vhash-foldq*))
1707 ((_ equal? mvalue object keys ...)
1708 (%mcached (lambda () mvalue)
1709 object (list keys ...)
1710 #:vhash-cons vhash-cons
1711 #:vhash-fold* vhash-fold*))
1712 ((_ mvalue object keys ...)
1713 (mcached eq? mvalue object keys ...))))
1715 (define (preserve-documentation original proc)
1716 "Return PROC with documentation taken from ORIGINAL."
1717 (set-object-property! proc 'documentation
1718 (procedure-property original 'documentation))
1721 (define (store-lift proc)
1722 "Lift PROC, a procedure whose first argument is a connection to the store,
1723 in the store monad."
1724 (preserve-documentation proc
1727 (values (apply proc store args) store)))))
1729 (define (store-lower proc)
1730 "Lower PROC, a monadic procedure in %STORE-MONAD, to a \"normal\" procedure
1731 taking the store as its first argument."
1732 (preserve-documentation proc
1733 (lambda (store . args)
1734 (run-with-store store (apply proc args)))))
1737 ;; Store monad operators.
1740 (define* (binary-file name
1742 #:optional (references '()))
1743 "Return as a monadic value the absolute file name in the store of the file
1744 containing DATA, a bytevector. REFERENCES is a list of store items that the
1745 resulting text file refers to; it defaults to the empty list."
1747 (values (add-data-to-store store name data references)
1750 (define* (text-file name
1752 #:optional (references '()))
1753 "Return as a monadic value the absolute file name in the store of the file
1754 containing TEXT, a string. REFERENCES is a list of store items that the
1755 resulting text file refers to; it defaults to the empty list."
1757 (values (add-text-to-store store name text references)
1760 (define* (interned-file file #:optional name
1761 #:key (recursive? #t) (select? true))
1762 "Return the name of FILE once interned in the store. Use NAME as its store
1763 name, or the basename of FILE if NAME is omitted.
1765 When RECURSIVE? is true, the contents of FILE are added recursively; if FILE
1766 designates a flat file and RECURSIVE? is true, its contents are added, and its
1767 permission bits are kept.
1769 When RECURSIVE? is true, call (SELECT? FILE STAT) for each directory entry,
1770 where FILE is the entry's absolute file name and STAT is the result of
1771 'lstat'; exclude entries for which SELECT? does not return true."
1773 (values (add-to-store store (or name (basename file))
1774 recursive? "sha256" file
1778 (define interned-file-tree
1779 (store-lift add-file-tree-to-store))
1782 ;; Monadic variant of 'build-things'.
1783 (store-lift build-things))
1785 (define set-build-options*
1786 (store-lift set-build-options))
1789 (store-lift references))
1791 (define (query-path-info* item)
1792 "Monadic version of 'query-path-info' that returns #f when ITEM is not in
1795 (guard (c ((store-protocol-error? c)
1796 ;; ITEM is not in the store; return #f.
1798 (values (query-path-info store item) store))))
1800 (define-inlinable (current-system)
1801 ;; Consult the %CURRENT-SYSTEM fluid at bind time. This is equivalent to
1802 ;; (lift0 %current-system %store-monad), but inlinable, thus avoiding
1803 ;; closure allocation in some cases.
1805 (values (%current-system) state)))
1807 (define-inlinable (set-current-system system)
1808 ;; Set the %CURRENT-SYSTEM fluid at bind time.
1810 (values (%current-system system) state)))
1812 (define %guile-for-build
1813 ;; The derivation of the Guile to be used within the build environment,
1814 ;; when using 'gexp->derivation' and co.
1815 (make-parameter #f))
1817 (define set-store-connection-object-cache!
1818 (record-modifier <store-connection> 'object-cache))
1820 (define* (run-with-store store mval
1822 (guile-for-build (%guile-for-build))
1823 (system (%current-system))
1825 "Run MVAL, a monadic value in the store monad, in STORE, an open store
1826 connection, and return the result."
1827 ;; Initialize the dynamic bindings here to avoid bad surprises. The
1828 ;; difficulty lies in the fact that dynamic bindings are resolved at
1829 ;; bind-time and not at call time, which can be disconcerting.
1830 (parameterize ((%guile-for-build guile-for-build)
1831 (%current-system system)
1832 (%current-target-system target))
1833 (call-with-values (lambda ()
1834 (run-with-state mval store))
1835 (lambda (result new-store)
1836 (when (and store new-store)
1837 ;; Copy the object cache from NEW-STORE so we don't fully discard
1839 (let ((cache (store-connection-object-cache new-store)))
1840 (set-store-connection-object-cache! store cache)))
1848 (define %store-prefix
1849 ;; Absolute path to the Nix store.
1850 (make-parameter %store-directory))
1852 (define (compressed-hash bv size) ; `compressHash'
1853 "Given the hash stored in BV, return a compressed version thereof that fits
1855 (define new (make-bytevector size 0))
1856 (define old-size (bytevector-length bv))
1860 (let* ((j (modulo i size))
1861 (o (bytevector-u8-ref new j)))
1862 (bytevector-u8-set! new j
1863 (logxor o (bytevector-u8-ref bv i)))
1866 (define (store-path type hash name) ; makeStorePath
1867 "Return the store path for NAME/HASH/TYPE."
1868 (let* ((s (string-append type ":sha256:"
1869 (bytevector->base16-string hash) ":"
1870 (%store-prefix) ":" name))
1871 (h (sha256 (string->utf8 s)))
1872 (c (compressed-hash h 20)))
1873 (string-append (%store-prefix) "/"
1874 (bytevector->nix-base32-string c) "-"
1877 (define (output-path output hash name) ; makeOutputPath
1878 "Return an output path for OUTPUT (the name of the output as a string) of
1879 the derivation called NAME with hash HASH."
1880 (store-path (string-append "output:" output) hash
1881 (if (string=? output "out")
1883 (string-append name "-" output))))
1885 (define* (fixed-output-path name hash
1890 "Return an output path for the fixed output OUTPUT defined by HASH of type
1891 HASH-ALGO, of the derivation NAME. RECURSIVE? has the same meaning as for
1893 (if (and recursive? (eq? hash-algo 'sha256))
1894 (store-path "source" hash name)
1895 (let ((tag (string-append "fixed:" output ":"
1896 (if recursive? "r:" "")
1897 (symbol->string hash-algo) ":"
1898 (bytevector->base16-string hash) ":")))
1899 (store-path (string-append "output:" output)
1900 (sha256 (string->utf8 tag))
1903 (define (store-path? path)
1904 "Return #t if PATH is a store path."
1905 ;; This is a lightweight check, compared to using a regexp, but this has to
1906 ;; be fast as it's called often in `derivation', for instance.
1907 ;; `isStorePath' in Nix does something similar.
1908 (string-prefix? (%store-prefix) path))
1910 (define (direct-store-path? path)
1911 "Return #t if PATH is a store path, and not a sub-directory of a store path.
1912 This predicate is sometimes needed because files *under* a store path are not
1914 (and (store-path? path)
1915 (not (string=? path (%store-prefix)))
1916 (let ((len (+ 1 (string-length (%store-prefix)))))
1917 (not (string-index (substring path len) #\/)))))
1919 (define (direct-store-path path)
1920 "Return the direct store path part of PATH, stripping components after
1921 '/gnu/store/xxxx-foo'."
1922 (let ((prefix-length (+ (string-length (%store-prefix)) 35)))
1923 (if (> (string-length path) prefix-length)
1924 (let ((slash (string-index path #\/ prefix-length)))
1925 (if slash (string-take path slash) path))
1928 (define (derivation-path? path)
1929 "Return #t if PATH is a derivation path."
1930 (and (store-path? path) (string-suffix? ".drv" path)))
1932 (define store-regexp*
1933 ;; The substituter makes repeated calls to 'store-path-hash-part', hence
1934 ;; this optimization.
1936 "Return a regexp matching a file in STORE."
1937 (make-regexp (string-append "^" (regexp-quote store)
1938 "/([0-9a-df-np-sv-z]{32})-([^/]+)$"))))
1940 (define (store-path-package-name path)
1941 "Return the package name part of PATH, a file name in the store."
1942 (let ((path-rx (store-regexp* (%store-prefix))))
1943 (and=> (regexp-exec path-rx path)
1944 (cut match:substring <> 2))))
1946 (define (store-path-hash-part path)
1947 "Return the hash part of PATH as a base32 string, or #f if PATH is not a
1948 syntactically valid store path."
1949 (and (string-prefix? (%store-prefix) path)
1950 (let ((base (string-drop path (+ 1 (string-length (%store-prefix))))))
1951 (and (> (string-length base) 33)
1952 (let ((hash (string-take base 32)))
1953 (and (string-every %nix-base32-charset hash)
1956 (define (derivation-log-file drv)
1957 "Return the build log file for DRV, a derivation file name, or #f if it
1958 could not be found."
1959 (let* ((base (basename drv))
1960 (log (string-append (or (getenv "GUIX_LOG_DIRECTORY")
1961 (string-append %localstatedir "/log/guix"))
1963 (string-take base 2) "/"
1964 (string-drop base 2)))
1965 (log.gz (string-append log ".gz"))
1966 (log.bz2 (string-append log ".bz2")))
1967 (cond ((file-exists? log.gz) log.gz)
1968 ((file-exists? log.bz2) log.bz2)
1969 ((file-exists? log) log)
1972 (define (log-file store file)
1973 "Return the build log file for FILE, or #f if none could be found. FILE
1974 must be an absolute store file name, or a derivation file name."
1975 (cond ((derivation-path? file)
1976 (derivation-log-file file))
1978 (match (valid-derivers store file)
1980 ;; Return the first that works.
1981 (any (cut log-file store <>) derivers))
1984 ;;; Local Variables:
1985 ;;; eval: (put 'system-error-to-connection-error 'scheme-indent-function 1)