store.scm 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275
  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. (if (>= (store-connection-minor-version store) 15)
  1292. (build store things mode)
  1293. (if (= mode (build-mode normal))
  1294. (build/old store things)
  1295. (raise (condition (&store-protocol-error
  1296. (message "unsupported build mode")
  1297. (status 1))))))))))))
  1298. (define-operation (ensure-path (store-path path))
  1299. "Ensure that a path is valid. If it is not valid, it may be made valid by
  1300. running a substitute. As a GC root is not created by the daemon, you may want
  1301. to call ADD-TEMP-ROOT on that store path."
  1302. boolean)
  1303. (define-operation (find-roots)
  1304. "Return a list of root/target pairs: for each pair, the first element is the
  1305. GC root file name and the second element is its target in the store.
  1306. When talking to a local daemon, this operation is equivalent to the 'gc-roots'
  1307. procedure in (guix store roots), except that the 'find-roots' excludes
  1308. potential roots that do not point to store items."
  1309. string-pairs)
  1310. (define-operation (add-temp-root (store-path path))
  1311. "Make PATH a temporary root for the duration of the current session.
  1312. Return #t."
  1313. boolean)
  1314. (define-operation (add-indirect-root (string file-name))
  1315. "Make the symlink FILE-NAME an indirect root for the garbage collector:
  1316. whatever store item FILE-NAME points to will not be collected. Return #t on
  1317. success.
  1318. FILE-NAME can be anywhere on the file system, but it must be an absolute file
  1319. name--it is the caller's responsibility to ensure that it is an absolute file
  1320. name."
  1321. boolean)
  1322. (define %gc-roots-directory
  1323. ;; The place where garbage collector roots (symlinks) are kept.
  1324. (string-append %state-directory "/gcroots"))
  1325. (define (add-permanent-root target)
  1326. "Add a garbage collector root pointing to TARGET, an element of the store,
  1327. preventing TARGET from even being collected. This can also be used if TARGET
  1328. does not exist yet.
  1329. Raise an error if the caller does not have write access to the GC root
  1330. directory."
  1331. (let* ((root (string-append %gc-roots-directory "/" (basename target))))
  1332. (catch 'system-error
  1333. (lambda ()
  1334. (symlink target root))
  1335. (lambda args
  1336. ;; If ROOT already exists, this is fine; otherwise, re-throw.
  1337. (unless (= EEXIST (system-error-errno args))
  1338. (apply throw args))))))
  1339. (define (remove-permanent-root target)
  1340. "Remove the permanent garbage collector root pointing to TARGET. Raise an
  1341. error if there is no such root."
  1342. (delete-file (string-append %gc-roots-directory "/" (basename target))))
  1343. (define references
  1344. (operation (query-references (store-path path))
  1345. "Return the list of references of PATH."
  1346. store-path-list))
  1347. (define* (fold-path store proc seed paths
  1348. #:optional (relatives (cut references store <>)))
  1349. "Call PROC for each of the RELATIVES of PATHS, exactly once, and return the
  1350. result formed from the successive calls to PROC, the first of which is passed
  1351. SEED."
  1352. (let loop ((paths paths)
  1353. (result seed)
  1354. (seen vlist-null))
  1355. (match paths
  1356. ((path rest ...)
  1357. (if (vhash-assoc path seen)
  1358. (loop rest result seen)
  1359. (let ((seen (vhash-cons path #t seen))
  1360. (rest (append rest (relatives path)))
  1361. (result (proc path result)))
  1362. (loop rest result seen))))
  1363. (()
  1364. result))))
  1365. (define (requisites store paths)
  1366. "Return the requisites of PATHS, including PATHS---i.e., their closures (all
  1367. its references, recursively)."
  1368. (fold-path store cons '() paths))
  1369. (define (topologically-sorted store paths)
  1370. "Return a list containing PATHS and all their references sorted in
  1371. topological order."
  1372. (define (traverse)
  1373. ;; Do a simple depth-first traversal of all of PATHS.
  1374. (let loop ((paths paths)
  1375. (visited vlist-null)
  1376. (result '()))
  1377. (define (visit n)
  1378. (vhash-cons n #t visited))
  1379. (define (visited? n)
  1380. (vhash-assoc n visited))
  1381. (match paths
  1382. ((head tail ...)
  1383. (if (visited? head)
  1384. (loop tail visited result)
  1385. (call-with-values
  1386. (lambda ()
  1387. (loop (references store head)
  1388. (visit head)
  1389. result))
  1390. (lambda (visited result)
  1391. (loop tail
  1392. visited
  1393. (cons head result))))))
  1394. (()
  1395. (values visited result)))))
  1396. (call-with-values traverse
  1397. (lambda (_ result)
  1398. (reverse result))))
  1399. (define referrers
  1400. (operation (query-referrers (store-path path))
  1401. "Return the list of path that refer to PATH."
  1402. store-path-list))
  1403. (define valid-derivers
  1404. (operation (query-valid-derivers (store-path path))
  1405. "Return the list of valid \"derivers\" of PATH---i.e., all the
  1406. .drv present in the store that have PATH among their outputs."
  1407. store-path-list))
  1408. (define query-derivation-outputs ; avoid name clash with `derivation-outputs'
  1409. (operation (query-derivation-outputs (store-path path))
  1410. "Return the list of outputs of PATH, a .drv file."
  1411. store-path-list))
  1412. (define-operation (has-substitutes? (store-path path))
  1413. "Return #t if binary substitutes are available for PATH, and #f otherwise."
  1414. boolean)
  1415. (define substitutable-paths
  1416. (operation (query-substitutable-paths (store-path-list paths))
  1417. "Return the subset of PATHS that is substitutable."
  1418. store-path-list))
  1419. (define substitutable-path-info
  1420. (operation (query-substitutable-path-infos (store-path-list paths))
  1421. "Return information about the subset of PATHS that is
  1422. substitutable. For each substitutable path, a `substitutable?' object is
  1423. returned; thus, the resulting list can be shorter than PATHS. Furthermore,
  1424. that there is no guarantee that the order of the resulting list matches the
  1425. order of PATHS."
  1426. substitutable-path-list))
  1427. (define %built-in-builders
  1428. (let ((builders (operation (built-in-builders)
  1429. "Return the built-in builders."
  1430. string-list)))
  1431. (lambda (store)
  1432. "Return the names of the supported built-in derivation builders
  1433. supported by STORE. The result is memoized for STORE."
  1434. ;; Check whether STORE's version supports this RPC and built-in
  1435. ;; derivation builders in general, which appeared in Guix > 0.11.0.
  1436. ;; Return the empty list if it doesn't. Note that this RPC does not
  1437. ;; exist in 'nix-daemon'.
  1438. (if (or (> (store-connection-major-version store) #x100)
  1439. (and (= (store-connection-major-version store) #x100)
  1440. (>= (store-connection-minor-version store) #x60)))
  1441. (builders store)
  1442. '()))))
  1443. (define (built-in-builders store)
  1444. "Return the names of the supported built-in derivation builders
  1445. supported by STORE."
  1446. (force (store-connection-built-in-builders store)))
  1447. (define-operation (optimize-store)
  1448. "Optimize the store by hard-linking identical files (\"deduplication\".)
  1449. Return #t on success."
  1450. ;; Note: the daemon in Guix <= 0.8.2 does not implement this RPC.
  1451. boolean)
  1452. (define verify-store
  1453. (let ((verify (operation (verify-store (boolean check-contents?)
  1454. (boolean repair?))
  1455. "Verify the store."
  1456. boolean)))
  1457. (lambda* (store #:key check-contents? repair?)
  1458. "Verify the integrity of the store and return false if errors remain,
  1459. and true otherwise. When REPAIR? is true, repair any missing or altered store
  1460. items by substituting them (this typically requires root privileges because it
  1461. is not an atomic operation.) When CHECK-CONTENTS? is true, check the contents
  1462. of store items; this can take a lot of time."
  1463. (not (verify store check-contents? repair?)))))
  1464. (define (run-gc server action to-delete min-freed)
  1465. "Perform the garbage-collector operation ACTION, one of the
  1466. `gc-action' values. When ACTION is `delete-specific', the TO-DELETE is
  1467. the list of store paths to delete. IGNORE-LIVENESS? should always be
  1468. #f. MIN-FREED is the minimum amount of disk space to be freed, in
  1469. bytes, before the GC can stop. Return the list of store paths delete,
  1470. and the number of bytes freed."
  1471. (let ((s (store-connection-socket server))
  1472. (buffered (store-connection-output-port server)))
  1473. (write-int (operation-id collect-garbage) buffered)
  1474. (write-int action buffered)
  1475. (write-store-path-list to-delete buffered)
  1476. (write-arg boolean #f buffered) ; ignore-liveness?
  1477. (write-long-long min-freed buffered)
  1478. (write-int 0 buffered) ; obsolete
  1479. (when (>= (store-connection-minor-version server) 5)
  1480. ;; Obsolete `use-atime' and `max-atime' parameters.
  1481. (write-int 0 buffered)
  1482. (write-int 0 buffered))
  1483. (write-buffered-output server)
  1484. ;; Loop until the server is done sending error output.
  1485. (let loop ((done? (process-stderr server)))
  1486. (or done? (loop (process-stderr server))))
  1487. (let ((paths (read-store-path-list s))
  1488. (freed (read-long-long s))
  1489. (obsolete (read-long-long s)))
  1490. (unless (null? paths)
  1491. ;; To be on the safe side, completely invalidate both caches.
  1492. ;; Otherwise we could end up returning store paths that are no longer
  1493. ;; valid.
  1494. (hash-clear! (store-connection-add-to-store-cache server))
  1495. (hash-clear! (store-connection-add-text-to-store-cache server)))
  1496. (values paths freed))))
  1497. (define-syntax-rule (%long-long-max)
  1498. ;; Maximum unsigned 64-bit integer.
  1499. (- (expt 2 64) 1))
  1500. (define (live-paths server)
  1501. "Return the list of live store paths---i.e., store paths still
  1502. referenced, and thus not subject to being garbage-collected."
  1503. (run-gc server (gc-action return-live) '() (%long-long-max)))
  1504. (define (dead-paths server)
  1505. "Return the list of dead store paths---i.e., store paths no longer
  1506. referenced, and thus subject to being garbage-collected."
  1507. (run-gc server (gc-action return-dead) '() (%long-long-max)))
  1508. (define* (collect-garbage server #:optional (min-freed (%long-long-max)))
  1509. "Collect garbage from the store at SERVER. If MIN-FREED is non-zero,
  1510. then collect at least MIN-FREED bytes. Return the paths that were
  1511. collected, and the number of bytes freed."
  1512. (run-gc server (gc-action delete-dead) '() min-freed))
  1513. (define* (delete-paths server paths #:optional (min-freed (%long-long-max)))
  1514. "Delete PATHS from the store at SERVER, if they are no longer
  1515. referenced. If MIN-FREED is non-zero, then stop after at least
  1516. MIN-FREED bytes have been collected. Return the paths that were
  1517. collected, and the number of bytes freed."
  1518. (run-gc server (gc-action delete-specific) paths min-freed))
  1519. (define (import-paths server port)
  1520. "Import the set of store paths read from PORT into SERVER's store. An error
  1521. is raised if the set of paths read from PORT is not signed (as per
  1522. 'export-path #:sign? #t'.) Return the list of store paths imported."
  1523. (let ((s (store-connection-socket server)))
  1524. (write-int (operation-id import-paths) s)
  1525. (let loop ((done? (process-stderr server port)))
  1526. (or done? (loop (process-stderr server port))))
  1527. (read-store-path-list s)))
  1528. (define* (export-path server path port #:key (sign? #t))
  1529. "Export PATH to PORT. When SIGN? is true, sign it."
  1530. (let ((s (store-connection-socket server))
  1531. (buffered (store-connection-output-port server)))
  1532. (write-int (operation-id export-path) buffered)
  1533. (write-store-path path buffered)
  1534. (write-arg boolean sign? buffered)
  1535. (write-buffered-output server)
  1536. (let loop ((done? (process-stderr server port)))
  1537. (or done? (loop (process-stderr server port))))
  1538. (= 1 (read-int s))))
  1539. (define* (export-paths server paths port #:key (sign? #t) recursive?
  1540. (start (const #f))
  1541. (progress (const #f))
  1542. (finish (const #f)))
  1543. "Export the store paths listed in PATHS to PORT, in topological order,
  1544. signing them if SIGN? is true. When RECURSIVE? is true, export the closure of
  1545. PATHS---i.e., PATHS and all their dependencies.
  1546. START, PROGRESS, and FINISH are used to track progress of the data transfer.
  1547. START is a one-argument that is passed the list of store items that will be
  1548. transferred; it returns values that are then used as the initial state
  1549. threaded through PROGRESS calls. PROGRESS is passed the store item about to
  1550. be sent, along with the values previously return by START or by PROGRESS
  1551. itself. FINISH is called when the last store item has been called."
  1552. (define ordered
  1553. (let ((sorted (topologically-sorted server paths)))
  1554. ;; When RECURSIVE? is #f, filter out the references of PATHS.
  1555. (if recursive?
  1556. sorted
  1557. (filter (cut member <> paths) sorted))))
  1558. (let loop ((paths ordered)
  1559. (state (call-with-values (lambda () (start ordered))
  1560. list)))
  1561. (match paths
  1562. (()
  1563. (apply finish state)
  1564. (write-int 0 port))
  1565. ((head tail ...)
  1566. (write-int 1 port)
  1567. (and (export-path server head port #:sign? sign?)
  1568. (loop tail
  1569. (call-with-values
  1570. (lambda () (apply progress head state))
  1571. list)))))))
  1572. (define-operation (query-failed-paths)
  1573. "Return the list of store items for which a build failure is cached.
  1574. The result is always the empty list unless the daemon was started with
  1575. '--cache-failures'."
  1576. store-path-list)
  1577. (define-operation (clear-failed-paths (store-path-list items))
  1578. "Remove ITEMS from the list of cached build failures.
  1579. This makes sense only when the daemon was started with '--cache-failures'."
  1580. boolean)
  1581. ;;;
  1582. ;;; Per-connection caches.
  1583. ;;;
  1584. ;; Number of currently allocated store connection caches--things that go in
  1585. ;; the 'caches' vector of <store-connection>.
  1586. (define %store-connection-caches (make-atomic-box 0))
  1587. (define (allocate-store-connection-cache name)
  1588. "Allocate a new cache for store connections and return its identifier. Said
  1589. identifier can be passed as an argument to "
  1590. (let loop ((current (atomic-box-ref %store-connection-caches)))
  1591. (let ((previous (atomic-box-compare-and-swap! %store-connection-caches
  1592. current (+ current 1))))
  1593. (if (= previous current)
  1594. current
  1595. (loop current)))))
  1596. (define %object-cache-id
  1597. ;; The "object cache", mapping lowerable objects such as <package> records
  1598. ;; to derivations.
  1599. (allocate-store-connection-cache 'object-cache))
  1600. (define (vector-set vector index value)
  1601. (let ((new (vector-copy vector)))
  1602. (vector-set! new index value)
  1603. new))
  1604. (define (store-connection-cache store cache)
  1605. "Return the cache of STORE identified by CACHE, an identifier as returned by
  1606. 'allocate-store-connection-cache'."
  1607. (vector-ref (store-connection-caches store) cache))
  1608. (define (set-store-connection-cache store cache value)
  1609. "Return a copy of STORE where CACHE has the given VALUE. CACHE must be a
  1610. value returned by 'allocate-store-connection-cache'."
  1611. (store-connection
  1612. (inherit store)
  1613. (caches (vector-set (store-connection-caches store) cache value))))
  1614. (define set-store-connection-caches! ;private
  1615. (record-modifier <store-connection> 'caches))
  1616. (define (set-store-connection-cache! store cache value)
  1617. "Set STORE's CACHE to VALUE.
  1618. This is a mutating version that should be avoided. Prefer the functional
  1619. 'set-store-connection-cache' instead, together with using %STORE-MONAD."
  1620. (vector-set! (store-connection-caches store) cache value))
  1621. (define %reference-cache-id
  1622. ;; Cache mapping store items to their list of references. Caching matters
  1623. ;; because when building a profile in the presence of grafts, we keep
  1624. ;; calling 'graft-derivation', which in turn calls 'references/cached' many
  1625. ;; times with the same arguments.
  1626. (allocate-store-connection-cache 'reference-cache))
  1627. (define (references/cached store item)
  1628. "Like 'references', but cache results."
  1629. (let ((cache (store-connection-cache store %reference-cache-id)))
  1630. (match (vhash-assoc item cache)
  1631. ((_ . references)
  1632. references)
  1633. (#f
  1634. (let* ((references (references store item))
  1635. (cache (vhash-cons item references cache)))
  1636. (set-store-connection-cache! store %reference-cache-id cache)
  1637. references)))))
  1638. ;;;
  1639. ;;; Store monad.
  1640. ;;;
  1641. (define-syntax-rule (define-alias new old)
  1642. (define-syntax new (identifier-syntax old)))
  1643. ;; The store monad allows us to (1) build sequences of operations in the
  1644. ;; store, and (2) make the store an implicit part of the execution context,
  1645. ;; rather than a parameter of every single function.
  1646. (define-alias %store-monad %state-monad)
  1647. (define-alias store-return state-return)
  1648. (define-alias store-bind state-bind)
  1649. ;; Instantiate templates for %STORE-MONAD since it's syntactically different
  1650. ;; from %STATE-MONAD.
  1651. (template-directory instantiations %store-monad)
  1652. (define* (cache-object-mapping object keys result
  1653. #:key
  1654. (cache %object-cache-id)
  1655. (vhash-cons vhash-consq))
  1656. "Augment the store's object cache with a mapping from OBJECT/KEYS to RESULT.
  1657. KEYS is a list of additional keys to match against, for instance a (SYSTEM
  1658. TARGET) tuple. Use VHASH-CONS to insert OBJECT into the cache.
  1659. OBJECT is typically a high-level object such as a <package> or an <origin>,
  1660. and RESULT is typically its derivation."
  1661. (lambda (store)
  1662. (values result
  1663. (set-store-connection-cache
  1664. store cache
  1665. (vhash-cons object (cons result keys)
  1666. (store-connection-cache store cache))))))
  1667. (define (cache-lookup-recorder component title)
  1668. "Return a procedure of two arguments to record cache lookups, hits, and
  1669. misses for COMPONENT. The procedure must be passed a Boolean indicating
  1670. whether the cache lookup was a hit, and the actual cache (a vhash)."
  1671. (if (profiled? component)
  1672. (let ((fresh 0)
  1673. (lookups 0)
  1674. (hits 0)
  1675. (size 0))
  1676. (register-profiling-hook!
  1677. component
  1678. (lambda ()
  1679. (format (current-error-port) "~a:
  1680. fresh caches: ~5@a
  1681. lookups: ~5@a
  1682. hits: ~5@a (~,1f%)
  1683. cache size: ~5@a entries~%"
  1684. title fresh lookups hits
  1685. (if (zero? lookups)
  1686. 100.
  1687. (* 100. (/ hits lookups)))
  1688. size)))
  1689. (lambda (hit? cache)
  1690. (set! fresh
  1691. (if (eq? cache vlist-null)
  1692. (+ 1 fresh)
  1693. fresh))
  1694. (set! lookups (+ 1 lookups))
  1695. (set! hits (if hit? (+ hits 1) hits))
  1696. (set! size (+ (if hit? 0 1)
  1697. (vlist-length cache)))))
  1698. (lambda (x y)
  1699. #t)))
  1700. (define record-cache-lookup!
  1701. (cache-lookup-recorder "object-cache" "Store object cache"))
  1702. (define-inlinable (lookup-cached-object object keys vhash-fold*)
  1703. "Return the cached object in the store connection corresponding to OBJECT
  1704. and KEYS; use VHASH-FOLD* to look for OBJECT in the cache. KEYS is a list of
  1705. additional keys to match against, and which are compared with 'equal?'.
  1706. Return #f on failure and the cached result otherwise."
  1707. (lambda (store)
  1708. (let* ((cache (store-connection-cache store %object-cache-id))
  1709. ;; Escape as soon as we find the result. This avoids traversing
  1710. ;; the whole vlist chain and significantly reduces the number of
  1711. ;; 'hashq' calls.
  1712. (value (let/ec return
  1713. (vhash-fold* (lambda (item result)
  1714. (match item
  1715. ((value . keys*)
  1716. (if (equal? keys keys*)
  1717. (return value)
  1718. result))))
  1719. #f object
  1720. cache))))
  1721. (record-cache-lookup! value cache)
  1722. (values value store))))
  1723. (define* (%mcached mthunk object #:optional (keys '())
  1724. #:key
  1725. (vhash-cons vhash-consq)
  1726. (vhash-fold* vhash-foldq*))
  1727. "Bind the monadic value returned by MTHUNK, which supposedly corresponds to
  1728. OBJECT/KEYS, or return its cached value. Use VHASH-CONS to insert OBJECT into
  1729. the cache, and VHASH-FOLD* to look it up."
  1730. (mlet %store-monad ((cached (lookup-cached-object object keys
  1731. vhash-fold*)))
  1732. (if cached
  1733. (return cached)
  1734. (>>= (mthunk)
  1735. (lambda (result)
  1736. (cache-object-mapping object keys result
  1737. #:vhash-cons vhash-cons))))))
  1738. (define-syntax mcached
  1739. (syntax-rules (eq? equal?)
  1740. "Run MVALUE, which corresponds to OBJECT/KEYS, and cache it; or return the
  1741. value associated with OBJECT/KEYS in the store's object cache if there is
  1742. one."
  1743. ((_ eq? mvalue object keys ...)
  1744. (%mcached (lambda () mvalue)
  1745. object (list keys ...)
  1746. #:vhash-cons vhash-consq
  1747. #:vhash-fold* vhash-foldq*))
  1748. ((_ equal? mvalue object keys ...)
  1749. (%mcached (lambda () mvalue)
  1750. object (list keys ...)
  1751. #:vhash-cons vhash-cons
  1752. #:vhash-fold* vhash-fold*))
  1753. ((_ mvalue object keys ...)
  1754. (mcached eq? mvalue object keys ...))))
  1755. (define (preserve-documentation original proc)
  1756. "Return PROC with documentation taken from ORIGINAL."
  1757. (set-object-property! proc 'documentation
  1758. (procedure-property original 'documentation))
  1759. proc)
  1760. (define (store-lift proc)
  1761. "Lift PROC, a procedure whose first argument is a connection to the store,
  1762. in the store monad."
  1763. (preserve-documentation proc
  1764. (lambda args
  1765. (lambda (store)
  1766. (values (apply proc store args) store)))))
  1767. (define (store-lower proc)
  1768. "Lower PROC, a monadic procedure in %STORE-MONAD, to a \"normal\" procedure
  1769. taking the store as its first argument."
  1770. (preserve-documentation proc
  1771. (lambda (store . args)
  1772. (run-with-store store (apply proc args)))))
  1773. (define (mapm/accumulate-builds mproc lst)
  1774. "Like 'mapm' in %STORE-MONAD, but accumulate 'build-things' calls and
  1775. coalesce them into a single call."
  1776. (lambda (store)
  1777. (values (map/accumulate-builds store
  1778. (lambda (obj)
  1779. (run-with-store store
  1780. (mproc obj)
  1781. #:system (%current-system)
  1782. #:target (%current-target-system)))
  1783. lst)
  1784. store)))
  1785. ;;
  1786. ;; Store monad operators.
  1787. ;;
  1788. (define* (binary-file name
  1789. data ;bytevector
  1790. #:optional (references '()))
  1791. "Return as a monadic value the absolute file name in the store of the file
  1792. containing DATA, a bytevector. REFERENCES is a list of store items that the
  1793. resulting text file refers to; it defaults to the empty list."
  1794. (lambda (store)
  1795. (values (add-data-to-store store name data references)
  1796. store)))
  1797. (define* (text-file name
  1798. text ;string
  1799. #:optional (references '()))
  1800. "Return as a monadic value the absolute file name in the store of the file
  1801. containing TEXT, a string. REFERENCES is a list of store items that the
  1802. resulting text file refers to; it defaults to the empty list."
  1803. (lambda (store)
  1804. (values (add-text-to-store store name text references)
  1805. store)))
  1806. (define* (interned-file file #:optional name
  1807. #:key (recursive? #t) (select? true))
  1808. "Return the name of FILE once interned in the store. Use NAME as its store
  1809. name, or the basename of FILE if NAME is omitted.
  1810. When RECURSIVE? is true, the contents of FILE are added recursively; if FILE
  1811. designates a flat file and RECURSIVE? is true, its contents are added, and its
  1812. permission bits are kept.
  1813. When RECURSIVE? is true, call (SELECT? FILE STAT) for each directory entry,
  1814. where FILE is the entry's absolute file name and STAT is the result of
  1815. 'lstat'; exclude entries for which SELECT? does not return true."
  1816. (lambda (store)
  1817. (values (add-to-store store (or name (basename file))
  1818. recursive? "sha256" file
  1819. #:select? select?)
  1820. store)))
  1821. (define interned-file-tree
  1822. (store-lift add-file-tree-to-store))
  1823. (define build
  1824. ;; Monadic variant of 'build-things'.
  1825. (store-lift build-things))
  1826. (define set-build-options*
  1827. (store-lift set-build-options))
  1828. (define references*
  1829. (store-lift references))
  1830. (define (query-path-info* item)
  1831. "Monadic version of 'query-path-info' that returns #f when ITEM is not in
  1832. the store."
  1833. (lambda (store)
  1834. (guard (c ((store-protocol-error? c)
  1835. ;; ITEM is not in the store; return #f.
  1836. (values #f store)))
  1837. (values (query-path-info store item) store))))
  1838. (define-inlinable (current-system)
  1839. ;; Consult the %CURRENT-SYSTEM fluid at bind time. This is equivalent to
  1840. ;; (lift0 %current-system %store-monad), but inlinable, thus avoiding
  1841. ;; closure allocation in some cases.
  1842. (lambda (state)
  1843. (values (%current-system) state)))
  1844. (define-inlinable (set-current-system system)
  1845. ;; Set the %CURRENT-SYSTEM fluid at bind time.
  1846. (lambda (state)
  1847. (values (%current-system system) state)))
  1848. (define-inlinable (current-target-system)
  1849. ;; Consult the %CURRENT-TARGET-SYSTEM fluid at bind time.
  1850. (lambda (state)
  1851. (values (%current-target-system) state)))
  1852. (define-inlinable (set-current-target target)
  1853. ;; Set the %CURRENT-TARGET-SYSTEM fluid at bind time.
  1854. (lambda (state)
  1855. (values (%current-target-system target) state)))
  1856. (define %guile-for-build
  1857. ;; The derivation of the Guile to be used within the build environment,
  1858. ;; when using 'gexp->derivation' and co.
  1859. (make-parameter #f))
  1860. (define* (run-with-store store mval
  1861. #:key
  1862. (guile-for-build (%guile-for-build))
  1863. (system (%current-system))
  1864. (target #f))
  1865. "Run MVAL, a monadic value in the store monad, in STORE, an open store
  1866. connection, and return the result."
  1867. ;; Initialize the dynamic bindings here to avoid bad surprises. The
  1868. ;; difficulty lies in the fact that dynamic bindings are resolved at
  1869. ;; bind-time and not at call time, which can be disconcerting.
  1870. (parameterize ((%guile-for-build guile-for-build)
  1871. (%current-system system)
  1872. (%current-target-system target))
  1873. (call-with-values (lambda ()
  1874. (run-with-state mval store))
  1875. (lambda (result new-store)
  1876. (when (and store new-store)
  1877. ;; Copy the object cache from NEW-STORE so we don't fully discard
  1878. ;; the state.
  1879. (let ((caches (store-connection-caches new-store)))
  1880. (set-store-connection-caches! store caches)))
  1881. result))))
  1882. ;;;
  1883. ;;; Store paths.
  1884. ;;;
  1885. (define %store-prefix
  1886. ;; Absolute path to the Nix store.
  1887. (make-parameter %store-directory))
  1888. (define (compressed-hash bv size) ; `compressHash'
  1889. "Given the hash stored in BV, return a compressed version thereof that fits
  1890. in SIZE bytes."
  1891. (define new (make-bytevector size 0))
  1892. (define old-size (bytevector-length bv))
  1893. (let loop ((i 0))
  1894. (if (= i old-size)
  1895. new
  1896. (let* ((j (modulo i size))
  1897. (o (bytevector-u8-ref new j)))
  1898. (bytevector-u8-set! new j
  1899. (logxor o (bytevector-u8-ref bv i)))
  1900. (loop (+ 1 i))))))
  1901. (define (store-path type hash name) ; makeStorePath
  1902. "Return the store path for NAME/HASH/TYPE."
  1903. (let* ((s (string-append type ":sha256:"
  1904. (bytevector->base16-string hash) ":"
  1905. (%store-prefix) ":" name))
  1906. (h (sha256 (string->utf8 s)))
  1907. (c (compressed-hash h 20)))
  1908. (string-append (%store-prefix) "/"
  1909. (bytevector->nix-base32-string c) "-"
  1910. name)))
  1911. (define (output-path output hash name) ; makeOutputPath
  1912. "Return an output path for OUTPUT (the name of the output as a string) of
  1913. the derivation called NAME with hash HASH."
  1914. (store-path (string-append "output:" output) hash
  1915. (if (string=? output "out")
  1916. name
  1917. (string-append name "-" output))))
  1918. (define* (fixed-output-path name hash
  1919. #:key
  1920. (output "out")
  1921. (hash-algo 'sha256)
  1922. (recursive? #t))
  1923. "Return an output path for the fixed output OUTPUT defined by HASH of type
  1924. HASH-ALGO, of the derivation NAME. RECURSIVE? has the same meaning as for
  1925. 'add-to-store'."
  1926. (if (and recursive? (eq? hash-algo 'sha256))
  1927. (store-path "source" hash name)
  1928. (let ((tag (string-append "fixed:" output ":"
  1929. (if recursive? "r:" "")
  1930. (symbol->string hash-algo) ":"
  1931. (bytevector->base16-string hash) ":")))
  1932. (store-path (string-append "output:" output)
  1933. (sha256 (string->utf8 tag))
  1934. name))))
  1935. (define (store-path? path)
  1936. "Return #t if PATH is a store path."
  1937. ;; This is a lightweight check, compared to using a regexp, but this has to
  1938. ;; be fast as it's called often in `derivation', for instance.
  1939. ;; `isStorePath' in Nix does something similar.
  1940. (string-prefix? (%store-prefix) path))
  1941. (define (direct-store-path? path)
  1942. "Return #t if PATH is a store path, and not a sub-directory of a store path.
  1943. This predicate is sometimes needed because files *under* a store path are not
  1944. valid inputs."
  1945. (and (store-path? path)
  1946. (not (string=? path (%store-prefix)))
  1947. (let ((len (+ 1 (string-length (%store-prefix)))))
  1948. (not (string-index (substring path len) #\/)))))
  1949. (define (direct-store-path path)
  1950. "Return the direct store path part of PATH, stripping components after
  1951. '/gnu/store/xxxx-foo'."
  1952. (let ((prefix-length (+ (string-length (%store-prefix)) 35)))
  1953. (if (> (string-length path) prefix-length)
  1954. (let ((slash (string-index path #\/ prefix-length)))
  1955. (if slash (string-take path slash) path))
  1956. path)))
  1957. (define (derivation-path? path)
  1958. "Return #t if PATH is a derivation path."
  1959. (and (store-path? path) (string-suffix? ".drv" path)))
  1960. (define (store-path-base path)
  1961. "Return the base path of a path in the store."
  1962. (and (string-prefix? (%store-prefix) path)
  1963. (let ((base (string-drop path (+ 1 (string-length (%store-prefix))))))
  1964. (and (> (string-length base) 33)
  1965. (not (string-index base #\/))
  1966. base))))
  1967. (define (store-path-package-name path)
  1968. "Return the package name part of PATH, a file name in the store."
  1969. (let ((base (store-path-base path)))
  1970. (string-drop base (+ 32 1)))) ;32 hash part + 1 hyphen
  1971. (define (store-path-hash-part path)
  1972. "Return the hash part of PATH as a base32 string, or #f if PATH is not a
  1973. syntactically valid store path."
  1974. (match (store-path-base path)
  1975. (#f #f)
  1976. (base
  1977. (let ((hash (string-take base 32)))
  1978. (and (string-every %nix-base32-charset hash)
  1979. hash)))))
  1980. (define (derivation-log-file drv)
  1981. "Return the build log file for DRV, a derivation file name, or #f if it
  1982. could not be found."
  1983. (let* ((base (basename drv))
  1984. (log (string-append (or (getenv "GUIX_LOG_DIRECTORY")
  1985. (string-append %localstatedir "/log/guix"))
  1986. "/drvs/"
  1987. (string-take base 2) "/"
  1988. (string-drop base 2)))
  1989. (log.gz (string-append log ".gz"))
  1990. (log.bz2 (string-append log ".bz2")))
  1991. (cond ((file-exists? log.gz) log.gz)
  1992. ((file-exists? log.bz2) log.bz2)
  1993. ((file-exists? log) log)
  1994. (else #f))))
  1995. (define (log-file store file)
  1996. "Return the build log file for FILE, or #f if none could be found. FILE
  1997. must be an absolute store file name, or a derivation file name."
  1998. (cond ((derivation-path? file)
  1999. (derivation-log-file file))
  2000. (else
  2001. (match (valid-derivers store file)
  2002. ((derivers ...)
  2003. ;; Return the first that works.
  2004. (any (cut log-file store <>) derivers))
  2005. (_ #f)))))
  2006. ;;; Local Variables:
  2007. ;;; eval: (put 'system-error-to-connection-error 'scheme-indent-function 1)
  2008. ;;; End: