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