shepherd.scm 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  1. ;;; GNU Guix --- Functional package management for GNU
  2. ;;; Copyright © 2013, 2014, 2015, 2016, 2018, 2019, 2020, 2021 Ludovic Courtès <ludo@gnu.org>
  3. ;;; Copyright © 2017 Clément Lassieur <clement@lassieur.org>
  4. ;;; Copyright © 2018 Carlo Zancanaro <carlo@zancanaro.id.au>
  5. ;;; Copyright © 2020 Jan (janneke) Nieuwenhuizen <janneke@gnu.org>
  6. ;;; Copyright © 2021 Maxime Devos <maximedevos@telenet.be>
  7. ;;;
  8. ;;; This file is part of GNU Guix.
  9. ;;;
  10. ;;; GNU Guix is free software; you can redistribute it and/or modify it
  11. ;;; under the terms of the GNU General Public License as published by
  12. ;;; the Free Software Foundation; either version 3 of the License, or (at
  13. ;;; your option) any later version.
  14. ;;;
  15. ;;; GNU Guix is distributed in the hope that it will be useful, but
  16. ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
  17. ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. ;;; GNU General Public License for more details.
  19. ;;;
  20. ;;; You should have received a copy of the GNU General Public License
  21. ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
  22. (define-module (gnu services shepherd)
  23. #:use-module (guix ui)
  24. #:use-module (guix sets)
  25. #:use-module (guix gexp)
  26. #:use-module (guix store)
  27. #:use-module (guix records)
  28. #:use-module (guix derivations) ;imported-modules, etc.
  29. #:use-module (guix utils)
  30. #:use-module (gnu services)
  31. #:use-module (gnu services herd)
  32. #:use-module (gnu packages admin)
  33. #:use-module (ice-9 match)
  34. #:use-module (ice-9 vlist)
  35. #:use-module (srfi srfi-1)
  36. #:use-module (srfi srfi-26)
  37. #:use-module (srfi srfi-34)
  38. #:use-module (srfi srfi-35)
  39. #:export (shepherd-configuration
  40. shepherd-configuration?
  41. shepherd-configuration-shepherd
  42. shepherd-configuration-services
  43. shepherd-root-service-type
  44. %shepherd-root-service
  45. shepherd-service-type
  46. shepherd-service
  47. shepherd-service?
  48. shepherd-service-documentation
  49. shepherd-service-provision
  50. shepherd-service-canonical-name
  51. shepherd-service-requirement
  52. shepherd-service-one-shot?
  53. shepherd-service-respawn?
  54. shepherd-service-start
  55. shepherd-service-stop
  56. shepherd-service-auto-start?
  57. shepherd-service-modules
  58. shepherd-action
  59. shepherd-action?
  60. shepherd-action-name
  61. shepherd-action-documentation
  62. shepherd-action-procedure
  63. %default-modules
  64. shepherd-service-file
  65. shepherd-service-lookup-procedure
  66. shepherd-service-back-edges
  67. shepherd-service-upgrade
  68. user-processes-service-type
  69. assert-valid-graph))
  70. ;;; Commentary:
  71. ;;;
  72. ;;; Instantiating system services as a shepherd configuration file.
  73. ;;;
  74. ;;; Code:
  75. (define-record-type* <shepherd-configuration>
  76. shepherd-configuration make-shepherd-configuration
  77. shepherd-configuration?
  78. (shepherd shepherd-configuration-shepherd
  79. (default shepherd)) ; package
  80. (services shepherd-configuration-services
  81. (default '()))) ; list of <shepherd-service>
  82. (define (shepherd-boot-gexp config)
  83. "Return a gexp starting the shepherd service."
  84. (let ((shepherd (shepherd-configuration-shepherd config))
  85. (services (shepherd-configuration-services config)))
  86. #~(begin
  87. ;; Keep track of the booted system.
  88. (false-if-exception (delete-file "/run/booted-system"))
  89. ;; Make /run/booted-system, an indirect GC root, point to the store item
  90. ;; /run/current-system points to. Use 'canonicalize-path' rather than
  91. ;; 'readlink' to make sure we get the store item.
  92. (symlink (canonicalize-path "/run/current-system")
  93. "/run/booted-system")
  94. ;; Close any remaining open file descriptors to be on the safe
  95. ;; side. This must be the very last thing we do, because
  96. ;; Guile has internal FDs such as 'sleep_pipe' that need to be
  97. ;; alive.
  98. (let loop ((fd 3))
  99. (when (< fd 1024)
  100. (false-if-exception (close-fdes fd))
  101. (loop (+ 1 fd))))
  102. ;; Start shepherd.
  103. (execl #$(file-append shepherd "/bin/shepherd")
  104. "shepherd" "--config"
  105. #$(shepherd-configuration-file services shepherd)))))
  106. (define shepherd-packages
  107. (compose list shepherd-configuration-shepherd))
  108. (define shepherd-root-service-type
  109. (service-type
  110. (name 'shepherd-root)
  111. ;; Extending the root shepherd service (aka. PID 1) happens by
  112. ;; concatenating the list of services provided by the extensions.
  113. (compose concatenate)
  114. (extend (lambda (config extra-services)
  115. (shepherd-configuration
  116. (inherit config)
  117. (services (append (shepherd-configuration-services config)
  118. extra-services)))))
  119. (extensions (list (service-extension boot-service-type
  120. shepherd-boot-gexp)
  121. (service-extension profile-service-type
  122. shepherd-packages)))
  123. (default-value (shepherd-configuration))
  124. (description
  125. "Run the GNU Shepherd as PID 1---i.e., the operating system's first
  126. process. The Shepherd takes care of managing services such as daemons by
  127. ensuring they are started and stopped in the right order.")))
  128. (define %shepherd-root-service
  129. ;; The root shepherd service, aka. PID 1. Its parameter is a
  130. ;; <shepherd-configuration>.
  131. (service shepherd-root-service-type))
  132. (define-syntax shepherd-service-type
  133. (syntax-rules (description)
  134. "Return a <service-type> denoting a simple shepherd service--i.e., the type
  135. for a service that extends SHEPHERD-ROOT-SERVICE-TYPE and nothing else. When
  136. DEFAULT is given, use it as the service's default value."
  137. ((_ service-name proc default (description text))
  138. (service-type
  139. (name service-name)
  140. (extensions
  141. (list (service-extension shepherd-root-service-type
  142. (compose list proc))))
  143. (default-value default)
  144. (description text)))
  145. ((_ service-name proc (description text))
  146. (service-type
  147. (name service-name)
  148. (extensions
  149. (list (service-extension shepherd-root-service-type
  150. (compose list proc))))
  151. (description text)))))
  152. (define %default-imported-modules
  153. ;; Default set of modules imported for a service's consumption.
  154. '((guix build utils)
  155. (guix build syscalls)))
  156. (define %default-modules
  157. ;; Default set of modules visible in a service's file.
  158. `((shepherd service)
  159. (oop goops)
  160. ((guix build utils) #:hide (delete))
  161. (guix build syscalls)))
  162. (define-record-type* <shepherd-service>
  163. shepherd-service make-shepherd-service
  164. shepherd-service?
  165. (documentation shepherd-service-documentation ;string
  166. (default "[No documentation.]"))
  167. (provision shepherd-service-provision) ;list of symbols
  168. (requirement shepherd-service-requirement ;list of symbols
  169. (default '()))
  170. (one-shot? shepherd-service-one-shot? ;Boolean
  171. (default #f))
  172. (respawn? shepherd-service-respawn? ;Boolean
  173. (default #t))
  174. (start shepherd-service-start) ;g-expression (procedure)
  175. (stop shepherd-service-stop ;g-expression (procedure)
  176. (default #~(const #f)))
  177. (actions shepherd-service-actions ;list of <shepherd-action>
  178. (default '()))
  179. (auto-start? shepherd-service-auto-start? ;Boolean
  180. (default #t))
  181. (modules shepherd-service-modules ;list of module names
  182. (default %default-modules)))
  183. (define-record-type* <shepherd-action>
  184. shepherd-action make-shepherd-action
  185. shepherd-action?
  186. (name shepherd-action-name) ;symbol
  187. (procedure shepherd-action-procedure) ;gexp
  188. (documentation shepherd-action-documentation)) ;string
  189. (define (shepherd-service-canonical-name service)
  190. "Return the 'canonical name' of SERVICE."
  191. (first (shepherd-service-provision service)))
  192. (define (assert-valid-graph services)
  193. "Raise an error if SERVICES does not define a valid shepherd service graph,
  194. for instance if a service requires a nonexistent service, or if more than one
  195. service uses a given name.
  196. These are constraints that shepherd's 'register-service' verifies but we'd
  197. better verify them here statically than wait until PID 1 halts with an
  198. assertion failure."
  199. (define provisions
  200. ;; The set of provisions (symbols). Bail out if a symbol is given more
  201. ;; than once.
  202. (fold (lambda (service set)
  203. (define (assert-unique symbol)
  204. (when (set-contains? set symbol)
  205. (raise (condition
  206. (&message
  207. (message
  208. (format #f (G_ "service '~a' provided more than once")
  209. symbol)))))))
  210. (for-each assert-unique (shepherd-service-provision service))
  211. (fold set-insert set (shepherd-service-provision service)))
  212. (setq 'shepherd)
  213. services))
  214. (define (assert-satisfied-requirements service)
  215. ;; Bail out if the requirements of SERVICE aren't satisfied.
  216. (for-each (lambda (requirement)
  217. (unless (set-contains? provisions requirement)
  218. (raise (condition
  219. (&message
  220. (message
  221. (format #f (G_ "service '~a' requires '~a', \
  222. which is not provided by any service")
  223. (match (shepherd-service-provision service)
  224. ((head . _) head)
  225. (_ service))
  226. requirement)))))))
  227. (shepherd-service-requirement service)))
  228. (for-each assert-satisfied-requirements services))
  229. (define %store-characters
  230. ;; Valid store characters; see 'checkStoreName' in the daemon.
  231. (string->char-set
  232. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+-._?="))
  233. (define (shepherd-service-file-name service)
  234. "Return the file name where the initialization code for SERVICE is to be
  235. stored."
  236. (let ((provisions (string-join (map symbol->string
  237. (shepherd-service-provision service)))))
  238. (string-append "shepherd-"
  239. (string-map (lambda (chr)
  240. (if (char-set-contains? %store-characters chr)
  241. chr
  242. #\-))
  243. provisions)
  244. ".scm")))
  245. (define (shepherd-service-file service)
  246. "Return a file defining SERVICE."
  247. (scheme-file (shepherd-service-file-name service)
  248. (with-imported-modules %default-imported-modules
  249. #~(begin
  250. (use-modules #$@(shepherd-service-modules service))
  251. (make <service>
  252. #:docstring '#$(shepherd-service-documentation service)
  253. #:provides '#$(shepherd-service-provision service)
  254. #:requires '#$(shepherd-service-requirement service)
  255. ;; The 'one-shot?' slot is new in Shepherd 0.6.0.
  256. ;; Older versions ignore it.
  257. #:one-shot? '#$(shepherd-service-one-shot? service)
  258. #:respawn? '#$(shepherd-service-respawn? service)
  259. #:start #$(shepherd-service-start service)
  260. #:stop #$(shepherd-service-stop service)
  261. #:actions
  262. (make-actions
  263. #$@(map (match-lambda
  264. (($ <shepherd-action> name proc doc)
  265. #~(#$name #$doc #$proc)))
  266. (shepherd-service-actions service))))))))
  267. (define (scm->go file shepherd)
  268. "Compile FILE, which contains code to be loaded by shepherd's config file,
  269. and return the resulting '.go' file. SHEPHERD is used as shepherd package."
  270. (let-system (system target)
  271. (with-extensions (list shepherd)
  272. (computed-file (string-append (basename (scheme-file-name file) ".scm")
  273. ".go")
  274. #~(begin
  275. (use-modules (system base compile)
  276. (system base target))
  277. ;; Do the same as the Shepherd's 'load-in-user-module'.
  278. (let ((env (make-fresh-user-module)))
  279. (module-use! env (resolve-interface '(oop goops)))
  280. (module-use! env (resolve-interface '(shepherd service)))
  281. (with-target #$(or target #~%host-type)
  282. (lambda _
  283. (compile-file #$file #:output-file #$output
  284. #:env env)))))
  285. ;; It's faster to build locally than to download.
  286. #:options '(#:local-build? #t
  287. #:substitutable? #f)))))
  288. (define (shepherd-configuration-file services shepherd)
  289. "Return the shepherd configuration file for SERVICES. SHEPHERD is used
  290. as shepherd package."
  291. (assert-valid-graph services)
  292. (let ((files (map shepherd-service-file services))
  293. (scm->go (cute scm->go <> shepherd)))
  294. (define config
  295. #~(begin
  296. (use-modules (srfi srfi-34)
  297. (system repl error-handling))
  298. ;; Specify the default environment visible to all the services.
  299. ;; Without this statement, all the environment variables of PID 1
  300. ;; are inherited by child services.
  301. (default-environment-variables
  302. '("PATH=/run/current-system/profile/bin"))
  303. ;; Booting off a DVD, especially on a slow machine, can make
  304. ;; everything slow. Thus, increase the timeout compared to the
  305. ;; default 5s in the Shepherd 0.7.0. See
  306. ;; <https://bugs.gnu.org/40572>.
  307. (default-pid-file-timeout 30)
  308. ;; Arrange to spawn a REPL if something goes wrong. This is better
  309. ;; than a kernel panic.
  310. (call-with-error-handling
  311. (lambda ()
  312. (apply register-services
  313. (parameterize ((current-warning-port
  314. (%make-void-port "w")))
  315. (map load-compiled '#$(map scm->go files))))))
  316. (format #t "starting services...~%")
  317. (for-each (lambda (service)
  318. ;; In the Shepherd 0.3 the 'start' method can raise
  319. ;; '&action-runtime-error' if it fails, so protect
  320. ;; against it. (XXX: 'action-runtime-error?' is not
  321. ;; exported is 0.3, hence 'service-error?'.)
  322. (guard (c ((service-error? c)
  323. (format (current-error-port)
  324. "failed to start service '~a'~%"
  325. service)))
  326. (start service)))
  327. '#$(append-map shepherd-service-provision
  328. (filter shepherd-service-auto-start?
  329. services)))
  330. ;; Hang up stdin. At this point, we assume that 'start' methods
  331. ;; that required user interaction on the console (e.g.,
  332. ;; 'cryptsetup open' invocations, post-fsck emergency REPL) have
  333. ;; completed. User interaction becomes impossible after this
  334. ;; call; this avoids situations where services wrongfully lead
  335. ;; PID 1 to read from stdin (the console), which users may not
  336. ;; have access to (see <https://bugs.gnu.org/23697>).
  337. (redirect-port (open-input-file "/dev/null")
  338. (current-input-port))))
  339. (scheme-file "shepherd.conf" config)))
  340. (define* (shepherd-service-lookup-procedure services
  341. #:optional
  342. (provision
  343. shepherd-service-provision))
  344. "Return a procedure that, when passed a symbol, return the item among
  345. SERVICES that provides this symbol. PROVISION must be a one-argument
  346. procedure that takes a service and returns the list of symbols it provides."
  347. (let ((services (fold (lambda (service result)
  348. (fold (cut vhash-consq <> service <>)
  349. result
  350. (provision service)))
  351. vlist-null
  352. services)))
  353. (lambda (name)
  354. (match (vhash-assq name services)
  355. ((_ . service) service)
  356. (#f #f)))))
  357. (define* (shepherd-service-back-edges services
  358. #:key
  359. (provision shepherd-service-provision)
  360. (requirement shepherd-service-requirement))
  361. "Return a procedure that, when given a <shepherd-service> from SERVICES,
  362. returns the list of <shepherd-service> that depend on it.
  363. Use PROVISION and REQUIREMENT as one-argument procedures that return the
  364. symbols provided/required by a service."
  365. (define provision->service
  366. (shepherd-service-lookup-procedure services provision))
  367. (define edges
  368. (fold (lambda (service edges)
  369. (fold (lambda (requirement edges)
  370. (vhash-consq (provision->service requirement) service
  371. edges))
  372. edges
  373. (requirement service)))
  374. vlist-null
  375. services))
  376. (lambda (service)
  377. (vhash-foldq* cons '() service edges)))
  378. (define (shepherd-service-upgrade live target)
  379. "Return two values: the subset of LIVE (a list of <live-service>) that needs
  380. to be unloaded, and the subset of TARGET (a list of <shepherd-service>) that
  381. need to be restarted to complete their upgrade."
  382. (define (essential? service)
  383. (memq (first (live-service-provision service))
  384. '(root shepherd)))
  385. (define lookup-target
  386. (shepherd-service-lookup-procedure target
  387. shepherd-service-provision))
  388. (define lookup-live
  389. (shepherd-service-lookup-procedure live
  390. live-service-provision))
  391. (define (running? service)
  392. (and=> (lookup-live (shepherd-service-canonical-name service))
  393. live-service-running))
  394. (define live-service-dependents
  395. (shepherd-service-back-edges live
  396. #:provision live-service-provision
  397. #:requirement live-service-requirement))
  398. (define (obsolete? service)
  399. (match (lookup-target (first (live-service-provision service)))
  400. (#f (every obsolete? (live-service-dependents service)))
  401. (_ #f)))
  402. (define to-restart
  403. ;; Restart services that are currently running.
  404. (filter running? target))
  405. (define to-unload
  406. ;; Unload services that are no longer required.
  407. (remove essential? (filter obsolete? live)))
  408. (values to-unload to-restart))
  409. ;;;
  410. ;;; User processes.
  411. ;;;
  412. (define %do-not-kill-file
  413. ;; Name of the file listing PIDs of processes that must survive when halting
  414. ;; the system. Typical example is user-space file systems.
  415. "/etc/shepherd/do-not-kill")
  416. (define (user-processes-shepherd-service requirements)
  417. "Return the 'user-processes' Shepherd service with dependencies on
  418. REQUIREMENTS (a list of service names).
  419. This is a synchronization point used to make sure user processes and daemons
  420. get started only after crucial initial services have been started---file
  421. system mounts, etc. This is similar to the 'sysvinit' target in systemd."
  422. (define grace-delay
  423. ;; Delay after sending SIGTERM and before sending SIGKILL.
  424. 4)
  425. (list (shepherd-service
  426. (documentation "When stopped, terminate all user processes.")
  427. (provision '(user-processes))
  428. (requirement requirements)
  429. (start #~(const #t))
  430. (stop #~(lambda _
  431. (define (kill-except omit signal)
  432. ;; Kill all the processes with SIGNAL except those listed
  433. ;; in OMIT and the current process.
  434. (let ((omit (cons (getpid) omit)))
  435. (for-each (lambda (pid)
  436. (unless (memv pid omit)
  437. (false-if-exception
  438. (kill pid signal))))
  439. (processes))))
  440. (define omitted-pids
  441. ;; List of PIDs that must not be killed.
  442. (if (file-exists? #$%do-not-kill-file)
  443. (map string->number
  444. (call-with-input-file #$%do-not-kill-file
  445. (compose string-tokenize
  446. (@ (ice-9 rdelim) read-string))))
  447. '()))
  448. (define (now)
  449. (car (gettimeofday)))
  450. (define (sleep* n)
  451. ;; Really sleep N seconds.
  452. ;; Work around <http://bugs.gnu.org/19581>.
  453. (define start (now))
  454. (let loop ((elapsed 0))
  455. (when (> n elapsed)
  456. (sleep (- n elapsed))
  457. (loop (- (now) start)))))
  458. (define lset= (@ (srfi srfi-1) lset=))
  459. (display "sending all processes the TERM signal\n")
  460. (if (null? omitted-pids)
  461. (begin
  462. ;; Easy: terminate all of them.
  463. (kill -1 SIGTERM)
  464. (sleep* #$grace-delay)
  465. (kill -1 SIGKILL))
  466. (begin
  467. ;; Kill them all except OMITTED-PIDS. XXX: We would
  468. ;; like to (kill -1 SIGSTOP) to get a fixed list of
  469. ;; processes, like 'killall5' does, but that seems
  470. ;; unreliable.
  471. (kill-except omitted-pids SIGTERM)
  472. (sleep* #$grace-delay)
  473. (kill-except omitted-pids SIGKILL)
  474. (delete-file #$%do-not-kill-file)))
  475. (let wait ()
  476. ;; Reap children, if any, so that we don't end up with
  477. ;; zombies and enter an infinite loop.
  478. (let reap-children ()
  479. (define result
  480. (false-if-exception
  481. (waitpid WAIT_ANY (if (null? omitted-pids)
  482. 0
  483. WNOHANG))))
  484. (when (and (pair? result)
  485. (not (zero? (car result))))
  486. (reap-children)))
  487. (let ((pids (processes)))
  488. (unless (lset= = pids (cons 1 omitted-pids))
  489. (format #t "waiting for process termination\
  490. (processes left: ~s)~%"
  491. pids)
  492. (sleep* 2)
  493. (wait))))
  494. (display "all processes have been terminated\n")
  495. #f))
  496. (respawn? #f))))
  497. (define user-processes-service-type
  498. (service-type
  499. (name 'user-processes)
  500. (extensions (list (service-extension shepherd-root-service-type
  501. user-processes-shepherd-service)))
  502. (compose concatenate)
  503. (extend append)
  504. ;; The value is the list of Shepherd services 'user-processes' depends on.
  505. ;; Extensions can add new services to this list.
  506. (default-value '())
  507. (description "The @code{user-processes} service is responsible for
  508. terminating all the processes so that the root file system can be re-mounted
  509. read-only, just before rebooting/halting. Processes still running after a few
  510. seconds after @code{SIGTERM} has been sent are terminated with
  511. @code{SIGKILL}.")))
  512. ;;; shepherd.scm ends here