vm.scm 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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 Christine Lemmer-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>
  9. ;;;
  10. ;;; This file is part of GNU Guix.
  11. ;;;
  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.
  16. ;;;
  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.
  21. ;;;
  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/>.
  24. (define-module (gnu build vm)
  25. #:use-module (guix build utils)
  26. #:use-module (guix build store-copy)
  27. #:use-module (guix build syscalls)
  28. #:use-module (guix store database)
  29. #:use-module (gnu build bootloader)
  30. #:use-module (gnu build linux-boot)
  31. #:use-module (gnu build install)
  32. #:use-module (gnu system uuid)
  33. #:use-module (guix records)
  34. #:use-module ((guix combinators) #:select (fold2))
  35. #:use-module (ice-9 format)
  36. #:use-module (ice-9 ftw)
  37. #:use-module (ice-9 match)
  38. #:use-module (ice-9 regex)
  39. #:use-module (ice-9 popen)
  40. #:use-module (srfi srfi-1)
  41. #:use-module (srfi srfi-9)
  42. #:use-module (srfi srfi-19)
  43. #:use-module (srfi srfi-26)
  44. #:export (qemu-command
  45. load-in-linux-vm
  46. format-partition
  47. partition
  48. partition?
  49. partition-device
  50. partition-size
  51. partition-file-system
  52. partition-label
  53. partition-flags
  54. partition-initializer
  55. estimated-partition-size
  56. root-partition-initializer
  57. initialize-partition-table
  58. initialize-hard-disk))
  59. ;;; Commentary:
  60. ;;;
  61. ;;; This module provides supporting code to run virtual machines and build
  62. ;;; virtual machine images using QEMU.
  63. ;;;
  64. ;;; Code:
  65. (define* (qemu-command #:optional (system %host-type))
  66. "Return the default name of the QEMU command for SYSTEM."
  67. (let ((cpu (substring system 0
  68. (string-index system #\-))))
  69. (string-append "qemu-system-"
  70. (cond
  71. ((string-match "^i[3456]86$" cpu) "i386")
  72. ((string-match "armhf" cpu) "arm")
  73. (else cpu)))))
  74. (define* (load-in-linux-vm builder
  75. #:key
  76. output
  77. (qemu (qemu-command)) (memory-size 512)
  78. linux initrd
  79. make-disk-image?
  80. single-file-output?
  81. (disk-image-size (* 100 (expt 2 20)))
  82. (disk-image-format "qcow2")
  83. (references-graphs '()))
  84. "Run BUILDER, a Scheme file, into a VM running LINUX with INITRD, and copy
  85. the result to OUTPUT. If SINGLE-FILE-OUTPUT? is true, copy a single file from
  86. /xchg to OUTPUT. Otherwise, copy the contents of /xchg to a new directory
  87. OUTPUT.
  88. When MAKE-DISK-IMAGE? is true, OUTPUT will contain a VM image of
  89. DISK-IMAGE-SIZE bytes resulting from the execution of BUILDER, which may
  90. access it via /dev/hda.
  91. REFERENCES-GRAPHS can specify a list of reference-graph files as produced by
  92. the #:references-graphs parameter of 'derivation'."
  93. (define target-arm32?
  94. (string-prefix? "arm-" %host-type))
  95. (define target-aarch64?
  96. (string-prefix? "aarch64-" %host-type))
  97. (define target-arm?
  98. (or target-arm32? target-aarch64?))
  99. (define arch-specific-flags
  100. `(;; On ARM, a machine has to be specified. Use "virt" machine to avoid
  101. ;; hardware limits imposed by other machines.
  102. ,@(if target-arm?
  103. '("-M" "virt")
  104. '())
  105. ;; On ARM32, if the kernel is built without LPAE support, ECAM conflicts
  106. ;; with VIRT_PCIE_MMIO causing PCI devices not to show up. Disable
  107. ;; explicitely highmem to fix it.
  108. ;; See: https://bugs.launchpad.net/qemu/+bug/1790975.
  109. ,@(if target-arm32?
  110. '("-machine" "highmem=off")
  111. '())
  112. ;; Only enable kvm if we see /dev/kvm exists. This allows users without
  113. ;; hardware virtualization to still use these commands. KVM support is
  114. ;; still buggy on some ARM boards. Do not use it even if available.
  115. ,@(if (and (file-exists? "/dev/kvm")
  116. (not target-arm?))
  117. '("-enable-kvm")
  118. '())
  119. ;; Pass "panic=1" so that the guest dies upon error.
  120. "-append"
  121. ,(string-append "panic=1 --load=" builder
  122. ;; The serial port name differs between emulated
  123. ;; architectures/machines.
  124. " console="
  125. (if target-arm? "ttyAMA0" "ttyS0"))))
  126. (when make-disk-image?
  127. (format #t "creating ~a image of ~,2f MiB...~%"
  128. disk-image-format (/ disk-image-size (expt 2 20)))
  129. (force-output)
  130. (invoke "qemu-img" "create" "-f" disk-image-format output
  131. (number->string disk-image-size)))
  132. (mkdir "xchg")
  133. (mkdir "tmp")
  134. (match references-graphs
  135. ((graph-files ...)
  136. ;; Copy the reference-graph files under xchg/ so EXP can access it.
  137. (map (lambda (file)
  138. (copy-file file (string-append "xchg/" file)))
  139. graph-files))
  140. (_ #f))
  141. (apply invoke qemu "-nographic" "-no-reboot"
  142. ;; CPU "max" behaves as "host" when KVM is enabled, and like a system
  143. ;; CPU with the maximum possible feature set otherwise.
  144. "-cpu" "max"
  145. "-m" (number->string memory-size)
  146. "-nic" "user,model=virtio-net-pci"
  147. "-object" "rng-random,filename=/dev/urandom,id=guixsd-vm-rng"
  148. "-device" "virtio-rng-pci,rng=guixsd-vm-rng"
  149. "-virtfs"
  150. (string-append "local,id=store_dev,path="
  151. (%store-directory)
  152. ",security_model=none,mount_tag=store")
  153. "-virtfs"
  154. (string-append "local,id=xchg_dev,path=xchg"
  155. ",security_model=none,mount_tag=xchg")
  156. "-virtfs"
  157. ;; Some programs require more space in /tmp than is normally
  158. ;; available in the guest. Accommodate such programs by sharing a
  159. ;; temporary directory.
  160. (string-append "local,id=tmp_dev,path=tmp"
  161. ",security_model=none,mount_tag=tmp")
  162. "-kernel" linux
  163. "-initrd" initrd
  164. (append
  165. (if make-disk-image?
  166. `("-device" "virtio-blk,drive=myhd"
  167. "-drive" ,(string-append "if=none,file=" output
  168. ",format=" disk-image-format
  169. ",id=myhd"))
  170. '())
  171. arch-specific-flags))
  172. (unless (file-exists? "xchg/.exit-status")
  173. (error "VM did not produce an exit code"))
  174. (match (call-with-input-file "xchg/.exit-status" read)
  175. (0 #t)
  176. (status (error "guest VM code exited with a non-zero status" status)))
  177. (delete-file "xchg/.exit-status")
  178. ;; When MAKE-DISK-IMAGE? is true, the image is in OUTPUT already.
  179. (unless make-disk-image?
  180. (if single-file-output?
  181. (let ((graph? (lambda (name stat)
  182. (member (basename name) references-graphs))))
  183. (match (find-files "xchg" (negate graph?))
  184. ((result)
  185. (copy-file result output))
  186. (x
  187. (error "did not find a single result file" x))))
  188. (begin
  189. (mkdir output)
  190. (copy-recursively "xchg" output)))))
  191. (define* (register-closure prefix closure
  192. #:key
  193. (schema (sql-schema)))
  194. "Register CLOSURE in PREFIX, where PREFIX is the directory name of the
  195. target store and CLOSURE is the name of a file containing a reference graph as
  196. produced by #:references-graphs."
  197. (let ((items (call-with-input-file closure read-reference-graph)))
  198. (parameterize ((sql-schema schema))
  199. (with-database (store-database-file #:prefix prefix) db
  200. (register-items db items
  201. #:prefix prefix
  202. #:registration-time %epoch)))))
  203. ;;;
  204. ;;; Partitions.
  205. ;;;
  206. (define-record-type* <partition> partition make-partition
  207. partition?
  208. (device partition-device (default #f))
  209. (size partition-size)
  210. (file-system partition-file-system (default "ext4"))
  211. (file-system-options partition-file-system-options ;passed to 'mkfs.FS'
  212. (default '()))
  213. (label partition-label (default #f))
  214. (uuid partition-uuid (default #f))
  215. (flags partition-flags (default '()))
  216. (initializer partition-initializer (default (const #t))))
  217. (define (estimated-partition-size graphs)
  218. "Return the estimated size of a partition that can store the store items
  219. given by GRAPHS, a list of file names produced by #:references-graphs."
  220. ;; Simply add a 25% overhead.
  221. (round (* 1.25 (closure-size graphs))))
  222. (define* (initialize-partition-table device partitions
  223. #:key
  224. (label-type "msdos")
  225. (offset (expt 2 20)))
  226. "Create on DEVICE a partition table of type LABEL-TYPE, containing the given
  227. PARTITIONS (a list of <partition> objects), starting at OFFSET bytes. On
  228. success, return PARTITIONS with their 'device' field changed to reflect their
  229. actual /dev name based on DEVICE."
  230. (define (partition-options part offset index)
  231. (cons* "mkpart" "primary" "ext2"
  232. (format #f "~aB" offset)
  233. (format #f "~aB" (+ offset (partition-size part)))
  234. (append-map (lambda (flag)
  235. (list "set" (number->string index)
  236. (symbol->string flag) "on"))
  237. (partition-flags part))))
  238. (define (options partitions offset)
  239. (let loop ((partitions partitions)
  240. (offset offset)
  241. (index 1)
  242. (result '()))
  243. (match partitions
  244. (()
  245. (concatenate (reverse result)))
  246. ((head tail ...)
  247. (loop tail
  248. ;; Leave one sector (512B) between partitions to placate
  249. ;; Parted.
  250. (+ offset 512 (partition-size head))
  251. (+ 1 index)
  252. (cons (partition-options head offset index)
  253. result))))))
  254. (format #t "creating partition table with ~a partitions (~a)...\n"
  255. (length partitions)
  256. (string-join (map (compose (cut string-append <> " MiB")
  257. number->string
  258. (lambda (size)
  259. (round (/ size (expt 2. 20))))
  260. partition-size)
  261. partitions)
  262. ", "))
  263. (apply invoke "parted" "--script"
  264. device "mklabel" label-type
  265. (options partitions offset))
  266. ;; Set the 'device' field of each partition.
  267. (reverse
  268. (fold2 (lambda (part result index)
  269. (values (cons (partition
  270. (inherit part)
  271. (device (string-append device
  272. (number->string index))))
  273. result)
  274. (+ 1 index)))
  275. '()
  276. 1
  277. partitions)))
  278. (define MS_BIND 4096) ; <sys/mounts.h> again!
  279. (define* (create-ext-file-system partition type
  280. #:key label uuid (options '()))
  281. "Create an ext-family file system of TYPE on PARTITION. If LABEL is true,
  282. use that as the volume name. If UUID is true, use it as the partition UUID."
  283. (format #t "creating ~a partition... ~@[label: ~s~] ~@[uuid: ~s~]\n"
  284. type label (and uuid (uuid->string uuid)))
  285. (apply invoke (string-append "mkfs." type)
  286. "-F" partition
  287. `(,@(if label
  288. `("-L" ,label)
  289. '())
  290. ,@(if uuid
  291. `("-U" ,(uuid->string uuid))
  292. '())
  293. ,@options)))
  294. (define* (create-fat-file-system partition
  295. #:key label uuid (options '()))
  296. "Create a FAT file system on PARTITION. The number of File Allocation Tables
  297. will be determined based on file system size. If LABEL is true, use that as the
  298. volume name."
  299. ;; FIXME: UUID is ignored!
  300. (format #t "creating FAT partition...\n")
  301. (apply invoke "mkfs.fat" partition
  302. (append (if label `("-n" ,label) '()) options)))
  303. (define* (format-partition partition type
  304. #:key label uuid (options '()))
  305. "Create a file system TYPE on PARTITION. If LABEL is true, use that as the
  306. volume name. Options is a list of command-line options passed to 'mkfs.FS'."
  307. (cond ((string-prefix? "ext" type)
  308. (create-ext-file-system partition type #:label label #:uuid uuid
  309. #:options options))
  310. ((or (string-prefix? "fat" type) (string= "vfat" type))
  311. (create-fat-file-system partition #:label label #:uuid uuid
  312. #:options options))
  313. (else (error "Unsupported file system."))))
  314. (define (initialize-partition partition)
  315. "Format PARTITION, a <partition> object with a non-#f 'device' field, mount
  316. it, run its initializer, and unmount it."
  317. (let ((target "/fs"))
  318. (format-partition (partition-device partition)
  319. (partition-file-system partition)
  320. #:label (partition-label partition)
  321. #:uuid (partition-uuid partition)
  322. #:options (partition-file-system-options partition))
  323. (mkdir-p target)
  324. (mount (partition-device partition) target
  325. (partition-file-system partition))
  326. ((partition-initializer partition) target)
  327. (umount target)
  328. partition))
  329. (define* (root-partition-initializer #:key (closures '())
  330. copy-closures?
  331. (register-closures? #t)
  332. system-directory
  333. (deduplicate? #t)
  334. (make-device-nodes
  335. make-essential-device-nodes)
  336. (extra-directives '()))
  337. "Return a procedure to initialize a root partition.
  338. If REGISTER-CLOSURES? is true, register all of CLOSURES in the partition's
  339. store. If DEDUPLICATE? is true, then also deduplicate files common to
  340. CLOSURES and the rest of the store when registering the closures. If
  341. COPY-CLOSURES? is true, copy all of CLOSURES to the partition.
  342. SYSTEM-DIRECTORY is the name of the directory of the 'system' derivation.
  343. EXTRA-DIRECTIVES is an optional list of directives to populate the root file
  344. system that is passed to 'populate-root-file-system'."
  345. (lambda (target)
  346. (define target-store
  347. (string-append target (%store-directory)))
  348. (when copy-closures?
  349. ;; Populate the store.
  350. (populate-store (map (cut string-append "/xchg/" <>) closures)
  351. target
  352. #:deduplicate? deduplicate?))
  353. ;; Populate /dev.
  354. (make-device-nodes target)
  355. ;; Optionally, register the inputs in the image's store.
  356. (when register-closures?
  357. (unless copy-closures?
  358. ;; XXX: 'register-closure' wants to palpate the things it registers, so
  359. ;; bind-mount the store on the target.
  360. (mkdir-p target-store)
  361. (mount (%store-directory) target-store "" MS_BIND))
  362. (display "registering closures...\n")
  363. (for-each (lambda (closure)
  364. (register-closure target
  365. (string-append "/xchg/" closure)))
  366. closures)
  367. (unless copy-closures?
  368. (umount target-store)))
  369. ;; Add the non-store directories and files.
  370. (display "populating...\n")
  371. (populate-root-file-system system-directory target
  372. #:extras extra-directives)
  373. ;; 'register-closure' resets timestamps and everything, so no need to do it
  374. ;; once more in that case.
  375. (unless register-closures?
  376. ;; 'reset-timestamps' also resets file permissions; do that everywhere
  377. ;; except on /dev so that /dev/null remains writable, etc.
  378. (for-each (lambda (directory)
  379. (reset-timestamps (string-append target "/" directory)))
  380. (scandir target
  381. (match-lambda
  382. ((or "." ".." "dev") #f)
  383. (_ #t))))
  384. (reset-timestamps (string-append target "/dev")
  385. #:preserve-permissions? #t))))
  386. (define (register-bootcfg-root target bootcfg)
  387. "On file system TARGET, register BOOTCFG as a GC root."
  388. (let ((directory (string-append target "/var/guix/gcroots")))
  389. (mkdir-p directory)
  390. (symlink bootcfg (string-append directory "/bootcfg"))))
  391. (define* (initialize-hard-disk device
  392. #:key
  393. bootloader-package
  394. bootcfg
  395. bootcfg-location
  396. bootloader-installer
  397. (grub-efi #f)
  398. (partitions '()))
  399. "Initialize DEVICE as a disk containing all the <partition> objects listed
  400. in PARTITIONS, and using BOOTCFG as its bootloader configuration file.
  401. Each partition is initialized by calling its 'initializer' procedure,
  402. passing it a directory name where it is mounted."
  403. (define (partition-bootable? partition)
  404. "Return the first partition found with the boot flag set."
  405. (member 'boot (partition-flags partition)))
  406. (define (partition-esp? partition)
  407. "Return the first EFI System Partition."
  408. (member 'esp (partition-flags partition)))
  409. (let* ((partitions (initialize-partition-table device partitions))
  410. (root (find partition-bootable? partitions))
  411. (esp (find partition-esp? partitions))
  412. (target "/fs"))
  413. (unless root
  414. (error "no bootable partition specified" partitions))
  415. (for-each initialize-partition partitions)
  416. (display "mounting root partition...\n")
  417. (mkdir-p target)
  418. (mount (partition-device root) target (partition-file-system root))
  419. (install-boot-config bootcfg bootcfg-location target)
  420. (when bootloader-installer
  421. (display "installing bootloader...\n")
  422. (bootloader-installer bootloader-package device target))
  423. (when esp
  424. ;; Mount the ESP somewhere and install GRUB UEFI image.
  425. (let ((mount-point (string-append target "/boot/efi")))
  426. (display "mounting EFI system partition...\n")
  427. (mkdir-p mount-point)
  428. (mount (partition-device esp) mount-point
  429. (partition-file-system esp))
  430. (display "creating EFI firmware image...")
  431. (install-efi-loader grub-efi mount-point)
  432. (display "done.\n")
  433. (umount mount-point)))
  434. ;; Register BOOTCFG as a GC root.
  435. (register-bootcfg-root target bootcfg)
  436. (umount target)))
  437. ;;; vm.scm ends here