store.scm 85 KB

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