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