vm.scm 37 KB

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