store.scm 85 KB

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