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