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 ;;; Copyright © 2020 Tobias Geerinckx-Rice <me@tobias.gr>
10 ;;; This file is part of GNU Guix.
12 ;;; GNU Guix is free software; you can redistribute it and/or modify it
13 ;;; under the terms of the GNU General Public License as published by
14 ;;; the Free Software Foundation; either version 3 of the License, or (at
15 ;;; your option) any later version.
17 ;;; GNU Guix is distributed in the hope that it will be useful, but
18 ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;;; GNU General Public License for more details.
22 ;;; You should have received a copy of the GNU General Public License
23 ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
25 (define-module (gnu build vm)
26 #:use-module (guix build utils)
27 #:use-module (guix build store-copy)
28 #:use-module (guix build syscalls)
29 #:use-module (guix store database)
30 #:use-module (gnu build bootloader)
31 #:use-module (gnu build linux-boot)
32 #:use-module (gnu build install)
33 #:use-module (gnu system uuid)
34 #:use-module (guix records)
35 #:use-module ((guix combinators) #:select (fold2))
36 #:use-module (ice-9 format)
37 #:use-module (ice-9 ftw)
38 #:use-module (ice-9 match)
39 #:use-module (ice-9 regex)
40 #:use-module (ice-9 popen)
41 #:use-module (srfi srfi-1)
42 #:use-module (srfi srfi-9)
43 #:use-module (srfi srfi-19)
44 #:use-module (srfi srfi-26)
45 #:export (qemu-command
58 estimated-partition-size
59 root-partition-initializer
60 initialize-partition-table
61 initialize-hard-disk))
65 ;;; This module provides supporting code to run virtual machines and build
66 ;;; virtual machine images using QEMU.
70 (define* (qemu-command #:optional (system %host-type))
71 "Return the default name of the QEMU command for SYSTEM."
72 (let ((cpu (substring system 0
73 (string-index system #\-))))
74 (string-append "qemu-system-"
76 ((string-match "^i[3456]86$" cpu) "i386")
77 ((string-match "armhf" cpu) "arm")
80 (define* (load-in-linux-vm builder
83 (qemu (qemu-command)) (memory-size 512)
87 (disk-image-size (* 100 (expt 2 20)))
88 (disk-image-format "qcow2")
89 (references-graphs '()))
90 "Run BUILDER, a Scheme file, into a VM running LINUX with INITRD, and copy
91 the result to OUTPUT. If SINGLE-FILE-OUTPUT? is true, copy a single file from
92 /xchg to OUTPUT. Otherwise, copy the contents of /xchg to a new directory
95 When MAKE-DISK-IMAGE? is true, OUTPUT will contain a VM image of
96 DISK-IMAGE-SIZE bytes resulting from the execution of BUILDER, which may
97 access it via /dev/hda.
99 REFERENCES-GRAPHS can specify a list of reference-graph files as produced by
100 the #:references-graphs parameter of 'derivation'."
102 (define target-arm32?
103 (string-prefix? "arm-" %host-type))
105 (define target-aarch64?
106 (string-prefix? "aarch64-" %host-type))
109 (or target-arm32? target-aarch64?))
111 (define arch-specific-flags
112 `(;; On ARM, a machine has to be specified. Use "virt" machine to avoid
113 ;; hardware limits imposed by other machines.
118 ;; On ARM32, if the kernel is built without LPAE support, ECAM conflicts
119 ;; with VIRT_PCIE_MMIO causing PCI devices not to show up. Disable
120 ;; explicitely highmem to fix it.
121 ;; See: https://bugs.launchpad.net/qemu/+bug/1790975.
123 '("-machine" "highmem=off")
126 ;; Only enable kvm if we see /dev/kvm exists. This allows users without
127 ;; hardware virtualization to still use these commands. KVM support is
128 ;; still buggy on some ARM boards. Do not use it even if available.
129 ,@(if (and (file-exists? "/dev/kvm")
134 ;; Pass "panic=1" so that the guest dies upon error.
136 ,(string-append "panic=1 --load=" builder
138 ;; The serial port name differs between emulated
139 ;; architectures/machines.
141 (if target-arm? "ttyAMA0" "ttyS0"))))
143 (when make-disk-image?
144 (format #t "creating ~a image of ~,2f MiB...~%"
145 disk-image-format (/ disk-image-size (expt 2 20)))
147 (invoke "qemu-img" "create" "-f" disk-image-format output
148 (number->string disk-image-size)))
153 (match references-graphs
155 ;; Copy the reference-graph files under xchg/ so EXP can access it.
157 (copy-file file (string-append "xchg/" file)))
161 (apply invoke qemu "-nographic" "-no-reboot"
162 ;; CPU "max" behaves as "host" when KVM is enabled, and like a system
163 ;; CPU with the maximum possible feature set otherwise.
165 "-m" (number->string memory-size)
166 "-nic" "user,model=virtio-net-pci"
167 "-object" "rng-random,filename=/dev/urandom,id=guixsd-vm-rng"
168 "-device" "virtio-rng-pci,rng=guixsd-vm-rng"
170 (string-append "local,id=store_dev,path="
172 ",security_model=none,mount_tag=store")
174 (string-append "local,id=xchg_dev,path=xchg"
175 ",security_model=none,mount_tag=xchg")
177 ;; Some programs require more space in /tmp than is normally
178 ;; available in the guest. Accommodate such programs by sharing a
179 ;; temporary directory.
180 (string-append "local,id=tmp_dev,path=tmp"
181 ",security_model=none,mount_tag=tmp")
186 `("-device" "virtio-blk,drive=myhd"
187 "-drive" ,(string-append "if=none,file=" output
188 ",format=" disk-image-format
191 arch-specific-flags))
193 (unless (file-exists? "xchg/.exit-status")
194 (error "VM did not produce an exit code"))
196 (match (call-with-input-file "xchg/.exit-status" read)
198 (status (error "guest VM code exited with a non-zero status" status)))
200 (delete-file "xchg/.exit-status")
202 ;; When MAKE-DISK-IMAGE? is true, the image is in OUTPUT already.
203 (unless make-disk-image?
204 (if single-file-output?
205 (let ((graph? (lambda (name stat)
206 (member (basename name) references-graphs))))
207 (match (find-files "xchg" (negate graph?))
209 (copy-file result output))
211 (error "did not find a single result file" x))))
214 (copy-recursively "xchg" output)))))
216 (define* (register-closure prefix closure
218 (schema (sql-schema)))
219 "Register CLOSURE in PREFIX, where PREFIX is the directory name of the
220 target store and CLOSURE is the name of a file containing a reference graph as
221 produced by #:references-graphs."
222 (let ((items (call-with-input-file closure read-reference-graph)))
223 (parameterize ((sql-schema schema))
224 (with-database (store-database-file #:prefix prefix) db
225 (register-items db items
227 #:registration-time %epoch)))))
234 (define-record-type* <partition> partition make-partition
236 (device partition-device (default #f))
237 (size partition-size)
238 (file-system partition-file-system (default "ext4"))
239 (file-system-options partition-file-system-options ;passed to 'mkfs.FS'
241 (label partition-label (default #f))
242 (uuid partition-uuid (default #f))
243 (flags partition-flags (default '()))
244 (initializer partition-initializer (default (const #t))))
246 (define (estimated-partition-size graphs)
247 "Return the estimated size of a partition that can store the store items
248 given by GRAPHS, a list of file names produced by #:references-graphs."
249 ;; Simply add a 25% overhead.
250 (round (* 1.25 (closure-size graphs))))
252 (define* (initialize-partition-table device partitions
255 (offset (expt 2 20)))
256 "Create on DEVICE a partition table of type LABEL-TYPE, containing the given
257 PARTITIONS (a list of <partition> objects), starting at OFFSET bytes. On
258 success, return PARTITIONS with their 'device' field changed to reflect their
259 actual /dev name based on DEVICE."
260 (define (partition-options part offset index)
261 (cons* "mkpart" "primary" "ext2"
262 (format #f "~aB" offset)
263 (format #f "~aB" (+ offset (partition-size part)))
264 (append-map (lambda (flag)
265 (list "set" (number->string index)
266 (symbol->string flag) "on"))
267 (partition-flags part))))
269 (define (options partitions offset)
270 (let loop ((partitions partitions)
276 (concatenate (reverse result)))
279 ;; Leave one sector (512B) between partitions to placate
281 (+ offset 512 (partition-size head))
283 (cons (partition-options head offset index)
286 (format #t "creating partition table with ~a partitions (~a)...\n"
288 (string-join (map (compose (cut string-append <> " MiB")
291 (round (/ size (expt 2. 20))))
295 (apply invoke "parted" "--script"
296 device "mklabel" label-type
297 (options partitions offset))
299 ;; Set the 'device' field of each partition.
301 (fold2 (lambda (part result index)
302 (values (cons (partition
304 (device (string-append device
305 (number->string index))))
312 (define MS_BIND 4096) ; <sys/mounts.h> again!
314 (define* (create-ext-file-system partition type
315 #:key label uuid (options '()))
316 "Create an ext-family file system of TYPE on PARTITION. If LABEL is true,
317 use that as the volume name. If UUID is true, use it as the partition UUID."
318 (format #t "creating ~a partition... ~@[label: ~s~] ~@[uuid: ~s~]\n"
319 type label (and uuid (uuid->string uuid)))
320 (apply invoke (string-append "mkfs." type)
326 `("-U" ,(uuid->string uuid))
330 (define* (create-fat-file-system partition
331 #:key label uuid (options '()))
332 "Create a FAT file system on PARTITION. The number of File Allocation Tables
333 will be determined based on file system size. If LABEL is true, use that as the
335 ;; FIXME: UUID is ignored!
336 (format #t "creating FAT partition...\n")
337 (apply invoke "mkfs.fat" partition
338 (append (if label `("-n" ,label) '()) options)))
340 (define* (format-partition partition type
341 #:key label uuid (options '()))
342 "Create a file system TYPE on PARTITION. If LABEL is true, use that as the
343 volume name. Options is a list of command-line options passed to 'mkfs.FS'."
344 (cond ((string-prefix? "ext" type)
345 (create-ext-file-system partition type #:label label #:uuid uuid
347 ((or (string-prefix? "fat" type) (string= "vfat" type))
348 (create-fat-file-system partition #:label label #:uuid uuid
350 (else (error "Unsupported file system."))))
352 (define (initialize-partition partition)
353 "Format PARTITION, a <partition> object with a non-#f 'device' field, mount
354 it, run its initializer, and unmount it."
355 (let ((target "/fs"))
356 (format-partition (partition-device partition)
357 (partition-file-system partition)
358 #:label (partition-label partition)
359 #:uuid (partition-uuid partition)
360 #:options (partition-file-system-options partition))
362 (mount (partition-device partition) target
363 (partition-file-system partition))
365 ((partition-initializer partition) target)
370 (define* (root-partition-initializer #:key (closures '())
372 (register-closures? #t)
376 make-essential-device-nodes)
377 (extra-directives '()))
378 "Return a procedure to initialize a root partition.
380 If REGISTER-CLOSURES? is true, register all of CLOSURES in the partition's
381 store. If DEDUPLICATE? is true, then also deduplicate files common to
382 CLOSURES and the rest of the store when registering the closures. If
383 COPY-CLOSURES? is true, copy all of CLOSURES to the partition.
384 SYSTEM-DIRECTORY is the name of the directory of the 'system' derivation.
386 EXTRA-DIRECTIVES is an optional list of directives to populate the root file
387 system that is passed to 'populate-root-file-system'."
390 (string-append target (%store-directory)))
393 ;; Populate the store.
394 (populate-store (map (cut string-append "/xchg/" <>) closures)
396 #:deduplicate? deduplicate?))
399 (make-device-nodes target)
401 ;; Optionally, register the inputs in the image's store.
402 (when register-closures?
403 (unless copy-closures?
404 ;; XXX: 'register-closure' wants to palpate the things it registers, so
405 ;; bind-mount the store on the target.
406 (mkdir-p target-store)
407 (mount (%store-directory) target-store "" MS_BIND))
409 (display "registering closures...\n")
410 (for-each (lambda (closure)
411 (register-closure target
412 (string-append "/xchg/" closure)))
414 (unless copy-closures?
415 (umount target-store)))
417 ;; Add the non-store directories and files.
418 (display "populating...\n")
419 (populate-root-file-system system-directory target
420 #:extras extra-directives)
422 ;; 'register-closure' resets timestamps and everything, so no need to do it
423 ;; once more in that case.
424 (unless register-closures?
425 ;; 'reset-timestamps' also resets file permissions; do that everywhere
426 ;; except on /dev so that /dev/null remains writable, etc.
427 (for-each (lambda (directory)
428 (reset-timestamps (string-append target "/" directory)))
431 ((or "." ".." "dev") #f)
433 (reset-timestamps (string-append target "/dev")
434 #:preserve-permissions? #t))))
436 (define (register-bootcfg-root target bootcfg)
437 "On file system TARGET, register BOOTCFG as a GC root."
438 (let ((directory (string-append target "/var/guix/gcroots")))
440 (symlink bootcfg (string-append directory "/bootcfg"))))
442 (define* (initialize-hard-disk device
450 "Initialize DEVICE as a disk containing all the <partition> objects listed
451 in PARTITIONS, and using BOOTCFG as its bootloader configuration file.
453 Each partition is initialized by calling its 'initializer' procedure,
454 passing it a directory name where it is mounted."
456 (define (partition-bootable? partition)
457 "Return the first partition found with the boot flag set."
458 (member 'boot (partition-flags partition)))
460 (define (partition-esp? partition)
461 "Return the first EFI System Partition."
462 (member 'esp (partition-flags partition)))
464 (let* ((partitions (initialize-partition-table device partitions))
465 (root (find partition-bootable? partitions))
466 (esp (find partition-esp? partitions))
469 (error "no bootable partition specified" partitions))
471 (for-each initialize-partition partitions)
473 (display "mounting root partition...\n")
475 (mount (partition-device root) target (partition-file-system root))
476 (install-boot-config bootcfg bootcfg-location target)
477 (when bootloader-installer
478 (display "installing bootloader...\n")
479 (bootloader-installer bootloader-package device target))
482 ;; Mount the ESP somewhere and install GRUB UEFI image.
483 (let ((mount-point (string-append target "/boot/efi")))
484 (display "mounting EFI system partition...\n")
485 (mkdir-p mount-point)
486 (mount (partition-device esp) mount-point
487 (partition-file-system esp))
489 (display "creating EFI firmware image...")
490 (install-efi-loader grub-efi mount-point)
493 (umount mount-point)))
495 ;; Register BOOTCFG as a GC root.
496 (register-bootcfg-root target bootcfg)