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