store.scm 87 KB

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