store.scm 85 KB

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