store.scm 84 KB

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