store.scm 90 KB

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