You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1698 lines
64 KiB

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