vm.scm 41 KB

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