gnu: xpra: Update to 2.1.2.
[guix.git] / guix / store.scm
blobd571122021f98a7336e253a4871b37263532b581
1 ;;; GNU Guix --- Functional package management for GNU
2 ;;; Copyright © 2012, 2013, 2014, 2015, 2016, 2017 Ludovic Courtès <ludo@gnu.org>
3 ;;;
4 ;;; This file is part of GNU Guix.
5 ;;;
6 ;;; GNU Guix is free software; you can redistribute it and/or modify it
7 ;;; under the terms of the GNU General Public License as published by
8 ;;; the Free Software Foundation; either version 3 of the License, or (at
9 ;;; your option) any later version.
10 ;;;
11 ;;; GNU Guix is distributed in the hope that it will be useful, but
12 ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
13 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 ;;; GNU General Public License for more details.
15 ;;;
16 ;;; You should have received a copy of the GNU General Public License
17 ;;; along with GNU Guix.  If not, see <http://www.gnu.org/licenses/>.
19 (define-module (guix store)
20   #:use-module (guix utils)
21   #:use-module (guix config)
22   #:use-module (guix memoization)
23   #:use-module (guix serialization)
24   #:use-module (guix monads)
25   #:use-module (guix base16)
26   #:use-module (guix base32)
27   #:use-module (guix hash)
28   #:autoload   (guix build syscalls) (terminal-columns)
29   #:use-module (rnrs bytevectors)
30   #:use-module (ice-9 binary-ports)
31   #:use-module (srfi srfi-1)
32   #:use-module (srfi srfi-9)
33   #:use-module (srfi srfi-9 gnu)
34   #:use-module (srfi srfi-11)
35   #:use-module (srfi srfi-26)
36   #:use-module (srfi srfi-34)
37   #:use-module (srfi srfi-35)
38   #:use-module (srfi srfi-39)
39   #:use-module (ice-9 match)
40   #:use-module (ice-9 regex)
41   #:use-module (ice-9 vlist)
42   #:use-module (ice-9 popen)
43   #:use-module (ice-9 threads)
44   #:use-module (web uri)
45   #:export (%daemon-socket-uri
46             %gc-roots-directory
47             %default-substitute-urls
49             nix-server?
50             nix-server-major-version
51             nix-server-minor-version
52             nix-server-socket
54             &nix-error nix-error?
55             &nix-connection-error nix-connection-error?
56             nix-connection-error-file
57             nix-connection-error-code
58             &nix-protocol-error nix-protocol-error?
59             nix-protocol-error-message
60             nix-protocol-error-status
62             hash-algo
63             build-mode
65             open-connection
66             close-connection
67             with-store
68             set-build-options
69             set-build-options*
70             valid-path?
71             query-path-hash
72             hash-part->path
73             query-path-info
74             add-data-to-store
75             add-text-to-store
76             add-to-store
77             build-things
78             build
79             query-failed-paths
80             clear-failed-paths
81             add-temp-root
82             add-indirect-root
83             add-permanent-root
84             remove-permanent-root
86             substitutable?
87             substitutable-path
88             substitutable-deriver
89             substitutable-references
90             substitutable-download-size
91             substitutable-nar-size
92             has-substitutes?
93             substitutable-paths
94             substitutable-path-info
96             path-info?
97             path-info-deriver
98             path-info-hash
99             path-info-references
100             path-info-registration-time
101             path-info-nar-size
103             built-in-builders
104             references
105             references/substitutes
106             references*
107             requisites
108             referrers
109             optimize-store
110             verify-store
111             topologically-sorted
112             valid-derivers
113             query-derivation-outputs
114             live-paths
115             dead-paths
116             collect-garbage
117             delete-paths
118             import-paths
119             export-paths
121             current-build-output-port
123             register-path
125             %store-monad
126             store-bind
127             store-return
128             store-lift
129             store-lower
130             run-with-store
131             %guile-for-build
132             current-system
133             set-current-system
134             text-file
135             interned-file
137             %store-prefix
138             store-path
139             output-path
140             fixed-output-path
141             store-path?
142             direct-store-path?
143             derivation-path?
144             store-path-package-name
145             store-path-hash-part
146             direct-store-path
147             log-file))
149 (define %protocol-version #x161)
151 (define %worker-magic-1 #x6e697863)               ; "nixc"
152 (define %worker-magic-2 #x6478696f)               ; "dxio"
154 (define (protocol-major magic)
155   (logand magic #xff00))
156 (define (protocol-minor magic)
157   (logand magic #x00ff))
159 (define-syntax define-enumerate-type
160   (syntax-rules ()
161     ((_ name->int (name id) ...)
162      (define-syntax name->int
163        (syntax-rules (name ...)
164          ((_ name) id) ...)))))
166 (define-enumerate-type operation-id
167   ;; operation numbers from worker-protocol.hh
168   (quit 0)
169   (valid-path? 1)
170   (has-substitutes? 3)
171   (query-path-hash 4)
172   (query-references 5)
173   (query-referrers 6)
174   (add-to-store 7)
175   (add-text-to-store 8)
176   (build-things 9)
177   (ensure-path 10)
178   (add-temp-root 11)
179   (add-indirect-root 12)
180   (sync-with-gc 13)
181   (find-roots 14)
182   (export-path 16)
183   (query-deriver 18)
184   (set-options 19)
185   (collect-garbage 20)
186   ;;(query-substitutable-path-info 21)  ; obsolete as of #x10c
187   (query-derivation-outputs 22)
188   (query-all-valid-paths 23)
189   (query-failed-paths 24)
190   (clear-failed-paths 25)
191   (query-path-info 26)
192   (import-paths 27)
193   (query-derivation-output-names 28)
194   (query-path-from-hash-part 29)
195   (query-substitutable-path-infos 30)
196   (query-valid-paths 31)
197   (query-substitutable-paths 32)
198   (query-valid-derivers 33)
199   (optimize-store 34)
200   (verify-store 35)
201   (built-in-builders 80))
203 (define-enumerate-type hash-algo
204   ;; hash.hh
205   (md5 1)
206   (sha1 2)
207   (sha256 3))
209 (define-enumerate-type build-mode
210   ;; store-api.hh
211   (normal 0)
212   (repair 1)
213   (check 2))
215 (define-enumerate-type gc-action
216   ;; store-api.hh
217   (return-live 0)
218   (return-dead 1)
219   (delete-dead 2)
220   (delete-specific 3))
222 (define %default-socket-path
223   (string-append %state-directory "/daemon-socket/socket"))
225 (define %daemon-socket-uri
226   ;; URI or file name of the socket the daemon listens too.
227   (make-parameter (or (getenv "GUIX_DAEMON_SOCKET")
228                       %default-socket-path)))
232 ;; Information about a substitutable store path.
233 (define-record-type <substitutable>
234   (substitutable path deriver refs dl-size nar-size)
235   substitutable?
236   (path      substitutable-path)
237   (deriver   substitutable-deriver)
238   (refs      substitutable-references)
239   (dl-size   substitutable-download-size)
240   (nar-size  substitutable-nar-size))
242 (define (read-substitutable-path-list p)
243   (let loop ((len    (read-int p))
244              (result '()))
245     (if (zero? len)
246         (reverse result)
247         (let ((path     (read-store-path p))
248               (deriver  (read-store-path p))
249               (refs     (read-store-path-list p))
250               (dl-size  (read-long-long p))
251               (nar-size (read-long-long p)))
252           (loop (- len 1)
253                 (cons (substitutable path deriver refs dl-size nar-size)
254                       result))))))
256 ;; Information about a store path.
257 (define-record-type <path-info>
258   (path-info deriver hash references registration-time nar-size)
259   path-info?
260   (deriver path-info-deriver)                     ;string | #f
261   (hash path-info-hash)
262   (references path-info-references)
263   (registration-time path-info-registration-time)
264   (nar-size path-info-nar-size))
266 (define (read-path-info p)
267   (let ((deriver  (match (read-store-path p)
268                     ("" #f)
269                     (x  x)))
270         (hash     (base16-string->bytevector (read-string p)))
271         (refs     (read-store-path-list p))
272         (registration-time (read-int p))
273         (nar-size (read-long-long p)))
274     (path-info deriver hash refs registration-time nar-size)))
276 (define-syntax write-arg
277   (syntax-rules (integer boolean bytevector
278                  string string-list string-pairs
279                  store-path store-path-list base16)
280     ((_ integer arg p)
281      (write-int arg p))
282     ((_ boolean arg p)
283      (write-int (if arg 1 0) p))
284     ((_ bytevector arg p)
285      (write-bytevector arg p))
286     ((_ string arg p)
287      (write-string arg p))
288     ((_ string-list arg p)
289      (write-string-list arg p))
290     ((_ string-pairs arg p)
291      (write-string-pairs arg p))
292     ((_ store-path arg p)
293      (write-store-path arg p))
294     ((_ store-path-list arg p)
295      (write-store-path-list arg p))
296     ((_ base16 arg p)
297      (write-string (bytevector->base16-string arg) p))))
299 (define-syntax read-arg
300   (syntax-rules (integer boolean string store-path store-path-list string-list
301                  substitutable-path-list path-info base16)
302     ((_ integer p)
303      (read-int p))
304     ((_ boolean p)
305      (not (zero? (read-int p))))
306     ((_ string p)
307      (read-string p))
308     ((_ store-path p)
309      (read-store-path p))
310     ((_ store-path-list p)
311      (read-store-path-list p))
312     ((_ string-list p)
313      (read-string-list p))
314     ((_ substitutable-path-list p)
315      (read-substitutable-path-list p))
316     ((_ path-info p)
317      (read-path-info p))
318     ((_ base16 p)
319      (base16-string->bytevector (read-string p)))))
322 ;; remote-store.cc
324 (define-record-type <nix-server>
325   (%make-nix-server socket major minor
326                     buffer flush
327                     ats-cache atts-cache)
328   nix-server?
329   (socket nix-server-socket)
330   (major  nix-server-major-version)
331   (minor  nix-server-minor-version)
333   (buffer nix-server-output-port)                 ;output port
334   (flush  nix-server-flush-output)                ;thunk
336   ;; Caches.  We keep them per-connection, because store paths build
337   ;; during the session are temporary GC roots kept for the duration of
338   ;; the session.
339   (ats-cache  nix-server-add-to-store-cache)
340   (atts-cache nix-server-add-text-to-store-cache))
342 (set-record-type-printer! <nix-server>
343                           (lambda (obj port)
344                             (format port "#<build-daemon ~a.~a ~a>"
345                                     (nix-server-major-version obj)
346                                     (nix-server-minor-version obj)
347                                     (number->string (object-address obj)
348                                                     16))))
350 (define-condition-type &nix-error &error
351   nix-error?)
353 (define-condition-type &nix-connection-error &nix-error
354   nix-connection-error?
355   (file   nix-connection-error-file)
356   (errno  nix-connection-error-code))
358 (define-condition-type &nix-protocol-error &nix-error
359   nix-protocol-error?
360   (message nix-protocol-error-message)
361   (status  nix-protocol-error-status))
363 (define-syntax-rule (system-error-to-connection-error file exp ...)
364   "Catch 'system-error' exceptions and translate them to
365 '&nix-connection-error'."
366   (catch 'system-error
367     (lambda ()
368       exp ...)
369     (lambda args
370       (let ((errno (system-error-errno args)))
371         (raise (condition (&nix-connection-error
372                            (file file)
373                            (errno errno))))))))
375 (define (open-unix-domain-socket file)
376   "Connect to the Unix-domain socket at FILE and return it.  Raise a
377 '&nix-connection-error' upon error."
378   (let ((s (with-fluids ((%default-port-encoding #f))
379              ;; This trick allows use of the `scm_c_read' optimization.
380              (socket PF_UNIX SOCK_STREAM 0)))
381         (a (make-socket-address PF_UNIX file)))
383     (system-error-to-connection-error file
384       (connect s a)
385       s)))
387 (define %default-guix-port
388   ;; Default port when connecting to a daemon over TCP/IP.
389   44146)
391 (define (open-inet-socket host port)
392   "Connect to the Unix-domain socket at HOST:PORT and return it.  Raise a
393 '&nix-connection-error' upon error."
394   ;; Define 'TCP_NODELAY' on Guile 2.0.  The value is the same on all GNU
395   ;; systems.
396   (cond-expand (guile-2.2 #t)
397                (else      (define TCP_NODELAY 1)))
399   (let ((sock (with-fluids ((%default-port-encoding #f))
400                 ;; This trick allows use of the `scm_c_read' optimization.
401                 (socket PF_UNIX SOCK_STREAM 0))))
402     (define addresses
403       (getaddrinfo host
404                    (if (number? port) (number->string port) port)
405                    (if (number? port)
406                        (logior AI_ADDRCONFIG AI_NUMERICSERV)
407                        AI_ADDRCONFIG)
408                    0                              ;any address family
409                    SOCK_STREAM))                  ;TCP only
411     (let loop ((addresses addresses))
412       (match addresses
413         ((ai rest ...)
414          (let ((s (socket (addrinfo:fam ai)
415                           ;; TCP/IP only
416                           SOCK_STREAM IPPROTO_IP)))
418            (catch 'system-error
419              (lambda ()
420                (connect s (addrinfo:addr ai))
422                ;; Setting this option makes a dramatic difference because it
423                ;; avoids the "ACK delay" on our RPC messages.
424                (setsockopt s IPPROTO_TCP TCP_NODELAY 1)
425                s)
426              (lambda args
427                ;; Connection failed, so try one of the other addresses.
428                (close s)
429                (if (null? rest)
430                    (raise (condition (&nix-connection-error
431                                       (file host)
432                                       (errno (system-error-errno args)))))
433                    (loop rest))))))))))
435 (define (connect-to-daemon uri)
436   "Connect to the daemon at URI, a string that may be an actual URI or a file
437 name."
438   (define (not-supported)
439     (raise (condition (&nix-connection-error
440                        (file uri)
441                        (errno ENOTSUP)))))
443   (define connect
444     (match (string->uri uri)
445       (#f                                         ;URI is a file name
446        open-unix-domain-socket)
447       ((? uri? uri)
448        (match (uri-scheme uri)
449          ((or #f 'file 'unix)
450           (lambda (_)
451             (open-unix-domain-socket (uri-path uri))))
452          ('guix
453           (lambda (_)
454             (open-inet-socket (uri-host uri)
455                               (or (uri-port uri) %default-guix-port))))
456          ((? symbol? scheme)
457           ;; Try to dynamically load a module for SCHEME.
458           ;; XXX: Errors are swallowed.
459           (match (false-if-exception
460                   (resolve-interface `(guix store ,scheme)))
461             ((? module? module)
462              (match (false-if-exception
463                      (module-ref module 'connect-to-daemon))
464                ((? procedure? connect)
465                 (lambda (_)
466                   (connect uri)))
467                (x (not-supported))))
468             (#f (not-supported))))
469          (x
470           (not-supported))))))
472   (connect uri))
474 (define* (open-connection #:optional (uri (%daemon-socket-uri))
475                           #:key port (reserve-space? #t) cpu-affinity)
476   "Connect to the daemon at URI (a string), or, if PORT is not #f, use it as
477 the I/O port over which to communicate to a build daemon.
479 When RESERVE-SPACE? is true, instruct it to reserve a little bit of extra
480 space on the file system so that the garbage collector can still operate,
481 should the disk become full.  When CPU-AFFINITY is true, it must be an integer
482 corresponding to an OS-level CPU number to which the daemon's worker process
483 for this connection will be pinned.  Return a server object."
484   (guard (c ((nar-error? c)
485              ;; One of the 'write-' or 'read-' calls below failed, but this is
486              ;; really a connection error.
487              (raise (condition
488                      (&nix-connection-error (file (or port uri))
489                                             (errno EPROTO))
490                      (&message (message "build daemon handshake failed"))))))
491     (let*-values (((port)
492                    (or port (connect-to-daemon uri)))
493                   ((output flush)
494                    (buffering-output-port port
495                                           (make-bytevector 8192))))
496       (write-int %worker-magic-1 port)
497       (let ((r (read-int port)))
498         (and (eqv? r %worker-magic-2)
499              (let ((v (read-int port)))
500                (and (eqv? (protocol-major %protocol-version)
501                           (protocol-major v))
502                     (begin
503                       (write-int %protocol-version port)
504                       (when (>= (protocol-minor v) 14)
505                         (write-int (if cpu-affinity 1 0) port)
506                         (when cpu-affinity
507                           (write-int cpu-affinity port)))
508                       (when (>= (protocol-minor v) 11)
509                         (write-int (if reserve-space? 1 0) port))
510                       (let ((conn (%make-nix-server port
511                                                     (protocol-major v)
512                                                     (protocol-minor v)
513                                                     output flush
514                                                     (make-hash-table 100)
515                                                     (make-hash-table 100))))
516                         (let loop ((done? (process-stderr conn)))
517                           (or done? (process-stderr conn)))
518                         conn)))))))))
520 (define (write-buffered-output server)
521   "Flush SERVER's output port."
522   (force-output (nix-server-output-port server))
523   ((nix-server-flush-output server)))
525 (define (close-connection server)
526   "Close the connection to SERVER."
527   (close (nix-server-socket server)))
529 (define-syntax-rule (with-store store exp ...)
530   "Bind STORE to an open connection to the store and evaluate EXPs;
531 automatically close the store when the dynamic extent of EXP is left."
532   (let ((store (open-connection)))
533     (dynamic-wind
534       (const #f)
535       (lambda ()
536         exp ...)
537       (lambda ()
538         (false-if-exception (close-connection store))))))
540 (define current-build-output-port
541   ;; The port where build output is sent.
542   (make-parameter (current-error-port)))
544 (define* (dump-port in out
545                     #:optional len
546                     #:key (buffer-size 16384))
547   "Read LEN bytes from IN (or as much as possible if LEN is #f) and write it
548 to OUT, using chunks of BUFFER-SIZE bytes."
549   (define buffer
550     (make-bytevector buffer-size))
552   (let loop ((total 0)
553              (bytes (get-bytevector-n! in buffer 0
554                                        (if len
555                                            (min len buffer-size)
556                                            buffer-size))))
557     (or (eof-object? bytes)
558         (and len (= total len))
559         (let ((total (+ total bytes)))
560           (put-bytevector out buffer 0 bytes)
561           (loop total
562                 (get-bytevector-n! in buffer 0
563                                    (if len
564                                        (min (- len total) buffer-size)
565                                        buffer-size)))))))
567 (define %newlines
568   ;; Newline characters triggering a flush of 'current-build-output-port'.
569   ;; Unlike Guile's _IOLBF, we flush upon #\return so that progress reports
570   ;; that use that trick are correctly displayed.
571   (char-set #\newline #\return))
573 (define* (process-stderr server #:optional user-port)
574   "Read standard output and standard error from SERVER, writing it to
575 CURRENT-BUILD-OUTPUT-PORT.  Return #t when SERVER is done sending data, and
576 #f otherwise; in the latter case, the caller should call `process-stderr'
577 again until #t is returned or an error is raised.
579 Since the build process's output cannot be assumed to be UTF-8, we
580 conservatively consider it to be Latin-1, thereby avoiding possible
581 encoding conversion errors."
582   (define p
583     (nix-server-socket server))
585   ;; magic cookies from worker-protocol.hh
586   (define %stderr-next  #x6f6c6d67)          ; "olmg", build log
587   (define %stderr-read  #x64617461)          ; "data", data needed from source
588   (define %stderr-write #x64617416)          ; "dat\x16", data for sink
589   (define %stderr-last  #x616c7473)          ; "alts", we're done
590   (define %stderr-error #x63787470)          ; "cxtp", error reporting
592   (let ((k (read-int p)))
593     (cond ((= k %stderr-write)
594            ;; Write a byte stream to USER-PORT.
595            (let* ((len (read-int p))
596                   (m   (modulo len 8)))
597              (dump-port p user-port len
598                         #:buffer-size (if (<= len 16384) 16384 65536))
599              (unless (zero? m)
600                ;; Consume padding, as for strings.
601                (get-bytevector-n p (- 8 m))))
602            #f)
603           ((= k %stderr-read)
604            ;; Read a byte stream from USER-PORT.
605            ;; Note: Avoid 'get-bytevector-n' to work around
606            ;; <http://bugs.gnu.org/17591> in Guile up to 2.0.11.
607            (let* ((max-len (read-int p))
608                   (data    (make-bytevector max-len))
609                   (len     (get-bytevector-n! user-port data 0 max-len)))
610              (write-bytevector data p)
611              #f))
612           ((= k %stderr-next)
613            ;; Log a string.  Build logs are usually UTF-8-encoded, but they
614            ;; may also contain arbitrary byte sequences that should not cause
615            ;; this to fail.  Thus, use the permissive
616            ;; 'read-maybe-utf8-string'.
617            (let ((s (read-maybe-utf8-string p)))
618              (display s (current-build-output-port))
619              (when (string-any %newlines s)
620                (force-output (current-build-output-port)))
621              #f))
622           ((= k %stderr-error)
623            ;; Report an error.
624            (let ((error  (read-maybe-utf8-string p))
625                  ;; Currently the daemon fails to send a status code for early
626                  ;; errors like DB schema version mismatches, so check for EOF.
627                  (status (if (and (>= (nix-server-minor-version server) 8)
628                                   (not (eof-object? (lookahead-u8 p))))
629                              (read-int p)
630                              1)))
631              (raise (condition (&nix-protocol-error
632                                 (message error)
633                                 (status  status))))))
634           ((= k %stderr-last)
635            ;; The daemon is done (see `stopWork' in `nix-worker.cc'.)
636            #t)
637           (else
638            (raise (condition (&nix-protocol-error
639                               (message "invalid error code")
640                               (status   k))))))))
642 (define %default-substitute-urls
643   ;; Default list of substituters.  This is *not* the list baked in
644   ;; 'guix-daemon', but it is used by 'guix-service-type' and and a couple of
645   ;; clients ('guix build --log-file' uses it.)
646   (map (if (false-if-exception (resolve-interface '(gnutls)))
647            (cut string-append "https://" <>)
648            (cut string-append "http://" <>))
649        '("mirror.hydra.gnu.org")))
651 (define* (set-build-options server
652                             #:key keep-failed? keep-going? fallback?
653                             (verbosity 0)
654                             rounds                ;number of build rounds
655                             max-build-jobs
656                             timeout
657                             max-silent-time
658                             (use-build-hook? #t)
659                             (build-verbosity 0)
660                             (log-type 0)
661                             (print-build-trace #t)
662                             build-cores
663                             (use-substitutes? #t)
665                             ;; Client-provided substitute URLs.  If it is #f,
666                             ;; the daemon's settings are used.  Otherwise, it
667                             ;; overrides the daemons settings; see 'guix
668                             ;; substitute'.
669                             (substitute-urls #f)
671                             ;; Number of columns in the client's terminal.
672                             (terminal-columns (terminal-columns))
674                             ;; Locale of the client.
675                             (locale (false-if-exception (setlocale LC_ALL))))
676   ;; Must be called after `open-connection'.
678   (define socket
679     (nix-server-socket server))
681   (let-syntax ((send (syntax-rules ()
682                        ((_ (type option) ...)
683                         (begin
684                           (write-arg type option socket)
685                           ...)))))
686     (write-int (operation-id set-options) socket)
687     (send (boolean keep-failed?) (boolean keep-going?)
688           (boolean fallback?) (integer verbosity))
689     (when (< (nix-server-minor-version server) #x61)
690       (let ((max-build-jobs (or max-build-jobs 1))
691             (max-silent-time (or max-silent-time 3600)))
692         (send (integer max-build-jobs) (integer max-silent-time))))
693     (when (>= (nix-server-minor-version server) 2)
694       (send (boolean use-build-hook?)))
695     (when (>= (nix-server-minor-version server) 4)
696       (send (integer build-verbosity) (integer log-type)
697             (boolean print-build-trace)))
698     (when (and (>= (nix-server-minor-version server) 6)
699                (< (nix-server-minor-version server) #x61))
700       (let ((build-cores (or build-cores (current-processor-count))))
701         (send (integer build-cores))))
702     (when (>= (nix-server-minor-version server) 10)
703       (send (boolean use-substitutes?)))
704     (when (>= (nix-server-minor-version server) 12)
705       (let ((pairs `(,@(if timeout
706                            `(("build-timeout" . ,(number->string timeout)))
707                            '())
708                      ,@(if max-silent-time
709                            `(("build-max-silent-time"
710                               . ,(number->string max-silent-time)))
711                            '())
712                      ,@(if max-build-jobs
713                            `(("build-max-jobs"
714                               . ,(number->string max-build-jobs)))
715                            '())
716                      ,@(if build-cores
717                            `(("build-cores" . ,(number->string build-cores)))
718                            '())
719                      ,@(if substitute-urls
720                            `(("substitute-urls"
721                               . ,(string-join substitute-urls)))
722                            '())
723                      ,@(if rounds
724                            `(("build-repeat"
725                               . ,(number->string (max 0 (1- rounds)))))
726                            '())
727                      ,@(if terminal-columns
728                            `(("terminal-columns"
729                               . ,(number->string terminal-columns)))
730                            '())
731                      ,@(if locale
732                            `(("locale" . ,locale))
733                            '()))))
734         (send (string-pairs pairs))))
735     (let loop ((done? (process-stderr server)))
736       (or done? (process-stderr server)))))
738 (define (buffering-output-port port buffer)
739   "Return two value: an output port wrapped around PORT that uses BUFFER (a
740 bytevector) as its internal buffer, and a thunk to flush this output port."
741   ;; Note: In Guile 2.2.2, custom binary output ports already have their own
742   ;; 4K internal buffer.
743   (define size
744     (bytevector-length buffer))
746   (define total 0)
748   (define (flush)
749     (put-bytevector port buffer 0 total)
750     (set! total 0))
752   (define (write bv offset count)
753     (if (zero? count)                             ;end of file
754         (flush)
755         (let loop ((offset offset)
756                    (count count)
757                    (written 0))
758           (cond ((= total size)
759                  (flush)
760                  (loop offset count written))
761                 ((zero? count)
762                  written)
763                 (else
764                  (let ((to-copy (min count (- size total))))
765                    (bytevector-copy! bv offset buffer total to-copy)
766                    (set! total (+ total to-copy))
767                    (loop (+ offset to-copy) (- count to-copy)
768                          (+ written to-copy))))))))
770   ;; Note: We need to return FLUSH because the custom binary port has no way
771   ;; to be notified of a 'force-output' call on itself.
772   (values (make-custom-binary-output-port "buffering-output-port"
773                                           write #f #f flush)
774           flush))
776 (define %rpc-calls
777   ;; Mapping from RPC names (symbols) to invocation counts.
778   (make-hash-table))
780 (define* (show-rpc-profile #:optional (port (current-error-port)))
781   "Write to PORT a summary of the RPCs that have been made."
782   (let ((profile (sort (hash-fold alist-cons '() %rpc-calls)
783                        (lambda (rpc1 rpc2)
784                          (< (cdr rpc1) (cdr rpc2))))))
785     (format port "Remote procedure call summary: ~a RPCs~%"
786             (match profile
787               (((names . counts) ...)
788                (reduce + 0 counts))))
789     (for-each (match-lambda
790                 ((rpc . count)
791                  (format port "  ~30a ... ~5@a~%" rpc count)))
792               profile)))
794 (define record-operation
795   ;; Optionally, increment the number of calls of the given RPC.
796   (let ((profiled (or (and=> (getenv "GUIX_PROFILING") string-tokenize)
797                       '())))
798     (if (member "rpc" profiled)
799         (begin
800           (add-hook! exit-hook show-rpc-profile)
801           (lambda (name)
802             (let ((count (or (hashq-ref %rpc-calls name) 0)))
803               (hashq-set! %rpc-calls name (+ count 1)))))
804         (lambda (_)
805           #t))))
807 (define-syntax operation
808   (syntax-rules ()
809     "Define a client-side RPC stub for the given operation."
810     ((_ (name (type arg) ...) docstring return ...)
811      (lambda (server arg ...)
812        docstring
813        (let* ((s (nix-server-socket server))
814               (buffered (nix-server-output-port server)))
815          (record-operation 'name)
816          (write-int (operation-id name) buffered)
817          (write-arg type arg buffered)
818          ...
819          (write-buffered-output server)
821          ;; Loop until the server is done sending error output.
822          (let loop ((done? (process-stderr server)))
823            (or done? (loop (process-stderr server))))
824          (values (read-arg return s) ...))))))
826 (define-syntax-rule (define-operation (name args ...)
827                       docstring return ...)
828   (define name
829     (operation (name args ...) docstring return ...)))
831 (define-operation (valid-path? (string path))
832   "Return #t when PATH designates a valid store item and #f otherwise (an
833 invalid item may exist on disk but still be invalid, for instance because it
834 is the result of an aborted or failed build.)
836 A '&nix-protocol-error' condition is raised if PATH is not prefixed by the
837 store directory (/gnu/store)."
838   boolean)
840 (define-operation (query-path-hash (store-path path))
841   "Return the SHA256 hash of the nar serialization of PATH as a bytevector."
842   base16)
844 (define hash-part->path
845   (let ((query-path-from-hash-part
846          (operation (query-path-from-hash-part (string hash))
847                     #f
848                     store-path)))
849    (lambda (server hash-part)
850      "Return the store path whose hash part is HASH-PART (a nix-base32
851 string).  Raise an error if no such path exists."
852      ;; This RPC is primarily used by Hydra to reply to HTTP GETs of
853      ;; /HASH.narinfo.
854      (query-path-from-hash-part server hash-part))))
856 (define-operation (query-path-info (store-path path))
857   "Return the info (hash, references, etc.) for PATH."
858   path-info)
860 (define add-data-to-store
861   ;; A memoizing version of `add-to-store', to avoid repeated RPCs with
862   ;; the very same arguments during a given session.
863   (let ((add-text-to-store
864          (operation (add-text-to-store (string name) (bytevector text)
865                                        (string-list references))
866                     #f
867                     store-path)))
868     (lambda* (server name bytes #:optional (references '()))
869       "Add BYTES under file NAME in the store, and return its store path.
870 REFERENCES is the list of store paths referred to by the resulting store
871 path."
872       (let* ((args  `(,bytes ,name ,references))
873              (cache (nix-server-add-text-to-store-cache server)))
874         (or (hash-ref cache args)
875             (let ((path (add-text-to-store server name bytes references)))
876               (hash-set! cache args path)
877               path))))))
879 (define* (add-text-to-store store name text #:optional (references '()))
880   "Add TEXT under file NAME in the store, and return its store path.
881 REFERENCES is the list of store paths referred to by the resulting store
882 path."
883   (add-data-to-store store name (string->utf8 text) references))
885 (define true
886   ;; Define it once and for all since we use it as a default value for
887   ;; 'add-to-store' and want to make sure two default values are 'eq?' for the
888   ;; purposes or memoization.
889   (lambda (file stat)
890     #t))
892 (define add-to-store
893   ;; A memoizing version of `add-to-store'.  This is important because
894   ;; `add-to-store' leads to huge data transfers to the server, and
895   ;; because it's often called many times with the very same argument.
896   (let ((add-to-store
897          (lambda* (server basename recursive? hash-algo file-name
898                           #:key (select? true))
899            ;; We don't use the 'operation' macro so we can pass SELECT? to
900            ;; 'write-file'.
901            (record-operation 'add-to-store)
902            (let ((port (nix-server-socket server)))
903              (write-int (operation-id add-to-store) port)
904              (write-string basename port)
905              (write-int 1 port)                   ;obsolete, must be #t
906              (write-int (if recursive? 1 0) port)
907              (write-string hash-algo port)
908              (write-file file-name port #:select? select?)
909              (let loop ((done? (process-stderr server)))
910                (or done? (loop (process-stderr server))))
911              (read-store-path port)))))
912     (lambda* (server basename recursive? hash-algo file-name
913                      #:key (select? true))
914       "Add the contents of FILE-NAME under BASENAME to the store.  When
915 RECURSIVE? is false, FILE-NAME must designate a regular file--not a directory
916 nor a symlink.  When RECURSIVE? is true and FILE-NAME designates a directory,
917 the contents of FILE-NAME are added recursively; if FILE-NAME designates a
918 flat file and RECURSIVE? is true, its contents are added, and its permission
919 bits are kept.  HASH-ALGO must be a string such as \"sha256\".
921 When RECURSIVE? is true, call (SELECT?  FILE STAT) for each directory entry,
922 where FILE is the entry's absolute file name and STAT is the result of
923 'lstat'; exclude entries for which SELECT? does not return true."
924       ;; Note: We don't stat FILE-NAME at each call, and thus we assume that
925       ;; the file remains unchanged for the lifetime of SERVER.
926       (let* ((args  `(,file-name ,basename ,recursive? ,hash-algo ,select?))
927              (cache (nix-server-add-to-store-cache server)))
928         (or (hash-ref cache args)
929             (let ((path (add-to-store server basename recursive?
930                                       hash-algo file-name
931                                       #:select? select?)))
932               (hash-set! cache args path)
933               path))))))
935 (define build-things
936   (let ((build (operation (build-things (string-list things)
937                                         (integer mode))
938                           "Do it!"
939                           boolean))
940         (build/old (operation (build-things (string-list things))
941                               "Do it!"
942                               boolean)))
943     (lambda* (store things #:optional (mode (build-mode normal)))
944       "Build THINGS, a list of store items which may be either '.drv' files or
945 outputs, and return when the worker is done building them.  Elements of THINGS
946 that are not derivations can only be substituted and not built locally.
947 Return #t on success."
948       (if (>= (nix-server-minor-version store) 15)
949           (build store things mode)
950           (if (= mode (build-mode normal))
951               (build/old store things)
952               (raise (condition (&nix-protocol-error
953                                  (message "unsupported build mode")
954                                  (status  1)))))))))
956 (define-operation (add-temp-root (store-path path))
957   "Make PATH a temporary root for the duration of the current session.
958 Return #t."
959   boolean)
961 (define-operation (add-indirect-root (string file-name))
962   "Make the symlink FILE-NAME an indirect root for the garbage collector:
963 whatever store item FILE-NAME points to will not be collected.  Return #t on
964 success.
966 FILE-NAME can be anywhere on the file system, but it must be an absolute file
967 name--it is the caller's responsibility to ensure that it is an absolute file
968 name."
969   boolean)
971 (define %gc-roots-directory
972   ;; The place where garbage collector roots (symlinks) are kept.
973   (string-append %state-directory "/gcroots"))
975 (define (add-permanent-root target)
976   "Add a garbage collector root pointing to TARGET, an element of the store,
977 preventing TARGET from even being collected.  This can also be used if TARGET
978 does not exist yet.
980 Raise an error if the caller does not have write access to the GC root
981 directory."
982   (let* ((root (string-append %gc-roots-directory "/" (basename target))))
983     (catch 'system-error
984       (lambda ()
985         (symlink target root))
986       (lambda args
987         ;; If ROOT already exists, this is fine; otherwise, re-throw.
988         (unless (= EEXIST (system-error-errno args))
989           (apply throw args))))))
991 (define (remove-permanent-root target)
992   "Remove the permanent garbage collector root pointing to TARGET.  Raise an
993 error if there is no such root."
994   (delete-file (string-append %gc-roots-directory "/" (basename target))))
996 (define references
997   (operation (query-references (store-path path))
998              "Return the list of references of PATH."
999              store-path-list))
1001 (define %reference-cache
1002   ;; Brute-force cache mapping store items to their list of references.
1003   ;; Caching matters because when building a profile in the presence of
1004   ;; grafts, we keep calling 'graft-derivation', which in turn calls
1005   ;; 'references/substitutes' many times with the same arguments.  Ideally we
1006   ;; would use a cache associated with the daemon connection instead (XXX).
1007   (make-hash-table 100))
1009 (define (references/substitutes store items)
1010   "Return the list of list of references of ITEMS; the result has the same
1011 length as ITEMS.  Query substitute information for any item missing from the
1012 store at once.  Raise a '&nix-protocol-error' exception if reference
1013 information for one of ITEMS is missing."
1014   (let* ((requested  items)
1015          (local-refs (map (lambda (item)
1016                             (or (hash-ref %reference-cache item)
1017                                 (guard (c ((nix-protocol-error? c) #f))
1018                                   (references store item))))
1019                           items))
1020          (missing    (fold-right (lambda (item local-ref result)
1021                                    (if local-ref
1022                                        result
1023                                        (cons item result)))
1024                                  '()
1025                                  items local-refs))
1027          ;; Query all the substitutes at once to minimize the cost of
1028          ;; launching 'guix substitute' and making HTTP requests.
1029          (substs     (if (null? missing)
1030                          '()
1031                          (substitutable-path-info store missing))))
1032     (when (< (length substs) (length missing))
1033       (raise (condition (&nix-protocol-error
1034                          (message "cannot determine \
1035 the list of references")
1036                          (status 1)))))
1038     ;; Intersperse SUBSTS and LOCAL-REFS.
1039     (let loop ((items       items)
1040                (local-refs  local-refs)
1041                (result      '()))
1042       (match items
1043         (()
1044          (let ((result (reverse result)))
1045            (for-each (cut hash-set! %reference-cache <> <>)
1046                      requested result)
1047            result))
1048         ((item items ...)
1049          (match local-refs
1050            ((#f tail ...)
1051             (loop items tail
1052                   (cons (any (lambda (subst)
1053                                (and (string=? (substitutable-path subst) item)
1054                                     (substitutable-references subst)))
1055                              substs)
1056                         result)))
1057            ((head tail ...)
1058             (loop items tail
1059                   (cons head result)))))))))
1061 (define* (fold-path store proc seed paths
1062                     #:optional (relatives (cut references store <>)))
1063   "Call PROC for each of the RELATIVES of PATHS, exactly once, and return the
1064 result formed from the successive calls to PROC, the first of which is passed
1065 SEED."
1066   (let loop ((paths  paths)
1067              (result seed)
1068              (seen   vlist-null))
1069     (match paths
1070       ((path rest ...)
1071        (if (vhash-assoc path seen)
1072            (loop rest result seen)
1073            (let ((seen   (vhash-cons path #t seen))
1074                  (rest   (append rest (relatives path)))
1075                  (result (proc path result)))
1076              (loop rest result seen))))
1077       (()
1078        result))))
1080 (define (requisites store paths)
1081   "Return the requisites of PATHS, including PATHS---i.e., their closures (all
1082 its references, recursively)."
1083   (fold-path store cons '() paths))
1085 (define (topologically-sorted store paths)
1086   "Return a list containing PATHS and all their references sorted in
1087 topological order."
1088   (define (traverse)
1089     ;; Do a simple depth-first traversal of all of PATHS.
1090     (let loop ((paths   paths)
1091                (visited vlist-null)
1092                (result  '()))
1093       (define (visit n)
1094         (vhash-cons n #t visited))
1096       (define (visited? n)
1097         (vhash-assoc n visited))
1099       (match paths
1100         ((head tail ...)
1101          (if (visited? head)
1102              (loop tail visited result)
1103              (call-with-values
1104                  (lambda ()
1105                    (loop (references store head)
1106                          (visit head)
1107                          result))
1108                (lambda (visited result)
1109                  (loop tail
1110                        visited
1111                        (cons head result))))))
1112         (()
1113          (values visited result)))))
1115   (call-with-values traverse
1116     (lambda (_ result)
1117       (reverse result))))
1119 (define referrers
1120   (operation (query-referrers (store-path path))
1121              "Return the list of path that refer to PATH."
1122              store-path-list))
1124 (define valid-derivers
1125   (operation (query-valid-derivers (store-path path))
1126              "Return the list of valid \"derivers\" of PATH---i.e., all the
1127 .drv present in the store that have PATH among their outputs."
1128              store-path-list))
1130 (define query-derivation-outputs  ; avoid name clash with `derivation-outputs'
1131   (operation (query-derivation-outputs (store-path path))
1132              "Return the list of outputs of PATH, a .drv file."
1133              store-path-list))
1135 (define-operation (has-substitutes? (store-path path))
1136   "Return #t if binary substitutes are available for PATH, and #f otherwise."
1137   boolean)
1139 (define substitutable-paths
1140   (operation (query-substitutable-paths (store-path-list paths))
1141              "Return the subset of PATHS that is substitutable."
1142              store-path-list))
1144 (define substitutable-path-info
1145   (operation (query-substitutable-path-infos (store-path-list paths))
1146              "Return information about the subset of PATHS that is
1147 substitutable.  For each substitutable path, a `substitutable?' object is
1148 returned; thus, the resulting list can be shorter than PATHS.  Furthermore,
1149 that there is no guarantee that the order of the resulting list matches the
1150 order of PATHS."
1151              substitutable-path-list))
1153 (define built-in-builders
1154   (let ((builders (operation (built-in-builders)
1155                              "Return the built-in builders."
1156                              string-list)))
1157     (lambda (store)
1158       "Return the names of the supported built-in derivation builders
1159 supported by STORE."
1160       ;; Check whether STORE's version supports this RPC and built-in
1161       ;; derivation builders in general, which appeared in Guix > 0.11.0.
1162       ;; Return the empty list if it doesn't.  Note that this RPC does not
1163       ;; exist in 'nix-daemon'.
1164       (if (or (> (nix-server-major-version store) #x100)
1165               (and (= (nix-server-major-version store) #x100)
1166                    (>= (nix-server-minor-version store) #x60)))
1167           (builders store)
1168           '()))))
1170 (define-operation (optimize-store)
1171   "Optimize the store by hard-linking identical files (\"deduplication\".)
1172 Return #t on success."
1173   ;; Note: the daemon in Guix <= 0.8.2 does not implement this RPC.
1174   boolean)
1176 (define verify-store
1177   (let ((verify (operation (verify-store (boolean check-contents?)
1178                                          (boolean repair?))
1179                            "Verify the store."
1180                            boolean)))
1181     (lambda* (store #:key check-contents? repair?)
1182       "Verify the integrity of the store and return false if errors remain,
1183 and true otherwise.  When REPAIR? is true, repair any missing or altered store
1184 items by substituting them (this typically requires root privileges because it
1185 is not an atomic operation.)  When CHECK-CONTENTS? is true, check the contents
1186 of store items; this can take a lot of time."
1187       (not (verify store check-contents? repair?)))))
1189 (define (run-gc server action to-delete min-freed)
1190   "Perform the garbage-collector operation ACTION, one of the
1191 `gc-action' values.  When ACTION is `delete-specific', the TO-DELETE is
1192 the list of store paths to delete.  IGNORE-LIVENESS? should always be
1193 #f.  MIN-FREED is the minimum amount of disk space to be freed, in
1194 bytes, before the GC can stop.  Return the list of store paths delete,
1195 and the number of bytes freed."
1196   (let ((s (nix-server-socket server)))
1197     (write-int (operation-id collect-garbage) s)
1198     (write-int action s)
1199     (write-store-path-list to-delete s)
1200     (write-arg boolean #f s)                      ; ignore-liveness?
1201     (write-long-long min-freed s)
1202     (write-int 0 s)                               ; obsolete
1203     (when (>= (nix-server-minor-version server) 5)
1204       ;; Obsolete `use-atime' and `max-atime' parameters.
1205       (write-int 0 s)
1206       (write-int 0 s))
1208     ;; Loop until the server is done sending error output.
1209     (let loop ((done? (process-stderr server)))
1210       (or done? (loop (process-stderr server))))
1212     (let ((paths    (read-store-path-list s))
1213           (freed    (read-long-long s))
1214           (obsolete (read-long-long s)))
1215       (unless (null? paths)
1216         ;; To be on the safe side, completely invalidate both caches.
1217         ;; Otherwise we could end up returning store paths that are no longer
1218         ;; valid.
1219         (hash-clear! (nix-server-add-to-store-cache server))
1220         (hash-clear! (nix-server-add-text-to-store-cache server)))
1222      (values paths freed))))
1224 (define-syntax-rule (%long-long-max)
1225   ;; Maximum unsigned 64-bit integer.
1226   (- (expt 2 64) 1))
1228 (define (live-paths server)
1229   "Return the list of live store paths---i.e., store paths still
1230 referenced, and thus not subject to being garbage-collected."
1231   (run-gc server (gc-action return-live) '() (%long-long-max)))
1233 (define (dead-paths server)
1234   "Return the list of dead store paths---i.e., store paths no longer
1235 referenced, and thus subject to being garbage-collected."
1236   (run-gc server (gc-action return-dead) '() (%long-long-max)))
1238 (define* (collect-garbage server #:optional (min-freed (%long-long-max)))
1239   "Collect garbage from the store at SERVER.  If MIN-FREED is non-zero,
1240 then collect at least MIN-FREED bytes.  Return the paths that were
1241 collected, and the number of bytes freed."
1242   (run-gc server (gc-action delete-dead) '() min-freed))
1244 (define* (delete-paths server paths #:optional (min-freed (%long-long-max)))
1245   "Delete PATHS from the store at SERVER, if they are no longer
1246 referenced.  If MIN-FREED is non-zero, then stop after at least
1247 MIN-FREED bytes have been collected.  Return the paths that were
1248 collected, and the number of bytes freed."
1249   (run-gc server (gc-action delete-specific) paths min-freed))
1251 (define (import-paths server port)
1252   "Import the set of store paths read from PORT into SERVER's store.  An error
1253 is raised if the set of paths read from PORT is not signed (as per
1254 'export-path #:sign? #t'.)  Return the list of store paths imported."
1255   (let ((s (nix-server-socket server)))
1256     (write-int (operation-id import-paths) s)
1257     (let loop ((done? (process-stderr server port)))
1258       (or done? (loop (process-stderr server port))))
1259     (read-store-path-list s)))
1261 (define* (export-path server path port #:key (sign? #t))
1262   "Export PATH to PORT.  When SIGN? is true, sign it."
1263   (let ((s (nix-server-socket server)))
1264     (write-int (operation-id export-path) s)
1265     (write-store-path path s)
1266     (write-arg boolean sign? s)
1267     (let loop ((done? (process-stderr server port)))
1268       (or done? (loop (process-stderr server port))))
1269     (= 1 (read-int s))))
1271 (define* (export-paths server paths port #:key (sign? #t) recursive?)
1272   "Export the store paths listed in PATHS to PORT, in topological order,
1273 signing them if SIGN? is true.  When RECURSIVE? is true, export the closure of
1274 PATHS---i.e., PATHS and all their dependencies."
1275   (define ordered
1276     (let ((sorted (topologically-sorted server paths)))
1277       ;; When RECURSIVE? is #f, filter out the references of PATHS.
1278       (if recursive?
1279           sorted
1280           (filter (cut member <> paths) sorted))))
1282   (let loop ((paths ordered))
1283     (match paths
1284       (()
1285        (write-int 0 port))
1286       ((head tail ...)
1287        (write-int 1 port)
1288        (and (export-path server head port #:sign? sign?)
1289             (loop tail))))))
1291 (define-operation (query-failed-paths)
1292   "Return the list of store items for which a build failure is cached.
1294 The result is always the empty list unless the daemon was started with
1295 '--cache-failures'."
1296   store-path-list)
1298 (define-operation (clear-failed-paths (store-path-list items))
1299   "Remove ITEMS from the list of cached build failures.
1301 This makes sense only when the daemon was started with '--cache-failures'."
1302   boolean)
1304 (define* (register-path path
1305                         #:key (references '()) deriver prefix
1306                         state-directory)
1307   "Register PATH as a valid store file, with REFERENCES as its list of
1308 references, and DERIVER as its deriver (.drv that led to it.)  If PREFIX is
1309 not #f, it must be the name of the directory containing the new store to
1310 initialize; if STATE-DIRECTORY is not #f, it must be a string containing the
1311 absolute file name to the state directory of the store being initialized.
1312 Return #t on success.
1314 Use with care as it directly modifies the store!  This is primarily meant to
1315 be used internally by the daemon's build hook."
1316   ;; Currently this is implemented by calling out to the fine C++ blob.
1317   (let ((pipe (apply open-pipe* OPEN_WRITE %guix-register-program
1318                      `(,@(if prefix
1319                              `("--prefix" ,prefix)
1320                              '())
1321                        ,@(if state-directory
1322                              `("--state-directory" ,state-directory)
1323                              '())))))
1324     (and pipe
1325          (begin
1326            (format pipe "~a~%~a~%~a~%"
1327                    path (or deriver "") (length references))
1328            (for-each (cut format pipe "~a~%" <>) references)
1329            (zero? (close-pipe pipe))))))
1333 ;;; Store monad.
1336 (define-syntax-rule (define-alias new old)
1337   (define-syntax new (identifier-syntax old)))
1339 ;; The store monad allows us to (1) build sequences of operations in the
1340 ;; store, and (2) make the store an implicit part of the execution context,
1341 ;; rather than a parameter of every single function.
1342 (define-alias %store-monad %state-monad)
1343 (define-alias store-return state-return)
1344 (define-alias store-bind state-bind)
1346 ;; Instantiate templates for %STORE-MONAD since it's syntactically different
1347 ;; from %STATE-MONAD.
1348 (template-directory instantiations %store-monad)
1350 (define (preserve-documentation original proc)
1351   "Return PROC with documentation taken from ORIGINAL."
1352   (set-object-property! proc 'documentation
1353                         (procedure-property original 'documentation))
1354   proc)
1356 (define (store-lift proc)
1357   "Lift PROC, a procedure whose first argument is a connection to the store,
1358 in the store monad."
1359   (preserve-documentation proc
1360                           (lambda args
1361                             (lambda (store)
1362                               (values (apply proc store args) store)))))
1364 (define (store-lower proc)
1365   "Lower PROC, a monadic procedure in %STORE-MONAD, to a \"normal\" procedure
1366 taking the store as its first argument."
1367   (preserve-documentation proc
1368                           (lambda (store . args)
1369                             (run-with-store store (apply proc args)))))
1372 ;; Store monad operators.
1375 (define* (text-file name text
1376                     #:optional (references '()))
1377   "Return as a monadic value the absolute file name in the store of the file
1378 containing TEXT, a string.  REFERENCES is a list of store items that the
1379 resulting text file refers to; it defaults to the empty list."
1380   (lambda (store)
1381     (values (add-text-to-store store name text references)
1382             store)))
1384 (define* (interned-file file #:optional name
1385                         #:key (recursive? #t) (select? true))
1386   "Return the name of FILE once interned in the store.  Use NAME as its store
1387 name, or the basename of FILE if NAME is omitted.
1389 When RECURSIVE? is true, the contents of FILE are added recursively; if FILE
1390 designates a flat file and RECURSIVE? is true, its contents are added, and its
1391 permission bits are kept.
1393 When RECURSIVE? is true, call (SELECT?  FILE STAT) for each directory entry,
1394 where FILE is the entry's absolute file name and STAT is the result of
1395 'lstat'; exclude entries for which SELECT? does not return true."
1396   (lambda (store)
1397     (values (add-to-store store (or name (basename file))
1398                           recursive? "sha256" file
1399                           #:select? select?)
1400             store)))
1402 (define build
1403   ;; Monadic variant of 'build-things'.
1404   (store-lift build-things))
1406 (define set-build-options*
1407   (store-lift set-build-options))
1409 (define references*
1410   (store-lift references))
1412 (define-inlinable (current-system)
1413   ;; Consult the %CURRENT-SYSTEM fluid at bind time.  This is equivalent to
1414   ;; (lift0 %current-system %store-monad), but inlinable, thus avoiding
1415   ;; closure allocation in some cases.
1416   (lambda (state)
1417     (values (%current-system) state)))
1419 (define-inlinable (set-current-system system)
1420   ;; Set the %CURRENT-SYSTEM fluid at bind time.
1421   (lambda (state)
1422     (values (%current-system system) state)))
1424 (define %guile-for-build
1425   ;; The derivation of the Guile to be used within the build environment,
1426   ;; when using 'gexp->derivation' and co.
1427   (make-parameter #f))
1429 (define* (run-with-store store mval
1430                          #:key
1431                          (guile-for-build (%guile-for-build))
1432                          (system (%current-system))
1433                          (target #f))
1434   "Run MVAL, a monadic value in the store monad, in STORE, an open store
1435 connection, and return the result."
1436   ;; Initialize the dynamic bindings here to avoid bad surprises.  The
1437   ;; difficulty lies in the fact that dynamic bindings are resolved at
1438   ;; bind-time and not at call time, which can be disconcerting.
1439   (parameterize ((%guile-for-build guile-for-build)
1440                  (%current-system system)
1441                  (%current-target-system target))
1442     (call-with-values (lambda ()
1443                         (run-with-state mval store))
1444       (lambda (result store)
1445         ;; Discard the state.
1446         result))))
1450 ;;; Store paths.
1453 (define %store-prefix
1454   ;; Absolute path to the Nix store.
1455   (make-parameter %store-directory))
1457 (define (compressed-hash bv size)                 ; `compressHash'
1458   "Given the hash stored in BV, return a compressed version thereof that fits
1459 in SIZE bytes."
1460   (define new (make-bytevector size 0))
1461   (define old-size (bytevector-length bv))
1462   (let loop ((i 0))
1463     (if (= i old-size)
1464         new
1465         (let* ((j (modulo i size))
1466                (o (bytevector-u8-ref new j)))
1467           (bytevector-u8-set! new j
1468                               (logxor o (bytevector-u8-ref bv i)))
1469           (loop (+ 1 i))))))
1471 (define (store-path type hash name)               ; makeStorePath
1472   "Return the store path for NAME/HASH/TYPE."
1473   (let* ((s (string-append type ":sha256:"
1474                            (bytevector->base16-string hash) ":"
1475                            (%store-prefix) ":" name))
1476          (h (sha256 (string->utf8 s)))
1477          (c (compressed-hash h 20)))
1478     (string-append (%store-prefix) "/"
1479                    (bytevector->nix-base32-string c) "-"
1480                    name)))
1482 (define (output-path output hash name)            ; makeOutputPath
1483   "Return an output path for OUTPUT (the name of the output as a string) of
1484 the derivation called NAME with hash HASH."
1485   (store-path (string-append "output:" output) hash
1486               (if (string=? output "out")
1487                   name
1488                   (string-append name "-" output))))
1490 (define* (fixed-output-path name hash
1491                             #:key
1492                             (output "out")
1493                             (hash-algo 'sha256)
1494                             (recursive? #t))
1495   "Return an output path for the fixed output OUTPUT defined by HASH of type
1496 HASH-ALGO, of the derivation NAME.  RECURSIVE? has the same meaning as for
1497 'add-to-store'."
1498   (if (and recursive? (eq? hash-algo 'sha256))
1499       (store-path "source" hash name)
1500       (let ((tag (string-append "fixed:" output ":"
1501                                 (if recursive? "r:" "")
1502                                 (symbol->string hash-algo) ":"
1503                                 (bytevector->base16-string hash) ":")))
1504         (store-path (string-append "output:" output)
1505                     (sha256 (string->utf8 tag))
1506                     name))))
1508 (define (store-path? path)
1509   "Return #t if PATH is a store path."
1510   ;; This is a lightweight check, compared to using a regexp, but this has to
1511   ;; be fast as it's called often in `derivation', for instance.
1512   ;; `isStorePath' in Nix does something similar.
1513   (string-prefix? (%store-prefix) path))
1515 (define (direct-store-path? path)
1516   "Return #t if PATH is a store path, and not a sub-directory of a store path.
1517 This predicate is sometimes needed because files *under* a store path are not
1518 valid inputs."
1519   (and (store-path? path)
1520        (not (string=? path (%store-prefix)))
1521        (let ((len (+ 1 (string-length (%store-prefix)))))
1522          (not (string-index (substring path len) #\/)))))
1524 (define (direct-store-path path)
1525   "Return the direct store path part of PATH, stripping components after
1526 '/gnu/store/xxxx-foo'."
1527   (let ((prefix-length (+ (string-length (%store-prefix)) 35)))
1528     (if (> (string-length path) prefix-length)
1529         (let ((slash (string-index path #\/ prefix-length)))
1530           (if slash (string-take path slash) path))
1531         path)))
1533 (define (derivation-path? path)
1534   "Return #t if PATH is a derivation path."
1535   (and (store-path? path) (string-suffix? ".drv" path)))
1537 (define store-regexp*
1538   ;; The substituter makes repeated calls to 'store-path-hash-part', hence
1539   ;; this optimization.
1540   (mlambda (store)
1541     "Return a regexp matching a file in STORE."
1542     (make-regexp (string-append "^" (regexp-quote store)
1543                                 "/([0-9a-df-np-sv-z]{32})-([^/]+)$"))))
1545 (define (store-path-package-name path)
1546   "Return the package name part of PATH, a file name in the store."
1547   (let ((path-rx (store-regexp* (%store-prefix))))
1548     (and=> (regexp-exec path-rx path)
1549            (cut match:substring <> 2))))
1551 (define (store-path-hash-part path)
1552   "Return the hash part of PATH as a base32 string, or #f if PATH is not a
1553 syntactically valid store path."
1554   (and (string-prefix? (%store-prefix) path)
1555        (let ((base (string-drop path (+ 1 (string-length (%store-prefix))))))
1556          (and (> (string-length base) 33)
1557               (let ((hash (string-take base 32)))
1558                 (and (string-every %nix-base32-charset hash)
1559                      hash))))))
1561 (define (log-file store file)
1562   "Return the build log file for FILE, or #f if none could be found.  FILE
1563 must be an absolute store file name, or a derivation file name."
1564   (cond ((derivation-path? file)
1565          (let* ((base    (basename file))
1566                 (log     (string-append (dirname %state-directory) ; XXX
1567                                         "/log/guix/drvs/"
1568                                         (string-take base 2) "/"
1569                                         (string-drop base 2)))
1570                 (log.bz2 (string-append log ".bz2")))
1571            (cond ((file-exists? log.bz2) log.bz2)
1572                  ((file-exists? log) log)
1573                  (else #f))))
1574         (else
1575          (match (valid-derivers store file)
1576            ((derivers ...)
1577             ;; Return the first that works.
1578             (any (cut log-file store <>) derivers))
1579            (_ #f)))))
1581 ;;; Local Variables:
1582 ;;; eval: (put 'system-error-to-connection-error 'scheme-indent-function 1)
1583 ;;; End: