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