vm.scm 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. ;;; GNU Guix --- Functional package management for GNU
  2. ;;; Copyright © 2013, 2014, 2015, 2016, 2017 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. ;;;
  8. ;;; This file is part of GNU Guix.
  9. ;;;
  10. ;;; GNU Guix is free software; you can redistribute it and/or modify it
  11. ;;; under the terms of the GNU General Public License as published by
  12. ;;; the Free Software Foundation; either version 3 of the License, or (at
  13. ;;; your option) any later version.
  14. ;;;
  15. ;;; GNU Guix is distributed in the hope that it will be useful, but
  16. ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
  17. ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. ;;; GNU General Public License for more details.
  19. ;;;
  20. ;;; You should have received a copy of the GNU General Public License
  21. ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
  22. (define-module (gnu build vm)
  23. #:use-module (guix build utils)
  24. #:use-module (guix build store-copy)
  25. #:use-module (guix build syscalls)
  26. #:use-module (gnu build linux-boot)
  27. #:use-module (gnu build install)
  28. #:use-module (gnu system uuid)
  29. #:use-module (guix records)
  30. #:use-module ((guix combinators) #:select (fold2))
  31. #:use-module (ice-9 format)
  32. #:use-module (ice-9 match)
  33. #:use-module (ice-9 regex)
  34. #:use-module (srfi srfi-1)
  35. #:use-module (srfi srfi-9)
  36. #:use-module (srfi srfi-26)
  37. #:export (qemu-command
  38. load-in-linux-vm
  39. format-partition
  40. partition
  41. partition?
  42. partition-device
  43. partition-size
  44. partition-file-system
  45. partition-label
  46. partition-flags
  47. partition-initializer
  48. estimated-partition-size
  49. root-partition-initializer
  50. initialize-partition-table
  51. initialize-hard-disk
  52. make-iso9660-image))
  53. ;;; Commentary:
  54. ;;;
  55. ;;; This module provides supporting code to run virtual machines and build
  56. ;;; virtual machine images using QEMU.
  57. ;;;
  58. ;;; Code:
  59. (define* (qemu-command #:optional (system %host-type))
  60. "Return the default name of the QEMU command for SYSTEM."
  61. (let ((cpu (substring system 0
  62. (string-index system #\-))))
  63. (string-append "qemu-system-"
  64. (if (string-match "^i[3456]86$" cpu)
  65. "i386"
  66. cpu))))
  67. (define* (load-in-linux-vm builder
  68. #:key
  69. output
  70. (qemu (qemu-command)) (memory-size 512)
  71. linux initrd
  72. make-disk-image?
  73. single-file-output?
  74. target-arm32?
  75. (disk-image-size (* 100 (expt 2 20)))
  76. (disk-image-format "qcow2")
  77. (references-graphs '()))
  78. "Run BUILDER, a Scheme file, into a VM running LINUX with INITRD, and copy
  79. the result to OUTPUT. If SINGLE-FILE-OUTPUT? is true, copy a single file from
  80. /xchg to OUTPUT. Otherwise, copy the contents of /xchg to a new directory
  81. OUTPUT.
  82. When MAKE-DISK-IMAGE? is true, OUTPUT will contain a VM image of
  83. DISK-IMAGE-SIZE bytes resulting from the execution of BUILDER, which may
  84. access it via /dev/hda.
  85. REFERENCES-GRAPHS can specify a list of reference-graph files as produced by
  86. the #:references-graphs parameter of 'derivation'."
  87. (define arch-specific-flags
  88. `(;; On ARM, a machine has to be specified. Use "virt" machine to avoid
  89. ;; hardware limits imposed by other machines.
  90. ,@(if target-arm32? '("-M" "virt") '())
  91. ;; Only enable kvm if we see /dev/kvm exists. This allows users without
  92. ;; hardware virtualization to still use these commands. KVM support is
  93. ;; still buggy on some ARM32 boards. Do not use it even if available.
  94. ,@(if (and (file-exists? "/dev/kvm")
  95. (not target-arm32?))
  96. '("-enable-kvm")
  97. '())
  98. "-append"
  99. ;; The serial port name differs between emulated architectures/machines.
  100. ,@(if target-arm32?
  101. `(,(string-append "console=ttyAMA0 --load=" builder))
  102. `(,(string-append "console=ttyS0 --load=" builder)))
  103. ;; NIC is not supported on ARM "virt" machine, so use a user mode
  104. ;; network stack instead.
  105. ,@(if target-arm32?
  106. '("-device" "virtio-net-pci,netdev=mynet"
  107. "-netdev" "user,id=mynet")
  108. '("-net" "nic,model=virtio"))))
  109. (when make-disk-image?
  110. (format #t "creating ~a image of ~,2f MiB...~%"
  111. disk-image-format (/ disk-image-size (expt 2 20)))
  112. (force-output)
  113. (unless (zero? (system* "qemu-img" "create" "-f" disk-image-format
  114. output
  115. (number->string disk-image-size)))
  116. (error "qemu-img failed")))
  117. (mkdir "xchg")
  118. (match references-graphs
  119. ((graph-files ...)
  120. ;; Copy the reference-graph files under xchg/ so EXP can access it.
  121. (map (lambda (file)
  122. (copy-file file (string-append "xchg/" file)))
  123. graph-files))
  124. (_ #f))
  125. (unless (zero?
  126. (apply system* qemu "-nographic" "-no-reboot"
  127. "-m" (number->string memory-size)
  128. "-object" "rng-random,filename=/dev/urandom,id=guixsd-vm-rng"
  129. "-device" "virtio-rng-pci,rng=guixsd-vm-rng"
  130. "-virtfs"
  131. (string-append "local,id=store_dev,path="
  132. (%store-directory)
  133. ",security_model=none,mount_tag=store")
  134. "-virtfs"
  135. (string-append "local,id=xchg_dev,path=xchg"
  136. ",security_model=none,mount_tag=xchg")
  137. "-kernel" linux
  138. "-initrd" initrd
  139. "-append" (string-append "console=ttyS0 --load="
  140. builder)
  141. (append
  142. (if make-disk-image?
  143. `("-device" "virtio-blk,drive=myhd"
  144. "-drive" ,(string-append "if=none,file=" output
  145. ",format=" disk-image-format
  146. ",id=myhd"))
  147. '())
  148. arch-specific-flags)))
  149. (error "qemu failed" qemu))
  150. ;; When MAKE-DISK-IMAGE? is true, the image is in OUTPUT already.
  151. (unless make-disk-image?
  152. (if single-file-output?
  153. (let ((graph? (lambda (name stat)
  154. (member (basename name) references-graphs))))
  155. (match (find-files "xchg" (negate graph?))
  156. ((result)
  157. (copy-file result output))
  158. (x
  159. (error "did not find a single result file" x))))
  160. (begin
  161. (mkdir output)
  162. (copy-recursively "xchg" output)))))
  163. ;;;
  164. ;;; Partitions.
  165. ;;;
  166. (define-record-type* <partition> partition make-partition
  167. partition?
  168. (device partition-device (default #f))
  169. (size partition-size)
  170. (file-system partition-file-system (default "ext4"))
  171. (label partition-label (default #f))
  172. (uuid partition-uuid (default #f))
  173. (flags partition-flags (default '()))
  174. (initializer partition-initializer (default (const #t))))
  175. (define (estimated-partition-size graphs)
  176. "Return the estimated size of a partition that can store the store items
  177. given by GRAPHS, a list of file names produced by #:references-graphs."
  178. ;; Simply add a 25% overhead.
  179. (round (* 1.25 (closure-size graphs))))
  180. (define* (initialize-partition-table device partitions
  181. #:key
  182. (label-type "msdos")
  183. (offset (expt 2 20)))
  184. "Create on DEVICE a partition table of type LABEL-TYPE, containing the given
  185. PARTITIONS (a list of <partition> objects), starting at OFFSET bytes. On
  186. success, return PARTITIONS with their 'device' field changed to reflect their
  187. actual /dev name based on DEVICE."
  188. (define (partition-options part offset index)
  189. (cons* "mkpart" "primary" "ext2"
  190. (format #f "~aB" offset)
  191. (format #f "~aB" (+ offset (partition-size part)))
  192. (append-map (lambda (flag)
  193. (list "set" (number->string index)
  194. (symbol->string flag) "on"))
  195. (partition-flags part))))
  196. (define (options partitions offset)
  197. (let loop ((partitions partitions)
  198. (offset offset)
  199. (index 1)
  200. (result '()))
  201. (match partitions
  202. (()
  203. (concatenate (reverse result)))
  204. ((head tail ...)
  205. (loop tail
  206. ;; Leave one sector (512B) between partitions to placate
  207. ;; Parted.
  208. (+ offset 512 (partition-size head))
  209. (+ 1 index)
  210. (cons (partition-options head offset index)
  211. result))))))
  212. (format #t "creating partition table with ~a partitions (~a)...\n"
  213. (length partitions)
  214. (string-join (map (compose (cut string-append <> " MiB")
  215. number->string
  216. (lambda (size)
  217. (round (/ size (expt 2. 20))))
  218. partition-size)
  219. partitions)
  220. ", "))
  221. (unless (zero? (apply system* "parted" "--script"
  222. device "mklabel" label-type
  223. (options partitions offset)))
  224. (error "failed to create partition table"))
  225. ;; Set the 'device' field of each partition.
  226. (reverse
  227. (fold2 (lambda (part result index)
  228. (values (cons (partition
  229. (inherit part)
  230. (device (string-append device
  231. (number->string index))))
  232. result)
  233. (+ 1 index)))
  234. '()
  235. 1
  236. partitions)))
  237. (define MS_BIND 4096) ; <sys/mounts.h> again!
  238. (define* (create-ext-file-system partition type
  239. #:key label uuid)
  240. "Create an ext-family filesystem of TYPE on PARTITION. If LABEL is true,
  241. use that as the volume name. If UUID is true, use it as the partition UUID."
  242. (format #t "creating ~a partition...\n" type)
  243. (unless (zero? (apply system* (string-append "mkfs." type)
  244. "-F" partition
  245. `(,@(if label
  246. `("-L" ,label)
  247. '())
  248. ,@(if uuid
  249. `("-U" ,(uuid->string uuid))
  250. '()))))
  251. (error "failed to create partition")))
  252. (define* (create-fat-file-system partition
  253. #:key label uuid)
  254. "Create a FAT filesystem on PARTITION. The number of File Allocation Tables
  255. will be determined based on filesystem size. If LABEL is true, use that as the
  256. volume name."
  257. ;; FIXME: UUID is ignored!
  258. (format #t "creating FAT partition...\n")
  259. (unless (zero? (apply system* "mkfs.fat" partition
  260. (if label
  261. `("-n" ,label)
  262. '())))
  263. (error "failed to create FAT partition")))
  264. (define* (format-partition partition type
  265. #:key label uuid)
  266. "Create a file system TYPE on PARTITION. If LABEL is true, use that as the
  267. volume name."
  268. (cond ((string-prefix? "ext" type)
  269. (create-ext-file-system partition type #:label label #:uuid uuid))
  270. ((or (string-prefix? "fat" type) (string= "vfat" type))
  271. (create-fat-file-system partition #:label label #:uuid uuid))
  272. (else (error "Unsupported file system."))))
  273. (define (initialize-partition partition)
  274. "Format PARTITION, a <partition> object with a non-#f 'device' field, mount
  275. it, run its initializer, and unmount it."
  276. (let ((target "/fs"))
  277. (format-partition (partition-device partition)
  278. (partition-file-system partition)
  279. #:label (partition-label partition)
  280. #:uuid (partition-uuid partition))
  281. (mkdir-p target)
  282. (mount (partition-device partition) target
  283. (partition-file-system partition))
  284. ((partition-initializer partition) target)
  285. (umount target)
  286. partition))
  287. (define* (root-partition-initializer #:key (closures '())
  288. copy-closures?
  289. (register-closures? #t)
  290. system-directory)
  291. "Return a procedure to initialize a root partition.
  292. If REGISTER-CLOSURES? is true, register all of CLOSURES is the partition's
  293. store. If COPY-CLOSURES? is true, copy all of CLOSURES to the partition.
  294. SYSTEM-DIRECTORY is the name of the directory of the 'system' derivation."
  295. (lambda (target)
  296. (define target-store
  297. (string-append target (%store-directory)))
  298. (when copy-closures?
  299. ;; Populate the store.
  300. (populate-store (map (cut string-append "/xchg/" <>) closures)
  301. target))
  302. ;; Populate /dev.
  303. (make-essential-device-nodes #:root target)
  304. ;; Optionally, register the inputs in the image's store.
  305. (when register-closures?
  306. (unless copy-closures?
  307. ;; XXX: 'guix-register' wants to palpate the things it registers, so
  308. ;; bind-mount the store on the target.
  309. (mkdir-p target-store)
  310. (mount (%store-directory) target-store "" MS_BIND))
  311. (display "registering closures...\n")
  312. (for-each (lambda (closure)
  313. (register-closure target
  314. (string-append "/xchg/" closure)))
  315. closures)
  316. (unless copy-closures?
  317. (umount target-store)))
  318. ;; Add the non-store directories and files.
  319. (display "populating...\n")
  320. (populate-root-file-system system-directory target)
  321. ;; 'guix-register' resets timestamps and everything, so no need to do it
  322. ;; once more in that case.
  323. (unless register-closures?
  324. (reset-timestamps target))))
  325. (define (register-bootcfg-root target bootcfg)
  326. "On file system TARGET, register BOOTCFG as a GC root."
  327. (let ((directory (string-append target "/var/guix/gcroots")))
  328. (mkdir-p directory)
  329. (symlink bootcfg (string-append directory "/bootcfg"))))
  330. (define (install-efi grub esp config-file)
  331. "Write a self-contained GRUB EFI loader to the mounted ESP using CONFIG-FILE."
  332. (let* ((system %host-type)
  333. ;; Hard code the output location to a well-known path recognized by
  334. ;; compliant firmware. See "3.5.1.1 Removable Media Boot Behaviour":
  335. ;; http://www.uefi.org/sites/default/files/resources/UEFI%20Spec%202_6.pdf
  336. (grub-mkstandalone (string-append grub "/bin/grub-mkstandalone"))
  337. (efi-directory (string-append esp "/EFI/BOOT"))
  338. ;; Map grub target names to boot file names.
  339. (efi-targets (cond ((string-prefix? "x86_64" system)
  340. '("x86_64-efi" . "BOOTX64.EFI"))
  341. ((string-prefix? "i686" system)
  342. '("i386-efi" . "BOOTIA32.EFI"))
  343. ((string-prefix? "armhf" system)
  344. '("arm-efi" . "BOOTARM.EFI"))
  345. ((string-prefix? "aarch64" system)
  346. '("arm64-efi" . "BOOTAA64.EFI")))))
  347. ;; grub-mkstandalone requires a TMPDIR to prepare the firmware image.
  348. (setenv "TMPDIR" esp)
  349. (mkdir-p efi-directory)
  350. (unless (zero? (system* grub-mkstandalone "-O" (car efi-targets)
  351. "-o" (string-append efi-directory "/"
  352. (cdr efi-targets))
  353. ;; Graft the configuration file onto the image.
  354. (string-append "boot/grub/grub.cfg=" config-file)))
  355. (error "failed to create GRUB EFI image"))))
  356. (define* (make-iso9660-image grub config-file os-drv target
  357. #:key (volume-id "GuixSD_image") (volume-uuid #f)
  358. register-closures? (closures '()))
  359. "Given a GRUB package, creates an iso image as TARGET, using CONFIG-FILE as
  360. GRUB configuration and OS-DRV as the stuff in it."
  361. (let ((grub-mkrescue (string-append grub "/bin/grub-mkrescue"))
  362. (target-store (string-append "/tmp/root" (%store-directory))))
  363. (populate-root-file-system os-drv "/tmp/root")
  364. (mount (%store-directory) target-store "" MS_BIND)
  365. (when register-closures?
  366. (display "registering closures...\n")
  367. (for-each (lambda (closure)
  368. (register-closure
  369. "/tmp/root"
  370. (string-append "/xchg/" closure)
  371. ;; XXX: Using deduplication causes cross device link errors.
  372. #:deduplicate? #f))
  373. closures))
  374. (unless (zero? (apply system*
  375. `(,grub-mkrescue "-o" ,target
  376. ,(string-append "boot/grub/grub.cfg=" config-file)
  377. ,(string-append "gnu/store=" os-drv "/..")
  378. "etc=/tmp/root/etc"
  379. "var=/tmp/root/var"
  380. "run=/tmp/root/run"
  381. ;; /mnt is used as part of the installation
  382. ;; process, as the mount point for the target
  383. ;; filesystem, so create it.
  384. "mnt=/tmp/root/mnt"
  385. "--"
  386. "-volid" ,(string-upcase volume-id)
  387. ,@(if volume-uuid
  388. `("-volume_date" "uuid"
  389. ,(string-filter (lambda (value)
  390. (not (char=? #\- value)))
  391. (iso9660-uuid->string
  392. volume-uuid)))
  393. `()))))
  394. (error "failed to create ISO9660 image"))))
  395. (define* (initialize-hard-disk device
  396. #:key
  397. bootloader-package
  398. bootcfg
  399. bootcfg-location
  400. bootloader-installer
  401. (grub-efi #f)
  402. (partitions '()))
  403. "Initialize DEVICE as a disk containing all the <partition> objects listed
  404. in PARTITIONS, and using BOOTCFG as its bootloader configuration file.
  405. Each partition is initialized by calling its 'initializer' procedure,
  406. passing it a directory name where it is mounted."
  407. (define (partition-bootable? partition)
  408. "Return the first partition found with the boot flag set."
  409. (member 'boot (partition-flags partition)))
  410. (define (partition-esp? partition)
  411. "Return the first EFI System Partition."
  412. (member 'esp (partition-flags partition)))
  413. (let* ((partitions (initialize-partition-table device partitions))
  414. (root (find partition-bootable? partitions))
  415. (esp (find partition-esp? partitions))
  416. (target "/fs"))
  417. (unless root
  418. (error "no bootable partition specified" partitions))
  419. (for-each initialize-partition partitions)
  420. (display "mounting root partition...\n")
  421. (mkdir-p target)
  422. (mount (partition-device root) target (partition-file-system root))
  423. (install-boot-config bootcfg bootcfg-location target)
  424. (when bootloader-installer
  425. (display "installing bootloader...\n")
  426. (bootloader-installer bootloader-package device target))
  427. (when esp
  428. ;; Mount the ESP somewhere and install GRUB UEFI image.
  429. (let ((mount-point (string-append target "/boot/efi"))
  430. (grub-config (string-append target "/tmp/grub-standalone.cfg")))
  431. (display "mounting EFI system partition...\n")
  432. (mkdir-p mount-point)
  433. (mount (partition-device esp) mount-point
  434. (partition-file-system esp))
  435. ;; Create a tiny configuration file telling the embedded grub
  436. ;; where to load the real thing.
  437. ;; XXX This is quite fragile, and can prevent the image from booting
  438. ;; when there's more than one volume with this label present.
  439. ;; Reproducible almost-UUIDs could reduce the risk (not eliminate it).
  440. (call-with-output-file grub-config
  441. (lambda (port)
  442. (format port
  443. "insmod part_msdos~@
  444. search --set=root --label GuixSD_image~@
  445. configfile /boot/grub/grub.cfg~%")))
  446. (display "creating EFI firmware image...")
  447. (install-efi grub-efi mount-point grub-config)
  448. (display "done.\n")
  449. (delete-file grub-config)
  450. (umount mount-point)))
  451. ;; Register BOOTCFG as a GC root.
  452. (register-bootcfg-root target bootcfg)
  453. (umount target)))
  454. ;;; vm.scm ends here