vm.scm 20 KB

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