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