guix system: 'reconfigure' disallows downgrades by default.
[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* (display-system-generation number
450 #:optional (profile %system-profile))
451 "Display a summary of system generation NUMBER in a human-readable format."
452 (define (display-channel channel)
453 (format #t " ~a:~%" (channel-name channel))
454 (format #t (G_ " repository URL: ~a~%") (channel-url channel))
455 (when (channel-branch channel)
456 (format #t (G_ " branch: ~a~%") (channel-branch channel)))
457 (format #t (G_ " commit: ~a~%")
458 (if (supports-hyperlinks?)
459 (channel-commit-hyperlink channel)
460 (channel-commit channel))))
461
462 (unless (zero? number)
463 (let* ((generation (generation-file-name profile number))
464 (params (read-boot-parameters-file generation))
465 (label (boot-parameters-label params))
466 (bootloader-name (boot-parameters-bootloader-name params))
467 (root (boot-parameters-root-device params))
468 (root-device (if (bytevector? root)
469 (uuid->string root)
470 root))
471 (kernel (boot-parameters-kernel params))
472 (multiboot-modules (boot-parameters-multiboot-modules params)))
473 (define-values (channels config-file)
474 (system-provenance generation))
475
476 (display-generation profile number)
477 (format #t (G_ " file name: ~a~%") generation)
478 (format #t (G_ " canonical file name: ~a~%") (readlink* generation))
479 ;; TRANSLATORS: Please preserve the two-space indentation.
480 (format #t (G_ " label: ~a~%") label)
481 (format #t (G_ " bootloader: ~a~%") bootloader-name)
482
483 ;; TRANSLATORS: The '~[', '~;', and '~]' sequences in this string must
484 ;; be preserved. They denote conditionals, such that the result will
485 ;; look like:
486 ;; root device: UUID: 12345-678
487 ;; or:
488 ;; root device: label: "my-root"
489 ;; or just:
490 ;; root device: /dev/sda3
491 (format #t (G_ " root device: ~[UUID: ~a~;label: ~s~;~a~]~%")
492 (cond ((uuid? root-device) 0)
493 ((file-system-label? root-device) 1)
494 (else 2))
495 (file-system-device->string root-device))
496
497 (format #t (G_ " kernel: ~a~%") kernel)
498
499 (match multiboot-modules
500 (() #f)
501 (((modules . _) ...)
502 (format #t (G_ " multiboot: ~a~%")
503 (string-join modules "\n "))))
504
505 (unless (null? channels)
506 ;; TRANSLATORS: Here "channel" is the same terminology as used in
507 ;; "guix describe" and "guix pull --channels".
508 (format #t (G_ " channels:~%"))
509 (for-each display-channel channels))
510 (when config-file
511 (format #t (G_ " configuration file: ~a~%")
512 (if (supports-hyperlinks?)
513 (file-hyperlink config-file)
514 config-file))))))
515
516 (define* (list-generations pattern #:optional (profile %system-profile))
517 "Display in a human-readable format all the system generations matching
518 PATTERN, a string. When PATTERN is #f, display all the system generations."
519 (cond ((not (file-exists? profile)) ; XXX: race condition
520 (raise (condition (&profile-not-found-error
521 (profile profile)))))
522 ((not pattern)
523 (for-each display-system-generation (profile-generations profile)))
524 ((matching-generations pattern profile)
525 =>
526 (lambda (numbers)
527 (if (null-list? numbers)
528 (exit 1)
529 (leave-on-EPIPE
530 (for-each display-system-generation numbers)))))))
531
532 \f
533 ;;;
534 ;;; File system declaration checks.
535 ;;;
536
537 (define (check-file-system-availability file-systems)
538 "Check whether the UUIDs or partition labels that FILE-SYSTEMS refer to, if
539 any, are available. Raise an error if they're not."
540 (define relevant
541 (filter (lambda (fs)
542 (and (file-system-mount? fs)
543 (not (member (file-system-type fs)
544 %pseudo-file-system-types))
545 ;; Don't try to validate network file systems.
546 (not (string-prefix? "nfs" (file-system-type fs)))
547 (not (memq 'bind-mount (file-system-flags fs)))))
548 file-systems))
549
550 (define labeled
551 (filter (lambda (fs)
552 (file-system-label? (file-system-device fs)))
553 relevant))
554
555 (define literal
556 (filter (lambda (fs)
557 (string? (file-system-device fs)))
558 relevant))
559
560 (define uuid
561 (filter (lambda (fs)
562 (uuid? (file-system-device fs)))
563 relevant))
564
565 (define fail? #f)
566
567 (define (file-system-location* fs)
568 (location->string
569 (source-properties->location
570 (file-system-location fs))))
571
572 (let-syntax ((error (syntax-rules ()
573 ((_ args ...)
574 (begin
575 (set! fail? #t)
576 (format (current-error-port)
577 args ...))))))
578 (for-each (lambda (fs)
579 (catch 'system-error
580 (lambda ()
581 (stat (file-system-device fs)))
582 (lambda args
583 (let ((errno (system-error-errno args))
584 (device (file-system-device fs)))
585 (error (G_ "~a: error: device '~a' not found: ~a~%")
586 (file-system-location* fs) device
587 (strerror errno))
588 (unless (string-prefix? "/" device)
589 (display-hint (format #f (G_ "If '~a' is a file system
590 label, write @code{(file-system-label ~s)} in your @code{device} field.")
591 device device)))))))
592 literal)
593 (for-each (lambda (fs)
594 (let ((label (file-system-label->string
595 (file-system-device fs))))
596 (unless (find-partition-by-label label)
597 (error (G_ "~a: error: file system with label '~a' not found~%")
598 (file-system-location* fs) label))))
599 labeled)
600 (for-each (lambda (fs)
601 (unless (find-partition-by-uuid (file-system-device fs))
602 (error (G_ "~a: error: file system with UUID '~a' not found~%")
603 (file-system-location* fs)
604 (uuid->string (file-system-device fs)))))
605 uuid)
606
607 (when fail?
608 ;; Better be safe than sorry.
609 (exit 1))))
610
611 (define (check-mapped-devices os)
612 "Check that each of MAPPED-DEVICES is valid according to the 'check'
613 procedure of its type."
614 (define boot-mapped-devices
615 (operating-system-boot-mapped-devices os))
616
617 (define (needed-for-boot? md)
618 (memq md boot-mapped-devices))
619
620 (define initrd-modules
621 (operating-system-initrd-modules os))
622
623 (for-each (lambda (md)
624 (let ((check (mapped-device-kind-check
625 (mapped-device-type md))))
626 ;; We expect CHECK to raise an exception with a detailed
627 ;; '&message' if something goes wrong.
628 (check md
629 #:needed-for-boot? (needed-for-boot? md)
630 #:initrd-modules initrd-modules)))
631 (operating-system-mapped-devices os)))
632
633 (define (check-initrd-modules os)
634 "Check that modules needed by 'needed-for-boot' file systems in OS are
635 available in the initrd. Note that mapped devices are responsible for
636 checking this by themselves in their 'check' procedure."
637 (define (file-system-/dev fs)
638 (let ((device (file-system-device fs)))
639 (match device
640 ((? string?)
641 device)
642 ((? uuid?)
643 (find-partition-by-uuid device))
644 ((? file-system-label?)
645 (find-partition-by-label (file-system-label->string device))))))
646
647 (define file-systems
648 (filter file-system-needed-for-boot?
649 (operating-system-file-systems os)))
650
651 (for-each (lambda (fs)
652 (check-device-initrd-modules (file-system-/dev fs)
653 (operating-system-initrd-modules os)
654 (source-properties->location
655 (file-system-location fs))))
656 file-systems))
657
658 \f
659 ;;;
660 ;;; Action.
661 ;;;
662
663 (define* (system-derivation-for-action os base-image action
664 #:key image-size file-system-type
665 full-boot? container-shared-network?
666 mappings)
667 "Return as a monadic value the derivation for OS according to ACTION."
668 (case action
669 ((build init reconfigure)
670 (operating-system-derivation os))
671 ((container)
672 (container-script
673 os
674 #:mappings mappings
675 #:shared-network? container-shared-network?))
676 ((vm-image)
677 (system-qemu-image os #:disk-image-size image-size))
678 ((vm)
679 (system-qemu-image/shared-store-script os
680 #:full-boot? full-boot?
681 #:disk-image-size
682 (if full-boot?
683 image-size
684 (* 70 (expt 2 20)))
685 #:mappings mappings))
686 ((disk-image)
687 (lower-object
688 (system-image
689 (image
690 (inherit base-image)
691 (size image-size)
692 (operating-system os)))))
693 ((docker-image)
694 (system-docker-image os #:shared-network? container-shared-network?))))
695
696 (define (maybe-suggest-running-guix-pull)
697 "Suggest running 'guix pull' if this has never been done before."
698 ;; Check whether we're running a 'guix pull'-provided 'guix' command. When
699 ;; 'current-profile' returns #f, we may be running the globally-installed
700 ;; 'guix' and thus run the risk of deploying an older 'guix'. See
701 ;; <https://lists.gnu.org/archive/html/guix-devel/2014-08/msg00057.html>
702 (unless (or (current-profile) (getenv "GUIX_UNINSTALLED"))
703 (warning (G_ "Consider running 'guix pull' before 'reconfigure'.~%"))
704 (warning (G_ "Failing to do that may downgrade your system!~%"))))
705
706 (define (bootloader-installer-script installer
707 bootloader device target)
708 "Return a file calling INSTALLER gexp with given BOOTLOADER, DEVICE
709 and TARGET arguments."
710 (scheme-file "bootloader-installer"
711 (with-imported-modules '((gnu build bootloader)
712 (guix build utils))
713 #~(begin
714 (use-modules (gnu build bootloader)
715 (guix build utils)
716 (ice-9 binary-ports)
717 (srfi srfi-34)
718 (srfi srfi-35))
719
720 (guard (c ((message-condition? c) ;XXX: i18n
721 (format (current-error-port) "error: ~a~%"
722 (condition-message c))
723 (exit 1)))
724 (#$installer #$bootloader #$device #$target)
725 (info (G_ "bootloader successfully installed on '~a'~%")
726 #$device))))))
727
728 (define (local-eval exp)
729 "Evaluate EXP, a G-Expression, in-place."
730 (mlet* %store-monad ((lowered (lower-gexp exp))
731 (_ (built-derivations (lowered-gexp-inputs lowered))))
732 (save-load-path-excursion
733 (set! %load-path (lowered-gexp-load-path lowered))
734 (set! %load-compiled-path (lowered-gexp-load-compiled-path lowered))
735 (return (primitive-eval (lowered-gexp-sexp lowered))))))
736
737 (define* (perform-action action os
738 #:key
739 (validate-reconfigure ensure-forward-reconfigure)
740 save-provenance?
741 skip-safety-checks?
742 install-bootloader?
743 dry-run? derivations-only?
744 use-substitutes? bootloader-target target
745 image-size file-system-type full-boot?
746 container-shared-network?
747 (mappings '())
748 (gc-root #f))
749 "Perform ACTION for OS. INSTALL-BOOTLOADER? specifies whether to install
750 bootloader; BOOTLOADER-TAGET is the target for the bootloader; TARGET is the
751 target root directory; IMAGE-SIZE is the size of the image to be built, for
752 the 'vm-image' and 'disk-image' actions. The root file system is created as a
753 FILE-SYSTEM-TYPE file system. FULL-BOOT? is used for the 'vm' action; it
754 determines whether to boot directly to the kernel or to the bootloader.
755 CONTAINER-SHARED-NETWORK? determines if the container will use a separate
756 network namespace.
757
758 When DERIVATIONS-ONLY? is true, print the derivation file name(s) without
759 building anything.
760
761 When GC-ROOT is a path, also make that path an indirect root of the build
762 output when building a system derivation, such as a disk image.
763
764 When SKIP-SAFETY-CHECKS? is true, skip the file system and initrd module
765 static checks."
766 (define println
767 (cut format #t "~a~%" <>))
768
769 (define menu-entries
770 (if (eq? 'init action)
771 '()
772 (map boot-parameters->menu-entry (profile-boot-parameters))))
773
774 (define bootloader
775 (operating-system-bootloader os))
776
777 (define bootcfg
778 (and (memq action '(init reconfigure))
779 (operating-system-bootcfg os menu-entries)))
780
781 (when (eq? action 'reconfigure)
782 (maybe-suggest-running-guix-pull)
783 (check-forward-update validate-reconfigure))
784
785 ;; Check whether the declared file systems exist. This is better than
786 ;; instantiating a broken configuration. Assume that we can only check if
787 ;; running as root.
788 (when (and (not skip-safety-checks?)
789 (memq action '(init reconfigure)))
790 (check-mapped-devices os)
791 (when (zero? (getuid))
792 (check-file-system-availability (operating-system-file-systems os))
793 (check-initrd-modules os)))
794
795 (mlet* %store-monad
796 ((target* (current-target-system))
797 (image -> (find-image file-system-type target*))
798 (sys (system-derivation-for-action os image action
799 #:file-system-type file-system-type
800 #:image-size image-size
801 #:full-boot? full-boot?
802 #:container-shared-network? container-shared-network?
803 #:mappings mappings))
804
805 ;; For 'init' and 'reconfigure', always build BOOTCFG, even if
806 ;; --no-bootloader is passed, because we then use it as a GC root.
807 ;; See <http://bugs.gnu.org/21068>.
808 (drvs (mapm/accumulate-builds lower-object
809 (if (memq action '(init reconfigure))
810 (list sys bootcfg)
811 (list sys))))
812 (% (if derivations-only?
813 (return (for-each (compose println derivation-file-name)
814 drvs))
815 (built-derivations drvs))))
816
817 (if (or dry-run? derivations-only?)
818 (return #f)
819 (begin
820 (for-each (compose println derivation->output-path)
821 drvs)
822
823 (case action
824 ((reconfigure)
825 (newline)
826 (format #t (G_ "activating system...~%"))
827 (mbegin %store-monad
828 (switch-to-system local-eval os)
829 (mwhen install-bootloader?
830 (install-bootloader local-eval bootloader bootcfg
831 #:target (or target "/"))
832 (return
833 (info (G_ "bootloader successfully installed on '~a'~%")
834 (bootloader-configuration-target bootloader))))
835 (with-shepherd-error-handling
836 (upgrade-shepherd-services local-eval os)
837 (return (format #t (G_ "\
838 To complete the upgrade, run 'herd restart SERVICE' to stop,
839 upgrade, and restart each service that was not automatically restarted.\n"))))))
840 ((init)
841 (newline)
842 (format #t (G_ "initializing operating system under '~a'...~%")
843 target)
844 (install sys (canonicalize-path target)
845 #:install-bootloader? install-bootloader?
846 #:bootloader bootloader
847 #:bootcfg bootcfg))
848 (else
849 ;; All we had to do was to build SYS and maybe register an
850 ;; indirect GC root.
851 (let ((output (derivation->output-path sys)))
852 (mbegin %store-monad
853 (mwhen gc-root
854 (register-root* (list output) gc-root))
855 (return output)))))))))
856
857 (define (export-extension-graph os port)
858 "Export the service extension graph of OS to PORT."
859 (let* ((services (operating-system-services os))
860 (system (find (lambda (service)
861 (eq? (service-kind service) system-service-type))
862 services)))
863 (export-graph (list system) (current-output-port)
864 #:node-type (service-node-type services)
865 #:reverse-edges? #t)))
866
867 (define (export-shepherd-graph os port)
868 "Export the graph of shepherd services of OS to PORT."
869 (let* ((services (operating-system-services os))
870 (pid1 (fold-services services
871 #:target-type shepherd-root-service-type))
872 (shepherds (service-value pid1)) ;list of <shepherd-service>
873 (sinks (filter (lambda (service)
874 (null? (shepherd-service-requirement service)))
875 shepherds)))
876 (export-graph sinks (current-output-port)
877 #:node-type (shepherd-service-node-type shepherds)
878 #:reverse-edges? #t)))
879
880 \f
881 ;;;
882 ;;; Options.
883 ;;;
884
885 (define (show-help)
886 (display (G_ "Usage: guix system [OPTION ...] ACTION [ARG ...] [FILE]
887 Build the operating system declared in FILE according to ACTION.
888 Some ACTIONS support additional ARGS.\n"))
889 (newline)
890 (display (G_ "The valid values for ACTION are:\n"))
891 (newline)
892 (display (G_ "\
893 search search for existing service types\n"))
894 (display (G_ "\
895 reconfigure switch to a new operating system configuration\n"))
896 (display (G_ "\
897 roll-back switch to the previous operating system configuration\n"))
898 (display (G_ "\
899 describe describe the current system\n"))
900 (display (G_ "\
901 list-generations list the system generations\n"))
902 (display (G_ "\
903 switch-generation switch to an existing operating system configuration\n"))
904 (display (G_ "\
905 delete-generations delete old system generations\n"))
906 (display (G_ "\
907 build build the operating system without installing anything\n"))
908 (display (G_ "\
909 container build a container that shares the host's store\n"))
910 (display (G_ "\
911 vm build a virtual machine image that shares the host's store\n"))
912 (display (G_ "\
913 vm-image build a freestanding virtual machine image\n"))
914 (display (G_ "\
915 disk-image build a disk image, suitable for a USB stick\n"))
916 (display (G_ "\
917 docker-image build a Docker image\n"))
918 (display (G_ "\
919 init initialize a root file system to run GNU\n"))
920 (display (G_ "\
921 extension-graph emit the service extension graph in Dot format\n"))
922 (display (G_ "\
923 shepherd-graph emit the graph of shepherd services in Dot format\n"))
924
925 (show-build-options-help)
926 (display (G_ "
927 -d, --derivation return the derivation of the given system"))
928 (display (G_ "
929 -e, --expression=EXPR consider the operating-system EXPR evaluates to
930 instead of reading FILE, when applicable"))
931 (display (G_ "
932 --allow-downgrades for 'reconfigure', allow downgrades to earlier
933 channel revisions"))
934 (display (G_ "
935 --on-error=STRATEGY
936 apply STRATEGY (one of nothing-special, backtrace,
937 or debug) when an error occurs while reading FILE"))
938 (display (G_ "
939 --file-system-type=TYPE
940 for 'disk-image', produce a root file system of TYPE
941 (one of 'ext4', 'iso9660')"))
942 (display (G_ "
943 --image-size=SIZE for 'vm-image', produce an image of SIZE"))
944 (display (G_ "
945 --no-bootloader for 'init', do not install a bootloader"))
946 (display (G_ "
947 --save-provenance save provenance information"))
948 (display (G_ "
949 --share=SPEC for 'vm', share host file system according to SPEC"))
950 (display (G_ "
951 --expose=SPEC for 'vm', expose host file system according to SPEC"))
952 (display (G_ "
953 -N, --network for 'container', allow containers to access the network"))
954 (display (G_ "
955 -r, --root=FILE for 'vm', 'vm-image', 'disk-image', 'container',
956 and 'build', make FILE a symlink to the result, and
957 register it as a garbage collector root"))
958 (display (G_ "
959 --full-boot for 'vm', make a full boot sequence"))
960 (display (G_ "
961 --skip-checks skip file system and initrd module safety checks"))
962 (display (G_ "
963 --target=TRIPLET cross-build for TRIPLET--e.g., \"armel-linux-gnu\""))
964 (display (G_ "
965 -v, --verbosity=LEVEL use the given verbosity LEVEL"))
966 (newline)
967 (display (G_ "
968 -h, --help display this help and exit"))
969 (display (G_ "
970 -V, --version display version information and exit"))
971 (newline)
972 (show-bug-report-information))
973
974 (define %options
975 ;; Specifications of the command-line options.
976 (cons* (option '(#\h "help") #f #f
977 (lambda args
978 (show-help)
979 (exit 0)))
980 (option '(#\V "version") #f #f
981 (lambda args
982 (show-version-and-exit "guix system")))
983 (option '(#\e "expression") #t #f
984 (lambda (opt name arg result)
985 (alist-cons 'expression arg result)))
986 (option '(#\d "derivation") #f #f
987 (lambda (opt name arg result)
988 (alist-cons 'derivations-only? #t result)))
989 (option '("allow-downgrades") #f #f
990 (lambda (opt name arg result)
991 (alist-cons 'validate-reconfigure
992 warn-about-backward-reconfigure
993 result)))
994 (option '("on-error") #t #f
995 (lambda (opt name arg result)
996 (alist-cons 'on-error (string->symbol arg)
997 result)))
998 (option '(#\t "file-system-type") #t #f
999 (lambda (opt name arg result)
1000 (alist-cons 'file-system-type arg
1001 result)))
1002 (option '("image-size") #t #f
1003 (lambda (opt name arg result)
1004 (alist-cons 'image-size (size->number arg)
1005 result)))
1006 (option '(#\N "network") #f #f
1007 (lambda (opt name arg result)
1008 (alist-cons 'container-shared-network? #t result)))
1009 (option '("no-bootloader" "no-grub") #f #f
1010 (lambda (opt name arg result)
1011 (alist-cons 'install-bootloader? #f result)))
1012 (option '("full-boot") #f #f
1013 (lambda (opt name arg result)
1014 (alist-cons 'full-boot? #t result)))
1015 (option '("save-provenance") #f #f
1016 (lambda (opt name arg result)
1017 (alist-cons 'save-provenance? #t result)))
1018 (option '("skip-checks") #f #f
1019 (lambda (opt name arg result)
1020 (alist-cons 'skip-safety-checks? #t result)))
1021
1022 (option '("share") #t #f
1023 (lambda (opt name arg result)
1024 (alist-cons 'file-system-mapping
1025 (specification->file-system-mapping arg #t)
1026 result)))
1027 (option '("expose") #t #f
1028 (lambda (opt name arg result)
1029 (alist-cons 'file-system-mapping
1030 (specification->file-system-mapping arg #f)
1031 result)))
1032
1033 (option '(#\n "dry-run") #f #f
1034 (lambda (opt name arg result)
1035 (alist-cons 'dry-run? #t result)))
1036 (option '(#\v "verbosity") #t #f
1037 (lambda (opt name arg result)
1038 (let ((level (string->number* arg)))
1039 (alist-cons 'verbosity level
1040 (alist-delete 'verbosity result)))))
1041 (option '(#\s "system") #t #f
1042 (lambda (opt name arg result)
1043 (alist-cons 'system arg
1044 (alist-delete 'system result eq?))))
1045 (option '("target") #t #f
1046 (lambda (opt name arg result)
1047 (alist-cons 'target arg
1048 (alist-delete 'target result eq?))))
1049 (option '(#\r "root") #t #f
1050 (lambda (opt name arg result)
1051 (alist-cons 'gc-root arg result)))
1052 %standard-build-options))
1053
1054 (define %default-options
1055 ;; Alist of default option values.
1056 `((system . ,(%current-system))
1057 (target . #f)
1058 (substitutes? . #t)
1059 (offload? . #t)
1060 (print-build-trace? . #t)
1061 (print-extended-build-trace? . #t)
1062 (multiplexed-build-output? . #t)
1063 (graft? . #t)
1064 (debug . 0)
1065 (verbosity . #f) ;default
1066 (validate-reconfigure . ,ensure-forward-reconfigure)
1067 (file-system-type . "ext4")
1068 (image-size . guess)
1069 (install-bootloader? . #t)))
1070
1071 \f
1072 ;;;
1073 ;;; Entry point.
1074 ;;;
1075
1076 (define (process-action action args opts)
1077 "Process ACTION, a sub-command, with the arguments are listed in ARGS.
1078 ACTION must be one of the sub-commands that takes an operating system
1079 declaration as an argument (a file name.) OPTS is the raw alist of options
1080 resulting from command-line parsing."
1081 (define (ensure-operating-system file-or-exp obj)
1082 (unless (operating-system? obj)
1083 (leave (G_ "'~a' does not return an operating system~%")
1084 file-or-exp))
1085 obj)
1086
1087 (define save-provenance?
1088 (or (assoc-ref opts 'save-provenance?)
1089 (memq action '(init reconfigure))))
1090
1091 (let* ((file (match args
1092 (() #f)
1093 ((x . _) x)))
1094 (expr (assoc-ref opts 'expression))
1095 (system (assoc-ref opts 'system))
1096 (target (assoc-ref opts 'target))
1097 (transform (if save-provenance?
1098 (cut operating-system-with-provenance <> file)
1099 identity))
1100 (os (transform
1101 (ensure-operating-system
1102 (or file expr)
1103 (cond
1104 ((and expr file)
1105 (leave
1106 (G_ "both file and expression cannot be specified~%")))
1107 (expr
1108 (read/eval expr))
1109 (file
1110 (load* file %user-module
1111 #:on-error (assoc-ref opts 'on-error)))
1112 (else
1113 (leave (G_ "no configuration specified~%")))))))
1114
1115 (dry? (assoc-ref opts 'dry-run?))
1116 (bootloader? (assoc-ref opts 'install-bootloader?))
1117 (target-file (match args
1118 ((first second) second)
1119 (_ #f)))
1120 (bootloader-target
1121 (and bootloader?
1122 (bootloader-configuration-target
1123 (operating-system-bootloader os)))))
1124
1125 (with-store store
1126 (set-build-options-from-command-line store opts)
1127
1128 (with-build-handler (build-notifier #:use-substitutes?
1129 (assoc-ref opts 'substitutes?)
1130 #:dry-run?
1131 (assoc-ref opts 'dry-run?))
1132 (run-with-store store
1133 (mbegin %store-monad
1134 (set-guile-for-build (default-guile))
1135 (case action
1136 ((extension-graph)
1137 (export-extension-graph os (current-output-port)))
1138 ((shepherd-graph)
1139 (export-shepherd-graph os (current-output-port)))
1140 (else
1141 (unless (memq action '(build init))
1142 (warn-about-old-distro #:suggested-command
1143 "guix system reconfigure"))
1144
1145 (perform-action action os
1146 #:dry-run? dry?
1147 #:derivations-only? (assoc-ref opts
1148 'derivations-only?)
1149 #:use-substitutes? (assoc-ref opts 'substitutes?)
1150 #:skip-safety-checks?
1151 (assoc-ref opts 'skip-safety-checks?)
1152 #:validate-reconfigure
1153 (assoc-ref opts 'validate-reconfigure)
1154 #:file-system-type (assoc-ref opts 'file-system-type)
1155 #:image-size (assoc-ref opts 'image-size)
1156 #:full-boot? (assoc-ref opts 'full-boot?)
1157 #:container-shared-network?
1158 (assoc-ref opts 'container-shared-network?)
1159 #:mappings (filter-map (match-lambda
1160 (('file-system-mapping . m)
1161 m)
1162 (_ #f))
1163 opts)
1164 #:install-bootloader? bootloader?
1165 #:target target-file
1166 #:bootloader-target bootloader-target
1167 #:gc-root (assoc-ref opts 'gc-root)))))
1168 #:target target
1169 #:system system)))
1170 (warn-about-disk-space)))
1171
1172 (define (resolve-subcommand name)
1173 (let ((module (resolve-interface
1174 `(guix scripts system ,(string->symbol name))))
1175 (proc (string->symbol (string-append "guix-system-" name))))
1176 (module-ref module proc)))
1177
1178 (define (process-command command args opts)
1179 "Process COMMAND, one of the 'guix system' sub-commands. ARGS is its
1180 argument list and OPTS is the option alist."
1181 (define-syntax-rule (with-store* store exp ...)
1182 (with-store store
1183 (set-build-options-from-command-line store opts)
1184 exp ...))
1185
1186 (case command
1187 ;; The following commands do not need to use the store, and they do not need
1188 ;; an operating system configuration file.
1189 ((list-generations)
1190 (let ((pattern (match args
1191 (() #f)
1192 ((pattern) pattern)
1193 (x (leave (G_ "wrong number of arguments~%"))))))
1194 (list-generations pattern)))
1195 ((describe)
1196 (match (generation-number %system-profile)
1197 (0
1198 (error (G_ "no system generation, nothing to describe~%")))
1199 (generation
1200 (display-system-generation generation))))
1201 ((search)
1202 (apply (resolve-subcommand "search") args))
1203 ;; The following commands need to use the store, but they do not need an
1204 ;; operating system configuration file.
1205 ((delete-generations)
1206 (let ((pattern (match args
1207 (() #f)
1208 ((pattern) pattern)
1209 (x (leave (G_ "wrong number of arguments~%"))))))
1210 (with-store* store
1211 (delete-matching-generations store %system-profile pattern)
1212 (reinstall-bootloader store (generation-number %system-profile)))))
1213 ((switch-generation)
1214 (let ((pattern (match args
1215 ((pattern) pattern)
1216 (x (leave (G_ "wrong number of arguments~%"))))))
1217 (with-store* store
1218 (switch-to-system-generation store pattern))))
1219 ((roll-back)
1220 (let ((pattern (match args
1221 (() "")
1222 (x (leave (G_ "wrong number of arguments~%"))))))
1223 (with-store* store
1224 (roll-back-system store))))
1225 ;; The following commands need to use the store, and they also
1226 ;; need an operating system configuration file.
1227 (else (process-action command args opts))))
1228
1229 (define (guix-system . args)
1230 (define (parse-sub-command arg result)
1231 ;; Parse sub-command ARG and augment RESULT accordingly.
1232 (if (assoc-ref result 'action)
1233 (alist-cons 'argument arg result)
1234 (let ((action (string->symbol arg)))
1235 (case action
1236 ((build container vm vm-image disk-image reconfigure init
1237 extension-graph shepherd-graph
1238 list-generations describe
1239 delete-generations roll-back
1240 switch-generation search docker-image)
1241 (alist-cons 'action action result))
1242 (else (leave (G_ "~a: unknown action~%") action))))))
1243
1244 (define (match-pair car)
1245 ;; Return a procedure that matches a pair with CAR.
1246 (match-lambda
1247 ((head . tail)
1248 (and (eq? car head) tail))
1249 (_ #f)))
1250
1251 (define (option-arguments opts)
1252 ;; Extract the plain arguments from OPTS.
1253 (let* ((args (reverse (filter-map (match-pair 'argument) opts)))
1254 (count (length args))
1255 (action (assoc-ref opts 'action))
1256 (expr (assoc-ref opts 'expression)))
1257 (define (fail)
1258 (leave (G_ "wrong number of arguments for action '~a'~%")
1259 action))
1260
1261 (unless action
1262 (format (current-error-port)
1263 (G_ "guix system: missing command name~%"))
1264 (format (current-error-port)
1265 (G_ "Try 'guix system --help' for more information.~%"))
1266 (exit 1))
1267
1268 (case action
1269 ((build container vm vm-image disk-image docker-image reconfigure)
1270 (unless (or (= count 1)
1271 (and expr (= count 0)))
1272 (fail)))
1273 ((init)
1274 (unless (= count 2)
1275 (fail))))
1276 args))
1277
1278 (with-error-handling
1279 (let* ((opts (parse-command-line args %options
1280 (list %default-options)
1281 #:argument-handler
1282 parse-sub-command))
1283 (args (option-arguments opts))
1284 (command (assoc-ref opts 'action)))
1285 (parameterize ((%graft? (assoc-ref opts 'graft?)))
1286 (with-status-verbosity (or (assoc-ref opts 'verbosity)
1287 (if (eq? command 'build) 2 1))
1288 (process-command command args opts))))))
1289
1290 ;;; Local Variables:
1291 ;;; eval: (put 'with-store* 'scheme-indent-function 1)
1292 ;;; End:
1293
1294 ;;; system.scm ends here