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