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