store.scm 87 KB

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