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