vm.scm 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  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>
  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. (deduplicate? #t) (reset-timestamps? #t)
  194. (schema (sql-schema)))
  195. "Register CLOSURE in PREFIX, where PREFIX is the directory name of the
  196. target store and CLOSURE is the name of a file containing a reference graph as
  197. produced by #:references-graphs.. As a side effect, if RESET-TIMESTAMPS? is
  198. true, reset timestamps on store files and, if DEDUPLICATE? is true,
  199. deduplicates files common to CLOSURE and the rest of PREFIX."
  200. (let ((items (call-with-input-file closure read-reference-graph)))
  201. (parameterize ((sql-schema schema))
  202. (with-database (store-database-file #:prefix prefix) db
  203. (register-items db items
  204. #:prefix prefix
  205. #:deduplicate? deduplicate?
  206. #:reset-timestamps? reset-timestamps?
  207. #:registration-time %epoch)))))
  208. ;;;
  209. ;;; Partitions.
  210. ;;;
  211. (define-record-type* <partition> partition make-partition
  212. partition?
  213. (device partition-device (default #f))
  214. (size partition-size)
  215. (file-system partition-file-system (default "ext4"))
  216. (file-system-options partition-file-system-options ;passed to 'mkfs.FS'
  217. (default '()))
  218. (label partition-label (default #f))
  219. (uuid partition-uuid (default #f))
  220. (flags partition-flags (default '()))
  221. (initializer partition-initializer (default (const #t))))
  222. (define (estimated-partition-size graphs)
  223. "Return the estimated size of a partition that can store the store items
  224. given by GRAPHS, a list of file names produced by #:references-graphs."
  225. ;; Simply add a 25% overhead.
  226. (round (* 1.25 (closure-size graphs))))
  227. (define* (initialize-partition-table device partitions
  228. #:key
  229. (label-type "msdos")
  230. (offset (expt 2 20)))
  231. "Create on DEVICE a partition table of type LABEL-TYPE, containing the given
  232. PARTITIONS (a list of <partition> objects), starting at OFFSET bytes. On
  233. success, return PARTITIONS with their 'device' field changed to reflect their
  234. actual /dev name based on DEVICE."
  235. (define (partition-options part offset index)
  236. (cons* "mkpart" "primary" "ext2"
  237. (format #f "~aB" offset)
  238. (format #f "~aB" (+ offset (partition-size part)))
  239. (append-map (lambda (flag)
  240. (list "set" (number->string index)
  241. (symbol->string flag) "on"))
  242. (partition-flags part))))
  243. (define (options partitions offset)
  244. (let loop ((partitions partitions)
  245. (offset offset)
  246. (index 1)
  247. (result '()))
  248. (match partitions
  249. (()
  250. (concatenate (reverse result)))
  251. ((head tail ...)
  252. (loop tail
  253. ;; Leave one sector (512B) between partitions to placate
  254. ;; Parted.
  255. (+ offset 512 (partition-size head))
  256. (+ 1 index)
  257. (cons (partition-options head offset index)
  258. result))))))
  259. (format #t "creating partition table with ~a partitions (~a)...\n"
  260. (length partitions)
  261. (string-join (map (compose (cut string-append <> " MiB")
  262. number->string
  263. (lambda (size)
  264. (round (/ size (expt 2. 20))))
  265. partition-size)
  266. partitions)
  267. ", "))
  268. (apply invoke "parted" "--script"
  269. device "mklabel" label-type
  270. (options partitions offset))
  271. ;; Set the 'device' field of each partition.
  272. (reverse
  273. (fold2 (lambda (part result index)
  274. (values (cons (partition
  275. (inherit part)
  276. (device (string-append device
  277. (number->string index))))
  278. result)
  279. (+ 1 index)))
  280. '()
  281. 1
  282. partitions)))
  283. (define MS_BIND 4096) ; <sys/mounts.h> again!
  284. (define* (create-ext-file-system partition type
  285. #:key label uuid (options '()))
  286. "Create an ext-family file system of TYPE on PARTITION. If LABEL is true,
  287. use that as the volume name. If UUID is true, use it as the partition UUID."
  288. (format #t "creating ~a partition... ~@[label: ~s~] ~@[uuid: ~s~]\n"
  289. type label (and uuid (uuid->string uuid)))
  290. (apply invoke (string-append "mkfs." type)
  291. "-F" partition
  292. `(,@(if label
  293. `("-L" ,label)
  294. '())
  295. ,@(if uuid
  296. `("-U" ,(uuid->string uuid))
  297. '())
  298. ,@options)))
  299. (define* (create-fat-file-system partition
  300. #:key label uuid (options '()))
  301. "Create a FAT file system on PARTITION. The number of File Allocation Tables
  302. will be determined based on file system size. If LABEL is true, use that as the
  303. volume name."
  304. ;; FIXME: UUID is ignored!
  305. (format #t "creating FAT partition...\n")
  306. (apply invoke "mkfs.fat" partition
  307. (append (if label `("-n" ,label) '()) options)))
  308. (define* (format-partition partition type
  309. #:key label uuid (options '()))
  310. "Create a file system TYPE on PARTITION. If LABEL is true, use that as the
  311. volume name. Options is a list of command-line options passed to 'mkfs.FS'."
  312. (cond ((string-prefix? "ext" type)
  313. (create-ext-file-system partition type #:label label #:uuid uuid
  314. #:options options))
  315. ((or (string-prefix? "fat" type) (string= "vfat" type))
  316. (create-fat-file-system partition #:label label #:uuid uuid
  317. #:options options))
  318. (else (error "Unsupported file system."))))
  319. (define (initialize-partition partition)
  320. "Format PARTITION, a <partition> object with a non-#f 'device' field, mount
  321. it, run its initializer, and unmount it."
  322. (let ((target "/fs"))
  323. (format-partition (partition-device partition)
  324. (partition-file-system partition)
  325. #:label (partition-label partition)
  326. #:uuid (partition-uuid partition)
  327. #:options (partition-file-system-options partition))
  328. (mkdir-p target)
  329. (mount (partition-device partition) target
  330. (partition-file-system partition))
  331. ((partition-initializer partition) target)
  332. (umount target)
  333. partition))
  334. (define* (root-partition-initializer #:key (closures '())
  335. copy-closures?
  336. (register-closures? #t)
  337. system-directory
  338. (deduplicate? #t)
  339. (make-device-nodes
  340. make-essential-device-nodes)
  341. (extra-directives '()))
  342. "Return a procedure to initialize a root partition.
  343. If REGISTER-CLOSURES? is true, register all of CLOSURES in the partition's
  344. store. If DEDUPLICATE? is true, then also deduplicate files common to
  345. CLOSURES and the rest of the store when registering the closures. If
  346. COPY-CLOSURES? is true, copy all of CLOSURES to the partition.
  347. SYSTEM-DIRECTORY is the name of the directory of the 'system' derivation.
  348. EXTRA-DIRECTIVES is an optional list of directives to populate the root file
  349. system that is passed to 'populate-root-file-system'."
  350. (lambda (target)
  351. (define target-store
  352. (string-append target (%store-directory)))
  353. (when copy-closures?
  354. ;; Populate the store.
  355. (populate-store (map (cut string-append "/xchg/" <>) closures)
  356. target))
  357. ;; Populate /dev.
  358. (make-device-nodes target)
  359. ;; Optionally, register the inputs in the image's store.
  360. (when register-closures?
  361. (unless copy-closures?
  362. ;; XXX: 'register-closure' wants to palpate the things it registers, so
  363. ;; bind-mount the store on the target.
  364. (mkdir-p target-store)
  365. (mount (%store-directory) target-store "" MS_BIND))
  366. (display "registering closures...\n")
  367. (for-each (lambda (closure)
  368. (register-closure target
  369. (string-append "/xchg/" closure)
  370. #:reset-timestamps? copy-closures?
  371. #:deduplicate? deduplicate?))
  372. closures)
  373. (unless copy-closures?
  374. (umount target-store)))
  375. ;; Add the non-store directories and files.
  376. (display "populating...\n")
  377. (populate-root-file-system system-directory target
  378. #:extras extra-directives)
  379. ;; 'register-closure' resets timestamps and everything, so no need to do it
  380. ;; once more in that case.
  381. (unless register-closures?
  382. ;; 'reset-timestamps' also resets file permissions; do that everywhere
  383. ;; except on /dev so that /dev/null remains writable, etc.
  384. (for-each (lambda (directory)
  385. (reset-timestamps (string-append target "/" directory)))
  386. (scandir target
  387. (match-lambda
  388. ((or "." ".." "dev") #f)
  389. (_ #t))))
  390. (reset-timestamps (string-append target "/dev")
  391. #:preserve-permissions? #t))))
  392. (define (register-bootcfg-root target bootcfg)
  393. "On file system TARGET, register BOOTCFG as a GC root."
  394. (let ((directory (string-append target "/var/guix/gcroots")))
  395. (mkdir-p directory)
  396. (symlink bootcfg (string-append directory "/bootcfg"))))
  397. (define* (initialize-hard-disk device
  398. #:key
  399. bootloader-package
  400. bootcfg
  401. bootcfg-location
  402. bootloader-installer
  403. (grub-efi #f)
  404. (partitions '()))
  405. "Initialize DEVICE as a disk containing all the <partition> objects listed
  406. in PARTITIONS, and using BOOTCFG as its bootloader configuration file.
  407. Each partition is initialized by calling its 'initializer' procedure,
  408. passing it a directory name where it is mounted."
  409. (define (partition-bootable? partition)
  410. "Return the first partition found with the boot flag set."
  411. (member 'boot (partition-flags partition)))
  412. (define (partition-esp? partition)
  413. "Return the first EFI System Partition."
  414. (member 'esp (partition-flags partition)))
  415. (let* ((partitions (initialize-partition-table device partitions))
  416. (root (find partition-bootable? partitions))
  417. (esp (find partition-esp? partitions))
  418. (target "/fs"))
  419. (unless root
  420. (error "no bootable partition specified" partitions))
  421. (for-each initialize-partition partitions)
  422. (display "mounting root partition...\n")
  423. (mkdir-p target)
  424. (mount (partition-device root) target (partition-file-system root))
  425. (install-boot-config bootcfg bootcfg-location target)
  426. (when bootloader-installer
  427. (display "installing bootloader...\n")
  428. (bootloader-installer bootloader-package device target))
  429. (when esp
  430. ;; Mount the ESP somewhere and install GRUB UEFI image.
  431. (let ((mount-point (string-append target "/boot/efi")))
  432. (display "mounting EFI system partition...\n")
  433. (mkdir-p mount-point)
  434. (mount (partition-device esp) mount-point
  435. (partition-file-system esp))
  436. (display "creating EFI firmware image...")
  437. (install-efi-loader grub-efi mount-point)
  438. (display "done.\n")
  439. (umount mount-point)))
  440. ;; Register BOOTCFG as a GC root.
  441. (register-bootcfg-root target bootcfg)
  442. (umount target)))
  443. ;;; vm.scm ends here