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