chiark / gitweb /
unit: allow state change from running to restarting
[elogind.git] / service.c
1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2010 Lennart Poettering
7
8   systemd is free software; you can redistribute it and/or modify it
9   under the terms of the GNU General Public License as published by
10   the Free Software Foundation; either version 2 of the License, or
11   (at your option) any later version.
12
13   systemd is distributed in the hope that it will be useful, but
14   WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16   General Public License for more details.
17
18   You should have received a copy of the GNU General Public License
19   along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <errno.h>
23 #include <signal.h>
24 #include <dirent.h>
25 #include <unistd.h>
26
27 #include "unit.h"
28 #include "service.h"
29 #include "load-fragment.h"
30 #include "load-dropin.h"
31 #include "log.h"
32 #include "strv.h"
33
34 #define COMMENTS "#;\n"
35 #define NEWLINES "\n\r"
36 #define LINE_MAX 4096
37
38 static const char * const rcnd_table[] = {
39         "/rc0.d",  SPECIAL_RUNLEVEL0_TARGET,
40         "/rc1.d",  SPECIAL_RUNLEVEL1_TARGET,
41         "/rc2.d",  SPECIAL_RUNLEVEL2_TARGET,
42         "/rc3.d",  SPECIAL_RUNLEVEL3_TARGET,
43         "/rc4.d",  SPECIAL_RUNLEVEL4_TARGET,
44         "/rc5.d",  SPECIAL_RUNLEVEL5_TARGET,
45         "/rc6.d",  SPECIAL_RUNLEVEL6_TARGET,
46         "/boot.d", SPECIAL_BASIC_TARGET
47 };
48
49 static const UnitActiveState state_translation_table[_SERVICE_STATE_MAX] = {
50         [SERVICE_DEAD] = UNIT_INACTIVE,
51         [SERVICE_START_PRE] = UNIT_ACTIVATING,
52         [SERVICE_START] = UNIT_ACTIVATING,
53         [SERVICE_START_POST] = UNIT_ACTIVATING,
54         [SERVICE_RUNNING] = UNIT_ACTIVE,
55         [SERVICE_EXITED] = UNIT_ACTIVE,
56         [SERVICE_RELOAD] = UNIT_ACTIVE_RELOADING,
57         [SERVICE_STOP] = UNIT_DEACTIVATING,
58         [SERVICE_STOP_SIGTERM] = UNIT_DEACTIVATING,
59         [SERVICE_STOP_SIGKILL] = UNIT_DEACTIVATING,
60         [SERVICE_STOP_POST] = UNIT_DEACTIVATING,
61         [SERVICE_FINAL_SIGTERM] = UNIT_DEACTIVATING,
62         [SERVICE_FINAL_SIGKILL] = UNIT_DEACTIVATING,
63         [SERVICE_MAINTAINANCE] = UNIT_INACTIVE,
64         [SERVICE_AUTO_RESTART] = UNIT_ACTIVATING,
65 };
66
67 static void service_unwatch_control_pid(Service *s) {
68         assert(s);
69
70         if (s->control_pid <= 0)
71                 return;
72
73         unit_unwatch_pid(UNIT(s), s->control_pid);
74         s->control_pid = 0;
75 }
76
77 static void service_unwatch_main_pid(Service *s) {
78         assert(s);
79
80         if (s->main_pid <= 0)
81                 return;
82
83         unit_unwatch_pid(UNIT(s), s->main_pid);
84         s->main_pid = 0;
85 }
86
87 static void service_done(Unit *u) {
88         Service *s = SERVICE(u);
89
90         assert(s);
91
92         free(s->pid_file);
93         s->pid_file = NULL;
94
95         free(s->sysv_path);
96         s->sysv_path = NULL;
97
98         free(s->sysv_runlevels);
99         s->sysv_runlevels = NULL;
100
101         exec_context_done(&s->exec_context);
102         exec_command_free_array(s->exec_command, _SERVICE_EXEC_COMMAND_MAX);
103         s->control_command = NULL;
104
105         /* This will leak a process, but at least no memory or any of
106          * our resources */
107         service_unwatch_main_pid(s);
108         service_unwatch_control_pid(s);
109
110         unit_unwatch_timer(u, &s->timer_watch);
111 }
112
113 static int sysv_translate_name(const char *name, char **_r) {
114
115         static const char * const table[] = {
116                 "$local_fs",  SPECIAL_LOCAL_FS_TARGET,
117                 "$network",   SPECIAL_NETWORK_TARGET,
118                 "$named",     SPECIAL_NSS_LOOKUP_TARGET,
119                 "$portmap",   SPECIAL_RPCBIND_TARGET,
120                 "$remote_fs", SPECIAL_REMOTE_FS_TARGET,
121                 "$syslog",    SPECIAL_SYSLOG_TARGET,
122                 "$time",      SPECIAL_RTC_SET_TARGET
123         };
124
125         unsigned i;
126         char *r;
127
128         for (i = 0; i < ELEMENTSOF(table); i += 2)
129                 if (streq(table[i], name)) {
130                         if (!(r = strdup(table[i+1])))
131                                 return -ENOMEM;
132
133                         goto finish;
134                 }
135
136         if (*name == '$')
137                 return 0;
138
139         if (asprintf(&r, "%s.service", name) < 0)
140                 return -ENOMEM;
141
142 finish:
143
144         if (_r)
145                 *_r = r;
146
147         return 1;
148 }
149
150 static int sysv_chkconfig_order(Service *s) {
151         Meta *other;
152         int r;
153
154         assert(s);
155
156         if (s->sysv_start_priority < 0)
157                 return 0;
158
159         /* For each pair of services where at least one lacks a LSB
160          * header, we use the start priority value to order things. */
161
162         LIST_FOREACH(units_per_type, other, UNIT(s)->meta.manager->units_per_type[UNIT_SERVICE]) {
163                 Service *t;
164                 UnitDependency d;
165
166                 t = (Service*) other;
167
168                 if (s == t)
169                         continue;
170
171                 if (t->sysv_start_priority < 0)
172                         continue;
173
174                 /* If both units have modern headers we don't care
175                  * about the priorities */
176                 if ((!s->sysv_path || s->sysv_has_lsb) &&
177                     (!t->sysv_path || t->sysv_has_lsb))
178                         continue;
179
180                 if (t->sysv_start_priority < s->sysv_start_priority)
181                         d = UNIT_AFTER;
182                 else if (t->sysv_start_priority > s->sysv_start_priority)
183                         d = UNIT_BEFORE;
184                 else
185                         continue;
186
187                 /* FIXME: Maybe we should compare the name here lexicographically? */
188
189                 if (!(r = unit_add_dependency(UNIT(s), d, UNIT(t))) < 0)
190                         return r;
191         }
192
193         return 0;
194 }
195
196 static ExecCommand *exec_command_new(const char *path, const char *arg1) {
197         ExecCommand *c;
198
199         if (!(c = new0(ExecCommand, 1)))
200                 return NULL;
201
202         if (!(c->path = strdup(path))) {
203                 free(c);
204                 return NULL;
205         }
206
207         if (!(c->argv = strv_new(path, arg1, NULL))) {
208                 free(c->path);
209                 free(c);
210                 return NULL;
211         }
212
213         return c;
214 }
215
216 static int sysv_exec_commands(Service *s) {
217         ExecCommand *c;
218
219         assert(s);
220         assert(s->sysv_path);
221
222         if (!(c = exec_command_new(s->sysv_path, "start")))
223                 return -ENOMEM;
224         exec_command_append_list(s->exec_command+SERVICE_EXEC_START, c);
225
226         if (!(c = exec_command_new(s->sysv_path, "stop")))
227                 return -ENOMEM;
228         exec_command_append_list(s->exec_command+SERVICE_EXEC_STOP, c);
229
230         if (!(c = exec_command_new(s->sysv_path, "reload")))
231                 return -ENOMEM;
232         exec_command_append_list(s->exec_command+SERVICE_EXEC_RELOAD, c);
233
234         return 0;
235 }
236
237 static int priority_from_rcd(Service *s, const char *init_script) {
238         char **p;
239         unsigned i;
240
241         STRV_FOREACH(p, UNIT(s)->meta.manager->sysvrcnd_path)
242                 for (i = 0; i < ELEMENTSOF(rcnd_table); i += 2) {
243                         char *path;
244                         DIR *d;
245                         struct dirent *de;
246
247                         if (asprintf(&path, "%s/%s", *p, rcnd_table[i]) < 0)
248                                 return -ENOMEM;
249
250                         d = opendir(path);
251                         free(path);
252
253                         if (!d) {
254                                 if (errno != ENOENT)
255                                         log_warning("opendir() failed on %s: %s", path, strerror(errno));
256
257                                 continue;
258                         }
259
260                         while ((de = readdir(d))) {
261                                 int a, b;
262
263                                 if (ignore_file(de->d_name))
264                                         continue;
265
266                                 if (de->d_name[0] != 'S')
267                                         continue;
268
269                                 if (strlen(de->d_name) < 4)
270                                         continue;
271
272                                 if (!streq(de->d_name + 3, init_script))
273                                         continue;
274
275                                 /* Yay, we found it! Now decode the priority */
276
277                                 a = undecchar(de->d_name[1]);
278                                 b = undecchar(de->d_name[2]);
279
280                                 if (a < 0 || b < 0)
281                                         continue;
282
283                                 s->sysv_start_priority = a*10 + b;
284
285                                 log_debug("Determined priority %i from link farm for %s", s->sysv_start_priority, unit_id(UNIT(s)));
286
287                                 closedir(d);
288                                 return 0;
289                         }
290
291                         closedir(d);
292                 }
293
294         return 0;
295 }
296
297 static int service_load_sysv_path(Service *s, const char *path) {
298         FILE *f;
299         Unit *u;
300         unsigned line = 0;
301         int r;
302         enum {
303                 NORMAL,
304                 DESCRIPTION,
305                 LSB,
306                 LSB_DESCRIPTION
307         } state = NORMAL;
308
309         assert(s);
310         assert(path);
311
312         u = UNIT(s);
313
314         if (!(f = fopen(path, "re"))) {
315                 r = errno == ENOENT ? 0 : -errno;
316                 goto finish;
317         }
318
319         s->type = SERVICE_FORKING;
320         s->restart = SERVICE_ONCE;
321
322         free(s->sysv_path);
323         if (!(s->sysv_path = strdup(path))) {
324                 r = -ENOMEM;
325                 goto finish;
326         }
327
328         while (!feof(f)) {
329                 char l[LINE_MAX], *t;
330
331                 if (!fgets(l, sizeof(l), f)) {
332                         if (feof(f))
333                                 break;
334
335                         r = -errno;
336                         log_error("Failed to read configuration file '%s': %s", path, strerror(-r));
337                         goto finish;
338                 }
339
340                 line++;
341
342                 t = strstrip(l);
343                 if (*t != '#')
344                         continue;
345
346                 if (state == NORMAL && streq(t, "### BEGIN INIT INFO")) {
347                         state = LSB;
348                         s->sysv_has_lsb = true;
349                         continue;
350                 }
351
352                 if ((state == LSB_DESCRIPTION || state == LSB) && streq(t, "### END INIT INFO")) {
353                         state = NORMAL;
354                         continue;
355                 }
356
357                 t++;
358                 t += strspn(t, WHITESPACE);
359
360                 if (state == NORMAL) {
361
362                         /* Try to parse Red Hat style chkconfig headers */
363
364                         if (startswith(t, "chkconfig:")) {
365                                 int start_priority;
366                                 char runlevels[16], *k;
367
368                                 state = NORMAL;
369
370                                 if (sscanf(t+10, "%15s %i %*i",
371                                            runlevels,
372                                            &start_priority) != 2) {
373
374                                         log_warning("[%s:%u] Failed to parse chkconfig line. Ignoring.", path, line);
375                                         continue;
376                                 }
377
378                                 if (start_priority < 0 || start_priority > 99)
379                                         log_warning("[%s:%u] Start priority out of range. Ignoring.", path, line);
380                                 else
381                                         s->sysv_start_priority = start_priority;
382
383                                 char_array_0(runlevels);
384                                 k = delete_chars(runlevels, WHITESPACE "-");
385
386                                 if (k[0]) {
387                                         char *d;
388
389                                         if (!(d = strdup(k))) {
390                                                 r = -ENOMEM;
391                                                 goto finish;
392                                         }
393
394                                         free(s->sysv_runlevels);
395                                         s->sysv_runlevels = d;
396                                 }
397
398
399                         } else if (startswith(t, "description:")) {
400
401                                 size_t k = strlen(t);
402                                 char *d;
403
404                                 if (t[k-1] == '\\') {
405                                         state = DESCRIPTION;
406                                         t[k-1] = 0;
407                                 }
408
409                                 if (!(d = strdup(strstrip(t+12)))) {
410                                         r = -ENOMEM;
411                                         goto finish;
412                                 }
413
414                                 free(u->meta.description);
415                                 u->meta.description = d;
416
417                         } else if (startswith(t, "pidfile:")) {
418
419                                 char *fn;
420
421                                 state = NORMAL;
422
423                                 fn = strstrip(t+8);
424                                 if (!path_is_absolute(fn)) {
425                                         log_warning("[%s:%u] PID file not absolute. Ignoring.", path, line);
426                                         continue;
427                                 }
428
429                                 if (!(fn = strdup(fn))) {
430                                         r = -ENOMEM;
431                                         goto finish;
432                                 }
433
434                                 free(s->pid_file);
435                                 s->pid_file = fn;
436                         }
437
438                 } else if (state == DESCRIPTION) {
439
440                         /* Try to parse Red Hat style description
441                          * continuation */
442
443                         size_t k = strlen(t);
444                         char *d;
445
446                         if (t[k-1] == '\\')
447                                 t[k-1] = 0;
448                         else
449                                 state = NORMAL;
450
451                         assert(u->meta.description);
452                         if (asprintf(&d, "%s %s", u->meta.description, strstrip(t)) < 0) {
453                                 r = -ENOMEM;
454                                 goto finish;
455                         }
456
457                         free(u->meta.description);
458                         u->meta.description = d;
459
460                 } else if (state == LSB || state == LSB_DESCRIPTION) {
461
462                         if (startswith(t, "Provides:")) {
463                                 char *i, *w;
464                                 size_t z;
465
466                                 state = LSB;
467
468                                 FOREACH_WORD(w, z, t+9, i) {
469                                         char *n, *m;
470
471                                         if (!(n = strndup(w, z))) {
472                                                 r = -ENOMEM;
473                                                 goto finish;
474                                         }
475
476                                         r = sysv_translate_name(n, &m);
477                                         free(n);
478
479                                         if (r < 0)
480                                                 goto finish;
481
482                                         if (r == 0)
483                                                 continue;
484
485                                         if (unit_name_to_type(m) == UNIT_SERVICE)
486                                                 r = unit_add_name(u, m);
487                                         else {
488                                                 if ((r = unit_add_dependency_by_name_inverse(u, UNIT_REQUIRES, m)) >= 0)
489                                                         r = unit_add_dependency_by_name(u, UNIT_BEFORE, m);
490                                         }
491
492                                         free(m);
493
494                                         if (r < 0)
495                                                 goto finish;
496                                 }
497
498                         } else if (startswith(t, "Required-Start:") ||
499                                    startswith(t, "Should-Start:")) {
500                                 char *i, *w;
501                                 size_t z;
502
503                                 state = LSB;
504
505                                 FOREACH_WORD(w, z, strchr(t, ':')+1, i) {
506                                         char *n, *m;
507
508                                         if (!(n = strndup(w, z))) {
509                                                 r = -ENOMEM;
510                                                 goto finish;
511                                         }
512
513                                         r = sysv_translate_name(n, &m);
514                                         free(n);
515
516                                         if (r < 0)
517                                                 goto finish;
518
519                                         if (r == 0)
520                                                 continue;
521
522                                         r = unit_add_dependency_by_name(u, UNIT_AFTER, m);
523                                         free(m);
524
525                                         if (r < 0)
526                                                 goto finish;
527                                 }
528                         } else if (startswith(t, "Default-Start:")) {
529                                 char *k, *d;
530
531                                 state = LSB;
532
533                                 k = delete_chars(t+14, WHITESPACE "-");
534
535                                 if (k[0] != 0) {
536                                         if (!(d = strdup(k))) {
537                                                 r = -ENOMEM;
538                                                 goto finish;
539                                         }
540
541                                         free(s->sysv_runlevels);
542                                         s->sysv_runlevels = d;
543                                 }
544
545                         } else if (startswith(t, "Description:")) {
546                                 char *d;
547
548                                 state = LSB_DESCRIPTION;
549
550                                 if (!(d = strdup(strstrip(t+12)))) {
551                                         r = -ENOMEM;
552                                         goto finish;
553                                 }
554
555                                 free(u->meta.description);
556                                 u->meta.description = d;
557
558                         } else if (startswith(t, "Short-Description:") &&
559                                    !u->meta.description) {
560                                 char *d;
561
562                                 /* We use the short description only
563                                  * if no long description is set. */
564
565                                 state = LSB;
566
567                                 if (!(d = strdup(strstrip(t+18)))) {
568                                         r = -ENOMEM;
569                                         goto finish;
570                                 }
571
572                                 u->meta.description = d;
573
574                         } else if (state == LSB_DESCRIPTION) {
575
576                                 if (startswith(l, "#\t") || startswith(l, "#  ")) {
577                                         char *d;
578
579                                         assert(u->meta.description);
580                                         if (asprintf(&d, "%s %s", u->meta.description, t) < 0) {
581                                                 r = -ENOMEM;
582                                                 goto finish;
583                                         }
584
585                                         free(u->meta.description);
586                                         u->meta.description = d;
587                                 } else
588                                         state = LSB;
589                         }
590                 }
591         }
592
593         /* If init scripts have no LSB header, then we enforce the
594          * ordering via the chkconfig priorities. We try to determine
595          * a priority for *all* init scripts here, since they are
596          * needed as soon as at least one non-LSB script is used. */
597
598         if (s->sysv_start_priority < 0) {
599                 log_debug("%s has no chkconfig header, trying to determine SysV priority from link farm.", unit_id(u));
600
601                 if ((r = priority_from_rcd(s, file_name_from_path(path))) < 0)
602                         goto finish;
603
604                 if (s->sysv_start_priority < 0)
605                         log_warning("%s has neither a chkconfig header nor a directory link, cannot order unit!", unit_id(u));
606         }
607
608         if ((r = sysv_exec_commands(s)) < 0)
609                 goto finish;
610
611         if (!s->sysv_runlevels || chars_intersect("12345", s->sysv_runlevels)) {
612                 /* If there a runlevels configured for this service
613                  * but none of the standard ones, then we assume this
614                  * is some special kind of service (which might be
615                  * needed for early boot) and don't create any links
616                  * to it. */
617
618                 if ((r = unit_add_dependency_by_name(u, UNIT_REQUIRES, SPECIAL_BASIC_TARGET)) < 0 ||
619                     (r = unit_add_dependency_by_name(u, UNIT_AFTER, SPECIAL_BASIC_TARGET)) < 0)
620                         goto finish;
621         }
622
623         /* Special setting for all SysV services */
624         s->valid_no_process = true;
625
626         u->meta.load_state = UNIT_LOADED;
627         r = 0;
628
629 finish:
630
631         if (f)
632                 fclose(f);
633
634         return r;
635 }
636
637 static int service_load_sysv_name(Service *s, const char *name) {
638         char **p;
639
640         assert(s);
641         assert(name);
642
643         STRV_FOREACH(p, UNIT(s)->meta.manager->sysvinit_path) {
644                 char *path;
645                 int r;
646
647                 if (asprintf(&path, "%s/%s", *p, name) < 0)
648                         return -ENOMEM;
649
650                 assert(endswith(path, ".service"));
651                 path[strlen(path)-8] = 0;
652
653                 r = service_load_sysv_path(s, path);
654                 free(path);
655
656                 if (r < 0)
657                         return r;
658
659                 if ((UNIT(s)->meta.load_state != UNIT_STUB))
660                         break;
661         }
662
663         return 0;
664 }
665
666 static int service_load_sysv(Service *s) {
667         const char *t;
668         Iterator i;
669         int r;
670
671         assert(s);
672
673         /* Load service data from SysV init scripts, preferably with
674          * LSB headers ... */
675
676         if (strv_isempty(UNIT(s)->meta.manager->sysvinit_path))
677                 return 0;
678
679         if ((t = unit_id(UNIT(s))))
680                 if ((r = service_load_sysv_name(s, t)) < 0)
681                         return r;
682
683         if (UNIT(s)->meta.load_state == UNIT_STUB)
684                 SET_FOREACH(t, UNIT(s)->meta.names, i) {
685                         if (t == unit_id(UNIT(s)))
686                                 continue;
687
688                         if ((r == service_load_sysv_name(s, t)) < 0)
689                                 return r;
690
691                         if (UNIT(s)->meta.load_state != UNIT_STUB)
692                                 break;
693                 }
694
695         return 0;
696 }
697
698 static void service_init(Unit *u) {
699         Service *s = SERVICE(u);
700
701         assert(u);
702         assert(u->meta.load_state == UNIT_STUB);
703
704         s->type = 0;
705         s->restart = 0;
706
707         s->timeout_usec = DEFAULT_TIMEOUT_USEC;
708         s->restart_usec = DEFAULT_RESTART_USEC;
709
710         exec_context_init(&s->exec_context);
711
712         s->timer_watch.type = WATCH_INVALID;
713
714         s->state = SERVICE_DEAD;
715
716         s->sysv_start_priority = -1;
717         s->permissions_start_only = false;
718         s->root_directory_start_only = false;
719         s->valid_no_process = false;
720         s->kill_mode = 0;
721         s->sysv_has_lsb = false;
722         s->main_pid = s->control_pid = 0;
723         s->main_pid_known = false;
724         s->failure = false;
725
726         RATELIMIT_INIT(s->ratelimit, 10*USEC_PER_SEC, 5);
727 }
728
729 static int service_verify(Service *s) {
730         assert(s);
731
732         if (UNIT(s)->meta.load_state != UNIT_LOADED)
733                 return 0;
734
735         if (!s->exec_command[SERVICE_EXEC_START]) {
736                 log_error("%s lacks ExecStart setting. Refusing.", unit_id(UNIT(s)));
737                 return -EINVAL;
738         }
739
740         return 0;
741 }
742
743 static int service_load(Unit *u) {
744         int r;
745         Service *s = SERVICE(u);
746
747         assert(s);
748
749         /* Load a .service file */
750         if ((r = unit_load_fragment(u)) < 0)
751                 return r;
752
753         /* Load a classic init script as a fallback, if we couldn't find anything */
754         if (u->meta.load_state == UNIT_STUB)
755                 if ((r = service_load_sysv(s)) < 0)
756                         return r;
757
758         /* Still nothing found? Then let's give up */
759         if (u->meta.load_state == UNIT_STUB)
760                 return -ENOENT;
761
762         /* We were able to load something, then let's add in the
763          * dropin directories. */
764         if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
765                 return r;
766
767         /* This is a new unit? Then let's add in some extras */
768         if (u->meta.load_state == UNIT_LOADED) {
769                 if ((r = unit_add_exec_dependencies(u, &s->exec_context)) < 0)
770                         return r;
771
772                 if ((r = unit_add_default_cgroup(u)) < 0)
773                         return r;
774
775                 if ((r = sysv_chkconfig_order(s)) < 0)
776                         return r;
777         }
778
779         return service_verify(s);
780 }
781
782 static void service_dump(Unit *u, FILE *f, const char *prefix) {
783
784         ServiceExecCommand c;
785         Service *s = SERVICE(u);
786         const char *prefix2;
787         char *p2;
788
789         assert(s);
790
791         p2 = strappend(prefix, "\t");
792         prefix2 = p2 ? p2 : prefix;
793
794         fprintf(f,
795                 "%sService State: %s\n"
796                 "%sPermissionsStartOnly: %s\n"
797                 "%sRootDirectoryStartOnly: %s\n"
798                 "%sValidNoProcess: %s\n"
799                 "%sKillMode: %s\n"
800                 "%sType: %s\n",
801                 prefix, service_state_to_string(s->state),
802                 prefix, yes_no(s->permissions_start_only),
803                 prefix, yes_no(s->root_directory_start_only),
804                 prefix, yes_no(s->valid_no_process),
805                 prefix, kill_mode_to_string(s->kill_mode),
806                 prefix, service_type_to_string(s->type));
807
808         if (s->control_pid > 0)
809                 fprintf(f,
810                         "%sControl PID: %llu\n",
811                         prefix, (unsigned long long) s->control_pid);
812
813         if (s->main_pid > 0)
814                 fprintf(f,
815                         "%sMain PID: %llu\n",
816                         prefix, (unsigned long long) s->main_pid);
817
818         if (s->pid_file)
819                 fprintf(f,
820                         "%sPIDFile: %s\n",
821                         prefix, s->pid_file);
822
823         exec_context_dump(&s->exec_context, f, prefix);
824
825         for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
826
827                 if (!s->exec_command[c])
828                         continue;
829
830                 fprintf(f, "%s→ %s:\n",
831                         prefix, service_exec_command_to_string(c));
832
833                 exec_command_dump_list(s->exec_command[c], f, prefix2);
834         }
835
836         if (s->sysv_path)
837                 fprintf(f,
838                         "%sSysV Init Script Path: %s\n"
839                         "%sSysV Init Script has LSB Header: %s\n",
840                         prefix, s->sysv_path,
841                         prefix, yes_no(s->sysv_has_lsb));
842
843         if (s->sysv_start_priority >= 0)
844                 fprintf(f,
845                         "%sSysVStartPriority: %i\n",
846                         prefix, s->sysv_start_priority);
847
848         if (s->sysv_runlevels)
849                 fprintf(f, "%sSysVRunLevels: %s\n",
850                         prefix, s->sysv_runlevels);
851
852         free(p2);
853 }
854
855 static int service_load_pid_file(Service *s) {
856         char *k;
857         unsigned long p;
858         int r;
859
860         assert(s);
861
862         if (s->main_pid_known)
863                 return 0;
864
865         assert(s->main_pid <= 0);
866
867         if (!s->pid_file)
868                 return -ENOENT;
869
870         if ((r = read_one_line_file(s->pid_file, &k)) < 0)
871                 return r;
872
873         if ((r = safe_atolu(k, &p)) < 0) {
874                 free(k);
875                 return r;
876         }
877
878         if ((unsigned long) (pid_t) p != p)
879                 return -ERANGE;
880
881         if (kill((pid_t) p, 0) < 0 && errno != EPERM) {
882                 log_warning("PID %llu read from file %s does not exist. Your service or init script might be broken.",
883                             (unsigned long long) p, s->pid_file);
884                 return -ESRCH;
885         }
886
887         if ((r = unit_watch_pid(UNIT(s), (pid_t) p)) < 0)
888                 /* FIXME: we need to do something here */
889                 return r;
890
891         s->main_pid = (pid_t) p;
892         s->main_pid_known = true;
893
894         return 0;
895 }
896
897 static int service_get_sockets(Service *s, Set **_set) {
898         Set *set;
899         Iterator i;
900         char *t;
901         int r;
902
903         assert(s);
904         assert(_set);
905
906         /* Collects all Socket objects that belong to this
907          * service. Note that a service might have multiple sockets
908          * via multiple names. */
909
910         if (!(set = set_new(NULL, NULL)))
911                 return -ENOMEM;
912
913         SET_FOREACH(t, UNIT(s)->meta.names, i) {
914                 char *k;
915                 Unit *p;
916
917                 /* Look for all socket objects that go by any of our
918                  * units and collect their fds */
919
920                 if (!(k = unit_name_change_suffix(t, ".socket"))) {
921                         r = -ENOMEM;
922                         goto fail;
923                 }
924
925                 p = manager_get_unit(UNIT(s)->meta.manager, k);
926                 free(k);
927
928                 if (!p) continue;
929
930                 if ((r = set_put(set, p)) < 0)
931                         goto fail;
932         }
933
934         *_set = set;
935         return 0;
936
937 fail:
938         set_free(set);
939         return r;
940 }
941
942
943 static int service_notify_sockets_dead(Service *s) {
944         Iterator i;
945         Set *set;
946         Socket *sock;
947         int r;
948
949         assert(s);
950
951         /* Notifies all our sockets when we die */
952
953         if ((r = service_get_sockets(s, &set)) < 0)
954                 return r;
955
956         SET_FOREACH(sock, set, i)
957                 socket_notify_service_dead(sock);
958
959         set_free(set);
960
961         return 0;
962 }
963
964 static void service_set_state(Service *s, ServiceState state) {
965         ServiceState old_state;
966         assert(s);
967
968         old_state = s->state;
969         s->state = state;
970
971         if (state != SERVICE_START_PRE &&
972             state != SERVICE_START &&
973             state != SERVICE_START_POST &&
974             state != SERVICE_RELOAD &&
975             state != SERVICE_STOP &&
976             state != SERVICE_STOP_SIGTERM &&
977             state != SERVICE_STOP_SIGKILL &&
978             state != SERVICE_STOP_POST &&
979             state != SERVICE_FINAL_SIGTERM &&
980             state != SERVICE_FINAL_SIGKILL &&
981             state != SERVICE_AUTO_RESTART)
982                 unit_unwatch_timer(UNIT(s), &s->timer_watch);
983
984         if (state != SERVICE_START &&
985             state != SERVICE_START_POST &&
986             state != SERVICE_RUNNING &&
987             state != SERVICE_RELOAD &&
988             state != SERVICE_STOP &&
989             state != SERVICE_STOP_SIGTERM &&
990             state != SERVICE_STOP_SIGKILL)
991                 service_unwatch_main_pid(s);
992
993         if (state != SERVICE_START_PRE &&
994             state != SERVICE_START &&
995             state != SERVICE_START_POST &&
996             state != SERVICE_RELOAD &&
997             state != SERVICE_STOP &&
998             state != SERVICE_STOP_SIGTERM &&
999             state != SERVICE_STOP_SIGKILL &&
1000             state != SERVICE_STOP_POST &&
1001             state != SERVICE_FINAL_SIGTERM &&
1002             state != SERVICE_FINAL_SIGKILL) {
1003                 service_unwatch_control_pid(s);
1004                 s->control_command = NULL;
1005         }
1006
1007         if (state == SERVICE_DEAD ||
1008             state == SERVICE_STOP ||
1009             state == SERVICE_STOP_SIGTERM ||
1010             state == SERVICE_STOP_SIGKILL ||
1011             state == SERVICE_STOP_POST ||
1012             state == SERVICE_FINAL_SIGTERM ||
1013             state == SERVICE_FINAL_SIGKILL ||
1014             state == SERVICE_MAINTAINANCE ||
1015             state == SERVICE_AUTO_RESTART)
1016                 service_notify_sockets_dead(s);
1017
1018         if (old_state != state)
1019                 log_debug("%s changed %s â†’ %s", unit_id(UNIT(s)), service_state_to_string(old_state), service_state_to_string(state));
1020
1021         unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state]);
1022 }
1023
1024 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
1025         Iterator i;
1026         int r;
1027         int *rfds = NULL;
1028         unsigned rn_fds = 0;
1029         Set *set;
1030         Socket *sock;
1031
1032         assert(s);
1033         assert(fds);
1034         assert(n_fds);
1035
1036         if ((r = service_get_sockets(s, &set)) < 0)
1037                 return r;
1038
1039         SET_FOREACH(sock, set, i) {
1040                 int *cfds;
1041                 unsigned cn_fds;
1042
1043                 if ((r = socket_collect_fds(sock, &cfds, &cn_fds)) < 0)
1044                         goto fail;
1045
1046                 if (!cfds)
1047                         continue;
1048
1049                 if (!rfds) {
1050                         rfds = cfds;
1051                         rn_fds = cn_fds;
1052                 } else {
1053                         int *t;
1054
1055                         if (!(t = new(int, rn_fds+cn_fds))) {
1056                                 free(cfds);
1057                                 r = -ENOMEM;
1058                                 goto fail;
1059                         }
1060
1061                         memcpy(t, rfds, rn_fds);
1062                         memcpy(t+rn_fds, cfds, cn_fds);
1063                         free(rfds);
1064                         free(cfds);
1065
1066                         rfds = t;
1067                         rn_fds = rn_fds+cn_fds;
1068                 }
1069         }
1070
1071         *fds = rfds;
1072         *n_fds = rn_fds;
1073
1074         set_free(set);
1075
1076         return 0;
1077
1078 fail:
1079         set_free(set);
1080         free(rfds);
1081
1082         return r;
1083 }
1084
1085 static int service_spawn(
1086                 Service *s,
1087                 ExecCommand *c,
1088                 bool timeout,
1089                 bool pass_fds,
1090                 bool apply_permissions,
1091                 bool apply_chroot,
1092                 pid_t *_pid) {
1093
1094         pid_t pid;
1095         int r;
1096         int *fds = NULL;
1097         unsigned n_fds = 0;
1098
1099         assert(s);
1100         assert(c);
1101         assert(_pid);
1102
1103         if (pass_fds)
1104                 if ((r = service_collect_fds(s, &fds, &n_fds)) < 0)
1105                         goto fail;
1106
1107         if (timeout) {
1108                 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1109                         goto fail;
1110         } else
1111                 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1112
1113         if ((r = exec_spawn(c,
1114                             &s->exec_context,
1115                             fds, n_fds,
1116                             apply_permissions,
1117                             apply_chroot,
1118                             UNIT(s)->meta.manager->confirm_spawn,
1119                             UNIT(s)->meta.cgroup_bondings,
1120                             &pid)) < 0)
1121                 goto fail;
1122
1123         if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1124                 /* FIXME: we need to do something here */
1125                 goto fail;
1126
1127         free(fds);
1128         *_pid = pid;
1129
1130         return 0;
1131
1132 fail:
1133         free(fds);
1134
1135         if (timeout)
1136                 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1137
1138         return r;
1139 }
1140
1141 static int main_pid_good(Service *s) {
1142         assert(s);
1143
1144         /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1145          * don't know */
1146
1147         /* If we know the pid file, then lets just check if it is
1148          * still valid */
1149         if (s->main_pid_known)
1150                 return s->main_pid > 0;
1151
1152         /* We don't know the pid */
1153         return -EAGAIN;
1154 }
1155
1156 static int control_pid_good(Service *s) {
1157         assert(s);
1158
1159         return s->control_pid > 0;
1160 }
1161
1162 static int cgroup_good(Service *s) {
1163         int r;
1164
1165         assert(s);
1166
1167         if (s->valid_no_process)
1168                 return -EAGAIN;
1169
1170         if ((r = cgroup_bonding_is_empty_list(UNIT(s)->meta.cgroup_bondings)) < 0)
1171                 return r;
1172
1173         return !r;
1174 }
1175
1176 static void service_enter_dead(Service *s, bool success, bool allow_restart) {
1177         int r;
1178         assert(s);
1179
1180         if (!success)
1181                 s->failure = true;
1182
1183         if (allow_restart &&
1184             (s->restart == SERVICE_RESTART_ALWAYS ||
1185              (s->restart == SERVICE_RESTART_ON_SUCCESS && !s->failure))) {
1186
1187                 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
1188                         goto fail;
1189
1190                 service_set_state(s, SERVICE_AUTO_RESTART);
1191         } else
1192                 service_set_state(s, s->failure ? SERVICE_MAINTAINANCE : SERVICE_DEAD);
1193
1194         return;
1195
1196 fail:
1197         log_warning("%s failed to run install restart timer: %s", unit_id(UNIT(s)), strerror(-r));
1198         service_enter_dead(s, false, false);
1199 }
1200
1201 static void service_enter_signal(Service *s, ServiceState state, bool success);
1202
1203 static void service_enter_stop_post(Service *s, bool success) {
1204         int r;
1205         assert(s);
1206
1207         if (!success)
1208                 s->failure = true;
1209
1210         service_unwatch_control_pid(s);
1211
1212         if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST])) {
1213                 if ((r = service_spawn(s,
1214                                        s->control_command,
1215                                        true,
1216                                        false,
1217                                        !s->permissions_start_only,
1218                                        !s->root_directory_start_only,
1219                                        &s->control_pid)) < 0)
1220                         goto fail;
1221
1222
1223                 service_set_state(s, SERVICE_STOP_POST);
1224         } else
1225                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, true);
1226
1227         return;
1228
1229 fail:
1230         log_warning("%s failed to run stop-post executable: %s", unit_id(UNIT(s)), strerror(-r));
1231         service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1232 }
1233
1234 static void service_enter_signal(Service *s, ServiceState state, bool success) {
1235         int r;
1236         bool sent = false;
1237
1238         assert(s);
1239
1240         if (!success)
1241                 s->failure = true;
1242
1243         if (s->kill_mode != KILL_NONE) {
1244                 int sig = (state == SERVICE_STOP_SIGTERM || state == SERVICE_FINAL_SIGTERM) ? SIGTERM : SIGKILL;
1245
1246                 if (s->kill_mode == KILL_CONTROL_GROUP) {
1247
1248                         if ((r = cgroup_bonding_kill_list(UNIT(s)->meta.cgroup_bondings, sig)) < 0) {
1249                                 if (r != -EAGAIN && r != -ESRCH)
1250                                         goto fail;
1251                         } else
1252                                 sent = true;
1253                 }
1254
1255                 if (!sent) {
1256                         r = 0;
1257
1258                         if (s->main_pid > 0) {
1259                                 if (kill(s->kill_mode == KILL_PROCESS ? s->main_pid : -s->main_pid, sig) < 0 && errno != ESRCH)
1260                                         r = -errno;
1261                                 else
1262                                         sent = true;
1263                         }
1264
1265                         if (s->control_pid > 0) {
1266                                 if (kill(s->kill_mode == KILL_PROCESS ? s->control_pid : -s->control_pid, sig) < 0 && errno != ESRCH)
1267                                         r = -errno;
1268                                 else
1269                                         sent = true;
1270                         }
1271
1272                         if (r < 0)
1273                                 goto fail;
1274                 }
1275         }
1276
1277         if (sent) {
1278                 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1279                         goto fail;
1280
1281                 service_set_state(s, state);
1282         } else if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1283                 service_enter_stop_post(s, true);
1284         else
1285                 service_enter_dead(s, true, true);
1286
1287         return;
1288
1289 fail:
1290         log_warning("%s failed to kill processes: %s", unit_id(UNIT(s)), strerror(-r));
1291
1292         if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1293                 service_enter_stop_post(s, false);
1294         else
1295                 service_enter_dead(s, false, true);
1296 }
1297
1298 static void service_enter_stop(Service *s, bool success) {
1299         int r;
1300         assert(s);
1301
1302         if (!success)
1303                 s->failure = true;
1304
1305         service_unwatch_control_pid(s);
1306
1307         if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP])) {
1308                 if ((r = service_spawn(s,
1309                                        s->control_command,
1310                                        true,
1311                                        false,
1312                                        !s->permissions_start_only,
1313                                        !s->root_directory_start_only,
1314                                        &s->control_pid)) < 0)
1315                         goto fail;
1316
1317                 service_set_state(s, SERVICE_STOP);
1318         } else
1319                 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
1320
1321         return;
1322
1323 fail:
1324         log_warning("%s failed to run stop executable: %s", unit_id(UNIT(s)), strerror(-r));
1325         service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1326 }
1327
1328 static void service_enter_running(Service *s, bool success) {
1329         assert(s);
1330
1331         if (!success)
1332                 s->failure = true;
1333
1334         if (main_pid_good(s) != 0 && cgroup_good(s) != 0)
1335                 service_set_state(s, SERVICE_RUNNING);
1336         else if (s->valid_no_process)
1337                 service_set_state(s, SERVICE_EXITED);
1338         else
1339                 service_enter_stop(s, true);
1340 }
1341
1342 static void service_enter_start_post(Service *s) {
1343         int r;
1344         assert(s);
1345
1346         service_unwatch_control_pid(s);
1347
1348         if ((s->control_command = s->exec_command[SERVICE_EXEC_START_POST])) {
1349                 if ((r = service_spawn(s,
1350                                        s->control_command,
1351                                        true,
1352                                        false,
1353                                        !s->permissions_start_only,
1354                                        !s->root_directory_start_only,
1355                                        &s->control_pid)) < 0)
1356                         goto fail;
1357
1358
1359                 service_set_state(s, SERVICE_START_POST);
1360         } else
1361                 service_enter_running(s, true);
1362
1363         return;
1364
1365 fail:
1366         log_warning("%s failed to run start-post executable: %s", unit_id(UNIT(s)), strerror(-r));
1367         service_enter_stop(s, false);
1368 }
1369
1370 static void service_enter_start(Service *s) {
1371         pid_t pid;
1372         int r;
1373
1374         assert(s);
1375
1376         assert(s->exec_command[SERVICE_EXEC_START]);
1377         assert(!s->exec_command[SERVICE_EXEC_START]->command_next);
1378
1379         if (s->type == SERVICE_FORKING)
1380                 service_unwatch_control_pid(s);
1381         else
1382                 service_unwatch_main_pid(s);
1383
1384         if ((r = service_spawn(s,
1385                                s->exec_command[SERVICE_EXEC_START],
1386                                s->type == SERVICE_FORKING,
1387                                true,
1388                                true,
1389                                true,
1390                                &pid)) < 0)
1391                 goto fail;
1392
1393         if (s->type == SERVICE_SIMPLE) {
1394                 /* For simple services we immediately start
1395                  * the START_POST binaries. */
1396
1397                 s->main_pid = pid;
1398                 s->main_pid_known = true;
1399
1400                 service_enter_start_post(s);
1401
1402         } else  if (s->type == SERVICE_FORKING) {
1403
1404                 /* For forking services we wait until the start
1405                  * process exited. */
1406
1407                 s->control_pid = pid;
1408
1409                 s->control_command = s->exec_command[SERVICE_EXEC_START];
1410                 service_set_state(s, SERVICE_START);
1411
1412         } else if (s->type == SERVICE_FINISH) {
1413
1414                 /* For finishing services we wait until the start
1415                  * process exited, too, but it is our main process. */
1416
1417                 s->main_pid = pid;
1418                 s->main_pid_known = true;
1419
1420                 s->control_command = s->exec_command[SERVICE_EXEC_START];
1421                 service_set_state(s, SERVICE_START);
1422         } else
1423                 assert_not_reached("Unknown service type");
1424
1425         return;
1426
1427 fail:
1428         log_warning("%s failed to run start exectuable: %s", unit_id(UNIT(s)), strerror(-r));
1429         service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1430 }
1431
1432 static void service_enter_start_pre(Service *s) {
1433         int r;
1434
1435         assert(s);
1436
1437         service_unwatch_control_pid(s);
1438
1439         if ((s->control_command = s->exec_command[SERVICE_EXEC_START_PRE])) {
1440                 if ((r = service_spawn(s,
1441                                        s->control_command,
1442                                        true,
1443                                        false,
1444                                        !s->permissions_start_only,
1445                                        !s->root_directory_start_only,
1446                                        &s->control_pid)) < 0)
1447                         goto fail;
1448
1449                 service_set_state(s, SERVICE_START_PRE);
1450         } else
1451                 service_enter_start(s);
1452
1453         return;
1454
1455 fail:
1456         log_warning("%s failed to run start-pre executable: %s", unit_id(UNIT(s)), strerror(-r));
1457         service_enter_dead(s, false, true);
1458 }
1459
1460 static void service_enter_restart(Service *s) {
1461         int r;
1462         assert(s);
1463
1464         service_enter_dead(s, true, false);
1465
1466         if ((r = manager_add_job(UNIT(s)->meta.manager, JOB_START, UNIT(s), JOB_FAIL, false, NULL)) < 0)
1467                 goto fail;
1468
1469         log_debug("%s scheduled restart job.", unit_id(UNIT(s)));
1470         return;
1471
1472 fail:
1473
1474         log_warning("%s failed to schedule restart job: %s", unit_id(UNIT(s)), strerror(-r));
1475         service_enter_dead(s, false, false);
1476 }
1477
1478 static void service_enter_reload(Service *s) {
1479         int r;
1480
1481         assert(s);
1482
1483         service_unwatch_control_pid(s);
1484
1485         if ((s->control_command = s->exec_command[SERVICE_EXEC_RELOAD])) {
1486                 if ((r = service_spawn(s,
1487                                        s->control_command,
1488                                        true,
1489                                        false,
1490                                        !s->permissions_start_only,
1491                                        !s->root_directory_start_only,
1492                                        &s->control_pid)) < 0)
1493                         goto fail;
1494
1495                 service_set_state(s, SERVICE_RELOAD);
1496         } else
1497                 service_enter_running(s, true);
1498
1499         return;
1500
1501 fail:
1502         log_warning("%s failed to run reload executable: %s", unit_id(UNIT(s)), strerror(-r));
1503         service_enter_stop(s, false);
1504 }
1505
1506 static void service_run_next(Service *s, bool success) {
1507         int r;
1508
1509         assert(s);
1510         assert(s->control_command);
1511         assert(s->control_command->command_next);
1512
1513         if (!success)
1514                 s->failure = true;
1515
1516         s->control_command = s->control_command->command_next;
1517
1518         service_unwatch_control_pid(s);
1519
1520         if ((r = service_spawn(s,
1521                                s->control_command,
1522                                true,
1523                                false,
1524                                !s->permissions_start_only,
1525                                !s->root_directory_start_only,
1526                                &s->control_pid)) < 0)
1527                 goto fail;
1528
1529         return;
1530
1531 fail:
1532         log_warning("%s failed to run spawn next executable: %s", unit_id(UNIT(s)), strerror(-r));
1533
1534         if (s->state == SERVICE_START_PRE)
1535                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1536         else if (s->state == SERVICE_STOP)
1537                 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1538         else if (s->state == SERVICE_STOP_POST)
1539                 service_enter_dead(s, false, true);
1540         else
1541                 service_enter_stop(s, false);
1542 }
1543
1544 static int service_start(Unit *u) {
1545         Service *s = SERVICE(u);
1546
1547         assert(s);
1548
1549         /* We cannot fulfill this request right now, try again later
1550          * please! */
1551         if (s->state == SERVICE_STOP ||
1552             s->state == SERVICE_STOP_SIGTERM ||
1553             s->state == SERVICE_STOP_SIGKILL ||
1554             s->state == SERVICE_STOP_POST ||
1555             s->state == SERVICE_FINAL_SIGTERM ||
1556             s->state == SERVICE_FINAL_SIGKILL)
1557                 return -EAGAIN;
1558
1559         /* Already on it! */
1560         if (s->state == SERVICE_START_PRE ||
1561             s->state == SERVICE_START ||
1562             s->state == SERVICE_START_POST)
1563                 return 0;
1564
1565         assert(s->state == SERVICE_DEAD || s->state == SERVICE_MAINTAINANCE || s->state == SERVICE_AUTO_RESTART);
1566
1567         /* Make sure we don't enter a busy loop of some kind. */
1568         if (!ratelimit_test(&s->ratelimit)) {
1569                 log_warning("%s start request repeated too quickly, refusing to start.", unit_id(u));
1570                 return -EAGAIN;
1571         }
1572
1573         s->failure = false;
1574         s->main_pid_known = false;
1575
1576         service_enter_start_pre(s);
1577         return 0;
1578 }
1579
1580 static int service_stop(Unit *u) {
1581         Service *s = SERVICE(u);
1582
1583         assert(s);
1584
1585         /* Cannot do this now */
1586         if (s->state == SERVICE_START_PRE ||
1587             s->state == SERVICE_START ||
1588             s->state == SERVICE_START_POST ||
1589             s->state == SERVICE_RELOAD)
1590                 return -EAGAIN;
1591
1592         /* Already on it */
1593         if (s->state == SERVICE_STOP ||
1594             s->state == SERVICE_STOP_SIGTERM ||
1595             s->state == SERVICE_STOP_SIGKILL ||
1596             s->state == SERVICE_STOP_POST ||
1597             s->state == SERVICE_FINAL_SIGTERM ||
1598             s->state == SERVICE_FINAL_SIGKILL)
1599                 return 0;
1600
1601         if (s->state == SERVICE_AUTO_RESTART) {
1602                 service_set_state(s, SERVICE_DEAD);
1603                 return 0;
1604         }
1605
1606         assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
1607
1608         service_enter_stop(s, true);
1609         return 0;
1610 }
1611
1612 static int service_reload(Unit *u) {
1613         Service *s = SERVICE(u);
1614
1615         assert(s);
1616
1617         assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
1618
1619         service_enter_reload(s);
1620         return 0;
1621 }
1622
1623 static bool service_can_reload(Unit *u) {
1624         Service *s = SERVICE(u);
1625
1626         assert(s);
1627
1628         return !!s->exec_command[SERVICE_EXEC_RELOAD];
1629 }
1630
1631 static UnitActiveState service_active_state(Unit *u) {
1632         assert(u);
1633
1634         return state_translation_table[SERVICE(u)->state];
1635 }
1636
1637 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
1638         Service *s = SERVICE(u);
1639         bool success;
1640
1641         assert(s);
1642         assert(pid >= 0);
1643
1644         success = code == CLD_EXITED && status == 0;
1645         s->failure = s->failure || !success;
1646
1647         if (s->main_pid == pid) {
1648
1649                 exec_status_fill(&s->main_exec_status, pid, code, status);
1650                 s->main_pid = 0;
1651
1652                 if (s->type == SERVICE_SIMPLE || s->type == SERVICE_FINISH) {
1653                         assert(s->exec_command[SERVICE_EXEC_START]);
1654                         s->exec_command[SERVICE_EXEC_START]->exec_status = s->main_exec_status;
1655                 }
1656
1657                 log_debug("%s: main process exited, code=%s, status=%i", unit_id(u), sigchld_code_to_string(code), status);
1658
1659                 /* The service exited, so the service is officially
1660                  * gone. */
1661
1662                 switch (s->state) {
1663
1664                 case SERVICE_START_POST:
1665                 case SERVICE_RELOAD:
1666                 case SERVICE_STOP:
1667                         /* Need to wait until the operation is
1668                          * done */
1669                         break;
1670
1671                 case SERVICE_START:
1672                         assert(s->type == SERVICE_FINISH);
1673
1674                         /* This was our main goal, so let's go on */
1675                         if (success)
1676                                 service_enter_start_post(s);
1677                         else
1678                                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1679                         break;
1680
1681                 case SERVICE_RUNNING:
1682                         service_enter_running(s, success);
1683                         break;
1684
1685                 case SERVICE_STOP_SIGTERM:
1686                 case SERVICE_STOP_SIGKILL:
1687
1688                         if (!control_pid_good(s))
1689                                 service_enter_stop_post(s, success);
1690
1691                         /* If there is still a control process, wait for that first */
1692                         break;
1693
1694                 default:
1695                         assert_not_reached("Uh, main process died at wrong time.");
1696                 }
1697
1698         } else if (s->control_pid == pid) {
1699                 assert(s->control_command);
1700
1701                 exec_status_fill(&s->control_command->exec_status, pid, code, status);
1702                 s->control_pid = 0;
1703
1704                 log_debug("%s: control process exited, code=%s status=%i", unit_id(u), sigchld_code_to_string(code), status);
1705
1706                 /* If we are shutting things down anyway we
1707                  * don't care about failing commands. */
1708
1709                 if (s->control_command->command_next && success) {
1710
1711                         /* There is another command to *
1712                          * execute, so let's do that. */
1713
1714                         log_debug("%s running next command for state %s", unit_id(u), service_state_to_string(s->state));
1715                         service_run_next(s, success);
1716
1717                 } else {
1718                         /* No further commands for this step, so let's
1719                          * figure out what to do next */
1720
1721                         log_debug("%s got final SIGCHLD for state %s", unit_id(u), service_state_to_string(s->state));
1722
1723                         switch (s->state) {
1724
1725                         case SERVICE_START_PRE:
1726                                 if (success)
1727                                         service_enter_start(s);
1728                                 else
1729                                         service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1730                                 break;
1731
1732                         case SERVICE_START:
1733                                 assert(s->type == SERVICE_FORKING);
1734
1735                                 /* Let's try to load the pid
1736                                  * file here if we can. We
1737                                  * ignore the return value,
1738                                  * since the PID file might
1739                                  * actually be created by a
1740                                  * START_POST script */
1741
1742                                 if (success) {
1743                                         if (s->pid_file)
1744                                                 service_load_pid_file(s);
1745
1746                                         service_enter_start_post(s);
1747                                 } else
1748                                         service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1749
1750                                 break;
1751
1752                         case SERVICE_START_POST:
1753                                 if (success && s->pid_file && !s->main_pid_known) {
1754                                         int r;
1755
1756                                         /* Hmm, let's see if we can
1757                                          * load the pid now after the
1758                                          * start-post scripts got
1759                                          * executed. */
1760
1761                                         if ((r = service_load_pid_file(s)) < 0)
1762                                                 log_warning("%s: failed to load PID file %s: %s", unit_id(UNIT(s)), s->pid_file, strerror(-r));
1763                                 }
1764
1765                                 /* Fall through */
1766
1767                         case SERVICE_RELOAD:
1768                                 if (success)
1769                                         service_enter_running(s, true);
1770                                 else
1771                                         service_enter_stop(s, false);
1772
1773                                 break;
1774
1775                         case SERVICE_STOP:
1776                                 service_enter_signal(s, SERVICE_STOP_SIGTERM, success);
1777                                 break;
1778
1779                         case SERVICE_STOP_SIGTERM:
1780                         case SERVICE_STOP_SIGKILL:
1781                                 if (main_pid_good(s) <= 0)
1782                                         service_enter_stop_post(s, success);
1783
1784                                 /* If there is still a service
1785                                  * process around, wait until
1786                                  * that one quit, too */
1787                                 break;
1788
1789                         case SERVICE_STOP_POST:
1790                         case SERVICE_FINAL_SIGTERM:
1791                         case SERVICE_FINAL_SIGKILL:
1792                                 service_enter_dead(s, success, true);
1793                                 break;
1794
1795                         default:
1796                                 assert_not_reached("Uh, control process died at wrong time.");
1797                         }
1798                 }
1799         } else
1800                 assert_not_reached("Got SIGCHLD for unkown PID");
1801 }
1802
1803 static void service_timer_event(Unit *u, uint64_t elapsed, Watch* w) {
1804         Service *s = SERVICE(u);
1805
1806         assert(s);
1807         assert(elapsed == 1);
1808
1809         assert(w == &s->timer_watch);
1810
1811         switch (s->state) {
1812
1813         case SERVICE_START_PRE:
1814         case SERVICE_START:
1815                 log_warning("%s operation timed out. Terminating.", unit_id(u));
1816                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1817                 break;
1818
1819         case SERVICE_START_POST:
1820         case SERVICE_RELOAD:
1821                 log_warning("%s operation timed out. Stopping.", unit_id(u));
1822                 service_enter_stop(s, false);
1823                 break;
1824
1825         case SERVICE_STOP:
1826                 log_warning("%s stopping timed out. Terminating.", unit_id(u));
1827                 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1828                 break;
1829
1830         case SERVICE_STOP_SIGTERM:
1831                 log_warning("%s stopping timed out. Killing.", unit_id(u));
1832                 service_enter_signal(s, SERVICE_STOP_SIGKILL, false);
1833                 break;
1834
1835         case SERVICE_STOP_SIGKILL:
1836                 /* Uh, wie sent a SIGKILL and it is still not gone?
1837                  * Must be something we cannot kill, so let's just be
1838                  * weirded out and continue */
1839
1840                 log_warning("%s still around after SIGKILL. Ignoring.", unit_id(u));
1841                 service_enter_stop_post(s, false);
1842                 break;
1843
1844         case SERVICE_STOP_POST:
1845                 log_warning("%s stopping timed out (2). Terminating.", unit_id(u));
1846                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1847                 break;
1848
1849         case SERVICE_FINAL_SIGTERM:
1850                 log_warning("%s stopping timed out (2). Killing.", unit_id(u));
1851                 service_enter_signal(s, SERVICE_FINAL_SIGKILL, false);
1852                 break;
1853
1854         case SERVICE_FINAL_SIGKILL:
1855                 log_warning("%s still around after SIGKILL (2). Entering maintainance mode.", unit_id(u));
1856                 service_enter_dead(s, false, true);
1857                 break;
1858
1859         case SERVICE_AUTO_RESTART:
1860                 log_debug("%s holdoff time over, scheduling restart.", unit_id(u));
1861                 service_enter_restart(s);
1862                 break;
1863
1864         default:
1865                 assert_not_reached("Timeout at wrong time.");
1866         }
1867 }
1868
1869 static void service_cgroup_notify_event(Unit *u) {
1870         Service *s = SERVICE(u);
1871
1872         assert(u);
1873
1874         log_debug("%s: cgroup is empty", unit_id(u));
1875
1876         switch (s->state) {
1877
1878                 /* Waiting for SIGCHLD is usually more interesting,
1879                  * because it includes return codes/signals. Which is
1880                  * why we ignore the cgroup events for most cases,
1881                  * except when we don't know pid which to expect the
1882                  * SIGCHLD for. */
1883
1884         case SERVICE_RUNNING:
1885                 service_enter_running(s, true);
1886                 break;
1887
1888         default:
1889                 ;
1890         }
1891 }
1892
1893 static int service_enumerate(Manager *m) {
1894         char **p;
1895         unsigned i;
1896         DIR *d = NULL;
1897         char *path = NULL, *fpath = NULL, *name = NULL;
1898         int r;
1899
1900         assert(m);
1901
1902         STRV_FOREACH(p, m->sysvrcnd_path)
1903                 for (i = 0; i < ELEMENTSOF(rcnd_table); i += 2) {
1904                         struct dirent *de;
1905
1906                         free(path);
1907                         path = NULL;
1908                         if (asprintf(&path, "%s/%s", *p, rcnd_table[i]) < 0) {
1909                                 r = -ENOMEM;
1910                                 goto finish;
1911                         }
1912
1913                         if (d)
1914                                 closedir(d);
1915
1916                         if (!(d = opendir(path))) {
1917                                 if (errno != ENOENT)
1918                                         log_warning("opendir() failed on %s: %s", path, strerror(errno));
1919
1920                                 continue;
1921                         }
1922
1923                         while ((de = readdir(d))) {
1924                                 Unit *runlevel, *service;
1925
1926                                 if (ignore_file(de->d_name))
1927                                         continue;
1928
1929                                 if (de->d_name[0] != 'S' && de->d_name[0] != 'K')
1930                                         continue;
1931
1932                                 if (strlen(de->d_name) < 4)
1933                                         continue;
1934
1935                                 free(fpath);
1936                                 fpath = NULL;
1937                                 if (asprintf(&fpath, "%s/%s/%s", *p, rcnd_table[i], de->d_name) < 0) {
1938                                         r = -ENOMEM;
1939                                         goto finish;
1940                                 }
1941
1942                                 if (access(fpath, X_OK) < 0) {
1943
1944                                         if (errno != ENOENT)
1945                                                 log_warning("access() failed on %s: %s", fpath, strerror(errno));
1946
1947                                         continue;
1948                                 }
1949
1950                                 free(name);
1951                                 name = NULL;
1952                                 if (asprintf(&name, "%s.service", de->d_name+3) < 0) {
1953                                         r = -ENOMEM;
1954                                         goto finish;
1955                                 }
1956
1957                                 if ((r = manager_load_unit(m, name, &service)) < 0)
1958                                         goto finish;
1959
1960                                 if ((r = manager_load_unit(m, rcnd_table[i+1], &runlevel)) < 0)
1961                                         goto finish;
1962
1963                                 if (de->d_name[0] == 'S') {
1964                                         if ((r = unit_add_dependency(runlevel, UNIT_WANTS, service)) < 0)
1965                                                 goto finish;
1966
1967                                         if ((r = unit_add_dependency(runlevel, UNIT_AFTER, service)) < 0)
1968                                                 goto finish;
1969
1970                                 } else if (de->d_name[0] == 'K' &&
1971                                            (streq(rcnd_table[i+1], SPECIAL_RUNLEVEL0_TARGET) ||
1972                                             streq(rcnd_table[i+1], SPECIAL_RUNLEVEL6_TARGET))) {
1973
1974                                         /* We honour K links only for
1975                                          * halt/reboot. For the normal
1976                                          * runlevels we assume the
1977                                          * stop jobs will be
1978                                          * implicitly added by the
1979                                          * core logic. */
1980
1981                                         if ((r = unit_add_dependency(runlevel, UNIT_CONFLICTS, service)) < 0)
1982                                                 goto finish;
1983
1984                                         if ((r = unit_add_dependency(runlevel, UNIT_BEFORE, service)) < 0)
1985                                                 goto finish;
1986                                 }
1987                         }
1988                 }
1989
1990         r = 0;
1991
1992 finish:
1993         free(path);
1994         free(fpath);
1995         free(name);
1996         closedir(d);
1997
1998         return r;
1999 }
2000
2001 static const char* const service_state_table[_SERVICE_STATE_MAX] = {
2002         [SERVICE_DEAD] = "dead",
2003         [SERVICE_START_PRE] = "start-pre",
2004         [SERVICE_START] = "start",
2005         [SERVICE_START_POST] = "start-post",
2006         [SERVICE_RUNNING] = "running",
2007         [SERVICE_EXITED] = "exited",
2008         [SERVICE_RELOAD] = "reload",
2009         [SERVICE_STOP] = "stop",
2010         [SERVICE_STOP_SIGTERM] = "stop-sigterm",
2011         [SERVICE_STOP_SIGKILL] = "stop-sigkill",
2012         [SERVICE_STOP_POST] = "stop-post",
2013         [SERVICE_FINAL_SIGTERM] = "final-sigterm",
2014         [SERVICE_FINAL_SIGKILL] = "final-sigkill",
2015         [SERVICE_MAINTAINANCE] = "maintainance",
2016         [SERVICE_AUTO_RESTART] = "auto-restart",
2017 };
2018
2019 DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
2020
2021 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
2022         [SERVICE_ONCE] = "once",
2023         [SERVICE_RESTART_ON_SUCCESS] = "restart-on-success",
2024         [SERVICE_RESTART_ALWAYS] = "restart-always",
2025 };
2026
2027 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
2028
2029 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
2030         [SERVICE_FORKING] = "forking",
2031         [SERVICE_SIMPLE] = "simple",
2032         [SERVICE_FINISH] = "finish"
2033 };
2034
2035 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
2036
2037 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
2038         [SERVICE_EXEC_START_PRE] = "ExecStartPre",
2039         [SERVICE_EXEC_START] = "ExecStart",
2040         [SERVICE_EXEC_START_POST] = "ExecStartPost",
2041         [SERVICE_EXEC_RELOAD] = "ExecReload",
2042         [SERVICE_EXEC_STOP] = "ExecStop",
2043         [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
2044 };
2045
2046 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
2047
2048 const UnitVTable service_vtable = {
2049         .suffix = ".service",
2050
2051         .init = service_init,
2052         .load = service_load,
2053         .done = service_done,
2054
2055         .dump = service_dump,
2056
2057         .start = service_start,
2058         .stop = service_stop,
2059         .reload = service_reload,
2060
2061         .can_reload = service_can_reload,
2062
2063         .active_state = service_active_state,
2064
2065         .sigchld_event = service_sigchld_event,
2066         .timer_event = service_timer_event,
2067
2068         .cgroup_notify_empty = service_cgroup_notify_event,
2069
2070         .enumerate = service_enumerate
2071 };