services: guix-service: Remove extraneous monadism.
[jackhill/guix/guix.git] / gnu / services / base.scm
1 ;;; GNU Guix --- Functional package management for GNU
2 ;;; Copyright © 2013, 2014, 2015 Ludovic Courtès <ludo@gnu.org>
3 ;;;
4 ;;; This file is part of GNU Guix.
5 ;;;
6 ;;; GNU Guix is free software; you can redistribute it and/or modify it
7 ;;; under the terms of the GNU General Public License as published by
8 ;;; the Free Software Foundation; either version 3 of the License, or (at
9 ;;; your option) any later version.
10 ;;;
11 ;;; GNU Guix is distributed in the hope that it will be useful, but
12 ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
13 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 ;;; GNU General Public License for more details.
15 ;;;
16 ;;; You should have received a copy of the GNU General Public License
17 ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
18
19 (define-module (gnu services base)
20 #:use-module (guix store)
21 #:use-module (gnu services)
22 #:use-module (gnu services networking)
23 #:use-module (gnu system shadow) ; 'user-account', etc.
24 #:use-module (gnu system linux) ; 'pam-service', etc.
25 #:use-module (gnu packages admin)
26 #:use-module ((gnu packages linux)
27 #:select (eudev kbd e2fsprogs lvm2 fuse alsa-utils))
28 #:use-module ((gnu packages base)
29 #:select (canonical-package glibc))
30 #:use-module (gnu packages package-management)
31 #:use-module ((gnu build file-systems)
32 #:select (mount-flags->bit-mask))
33 #:use-module (guix gexp)
34 #:use-module (guix monads)
35 #:use-module (guix records)
36 #:use-module (srfi srfi-1)
37 #:use-module (srfi srfi-26)
38 #:use-module (ice-9 match)
39 #:use-module (ice-9 format)
40 #:export (root-file-system-service
41 file-system-service
42 user-unmount-service
43 device-mapping-service
44 swap-service
45 user-processes-service
46 host-name-service
47 console-font-service
48 udev-service
49 mingetty-service
50
51 %nscd-default-caches
52 %nscd-default-configuration
53
54 nscd-configuration
55 nscd-configuration?
56
57 nscd-cache
58 nscd-cache?
59
60 nscd-service
61 syslog-service
62 guix-service
63 %base-services))
64
65 ;;; Commentary:
66 ;;;
67 ;;; Base system services---i.e., services that 99% of the users will want to
68 ;;; use.
69 ;;;
70 ;;; Code:
71
72 (define (root-file-system-service)
73 "Return a service whose sole purpose is to re-mount read-only the root file
74 system upon shutdown (aka. cleanly \"umounting\" root.)
75
76 This service must be the root of the service dependency graph so that its
77 'stop' action is invoked when dmd is the only process left."
78 (with-monad %store-monad
79 (return
80 (service
81 (documentation "Take care of the root file system.")
82 (provision '(root-file-system))
83 (start #~(const #t))
84 (stop #~(lambda _
85 ;; Return #f if successfully stopped.
86 (sync)
87
88 (call-with-blocked-asyncs
89 (lambda ()
90 (let ((null (%make-void-port "w")))
91 ;; Close 'dmd.log'.
92 (display "closing log\n")
93 ;; XXX: Ideally we'd use 'stop-logging', but that one
94 ;; doesn't actually close the port as of dmd 0.1.
95 (close-port (@@ (dmd comm) log-output-port))
96 (set! (@@ (dmd comm) log-output-port) null)
97
98 ;; Redirect the default output ports..
99 (set-current-output-port null)
100 (set-current-error-port null)
101
102 ;; Close /dev/console.
103 (for-each close-fdes '(0 1 2))
104
105 ;; At this point, there are no open files left, so the
106 ;; root file system can be re-mounted read-only.
107 (mount #f "/" #f
108 (logior MS_REMOUNT MS_RDONLY)
109 #:update-mtab? #f)
110
111 #f)))))
112 (respawn? #f)))))
113
114 (define* (file-system-service device target type
115 #:key (flags '()) (check? #t)
116 create-mount-point? options (title 'any)
117 (requirements '()))
118 "Return a service that mounts DEVICE on TARGET as a file system TYPE with
119 OPTIONS. TITLE is a symbol specifying what kind of name DEVICE is: 'label for
120 a partition label, 'device for a device file name, or 'any. When CHECK? is
121 true, check the file system before mounting it. When CREATE-MOUNT-POINT? is
122 true, create TARGET if it does not exist yet. FLAGS is a list of symbols,
123 such as 'read-only' etc. Optionally, REQUIREMENTS may be a list of service
124 names such as device-mapping services."
125 (with-monad %store-monad
126 (return
127 (service
128 (provision (list (symbol-append 'file-system- (string->symbol target))))
129 (requirement `(root-file-system ,@requirements))
130 (documentation "Check, mount, and unmount the given file system.")
131 (start #~(lambda args
132 (let ((device (canonicalize-device-spec #$device '#$title)))
133 #$(if create-mount-point?
134 #~(mkdir-p #$target)
135 #~#t)
136 #$(if check?
137 #~(begin
138 ;; Make sure fsck.ext2 & co. can be found.
139 (setenv "PATH"
140 (string-append
141 #$e2fsprogs "/sbin:"
142 "/run/current-system/profile/sbin:"
143 (getenv "PATH")))
144 (check-file-system device #$type))
145 #~#t)
146 (mount device #$target #$type
147 #$(mount-flags->bit-mask flags)
148 #$options))
149 #t))
150 (stop #~(lambda args
151 ;; Normally there are no processes left at this point, so
152 ;; TARGET can be safely unmounted.
153
154 ;; Make sure PID 1 doesn't keep TARGET busy.
155 (chdir "/")
156
157 (umount #$target)
158 #f))))))
159
160 (define (user-unmount-service known-mount-points)
161 "Return a service whose sole purpose is to unmount file systems not listed
162 in KNOWN-MOUNT-POINTS when it is stopped."
163 (with-monad %store-monad
164 (return
165 (service
166 (documentation "Unmount manually-mounted file systems.")
167 (provision '(user-unmount))
168 (start #~(const #t))
169 (stop #~(lambda args
170 (define (known? mount-point)
171 (member mount-point
172 (cons* "/proc" "/sys"
173 '#$known-mount-points)))
174
175 ;; Make sure we don't keep the user's mount points busy.
176 (chdir "/")
177
178 (for-each (lambda (mount-point)
179 (format #t "unmounting '~a'...~%" mount-point)
180 (catch 'system-error
181 (lambda ()
182 (umount mount-point))
183 (lambda args
184 (let ((errno (system-error-errno args)))
185 (format #t "failed to unmount '~a': ~a~%"
186 mount-point (strerror errno))))))
187 (filter (negate known?) (mount-points)))
188 #f))))))
189
190 (define %do-not-kill-file
191 ;; Name of the file listing PIDs of processes that must survive when halting
192 ;; the system. Typical example is user-space file systems.
193 "/etc/dmd/do-not-kill")
194
195 (define* (user-processes-service requirements #:key (grace-delay 4))
196 "Return the service that is responsible for terminating all the processes so
197 that the root file system can be re-mounted read-only, just before
198 rebooting/halting. Processes still running GRACE-DELAY seconds after SIGTERM
199 has been sent are terminated with SIGKILL.
200
201 The returned service will depend on 'root-file-system' and on all the services
202 listed in REQUIREMENTS.
203
204 All the services that spawn processes must depend on this one so that they are
205 stopped before 'kill' is called."
206 (with-monad %store-monad
207 (return (service
208 (documentation "When stopped, terminate all user processes.")
209 (provision '(user-processes))
210 (requirement (cons 'root-file-system requirements))
211 (start #~(const #t))
212 (stop #~(lambda _
213 (define (kill-except omit signal)
214 ;; Kill all the processes with SIGNAL except those
215 ;; listed in OMIT and the current process.
216 (let ((omit (cons (getpid) omit)))
217 (for-each (lambda (pid)
218 (unless (memv pid omit)
219 (false-if-exception
220 (kill pid signal))))
221 (processes))))
222
223 (define omitted-pids
224 ;; List of PIDs that must not be killed.
225 (if (file-exists? #$%do-not-kill-file)
226 (map string->number
227 (call-with-input-file #$%do-not-kill-file
228 (compose string-tokenize
229 (@ (ice-9 rdelim) read-string))))
230 '()))
231
232 (define (now)
233 (car (gettimeofday)))
234
235 (define (sleep* n)
236 ;; Really sleep N seconds.
237 ;; Work around <http://bugs.gnu.org/19581>.
238 (define start (now))
239 (let loop ((elapsed 0))
240 (when (> n elapsed)
241 (sleep (- n elapsed))
242 (loop (- (now) start)))))
243
244 (define lset= (@ (srfi srfi-1) lset=))
245
246 (display "sending all processes the TERM signal\n")
247
248 (if (null? omitted-pids)
249 (begin
250 ;; Easy: terminate all of them.
251 (kill -1 SIGTERM)
252 (sleep* #$grace-delay)
253 (kill -1 SIGKILL))
254 (begin
255 ;; Kill them all except OMITTED-PIDS. XXX: We
256 ;; would like to (kill -1 SIGSTOP) to get a fixed
257 ;; list of processes, like 'killall5' does, but
258 ;; that seems unreliable.
259 (kill-except omitted-pids SIGTERM)
260 (sleep* #$grace-delay)
261 (kill-except omitted-pids SIGKILL)
262 (delete-file #$%do-not-kill-file)))
263
264 (let wait ()
265 (let ((pids (processes)))
266 (unless (lset= = pids (cons 1 omitted-pids))
267 (format #t "waiting for process termination\
268 (processes left: ~s)~%"
269 pids)
270 (sleep* 2)
271 (wait))))
272
273 (display "all processes have been terminated\n")
274 #f))
275 (respawn? #f)))))
276
277 (define (host-name-service name)
278 "Return a service that sets the host name to @var{name}."
279 (with-monad %store-monad
280 (return (service
281 (documentation "Initialize the machine's host name.")
282 (provision '(host-name))
283 (start #~(lambda _
284 (sethostname #$name)))
285 (respawn? #f)))))
286
287 (define (unicode-start tty)
288 "Return a gexp to start Unicode support on @var{tty}."
289
290 ;; We have to run 'unicode_start' in a pipe so that when it invokes the
291 ;; 'tty' command, that command returns TTY.
292 #~(begin
293 (let ((pid (primitive-fork)))
294 (case pid
295 ((0)
296 (close-fdes 0)
297 (dup2 (open-fdes #$tty O_RDONLY) 0)
298 (close-fdes 1)
299 (dup2 (open-fdes #$tty O_WRONLY) 1)
300 (execl (string-append #$kbd "/bin/unicode_start")
301 "unicode_start"))
302 (else
303 (zero? (cdr (waitpid pid))))))))
304
305 (define* (console-font-service tty #:optional (font "LatGrkCyr-8x16"))
306 "Return a service that sets up Unicode support in @var{tty} and loads
307 @var{font} for that tty (fonts are per virtual console in Linux.)"
308 ;; Note: 'LatGrkCyr-8x16' has the advantage of providing three common
309 ;; scripts as well as glyphs for em dash, quotation marks, and other Unicode
310 ;; codepoints notably found in the UTF-8 manual.
311 (let ((device (string-append "/dev/" tty)))
312 (with-monad %store-monad
313 (return (service
314 (documentation "Load a Unicode console font.")
315 (provision (list (symbol-append 'console-font-
316 (string->symbol tty))))
317
318 ;; Start after mingetty has been started on TTY, otherwise the
319 ;; settings are ignored.
320 (requirement (list (symbol-append 'term-
321 (string->symbol tty))))
322
323 (start #~(lambda _
324 (and #$(unicode-start device)
325 (zero?
326 (system* (string-append #$kbd "/bin/setfont")
327 "-C" #$device #$font)))))
328 (stop #~(const #t))
329 (respawn? #f))))))
330
331 (define* (mingetty-service tty
332 #:key
333 (motd (text-file "motd" "Welcome.\n"))
334 auto-login
335 login-program
336 login-pause?
337
338 ;; Allow empty passwords by default so that
339 ;; first-time users can log in when the 'root'
340 ;; account has just been created.
341 (allow-empty-passwords? #t))
342 "Return a service to run mingetty on @var{tty}.
343
344 When @var{allow-empty-passwords?} is true, allow empty log-in password. When
345 @var{auto-login} is true, it must be a user name under which to log-in
346 automatically. @var{login-pause?} can be set to @code{#t} in conjunction with
347 @var{auto-login}, in which case the user will have to press a key before the
348 login shell is launched.
349
350 When true, @var{login-program} is a gexp or a monadic gexp denoting the name
351 of the log-in program (the default is the @code{login} program from the Shadow
352 tool suite.)
353
354 @var{motd} is a monadic value containing a text file to use as
355 the ``message of the day''."
356 (mlet %store-monad ((motd motd)
357 (login-program (cond ((gexp? login-program)
358 (return login-program))
359 ((not login-program)
360 (return #f))
361 (else
362 login-program))))
363 (return
364 (service
365 (documentation (string-append "Run mingetty on " tty "."))
366 (provision (list (symbol-append 'term- (string->symbol tty))))
367
368 ;; Since the login prompt shows the host name, wait for the 'host-name'
369 ;; service to be done. Also wait for udev essentially so that the tty
370 ;; text is not lost in the middle of kernel messages (XXX).
371 (requirement '(user-processes host-name udev))
372
373 (start #~(make-forkexec-constructor
374 (list (string-append #$mingetty "/sbin/mingetty")
375 "--noclear" #$tty
376 #$@(if auto-login
377 #~("--autologin" #$auto-login)
378 #~())
379 #$@(if login-program
380 #~("--loginprog" #$login-program)
381 #~())
382 #$@(if login-pause?
383 #~("--loginpause")
384 #~()))))
385 (stop #~(make-kill-destructor))
386
387 (pam-services
388 ;; Let 'login' be known to PAM. All the mingetty services will have
389 ;; that PAM service, but that's fine because they're all identical and
390 ;; duplicates are removed.
391 (list (unix-pam-service "login"
392 #:allow-empty-passwords? allow-empty-passwords?
393 #:motd motd)))))))
394
395 (define-record-type* <nscd-configuration> nscd-configuration
396 make-nscd-configuration
397 nscd-configuration?
398 (log-file nscd-configuration-log-file ;string
399 (default "/var/log/nscd.log"))
400 (debug-level nscd-debug-level ;integer
401 (default 0))
402 ;; TODO: See nscd.conf in glibc for other options to add.
403 (caches nscd-configuration-caches ;list of <nscd-cache>
404 (default %nscd-default-caches)))
405
406 (define-record-type* <nscd-cache> nscd-cache make-nscd-cache
407 nscd-cache?
408 (database nscd-cache-database) ;symbol
409 (positive-time-to-live nscd-cache-positive-time-to-live) ;integer
410 (negative-time-to-live nscd-cache-negative-time-to-live
411 (default 20)) ;integer
412 (suggested-size nscd-cache-suggested-size ;integer ("default module
413 ;of hash table")
414 (default 211))
415 (check-files? nscd-cache-check-files? ;Boolean
416 (default #t))
417 (persistent? nscd-cache-persistent? ;Boolean
418 (default #t))
419 (shared? nscd-cache-shared? ;Boolean
420 (default #t))
421 (max-database-size nscd-cache-max-database-size ;integer
422 (default (* 32 (expt 2 20))))
423 (auto-propagate? nscd-cache-auto-propagate? ;Boolean
424 (default #t)))
425
426 (define %nscd-default-caches
427 ;; Caches that we want to enable by default. Note that when providing an
428 ;; empty nscd.conf, all caches are disabled.
429 (list (nscd-cache (database 'hosts)
430
431 ;; Aggressively cache the host name cache to improve
432 ;; privacy and resilience.
433 (positive-time-to-live (* 3600 12))
434 (negative-time-to-live 20)
435 (persistent? #t))
436
437 (nscd-cache (database 'services)
438
439 ;; Services are unlikely to change, so we can be even more
440 ;; aggressive.
441 (positive-time-to-live (* 3600 24))
442 (negative-time-to-live 3600)
443 (check-files? #t) ;check /etc/services changes
444 (persistent? #t))))
445
446 (define %nscd-default-configuration
447 ;; Default nscd configuration.
448 (nscd-configuration))
449
450 (define (nscd.conf-file config)
451 "Return the @file{nscd.conf} configuration file for @var{config}, an
452 @code{<nscd-configuration>} object."
453 (define cache->config
454 (match-lambda
455 (($ <nscd-cache> (= symbol->string database)
456 positive-ttl negative-ttl size check-files?
457 persistent? shared? max-size propagate?)
458 (string-append "\nenable-cache\t" database "\tyes\n"
459
460 "positive-time-to-live\t" database "\t"
461 (number->string positive-ttl) "\n"
462 "negative-time-to-live\t" database "\t"
463 (number->string negative-ttl) "\n"
464 "suggested-size\t" database "\t"
465 (number->string size) "\n"
466 "check-files\t" database "\t"
467 (if check-files? "yes\n" "no\n")
468 "persistent\t" database "\t"
469 (if persistent? "yes\n" "no\n")
470 "shared\t" database "\t"
471 (if shared? "yes\n" "no\n")
472 "max-db-size\t" database "\t"
473 (number->string max-size) "\n"
474 "auto-propagate\t" database "\t"
475 (if propagate? "yes\n" "no\n")))))
476
477 (match config
478 (($ <nscd-configuration> log-file debug-level caches)
479 (text-file "nscd.conf"
480 (string-append "\
481 # Configuration of libc's name service cache daemon (nscd).\n\n"
482 (if log-file
483 (string-append "logfile\t" log-file)
484 "")
485 "\n"
486 (if debug-level
487 (string-append "debug-level\t"
488 (number->string debug-level))
489 "")
490 "\n"
491 (string-concatenate
492 (map cache->config caches)))))))
493
494 (define* (nscd-service #:optional (config %nscd-default-configuration)
495 #:key (glibc (canonical-package glibc))
496 (name-services '()))
497 "Return a service that runs libc's name service cache daemon (nscd) with the
498 given @var{config}---an @code{<nscd-configuration>} object. Optionally,
499 @code{#:name-services} is a list of packages that provide name service switch
500 (NSS) modules needed by nscd."
501 (mlet %store-monad ((nscd.conf (nscd.conf-file config)))
502 (return (service
503 (documentation "Run libc's name service cache daemon (nscd).")
504 (provision '(nscd))
505 (requirement '(user-processes))
506
507 (activate #~(begin
508 (use-modules (guix build utils))
509 (mkdir-p "/var/run/nscd")
510 (mkdir-p "/var/db/nscd"))) ;for the persistent cache
511
512 (start #~(make-forkexec-constructor
513 (list (string-append #$glibc "/sbin/nscd")
514 "-f" #$nscd.conf "--foreground")
515
516 #:environment-variables
517 (list (string-append "LD_LIBRARY_PATH="
518 (string-join
519 (map (lambda (dir)
520 (string-append dir "/lib"))
521 (list #$@name-services))
522 ":")))))
523 (stop #~(make-kill-destructor))
524
525 (respawn? #f)))))
526
527 (define (syslog-service)
528 "Return a service that runs @code{syslogd} with reasonable default settings."
529
530 ;; Snippet adapted from the GNU inetutils manual.
531 (define contents "
532 # Log all error messages, authentication messages of
533 # level notice or higher and anything of level err or
534 # higher to the console.
535 # Don't log private authentication messages!
536 *.alert;auth.notice;authpriv.none /dev/console
537
538 # Log anything (except mail) of level info or higher.
539 # Don't log private authentication messages!
540 *.info;mail.none;authpriv.none /var/log/messages
541
542 # Same, in a different place.
543 *.info;mail.none;authpriv.none /dev/tty12
544
545 # The authpriv file has restricted access.
546 authpriv.* /var/log/secure
547
548 # Log all the mail messages in one place.
549 mail.* /var/log/maillog
550 ")
551
552 (mlet %store-monad
553 ((syslog.conf (text-file "syslog.conf" contents)))
554 (return
555 (service
556 (documentation "Run the syslog daemon (syslogd).")
557 (provision '(syslogd))
558 (requirement '(user-processes))
559 (start
560 #~(make-forkexec-constructor
561 (list (string-append #$inetutils "/libexec/syslogd")
562 "--no-detach" "--rcfile" #$syslog.conf)))
563 (stop #~(make-kill-destructor))))))
564
565 (define* (guix-build-accounts count #:key
566 (group "guixbuild")
567 (first-uid 30001)
568 (shadow shadow))
569 "Return a list of COUNT user accounts for Guix build users, with UIDs
570 starting at FIRST-UID, and under GID."
571 (unfold (cut > <> count)
572 (lambda (n)
573 (user-account
574 (name (format #f "guixbuilder~2,'0d" n))
575 (system? #t)
576 (uid (+ first-uid n -1))
577 (group group)
578
579 ;; guix-daemon expects GROUP to be listed as a
580 ;; supplementary group too:
581 ;; <http://lists.gnu.org/archive/html/bug-guix/2013-01/msg00239.html>.
582 (supplementary-groups (list group "kvm"))
583
584 (comment (format #f "Guix Build User ~2d" n))
585 (home-directory "/var/empty")
586 (shell #~(string-append #$shadow "/sbin/nologin"))))
587 1+
588 1))
589
590 (define (hydra-key-authorization guix)
591 "Return a gexp with code to register the hydra.gnu.org public key with
592 GUIX."
593 #~(unless (file-exists? "/etc/guix/acl")
594 (let ((pid (primitive-fork)))
595 (case pid
596 ((0)
597 (let* ((key (string-append #$guix
598 "/share/guix/hydra.gnu.org.pub"))
599 (port (open-file key "r0b")))
600 (format #t "registering public key '~a'...~%" key)
601 (close-port (current-input-port))
602 (dup port 0)
603 (execl (string-append #$guix "/bin/guix")
604 "guix" "archive" "--authorize")
605 (exit 1)))
606 (else
607 (let ((status (cdr (waitpid pid))))
608 (unless (zero? status)
609 (format (current-error-port) "warning: \
610 failed to register hydra.gnu.org public key: ~a~%" status))))))))
611
612 (define* (guix-service #:key (guix guix) (builder-group "guixbuild")
613 (build-accounts 10) (authorize-hydra-key? #t)
614 (use-substitutes? #t)
615 (extra-options '()))
616 "Return a service that runs the build daemon from @var{guix}, and has
617 @var{build-accounts} user accounts available under @var{builder-group}.
618
619 When @var{authorize-hydra-key?} is true, the @code{hydra.gnu.org} public key
620 provided by @var{guix} is authorized upon activation, meaning that substitutes
621 from @code{hydra.gnu.org} are used by default.
622
623 If @var{use-substitutes?} is false, the daemon is run with
624 @option{--no-substitutes} (@pxref{Invoking guix-daemon,
625 @option{--no-substitutes}}).
626
627 Finally, @var{extra-options} is a list of additional command-line options
628 passed to @command{guix-daemon}."
629 (define activate
630 ;; Assume that the store has BUILDER-GROUP as its group. We could
631 ;; otherwise call 'chown' here, but the problem is that on a COW unionfs,
632 ;; chown leads to an entire copy of the tree, which is a bad idea.
633
634 ;; Optionally authorize hydra.gnu.org's key.
635 (and authorize-hydra-key?
636 (hydra-key-authorization guix)))
637
638 (with-monad %store-monad
639 (return (service
640 (provision '(guix-daemon))
641 (requirement '(user-processes))
642 (start
643 #~(make-forkexec-constructor
644 (list (string-append #$guix "/bin/guix-daemon")
645 "--build-users-group" #$builder-group
646 #$@(if use-substitutes?
647 '()
648 '("--no-substitutes"))
649 #$@extra-options)))
650 (stop #~(make-kill-destructor))
651 (user-accounts (guix-build-accounts build-accounts
652 #:group builder-group))
653 (user-groups (list (user-group
654 (name builder-group)
655 (system? #t)
656
657 ;; Use a fixed GID so that we can create the
658 ;; store with the right owner.
659 (id 30000))))
660 (activate activate)))))
661
662 (define (udev-rules-union packages)
663 "Return the union of the @code{lib/udev/rules.d} directories found in each
664 item of @var{packages}."
665 (define build
666 #~(begin
667 (use-modules (guix build union)
668 (guix build utils)
669 (srfi srfi-1)
670 (srfi srfi-26))
671
672 (define %standard-locations
673 '("/lib/udev/rules.d" "/libexec/udev/rules.d"))
674
675 (define (rules-sub-directory directory)
676 ;; Return the sub-directory of DIRECTORY containing udev rules, or
677 ;; #f if none was found.
678 (find directory-exists?
679 (map (cut string-append directory <>) %standard-locations)))
680
681 (mkdir-p (string-append #$output "/lib/udev"))
682 (union-build (string-append #$output "/lib/udev/rules.d")
683 (filter-map rules-sub-directory '#$packages))))
684
685 (gexp->derivation "udev-rules" build
686 #:modules '((guix build union)
687 (guix build utils))
688 #:local-build? #t))
689
690 (define* (kvm-udev-rule)
691 "Return a directory with a udev rule that changes the group of
692 @file{/dev/kvm} to \"kvm\" and makes it #o660."
693 ;; Apparently QEMU-KVM used to ship this rule, but now we have to add it by
694 ;; ourselves.
695 (gexp->derivation "kvm-udev-rules"
696 #~(begin
697 (use-modules (guix build utils))
698
699 (define rules.d
700 (string-append #$output "/lib/udev/rules.d"))
701
702 (mkdir-p rules.d)
703 (call-with-output-file
704 (string-append rules.d "/90-kvm.rules")
705 (lambda (port)
706 ;; FIXME: As a workaround for
707 ;; <http://bugs.gnu.org/18994>, make /dev/kvm 666
708 ;; instead of 660.
709 (display "\
710 KERNEL==\"kvm\", GROUP=\"kvm\", MODE=\"0666\"\n" port))))
711 #:modules '((guix build utils))))
712
713 (define* (udev-service #:key (udev eudev) (rules '()))
714 "Run @var{udev}, which populates the @file{/dev} directory dynamically. Get
715 extra rules from the packages listed in @var{rules}."
716 (mlet* %store-monad ((kvm (kvm-udev-rule))
717 (rules (udev-rules-union (cons* udev kvm rules)))
718 (udev.conf (text-file* "udev.conf"
719 "udev_rules=\"" rules
720 "/lib/udev/rules.d\"\n")))
721 (return (service
722 (provision '(udev))
723
724 ;; Udev needs /dev to be a 'devtmpfs' mount so that new device
725 ;; nodes can be added: see
726 ;; <http://www.linuxfromscratch.org/lfs/view/development/chapter07/udev.html>.
727 (requirement '(root-file-system))
728
729 (documentation "Populate the /dev directory, dynamically.")
730 (start #~(lambda ()
731 (define find
732 (@ (srfi srfi-1) find))
733
734 (define udevd
735 ;; Choose the right 'udevd'.
736 (find file-exists?
737 (map (lambda (suffix)
738 (string-append #$udev suffix))
739 '("/libexec/udev/udevd" ;udev
740 "/sbin/udevd")))) ;eudev
741
742 (define (wait-for-udevd)
743 ;; Wait until someone's listening on udevd's control
744 ;; socket.
745 (let ((sock (socket AF_UNIX SOCK_SEQPACKET 0)))
746 (let try ()
747 (catch 'system-error
748 (lambda ()
749 (connect sock PF_UNIX "/run/udev/control")
750 (close-port sock))
751 (lambda args
752 (format #t "waiting for udevd...~%")
753 (usleep 500000)
754 (try))))))
755
756 ;; Allow udev to find the modules.
757 (setenv "LINUX_MODULE_DIRECTORY"
758 "/run/booted-system/kernel/lib/modules")
759
760 ;; The first one is for udev, the second one for eudev.
761 (setenv "UDEV_CONFIG_FILE" #$udev.conf)
762 (setenv "EUDEV_RULES_DIRECTORY"
763 (string-append #$rules "/lib/udev/rules.d"))
764
765 (let ((pid (primitive-fork)))
766 (case pid
767 ((0)
768 (exec-command (list udevd)))
769 (else
770 ;; Wait until udevd is up and running. This
771 ;; appears to be needed so that the events
772 ;; triggered below are actually handled.
773 (wait-for-udevd)
774
775 ;; Trigger device node creation.
776 (system* (string-append #$udev "/bin/udevadm")
777 "trigger" "--action=add")
778
779 ;; Wait for things to settle down.
780 (system* (string-append #$udev "/bin/udevadm")
781 "settle")
782 pid)))))
783 (stop #~(make-kill-destructor))
784
785 ;; When halting the system, 'udev' is actually killed by
786 ;; 'user-processes', i.e., before its own 'stop' method was
787 ;; called. Thus, make sure it is not respawned.
788 (respawn? #f)))))
789
790 (define (device-mapping-service target open close)
791 "Return a service that maps device @var{target}, a string such as
792 @code{\"home\"} (meaning @code{/dev/mapper/home}). Evaluate @var{open}, a
793 gexp, to open it, and evaluate @var{close} to close it."
794 (with-monad %store-monad
795 (return (service
796 (provision (list (symbol-append 'device-mapping-
797 (string->symbol target))))
798 (requirement '(udev))
799 (documentation "Map a device node using Linux's device mapper.")
800 (start #~(lambda () #$open))
801 (stop #~(lambda _ (not #$close)))
802 (respawn? #f)))))
803
804 (define (swap-service device)
805 "Return a service that uses @var{device} as a swap device."
806 (define requirement
807 (if (string-prefix? "/dev/mapper/" device)
808 (list (symbol-append 'device-mapping-
809 (string->symbol (basename device))))
810 '()))
811
812 (with-monad %store-monad
813 (return (service
814 (provision (list (symbol-append 'swap- (string->symbol device))))
815 (requirement `(udev ,@requirement))
816 (documentation "Enable the given swap device.")
817 (start #~(lambda ()
818 (swapon #$device)
819 #t))
820 (stop #~(lambda _
821 (swapoff #$device)
822 #f))
823 (respawn? #f)))))
824
825 (define %base-services
826 ;; Convenience variable holding the basic services.
827 (let ((motd (text-file "motd" "
828 This is the GNU operating system, welcome!\n\n")))
829 (list (console-font-service "tty1")
830 (console-font-service "tty2")
831 (console-font-service "tty3")
832 (console-font-service "tty4")
833 (console-font-service "tty5")
834 (console-font-service "tty6")
835
836 (mingetty-service "tty1" #:motd motd)
837 (mingetty-service "tty2" #:motd motd)
838 (mingetty-service "tty3" #:motd motd)
839 (mingetty-service "tty4" #:motd motd)
840 (mingetty-service "tty5" #:motd motd)
841 (mingetty-service "tty6" #:motd motd)
842 (static-networking-service "lo" "127.0.0.1"
843 #:provision '(loopback))
844 (syslog-service)
845 (guix-service)
846 (nscd-service)
847
848 ;; The LVM2 rules are needed as soon as LVM2 or the device-mapper is
849 ;; used, so enable them by default. The FUSE and ALSA rules are
850 ;; less critical, but handy.
851 (udev-service #:rules (list lvm2 fuse alsa-utils)))))
852
853 ;;; base.scm ends here