guix system: "describe" displays multiboot info.
[jackhill/guix/guix.git] / guix / scripts / system.scm
1 ;;; GNU Guix --- Functional package management for GNU
2 ;;; Copyright © 2014, 2015, 2016, 2017, 2018, 2019, 2020 Ludovic Courtès <ludo@gnu.org>
3 ;;; Copyright © 2016 Alex Kost <alezost@gmail.com>
4 ;;; Copyright © 2016, 2017, 2018 Chris Marusich <cmmarusich@gmail.com>
5 ;;; Copyright © 2017, 2019 Mathieu Othacehe <m.othacehe@gmail.com>
6 ;;; Copyright © 2018 Ricardo Wurmus <rekado@elephly.net>
7 ;;; Copyright © 2019 Christopher Baines <mail@cbaines.net>
8 ;;; Copyright © 2020 Jan (janneke) Nieuwenhuizen <janneke@gnu.org>
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
25 (define-module (guix scripts system)
26 #:use-module (guix config)
27 #:use-module (guix ui)
28 #:use-module ((guix status) #:select (with-status-verbosity))
29 #:use-module (guix store)
30 #:autoload (guix store database) (register-path)
31 #:use-module (guix describe)
32 #:use-module (guix grafts)
33 #:use-module (guix gexp)
34 #:use-module (guix derivations)
35 #:use-module (guix packages)
36 #:use-module (guix utils)
37 #:use-module (guix monads)
38 #:use-module (guix records)
39 #:use-module (guix profiles)
40 #:use-module (guix scripts)
41 #:use-module (guix channels)
42 #:use-module (guix scripts build)
43 #:autoload (guix scripts package) (delete-generations
44 delete-matching-generations)
45 #:autoload (guix scripts pull) (channel-commit-hyperlink)
46 #:use-module (guix graph)
47 #:use-module (guix scripts graph)
48 #:use-module (guix scripts system reconfigure)
49 #:use-module (guix build utils)
50 #:use-module (guix progress)
51 #:use-module ((guix build syscalls) #:select (terminal-columns))
52 #:use-module (gnu build install)
53 #:autoload (gnu build file-systems)
54 (find-partition-by-label find-partition-by-uuid)
55 #:autoload (gnu build linux-modules)
56 (device-module-aliases matching-modules)
57 #:use-module (gnu system linux-initrd)
58 #:use-module (gnu image)
59 #:use-module (gnu system)
60 #:use-module (gnu bootloader)
61 #:use-module (gnu system file-systems)
62 #:use-module (gnu system image)
63 #:use-module (gnu system mapped-devices)
64 #:use-module (gnu system linux-container)
65 #:use-module (gnu system uuid)
66 #:use-module (gnu system vm)
67 #:use-module (gnu services)
68 #:use-module (gnu services shepherd)
69 #:use-module (gnu services herd)
70 #:use-module (srfi srfi-1)
71 #:use-module (srfi srfi-11)
72 #:use-module (srfi srfi-19)
73 #:use-module (srfi srfi-26)
74 #:use-module (srfi srfi-34)
75 #:use-module (srfi srfi-35)
76 #:use-module (srfi srfi-37)
77 #:use-module (ice-9 format)
78 #:use-module (ice-9 match)
79 #:use-module (rnrs bytevectors)
80 #:export (guix-system
81 read-operating-system))
82
83 \f
84 ;;;
85 ;;; Operating system declaration.
86 ;;;
87
88 (define %user-module
89 ;; Module in which the machine description file is loaded.
90 (make-user-module '((gnu system)
91 (gnu services)
92 (gnu system shadow))))
93
94 (define (read-operating-system file)
95 "Read the operating-system declaration from FILE and return it."
96 (load* file %user-module))
97
98 \f
99 ;;;
100 ;;; Installation.
101 ;;;
102
103 (define-syntax-rule (save-load-path-excursion body ...)
104 "Save the current values of '%load-path' and '%load-compiled-path', run
105 BODY..., and restore them."
106 (let ((path %load-path)
107 (cpath %load-compiled-path))
108 (dynamic-wind
109 (const #t)
110 (lambda ()
111 body ...)
112 (lambda ()
113 (set! %load-path path)
114 (set! %load-compiled-path cpath)))))
115
116 (define-syntax-rule (save-environment-excursion body ...)
117 "Save the current environment variables, run BODY..., and restore them."
118 (let ((env (environ)))
119 (dynamic-wind
120 (const #t)
121 (lambda ()
122 body ...)
123 (lambda ()
124 (environ env)))))
125
126 (define topologically-sorted*
127 (store-lift topologically-sorted))
128
129
130 (define* (copy-item item references target
131 #:key (log-port (current-error-port)))
132 "Copy ITEM to the store under root directory TARGET and register it with
133 REFERENCES as its set of references."
134 (let ((dest (string-append target item))
135 (state (string-append target "/var/guix")))
136 (format log-port "copying '~a'...~%" item)
137
138 ;; Remove DEST if it exists to make sure that (1) we do not fail badly
139 ;; while trying to overwrite it (see <http://bugs.gnu.org/20722>), and
140 ;; (2) we end up with the right contents.
141 (when (false-if-exception (lstat dest))
142 (for-each make-file-writable
143 (find-files dest (lambda (file stat)
144 (eq? 'directory (stat:type stat)))
145 #:directories? #t))
146 (delete-file-recursively dest))
147
148 (copy-recursively item dest
149 #:log (%make-void-port "w"))
150
151 ;; Register ITEM; as a side-effect, it resets timestamps, etc.
152 ;; Explicitly use "TARGET/var/guix" as the state directory, to avoid
153 ;; reproducing the user's current settings; see
154 ;; <http://bugs.gnu.org/18049>.
155 (unless (register-path item
156 #:prefix target
157 #:state-directory state
158 #:references references)
159 (leave (G_ "failed to register '~a' under '~a'~%")
160 item target))))
161
162 (define* (copy-closure item target
163 #:key (log-port (current-error-port)))
164 "Copy ITEM and all its dependencies to the store under root directory
165 TARGET, and register them."
166 (mlet* %store-monad ((to-copy (topologically-sorted* (list item)))
167 (refs (mapm %store-monad references* to-copy))
168 (info (mapm %store-monad query-path-info*
169 (delete-duplicates
170 (append to-copy (concatenate refs)))))
171 (size -> (reduce + 0 (map path-info-nar-size info))))
172 (define progress-bar
173 (progress-reporter/bar (length to-copy)
174 (format #f (G_ "copying to '~a'...")
175 target)))
176
177 (check-available-space size target)
178
179 (call-with-progress-reporter progress-bar
180 (lambda (report)
181 (let ((void (%make-void-port "w")))
182 (for-each (lambda (item refs)
183 (copy-item item refs target #:log-port void)
184 (report))
185 to-copy refs))))
186
187 (return *unspecified*)))
188
189 (define* (install os-drv target
190 #:key (log-port (current-output-port))
191 install-bootloader? bootloader bootcfg)
192 "Copy the closure of BOOTCFG, which includes the output of OS-DRV, to
193 directory TARGET. TARGET must be an absolute directory name since that's what
194 'register-path' expects.
195
196 When INSTALL-BOOTLOADER? is true, install bootloader using BOOTCFG."
197 (define (maybe-copy to-copy)
198 (with-monad %store-monad
199 (if (string=? target "/")
200 (begin
201 (warning (G_ "initializing the current root file system~%"))
202 (return #t))
203 (begin
204 ;; Make sure the target store exists.
205 (mkdir-p (string-append target (%store-prefix)))
206
207 ;; Copy items to the new store.
208 (copy-closure to-copy target #:log-port log-port)))))
209
210 ;; Make sure TARGET is root-owned when running as root, but still allow
211 ;; non-root uses (useful for testing.) See
212 ;; <http://lists.gnu.org/archive/html/guix-devel/2015-05/msg00452.html>.
213 (if (zero? (geteuid))
214 (chown target 0 0)
215 (warning (G_ "not running as 'root', so \
216 the ownership of '~a' may be incorrect!~%")
217 target))
218
219 ;; If a previous installation was attempted, make sure we start anew; in
220 ;; particular, we don't want to keep a store database that might not
221 ;; correspond to what we're actually putting in the store.
222 (let ((state (string-append target "/var/guix")))
223 (when (file-exists? state)
224 (delete-file-recursively state)))
225
226 (chmod target #o755)
227 (let ((os-dir (derivation->output-path os-drv))
228 (format (lift format %store-monad))
229 (populate (lift2 populate-root-file-system %store-monad)))
230
231 (mlet %store-monad ((bootcfg (lower-object bootcfg)))
232 (mbegin %store-monad
233 ;; Copy the closure of BOOTCFG, which includes OS-DIR,
234 ;; eventual background image and so on.
235 (maybe-copy (derivation->output-path bootcfg))
236
237 ;; Create a bunch of additional files.
238 (format log-port "populating '~a'...~%" target)
239 (populate os-dir target)
240
241 (mwhen install-bootloader?
242 (install-bootloader local-eval bootloader bootcfg
243 #:target target)
244 (return
245 (info (G_ "bootloader successfully installed on '~a'~%")
246 (bootloader-configuration-target bootloader))))))))
247
248 \f
249 ;;;
250 ;;; Reconfiguration.
251 ;;;
252
253 (define %system-profile
254 ;; The system profile.
255 (string-append %state-directory "/profiles/system"))
256
257 (define-syntax-rule (with-shepherd-error-handling mbody ...)
258 "Catch and report Shepherd errors that arise when binding MBODY, a monadic
259 expression in %STORE-MONAD."
260 (lambda (store)
261 (catch 'system-error
262 (lambda ()
263 (guard (c ((shepherd-error? c)
264 (values (report-shepherd-error c) store)))
265 (values (run-with-store store (mbegin %store-monad mbody ...))
266 store)))
267 (lambda (key proc format-string format-args errno . rest)
268 (warning (G_ "while talking to shepherd: ~a~%")
269 (apply format #f format-string format-args))
270 (values #f store)))))
271
272 (define (report-shepherd-error error)
273 "Report ERROR, a '&shepherd-error' error condition object."
274 (cond ((service-not-found-error? error)
275 (report-error (G_ "service '~a' could not be found~%")
276 (service-not-found-error-service error)))
277 ((action-not-found-error? error)
278 (report-error (G_ "service '~a' does not have an action '~a'~%")
279 (action-not-found-error-service error)
280 (action-not-found-error-action error)))
281 ((action-exception-error? error)
282 (report-error (G_ "exception caught while executing '~a' \
283 on service '~a':~%")
284 (action-exception-error-action error)
285 (action-exception-error-service error))
286 (print-exception (current-error-port) #f
287 (action-exception-error-key error)
288 (action-exception-error-arguments error)))
289 ((unknown-shepherd-error? error)
290 (report-error (G_ "something went wrong: ~s~%")
291 (unknown-shepherd-error-sexp error)))
292 ((shepherd-error? error)
293 (report-error (G_ "shepherd error~%")))
294 ((not error) ;not an error
295 #t)))
296
297 (define-syntax-rule (unless-file-not-found exp)
298 (catch 'system-error
299 (lambda ()
300 exp)
301 (lambda args
302 (if (= ENOENT (system-error-errno args))
303 #f
304 (apply throw args)))))
305
306 (define (seconds->string seconds)
307 "Return a string representing the date for SECONDS."
308 (let ((time (make-time time-utc 0 seconds)))
309 (date->string (time-utc->date time)
310 "~Y-~m-~d ~H:~M")))
311
312 (define* (profile-boot-parameters #:optional (profile %system-profile)
313 (numbers
314 (reverse (generation-numbers profile))))
315 "Return a list of 'boot-parameters' for the generations of PROFILE specified
316 by NUMBERS, which is a list of generation numbers. The list is ordered from
317 the most recent to the oldest profiles."
318 (define (system->boot-parameters system number time)
319 (unless-file-not-found
320 (let* ((params (read-boot-parameters-file system))
321 (label (boot-parameters-label params)))
322 (boot-parameters
323 (inherit params)
324 (label (string-append label " (#"
325 (number->string number) ", "
326 (seconds->string time) ")"))))))
327 (let* ((systems (map (cut generation-file-name profile <>)
328 numbers))
329 (times (map (lambda (system)
330 (unless-file-not-found
331 (stat:mtime (lstat system))))
332 systems)))
333 (filter-map system->boot-parameters systems numbers times)))
334
335 \f
336 ;;;
337 ;;; Roll-back.
338 ;;;
339 (define (roll-back-system store)
340 "Roll back the system profile to its previous generation. STORE is an open
341 connection to the store."
342 (switch-to-system-generation store "-1"))
343
344 \f
345 ;;;
346 ;;; Switch generations.
347 ;;;
348 (define (switch-to-system-generation store spec)
349 "Switch the system profile to the generation specified by SPEC, and
350 re-install bootloader with a configuration file that uses the specified system
351 generation as its default entry. STORE is an open connection to the store."
352 (let ((number (relative-generation-spec->number %system-profile spec)))
353 (if number
354 (begin
355 (reinstall-bootloader store number)
356 (switch-to-generation* %system-profile number))
357 (leave (G_ "cannot switch to system generation '~a'~%") spec))))
358
359 (define* (system-bootloader-name #:optional (system %system-profile))
360 "Return the bootloader name stored in SYSTEM's \"parameters\" file."
361 (let ((params (unless-file-not-found
362 (read-boot-parameters-file system))))
363 (boot-parameters-bootloader-name params)))
364
365 (define (reinstall-bootloader store number)
366 "Re-install bootloader for existing system profile generation NUMBER.
367 STORE is an open connection to the store."
368 (let* ((generation (generation-file-name %system-profile number))
369 ;; Detect the bootloader used in %system-profile.
370 (bootloader (lookup-bootloader-by-name (system-bootloader-name)))
371
372 ;; Use the detected bootloader with default configuration.
373 ;; It will be enough to allow the system to boot.
374 (bootloader-config (bootloader-configuration
375 (bootloader bootloader)))
376
377 ;; Make the specified system generation the default entry.
378 (params (first (profile-boot-parameters %system-profile
379 (list number))))
380 (old-generations
381 (delv number (reverse (generation-numbers %system-profile))))
382 (old-params (profile-boot-parameters
383 %system-profile old-generations))
384 (entries (cons (boot-parameters->menu-entry params)
385 (boot-parameters-bootloader-menu-entries params)))
386 (old-entries (map boot-parameters->menu-entry old-params)))
387 (run-with-store store
388 (mlet* %store-monad
389 ((bootcfg (lower-object
390 ((bootloader-configuration-file-generator bootloader)
391 bootloader-config entries
392 #:old-entries old-entries)))
393 (drvs -> (list bootcfg)))
394 (mbegin %store-monad
395 (built-derivations drvs)
396 ;; Only install bootloader configuration file.
397 (install-bootloader local-eval bootloader-config bootcfg
398 #:run-installer? #f))))))
399
400 \f
401 ;;;
402 ;;; Graphs.
403 ;;;
404
405 (define (service-node-label service)
406 "Return a label to represent SERVICE."
407 (let ((type (service-kind service))
408 (value (service-value service)))
409 (string-append (symbol->string (service-type-name type))
410 (cond ((or (number? value) (symbol? value))
411 (string-append " " (object->string value)))
412 ((string? value)
413 (string-append " " value))
414 ((file-system? value)
415 (string-append " " (file-system-mount-point value)))
416 (else
417 "")))))
418
419 (define (service-node-type services)
420 "Return a node type for SERVICES. Since <service> instances are not
421 self-contained (they express dependencies on service types, not on services),
422 we have to create the 'edges' procedure dynamically as a function of the full
423 list of services."
424 (node-type
425 (name "service")
426 (description "the DAG of services")
427 (identifier (lift1 object-address %store-monad))
428 (label service-node-label)
429 (edges (lift1 (service-back-edges services) %store-monad))))
430
431 (define (shepherd-service-node-label service)
432 "Return a label for a node representing a <shepherd-service>."
433 (string-join (map symbol->string (shepherd-service-provision service))))
434
435 (define (shepherd-service-node-type services)
436 "Return a node type for SERVICES, a list of <shepherd-service>."
437 (node-type
438 (name "shepherd-service")
439 (description "the dependency graph of shepherd services")
440 (identifier (lift1 shepherd-service-node-label %store-monad))
441 (label shepherd-service-node-label)
442 (edges (lift1 (shepherd-service-back-edges services) %store-monad))))
443
444 \f
445 ;;;
446 ;;; Generations.
447 ;;;
448
449 (define (sexp->channel sexp)
450 "Return the channel corresponding to SEXP, an sexp as found in the
451 \"provenance\" file produced by 'provenance-service-type'."
452 (match sexp
453 (('channel ('name name)
454 ('url url)
455 ('branch branch)
456 ('commit commit)
457 rest ...)
458 ;; XXX: In the future REST may include a channel introduction.
459 (channel (name name) (url url)
460 (branch branch) (commit commit)))))
461
462 (define* (display-system-generation number
463 #:optional (profile %system-profile))
464 "Display a summary of system generation NUMBER in a human-readable format."
465 (define (display-channel channel)
466 (format #t " ~a:~%" (channel-name channel))
467 (format #t (G_ " repository URL: ~a~%") (channel-url channel))
468 (when (channel-branch channel)
469 (format #t (G_ " branch: ~a~%") (channel-branch channel)))
470 (format #t (G_ " commit: ~a~%")
471 (if (supports-hyperlinks?)
472 (channel-commit-hyperlink channel)
473 (channel-commit channel))))
474
475 (unless (zero? number)
476 (let* ((generation (generation-file-name profile number))
477 (params (read-boot-parameters-file generation))
478 (label (boot-parameters-label params))
479 (bootloader-name (boot-parameters-bootloader-name params))
480 (root (boot-parameters-root-device params))
481 (root-device (if (bytevector? root)
482 (uuid->string root)
483 root))
484 (kernel (boot-parameters-kernel params))
485 (multiboot-modules (boot-parameters-multiboot-modules params))
486 (provenance (catch 'system-error
487 (lambda ()
488 (call-with-input-file
489 (string-append generation "/provenance")
490 read))
491 (const #f))))
492 (display-generation profile number)
493 (format #t (G_ " file name: ~a~%") generation)
494 (format #t (G_ " canonical file name: ~a~%") (readlink* generation))
495 ;; TRANSLATORS: Please preserve the two-space indentation.
496 (format #t (G_ " label: ~a~%") label)
497 (format #t (G_ " bootloader: ~a~%") bootloader-name)
498
499 ;; TRANSLATORS: The '~[', '~;', and '~]' sequences in this string must
500 ;; be preserved. They denote conditionals, such that the result will
501 ;; look like:
502 ;; root device: UUID: 12345-678
503 ;; or:
504 ;; root device: label: "my-root"
505 ;; or just:
506 ;; root device: /dev/sda3
507 (format #t (G_ " root device: ~[UUID: ~a~;label: ~s~;~a~]~%")
508 (cond ((uuid? root-device) 0)
509 ((file-system-label? root-device) 1)
510 (else 2))
511 (file-system-device->string root-device))
512
513 (format #t (G_ " kernel: ~a~%") kernel)
514
515 (match multiboot-modules
516 (() #f)
517 (((modules . _) ...)
518 (format #t (G_ " multiboot: ~a~%")
519 (string-join modules "\n "))))
520
521 (match provenance
522 (#f #t)
523 (('provenance ('version 0)
524 ('channels channels ...)
525 ('configuration-file config-file))
526 (unless (null? channels)
527 ;; TRANSLATORS: Here "channel" is the same terminology as used in
528 ;; "guix describe" and "guix pull --channels".
529 (format #t (G_ " channels:~%"))
530 (for-each display-channel (map sexp->channel channels)))
531 (when config-file
532 (format #t (G_ " configuration file: ~a~%")
533 (if (supports-hyperlinks?)
534 (file-hyperlink config-file)
535 config-file))))))))
536
537 (define* (list-generations pattern #:optional (profile %system-profile))
538 "Display in a human-readable format all the system generations matching
539 PATTERN, a string. When PATTERN is #f, display all the system generations."
540 (cond ((not (file-exists? profile)) ; XXX: race condition
541 (raise (condition (&profile-not-found-error
542 (profile profile)))))
543 ((not pattern)
544 (for-each display-system-generation (profile-generations profile)))
545 ((matching-generations pattern profile)
546 =>
547 (lambda (numbers)
548 (if (null-list? numbers)
549 (exit 1)
550 (leave-on-EPIPE
551 (for-each display-system-generation numbers)))))))
552
553 \f
554 ;;;
555 ;;; File system declaration checks.
556 ;;;
557
558 (define (check-file-system-availability file-systems)
559 "Check whether the UUIDs or partition labels that FILE-SYSTEMS refer to, if
560 any, are available. Raise an error if they're not."
561 (define relevant
562 (filter (lambda (fs)
563 (and (file-system-mount? fs)
564 (not (member (file-system-type fs)
565 %pseudo-file-system-types))
566 ;; Don't try to validate network file systems.
567 (not (string-prefix? "nfs" (file-system-type fs)))
568 (not (memq 'bind-mount (file-system-flags fs)))))
569 file-systems))
570
571 (define labeled
572 (filter (lambda (fs)
573 (file-system-label? (file-system-device fs)))
574 relevant))
575
576 (define literal
577 (filter (lambda (fs)
578 (string? (file-system-device fs)))
579 relevant))
580
581 (define uuid
582 (filter (lambda (fs)
583 (uuid? (file-system-device fs)))
584 relevant))
585
586 (define fail? #f)
587
588 (define (file-system-location* fs)
589 (location->string
590 (source-properties->location
591 (file-system-location fs))))
592
593 (let-syntax ((error (syntax-rules ()
594 ((_ args ...)
595 (begin
596 (set! fail? #t)
597 (format (current-error-port)
598 args ...))))))
599 (for-each (lambda (fs)
600 (catch 'system-error
601 (lambda ()
602 (stat (file-system-device fs)))
603 (lambda args
604 (let ((errno (system-error-errno args))
605 (device (file-system-device fs)))
606 (error (G_ "~a: error: device '~a' not found: ~a~%")
607 (file-system-location* fs) device
608 (strerror errno))
609 (unless (string-prefix? "/" device)
610 (display-hint (format #f (G_ "If '~a' is a file system
611 label, write @code{(file-system-label ~s)} in your @code{device} field.")
612 device device)))))))
613 literal)
614 (for-each (lambda (fs)
615 (let ((label (file-system-label->string
616 (file-system-device fs))))
617 (unless (find-partition-by-label label)
618 (error (G_ "~a: error: file system with label '~a' not found~%")
619 (file-system-location* fs) label))))
620 labeled)
621 (for-each (lambda (fs)
622 (unless (find-partition-by-uuid (file-system-device fs))
623 (error (G_ "~a: error: file system with UUID '~a' not found~%")
624 (file-system-location* fs)
625 (uuid->string (file-system-device fs)))))
626 uuid)
627
628 (when fail?
629 ;; Better be safe than sorry.
630 (exit 1))))
631
632 (define (check-mapped-devices os)
633 "Check that each of MAPPED-DEVICES is valid according to the 'check'
634 procedure of its type."
635 (define boot-mapped-devices
636 (operating-system-boot-mapped-devices os))
637
638 (define (needed-for-boot? md)
639 (memq md boot-mapped-devices))
640
641 (define initrd-modules
642 (operating-system-initrd-modules os))
643
644 (for-each (lambda (md)
645 (let ((check (mapped-device-kind-check
646 (mapped-device-type md))))
647 ;; We expect CHECK to raise an exception with a detailed
648 ;; '&message' if something goes wrong.
649 (check md
650 #:needed-for-boot? (needed-for-boot? md)
651 #:initrd-modules initrd-modules)))
652 (operating-system-mapped-devices os)))
653
654 (define (check-initrd-modules os)
655 "Check that modules needed by 'needed-for-boot' file systems in OS are
656 available in the initrd. Note that mapped devices are responsible for
657 checking this by themselves in their 'check' procedure."
658 (define (file-system-/dev fs)
659 (let ((device (file-system-device fs)))
660 (match device
661 ((? string?)
662 device)
663 ((? uuid?)
664 (find-partition-by-uuid device))
665 ((? file-system-label?)
666 (find-partition-by-label (file-system-label->string device))))))
667
668 (define file-systems
669 (filter file-system-needed-for-boot?
670 (operating-system-file-systems os)))
671
672 (for-each (lambda (fs)
673 (check-device-initrd-modules (file-system-/dev fs)
674 (operating-system-initrd-modules os)
675 (source-properties->location
676 (file-system-location fs))))
677 file-systems))
678
679 \f
680 ;;;
681 ;;; Action.
682 ;;;
683
684 (define* (system-derivation-for-action os base-image action
685 #:key image-size file-system-type
686 full-boot? container-shared-network?
687 mappings)
688 "Return as a monadic value the derivation for OS according to ACTION."
689 (case action
690 ((build init reconfigure)
691 (operating-system-derivation os))
692 ((container)
693 (container-script
694 os
695 #:mappings mappings
696 #:shared-network? container-shared-network?))
697 ((vm-image)
698 (system-qemu-image os #:disk-image-size image-size))
699 ((vm)
700 (system-qemu-image/shared-store-script os
701 #:full-boot? full-boot?
702 #:disk-image-size
703 (if full-boot?
704 image-size
705 (* 70 (expt 2 20)))
706 #:mappings mappings))
707 ((disk-image)
708 (lower-object
709 (system-image
710 (image
711 (inherit base-image)
712 (size image-size)
713 (operating-system os)))))
714 ((docker-image)
715 (system-docker-image os #:shared-network? container-shared-network?))))
716
717 (define (maybe-suggest-running-guix-pull)
718 "Suggest running 'guix pull' if this has never been done before."
719 ;; Check whether we're running a 'guix pull'-provided 'guix' command. When
720 ;; 'current-profile' returns #f, we may be running the globally-installed
721 ;; 'guix' and thus run the risk of deploying an older 'guix'. See
722 ;; <https://lists.gnu.org/archive/html/guix-devel/2014-08/msg00057.html>
723 (unless (or (current-profile) (getenv "GUIX_UNINSTALLED"))
724 (warning (G_ "Consider running 'guix pull' before 'reconfigure'.~%"))
725 (warning (G_ "Failing to do that may downgrade your system!~%"))))
726
727 (define (bootloader-installer-script installer
728 bootloader device target)
729 "Return a file calling INSTALLER gexp with given BOOTLOADER, DEVICE
730 and TARGET arguments."
731 (scheme-file "bootloader-installer"
732 (with-imported-modules '((gnu build bootloader)
733 (guix build utils))
734 #~(begin
735 (use-modules (gnu build bootloader)
736 (guix build utils)
737 (ice-9 binary-ports)
738 (srfi srfi-34)
739 (srfi srfi-35))
740
741 (guard (c ((message-condition? c) ;XXX: i18n
742 (format (current-error-port) "error: ~a~%"
743 (condition-message c))
744 (exit 1)))
745 (#$installer #$bootloader #$device #$target)
746 (info (G_ "bootloader successfully installed on '~a'~%")
747 #$device))))))
748
749 (define (local-eval exp)
750 "Evaluate EXP, a G-Expression, in-place."
751 (mlet* %store-monad ((lowered (lower-gexp exp))
752 (_ (built-derivations (lowered-gexp-inputs lowered))))
753 (save-load-path-excursion
754 (set! %load-path (lowered-gexp-load-path lowered))
755 (set! %load-compiled-path (lowered-gexp-load-compiled-path lowered))
756 (return (primitive-eval (lowered-gexp-sexp lowered))))))
757
758 (define* (perform-action action os
759 #:key
760 save-provenance?
761 skip-safety-checks?
762 install-bootloader?
763 dry-run? derivations-only?
764 use-substitutes? bootloader-target target
765 image-size file-system-type full-boot?
766 container-shared-network?
767 (mappings '())
768 (gc-root #f))
769 "Perform ACTION for OS. INSTALL-BOOTLOADER? specifies whether to install
770 bootloader; BOOTLOADER-TAGET is the target for the bootloader; TARGET is the
771 target root directory; IMAGE-SIZE is the size of the image to be built, for
772 the 'vm-image' and 'disk-image' actions. The root file system is created as a
773 FILE-SYSTEM-TYPE file system. FULL-BOOT? is used for the 'vm' action; it
774 determines whether to boot directly to the kernel or to the bootloader.
775 CONTAINER-SHARED-NETWORK? determines if the container will use a separate
776 network namespace.
777
778 When DERIVATIONS-ONLY? is true, print the derivation file name(s) without
779 building anything.
780
781 When GC-ROOT is a path, also make that path an indirect root of the build
782 output when building a system derivation, such as a disk image.
783
784 When SKIP-SAFETY-CHECKS? is true, skip the file system and initrd module
785 static checks."
786 (define println
787 (cut format #t "~a~%" <>))
788
789 (define menu-entries
790 (if (eq? 'init action)
791 '()
792 (map boot-parameters->menu-entry (profile-boot-parameters))))
793
794 (define bootloader
795 (operating-system-bootloader os))
796
797 (define bootcfg
798 (and (memq action '(init reconfigure))
799 (operating-system-bootcfg os menu-entries)))
800
801 (when (eq? action 'reconfigure)
802 (maybe-suggest-running-guix-pull))
803
804 ;; Check whether the declared file systems exist. This is better than
805 ;; instantiating a broken configuration. Assume that we can only check if
806 ;; running as root.
807 (when (and (not skip-safety-checks?)
808 (memq action '(init reconfigure)))
809 (check-mapped-devices os)
810 (when (zero? (getuid))
811 (check-file-system-availability (operating-system-file-systems os))
812 (check-initrd-modules os)))
813
814 (mlet* %store-monad
815 ((target* (current-target-system))
816 (image -> (find-image file-system-type target*))
817 (sys (system-derivation-for-action os image action
818 #:file-system-type file-system-type
819 #:image-size image-size
820 #:full-boot? full-boot?
821 #:container-shared-network? container-shared-network?
822 #:mappings mappings))
823
824 ;; For 'init' and 'reconfigure', always build BOOTCFG, even if
825 ;; --no-bootloader is passed, because we then use it as a GC root.
826 ;; See <http://bugs.gnu.org/21068>.
827 (drvs (mapm/accumulate-builds lower-object
828 (if (memq action '(init reconfigure))
829 (list sys bootcfg)
830 (list sys))))
831 (% (if derivations-only?
832 (return (for-each (compose println derivation-file-name)
833 drvs))
834 (built-derivations drvs))))
835
836 (if (or dry-run? derivations-only?)
837 (return #f)
838 (begin
839 (for-each (compose println derivation->output-path)
840 drvs)
841
842 (case action
843 ((reconfigure)
844 (newline)
845 (format #t (G_ "activating system...~%"))
846 (mbegin %store-monad
847 (switch-to-system local-eval os)
848 (mwhen install-bootloader?
849 (install-bootloader local-eval bootloader bootcfg
850 #:target (or target "/"))
851 (return
852 (info (G_ "bootloader successfully installed on '~a'~%")
853 (bootloader-configuration-target bootloader))))
854 (with-shepherd-error-handling
855 (upgrade-shepherd-services local-eval os)
856 (return (format #t (G_ "\
857 To complete the upgrade, run 'herd restart SERVICE' to stop,
858 upgrade, and restart each service that was not automatically restarted.\n"))))))
859 ((init)
860 (newline)
861 (format #t (G_ "initializing operating system under '~a'...~%")
862 target)
863 (install sys (canonicalize-path target)
864 #:install-bootloader? install-bootloader?
865 #:bootloader bootloader
866 #:bootcfg bootcfg))
867 (else
868 ;; All we had to do was to build SYS and maybe register an
869 ;; indirect GC root.
870 (let ((output (derivation->output-path sys)))
871 (mbegin %store-monad
872 (mwhen gc-root
873 (register-root* (list output) gc-root))
874 (return output)))))))))
875
876 (define (export-extension-graph os port)
877 "Export the service extension graph of OS to PORT."
878 (let* ((services (operating-system-services os))
879 (system (find (lambda (service)
880 (eq? (service-kind service) system-service-type))
881 services)))
882 (export-graph (list system) (current-output-port)
883 #:node-type (service-node-type services)
884 #:reverse-edges? #t)))
885
886 (define (export-shepherd-graph os port)
887 "Export the graph of shepherd services of OS to PORT."
888 (let* ((services (operating-system-services os))
889 (pid1 (fold-services services
890 #:target-type shepherd-root-service-type))
891 (shepherds (service-value pid1)) ;list of <shepherd-service>
892 (sinks (filter (lambda (service)
893 (null? (shepherd-service-requirement service)))
894 shepherds)))
895 (export-graph sinks (current-output-port)
896 #:node-type (shepherd-service-node-type shepherds)
897 #:reverse-edges? #t)))
898
899 \f
900 ;;;
901 ;;; Options.
902 ;;;
903
904 (define (show-help)
905 (display (G_ "Usage: guix system [OPTION ...] ACTION [ARG ...] [FILE]
906 Build the operating system declared in FILE according to ACTION.
907 Some ACTIONS support additional ARGS.\n"))
908 (newline)
909 (display (G_ "The valid values for ACTION are:\n"))
910 (newline)
911 (display (G_ "\
912 search search for existing service types\n"))
913 (display (G_ "\
914 reconfigure switch to a new operating system configuration\n"))
915 (display (G_ "\
916 roll-back switch to the previous operating system configuration\n"))
917 (display (G_ "\
918 describe describe the current system\n"))
919 (display (G_ "\
920 list-generations list the system generations\n"))
921 (display (G_ "\
922 switch-generation switch to an existing operating system configuration\n"))
923 (display (G_ "\
924 delete-generations delete old system generations\n"))
925 (display (G_ "\
926 build build the operating system without installing anything\n"))
927 (display (G_ "\
928 container build a container that shares the host's store\n"))
929 (display (G_ "\
930 vm build a virtual machine image that shares the host's store\n"))
931 (display (G_ "\
932 vm-image build a freestanding virtual machine image\n"))
933 (display (G_ "\
934 disk-image build a disk image, suitable for a USB stick\n"))
935 (display (G_ "\
936 docker-image build a Docker image\n"))
937 (display (G_ "\
938 init initialize a root file system to run GNU\n"))
939 (display (G_ "\
940 extension-graph emit the service extension graph in Dot format\n"))
941 (display (G_ "\
942 shepherd-graph emit the graph of shepherd services in Dot format\n"))
943
944 (show-build-options-help)
945 (display (G_ "
946 -d, --derivation return the derivation of the given system"))
947 (display (G_ "
948 -e, --expression=EXPR consider the operating-system EXPR evaluates to
949 instead of reading FILE, when applicable"))
950 (display (G_ "
951 --on-error=STRATEGY
952 apply STRATEGY (one of nothing-special, backtrace,
953 or debug) when an error occurs while reading FILE"))
954 (display (G_ "
955 --file-system-type=TYPE
956 for 'disk-image', produce a root file system of TYPE
957 (one of 'ext4', 'iso9660')"))
958 (display (G_ "
959 --image-size=SIZE for 'vm-image', produce an image of SIZE"))
960 (display (G_ "
961 --no-bootloader for 'init', do not install a bootloader"))
962 (display (G_ "
963 --save-provenance save provenance information"))
964 (display (G_ "
965 --share=SPEC for 'vm', share host file system according to SPEC"))
966 (display (G_ "
967 --expose=SPEC for 'vm', expose host file system according to SPEC"))
968 (display (G_ "
969 -N, --network for 'container', allow containers to access the network"))
970 (display (G_ "
971 -r, --root=FILE for 'vm', 'vm-image', 'disk-image', 'container',
972 and 'build', make FILE a symlink to the result, and
973 register it as a garbage collector root"))
974 (display (G_ "
975 --full-boot for 'vm', make a full boot sequence"))
976 (display (G_ "
977 --skip-checks skip file system and initrd module safety checks"))
978 (display (G_ "
979 --target=TRIPLET cross-build for TRIPLET--e.g., \"armel-linux-gnu\""))
980 (display (G_ "
981 -v, --verbosity=LEVEL use the given verbosity LEVEL"))
982 (newline)
983 (display (G_ "
984 -h, --help display this help and exit"))
985 (display (G_ "
986 -V, --version display version information and exit"))
987 (newline)
988 (show-bug-report-information))
989
990 (define %options
991 ;; Specifications of the command-line options.
992 (cons* (option '(#\h "help") #f #f
993 (lambda args
994 (show-help)
995 (exit 0)))
996 (option '(#\V "version") #f #f
997 (lambda args
998 (show-version-and-exit "guix system")))
999 (option '(#\e "expression") #t #f
1000 (lambda (opt name arg result)
1001 (alist-cons 'expression arg result)))
1002 (option '(#\d "derivation") #f #f
1003 (lambda (opt name arg result)
1004 (alist-cons 'derivations-only? #t result)))
1005 (option '("on-error") #t #f
1006 (lambda (opt name arg result)
1007 (alist-cons 'on-error (string->symbol arg)
1008 result)))
1009 (option '(#\t "file-system-type") #t #f
1010 (lambda (opt name arg result)
1011 (alist-cons 'file-system-type arg
1012 result)))
1013 (option '("image-size") #t #f
1014 (lambda (opt name arg result)
1015 (alist-cons 'image-size (size->number arg)
1016 result)))
1017 (option '(#\N "network") #f #f
1018 (lambda (opt name arg result)
1019 (alist-cons 'container-shared-network? #t result)))
1020 (option '("no-bootloader" "no-grub") #f #f
1021 (lambda (opt name arg result)
1022 (alist-cons 'install-bootloader? #f result)))
1023 (option '("full-boot") #f #f
1024 (lambda (opt name arg result)
1025 (alist-cons 'full-boot? #t result)))
1026 (option '("save-provenance") #f #f
1027 (lambda (opt name arg result)
1028 (alist-cons 'save-provenance? #t result)))
1029 (option '("skip-checks") #f #f
1030 (lambda (opt name arg result)
1031 (alist-cons 'skip-safety-checks? #t result)))
1032
1033 (option '("share") #t #f
1034 (lambda (opt name arg result)
1035 (alist-cons 'file-system-mapping
1036 (specification->file-system-mapping arg #t)
1037 result)))
1038 (option '("expose") #t #f
1039 (lambda (opt name arg result)
1040 (alist-cons 'file-system-mapping
1041 (specification->file-system-mapping arg #f)
1042 result)))
1043
1044 (option '(#\n "dry-run") #f #f
1045 (lambda (opt name arg result)
1046 (alist-cons 'dry-run? #t result)))
1047 (option '(#\v "verbosity") #t #f
1048 (lambda (opt name arg result)
1049 (let ((level (string->number* arg)))
1050 (alist-cons 'verbosity level
1051 (alist-delete 'verbosity result)))))
1052 (option '(#\s "system") #t #f
1053 (lambda (opt name arg result)
1054 (alist-cons 'system arg
1055 (alist-delete 'system result eq?))))
1056 (option '("target") #t #f
1057 (lambda (opt name arg result)
1058 (alist-cons 'target arg
1059 (alist-delete 'target result eq?))))
1060 (option '(#\r "root") #t #f
1061 (lambda (opt name arg result)
1062 (alist-cons 'gc-root arg result)))
1063 %standard-build-options))
1064
1065 (define %default-options
1066 ;; Alist of default option values.
1067 `((system . ,(%current-system))
1068 (target . #f)
1069 (substitutes? . #t)
1070 (offload? . #t)
1071 (print-build-trace? . #t)
1072 (print-extended-build-trace? . #t)
1073 (multiplexed-build-output? . #t)
1074 (graft? . #t)
1075 (debug . 0)
1076 (verbosity . #f) ;default
1077 (file-system-type . "ext4")
1078 (image-size . guess)
1079 (install-bootloader? . #t)))
1080
1081 \f
1082 ;;;
1083 ;;; Entry point.
1084 ;;;
1085
1086 (define (process-action action args opts)
1087 "Process ACTION, a sub-command, with the arguments are listed in ARGS.
1088 ACTION must be one of the sub-commands that takes an operating system
1089 declaration as an argument (a file name.) OPTS is the raw alist of options
1090 resulting from command-line parsing."
1091 (define (ensure-operating-system file-or-exp obj)
1092 (unless (operating-system? obj)
1093 (leave (G_ "'~a' does not return an operating system~%")
1094 file-or-exp))
1095 obj)
1096
1097 (define save-provenance?
1098 (or (assoc-ref opts 'save-provenance?)
1099 (memq action '(init reconfigure))))
1100
1101 (let* ((file (match args
1102 (() #f)
1103 ((x . _) x)))
1104 (expr (assoc-ref opts 'expression))
1105 (system (assoc-ref opts 'system))
1106 (target (assoc-ref opts 'target))
1107 (transform (if save-provenance?
1108 (cut operating-system-with-provenance <> file)
1109 identity))
1110 (os (transform
1111 (ensure-operating-system
1112 (or file expr)
1113 (cond
1114 ((and expr file)
1115 (leave
1116 (G_ "both file and expression cannot be specified~%")))
1117 (expr
1118 (read/eval expr))
1119 (file
1120 (load* file %user-module
1121 #:on-error (assoc-ref opts 'on-error)))
1122 (else
1123 (leave (G_ "no configuration specified~%")))))))
1124
1125 (dry? (assoc-ref opts 'dry-run?))
1126 (bootloader? (assoc-ref opts 'install-bootloader?))
1127 (target-file (match args
1128 ((first second) second)
1129 (_ #f)))
1130 (bootloader-target
1131 (and bootloader?
1132 (bootloader-configuration-target
1133 (operating-system-bootloader os)))))
1134
1135 (with-store store
1136 (set-build-options-from-command-line store opts)
1137
1138 (with-build-handler (build-notifier #:use-substitutes?
1139 (assoc-ref opts 'substitutes?)
1140 #:dry-run?
1141 (assoc-ref opts 'dry-run?))
1142 (run-with-store store
1143 (mbegin %store-monad
1144 (set-guile-for-build (default-guile))
1145 (case action
1146 ((extension-graph)
1147 (export-extension-graph os (current-output-port)))
1148 ((shepherd-graph)
1149 (export-shepherd-graph os (current-output-port)))
1150 (else
1151 (unless (memq action '(build init))
1152 (warn-about-old-distro #:suggested-command
1153 "guix system reconfigure"))
1154
1155 (perform-action action os
1156 #:dry-run? dry?
1157 #:derivations-only? (assoc-ref opts
1158 'derivations-only?)
1159 #:use-substitutes? (assoc-ref opts 'substitutes?)
1160 #:skip-safety-checks?
1161 (assoc-ref opts 'skip-safety-checks?)
1162 #:file-system-type (assoc-ref opts 'file-system-type)
1163 #:image-size (assoc-ref opts 'image-size)
1164 #:full-boot? (assoc-ref opts 'full-boot?)
1165 #:container-shared-network?
1166 (assoc-ref opts 'container-shared-network?)
1167 #:mappings (filter-map (match-lambda
1168 (('file-system-mapping . m)
1169 m)
1170 (_ #f))
1171 opts)
1172 #:install-bootloader? bootloader?
1173 #:target target-file
1174 #:bootloader-target bootloader-target
1175 #:gc-root (assoc-ref opts 'gc-root)))))
1176 #:target target
1177 #:system system)))
1178 (warn-about-disk-space)))
1179
1180 (define (resolve-subcommand name)
1181 (let ((module (resolve-interface
1182 `(guix scripts system ,(string->symbol name))))
1183 (proc (string->symbol (string-append "guix-system-" name))))
1184 (module-ref module proc)))
1185
1186 (define (process-command command args opts)
1187 "Process COMMAND, one of the 'guix system' sub-commands. ARGS is its
1188 argument list and OPTS is the option alist."
1189 (define-syntax-rule (with-store* store exp ...)
1190 (with-store store
1191 (set-build-options-from-command-line store opts)
1192 exp ...))
1193
1194 (case command
1195 ;; The following commands do not need to use the store, and they do not need
1196 ;; an operating system configuration file.
1197 ((list-generations)
1198 (let ((pattern (match args
1199 (() #f)
1200 ((pattern) pattern)
1201 (x (leave (G_ "wrong number of arguments~%"))))))
1202 (list-generations pattern)))
1203 ((describe)
1204 (match (generation-number %system-profile)
1205 (0
1206 (error (G_ "no system generation, nothing to describe~%")))
1207 (generation
1208 (display-system-generation generation))))
1209 ((search)
1210 (apply (resolve-subcommand "search") args))
1211 ;; The following commands need to use the store, but they do not need an
1212 ;; operating system configuration file.
1213 ((delete-generations)
1214 (let ((pattern (match args
1215 (() #f)
1216 ((pattern) pattern)
1217 (x (leave (G_ "wrong number of arguments~%"))))))
1218 (with-store* store
1219 (delete-matching-generations store %system-profile pattern)
1220 (reinstall-bootloader store (generation-number %system-profile)))))
1221 ((switch-generation)
1222 (let ((pattern (match args
1223 ((pattern) pattern)
1224 (x (leave (G_ "wrong number of arguments~%"))))))
1225 (with-store* store
1226 (switch-to-system-generation store pattern))))
1227 ((roll-back)
1228 (let ((pattern (match args
1229 (() "")
1230 (x (leave (G_ "wrong number of arguments~%"))))))
1231 (with-store* store
1232 (roll-back-system store))))
1233 ;; The following commands need to use the store, and they also
1234 ;; need an operating system configuration file.
1235 (else (process-action command args opts))))
1236
1237 (define (guix-system . args)
1238 (define (parse-sub-command arg result)
1239 ;; Parse sub-command ARG and augment RESULT accordingly.
1240 (if (assoc-ref result 'action)
1241 (alist-cons 'argument arg result)
1242 (let ((action (string->symbol arg)))
1243 (case action
1244 ((build container vm vm-image disk-image reconfigure init
1245 extension-graph shepherd-graph
1246 list-generations describe
1247 delete-generations roll-back
1248 switch-generation search docker-image)
1249 (alist-cons 'action action result))
1250 (else (leave (G_ "~a: unknown action~%") action))))))
1251
1252 (define (match-pair car)
1253 ;; Return a procedure that matches a pair with CAR.
1254 (match-lambda
1255 ((head . tail)
1256 (and (eq? car head) tail))
1257 (_ #f)))
1258
1259 (define (option-arguments opts)
1260 ;; Extract the plain arguments from OPTS.
1261 (let* ((args (reverse (filter-map (match-pair 'argument) opts)))
1262 (count (length args))
1263 (action (assoc-ref opts 'action))
1264 (expr (assoc-ref opts 'expression)))
1265 (define (fail)
1266 (leave (G_ "wrong number of arguments for action '~a'~%")
1267 action))
1268
1269 (unless action
1270 (format (current-error-port)
1271 (G_ "guix system: missing command name~%"))
1272 (format (current-error-port)
1273 (G_ "Try 'guix system --help' for more information.~%"))
1274 (exit 1))
1275
1276 (case action
1277 ((build container vm vm-image disk-image docker-image reconfigure)
1278 (unless (or (= count 1)
1279 (and expr (= count 0)))
1280 (fail)))
1281 ((init)
1282 (unless (= count 2)
1283 (fail))))
1284 args))
1285
1286 (with-error-handling
1287 (let* ((opts (parse-command-line args %options
1288 (list %default-options)
1289 #:argument-handler
1290 parse-sub-command))
1291 (args (option-arguments opts))
1292 (command (assoc-ref opts 'action)))
1293 (parameterize ((%graft? (assoc-ref opts 'graft?)))
1294 (with-status-verbosity (or (assoc-ref opts 'verbosity)
1295 (if (eq? command 'build) 2 1))
1296 (process-command command args opts))))))
1297
1298 ;;; Local Variables:
1299 ;;; eval: (put 'with-store* 'scheme-indent-function 1)
1300 ;;; End:
1301
1302 ;;; system.scm ends here