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