1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
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.
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.
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/>.
29 #include "load-fragment.h"
30 #include "load-dropin.h"
34 #define COMMENTS "#;\n"
35 #define NEWLINES "\n\r"
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
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_RELOAD] = UNIT_ACTIVE_RELOADING,
56 [SERVICE_STOP] = UNIT_DEACTIVATING,
57 [SERVICE_STOP_SIGTERM] = UNIT_DEACTIVATING,
58 [SERVICE_STOP_SIGKILL] = UNIT_DEACTIVATING,
59 [SERVICE_STOP_POST] = UNIT_DEACTIVATING,
60 [SERVICE_FINAL_SIGTERM] = UNIT_DEACTIVATING,
61 [SERVICE_FINAL_SIGKILL] = UNIT_DEACTIVATING,
62 [SERVICE_MAINTAINANCE] = UNIT_INACTIVE,
63 [SERVICE_AUTO_RESTART] = UNIT_ACTIVATING,
66 static void service_unwatch_control_pid(Service *s) {
69 if (s->control_pid <= 0)
72 unit_unwatch_pid(UNIT(s), s->control_pid);
76 static void service_unwatch_main_pid(Service *s) {
82 unit_unwatch_pid(UNIT(s), s->main_pid);
86 static void service_done(Unit *u) {
87 Service *s = SERVICE(u);
97 free(s->sysv_runlevels);
98 s->sysv_runlevels = NULL;
100 exec_context_done(&s->exec_context);
101 exec_command_free_array(s->exec_command, _SERVICE_EXEC_COMMAND_MAX);
102 s->control_command = NULL;
104 /* This will leak a process, but at least no memory or any of
106 service_unwatch_main_pid(s);
107 service_unwatch_control_pid(s);
109 unit_unwatch_timer(u, &s->timer_watch);
112 static int sysv_translate_name(const char *name, char **_r) {
114 static const char * const table[] = {
115 "$local_fs", SPECIAL_LOCAL_FS_TARGET,
116 "$network", SPECIAL_NETWORK_TARGET,
117 "$named", SPECIAL_NSS_LOOKUP_TARGET,
118 "$portmap", SPECIAL_RPCBIND_TARGET,
119 "$remote_fs", SPECIAL_REMOTE_FS_TARGET,
120 "$syslog", SPECIAL_SYSLOG_TARGET,
121 "$time", SPECIAL_RTC_SET_TARGET
127 for (i = 0; i < ELEMENTSOF(table); i += 2)
128 if (streq(table[i], name)) {
129 if (!(r = strdup(table[i+1])))
138 if (asprintf(&r, "%s.service", name) < 0)
149 static int sysv_chkconfig_order(Service *s) {
155 if (s->sysv_start_priority < 0)
158 /* For each pair of services where at least one lacks a LSB
159 * header, we use the start priority value to order things. */
161 LIST_FOREACH(units_per_type, other, UNIT(s)->meta.manager->units_per_type[UNIT_SERVICE]) {
165 t = (Service*) other;
170 if (t->sysv_start_priority < 0)
173 /* If both units have modern headers we don't care
174 * about the priorities */
175 if ((!s->sysv_path || s->sysv_has_lsb) &&
176 (!t->sysv_path || t->sysv_has_lsb))
179 if (t->sysv_start_priority < s->sysv_start_priority)
181 else if (t->sysv_start_priority > s->sysv_start_priority)
186 /* FIXME: Maybe we should compare the name here lexicographically? */
188 if (!(r = unit_add_dependency(UNIT(s), d, UNIT(t))) < 0)
195 static ExecCommand *exec_command_new(const char *path, const char *arg1) {
198 if (!(c = new0(ExecCommand, 1)))
201 if (!(c->path = strdup(path))) {
206 if (!(c->argv = strv_new(path, arg1, NULL))) {
215 static int sysv_exec_commands(Service *s) {
219 assert(s->sysv_path);
221 if (!(c = exec_command_new(s->sysv_path, "start")))
223 exec_command_append_list(s->exec_command+SERVICE_EXEC_START, c);
225 if (!(c = exec_command_new(s->sysv_path, "stop")))
227 exec_command_append_list(s->exec_command+SERVICE_EXEC_STOP, c);
229 if (!(c = exec_command_new(s->sysv_path, "reload")))
231 exec_command_append_list(s->exec_command+SERVICE_EXEC_RELOAD, c);
236 static int priority_from_rcd(Service *s, const char *init_script) {
240 STRV_FOREACH(p, UNIT(s)->meta.manager->sysvrcnd_path)
241 for (i = 0; i < ELEMENTSOF(rcnd_table); i += 2) {
246 if (asprintf(&path, "%s/%s", *p, rcnd_table[i]) < 0)
254 log_warning("opendir() failed on %s: %s", path, strerror(errno));
259 while ((de = readdir(d))) {
262 if (ignore_file(de->d_name))
265 if (de->d_name[0] != 'S')
268 if (strlen(de->d_name) < 4)
271 if (!streq(de->d_name + 3, init_script))
274 /* Yay, we found it! Now decode the priority */
276 a = undecchar(de->d_name[1]);
277 b = undecchar(de->d_name[2]);
282 s->sysv_start_priority = a*10 + b;
284 log_debug("Determined priority %i from link farm for %s", s->sysv_start_priority, unit_id(UNIT(s)));
296 static int service_load_sysv_path(Service *s, const char *path) {
313 if (!(f = fopen(path, "re"))) {
314 r = errno == ENOENT ? 0 : -errno;
318 s->type = SERVICE_FORKING;
319 s->restart = SERVICE_ONCE;
322 if (!(s->sysv_path = strdup(path))) {
328 char l[LINE_MAX], *t;
330 if (!fgets(l, sizeof(l), f)) {
335 log_error("Failed to read configuration file '%s': %s", path, strerror(-r));
345 if (state == NORMAL && streq(t, "### BEGIN INIT INFO")) {
347 s->sysv_has_lsb = true;
351 if ((state == LSB_DESCRIPTION || state == LSB) && streq(t, "### END INIT INFO")) {
357 t += strspn(t, WHITESPACE);
359 if (state == NORMAL) {
361 /* Try to parse Red Hat style chkconfig headers */
363 if (startswith(t, "chkconfig:")) {
365 char runlevels[16], *k;
369 if (sscanf(t+10, "%15s %i %*i",
371 &start_priority) != 2) {
373 log_warning("[%s:%u] Failed to parse chkconfig line. Ignoring.", path, line);
377 if (start_priority < 0 || start_priority > 99)
378 log_warning("[%s:%u] Start priority out of range. Ignoring.", path, line);
380 s->sysv_start_priority = start_priority;
382 char_array_0(runlevels);
383 k = delete_chars(runlevels, WHITESPACE "-");
388 if (!(d = strdup(k))) {
393 free(s->sysv_runlevels);
394 s->sysv_runlevels = d;
398 } else if (startswith(t, "description:")) {
400 size_t k = strlen(t);
403 if (t[k-1] == '\\') {
408 if (!(d = strdup(strstrip(t+12)))) {
413 free(u->meta.description);
414 u->meta.description = d;
416 } else if (startswith(t, "pidfile:")) {
423 if (!path_is_absolute(fn)) {
424 log_warning("[%s:%u] PID file not absolute. Ignoring.", path, line);
428 if (!(fn = strdup(fn))) {
437 } else if (state == DESCRIPTION) {
439 /* Try to parse Red Hat style description
442 size_t k = strlen(t);
450 assert(u->meta.description);
451 if (asprintf(&d, "%s %s", u->meta.description, strstrip(t)) < 0) {
456 free(u->meta.description);
457 u->meta.description = d;
459 } else if (state == LSB || state == LSB_DESCRIPTION) {
461 if (startswith(t, "Provides:")) {
467 FOREACH_WORD(w, z, t+9, i) {
470 if (!(n = strndup(w, z))) {
475 r = sysv_translate_name(n, &m);
484 if (unit_name_to_type(m) == UNIT_SERVICE)
485 r = unit_add_name(u, m);
487 if ((r = unit_add_dependency_by_name_inverse(u, UNIT_REQUIRES, m)) >= 0)
488 r = unit_add_dependency_by_name(u, UNIT_BEFORE, m);
497 } else if (startswith(t, "Required-Start:") ||
498 startswith(t, "Should-Start:")) {
504 FOREACH_WORD(w, z, strchr(t, ':')+1, i) {
507 if (!(n = strndup(w, z))) {
512 r = sysv_translate_name(n, &m);
521 r = unit_add_dependency_by_name(u, UNIT_AFTER, m);
527 } else if (startswith(t, "Default-Start:")) {
532 k = delete_chars(t+14, WHITESPACE "-");
535 if (!(d = strdup(k))) {
540 free(s->sysv_runlevels);
541 s->sysv_runlevels = d;
544 } else if (startswith(t, "Description:")) {
547 state = LSB_DESCRIPTION;
549 if (!(d = strdup(strstrip(t+12)))) {
554 free(u->meta.description);
555 u->meta.description = d;
557 } else if (startswith(t, "Short-Description:") &&
558 !u->meta.description) {
561 /* We use the short description only
562 * if no long description is set. */
566 if (!(d = strdup(strstrip(t+18)))) {
571 u->meta.description = d;
573 } else if (state == LSB_DESCRIPTION) {
575 if (startswith(l, "#\t") || startswith(l, "# ")) {
578 assert(u->meta.description);
579 if (asprintf(&d, "%s %s", u->meta.description, t) < 0) {
584 free(u->meta.description);
585 u->meta.description = d;
592 /* If init scripts have no LSB header, then we enforce the
593 * ordering via the chkconfig priorities. We try to determine
594 * a priority for *all* init scripts here, since they are
595 * needed as soon as at least one non-LSB script is used. */
597 if (s->sysv_start_priority < 0) {
598 log_debug("%s has no chkconfig header, trying to determine SysV priority from link farm.", unit_id(u));
600 if ((r = priority_from_rcd(s, file_name_from_path(path))) < 0)
603 if (s->sysv_start_priority < 0)
604 log_warning("%s has neither a chkconfig header nor a directory link, cannot order unit!", unit_id(u));
607 if ((r = sysv_exec_commands(s)) < 0)
610 if (!s->sysv_runlevels || chars_intersect("12345", s->sysv_runlevels)) {
611 /* If there a runlevels configured for this service
612 * but none of the standard ones, then we assume this
613 * is some special kind of service (which might be
614 * needed for early boot) and don't create any links
617 if ((r = unit_add_dependency_by_name(u, UNIT_REQUIRES, SPECIAL_BASIC_TARGET)) < 0 ||
618 (r = unit_add_dependency_by_name(u, UNIT_AFTER, SPECIAL_BASIC_TARGET)) < 0)
622 u->meta.load_state = UNIT_LOADED;
633 static int service_load_sysv_name(Service *s, const char *name) {
639 STRV_FOREACH(p, UNIT(s)->meta.manager->sysvinit_path) {
643 if (asprintf(&path, "%s/%s", *p, name) < 0)
646 assert(endswith(path, ".service"));
647 path[strlen(path)-8] = 0;
649 r = service_load_sysv_path(s, path);
655 if ((UNIT(s)->meta.load_state != UNIT_STUB))
662 static int service_load_sysv(Service *s) {
669 /* Load service data from SysV init scripts, preferably with
672 if (strv_isempty(UNIT(s)->meta.manager->sysvinit_path))
675 if ((t = unit_id(UNIT(s))))
676 if ((r = service_load_sysv_name(s, t)) < 0)
679 if (UNIT(s)->meta.load_state == UNIT_STUB)
680 SET_FOREACH(t, UNIT(s)->meta.names, i) {
681 if (t == unit_id(UNIT(s)))
684 if ((r == service_load_sysv_name(s, t)) < 0)
687 if (UNIT(s)->meta.load_state != UNIT_STUB)
694 static void service_init(Unit *u) {
695 Service *s = SERVICE(u);
698 assert(u->meta.load_state == UNIT_STUB);
703 s->timeout_usec = DEFAULT_TIMEOUT_USEC;
704 s->restart_usec = DEFAULT_RESTART_USEC;
706 exec_context_init(&s->exec_context);
708 s->timer_watch.type = WATCH_INVALID;
710 s->state = SERVICE_DEAD;
712 s->sysv_start_priority = -1;
713 s->permissions_start_only = false;
714 s->root_directory_start_only = false;
715 s->valid_no_process = false;
717 s->sysv_has_lsb = false;
718 s->main_pid = s->control_pid = 0;
719 s->main_pid_known = false;
722 RATELIMIT_INIT(s->ratelimit, 10*USEC_PER_SEC, 5);
725 static int service_load(Unit *u) {
727 Service *s = SERVICE(u);
731 /* Load a .service file */
732 if ((r = unit_load_fragment(u)) < 0)
735 /* Load a classic init script as a fallback, if we couldn't find anything */
736 if (u->meta.load_state == UNIT_STUB)
737 if ((r = service_load_sysv(s)) < 0)
740 /* Still nothing found? Then let's give up */
741 if (u->meta.load_state == UNIT_STUB)
744 /* We were able to load something, then let's add in the
745 * dropin directories. */
746 if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
749 /* This is a new unit? Then let's add in some extras */
750 if (u->meta.load_state == UNIT_LOADED) {
751 if ((r = unit_add_exec_dependencies(u, &s->exec_context)) < 0)
754 if ((r = unit_add_default_cgroup(u)) < 0)
757 if ((r = sysv_chkconfig_order(s)) < 0)
764 static void service_dump(Unit *u, FILE *f, const char *prefix) {
766 ServiceExecCommand c;
767 Service *s = SERVICE(u);
773 p2 = strappend(prefix, "\t");
774 prefix2 = p2 ? p2 : prefix;
777 "%sService State: %s\n"
778 "%sPermissionsStartOnly: %s\n"
779 "%sRootDirectoryStartOnly: %s\n"
780 "%sValidNoProcess: %s\n"
783 prefix, service_state_to_string(s->state),
784 prefix, yes_no(s->permissions_start_only),
785 prefix, yes_no(s->root_directory_start_only),
786 prefix, yes_no(s->valid_no_process),
787 prefix, kill_mode_to_string(s->kill_mode),
788 prefix, service_type_to_string(s->type));
790 if (s->control_pid > 0)
792 "%sControl PID: %llu\n",
793 prefix, (unsigned long long) s->control_pid);
797 "%sMain PID: %llu\n",
798 prefix, (unsigned long long) s->main_pid);
803 prefix, s->pid_file);
805 exec_context_dump(&s->exec_context, f, prefix);
807 for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
809 if (!s->exec_command[c])
812 fprintf(f, "%s→ %s:\n",
813 prefix, service_exec_command_to_string(c));
815 exec_command_dump_list(s->exec_command[c], f, prefix2);
820 "%sSysV Init Script Path: %s\n"
821 "%sSysV Init Script has LSB Header: %s\n",
822 prefix, s->sysv_path,
823 prefix, yes_no(s->sysv_has_lsb));
825 if (s->sysv_start_priority >= 0)
827 "%sSysVStartPriority: %i\n",
828 prefix, s->sysv_start_priority);
830 if (s->sysv_runlevels)
831 fprintf(f, "%sSysVRunLevels: %s\n",
832 prefix, s->sysv_runlevels);
837 static int service_load_pid_file(Service *s) {
844 if (s->main_pid_known)
847 assert(s->main_pid <= 0);
852 if ((r = read_one_line_file(s->pid_file, &k)) < 0)
855 if ((r = safe_atolu(k, &p)) < 0) {
860 if ((unsigned long) (pid_t) p != p)
863 if (kill((pid_t) p, 0) < 0 && errno != EPERM) {
864 log_warning("PID %llu read from file %s does not exist. Your service or init script might be broken.",
865 (unsigned long long) p, s->pid_file);
869 if ((r = unit_watch_pid(UNIT(s), (pid_t) p)) < 0)
870 /* FIXME: we need to do something here */
873 s->main_pid = (pid_t) p;
874 s->main_pid_known = true;
879 static int service_get_sockets(Service *s, Set **_set) {
888 /* Collects all Socket objects that belong to this
889 * service. Note that a service might have multiple sockets
890 * via multiple names. */
892 if (!(set = set_new(NULL, NULL)))
895 SET_FOREACH(t, UNIT(s)->meta.names, i) {
899 /* Look for all socket objects that go by any of our
900 * units and collect their fds */
902 if (!(k = unit_name_change_suffix(t, ".socket"))) {
907 p = manager_get_unit(UNIT(s)->meta.manager, k);
912 if ((r = set_put(set, p)) < 0)
925 static int service_notify_sockets_dead(Service *s) {
933 /* Notifies all our sockets when we die */
935 if ((r = service_get_sockets(s, &set)) < 0)
938 SET_FOREACH(sock, set, i)
939 socket_notify_service_dead(sock);
946 static void service_set_state(Service *s, ServiceState state) {
947 ServiceState old_state;
950 old_state = s->state;
953 if (state != SERVICE_START_PRE &&
954 state != SERVICE_START &&
955 state != SERVICE_START_POST &&
956 state != SERVICE_RELOAD &&
957 state != SERVICE_STOP &&
958 state != SERVICE_STOP_SIGTERM &&
959 state != SERVICE_STOP_SIGKILL &&
960 state != SERVICE_STOP_POST &&
961 state != SERVICE_FINAL_SIGTERM &&
962 state != SERVICE_FINAL_SIGKILL &&
963 state != SERVICE_AUTO_RESTART)
964 unit_unwatch_timer(UNIT(s), &s->timer_watch);
966 if (state != SERVICE_START &&
967 state != SERVICE_START_POST &&
968 state != SERVICE_RUNNING &&
969 state != SERVICE_RELOAD &&
970 state != SERVICE_STOP &&
971 state != SERVICE_STOP_SIGTERM &&
972 state != SERVICE_STOP_SIGKILL)
973 service_unwatch_main_pid(s);
975 if (state != SERVICE_START_PRE &&
976 state != SERVICE_START &&
977 state != SERVICE_START_POST &&
978 state != SERVICE_RELOAD &&
979 state != SERVICE_STOP &&
980 state != SERVICE_STOP_SIGTERM &&
981 state != SERVICE_STOP_SIGKILL &&
982 state != SERVICE_STOP_POST &&
983 state != SERVICE_FINAL_SIGTERM &&
984 state != SERVICE_FINAL_SIGKILL) {
985 service_unwatch_control_pid(s);
986 s->control_command = NULL;
989 if (state == SERVICE_DEAD ||
990 state == SERVICE_STOP ||
991 state == SERVICE_STOP_SIGTERM ||
992 state == SERVICE_STOP_SIGKILL ||
993 state == SERVICE_STOP_POST ||
994 state == SERVICE_FINAL_SIGTERM ||
995 state == SERVICE_FINAL_SIGKILL ||
996 state == SERVICE_MAINTAINANCE ||
997 state == SERVICE_AUTO_RESTART)
998 service_notify_sockets_dead(s);
1000 if (old_state != state)
1001 log_debug("%s changed %s → %s", unit_id(UNIT(s)), service_state_to_string(old_state), service_state_to_string(state));
1003 unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state]);
1006 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
1010 unsigned rn_fds = 0;
1018 if ((r = service_get_sockets(s, &set)) < 0)
1021 SET_FOREACH(sock, set, i) {
1025 if ((r = socket_collect_fds(sock, &cfds, &cn_fds)) < 0)
1037 if (!(t = new(int, rn_fds+cn_fds))) {
1043 memcpy(t, rfds, rn_fds);
1044 memcpy(t+rn_fds, cfds, cn_fds);
1049 rn_fds = rn_fds+cn_fds;
1067 static int service_spawn(
1072 bool apply_permissions,
1086 if ((r = service_collect_fds(s, &fds, &n_fds)) < 0)
1090 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1093 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1095 if ((r = exec_spawn(c,
1100 UNIT(s)->meta.cgroup_bondings,
1104 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1105 /* FIXME: we need to do something here */
1117 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1122 static void service_enter_dead(Service *s, bool success, bool allow_restart) {
1129 if (allow_restart &&
1130 (s->restart == SERVICE_RESTART_ALWAYS ||
1131 (s->restart == SERVICE_RESTART_ON_SUCCESS && !s->failure))) {
1133 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
1136 service_set_state(s, SERVICE_AUTO_RESTART);
1138 service_set_state(s, s->failure ? SERVICE_MAINTAINANCE : SERVICE_DEAD);
1143 log_warning("%s failed to run install restart timer: %s", unit_id(UNIT(s)), strerror(-r));
1144 service_enter_dead(s, false, false);
1147 static void service_enter_signal(Service *s, ServiceState state, bool success);
1149 static void service_enter_stop_post(Service *s, bool success) {
1156 service_unwatch_control_pid(s);
1158 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST]))
1159 if ((r = service_spawn(s,
1163 !s->permissions_start_only,
1164 !s->root_directory_start_only,
1165 &s->control_pid)) < 0)
1169 service_set_state(s, SERVICE_STOP_POST);
1171 if (!s->control_command)
1172 service_enter_dead(s, true, true);
1177 log_warning("%s failed to run stop executable: %s", unit_id(UNIT(s)), strerror(-r));
1178 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1181 static void service_enter_signal(Service *s, ServiceState state, bool success) {
1190 if (s->main_pid > 0 || s->control_pid > 0) {
1193 sig = (state == SERVICE_STOP_SIGTERM || state == SERVICE_FINAL_SIGTERM) ? SIGTERM : SIGKILL;
1195 if (s->kill_mode == KILL_CONTROL_GROUP) {
1197 if ((r = cgroup_bonding_kill_list(UNIT(s)->meta.cgroup_bondings, sig)) < 0) {
1198 if (r != -EAGAIN && r != -ESRCH)
1206 if (s->main_pid > 0) {
1207 if (kill(s->kill_mode == KILL_PROCESS ? s->main_pid : -s->main_pid, sig) < 0 && errno != ESRCH)
1213 if (s->control_pid > 0) {
1214 if (kill(s->kill_mode == KILL_PROCESS ? s->control_pid : -s->control_pid, sig) < 0 && errno != ESRCH)
1225 service_set_state(s, state);
1227 if (s->main_pid <= 0 && s->control_pid <= 0)
1228 service_enter_dead(s, true, true);
1233 log_warning("%s failed to kill processes: %s", unit_id(UNIT(s)), strerror(-r));
1237 service_set_state(s, state);
1238 } else if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1239 service_enter_stop_post(s, false);
1241 service_enter_dead(s, false, true);
1244 static void service_enter_stop(Service *s, bool success) {
1251 service_unwatch_control_pid(s);
1253 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP]))
1254 if ((r = service_spawn(s,
1258 !s->permissions_start_only,
1259 !s->root_directory_start_only,
1260 &s->control_pid)) < 0)
1263 service_set_state(s, SERVICE_STOP);
1265 if (!s->control_command)
1266 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
1271 log_warning("%s failed to run stop executable: %s", unit_id(UNIT(s)), strerror(-r));
1272 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1275 static void service_enter_start_post(Service *s) {
1279 service_unwatch_control_pid(s);
1281 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_POST]))
1282 if ((r = service_spawn(s,
1286 !s->permissions_start_only,
1287 !s->root_directory_start_only,
1288 &s->control_pid)) < 0)
1292 service_set_state(s, SERVICE_START_POST);
1294 if (!s->control_command)
1295 service_set_state(s, SERVICE_RUNNING);
1300 log_warning("%s failed to run start-post executable: %s", unit_id(UNIT(s)), strerror(-r));
1301 service_enter_stop(s, false);
1304 static void service_enter_start(Service *s) {
1310 assert(s->exec_command[SERVICE_EXEC_START]);
1311 assert(!s->exec_command[SERVICE_EXEC_START]->command_next);
1313 if ((r = service_spawn(s,
1314 s->exec_command[SERVICE_EXEC_START],
1315 s->type == SERVICE_FORKING,
1322 service_set_state(s, SERVICE_START);
1324 if (s->type == SERVICE_SIMPLE) {
1325 /* For simple services we immediately start
1326 * the START_POST binaries. */
1328 service_unwatch_main_pid(s);
1331 s->main_pid_known = true;
1332 service_enter_start_post(s);
1334 } else if (s->type == SERVICE_FORKING) {
1336 /* For forking services we wait until the start
1337 * process exited. */
1339 service_unwatch_control_pid(s);
1341 s->control_pid = pid;
1342 s->control_command = s->exec_command[SERVICE_EXEC_START];
1343 } else if (s->type == SERVICE_FINISH) {
1345 /* For finishing services we wait until the start
1346 * process exited, too, but it is our main process. */
1348 service_unwatch_main_pid(s);
1351 s->main_pid_known = true;
1352 s->control_command = s->exec_command[SERVICE_EXEC_START];
1354 assert_not_reached("Unknown service type");
1359 log_warning("%s failed to run start exectuable: %s", unit_id(UNIT(s)), strerror(-r));
1360 service_enter_stop(s, false);
1363 static void service_enter_start_pre(Service *s) {
1368 service_unwatch_control_pid(s);
1370 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_PRE]))
1371 if ((r = service_spawn(s,
1375 !s->permissions_start_only,
1376 !s->root_directory_start_only,
1377 &s->control_pid)) < 0)
1380 service_set_state(s, SERVICE_START_PRE);
1382 if (!s->control_command)
1383 service_enter_start(s);
1388 log_warning("%s failed to run start-pre executable: %s", unit_id(UNIT(s)), strerror(-r));
1389 service_enter_dead(s, false, true);
1392 static void service_enter_restart(Service *s) {
1396 if ((r = manager_add_job(UNIT(s)->meta.manager, JOB_START, UNIT(s), JOB_FAIL, false, NULL)) < 0)
1399 log_debug("%s scheduled restart job.", unit_id(UNIT(s)));
1400 service_enter_dead(s, true, false);
1405 log_warning("%s failed to schedule restart job: %s", unit_id(UNIT(s)), strerror(-r));
1406 service_enter_dead(s, false, false);
1409 static void service_enter_reload(Service *s) {
1414 service_unwatch_control_pid(s);
1416 if ((s->control_command = s->exec_command[SERVICE_EXEC_RELOAD]))
1417 if ((r = service_spawn(s,
1421 !s->permissions_start_only,
1422 !s->root_directory_start_only,
1423 &s->control_pid)) < 0)
1426 service_set_state(s, SERVICE_RELOAD);
1428 if (!s->control_command)
1429 service_set_state(s, SERVICE_RUNNING);
1434 log_warning("%s failed to run reload executable: %s", unit_id(UNIT(s)), strerror(-r));
1435 service_enter_stop(s, false);
1438 static void service_run_next(Service *s, bool success) {
1442 assert(s->control_command);
1443 assert(s->control_command->command_next);
1448 s->control_command = s->control_command->command_next;
1450 service_unwatch_control_pid(s);
1452 if ((r = service_spawn(s,
1456 !s->permissions_start_only,
1457 !s->root_directory_start_only,
1458 &s->control_pid)) < 0)
1464 log_warning("%s failed to run spawn next executable: %s", unit_id(UNIT(s)), strerror(-r));
1466 if (s->state == SERVICE_STOP)
1467 service_enter_stop_post(s, false);
1468 else if (s->state == SERVICE_STOP_POST)
1469 service_enter_dead(s, false, true);
1471 service_enter_stop(s, false);
1474 static int service_start(Unit *u) {
1475 Service *s = SERVICE(u);
1479 /* We cannot fulfill this request right now, try again later
1481 if (s->state == SERVICE_STOP ||
1482 s->state == SERVICE_STOP_SIGTERM ||
1483 s->state == SERVICE_STOP_SIGKILL ||
1484 s->state == SERVICE_STOP_POST ||
1485 s->state == SERVICE_FINAL_SIGTERM ||
1486 s->state == SERVICE_FINAL_SIGKILL)
1489 /* Already on it! */
1490 if (s->state == SERVICE_START_PRE ||
1491 s->state == SERVICE_START ||
1492 s->state == SERVICE_START_POST)
1495 assert(s->state == SERVICE_DEAD || s->state == SERVICE_MAINTAINANCE || s->state == SERVICE_AUTO_RESTART);
1497 /* Make sure we don't enter a busy loop of some kind. */
1498 if (!ratelimit_test(&s->ratelimit)) {
1499 log_warning("%s start request repeated too quickly, refusing to start.", unit_id(u));
1504 s->main_pid_known = false;
1506 service_enter_start_pre(s);
1510 static int service_stop(Unit *u) {
1511 Service *s = SERVICE(u);
1515 /* Cannot do this now */
1516 if (s->state == SERVICE_START_PRE ||
1517 s->state == SERVICE_START ||
1518 s->state == SERVICE_START_POST ||
1519 s->state == SERVICE_RELOAD)
1523 if (s->state == SERVICE_STOP ||
1524 s->state == SERVICE_STOP_SIGTERM ||
1525 s->state == SERVICE_STOP_SIGKILL ||
1526 s->state == SERVICE_STOP_POST ||
1527 s->state == SERVICE_FINAL_SIGTERM ||
1528 s->state == SERVICE_FINAL_SIGKILL)
1531 if (s->state == SERVICE_AUTO_RESTART) {
1532 service_set_state(s, SERVICE_DEAD);
1536 assert(s->state == SERVICE_RUNNING);
1538 service_enter_stop(s, true);
1542 static int service_reload(Unit *u) {
1543 Service *s = SERVICE(u);
1547 assert(s->state == SERVICE_RUNNING);
1549 service_enter_reload(s);
1553 static bool service_can_reload(Unit *u) {
1554 Service *s = SERVICE(u);
1558 return !!s->exec_command[SERVICE_EXEC_RELOAD];
1561 static UnitActiveState service_active_state(Unit *u) {
1564 return state_translation_table[SERVICE(u)->state];
1567 static int main_pid_good(Service *s) {
1570 /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1573 /* If we know the pid file, then lets just check if it is
1575 if (s->main_pid_known)
1576 return s->main_pid > 0;
1578 /* We don't know the pid */
1582 static bool control_pid_good(Service *s) {
1585 return s->control_pid > 0;
1588 static int cgroup_good(Service *s) {
1591 if (s->valid_no_process)
1594 return cgroup_bonding_is_empty_list(UNIT(s)->meta.cgroup_bondings);
1597 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
1598 Service *s = SERVICE(u);
1604 success = code == CLD_EXITED && status == 0;
1605 s->failure = s->failure || !success;
1607 if (s->main_pid == pid) {
1609 exec_status_fill(&s->main_exec_status, pid, code, status);
1612 if (s->type == SERVICE_SIMPLE || s->type == SERVICE_FINISH) {
1613 assert(s->exec_command[SERVICE_EXEC_START]);
1614 s->exec_command[SERVICE_EXEC_START]->exec_status = s->main_exec_status;
1617 log_debug("%s: main process exited, code=%s, status=%i", unit_id(u), sigchld_code_to_string(code), status);
1619 /* The service exited, so the service is officially
1624 case SERVICE_START_POST:
1625 case SERVICE_RELOAD:
1627 /* Need to wait until the operation is
1632 assert(s->type == SERVICE_FINISH);
1634 /* This was our main goal, so let's go on */
1636 service_enter_start_post(s);
1638 service_enter_stop(s, false);
1641 case SERVICE_RUNNING:
1642 service_enter_stop(s, success);
1645 case SERVICE_STOP_SIGTERM:
1646 case SERVICE_STOP_SIGKILL:
1648 if (!control_pid_good(s))
1649 service_enter_stop_post(s, success);
1651 /* If there is still a control process, wait for that first */
1655 assert_not_reached("Uh, main process died at wrong time.");
1658 } else if (s->control_pid == pid) {
1659 assert(s->control_command);
1661 exec_status_fill(&s->control_command->exec_status, pid, code, status);
1664 log_debug("%s: control process exited, code=%s status=%i", unit_id(u), sigchld_code_to_string(code), status);
1666 /* If we are shutting things down anyway we
1667 * don't care about failing commands. */
1669 if (s->control_command->command_next &&
1670 (success || (s->state == SERVICE_STOP || s->state == SERVICE_STOP_POST)))
1672 /* There is another command to *
1673 * execute, so let's do that. */
1675 service_run_next(s, success);
1678 /* No further commands for this step, so let's
1679 * figure out what to do next */
1681 log_debug("%s got final SIGCHLD for state %s", unit_id(u), service_state_to_string(s->state));
1685 case SERVICE_START_PRE:
1687 service_enter_start(s);
1689 service_enter_stop(s, false);
1693 assert(s->type == SERVICE_FORKING);
1695 /* Let's try to load the pid
1696 * file here if we can. We
1697 * ignore the return value,
1698 * since the PID file might
1699 * actually be created by a
1700 * START_POST script */
1704 service_load_pid_file(s);
1706 service_enter_start_post(s);
1708 service_enter_stop(s, false);
1712 case SERVICE_START_POST:
1713 if (success && s->pid_file && !s->main_pid_known) {
1716 /* Hmm, let's see if we can
1717 * load the pid now after the
1718 * start-post scripts got
1721 if ((r = service_load_pid_file(s)) < 0)
1722 log_warning("%s: failed to load PID file %s: %s", unit_id(UNIT(s)), s->pid_file, strerror(-r));
1727 case SERVICE_RELOAD:
1729 if (main_pid_good(s) != 0 && cgroup_good(s) != 0)
1730 service_set_state(s, SERVICE_RUNNING);
1732 service_enter_stop(s, true);
1734 service_enter_stop(s, false);
1739 if (main_pid_good(s) > 0)
1740 /* Still not dead and we know the PID? Let's go hunting. */
1741 service_enter_signal(s, SERVICE_STOP_SIGTERM, success);
1743 service_enter_stop_post(s, success);
1746 case SERVICE_STOP_SIGTERM:
1747 case SERVICE_STOP_SIGKILL:
1748 if (main_pid_good(s) <= 0)
1749 service_enter_stop_post(s, success);
1751 /* If there is still a service
1752 * process around, wait until
1753 * that one quit, too */
1756 case SERVICE_STOP_POST:
1757 case SERVICE_FINAL_SIGTERM:
1758 case SERVICE_FINAL_SIGKILL:
1759 service_enter_dead(s, success, true);
1763 assert_not_reached("Uh, control process died at wrong time.");
1767 assert_not_reached("Got SIGCHLD for unkown PID");
1770 static void service_timer_event(Unit *u, uint64_t elapsed, Watch* w) {
1771 Service *s = SERVICE(u);
1774 assert(elapsed == 1);
1776 assert(w == &s->timer_watch);
1780 case SERVICE_START_PRE:
1782 case SERVICE_START_POST:
1783 case SERVICE_RELOAD:
1784 log_warning("%s operation timed out. Stopping.", unit_id(u));
1785 service_enter_stop(s, false);
1789 log_warning("%s stopping timed out. Terminating.", unit_id(u));
1790 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1793 case SERVICE_STOP_SIGTERM:
1794 log_warning("%s stopping timed out. Killing.", unit_id(u));
1795 service_enter_signal(s, SERVICE_STOP_SIGKILL, false);
1798 case SERVICE_STOP_SIGKILL:
1799 /* Uh, wie sent a SIGKILL and it is still not gone?
1800 * Must be something we cannot kill, so let's just be
1801 * weirded out and continue */
1803 log_warning("%s still around after SIGKILL. Ignoring.", unit_id(u));
1804 service_enter_stop_post(s, false);
1807 case SERVICE_STOP_POST:
1808 log_warning("%s stopping timed out (2). Terminating.", unit_id(u));
1809 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1812 case SERVICE_FINAL_SIGTERM:
1813 log_warning("%s stopping timed out (2). Killing.", unit_id(u));
1814 service_enter_signal(s, SERVICE_FINAL_SIGKILL, false);
1817 case SERVICE_FINAL_SIGKILL:
1818 log_warning("%s still around after SIGKILL (2). Entering maintainance mode.", unit_id(u));
1819 service_enter_dead(s, false, true);
1822 case SERVICE_AUTO_RESTART:
1823 log_debug("%s holdoff time over, scheduling restart.", unit_id(u));
1824 service_enter_restart(s);
1828 assert_not_reached("Timeout at wrong time.");
1832 static void service_cgroup_notify_event(Unit *u) {
1833 Service *s = SERVICE(u);
1837 log_debug("%s: cgroup is empty", unit_id(u));
1841 /* Waiting for SIGCHLD is usually more interesting,
1842 * because it includes return codes/signals. Which is
1843 * why we ignore the cgroup events for most cases,
1844 * except when we don't know pid which to expect the
1847 case SERVICE_RUNNING:
1849 if (!s->valid_no_process && main_pid_good(s) <= 0)
1850 service_enter_stop(s, true);
1859 static int service_enumerate(Manager *m) {
1863 char *path = NULL, *fpath = NULL, *name = NULL;
1868 STRV_FOREACH(p, m->sysvrcnd_path)
1869 for (i = 0; i < ELEMENTSOF(rcnd_table); i += 2) {
1874 if (asprintf(&path, "%s/%s", *p, rcnd_table[i]) < 0) {
1882 if (!(d = opendir(path))) {
1883 if (errno != ENOENT)
1884 log_warning("opendir() failed on %s: %s", path, strerror(errno));
1889 while ((de = readdir(d))) {
1890 Unit *runlevel, *service;
1892 if (ignore_file(de->d_name))
1895 if (de->d_name[0] != 'S' && de->d_name[0] != 'K')
1898 if (strlen(de->d_name) < 4)
1903 if (asprintf(&fpath, "%s/%s/%s", *p, rcnd_table[i], de->d_name) < 0) {
1908 if (access(fpath, X_OK) < 0) {
1910 if (errno != ENOENT)
1911 log_warning("access() failed on %s: %s", fpath, strerror(errno));
1918 if (asprintf(&name, "%s.service", de->d_name+3) < 0) {
1923 if ((r = manager_load_unit(m, name, &service)) < 0)
1926 if ((r = manager_load_unit(m, rcnd_table[i+1], &runlevel)) < 0)
1929 if (de->d_name[0] == 'S') {
1930 if ((r = unit_add_dependency(runlevel, UNIT_WANTS, service)) < 0)
1933 if ((r = unit_add_dependency(runlevel, UNIT_AFTER, service)) < 0)
1936 } else if (de->d_name[0] == 'K' &&
1937 (streq(rcnd_table[i+1], SPECIAL_RUNLEVEL0_TARGET) ||
1938 streq(rcnd_table[i+1], SPECIAL_RUNLEVEL6_TARGET))) {
1940 /* We honour K links only for
1941 * halt/reboot. For the normal
1942 * runlevels we assume the
1944 * implicitly added by the
1947 if ((r = unit_add_dependency(runlevel, UNIT_CONFLICTS, service)) < 0)
1950 if ((r = unit_add_dependency(runlevel, UNIT_BEFORE, service)) < 0)
1967 static const char* const service_state_table[_SERVICE_STATE_MAX] = {
1968 [SERVICE_DEAD] = "dead",
1969 [SERVICE_START_PRE] = "start-pre",
1970 [SERVICE_START] = "start",
1971 [SERVICE_START_POST] = "start-post",
1972 [SERVICE_RUNNING] = "running",
1973 [SERVICE_RELOAD] = "reload",
1974 [SERVICE_STOP] = "stop",
1975 [SERVICE_STOP_SIGTERM] = "stop-sigterm",
1976 [SERVICE_STOP_SIGKILL] = "stop-sigkill",
1977 [SERVICE_STOP_POST] = "stop-post",
1978 [SERVICE_FINAL_SIGTERM] = "final-sigterm",
1979 [SERVICE_FINAL_SIGKILL] = "final-sigkill",
1980 [SERVICE_MAINTAINANCE] = "maintainance",
1981 [SERVICE_AUTO_RESTART] = "auto-restart",
1984 DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
1986 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
1987 [SERVICE_ONCE] = "once",
1988 [SERVICE_RESTART_ON_SUCCESS] = "restart-on-success",
1989 [SERVICE_RESTART_ALWAYS] = "restart-on-failure",
1992 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
1994 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
1995 [SERVICE_FORKING] = "forking",
1996 [SERVICE_SIMPLE] = "simple",
1997 [SERVICE_FINISH] = "finish"
2000 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
2002 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
2003 [SERVICE_EXEC_START_PRE] = "ExecStartPre",
2004 [SERVICE_EXEC_START] = "ExecStart",
2005 [SERVICE_EXEC_START_POST] = "ExecStartPost",
2006 [SERVICE_EXEC_RELOAD] = "ExecReload",
2007 [SERVICE_EXEC_STOP] = "ExecStop",
2008 [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
2011 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
2013 const UnitVTable service_vtable = {
2014 .suffix = ".service",
2016 .init = service_init,
2017 .load = service_load,
2018 .done = service_done,
2020 .dump = service_dump,
2022 .start = service_start,
2023 .stop = service_stop,
2024 .reload = service_reload,
2026 .can_reload = service_can_reload,
2028 .active_state = service_active_state,
2030 .sigchld_event = service_sigchld_event,
2031 .timer_event = service_timer_event,
2033 .cgroup_notify_empty = service_cgroup_notify_event,
2035 .enumerate = service_enumerate