vm.scm 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  1. ;;; GNU Guix --- Functional package management for GNU
  2. ;;; Copyright © 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021 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 admin)
  52. #:use-module (gnu bootloader)
  53. #:use-module (gnu bootloader grub)
  54. #:use-module (gnu system shadow)
  55. #:use-module (gnu system pam)
  56. #:use-module (gnu system linux-container)
  57. #:use-module (gnu system linux-initrd)
  58. #:use-module (gnu bootloader)
  59. #:use-module (gnu system file-systems)
  60. #:use-module (gnu system)
  61. #:use-module (gnu services)
  62. #:use-module (gnu services base)
  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/shared-store
  72. system-qemu-image/shared-store-script
  73. system-docker-image
  74. virtual-machine
  75. virtual-machine?))
  76. ;;; Commentary:
  77. ;;;
  78. ;;; Tools to evaluate build expressions within virtual machines.
  79. ;;;
  80. ;;; Code:
  81. (define %linux-vm-file-systems
  82. ;; File systems mounted for 'derivation-in-linux-vm'. These are shared with
  83. ;; the host over 9p.
  84. ;;
  85. ;; The 9p documentation says that cache=loose is "intended for exclusive,
  86. ;; read-only mounts", without additional details. It's much faster than the
  87. ;; default cache=none, especially when copying and registering store items.
  88. ;; Thus, use cache=loose, except for /xchg where we want to ensure
  89. ;; consistency.
  90. (list (file-system
  91. (mount-point (%store-prefix))
  92. (device "store")
  93. (type "9p")
  94. (needed-for-boot? #t)
  95. (flags '(read-only))
  96. (options "trans=virtio,cache=loose")
  97. (check? #f))
  98. (file-system
  99. (mount-point "/xchg")
  100. (device "xchg")
  101. (type "9p")
  102. (needed-for-boot? #t)
  103. (options "trans=virtio")
  104. (check? #f))
  105. (file-system
  106. (mount-point "/tmp")
  107. (device "tmp")
  108. (type "9p")
  109. (needed-for-boot? #t)
  110. (options "trans=virtio,cache=loose")
  111. (check? #f))))
  112. (define not-config?
  113. ;; Select (guix …) and (gnu …) modules, except (guix config).
  114. (match-lambda
  115. (('guix 'config) #f)
  116. (('guix rest ...) #t)
  117. (('gnu rest ...) #t)
  118. (rest #f)))
  119. (define gcrypt-sqlite3&co
  120. ;; Guile-Gcrypt, Guile-SQLite3, and their propagated inputs.
  121. (append-map (lambda (package)
  122. (cons package
  123. (match (package-transitive-propagated-inputs package)
  124. (((labels packages) ...)
  125. packages))))
  126. (list guile-gcrypt guile-sqlite3)))
  127. (define* (expression->derivation-in-linux-vm name exp
  128. #:key
  129. (system (%current-system))
  130. (linux linux-libre)
  131. initrd
  132. (qemu qemu-minimal)
  133. (env-vars '())
  134. (guile-for-build
  135. (%guile-for-build))
  136. (file-systems
  137. %linux-vm-file-systems)
  138. (single-file-output? #f)
  139. (make-disk-image? #f)
  140. (references-graphs #f)
  141. (memory-size 256)
  142. (disk-image-format "qcow2")
  143. (disk-image-size 'guess)
  144. (substitutable? #t))
  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. SUBSTITUTABLE? determines whether the returned derivation should be marked as
  160. substitutable."
  161. (define user-builder
  162. (program-file "builder-in-linux-vm" exp))
  163. (define loader
  164. ;; Invoke USER-BUILDER instead using 'primitive-load'. The reason for
  165. ;; this is to allow USER-BUILDER to dlopen stuff by using a full-featured
  166. ;; Guile, which it couldn't do using the statically-linked guile used in
  167. ;; the initrd. See example at
  168. ;; <https://lists.gnu.org/archive/html/guix-devel/2017-10/msg00233.html>.
  169. (program-file "linux-vm-loader"
  170. ;; Communicate USER-BUILDER's exit status via /xchg so that
  171. ;; the host can distinguish between success, failure, and
  172. ;; kernel panic.
  173. #~(let ((status (system* #$user-builder)))
  174. (call-with-output-file "/xchg/.exit-status"
  175. (lambda (port)
  176. (write status port)))
  177. (sync)
  178. (reboot))))
  179. (define-syntax-rule (check predicate)
  180. (let-system (system target)
  181. (predicate (or target system))))
  182. (let ((initrd (or initrd
  183. (base-initrd file-systems
  184. #:on-error 'backtrace
  185. #:linux linux
  186. #:linux-modules %base-initrd-modules
  187. #:qemu-networking? #t))))
  188. (define builder
  189. ;; Code that launches the VM that evaluates EXP.
  190. (with-extensions gcrypt-sqlite3&co
  191. (with-imported-modules `(,@(source-module-closure
  192. '((guix build utils)
  193. (gnu build vm))
  194. #:select? not-config?)
  195. ;; For consumption by (gnu store database).
  196. ((guix config) => ,(make-config.scm)))
  197. #~(begin
  198. (use-modules (guix build utils)
  199. (gnu build vm))
  200. ;; Allow non-ASCII file names--e.g., 'nss-certs'--to be decoded
  201. ;; by 'estimated-partition-size' below.
  202. (setenv "GUIX_LOCPATH"
  203. #+(file-append glibc-utf8-locales "/lib/locale"))
  204. (setlocale LC_ALL "en_US.utf8")
  205. (let* ((native-inputs
  206. '#+(list qemu (canonical-package coreutils)))
  207. (linux (string-append
  208. #+linux "/"
  209. #+(system-linux-image-file-name system)))
  210. (initrd #+initrd)
  211. (loader #+loader)
  212. (graphs '#$(match references-graphs
  213. (((graph-files . _) ...) graph-files)
  214. (_ #f)))
  215. (target #$(let-system (system target)
  216. (or target system)))
  217. (size #$(if (eq? 'guess disk-image-size)
  218. #~(+ (* 70 (expt 2 20)) ;ESP
  219. (estimated-partition-size graphs))
  220. disk-image-size)))
  221. (set-path-environment-variable "PATH" '("bin") native-inputs)
  222. (load-in-linux-vm loader
  223. #:output #$output
  224. #:linux linux #:initrd initrd
  225. #:qemu (qemu-command target)
  226. #:memory-size #$memory-size
  227. #:make-disk-image? #$make-disk-image?
  228. #:single-file-output? #$single-file-output?
  229. #:disk-image-format #$disk-image-format
  230. #:disk-image-size size
  231. #:references-graphs graphs))))))
  232. (gexp->derivation name builder
  233. ;; TODO: Require the "kvm" feature.
  234. #:system system
  235. #:target #f ;EXP is always executed natively
  236. #:env-vars env-vars
  237. #:guile-for-build guile-for-build
  238. #:references-graphs references-graphs
  239. #:substitutable? substitutable?)))
  240. (define (has-guix-service-type? os)
  241. "Return true if OS contains a service of the type GUIX-SERVICE-TYPE."
  242. (not (not (find (lambda (service)
  243. (eq? (service-kind service) guix-service-type))
  244. (operating-system-services os)))))
  245. (define* (qemu-image #:key
  246. (name "qemu-image")
  247. (system (%current-system))
  248. (target (%current-target-system))
  249. (qemu qemu-minimal)
  250. (disk-image-size 'guess)
  251. (disk-image-format "qcow2")
  252. (file-system-type "ext4")
  253. (file-system-options '())
  254. (device-nodes 'linux)
  255. (extra-directives '())
  256. file-system-label
  257. file-system-uuid
  258. os
  259. bootcfg-drv
  260. bootloader
  261. (register-closures? (has-guix-service-type? os))
  262. (inputs '())
  263. copy-inputs?
  264. (substitutable? #t))
  265. "Return a bootable, stand-alone QEMU image of type DISK-IMAGE-FORMAT (e.g.,
  266. 'qcow2' or 'raw'), with a root partition of type FILE-SYSTEM-TYPE.
  267. Optionally, FILE-SYSTEM-LABEL can be specified as the volume name for the root
  268. partition; likewise FILE-SYSTEM-UUID, if true, specifies the UUID of the root
  269. partition (a UUID object). FILE-SYSTEM-OPTIONS is an optional list of
  270. command-line options passed to 'mkfs.ext4' (or similar).
  271. The returned image is a full disk image that runs OS-DERIVATION,
  272. with a GRUB installation that uses GRUB-CONFIGURATION as its configuration
  273. file (GRUB-CONFIGURATION must be the name of a file in the VM.)
  274. INPUTS is a list of inputs (as for packages). When COPY-INPUTS? is true, copy
  275. all of INPUTS into the image being built. When REGISTER-CLOSURES? is true,
  276. register INPUTS in the store database of the image so that Guix can be used in
  277. the image. By default, REGISTER-CLOSURES? is set to true only if a service of
  278. type GUIX-SERVICE-TYPE is present in the services definition of the operating
  279. system.
  280. When DEVICE-NODES is 'linux, create Linux-device block and character devices
  281. under /dev. When it is 'hurd, do Hurdish things.
  282. EXTRA-DIRECTIVES is an optional list of directives to populate the root file
  283. system that is passed to 'populate-root-file-system'."
  284. (define schema
  285. (and register-closures?
  286. (local-file (search-path %load-path
  287. "guix/store/schema.sql"))))
  288. (define preserve-target
  289. (if target
  290. (lambda (obj)
  291. (with-parameters ((%current-target-system target))
  292. obj))
  293. identity))
  294. (define inputs*
  295. (map (match-lambda
  296. ((name thing)
  297. `(,name ,(preserve-target thing)))
  298. ((name thing output)
  299. `(,name ,(preserve-target thing) ,output)))
  300. inputs))
  301. (expression->derivation-in-linux-vm
  302. name
  303. (with-extensions gcrypt-sqlite3&co
  304. (with-imported-modules `(,@(source-module-closure '((gnu build vm)
  305. (gnu build bootloader)
  306. (gnu build hurd-boot)
  307. (guix store database)
  308. (guix build utils))
  309. #:select? not-config?)
  310. ((guix config) => ,(make-config.scm)))
  311. #~(begin
  312. (use-modules (gnu build bootloader)
  313. (gnu build vm)
  314. ((gnu build hurd-boot)
  315. #:select (make-hurd-device-nodes))
  316. ((gnu build linux-boot)
  317. #:select (make-essential-device-nodes))
  318. (guix store database)
  319. (guix build utils)
  320. (srfi srfi-26)
  321. (ice-9 binary-ports))
  322. (sql-schema #$schema)
  323. ;; Allow non-ASCII file names--e.g., 'nss-certs'--to be decoded.
  324. (setenv "GUIX_LOCPATH"
  325. #+(file-append glibc-utf8-locales "/lib/locale"))
  326. (setlocale LC_ALL "en_US.utf8")
  327. (let ((inputs
  328. '#+(append (list parted e2fsprogs dosfstools)
  329. (map canonical-package
  330. (list sed grep coreutils findutils gawk))))
  331. ;; This variable is unused but allows us to add INPUTS-TO-COPY
  332. ;; as inputs.
  333. (to-register
  334. '#$(map (match-lambda
  335. ((name thing) thing)
  336. ((name thing output) `(,thing ,output)))
  337. inputs*)))
  338. (set-path-environment-variable "PATH" '("bin" "sbin") inputs)
  339. (let* ((graphs '#$(match inputs
  340. (((names . _) ...)
  341. names)))
  342. (initialize (root-partition-initializer
  343. #:extra-directives '#$extra-directives
  344. #:closures graphs
  345. #:copy-closures? #$copy-inputs?
  346. #:register-closures? #$register-closures?
  347. #:system-directory #$(preserve-target os)
  348. #:make-device-nodes
  349. #$(match device-nodes
  350. ('linux #~make-essential-device-nodes)
  351. ('hurd #~make-hurd-device-nodes))
  352. ;; Disable deduplication to speed things up,
  353. ;; and because it doesn't help much for a
  354. ;; single system generation.
  355. #:deduplicate? #f))
  356. (root-size #$(if (eq? 'guess disk-image-size)
  357. #~(max
  358. ;; Minimum 20 MiB root size
  359. (* 20 (expt 2 20))
  360. (estimated-partition-size
  361. (map (cut string-append "/xchg/" <>)
  362. graphs)))
  363. (- disk-image-size
  364. (* 50 (expt 2 20)))))
  365. (partitions
  366. (append
  367. (list (partition
  368. (size root-size)
  369. (label #$file-system-label)
  370. (uuid #$(and=> file-system-uuid
  371. uuid-bytevector))
  372. (file-system #$file-system-type)
  373. (file-system-options '#$file-system-options)
  374. (flags '(boot))
  375. (initializer initialize)))
  376. ;; Append a small EFI System Partition for use with UEFI
  377. ;; bootloaders if we are not targeting ARM because UEFI
  378. ;; support in U-Boot is experimental.
  379. ;;
  380. ;; FIXME: ‘target-arm?’ may be not operate on the right
  381. ;; system/target values. Rewrite using ‘let-system’ when
  382. ;; available.
  383. (if #$(target-arm?)
  384. '()
  385. (list (partition
  386. ;; The standalone grub image is about 10MiB, but
  387. ;; leave some room for custom or multiple images.
  388. (size (* 40 (expt 2 20)))
  389. (label "GNU-ESP") ;cosmetic only
  390. ;; Use "vfat" here since this property is used
  391. ;; when mounting. The actual FAT-ness is based
  392. ;; on file system size (16 in this case).
  393. (file-system "vfat")
  394. (flags '(esp)))))))
  395. (grub-efi #$(and (not (target-arm?)) grub-efi)))
  396. (initialize-hard-disk "/dev/vda"
  397. #:partitions partitions
  398. #:grub-efi grub-efi
  399. #:bootloader-package
  400. #+(bootloader-package bootloader)
  401. #:bootcfg #$(preserve-target bootcfg-drv)
  402. #:bootcfg-location
  403. #$(bootloader-configuration-file bootloader)
  404. #:bootloader-installer
  405. #+(bootloader-installer bootloader)))))))
  406. #:system system
  407. #:make-disk-image? #t
  408. #:disk-image-size disk-image-size
  409. #:disk-image-format disk-image-format
  410. #:references-graphs inputs*
  411. #:substitutable? substitutable?))
  412. (define* (system-docker-image os
  413. #:key
  414. (name "guix-docker-image")
  415. (register-closures? (has-guix-service-type? os))
  416. shared-network?)
  417. "Build a docker image. OS is the desired <operating-system>. NAME is the
  418. base name to use for the output file. When SHARED-NETWORK? is true, assume
  419. that the container will share network with the host and thus doesn't need a
  420. DHCP client, nscd, and so on.
  421. When REGISTER-CLOSURES? is true, register the closure of OS with Guix in the
  422. resulting Docker image. By default, REGISTER-CLOSURES? is set to true only if
  423. a service of type GUIX-SERVICE-TYPE is present in the services definition of
  424. the operating system."
  425. (define schema
  426. (and register-closures?
  427. (local-file (search-path %load-path
  428. "guix/store/schema.sql"))))
  429. (define boot-program
  430. ;; Program that runs the boot script of OS, which in turn starts shepherd.
  431. (program-file "boot-program"
  432. #~(let ((system (cadr (command-line))))
  433. (setenv "GUIX_NEW_SYSTEM" system)
  434. (execl #$(file-append guile-3.0 "/bin/guile")
  435. "guile" "--no-auto-compile"
  436. (string-append system "/boot")))))
  437. (let ((os (operating-system-with-gc-roots
  438. (containerized-operating-system os '()
  439. #:shared-network?
  440. shared-network?)
  441. (list boot-program)))
  442. (name (string-append name ".tar.gz"))
  443. (graph "system-graph"))
  444. (define build
  445. (with-extensions (cons guile-json-3 ;for (guix docker)
  446. gcrypt-sqlite3&co) ;for (guix store database)
  447. (with-imported-modules `(,@(source-module-closure
  448. '((guix docker)
  449. (guix store database)
  450. (guix build utils)
  451. (guix build store-copy)
  452. (gnu build vm))
  453. #:select? not-config?)
  454. ((guix config) => ,(make-config.scm)))
  455. #~(begin
  456. (use-modules (guix docker)
  457. (guix build utils)
  458. (gnu build vm)
  459. (srfi srfi-19)
  460. (guix build store-copy)
  461. (guix store database))
  462. ;; Set the SQL schema location.
  463. (sql-schema #$schema)
  464. ;; Allow non-ASCII file names--e.g., 'nss-certs'--to be decoded.
  465. (setenv "GUIX_LOCPATH"
  466. #+(file-append glibc-utf8-locales "/lib/locale"))
  467. (setlocale LC_ALL "en_US.utf8")
  468. (let* (;; This initializer requires elevated privileges that are
  469. ;; not normally available in the build environment (e.g.,
  470. ;; it needs to create device nodes). In order to obtain
  471. ;; such privileges, we run it as root in a VM.
  472. (initialize (root-partition-initializer
  473. #:closures '(#$graph)
  474. #:register-closures? #$register-closures?
  475. #:system-directory #$os
  476. ;; De-duplication would fail due to
  477. ;; cross-device link errors, so don't do it.
  478. #:deduplicate? #f))
  479. ;; Even as root in a VM, the initializer would fail due to
  480. ;; lack of privileges if we use a root-directory that is on
  481. ;; a file system that is shared with the host (e.g., /tmp).
  482. (root-directory "/guixsd-system-root"))
  483. (set-path-environment-variable "PATH" '("bin" "sbin") '(#+tar))
  484. (mkdir root-directory)
  485. (initialize root-directory)
  486. (build-docker-image
  487. (string-append "/xchg/" #$name) ;; The output file.
  488. (cons* root-directory
  489. (map store-info-item
  490. (call-with-input-file
  491. (string-append "/xchg/" #$graph)
  492. read-reference-graph)))
  493. #$os
  494. #:entry-point '(#$boot-program #$os)
  495. #:compressor '(#+(file-append gzip "/bin/gzip") "-9n")
  496. #:creation-time (make-time time-utc 0 1)
  497. #:transformations `((,root-directory -> ""))))))))
  498. (expression->derivation-in-linux-vm
  499. name build
  500. #:make-disk-image? #f
  501. #:single-file-output? #t
  502. #:references-graphs `((,graph ,os)))))
  503. ;;;
  504. ;;; VMs that share file systems with the host.
  505. ;;;
  506. (define (file-system->mount-tag fs)
  507. "Return a 9p mount tag for host file system FS."
  508. ;; QEMU mount tags must be ASCII, at most 31-byte long, cannot contain
  509. ;; slashes, and cannot start with '_'. Compute an identifier that
  510. ;; corresponds to the rules.
  511. (string-append "TAG"
  512. (string-drop (bytevector->base32-string
  513. (sha1 (string->utf8 fs)))
  514. 4)))
  515. (define (mapping->file-system mapping)
  516. "Return a 9p file system that realizes MAPPING."
  517. (match mapping
  518. (($ <file-system-mapping> source target writable?)
  519. (file-system
  520. (mount-point target)
  521. (device (file-system->mount-tag source))
  522. (type "9p")
  523. (flags (if writable? '() '(read-only)))
  524. (options (string-append "trans=virtio"
  525. (if writable? "" ",cache=loose")))
  526. (check? #f)
  527. (create-mount-point? #t)))))
  528. (define* (virtualized-operating-system os mappings #:optional (full-boot? #f))
  529. "Return an operating system based on OS suitable for use in a virtualized
  530. environment with the store shared with the host. MAPPINGS is a list of
  531. <file-system-mapping> to realize in the virtualized OS."
  532. (define user-file-systems
  533. ;; Remove file systems that conflict with those added below, or that are
  534. ;; normally bound to real devices.
  535. (remove (lambda (fs)
  536. (let ((target (file-system-mount-point fs))
  537. (source (file-system-device fs)))
  538. (or (string=? target (%store-prefix))
  539. (string=? target "/")
  540. (and (string? source)
  541. (string-prefix? "/dev/" source))
  542. ;; Labels and UUIDs are necessarily invalid in the VM.
  543. (and (file-system-mount? fs)
  544. (or (file-system-label? source)
  545. (uuid? source))))))
  546. (operating-system-file-systems os)))
  547. (define virtual-file-systems
  548. (cons (file-system
  549. (mount-point "/")
  550. (device "/dev/vda1")
  551. (type "ext4"))
  552. (append (map mapping->file-system mappings)
  553. user-file-systems)))
  554. (operating-system (inherit os)
  555. ;; XXX: Until we run QEMU with UEFI support (with the OVMF firmware),
  556. ;; force the traditional i386/BIOS method.
  557. ;; See <https://bugs.gnu.org/28768>.
  558. (bootloader (bootloader-configuration
  559. (inherit (operating-system-bootloader os))
  560. (bootloader grub-bootloader)
  561. (target "/dev/vda")))
  562. (initrd (lambda (file-systems . rest)
  563. (apply (operating-system-initrd os)
  564. file-systems
  565. #:volatile-root? #t
  566. rest)))
  567. ;; Disable swap.
  568. (swap-devices '())
  569. ;; XXX: When FULL-BOOT? is true, do not add a 9p mount for /gnu/store
  570. ;; since that would lead the bootloader config to look for the kernel and
  571. ;; initrd in it.
  572. (file-systems (if full-boot?
  573. virtual-file-systems
  574. (cons
  575. (file-system
  576. (inherit (mapping->file-system %store-mapping))
  577. (needed-for-boot? #t))
  578. virtual-file-systems)))))
  579. (define* (system-qemu-image/shared-store
  580. os
  581. #:key
  582. (system (%current-system))
  583. (target (%current-target-system))
  584. full-boot?
  585. (disk-image-size (* (if full-boot? 500 30) (expt 2 20))))
  586. "Return a derivation that builds a QEMU image of OS that shares its store
  587. with the host.
  588. When FULL-BOOT? is true, return an image that does a complete boot sequence,
  589. bootloaded included; thus, make a disk image that contains everything the
  590. bootloader refers to: OS kernel, initrd, bootloader data, etc."
  591. (define root-uuid
  592. ;; Use a fixed UUID to improve determinism.
  593. (operating-system-uuid os 'dce))
  594. (define bootcfg
  595. (operating-system-bootcfg os))
  596. ;; XXX: When FULL-BOOT? is true, we end up creating an image that contains
  597. ;; BOOTCFG and all its dependencies, including the output of OS.
  598. ;; This is more than needed (we only need the kernel, initrd, GRUB for its
  599. ;; font, and the background image), but it's hard to filter that.
  600. (qemu-image #:os os
  601. #:system system
  602. #:target target
  603. #:bootcfg-drv bootcfg
  604. #:bootloader (bootloader-configuration-bootloader
  605. (operating-system-bootloader os))
  606. #:disk-image-size disk-image-size
  607. #:file-system-uuid root-uuid
  608. #:inputs (if full-boot?
  609. `(("bootcfg" ,bootcfg))
  610. '())
  611. ;; XXX: Passing #t here is too slow, so let it off by default.
  612. #:register-closures? #f
  613. #:copy-inputs? full-boot?))
  614. (define* (common-qemu-options image shared-fs)
  615. "Return the a string-value gexp with the common QEMU options to boot IMAGE,
  616. with '-virtfs' options for the host file systems listed in SHARED-FS."
  617. (define (virtfs-option fs)
  618. #~(format #f "-virtfs local,path=~s,security_model=none,mount_tag=~s"
  619. #$fs #$(file-system->mount-tag fs)))
  620. #~(;; Only enable kvm if we see /dev/kvm exists.
  621. ;; This allows users without hardware virtualization to still use these
  622. ;; commands.
  623. #$@(if (file-exists? "/dev/kvm")
  624. '("-enable-kvm")
  625. '())
  626. "-no-reboot"
  627. "-object" "rng-random,filename=/dev/urandom,id=guixsd-vm-rng"
  628. "-device" "virtio-rng-pci,rng=guixsd-vm-rng"
  629. #$@(map virtfs-option shared-fs)
  630. "-vga std"
  631. (format #f "-drive file=~a,if=virtio,cache=writeback,werror=report,readonly"
  632. #$image)))
  633. (define* (system-qemu-image/shared-store-script os
  634. #:key
  635. (system (%current-system))
  636. (target (%current-target-system))
  637. (qemu qemu)
  638. (graphic? #t)
  639. (memory-size 256)
  640. (mappings '())
  641. full-boot?
  642. (disk-image-size
  643. (* (if full-boot? 500 70)
  644. (expt 2 20)))
  645. (options '()))
  646. "Return a derivation that builds a script to run a virtual machine image of
  647. OS that shares its store with the host. The virtual machine runs with
  648. MEMORY-SIZE MiB of memory.
  649. MAPPINGS is a list of <file-system-mapping> specifying mapping of host file
  650. systems into the guest.
  651. When FULL-BOOT? is true, the returned script runs everything starting from the
  652. bootloader; otherwise it directly starts the operating system kernel. The
  653. DISK-IMAGE-SIZE parameter specifies the size in bytes of the root disk image;
  654. it is mostly useful when FULL-BOOT? is true."
  655. (mlet* %store-monad ((os -> (virtualized-operating-system os mappings full-boot?))
  656. (image (system-qemu-image/shared-store
  657. os
  658. #:system system
  659. #:target target
  660. #:full-boot? full-boot?
  661. #:disk-image-size disk-image-size)))
  662. (define kernel-arguments
  663. #~(list #$@(if graphic? #~() #~("console=ttyS0"))
  664. #+@(operating-system-kernel-arguments os "/dev/vda1")))
  665. (define qemu-exec
  666. #~(list #+(file-append qemu "/bin/"
  667. (qemu-command (or target system)))
  668. #$@(if full-boot?
  669. #~()
  670. #~("-kernel" #$(operating-system-kernel-file os)
  671. "-initrd" #$(file-append os "/initrd")
  672. (format #f "-append ~s"
  673. (string-join #$kernel-arguments " "))))
  674. #$@(common-qemu-options image
  675. (map file-system-mapping-source
  676. (cons %store-mapping mappings)))
  677. "-m " (number->string #$memory-size)
  678. #$@options))
  679. (define builder
  680. #~(call-with-output-file #$output
  681. (lambda (port)
  682. (format port "#!~a~% exec ~a \"$@\"~%"
  683. #+(file-append bash "/bin/sh")
  684. (string-join #$qemu-exec " "))
  685. (chmod port #o555))))
  686. (gexp->derivation "run-vm.sh" builder)))
  687. ;;;
  688. ;;; High-level abstraction.
  689. ;;;
  690. (define-record-type* <virtual-machine> %virtual-machine
  691. make-virtual-machine
  692. virtual-machine?
  693. (operating-system virtual-machine-operating-system) ;<operating-system>
  694. (qemu virtual-machine-qemu ;<package>
  695. (default qemu))
  696. (graphic? virtual-machine-graphic? ;Boolean
  697. (default #f))
  698. (memory-size virtual-machine-memory-size ;integer (MiB)
  699. (default 256))
  700. (disk-image-size virtual-machine-disk-image-size ;integer (bytes)
  701. (default 'guess))
  702. (port-forwardings virtual-machine-port-forwardings ;list of integer pairs
  703. (default '())))
  704. (define-syntax virtual-machine
  705. (syntax-rules ()
  706. "Declare a virtual machine running the specified OS, with the given
  707. options."
  708. ((_ os) ;shortcut
  709. (%virtual-machine (operating-system os)))
  710. ((_ fields ...)
  711. (%virtual-machine fields ...))))
  712. (define (port-forwardings->qemu-options forwardings)
  713. "Return the QEMU option for the given port FORWARDINGS as a string, where
  714. FORWARDINGS is a list of host-port/guest-port pairs."
  715. (string-join
  716. (map (match-lambda
  717. ((host-port . guest-port)
  718. (string-append "hostfwd=tcp::"
  719. (number->string host-port)
  720. "-:" (number->string guest-port))))
  721. forwardings)
  722. ","))
  723. (define-gexp-compiler (virtual-machine-compiler (vm <virtual-machine>)
  724. system target)
  725. (match vm
  726. (($ <virtual-machine> os qemu graphic? memory-size disk-image-size ())
  727. (system-qemu-image/shared-store-script os
  728. #:system system
  729. #:target target
  730. #:qemu qemu
  731. #:graphic? graphic?
  732. #:memory-size memory-size
  733. #:disk-image-size
  734. disk-image-size))
  735. (($ <virtual-machine> os qemu graphic? memory-size disk-image-size
  736. forwardings)
  737. (let ((options
  738. `("-nic" ,(string-append
  739. "user,model=virtio-net-pci,"
  740. (port-forwardings->qemu-options forwardings)))))
  741. (system-qemu-image/shared-store-script os
  742. #:system system
  743. #:target target
  744. #:qemu qemu
  745. #:graphic? graphic?
  746. #:memory-size memory-size
  747. #:disk-image-size
  748. disk-image-size
  749. #:options options)))))
  750. ;;; vm.scm ends here