store.scm 89 KB

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