vm.scm 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995
  1. ;;; GNU Guix --- Functional package management for GNU
  2. ;;; Copyright © 2013, 2014, 2015, 2016, 2017, 2018, 2019 Ludovic Courtès <ludo@gnu.org>
  3. ;;; Copyright © 2016 Christopher Allan Webber <cwebber@dustycloud.org>
  4. ;;; Copyright © 2016, 2017 Leo Famulari <leo@famulari.name>
  5. ;;; Copyright © 2017 Mathieu Othacehe <m.othacehe@gmail.com>
  6. ;;; Copyright © 2017 Marius Bakke <mbakke@fastmail.com>
  7. ;;; Copyright © 2018 Chris Marusich <cmmarusich@gmail.com>
  8. ;;;
  9. ;;; This file is part of GNU Guix.
  10. ;;;
  11. ;;; GNU Guix is free software; you can redistribute it and/or modify it
  12. ;;; under the terms of the GNU General Public License as published by
  13. ;;; the Free Software Foundation; either version 3 of the License, or (at
  14. ;;; your option) any later version.
  15. ;;;
  16. ;;; GNU Guix is distributed in the hope that it will be useful, but
  17. ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
  18. ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. ;;; GNU General Public License for more details.
  20. ;;;
  21. ;;; You should have received a copy of the GNU General Public License
  22. ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
  23. (define-module (gnu system vm)
  24. #:use-module (guix config)
  25. #:use-module (guix store)
  26. #:use-module (guix gexp)
  27. #:use-module (guix derivations)
  28. #:use-module (guix packages)
  29. #:use-module (guix monads)
  30. #:use-module (guix records)
  31. #:use-module (guix modules)
  32. #:use-module (guix utils)
  33. #:use-module (gcrypt hash)
  34. #:use-module (guix base32)
  35. #:use-module ((guix self) #:select (make-config.scm))
  36. #:use-module ((gnu build vm)
  37. #:select (qemu-command))
  38. #:use-module (gnu packages base)
  39. #:use-module (gnu packages bootloaders)
  40. #:use-module (gnu packages cdrom)
  41. #:use-module (gnu packages compression)
  42. #:use-module (gnu packages guile)
  43. #:autoload (gnu packages gnupg) (guile-gcrypt)
  44. #:use-module (gnu packages gawk)
  45. #:use-module (gnu packages bash)
  46. #:use-module (gnu packages less)
  47. #:use-module (gnu packages virtualization)
  48. #:use-module (gnu packages disk)
  49. #:use-module (gnu packages zile)
  50. #:use-module (gnu packages linux)
  51. #:use-module ((gnu packages make-bootstrap)
  52. #:select (%guile-static-stripped))
  53. #:use-module (gnu packages admin)
  54. #:use-module (gnu bootloader)
  55. #:use-module (gnu bootloader grub)
  56. #:use-module (gnu system shadow)
  57. #:use-module (gnu system pam)
  58. #:use-module (gnu system linux-initrd)
  59. #:use-module (gnu bootloader)
  60. #:use-module (gnu system file-systems)
  61. #:use-module (gnu system)
  62. #:use-module (gnu services)
  63. #:use-module (gnu system uuid)
  64. #:use-module (srfi srfi-1)
  65. #:use-module (srfi srfi-26)
  66. #:use-module (rnrs bytevectors)
  67. #:use-module (ice-9 match)
  68. #:export (expression->derivation-in-linux-vm
  69. qemu-image
  70. virtualized-operating-system
  71. system-qemu-image
  72. system-qemu-image/shared-store
  73. system-qemu-image/shared-store-script
  74. system-disk-image
  75. system-docker-image
  76. virtual-machine
  77. virtual-machine?))
  78. ;;; Commentary:
  79. ;;;
  80. ;;; Tools to evaluate build expressions within virtual machines.
  81. ;;;
  82. ;;; Code:
  83. (define %linux-vm-file-systems
  84. ;; File systems mounted for 'derivation-in-linux-vm'. These are shared with
  85. ;; the host over 9p.
  86. (list (file-system
  87. (mount-point (%store-prefix))
  88. (device "store")
  89. (type "9p")
  90. (needed-for-boot? #t)
  91. (flags '(read-only))
  92. (options "trans=virtio,cache=loose")
  93. (check? #f))
  94. ;; The 9p documentation says that cache=loose is "intended for
  95. ;; exclusive, read-only mounts", without additional details. In
  96. ;; practice it seems to work well for these, and it's much faster than
  97. ;; the default cache=none, especially when copying and registering
  98. ;; store items.
  99. (file-system
  100. (mount-point "/xchg")
  101. (device "xchg")
  102. (type "9p")
  103. (needed-for-boot? #t)
  104. (options "trans=virtio,cache=loose")
  105. (check? #f))
  106. (file-system
  107. (mount-point "/tmp")
  108. (device "tmp")
  109. (type "9p")
  110. (needed-for-boot? #t)
  111. (options "trans=virtio,cache=loose")
  112. (check? #f))))
  113. (define not-config?
  114. ;; Select (guix …) and (gnu …) modules, except (guix config).
  115. (match-lambda
  116. (('guix 'config) #f)
  117. (('guix rest ...) #t)
  118. (('gnu rest ...) #t)
  119. (rest #f)))
  120. (define gcrypt-sqlite3&co
  121. ;; Guile-Gcrypt, Guile-SQLite3, and their propagated inputs.
  122. (append-map (lambda (package)
  123. (cons package
  124. (match (package-transitive-propagated-inputs package)
  125. (((labels packages) ...)
  126. packages))))
  127. (list guile-gcrypt guile-sqlite3)))
  128. (define* (expression->derivation-in-linux-vm name exp
  129. #:key
  130. (system (%current-system))
  131. (linux linux-libre)
  132. initrd
  133. (qemu qemu-minimal)
  134. (env-vars '())
  135. (guile-for-build
  136. (%guile-for-build))
  137. (file-systems
  138. %linux-vm-file-systems)
  139. (single-file-output? #f)
  140. (make-disk-image? #f)
  141. (references-graphs #f)
  142. (memory-size 256)
  143. (disk-image-format "qcow2")
  144. (disk-image-size 'guess))
  145. "Evaluate EXP in a QEMU virtual machine running LINUX with INITRD (a
  146. derivation). The virtual machine runs with MEMORY-SIZE MiB of memory. In the
  147. virtual machine, EXP has access to FILE-SYSTEMS, which, by default, includes a
  148. 9p share of the store, the '/xchg' where EXP should put its output file(s),
  149. and a 9p share of /tmp.
  150. If SINGLE-FILE-OUTPUT? is true, copy a single file from '/xchg' to OUTPUT.
  151. Otherwise, copy the contents of /xchg to a new directory OUTPUT.
  152. When MAKE-DISK-IMAGE? is true, then create a QEMU disk image of type
  153. DISK-IMAGE-FORMAT (e.g., 'qcow2' or 'raw'), of DISK-IMAGE-SIZE bytes and
  154. return it. When DISK-IMAGE-SIZE is 'guess, estimate the image size based
  155. based on the size of the closure of REFERENCES-GRAPHS.
  156. When REFERENCES-GRAPHS is true, it must be a list of file name/store path
  157. pairs, as for `derivation'. The files containing the reference graphs are
  158. made available under the /xchg CIFS share."
  159. (define user-builder
  160. (program-file "builder-in-linux-vm" exp))
  161. (define loader
  162. ;; Invoke USER-BUILDER instead using 'primitive-load'. The reason for
  163. ;; this is to allow USER-BUILDER to dlopen stuff by using a full-featured
  164. ;; Guile, which it couldn't do using the statically-linked guile used in
  165. ;; the initrd. See example at
  166. ;; <https://lists.gnu.org/archive/html/guix-devel/2017-10/msg00233.html>.
  167. (program-file "linux-vm-loader"
  168. ;; When USER-BUILDER succeeds, reboot (indicating a
  169. ;; success), otherwise die, which causes a kernel panic
  170. ;; ("Attempted to kill init!").
  171. #~(when (zero? (system* #$user-builder))
  172. (reboot))))
  173. (let ((initrd (or initrd
  174. (base-initrd file-systems
  175. #:on-error 'backtrace
  176. #:linux linux
  177. #:linux-modules %base-initrd-modules
  178. #:qemu-networking? #t))))
  179. (define builder
  180. ;; Code that launches the VM that evaluates EXP.
  181. (with-extensions gcrypt-sqlite3&co
  182. (with-imported-modules `(,@(source-module-closure
  183. '((guix build utils)
  184. (gnu build vm))
  185. #:select? not-config?)
  186. ;; For consumption by (gnu store database).
  187. ((guix config) => ,(make-config.scm)))
  188. #~(begin
  189. (use-modules (guix build utils)
  190. (gnu build vm))
  191. (let* ((inputs '#$(list qemu (canonical-package coreutils)))
  192. (linux (string-append #$linux "/"
  193. #$(system-linux-image-file-name)))
  194. (initrd #$initrd)
  195. (loader #$loader)
  196. (graphs '#$(match references-graphs
  197. (((graph-files . _) ...) graph-files)
  198. (_ #f)))
  199. (size #$(if (eq? 'guess disk-image-size)
  200. #~(+ (* 70 (expt 2 20)) ;ESP
  201. (estimated-partition-size graphs))
  202. disk-image-size)))
  203. (set-path-environment-variable "PATH" '("bin") inputs)
  204. (load-in-linux-vm loader
  205. #:output #$output
  206. #:linux linux #:initrd initrd
  207. #:memory-size #$memory-size
  208. #:make-disk-image? #$make-disk-image?
  209. #:single-file-output? #$single-file-output?
  210. ;; FIXME: ‘target-arm32?’ may not operate on
  211. ;; the right system/target values. Rewrite
  212. ;; using ‘let-system’ when available.
  213. #:target-arm32? #$(target-arm32?)
  214. #:disk-image-format #$disk-image-format
  215. #:disk-image-size size
  216. #:references-graphs graphs))))))
  217. (gexp->derivation name builder
  218. ;; TODO: Require the "kvm" feature.
  219. #:system system
  220. #:env-vars env-vars
  221. #:guile-for-build guile-for-build
  222. #:references-graphs references-graphs)))
  223. (define* (iso9660-image #:key
  224. (name "iso9660-image")
  225. file-system-label
  226. file-system-uuid
  227. (system (%current-system))
  228. (qemu qemu-minimal)
  229. os
  230. bootcfg-drv
  231. bootloader
  232. register-closures?
  233. (inputs '()))
  234. "Return a bootable, stand-alone iso9660 image.
  235. INPUTS is a list of inputs (as for packages)."
  236. (define schema
  237. (and register-closures?
  238. (local-file (search-path %load-path
  239. "guix/store/schema.sql"))))
  240. (expression->derivation-in-linux-vm
  241. name
  242. (with-extensions gcrypt-sqlite3&co
  243. (with-imported-modules `(,@(source-module-closure '((gnu build vm)
  244. (guix store database)
  245. (guix build utils))
  246. #:select? not-config?)
  247. ((guix config) => ,(make-config.scm)))
  248. #~(begin
  249. (use-modules (gnu build vm)
  250. (guix store database)
  251. (guix build utils))
  252. (sql-schema #$schema)
  253. (let ((inputs
  254. '#$(append (list qemu parted e2fsprogs dosfstools xorriso)
  255. (map canonical-package
  256. (list sed grep coreutils findutils gawk))))
  257. (graphs '#$(match inputs
  258. (((names . _) ...)
  259. names)))
  260. ;; This variable is unused but allows us to add INPUTS-TO-COPY
  261. ;; as inputs.
  262. (to-register
  263. '#$(map (match-lambda
  264. ((name thing) thing)
  265. ((name thing output) `(,thing ,output)))
  266. inputs)))
  267. (set-path-environment-variable "PATH" '("bin" "sbin") inputs)
  268. (make-iso9660-image #$(bootloader-package bootloader)
  269. #$bootcfg-drv
  270. #$os
  271. "/xchg/guixsd.iso"
  272. #:register-closures? #$register-closures?
  273. #:closures graphs
  274. #:volume-id #$file-system-label
  275. #:volume-uuid #$(and=> file-system-uuid
  276. uuid-bytevector))))))
  277. #:system system
  278. ;; Keep a local file system for /tmp so that we can populate it directly as
  279. ;; root and have files owned by root. See <https://bugs.gnu.org/31752>.
  280. #:file-systems (remove (lambda (file-system)
  281. (string=? (file-system-mount-point file-system)
  282. "/tmp"))
  283. %linux-vm-file-systems)
  284. #:make-disk-image? #f
  285. #:single-file-output? #t
  286. #:references-graphs inputs))
  287. (define* (qemu-image #:key
  288. (name "qemu-image")
  289. (system (%current-system))
  290. (qemu qemu-minimal)
  291. (disk-image-size 'guess)
  292. (disk-image-format "qcow2")
  293. (file-system-type "ext4")
  294. file-system-label
  295. file-system-uuid
  296. os
  297. bootcfg-drv
  298. bootloader
  299. (register-closures? #t)
  300. (inputs '())
  301. copy-inputs?)
  302. "Return a bootable, stand-alone QEMU image of type DISK-IMAGE-FORMAT (e.g.,
  303. 'qcow2' or 'raw'), with a root partition of type FILE-SYSTEM-TYPE.
  304. Optionally, FILE-SYSTEM-LABEL can be specified as the volume name for the root
  305. partition; likewise FILE-SYSTEM-UUID, if true, specifies the UUID of the root
  306. partition (a UUID object).
  307. The returned image is a full disk image that runs OS-DERIVATION,
  308. with a GRUB installation that uses GRUB-CONFIGURATION as its configuration
  309. file (GRUB-CONFIGURATION must be the name of a file in the VM.)
  310. INPUTS is a list of inputs (as for packages). When COPY-INPUTS? is true, copy
  311. all of INPUTS into the image being built. When REGISTER-CLOSURES? is true,
  312. register INPUTS in the store database of the image so that Guix can be used in
  313. the image."
  314. (define schema
  315. (and register-closures?
  316. (local-file (search-path %load-path
  317. "guix/store/schema.sql"))))
  318. (expression->derivation-in-linux-vm
  319. name
  320. (with-extensions gcrypt-sqlite3&co
  321. (with-imported-modules `(,@(source-module-closure '((gnu build vm)
  322. (gnu build bootloader)
  323. (guix store database)
  324. (guix build utils))
  325. #:select? not-config?)
  326. ((guix config) => ,(make-config.scm)))
  327. #~(begin
  328. (use-modules (gnu build bootloader)
  329. (gnu build vm)
  330. (guix store database)
  331. (guix build utils)
  332. (srfi srfi-26)
  333. (ice-9 binary-ports))
  334. (sql-schema #$schema)
  335. (let ((inputs
  336. '#$(append (list qemu parted e2fsprogs dosfstools)
  337. (map canonical-package
  338. (list sed grep coreutils findutils gawk))))
  339. ;; This variable is unused but allows us to add INPUTS-TO-COPY
  340. ;; as inputs.
  341. (to-register
  342. '#$(map (match-lambda
  343. ((name thing) thing)
  344. ((name thing output) `(,thing ,output)))
  345. inputs)))
  346. (set-path-environment-variable "PATH" '("bin" "sbin") inputs)
  347. (let* ((graphs '#$(match inputs
  348. (((names . _) ...)
  349. names)))
  350. (initialize (root-partition-initializer
  351. #:closures graphs
  352. #:copy-closures? #$copy-inputs?
  353. #:register-closures? #$register-closures?
  354. #:system-directory #$os
  355. ;; Disable deduplication to speed things up,
  356. ;; and because it doesn't help much for a
  357. ;; single system generation.
  358. #:deduplicate? #f))
  359. (root-size #$(if (eq? 'guess disk-image-size)
  360. #~(max
  361. ;; Minimum 20 MiB root size
  362. (* 20 (expt 2 20))
  363. (estimated-partition-size
  364. (map (cut string-append "/xchg/" <>)
  365. graphs)))
  366. (- disk-image-size
  367. (* 50 (expt 2 20)))))
  368. (partitions
  369. (append
  370. (list (partition
  371. (size root-size)
  372. (label #$file-system-label)
  373. (uuid #$(and=> file-system-uuid
  374. uuid-bytevector))
  375. (file-system #$file-system-type)
  376. (flags '(boot))
  377. (initializer initialize)))
  378. ;; Append a small EFI System Partition for use with UEFI
  379. ;; bootloaders if we are not targeting ARM because UEFI
  380. ;; support in U-Boot is experimental.
  381. ;;
  382. ;; FIXME: ‘target-arm32?’ may be not operate on the right
  383. ;; system/target values. Rewrite using ‘let-system’ when
  384. ;; available.
  385. (if #$(target-arm32?)
  386. '()
  387. (list (partition
  388. ;; The standalone grub image is about 10MiB, but
  389. ;; leave some room for custom or multiple images.
  390. (size (* 40 (expt 2 20)))
  391. (label "GNU-ESP") ;cosmetic only
  392. ;; Use "vfat" here since this property is used
  393. ;; when mounting. The actual FAT-ness is based
  394. ;; on file system size (16 in this case).
  395. (file-system "vfat")
  396. (flags '(esp))))))))
  397. (initialize-hard-disk "/dev/vda"
  398. #:partitions partitions
  399. #:grub-efi #$grub-efi
  400. #:bootloader-package
  401. #$(bootloader-package bootloader)
  402. #:bootcfg #$bootcfg-drv
  403. #:bootcfg-location
  404. #$(bootloader-configuration-file bootloader)
  405. #:bootloader-installer
  406. #$(bootloader-installer bootloader)))))))
  407. #:system system
  408. #:make-disk-image? #t
  409. #:disk-image-size disk-image-size
  410. #:disk-image-format disk-image-format
  411. #:references-graphs inputs))
  412. (define* (system-docker-image os
  413. #:key
  414. (name "guixsd-docker-image")
  415. register-closures?)
  416. "Build a docker image. OS is the desired <operating-system>. NAME is the
  417. base name to use for the output file. When REGISTER-CLOSURES? is not #f,
  418. register the closure of OS with Guix in the resulting Docker image. This only
  419. makes sense when you want to build a GuixSD Docker image that has Guix
  420. installed inside of it. If you don't need Guix (e.g., your GuixSD Docker
  421. image just contains a web server that is started by the Shepherd), then you
  422. should set REGISTER-CLOSURES? to #f."
  423. (define schema
  424. (and register-closures?
  425. (local-file (search-path %load-path
  426. "guix/store/schema.sql"))))
  427. (mlet %store-monad ((os-drv (operating-system-derivation os #:container? #t))
  428. (name -> (string-append name ".tar.gz"))
  429. (graph -> "system-graph"))
  430. (define build
  431. (with-extensions (cons guile-json ;for (guix docker)
  432. gcrypt-sqlite3&co) ;for (guix store database)
  433. (with-imported-modules `(,@(source-module-closure
  434. '((guix docker)
  435. (guix store database)
  436. (guix build utils)
  437. (guix build store-copy)
  438. (gnu build vm))
  439. #:select? not-config?)
  440. ((guix config) => ,(make-config.scm)))
  441. #~(begin
  442. (use-modules (guix docker)
  443. (guix build utils)
  444. (gnu build vm)
  445. (srfi srfi-19)
  446. (guix build store-copy)
  447. (guix store database))
  448. ;; Set the SQL schema location.
  449. (sql-schema #$schema)
  450. (let* (;; This initializer requires elevated privileges that are
  451. ;; not normally available in the build environment (e.g.,
  452. ;; it needs to create device nodes). In order to obtain
  453. ;; such privileges, we run it as root in a VM.
  454. (initialize (root-partition-initializer
  455. #:closures '(#$graph)
  456. #:register-closures? #$register-closures?
  457. #:system-directory #$os-drv
  458. ;; De-duplication would fail due to
  459. ;; cross-device link errors, so don't do it.
  460. #:deduplicate? #f))
  461. ;; Even as root in a VM, the initializer would fail due to
  462. ;; lack of privileges if we use a root-directory that is on
  463. ;; a file system that is shared with the host (e.g., /tmp).
  464. (root-directory "/guixsd-system-root"))
  465. (set-path-environment-variable "PATH" '("bin" "sbin") '(#+tar))
  466. (mkdir root-directory)
  467. (initialize root-directory)
  468. (build-docker-image
  469. (string-append "/xchg/" #$name) ;; The output file.
  470. (cons* root-directory
  471. (map store-info-item
  472. (call-with-input-file
  473. (string-append "/xchg/" #$graph)
  474. read-reference-graph)))
  475. #$os-drv
  476. #:compressor '(#+(file-append gzip "/bin/gzip") "-9n")
  477. #:creation-time (make-time time-utc 0 1)
  478. #:transformations `((,root-directory -> ""))))))))
  479. (expression->derivation-in-linux-vm
  480. name build
  481. #:make-disk-image? #f
  482. #:single-file-output? #t
  483. #:references-graphs `((,graph ,os-drv)))))
  484. ;;;
  485. ;;; VM and disk images.
  486. ;;;
  487. (define* (operating-system-uuid os #:optional (type 'dce))
  488. "Compute UUID object with a deterministic \"UUID\" for OS, of the given
  489. TYPE (one of 'iso9660 or 'dce). Return a UUID object."
  490. ;; Note: For this to be deterministic, we must not hash things that contains
  491. ;; (directly or indirectly) procedures, for example. That rules out
  492. ;; anything that contains gexps, thunk or delayed record fields, etc.
  493. (define service-name
  494. (compose service-type-name service-kind))
  495. (define (file-system-digest fs)
  496. ;; Return a hashable digest that does not contain 'dependencies' since
  497. ;; this field can contain procedures.
  498. (let ((device (file-system-device fs)))
  499. (list (file-system-mount-point fs)
  500. (file-system-type fs)
  501. (cond ((file-system-label? device)
  502. (file-system-label->string device))
  503. ((uuid? device)
  504. (uuid->string device))
  505. ((string? device)
  506. device)
  507. (else #f))
  508. (file-system-options fs))))
  509. (if (eq? type 'iso9660)
  510. (let ((pad (compose (cut string-pad <> 2 #\0)
  511. number->string))
  512. (h (hash (map service-name (operating-system-services os))
  513. 3600)))
  514. (bytevector->uuid
  515. (string->iso9660-uuid
  516. (string-append "1970-01-01-"
  517. (pad (hash (operating-system-host-name os) 24)) "-"
  518. (pad (quotient h 60)) "-"
  519. (pad (modulo h 60)) "-"
  520. (pad (hash (map file-system-digest
  521. (operating-system-file-systems os))
  522. 100))))
  523. 'iso9660))
  524. (bytevector->uuid
  525. (uint-list->bytevector
  526. (list (hash file-system-type
  527. (- (expt 2 32) 1))
  528. (hash (operating-system-host-name os)
  529. (- (expt 2 32) 1))
  530. (hash (map service-name (operating-system-services os))
  531. (- (expt 2 32) 1))
  532. (hash (map file-system-digest (operating-system-file-systems os))
  533. (- (expt 2 32) 1)))
  534. (endianness little)
  535. 4)
  536. type)))
  537. (define* (system-disk-image os
  538. #:key
  539. (name "disk-image")
  540. (file-system-type "ext4")
  541. (disk-image-size (* 900 (expt 2 20)))
  542. (volatile? #t))
  543. "Return the derivation of a disk image of DISK-IMAGE-SIZE bytes of the
  544. system described by OS. Said image can be copied on a USB stick as is. When
  545. VOLATILE? is true, the root file system is made volatile; this is useful
  546. to USB sticks meant to be read-only."
  547. (define normalize-label
  548. ;; ISO labels are all-caps (case-insensitive), but since
  549. ;; 'find-partition-by-label' is case-sensitive, make it all-caps here.
  550. (if (string=? "iso9660" file-system-type)
  551. string-upcase
  552. identity))
  553. (define root-label
  554. ;; Volume name of the root file system.
  555. (normalize-label "GuixSD_image"))
  556. (define root-uuid
  557. ;; UUID of the root file system, computed in a deterministic fashion.
  558. ;; This is what we use to locate the root file system so it has to be
  559. ;; different from the user's own file system UUIDs.
  560. (operating-system-uuid os
  561. (if (string=? file-system-type "iso9660")
  562. 'iso9660
  563. 'dce)))
  564. (define file-systems-to-keep
  565. (remove (lambda (fs)
  566. (string=? (file-system-mount-point fs) "/"))
  567. (operating-system-file-systems os)))
  568. (let* ((os (operating-system (inherit os)
  569. ;; Since this is meant to be used on real hardware, don't
  570. ;; install QEMU networking or anything like that. Assume USB
  571. ;; mass storage devices (usb-storage.ko) are available.
  572. (initrd (lambda (file-systems . rest)
  573. (apply (operating-system-initrd os)
  574. file-systems
  575. #:volatile-root? #t
  576. rest)))
  577. (bootloader (if (string=? "iso9660" file-system-type)
  578. (bootloader-configuration
  579. (inherit (operating-system-bootloader os))
  580. (bootloader grub-mkrescue-bootloader))
  581. (operating-system-bootloader os)))
  582. ;; Force our own root file system.
  583. (file-systems (cons (file-system
  584. (mount-point "/")
  585. (device root-uuid)
  586. (type file-system-type))
  587. file-systems-to-keep))))
  588. (bootcfg (operating-system-bootcfg os)))
  589. (if (string=? "iso9660" file-system-type)
  590. (iso9660-image #:name name
  591. #:file-system-label root-label
  592. #:file-system-uuid root-uuid
  593. #:os os
  594. #:register-closures? #t
  595. #:bootcfg-drv bootcfg
  596. #:bootloader (bootloader-configuration-bootloader
  597. (operating-system-bootloader os))
  598. #:inputs `(("system" ,os)
  599. ("bootcfg" ,bootcfg)))
  600. (qemu-image #:name name
  601. #:os os
  602. #:bootcfg-drv bootcfg
  603. #:bootloader (bootloader-configuration-bootloader
  604. (operating-system-bootloader os))
  605. #:disk-image-size disk-image-size
  606. #:disk-image-format "raw"
  607. #:file-system-type file-system-type
  608. #:file-system-label root-label
  609. #:file-system-uuid root-uuid
  610. #:copy-inputs? #t
  611. #:register-closures? #t
  612. #:inputs `(("system" ,os)
  613. ("bootcfg" ,bootcfg))))))
  614. (define* (system-qemu-image os
  615. #:key
  616. (file-system-type "ext4")
  617. (disk-image-size (* 900 (expt 2 20))))
  618. "Return the derivation of a freestanding QEMU image of DISK-IMAGE-SIZE bytes
  619. of the GNU system as described by OS."
  620. (define file-systems-to-keep
  621. ;; Keep only file systems other than root and not normally bound to real
  622. ;; devices.
  623. (remove (lambda (fs)
  624. (let ((target (file-system-mount-point fs))
  625. (source (file-system-device fs)))
  626. (or (string=? target "/")
  627. (string-prefix? "/dev/" source))))
  628. (operating-system-file-systems os)))
  629. (define root-uuid
  630. ;; UUID of the root file system.
  631. (operating-system-uuid os
  632. (if (string=? file-system-type "iso9660")
  633. 'iso9660
  634. 'dce)))
  635. (let* ((os (operating-system (inherit os)
  636. ;; Assume we have an initrd with the whole QEMU shebang.
  637. ;; Force our own root file system. Refer to it by UUID so that
  638. ;; it works regardless of how the image is used ("qemu -hda",
  639. ;; Xen, etc.).
  640. (file-systems (cons (file-system
  641. (mount-point "/")
  642. (device root-uuid)
  643. (type file-system-type))
  644. file-systems-to-keep))))
  645. (bootcfg (operating-system-bootcfg os)))
  646. (qemu-image #:os os
  647. #:bootcfg-drv bootcfg
  648. #:bootloader (bootloader-configuration-bootloader
  649. (operating-system-bootloader os))
  650. #:disk-image-size disk-image-size
  651. #:file-system-type file-system-type
  652. #:file-system-uuid root-uuid
  653. #:inputs `(("system" ,os)
  654. ("bootcfg" ,bootcfg))
  655. #:copy-inputs? #t)))
  656. ;;;
  657. ;;; VMs that share file systems with the host.
  658. ;;;
  659. (define (file-system->mount-tag fs)
  660. "Return a 9p mount tag for host file system FS."
  661. ;; QEMU mount tags must be ASCII, at most 31-byte long, cannot contain
  662. ;; slashes, and cannot start with '_'. Compute an identifier that
  663. ;; corresponds to the rules.
  664. (string-append "TAG"
  665. (string-drop (bytevector->base32-string
  666. (sha1 (string->utf8 fs)))
  667. 4)))
  668. (define (mapping->file-system mapping)
  669. "Return a 9p file system that realizes MAPPING."
  670. (match mapping
  671. (($ <file-system-mapping> source target writable?)
  672. (file-system
  673. (mount-point target)
  674. (device (file-system->mount-tag source))
  675. (type "9p")
  676. (flags (if writable? '() '(read-only)))
  677. (options "trans=virtio,cache=loose")
  678. (check? #f)
  679. (create-mount-point? #t)))))
  680. (define* (virtualized-operating-system os mappings #:optional (full-boot? #f))
  681. "Return an operating system based on OS suitable for use in a virtualized
  682. environment with the store shared with the host. MAPPINGS is a list of
  683. <file-system-mapping> to realize in the virtualized OS."
  684. (define user-file-systems
  685. ;; Remove file systems that conflict with those added below, or that are
  686. ;; normally bound to real devices.
  687. (remove (lambda (fs)
  688. (let ((target (file-system-mount-point fs))
  689. (source (file-system-device fs)))
  690. (or (string=? target (%store-prefix))
  691. (string=? target "/")
  692. (and (string? source)
  693. (string-prefix? "/dev/" source))
  694. ;; Labels and UUIDs are necessarily invalid in the VM.
  695. (and (file-system-mount? fs)
  696. (or (file-system-label? source)
  697. (uuid? source))))))
  698. (operating-system-file-systems os)))
  699. (define virtual-file-systems
  700. (cons (file-system
  701. (mount-point "/")
  702. (device "/dev/vda1")
  703. (type "ext4"))
  704. (append (map mapping->file-system mappings)
  705. user-file-systems)))
  706. (operating-system (inherit os)
  707. ;; XXX: Until we run QEMU with UEFI support (with the OVMF firmware),
  708. ;; force the traditional i386/BIOS method.
  709. ;; See <https://bugs.gnu.org/28768>.
  710. (bootloader (bootloader-configuration
  711. (bootloader grub-bootloader)
  712. (target "/dev/vda")))
  713. (initrd (lambda (file-systems . rest)
  714. (apply (operating-system-initrd os)
  715. file-systems
  716. #:volatile-root? #t
  717. rest)))
  718. ;; Disable swap.
  719. (swap-devices '())
  720. ;; XXX: When FULL-BOOT? is true, do not add a 9p mount for /gnu/store
  721. ;; since that would lead the bootloader config to look for the kernel and
  722. ;; initrd in it.
  723. (file-systems (if full-boot?
  724. virtual-file-systems
  725. (cons
  726. (file-system
  727. (inherit (mapping->file-system %store-mapping))
  728. (needed-for-boot? #t))
  729. virtual-file-systems)))))
  730. (define* (system-qemu-image/shared-store
  731. os
  732. #:key
  733. full-boot?
  734. (disk-image-size (* (if full-boot? 500 30) (expt 2 20))))
  735. "Return a derivation that builds a QEMU image of OS that shares its store
  736. with the host.
  737. When FULL-BOOT? is true, return an image that does a complete boot sequence,
  738. bootloaded included; thus, make a disk image that contains everything the
  739. bootloader refers to: OS kernel, initrd, bootloader data, etc."
  740. (define root-uuid
  741. ;; Use a fixed UUID to improve determinism.
  742. (operating-system-uuid os 'dce))
  743. (define bootcfg
  744. (operating-system-bootcfg os))
  745. ;; XXX: When FULL-BOOT? is true, we end up creating an image that contains
  746. ;; BOOTCFG and all its dependencies, including the output of OS.
  747. ;; This is more than needed (we only need the kernel, initrd, GRUB for its
  748. ;; font, and the background image), but it's hard to filter that.
  749. (qemu-image #:os os
  750. #:bootcfg-drv bootcfg
  751. #:bootloader (bootloader-configuration-bootloader
  752. (operating-system-bootloader os))
  753. #:disk-image-size disk-image-size
  754. #:file-system-uuid root-uuid
  755. #:inputs (if full-boot?
  756. `(("bootcfg" ,bootcfg))
  757. '())
  758. ;; XXX: Passing #t here is too slow, so let it off by default.
  759. #:register-closures? #f
  760. #:copy-inputs? full-boot?))
  761. (define* (common-qemu-options image shared-fs)
  762. "Return the a string-value gexp with the common QEMU options to boot IMAGE,
  763. with '-virtfs' options for the host file systems listed in SHARED-FS."
  764. (define (virtfs-option fs)
  765. #~(format #f "-virtfs local,path=~s,security_model=none,mount_tag=~s"
  766. #$fs #$(file-system->mount-tag fs)))
  767. #~(;; Only enable kvm if we see /dev/kvm exists.
  768. ;; This allows users without hardware virtualization to still use these
  769. ;; commands.
  770. #$@(if (file-exists? "/dev/kvm")
  771. '("-enable-kvm")
  772. '())
  773. "-no-reboot"
  774. "-net nic,model=virtio"
  775. "-object" "rng-random,filename=/dev/urandom,id=guixsd-vm-rng"
  776. "-device" "virtio-rng-pci,rng=guixsd-vm-rng"
  777. #$@(map virtfs-option shared-fs)
  778. "-vga std"
  779. (format #f "-drive file=~a,if=virtio,cache=writeback,werror=report,readonly"
  780. #$image)))
  781. (define* (system-qemu-image/shared-store-script os
  782. #:key
  783. (qemu qemu)
  784. (graphic? #t)
  785. (memory-size 256)
  786. (mappings '())
  787. full-boot?
  788. (disk-image-size
  789. (* (if full-boot? 500 70)
  790. (expt 2 20)))
  791. (options '()))
  792. "Return a derivation that builds a script to run a virtual machine image of
  793. OS that shares its store with the host. The virtual machine runs with
  794. MEMORY-SIZE MiB of memory.
  795. MAPPINGS is a list of <file-system-mapping> specifying mapping of host file
  796. systems into the guest.
  797. When FULL-BOOT? is true, the returned script runs everything starting from the
  798. bootloader; otherwise it directly starts the operating system kernel. The
  799. DISK-IMAGE-SIZE parameter specifies the size in bytes of the root disk image;
  800. it is mostly useful when FULL-BOOT? is true."
  801. (mlet* %store-monad ((os -> (virtualized-operating-system os mappings full-boot?))
  802. (image (system-qemu-image/shared-store
  803. os
  804. #:full-boot? full-boot?
  805. #:disk-image-size disk-image-size)))
  806. (define kernel-arguments
  807. #~(list #$@(if graphic? #~() #~("console=ttyS0"))
  808. #+@(operating-system-kernel-arguments os "/dev/vda1")))
  809. (define qemu-exec
  810. #~(list (string-append #$qemu "/bin/" #$(qemu-command (%current-system)))
  811. #$@(if full-boot?
  812. #~()
  813. #~("-kernel" #$(operating-system-kernel-file os)
  814. "-initrd" #$(file-append os "/initrd")
  815. (format #f "-append ~s"
  816. (string-join #$kernel-arguments " "))))
  817. #$@(common-qemu-options image
  818. (map file-system-mapping-source
  819. (cons %store-mapping mappings)))
  820. "-m " (number->string #$memory-size)
  821. #$@options))
  822. (define builder
  823. #~(call-with-output-file #$output
  824. (lambda (port)
  825. (format port "#!~a~% exec ~a \"$@\"~%"
  826. #$(file-append bash "/bin/sh")
  827. (string-join #$qemu-exec " "))
  828. (chmod port #o555))))
  829. (gexp->derivation "run-vm.sh" builder)))
  830. ;;;
  831. ;;; High-level abstraction.
  832. ;;;
  833. (define-record-type* <virtual-machine> %virtual-machine
  834. make-virtual-machine
  835. virtual-machine?
  836. (operating-system virtual-machine-operating-system) ;<operating-system>
  837. (qemu virtual-machine-qemu ;<package>
  838. (default qemu))
  839. (graphic? virtual-machine-graphic? ;Boolean
  840. (default #f))
  841. (memory-size virtual-machine-memory-size ;integer (MiB)
  842. (default 256))
  843. (disk-image-size virtual-machine-disk-image-size ;integer (bytes)
  844. (default 'guess))
  845. (port-forwardings virtual-machine-port-forwardings ;list of integer pairs
  846. (default '())))
  847. (define-syntax virtual-machine
  848. (syntax-rules ()
  849. "Declare a virtual machine running the specified OS, with the given
  850. options."
  851. ((_ os) ;shortcut
  852. (%virtual-machine (operating-system os)))
  853. ((_ fields ...)
  854. (%virtual-machine fields ...))))
  855. (define (port-forwardings->qemu-options forwardings)
  856. "Return the QEMU option for the given port FORWARDINGS as a string, where
  857. FORWARDINGS is a list of host-port/guest-port pairs."
  858. (string-join
  859. (map (match-lambda
  860. ((host-port . guest-port)
  861. (string-append "hostfwd=tcp::"
  862. (number->string host-port)
  863. "-:" (number->string guest-port))))
  864. forwardings)
  865. ","))
  866. (define-gexp-compiler (virtual-machine-compiler (vm <virtual-machine>)
  867. system target)
  868. ;; XXX: SYSTEM and TARGET are ignored.
  869. (match vm
  870. (($ <virtual-machine> os qemu graphic? memory-size disk-image-size ())
  871. (system-qemu-image/shared-store-script os
  872. #:qemu qemu
  873. #:graphic? graphic?
  874. #:memory-size memory-size
  875. #:disk-image-size
  876. disk-image-size))
  877. (($ <virtual-machine> os qemu graphic? memory-size disk-image-size
  878. forwardings)
  879. (let ((options
  880. `("-net" ,(string-append
  881. "user,"
  882. (port-forwardings->qemu-options forwardings)))))
  883. (system-qemu-image/shared-store-script os
  884. #:qemu qemu
  885. #:graphic? graphic?
  886. #:memory-size memory-size
  887. #:disk-image-size
  888. disk-image-size
  889. #:options options)))))
  890. ;;; vm.scm ends here