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