doc: Mention 'sync' after 'dd'.
[guix.git] / gnu / services.scm
blob5c314748da135d62e1c2bb67b49c12f483478c2a
1 ;;; GNU Guix --- Functional package management for GNU
2 ;;; Copyright © 2015, 2016, 2017 Ludovic Courtès <ludo@gnu.org>
3 ;;; Copyright © 2016 Chris Marusich <cmmarusich@gmail.com>
4 ;;;
5 ;;; This file is part of GNU Guix.
6 ;;;
7 ;;; GNU Guix is free software; you can redistribute it and/or modify it
8 ;;; under the terms of the GNU General Public License as published by
9 ;;; the Free Software Foundation; either version 3 of the License, or (at
10 ;;; your option) any later version.
11 ;;;
12 ;;; GNU Guix is distributed in the hope that it will be useful, but
13 ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
14 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 ;;; GNU General Public License for more details.
16 ;;;
17 ;;; You should have received a copy of the GNU General Public License
18 ;;; along with GNU Guix.  If not, see <http://www.gnu.org/licenses/>.
20 (define-module (gnu services)
21   #:use-module (guix gexp)
22   #:use-module (guix monads)
23   #:use-module (guix store)
24   #:use-module (guix records)
25   #:use-module (guix profiles)
26   #:use-module (guix sets)
27   #:use-module (guix ui)
28   #:use-module ((guix utils) #:select (source-properties->location))
29   #:use-module (guix modules)
30   #:use-module (gnu packages base)
31   #:use-module (gnu packages bash)
32   #:use-module (srfi srfi-1)
33   #:use-module (srfi srfi-9)
34   #:use-module (srfi srfi-9 gnu)
35   #:use-module (srfi srfi-26)
36   #:use-module (srfi srfi-34)
37   #:use-module (srfi srfi-35)
38   #:use-module (ice-9 vlist)
39   #:use-module (ice-9 match)
40   #:export (service-extension
41             service-extension?
42             service-extension-target
43             service-extension-compute
45             service-type
46             service-type?
47             service-type-name
48             service-type-extensions
49             service-type-compose
50             service-type-extend
51             service-type-default-value
53             service
54             service?
55             service-kind
56             service-value
57             service-parameters                    ;deprecated
59             simple-service
60             modify-services
61             service-back-edges
62             fold-services
64             service-error?
65             missing-value-service-error?
66             missing-value-service-error-type
67             missing-value-service-error-location
68             missing-target-service-error?
69             missing-target-service-error-service
70             missing-target-service-error-target-type
71             ambiguous-target-service-error?
72             ambiguous-target-service-error-service
73             ambiguous-target-service-error-target-type
75             system-service-type
76             boot-service-type
77             cleanup-service-type
78             activation-service-type
79             activation-service->script
80             %linux-bare-metal-service
81             special-files-service-type
82             extra-special-file
83             etc-service-type
84             etc-directory
85             setuid-program-service-type
86             profile-service-type
87             firmware-service-type
88             gc-root-service-type
90             %boot-service
91             %activation-service
92             etc-service
94             file-union))                      ;XXX: for lack of a better place
96 ;;; Comment:
97 ;;;
98 ;;; This module defines a broad notion of "service types" and "services."
99 ;;;
100 ;;; A service type describe how its instances extend instances of other
101 ;;; service types.  For instance, some services extend the instance of
102 ;;; ACCOUNT-SERVICE-TYPE by providing it with accounts and groups to create;
103 ;;; others extend SHEPHERD-ROOT-SERVICE-TYPE by passing it instances of
104 ;;; <shepherd-service>.
106 ;;; When applicable, the service type defines how it can itself be extended,
107 ;;; by providing one procedure to compose extensions, and one procedure to
108 ;;; extend itself.
110 ;;; A notable service type is SYSTEM-SERVICE-TYPE, which has a single
111 ;;; instance, which is the root of the service DAG.  Its value is the
112 ;;; derivation that produces the 'system' directory as returned by
113 ;;; 'operating-system-derivation'.
115 ;;; The 'fold-services' procedure can be passed a list of procedures, which it
116 ;;; "folds" by propagating extensions down the graph; it returns the root
117 ;;; service after the applying all its extensions.
119 ;;; Code:
121 (define-record-type <service-extension>
122   (service-extension target compute)
123   service-extension?
124   (target  service-extension-target)              ;<service-type>
125   (compute service-extension-compute))            ;params -> params
127 (define &no-default-value
128   ;; Value used to denote service types that have no associated default value.
129   '(no default value))
131 (define-record-type* <service-type> service-type make-service-type
132   service-type?
133   (name       service-type-name)                  ;symbol (for debugging)
135   ;; Things extended by services of this type.
136   (extensions service-type-extensions)            ;list of <service-extensions>
138   ;; Given a list of extensions, "compose" them.
139   (compose    service-type-compose                ;list of Any -> Any
140               (default #f))
142   ;; Extend the services' own parameters with the extension composition.
143   (extend     service-type-extend                 ;list of Any -> parameters
144               (default #f))
146   ;; Optional default value for instances of this type.
147   (default-value service-type-default-value       ;Any
148                  (default &no-default-value)))
150 (define (write-service-type type port)
151   (format port "#<service-type ~a ~a>"
152           (service-type-name type)
153           (number->string (object-address type) 16)))
155 (set-record-type-printer! <service-type> write-service-type)
157 ;; Services of a given type.
158 (define-record-type <service>
159   (make-service type value)
160   service?
161   (type       service-kind)
162   (value      service-value))
164 (define-syntax service
165   (syntax-rules ()
166     "Return a service instance of TYPE.  The service value is VALUE or, if
167 omitted, TYPE's default value."
168     ((_ type value)
169      (make-service type value))
170     ((_ type)
171      (%service-with-default-value (current-source-location)
172                                   type))))
174 (define (%service-with-default-value location type)
175   "Return a instance of service type TYPE with its default value, if any.  If
176 TYPE does not have a default value, an error is raised."
177   ;; TODO: Currently this is a run-time error but with a little bit macrology
178   ;; we could turn it into an expansion-time error.
179   (let ((default (service-type-default-value type)))
180     (if (eq? default &no-default-value)
181         (let ((location (source-properties->location location)))
182           (raise
183            (condition
184             (&missing-value-service-error (type type) (location location))
185             (&message
186              (message (format #f (G_ "~a: no value specified \
187 for service of type '~a'")
188                               (location->string location)
189                               (service-type-name type)))))))
190         (service type default))))
192 (define-condition-type &service-error &error
193   service-error?)
195 (define-condition-type &missing-value-service-error &service-error
196   missing-value-service-error?
197   (type     missing-value-service-error-type)
198   (location missing-value-service-error-location))
203 ;;; Helpers.
206 (define service-parameters
207   ;; Deprecated alias.
208   service-value)
210 (define (simple-service name target value)
211   "Return a service that extends TARGET with VALUE.  This works by creating a
212 singleton service type NAME, of which the returned service is an instance."
213   (let* ((extension (service-extension target identity))
214          (type      (service-type (name name)
215                                   (extensions (list extension)))))
216     (service type value)))
218 (define-syntax %modify-service
219   (syntax-rules (=>)
220     ((_ service)
221      service)
222     ((_ svc (kind param => exp ...) clauses ...)
223      (if (eq? (service-kind svc) kind)
224          (let ((param (service-value svc)))
225            (service (service-kind svc)
226                     (begin exp ...)))
227          (%modify-service svc clauses ...)))))
229 (define-syntax modify-services
230   (syntax-rules ()
231     "Modify the services listed in SERVICES according to CLAUSES and return
232 the resulting list of services.  Each clause must have the form:
234   (TYPE VARIABLE => BODY)
236 where TYPE is a service type, such as 'guix-service-type', and VARIABLE is an
237 identifier that is bound within BODY to the value of the service of that
238 TYPE.  Consider this example:
240   (modify-services %base-services
241     (guix-service-type config =>
242                        (guix-configuration
243                         (inherit config)
244                         (use-substitutes? #f)
245                         (extra-options '(\"--gc-keep-derivations\"))))
246     (mingetty-service-type config =>
247                            (mingetty-configuration
248                             (inherit config)
249                             (motd (plain-file \"motd\" \"Hi there!\")))))
251 It changes the configuration of the GUIX-SERVICE-TYPE instance, and that of
252 all the MINGETTY-SERVICE-TYPE instances.
254 This is a shorthand for (map (lambda (svc) ...) %base-services)."
255     ((_ services clauses ...)
256      (map (lambda (service)
257             (%modify-service service clauses ...))
258           services))))
262 ;;; Core services.
265 (define (system-derivation mentries mextensions)
266   "Return as a monadic value the derivation of the 'system' directory
267 containing the given entries."
268   (mlet %store-monad ((entries    mentries)
269                       (extensions (sequence %store-monad mextensions)))
270     (lower-object
271      (file-union "system"
272                  (append entries (concatenate extensions))))))
274 (define system-service-type
275   ;; This is the ultimate service type, the root of the service DAG.  The
276   ;; service of this type is extended by monadic name/item pairs.  These items
277   ;; end up in the "system directory" as returned by
278   ;; 'operating-system-derivation'.
279   (service-type (name 'system)
280                 (extensions '())
281                 (compose identity)
282                 (extend system-derivation)))
284 (define (compute-boot-script _ mexps)
285   (mlet %store-monad ((gexps (sequence %store-monad mexps)))
286     (gexp->file "boot"
287                 ;; Clean up and activate the system, then spawn shepherd.
288                 #~(begin #$@gexps))))
290 (define (boot-script-entry mboot)
291   "Return, as a monadic value, an entry for the boot script in the system
292 directory."
293   (mlet %store-monad ((boot mboot))
294     (return `(("boot" ,boot)))))
296 (define boot-service-type
297   ;; The service of this type is extended by being passed gexps as monadic
298   ;; values.  It aggregates them in a single script, as a monadic value, which
299   ;; becomes its 'parameters'.  It is the only service that extends nothing.
300   (service-type (name 'boot)
301                 (extensions
302                  (list (service-extension system-service-type
303                                           boot-script-entry)))
304                 (compose append)
305                 (extend compute-boot-script)))
307 (define %boot-service
308   ;; The service that produces the boot script.
309   (service boot-service-type #t))
311 (define (cleanup-gexp _)
312   "Return as a monadic value a gexp to clean up /tmp and similar places upon
313 boot."
314   (with-monad %store-monad
315     (with-imported-modules '((guix build utils))
316       (return #~(begin
317                   (use-modules (guix build utils))
319                   ;; Clean out /tmp and /var/run.
320                   ;;
321                   ;; XXX This needs to happen before service activations, so it
322                   ;; has to be here, but this also implicitly assumes that /tmp
323                   ;; and /var/run are on the root partition.
324                   (letrec-syntax ((fail-safe (syntax-rules ()
325                                                ((_ exp rest ...)
326                                                 (begin
327                                                   (catch 'system-error
328                                                     (lambda () exp)
329                                                     (const #f))
330                                                   (fail-safe rest ...)))
331                                                ((_)
332                                                 #t))))
333                     ;; Ignore I/O errors so the system can boot.
334                     (fail-safe
335                      (delete-file-recursively "/tmp")
336                      (delete-file-recursively "/var/run")
337                      (mkdir "/tmp")
338                      (chmod "/tmp" #o1777)
339                      (mkdir "/var/run")
340                      (chmod "/var/run" #o755))))))))
342 (define cleanup-service-type
343   ;; Service that cleans things up in /tmp and similar.
344   (service-type (name 'cleanup)
345                 (extensions
346                  (list (service-extension boot-service-type
347                                           cleanup-gexp)))))
349 (define* (file-union name files)                  ;FIXME: Factorize.
350   "Return a <computed-file> that builds a directory containing all of FILES.
351 Each item in FILES must be a list where the first element is the file name to
352 use in the new directory, and the second element is a gexp denoting the target
353 file."
354   (computed-file name
355                  #~(begin
356                      (mkdir #$output)
357                      (chdir #$output)
358                      #$@(map (match-lambda
359                                ((target source)
360                                 #~(begin
361                                     ;; Stat the source to abort early if it
362                                     ;; does not exist.
363                                     (stat #$source)
365                                     (symlink #$source #$target))))
366                              files))))
368 (define (directory-union name things)
369   "Return a directory that is the union of THINGS."
370   (match things
371     ((one)
372      ;; Only one thing; return it.
373      one)
374     (_
375      (computed-file name
376                     (with-imported-modules '((guix build union))
377                       #~(begin
378                           (use-modules (guix build union))
379                           (union-build #$output '#$things)))))))
381 (define* (activation-service->script service)
382   "Return as a monadic value the activation script for SERVICE, a service of
383 ACTIVATION-SCRIPT-TYPE."
384   (activation-script (service-value service)))
386 (define (activation-script gexps)
387   "Return the system's activation script, which evaluates GEXPS."
388   (define (service-activations)
389     ;; Return the activation scripts for SERVICES.
390     (mapm %store-monad
391           (cut gexp->file "activate-service" <>)
392           gexps))
394   (mlet* %store-monad ((actions (service-activations)))
395     (gexp->file "activate"
396                 (with-imported-modules (source-module-closure
397                                         '((gnu build activation)
398                                           (guix build utils)))
399                   #~(begin
400                       (use-modules (gnu build activation)
401                                    (guix build utils))
403                       ;; Make sure the user accounting database exists.  If it
404                       ;; does not exist, 'setutxent' does not create it and
405                       ;; thus there is no accounting at all.
406                       (close-port (open-file "/var/run/utmpx" "a0"))
408                       ;; Same for 'wtmp', which is populated by mingetty et
409                       ;; al.
410                       (mkdir-p "/var/log")
411                       (close-port (open-file "/var/log/wtmp" "a0"))
413                       ;; Set up /run/current-system.  Among other things this
414                       ;; sets up locales, which the activation snippets
415                       ;; executed below may expect.
416                       (activate-current-system)
418                       ;; Run the services' activation snippets.
419                       ;; TODO: Use 'load-compiled'.
420                       (for-each primitive-load '#$actions))))))
422 (define (gexps->activation-gexp gexps)
423   "Return a gexp that runs the activation script containing GEXPS."
424   (mlet %store-monad ((script (activation-script gexps)))
425     (return #~(primitive-load #$script))))
427 (define (second-argument a b) b)
429 (define activation-service-type
430   (service-type (name 'activate)
431                 (extensions
432                  (list (service-extension boot-service-type
433                                           gexps->activation-gexp)))
434                 (compose append)
435                 (extend second-argument)))
437 (define %activation-service
438   ;; The activation service produces the activation script from the gexps it
439   ;; receives.
440   (service activation-service-type #t))
442 (define %modprobe-wrapper
443   ;; Wrapper for the 'modprobe' command that knows where modules live.
444   ;;
445   ;; This wrapper is typically invoked by the Linux kernel ('call_modprobe',
446   ;; in kernel/kmod.c), a situation where the 'LINUX_MODULE_DIRECTORY'
447   ;; environment variable is not set---hence the need for this wrapper.
448   (let ((modprobe "/run/current-system/profile/bin/modprobe"))
449     (program-file "modprobe"
450                   #~(begin
451                       (setenv "LINUX_MODULE_DIRECTORY"
452                               "/run/booted-system/kernel/lib/modules")
453                       (apply execl #$modprobe
454                              (cons #$modprobe (cdr (command-line))))))))
456 (define %linux-kernel-activation
457   ;; Activation of the Linux kernel running on the bare metal (as opposed to
458   ;; running in a container.)
459   #~(begin
460       ;; Tell the kernel to use our 'modprobe' command.
461       (activate-modprobe #$%modprobe-wrapper)
463       ;; Let users debug their own processes!
464       (activate-ptrace-attach)))
466 (define %linux-bare-metal-service
467   ;; The service that does things that are needed on the "bare metal", but not
468   ;; necessary or impossible in a container.
469   (simple-service 'linux-bare-metal
470                   activation-service-type
471                   %linux-kernel-activation))
474 (define special-files-service-type
475   ;; Service to install "special files" such as /bin/sh and /usr/bin/env.
476   (service-type
477    (name 'special-files)
478    (extensions
479     (list (service-extension activation-service-type
480                              (lambda (files)
481                                #~(activate-special-files '#$files)))))
482    (compose concatenate)
483    (extend append)))
485 (define (extra-special-file file target)
486   "Use TARGET as the \"special file\" FILE.  For example, TARGET might be
487   (file-append coreutils \"/bin/env\")
488 and FILE could be \"/usr/bin/env\"."
489   (simple-service (string->symbol (string-append "special-file-" file))
490                   special-files-service-type
491                   `((,file ,target))))
493 (define (etc-directory service)
494   "Return the directory for SERVICE, a service of type ETC-SERVICE-TYPE."
495   (files->etc-directory (service-value service)))
497 (define (files->etc-directory files)
498   (file-union "etc" files))
500 (define (etc-entry files)
501   "Return an entry for the /etc directory consisting of FILES in the system
502 directory."
503   (with-monad %store-monad
504     (return `(("etc" ,(files->etc-directory files))))))
506 (define etc-service-type
507   (service-type (name 'etc)
508                 (extensions
509                  (list
510                   (service-extension activation-service-type
511                                      (lambda (files)
512                                        (let ((etc
513                                               (files->etc-directory files)))
514                                          #~(activate-etc #$etc))))
515                   (service-extension system-service-type etc-entry)))
516                 (compose concatenate)
517                 (extend append)))
519 (define (etc-service files)
520   "Return a new service of ETC-SERVICE-TYPE that populates /etc with FILES.
521 FILES must be a list of name/file-like object pairs."
522   (service etc-service-type files))
524 (define setuid-program-service-type
525   (service-type (name 'setuid-program)
526                 (extensions
527                  (list (service-extension activation-service-type
528                                           (lambda (programs)
529                                             #~(activate-setuid-programs
530                                                (list #$@programs))))))
531                 (compose concatenate)
532                 (extend append)))
534 (define (packages->profile-entry packages)
535   "Return a system entry for the profile containing PACKAGES."
536   (mlet %store-monad ((profile (profile-derivation
537                                 (packages->manifest
538                                  (delete-duplicates packages eq?)))))
539     (return `(("profile" ,profile)))))
541 (define profile-service-type
542   ;; The service that populates the system's profile---i.e.,
543   ;; /run/current-system/profile.  It is extended by package lists.
544   (service-type (name 'profile)
545                 (extensions
546                  (list (service-extension system-service-type
547                                           packages->profile-entry)))
548                 (compose concatenate)
549                 (extend append)))
551 (define (firmware->activation-gexp firmware)
552   "Return a gexp to make the packages listed in FIRMWARE loadable by the
553 kernel."
554   (let ((directory (directory-union "firmware" firmware)))
555     ;; Tell the kernel where firmware is.
556     #~(activate-firmware (string-append #$directory "/lib/firmware"))))
558 (define firmware-service-type
559   ;; The service that collects firmware.
560   (service-type (name 'firmware)
561                 (extensions
562                  (list (service-extension activation-service-type
563                                           firmware->activation-gexp)))
564                 (compose concatenate)
565                 (extend append)))
567 (define (gc-roots->system-entry roots)
568   "Return an entry in the system's output containing symlinks to ROOTS."
569   (mlet %store-monad ((entry (gexp->derivation
570                               "gc-roots"
571                               #~(let ((roots '#$roots))
572                                   (mkdir #$output)
573                                   (chdir #$output)
574                                   (for-each symlink
575                                             roots
576                                             (map number->string
577                                                  (iota (length roots))))))))
578     (return (if (null? roots)
579                 '()
580                 `(("gc-roots" ,entry))))))
582 (define gc-root-service-type
583   ;; A service to associate extra garbage-collector roots to the system.  This
584   ;; is a simple hack that guarantees that the system retains references to
585   ;; the given list of roots.  Roots must be "lowerable" objects like
586   ;; packages, or derivations.
587   (service-type (name 'gc-roots)
588                 (extensions
589                  (list (service-extension system-service-type
590                                           gc-roots->system-entry)))
591                 (compose concatenate)
592                 (extend append)))
596 ;;; Service folding.
599 (define-condition-type &missing-target-service-error &service-error
600   missing-target-service-error?
601   (service      missing-target-service-error-service)
602   (target-type  missing-target-service-error-target-type))
604 (define-condition-type &ambiguous-target-service-error &service-error
605   ambiguous-target-service-error?
606   (service      ambiguous-target-service-error-service)
607   (target-type  ambiguous-target-service-error-target-type))
609 (define (service-back-edges services)
610   "Return a procedure that, when passed a <service>, returns the list of
611 <service> objects that depend on it."
612   (define (add-edges service edges)
613     (define (add-edge extension edges)
614       (let ((target-type (service-extension-target extension)))
615         (match (filter (lambda (service)
616                          (eq? (service-kind service) target-type))
617                        services)
618           ((target)
619            (vhash-consq target service edges))
620           (()
621            (raise
622             (condition (&missing-target-service-error
623                         (service service)
624                         (target-type target-type))
625                        (&message
626                         (message
627                          (format #f (G_ "no target of type '~a' for service ~s")
628                                  (service-type-name target-type)
629                                  service))))))
630           (x
631            (raise
632             (condition (&ambiguous-target-service-error
633                         (service service)
634                         (target-type target-type))
635                        (&message
636                         (message
637                          (format #f
638                                  (G_ "more than one target service of type '~a'")
639                                  (service-type-name target-type))))))))))
641     (fold add-edge edges (service-type-extensions (service-kind service))))
643   (let ((edges (fold add-edges vlist-null services)))
644     (lambda (node)
645       (reverse (vhash-foldq* cons '() node edges)))))
647 (define* (fold-services services
648                         #:key (target-type system-service-type))
649   "Fold SERVICES by propagating their extensions down to the root of type
650 TARGET-TYPE; return the root service adjusted accordingly."
651   (define dependents
652     (service-back-edges services))
654   (define (matching-extension target)
655     (let ((target (service-kind target)))
656       (match-lambda
657         (($ <service-extension> type)
658          (eq? type target)))))
660   (define (apply-extension target)
661     (lambda (service)
662       (match (find (matching-extension target)
663                    (service-type-extensions (service-kind service)))
664         (($ <service-extension> _ compute)
665          (compute (service-value service))))))
667   (match (filter (lambda (service)
668                    (eq? (service-kind service) target-type))
669                  services)
670     ((sink)
671      (let loop ((sink sink))
672        (let* ((dependents (map loop (dependents sink)))
673               (extensions (map (apply-extension sink) dependents))
674               (extend     (service-type-extend (service-kind sink)))
675               (compose    (service-type-compose (service-kind sink)))
676               (params     (service-value sink)))
677          ;; We distinguish COMPOSE and EXTEND because PARAMS typically has a
678          ;; different type than the elements of EXTENSIONS.
679          (if extend
680              (service (service-kind sink)
681                       (extend params (compose extensions)))
682              sink))))
683     (()
684      (raise
685       (condition (&missing-target-service-error
686                   (service #f)
687                   (target-type target-type))
688                  (&message
689                   (message (format #f (G_ "service of type '~a' not found")
690                                    (service-type-name target-type)))))))
691     (x
692      (raise
693       (condition (&ambiguous-target-service-error
694                   (service #f)
695                   (target-type target-type))
696                  (&message
697                   (message
698                    (format #f
699                            (G_ "more than one target service of type '~a'")
700                            (service-type-name target-type)))))))))
702 ;;; services.scm ends here.