1 ;;; GNU Guix --- Functional package management for GNU
2 ;;; Copyright © 2012, 2013, 2014, 2015, 2016 Ludovic Courtès <ludo@gnu.org>
4 ;;; This file is part of GNU Guix.
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.
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.
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 serialization)
23 #:use-module (guix monads)
24 #:autoload (guix base32) (bytevector->base32-string)
25 #:autoload (guix build syscalls) (terminal-columns)
26 #:use-module (rnrs bytevectors)
27 #:use-module (rnrs io ports)
28 #:use-module (srfi srfi-1)
29 #:use-module (srfi srfi-9)
30 #:use-module (srfi srfi-9 gnu)
31 #:use-module (srfi srfi-11)
32 #:use-module (srfi srfi-26)
33 #:use-module (srfi srfi-34)
34 #:use-module (srfi srfi-35)
35 #:use-module (srfi srfi-39)
36 #:use-module (ice-9 match)
37 #:use-module (ice-9 regex)
38 #:use-module (ice-9 vlist)
39 #:use-module (ice-9 popen)
40 #:export (%daemon-socket-file
42 %default-substitute-urls
45 nix-server-major-version
46 nix-server-minor-version
50 &nix-connection-error nix-connection-error?
51 nix-connection-error-file
52 nix-connection-error-code
53 &nix-protocol-error nix-protocol-error?
54 nix-protocol-error-message
55 nix-protocol-error-status
83 substitutable-references
84 substitutable-download-size
85 substitutable-nar-size
88 substitutable-path-info
94 path-info-registration-time
98 references/substitutes
105 query-derivation-outputs
113 current-build-output-port
133 store-path-package-name
138 (define %protocol-version #x10f)
140 (define %worker-magic-1 #x6e697863) ; "nixc"
141 (define %worker-magic-2 #x6478696f) ; "dxio"
143 (define (protocol-major magic)
144 (logand magic #xff00))
145 (define (protocol-minor magic)
146 (logand magic #x00ff))
148 (define-syntax define-enumerate-type
150 ((_ name->int (name id) ...)
151 (define-syntax name->int
152 (syntax-rules (name ...)
153 ((_ name) id) ...)))))
155 (define-enumerate-type operation-id
156 ;; operation numbers from worker-protocol.hh
164 (add-text-to-store 8)
168 (add-indirect-root 12)
175 ;;(query-substitutable-path-info 21) ; obsolete as of #x10c
176 (query-derivation-outputs 22)
177 (query-all-valid-paths 23)
178 (query-failed-paths 24)
179 (clear-failed-paths 25)
182 (query-derivation-output-names 28)
183 (query-path-from-hash-part 29)
184 (query-substitutable-path-infos 30)
185 (query-valid-paths 31)
186 (query-substitutable-paths 32)
187 (query-valid-derivers 33)
191 (define-enumerate-type hash-algo
197 (define-enumerate-type build-mode
203 (define-enumerate-type gc-action
210 (define %default-socket-path
211 (string-append %state-directory "/daemon-socket/socket"))
213 (define %daemon-socket-file
214 ;; File name of the socket the daemon listens too.
215 (make-parameter (or (getenv "GUIX_DAEMON_SOCKET")
216 %default-socket-path)))
220 ;; Information about a substitutable store path.
221 (define-record-type <substitutable>
222 (substitutable path deriver refs dl-size nar-size)
224 (path substitutable-path)
225 (deriver substitutable-deriver)
226 (refs substitutable-references)
227 (dl-size substitutable-download-size)
228 (nar-size substitutable-nar-size))
230 (define (read-substitutable-path-list p)
231 (let loop ((len (read-int p))
235 (let ((path (read-store-path p))
236 (deriver (read-store-path p))
237 (refs (read-store-path-list p))
238 (dl-size (read-long-long p))
239 (nar-size (read-long-long p)))
241 (cons (substitutable path deriver refs dl-size nar-size)
244 ;; Information about a store path.
245 (define-record-type <path-info>
246 (path-info deriver hash references registration-time nar-size)
248 (deriver path-info-deriver) ;string | #f
249 (hash path-info-hash)
250 (references path-info-references)
251 (registration-time path-info-registration-time)
252 (nar-size path-info-nar-size))
254 (define (read-path-info p)
255 (let ((deriver (match (read-store-path p)
258 (hash (base16-string->bytevector (read-string p)))
259 (refs (read-store-path-list p))
260 (registration-time (read-int p))
261 (nar-size (read-long-long p)))
262 (path-info deriver hash refs registration-time nar-size)))
264 (define-syntax write-arg
265 (syntax-rules (integer boolean file string string-list string-pairs
266 store-path store-path-list base16)
270 (write-int (if arg 1 0) p))
274 (write-string arg p))
275 ((_ string-list arg p)
276 (write-string-list arg p))
277 ((_ string-pairs arg p)
278 (write-string-pairs arg p))
279 ((_ store-path arg p)
280 (write-store-path arg p))
281 ((_ store-path-list arg p)
282 (write-store-path-list arg p))
284 (write-string (bytevector->base16-string arg) p))))
286 (define-syntax read-arg
287 (syntax-rules (integer boolean string store-path store-path-list
288 substitutable-path-list path-info base16)
292 (not (zero? (read-int p))))
297 ((_ store-path-list p)
298 (read-store-path-list p))
299 ((_ substitutable-path-list p)
300 (read-substitutable-path-list p))
304 (base16-string->bytevector (read-string p)))))
309 (define-record-type <nix-server>
310 (%make-nix-server socket major minor
311 ats-cache atts-cache)
313 (socket nix-server-socket)
314 (major nix-server-major-version)
315 (minor nix-server-minor-version)
317 ;; Caches. We keep them per-connection, because store paths build
318 ;; during the session are temporary GC roots kept for the duration of
320 (ats-cache nix-server-add-to-store-cache)
321 (atts-cache nix-server-add-text-to-store-cache))
323 (set-record-type-printer! <nix-server>
325 (format port "#<build-daemon ~a.~a ~a>"
326 (nix-server-major-version obj)
327 (nix-server-minor-version obj)
328 (number->string (object-address obj)
331 (define-condition-type &nix-error &error
334 (define-condition-type &nix-connection-error &nix-error
335 nix-connection-error?
336 (file nix-connection-error-file)
337 (errno nix-connection-error-code))
339 (define-condition-type &nix-protocol-error &nix-error
341 (message nix-protocol-error-message)
342 (status nix-protocol-error-status))
344 (define* (open-connection #:optional (file (%daemon-socket-file))
345 #:key (reserve-space? #t) cpu-affinity)
346 "Connect to the daemon over the Unix-domain socket at FILE. When
347 RESERVE-SPACE? is true, instruct it to reserve a little bit of extra space on
348 the file system so that the garbage collector can still operate, should the
349 disk become full. When CPU-AFFINITY is true, it must be an integer
350 corresponding to an OS-level CPU number to which the daemon's worker process
351 for this connection will be pinned. Return a server object."
352 (let ((s (with-fluids ((%default-port-encoding #f))
353 ;; This trick allows use of the `scm_c_read' optimization.
354 (socket PF_UNIX SOCK_STREAM 0)))
355 (a (make-socket-address PF_UNIX file)))
360 ;; Translate the error to something user-friendly.
361 (let ((errno (system-error-errno args)))
362 (raise (condition (&nix-connection-error
366 (write-int %worker-magic-1 s)
367 (let ((r (read-int s)))
368 (and (eqv? r %worker-magic-2)
369 (let ((v (read-int s)))
370 (and (eqv? (protocol-major %protocol-version)
373 (write-int %protocol-version s)
374 (when (>= (protocol-minor v) 14)
375 (write-int (if cpu-affinity 1 0) s)
377 (write-int cpu-affinity s)))
378 (when (>= (protocol-minor v) 11)
379 (write-int (if reserve-space? 1 0) s))
380 (let ((s (%make-nix-server s
383 (make-hash-table 100)
384 (make-hash-table 100))))
385 (let loop ((done? (process-stderr s)))
386 (or done? (process-stderr s)))
389 (define (close-connection server)
390 "Close the connection to SERVER."
391 (close (nix-server-socket server)))
393 (define-syntax-rule (with-store store exp ...)
394 "Bind STORE to an open connection to the store and evaluate EXPs;
395 automatically close the store when the dynamic extent of EXP is left."
396 (let ((store (open-connection)))
402 (false-if-exception (close-connection store))))))
404 (define current-build-output-port
405 ;; The port where build output is sent.
406 (make-parameter (current-error-port)))
408 (define* (dump-port in out
410 #:key (buffer-size 16384))
411 "Read LEN bytes from IN (or as much as possible if LEN is #f) and write it
412 to OUT, using chunks of BUFFER-SIZE bytes."
414 (make-bytevector buffer-size))
417 (bytes (get-bytevector-n! in buffer 0
419 (min len buffer-size)
421 (or (eof-object? bytes)
422 (and len (= total len))
423 (let ((total (+ total bytes)))
424 (put-bytevector out buffer 0 bytes)
426 (get-bytevector-n! in buffer 0
428 (min (- len total) buffer-size)
432 ;; Newline characters triggering a flush of 'current-build-output-port'.
433 ;; Unlike Guile's _IOLBF, we flush upon #\return so that progress reports
434 ;; that use that trick are correctly displayed.
435 (char-set #\newline #\return))
437 (define* (process-stderr server #:optional user-port)
438 "Read standard output and standard error from SERVER, writing it to
439 CURRENT-BUILD-OUTPUT-PORT. Return #t when SERVER is done sending data, and
440 #f otherwise; in the latter case, the caller should call `process-stderr'
441 again until #t is returned or an error is raised.
443 Since the build process's output cannot be assumed to be UTF-8, we
444 conservatively consider it to be Latin-1, thereby avoiding possible
445 encoding conversion errors."
447 (nix-server-socket server))
449 ;; magic cookies from worker-protocol.hh
450 (define %stderr-next #x6f6c6d67) ; "olmg", build log
451 (define %stderr-read #x64617461) ; "data", data needed from source
452 (define %stderr-write #x64617416) ; "dat\x16", data for sink
453 (define %stderr-last #x616c7473) ; "alts", we're done
454 (define %stderr-error #x63787470) ; "cxtp", error reporting
456 (let ((k (read-int p)))
457 (cond ((= k %stderr-write)
458 ;; Write a byte stream to USER-PORT.
459 (let* ((len (read-int p))
461 (dump-port p user-port len)
463 ;; Consume padding, as for strings.
464 (get-bytevector-n p (- 8 m))))
467 ;; Read a byte stream from USER-PORT.
468 ;; Note: Avoid 'get-bytevector-n' to work around
469 ;; <http://bugs.gnu.org/17591> in Guile up to 2.0.11.
470 (let* ((max-len (read-int p))
471 (data (make-bytevector max-len))
472 (len (get-bytevector-n! user-port data 0 max-len)))
474 (put-bytevector p data 0 len)
475 (write-padding len p)
478 ;; Log a string. Build logs are usually UTF-8-encoded, but they
479 ;; may also contain arbitrary byte sequences that should not cause
480 ;; this to fail. Thus, use the permissive
481 ;; 'read-maybe-utf8-string'.
482 (let ((s (read-maybe-utf8-string p)))
483 (display s (current-build-output-port))
484 (when (string-any %newlines s)
485 (flush-output-port (current-build-output-port)))
489 (let ((error (read-maybe-utf8-string p))
490 ;; Currently the daemon fails to send a status code for early
491 ;; errors like DB schema version mismatches, so check for EOF.
492 (status (if (and (>= (nix-server-minor-version server) 8)
493 (not (eof-object? (lookahead-u8 p))))
496 (raise (condition (&nix-protocol-error
500 ;; The daemon is done (see `stopWork' in `nix-worker.cc'.)
503 (raise (condition (&nix-protocol-error
504 (message "invalid error code")
507 (define %default-substitute-urls
508 ;; Default list of substituters. This is *not* the list baked in
509 ;; 'guix-daemon', but it is used by 'guix-service-type' and and a couple of
510 ;; clients ('guix build --log-file' uses it.)
511 (map (if (false-if-exception (resolve-interface '(gnutls)))
512 (cut string-append "https://" <>)
513 (cut string-append "http://" <>))
514 '("mirror.hydra.gnu.org" "hydra.gnu.org")))
516 (define* (set-build-options server
517 #:key keep-failed? keep-going? fallback?
519 rounds ;number of build rounds
522 (max-silent-time 3600)
526 (print-build-trace #t)
527 (build-cores (current-processor-count))
528 (use-substitutes? #t)
530 ;; Client-provided substitute URLs. If it is #f,
531 ;; the daemon's settings are used. Otherwise, it
532 ;; overrides the daemons settings; see 'guix
536 ;; Number of columns in the client's terminal.
537 (terminal-columns (terminal-columns))
539 ;; Locale of the client.
540 (locale (false-if-exception (setlocale LC_ALL))))
541 ;; Must be called after `open-connection'.
544 (nix-server-socket server))
546 (let-syntax ((send (syntax-rules ()
547 ((_ (type option) ...)
549 (write-arg type option socket)
551 (write-int (operation-id set-options) socket)
552 (send (boolean keep-failed?) (boolean keep-going?)
553 (boolean fallback?) (integer verbosity)
554 (integer max-build-jobs) (integer max-silent-time))
555 (when (>= (nix-server-minor-version server) 2)
556 (send (boolean use-build-hook?)))
557 (when (>= (nix-server-minor-version server) 4)
558 (send (integer build-verbosity) (integer log-type)
559 (boolean print-build-trace)))
560 (when (>= (nix-server-minor-version server) 6)
561 (send (integer build-cores)))
562 (when (>= (nix-server-minor-version server) 10)
563 (send (boolean use-substitutes?)))
564 (when (>= (nix-server-minor-version server) 12)
565 (let ((pairs `(,@(if timeout
566 `(("build-timeout" . ,(number->string timeout)))
568 ,@(if substitute-urls
570 . ,(string-join substitute-urls)))
574 . ,(number->string (max 0 (1- rounds)))))
576 ,@(if terminal-columns
577 `(("terminal-columns"
578 . ,(number->string terminal-columns)))
581 `(("locale" . ,locale))
583 (send (string-pairs pairs))))
584 (let loop ((done? (process-stderr server)))
585 (or done? (process-stderr server)))))
587 (define-syntax operation
589 "Define a client-side RPC stub for the given operation."
590 ((_ (name (type arg) ...) docstring return ...)
591 (lambda (server arg ...)
593 (let ((s (nix-server-socket server)))
594 (write-int (operation-id name) s)
595 (write-arg type arg s)
597 ;; Loop until the server is done sending error output.
598 (let loop ((done? (process-stderr server)))
599 (or done? (loop (process-stderr server))))
600 (values (read-arg return s) ...))))))
602 (define-syntax-rule (define-operation (name args ...)
603 docstring return ...)
605 (operation (name args ...) docstring return ...)))
607 (define-operation (valid-path? (string path))
608 "Return #t when PATH designates a valid store item and #f otherwise (an
609 invalid item may exist on disk but still be invalid, for instance because it
610 is the result of an aborted or failed build.)
612 A '&nix-protocol-error' condition is raised if PATH is not prefixed by the
613 store directory (/gnu/store)."
616 (define-operation (query-path-hash (store-path path))
617 "Return the SHA256 hash of PATH as a bytevector."
620 (define hash-part->path
621 (let ((query-path-from-hash-part
622 (operation (query-path-from-hash-part (string hash))
625 (lambda (server hash-part)
626 "Return the store path whose hash part is HASH-PART (a nix-base32
627 string). Raise an error if no such path exists."
628 ;; This RPC is primarily used by Hydra to reply to HTTP GETs of
630 (query-path-from-hash-part server hash-part))))
632 (define-operation (query-path-info (store-path path))
633 "Return the info (hash, references, etc.) for PATH."
636 (define add-text-to-store
637 ;; A memoizing version of `add-to-store', to avoid repeated RPCs with
638 ;; the very same arguments during a given session.
639 (let ((add-text-to-store
640 (operation (add-text-to-store (string name) (string text)
641 (string-list references))
644 (lambda* (server name text #:optional (references '()))
645 "Add TEXT under file NAME in the store, and return its store path.
646 REFERENCES is the list of store paths referred to by the resulting store
648 (let ((args `(,text ,name ,references))
649 (cache (nix-server-add-text-to-store-cache server)))
650 (or (hash-ref cache args)
651 (let ((path (add-text-to-store server name text references)))
652 (hash-set! cache args path)
656 ;; A memoizing version of `add-to-store'. This is important because
657 ;; `add-to-store' leads to huge data transfers to the server, and
658 ;; because it's often called many times with the very same argument.
659 (let ((add-to-store (operation (add-to-store (string basename)
660 (boolean fixed?) ; obsolete, must be #t
666 (lambda (server basename recursive? hash-algo file-name)
667 "Add the contents of FILE-NAME under BASENAME to the store. When
668 RECURSIVE? is false, FILE-NAME must designate a regular file--not a directory
669 nor a symlink. When RECURSIVE? is true and FILE-NAME designates a directory,
670 the contents of FILE-NAME are added recursively; if FILE-NAME designates a
671 flat file and RECURSIVE? is true, its contents are added, and its permission
672 bits are kept. HASH-ALGO must be a string such as \"sha256\"."
673 (let* ((st (false-if-exception (lstat file-name)))
674 (args `(,st ,basename ,recursive? ,hash-algo))
675 (cache (nix-server-add-to-store-cache server)))
676 (or (and st (hash-ref cache args))
677 (let ((path (add-to-store server basename #t recursive?
678 hash-algo file-name)))
679 (hash-set! cache args path)
683 (let ((build (operation (build-things (string-list things)
687 (build/old (operation (build-things (string-list things))
690 (lambda* (store things #:optional (mode (build-mode normal)))
691 "Build THINGS, a list of store items which may be either '.drv' files or
692 outputs, and return when the worker is done building them. Elements of THINGS
693 that are not derivations can only be substituted and not built locally.
694 Return #t on success."
695 (if (>= (nix-server-minor-version store) 15)
696 (build store things mode)
697 (if (= mode (build-mode normal))
698 (build/old store things)
699 (raise (condition (&nix-protocol-error
700 (message "unsupported build mode")
703 (define-operation (add-temp-root (store-path path))
704 "Make PATH a temporary root for the duration of the current session.
708 (define-operation (add-indirect-root (string file-name))
709 "Make the symlink FILE-NAME an indirect root for the garbage collector:
710 whatever store item FILE-NAME points to will not be collected. Return #t on
713 FILE-NAME can be anywhere on the file system, but it must be an absolute file
714 name--it is the caller's responsibility to ensure that it is an absolute file
718 (define %gc-roots-directory
719 ;; The place where garbage collector roots (symlinks) are kept.
720 (string-append %state-directory "/gcroots"))
722 (define (add-permanent-root target)
723 "Add a garbage collector root pointing to TARGET, an element of the store,
724 preventing TARGET from even being collected. This can also be used if TARGET
727 Raise an error if the caller does not have write access to the GC root
729 (let* ((root (string-append %gc-roots-directory "/" (basename target))))
732 (symlink target root))
734 ;; If ROOT already exists, this is fine; otherwise, re-throw.
735 (unless (= EEXIST (system-error-errno args))
736 (apply throw args))))))
738 (define (remove-permanent-root target)
739 "Remove the permanent garbage collector root pointing to TARGET. Raise an
740 error if there is no such root."
741 (delete-file (string-append %gc-roots-directory "/" (basename target))))
744 (operation (query-references (store-path path))
745 "Return the list of references of PATH."
748 (define %reference-cache
749 ;; Brute-force cache mapping store items to their list of references.
750 ;; Caching matters because when building a profile in the presence of
751 ;; grafts, we keep calling 'graft-derivation', which in turn calls
752 ;; 'references/substitutes' many times with the same arguments. Ideally we
753 ;; would use a cache associated with the daemon connection instead (XXX).
754 (make-hash-table 100))
756 (define (references/substitutes store items)
757 "Return the list of list of references of ITEMS; the result has the same
758 length as ITEMS. Query substitute information for any item missing from the
759 store at once. Raise a '&nix-protocol-error' exception if reference
760 information for one of ITEMS is missing."
761 (let* ((local-refs (map (lambda (item)
762 (or (hash-ref %reference-cache item)
763 (guard (c ((nix-protocol-error? c) #f))
764 (references store item))))
766 (missing (fold-right (lambda (item local-ref result)
773 ;; Query all the substitutes at once to minimize the cost of
774 ;; launching 'guix substitute' and making HTTP requests.
775 (substs (substitutable-path-info store missing)))
776 (when (< (length substs) (length missing))
777 (raise (condition (&nix-protocol-error
778 (message "cannot determine \
779 the list of references")
782 ;; Intersperse SUBSTS and LOCAL-REFS.
783 (let loop ((items items)
784 (local-refs local-refs)
788 (let ((result (reverse result)))
789 (for-each (cut hash-set! %reference-cache <> <>)
796 (cons (any (lambda (subst)
797 (and (string=? (substitutable-path subst) item)
798 (substitutable-references subst)))
803 (cons head result)))))))))
805 (define* (fold-path store proc seed path
806 #:optional (relatives (cut references store <>)))
807 "Call PROC for each of the RELATIVES of PATH, exactly once, and return the
808 result formed from the successive calls to PROC, the first of which is passed
810 (let loop ((paths (list path))
815 (if (vhash-assoc path seen)
816 (loop rest result seen)
817 (let ((seen (vhash-cons path #t seen))
818 (rest (append rest (relatives path)))
819 (result (proc path result)))
820 (loop rest result seen))))
824 (define (requisites store path)
825 "Return the requisites of PATH, including PATH---i.e., its closure (all its
826 references, recursively)."
827 (fold-path store cons '() path))
829 (define (topologically-sorted store paths)
830 "Return a list containing PATHS and all their references sorted in
833 ;; Do a simple depth-first traversal of all of PATHS.
834 (let loop ((paths paths)
838 (vhash-cons n #t visited))
841 (vhash-assoc n visited))
846 (loop tail visited result)
849 (loop (references store head)
852 (lambda (visited result)
855 (cons head result))))))
857 (values visited result)))))
859 (call-with-values traverse
864 (operation (query-referrers (store-path path))
865 "Return the list of path that refer to PATH."
868 (define valid-derivers
869 (operation (query-valid-derivers (store-path path))
870 "Return the list of valid \"derivers\" of PATH---i.e., all the
871 .drv present in the store that have PATH among their outputs."
874 (define query-derivation-outputs ; avoid name clash with `derivation-outputs'
875 (operation (query-derivation-outputs (store-path path))
876 "Return the list of outputs of PATH, a .drv file."
879 (define-operation (has-substitutes? (store-path path))
880 "Return #t if binary substitutes are available for PATH, and #f otherwise."
883 (define substitutable-paths
884 (operation (query-substitutable-paths (store-path-list paths))
885 "Return the subset of PATHS that is substitutable."
888 (define substitutable-path-info
889 (operation (query-substitutable-path-infos (store-path-list paths))
890 "Return information about the subset of PATHS that is
891 substitutable. For each substitutable path, a `substitutable?' object is
892 returned; thus, the resulting list can be shorter than PATHS. Furthermore,
893 that there is no guarantee that the order of the resulting list matches the
895 substitutable-path-list))
897 (define-operation (optimize-store)
898 "Optimize the store by hard-linking identical files (\"deduplication\".)
899 Return #t on success."
900 ;; Note: the daemon in Guix <= 0.8.2 does not implement this RPC.
904 (let ((verify (operation (verify-store (boolean check-contents?)
908 (lambda* (store #:key check-contents? repair?)
909 "Verify the integrity of the store and return false if errors remain,
910 and true otherwise. When REPAIR? is true, repair any missing or altered store
911 items by substituting them (this typically requires root privileges because it
912 is not an atomic operation.) When CHECK-CONTENTS? is true, check the contents
913 of store items; this can take a lot of time."
914 (not (verify store check-contents? repair?)))))
916 (define (run-gc server action to-delete min-freed)
917 "Perform the garbage-collector operation ACTION, one of the
918 `gc-action' values. When ACTION is `delete-specific', the TO-DELETE is
919 the list of store paths to delete. IGNORE-LIVENESS? should always be
920 #f. MIN-FREED is the minimum amount of disk space to be freed, in
921 bytes, before the GC can stop. Return the list of store paths delete,
922 and the number of bytes freed."
923 (let ((s (nix-server-socket server)))
924 (write-int (operation-id collect-garbage) s)
926 (write-store-path-list to-delete s)
927 (write-arg boolean #f s) ; ignore-liveness?
928 (write-long-long min-freed s)
929 (write-int 0 s) ; obsolete
930 (when (>= (nix-server-minor-version server) 5)
931 ;; Obsolete `use-atime' and `max-atime' parameters.
935 ;; Loop until the server is done sending error output.
936 (let loop ((done? (process-stderr server)))
937 (or done? (loop (process-stderr server))))
939 (let ((paths (read-store-path-list s))
940 (freed (read-long-long s))
941 (obsolete (read-long-long s)))
942 (unless (null? paths)
943 ;; To be on the safe side, completely invalidate both caches.
944 ;; Otherwise we could end up returning store paths that are no longer
946 (hash-clear! (nix-server-add-to-store-cache server))
947 (hash-clear! (nix-server-add-text-to-store-cache server)))
949 (values paths freed))))
951 (define-syntax-rule (%long-long-max)
952 ;; Maximum unsigned 64-bit integer.
955 (define (live-paths server)
956 "Return the list of live store paths---i.e., store paths still
957 referenced, and thus not subject to being garbage-collected."
958 (run-gc server (gc-action return-live) '() (%long-long-max)))
960 (define (dead-paths server)
961 "Return the list of dead store paths---i.e., store paths no longer
962 referenced, and thus subject to being garbage-collected."
963 (run-gc server (gc-action return-dead) '() (%long-long-max)))
965 (define* (collect-garbage server #:optional (min-freed (%long-long-max)))
966 "Collect garbage from the store at SERVER. If MIN-FREED is non-zero,
967 then collect at least MIN-FREED bytes. Return the paths that were
968 collected, and the number of bytes freed."
969 (run-gc server (gc-action delete-dead) '() min-freed))
971 (define* (delete-paths server paths #:optional (min-freed (%long-long-max)))
972 "Delete PATHS from the store at SERVER, if they are no longer
973 referenced. If MIN-FREED is non-zero, then stop after at least
974 MIN-FREED bytes have been collected. Return the paths that were
975 collected, and the number of bytes freed."
976 (run-gc server (gc-action delete-specific) paths min-freed))
978 (define (import-paths server port)
979 "Import the set of store paths read from PORT into SERVER's store. An error
980 is raised if the set of paths read from PORT is not signed (as per
981 'export-path #:sign? #t'.) Return the list of store paths imported."
982 (let ((s (nix-server-socket server)))
983 (write-int (operation-id import-paths) s)
984 (let loop ((done? (process-stderr server port)))
985 (or done? (loop (process-stderr server port))))
986 (read-store-path-list s)))
988 (define* (export-path server path port #:key (sign? #t))
989 "Export PATH to PORT. When SIGN? is true, sign it."
990 (let ((s (nix-server-socket server)))
991 (write-int (operation-id export-path) s)
992 (write-store-path path s)
993 (write-arg boolean sign? s)
994 (let loop ((done? (process-stderr server port)))
995 (or done? (loop (process-stderr server port))))
998 (define* (export-paths server paths port #:key (sign? #t) recursive?)
999 "Export the store paths listed in PATHS to PORT, in topological order,
1000 signing them if SIGN? is true. When RECURSIVE? is true, export the closure of
1001 PATHS---i.e., PATHS and all their dependencies."
1003 (let ((sorted (topologically-sorted server paths)))
1004 ;; When RECURSIVE? is #f, filter out the references of PATHS.
1007 (filter (cut member <> paths) sorted))))
1009 (let loop ((paths ordered))
1015 (and (export-path server head port #:sign? sign?)
1018 (define-operation (query-failed-paths)
1019 "Return the list of store items for which a build failure is cached.
1021 The result is always the empty list unless the daemon was started with
1022 '--cache-failures'."
1025 (define-operation (clear-failed-paths (store-path-list items))
1026 "Remove ITEMS from the list of cached build failures.
1028 This makes sense only when the daemon was started with '--cache-failures'."
1031 (define* (register-path path
1032 #:key (references '()) deriver prefix
1034 "Register PATH as a valid store file, with REFERENCES as its list of
1035 references, and DERIVER as its deriver (.drv that led to it.) If PREFIX is
1036 not #f, it must be the name of the directory containing the new store to
1037 initialize; if STATE-DIRECTORY is not #f, it must be a string containing the
1038 absolute file name to the state directory of the store being initialized.
1039 Return #t on success.
1041 Use with care as it directly modifies the store! This is primarily meant to
1042 be used internally by the daemon's build hook."
1043 ;; Currently this is implemented by calling out to the fine C++ blob.
1044 (catch 'system-error
1046 (let ((pipe (apply open-pipe* OPEN_WRITE %guix-register-program
1048 `("--prefix" ,prefix)
1050 ,@(if state-directory
1051 `("--state-directory" ,state-directory)
1055 (format pipe "~a~%~a~%~a~%"
1056 path (or deriver "") (length references))
1057 (for-each (cut format pipe "~a~%" <>) references)
1058 (zero? (close-pipe pipe))))))
1060 ;; Failed to run %GUIX-REGISTER-PROGRAM.
1068 (define-syntax-rule (define-alias new old)
1069 (define-syntax new (identifier-syntax old)))
1071 ;; The store monad allows us to (1) build sequences of operations in the
1072 ;; store, and (2) make the store an implicit part of the execution context,
1073 ;; rather than a parameter of every single function.
1074 (define-alias %store-monad %state-monad)
1075 (define-alias store-return state-return)
1076 (define-alias store-bind state-bind)
1078 (define (preserve-documentation original proc)
1079 "Return PROC with documentation taken from ORIGINAL."
1080 (set-object-property! proc 'documentation
1081 (procedure-property original 'documentation))
1084 (define (store-lift proc)
1085 "Lift PROC, a procedure whose first argument is a connection to the store,
1086 in the store monad."
1087 (preserve-documentation proc
1090 (values (apply proc store args) store)))))
1092 (define (store-lower proc)
1093 "Lower PROC, a monadic procedure in %STORE-MONAD, to a \"normal\" procedure
1094 taking the store as its first argument."
1095 (preserve-documentation proc
1096 (lambda (store . args)
1097 (run-with-store store (apply proc args)))))
1100 ;; Store monad operators.
1103 (define* (text-file name text
1104 #:optional (references '()))
1105 "Return as a monadic value the absolute file name in the store of the file
1106 containing TEXT, a string. REFERENCES is a list of store items that the
1107 resulting text file refers to; it defaults to the empty list."
1109 (values (add-text-to-store store name text references)
1112 (define* (interned-file file #:optional name
1113 #:key (recursive? #t))
1114 "Return the name of FILE once interned in the store. Use NAME as its store
1115 name, or the basename of FILE if NAME is omitted.
1117 When RECURSIVE? is true, the contents of FILE are added recursively; if FILE
1118 designates a flat file and RECURSIVE? is true, its contents are added, and its
1119 permission bits are kept."
1121 (values (add-to-store store (or name (basename file))
1122 recursive? "sha256" file)
1126 ;; Monadic variant of 'build-things'.
1127 (store-lift build-things))
1129 (define set-build-options*
1130 (store-lift set-build-options))
1132 (define-inlinable (current-system)
1133 ;; Consult the %CURRENT-SYSTEM fluid at bind time. This is equivalent to
1134 ;; (lift0 %current-system %store-monad), but inlinable, thus avoiding
1135 ;; closure allocation in some cases.
1137 (values (%current-system) state)))
1139 (define-inlinable (set-current-system system)
1140 ;; Set the %CURRENT-SYSTEM fluid at bind time.
1142 (values (%current-system system) state)))
1144 (define %guile-for-build
1145 ;; The derivation of the Guile to be used within the build environment,
1146 ;; when using 'gexp->derivation' and co.
1147 (make-parameter #f))
1149 (define* (run-with-store store mval
1151 (guile-for-build (%guile-for-build))
1152 (system (%current-system)))
1153 "Run MVAL, a monadic value in the store monad, in STORE, an open store
1154 connection, and return the result."
1155 ;; Initialize the dynamic bindings here to avoid bad surprises. The
1156 ;; difficulty lies in the fact that dynamic bindings are resolved at
1157 ;; bind-time and not at call time, which can be disconcerting.
1158 (parameterize ((%guile-for-build guile-for-build)
1159 (%current-system system)
1160 (%current-target-system #f))
1161 (call-with-values (lambda ()
1162 (run-with-state mval store))
1163 (lambda (result store)
1164 ;; Discard the state.
1172 (define %store-prefix
1173 ;; Absolute path to the Nix store.
1174 (make-parameter %store-directory))
1176 (define (store-path? path)
1177 "Return #t if PATH is a store path."
1178 ;; This is a lightweight check, compared to using a regexp, but this has to
1179 ;; be fast as it's called often in `derivation', for instance.
1180 ;; `isStorePath' in Nix does something similar.
1181 (string-prefix? (%store-prefix) path))
1183 (define (direct-store-path? path)
1184 "Return #t if PATH is a store path, and not a sub-directory of a store path.
1185 This predicate is sometimes needed because files *under* a store path are not
1187 (and (store-path? path)
1188 (not (string=? path (%store-prefix)))
1189 (let ((len (+ 1 (string-length (%store-prefix)))))
1190 (not (string-index (substring path len) #\/)))))
1192 (define (direct-store-path path)
1193 "Return the direct store path part of PATH, stripping components after
1194 '/gnu/store/xxxx-foo'."
1195 (let ((prefix-length (+ (string-length (%store-prefix)) 35)))
1196 (if (> (string-length path) prefix-length)
1197 (let ((slash (string-index path #\/ prefix-length)))
1198 (if slash (string-take path slash) path))
1201 (define (derivation-path? path)
1202 "Return #t if PATH is a derivation path."
1203 (and (store-path? path) (string-suffix? ".drv" path)))
1205 (define store-regexp*
1206 ;; The substituter makes repeated calls to 'store-path-hash-part', hence
1207 ;; this optimization.
1210 "Return a regexp matching a file in STORE."
1211 (make-regexp (string-append "^" (regexp-quote store)
1212 "/([0-9a-df-np-sv-z]{32})-([^/]+)$")))))
1214 (define (store-path-package-name path)
1215 "Return the package name part of PATH, a file name in the store."
1216 (let ((path-rx (store-regexp* (%store-prefix))))
1217 (and=> (regexp-exec path-rx path)
1218 (cut match:substring <> 2))))
1220 (define (store-path-hash-part path)
1221 "Return the hash part of PATH as a base32 string, or #f if PATH is not a
1222 syntactically valid store path."
1223 (let ((path-rx (store-regexp* (%store-prefix))))
1224 (and=> (regexp-exec path-rx path)
1225 (cut match:substring <> 1))))
1227 (define (log-file store file)
1228 "Return the build log file for FILE, or #f if none could be found. FILE
1229 must be an absolute store file name, or a derivation file name."
1230 (cond ((derivation-path? file)
1231 (let* ((base (basename file))
1232 (log (string-append (dirname %state-directory) ; XXX
1234 (string-take base 2) "/"
1235 (string-drop base 2)))
1236 (log.bz2 (string-append log ".bz2")))
1237 (cond ((file-exists? log.bz2) log.bz2)
1238 ((file-exists? log) log)
1241 (match (valid-derivers store file)
1243 ;; Return the first that works.
1244 (any (cut log-file store <>) derivers))