store.scm 77 KB

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