store.scm 60 KB

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