shepherd.scm 22 KB

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