1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
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"
33 #include "unit-name.h"
34 #include "dbus-service.h"
36 #include "bus-errors.h"
37 #include "exit-status.h"
41 #ifdef HAVE_SYSV_COMPAT
43 #define DEFAULT_SYSV_TIMEOUT_USEC (5*USEC_PER_MINUTE)
45 typedef enum RunlevelType {
54 const RunlevelType type;
56 /* Standard SysV runlevels for start-up */
57 { "rc1.d", SPECIAL_RESCUE_TARGET, RUNLEVEL_UP },
58 { "rc2.d", SPECIAL_RUNLEVEL2_TARGET, RUNLEVEL_UP },
59 { "rc3.d", SPECIAL_RUNLEVEL3_TARGET, RUNLEVEL_UP },
60 { "rc4.d", SPECIAL_RUNLEVEL4_TARGET, RUNLEVEL_UP },
61 { "rc5.d", SPECIAL_RUNLEVEL5_TARGET, RUNLEVEL_UP },
64 /* SUSE style boot.d */
65 { "boot.d", SPECIAL_SYSINIT_TARGET, RUNLEVEL_SYSINIT },
68 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU) || defined(TARGET_ANGSTROM)
69 /* Debian style rcS.d */
70 { "rcS.d", SPECIAL_SYSINIT_TARGET, RUNLEVEL_SYSINIT },
73 /* Standard SysV runlevels for shutdown */
74 { "rc0.d", SPECIAL_POWEROFF_TARGET, RUNLEVEL_DOWN },
75 { "rc6.d", SPECIAL_REBOOT_TARGET, RUNLEVEL_DOWN }
77 /* Note that the order here matters, as we read the
78 directories in this order, and we want to make sure that
79 sysv_start_priority is known when we first load the
80 unit. And that value we only know from S links. Hence
81 UP/SYSINIT must be read before DOWN */
84 #define RUNLEVELS_UP "12345"
85 /* #define RUNLEVELS_DOWN "06" */
86 /* #define RUNLEVELS_BOOT "bBsS" */
89 static const UnitActiveState state_translation_table[_SERVICE_STATE_MAX] = {
90 [SERVICE_DEAD] = UNIT_INACTIVE,
91 [SERVICE_START_PRE] = UNIT_ACTIVATING,
92 [SERVICE_START] = UNIT_ACTIVATING,
93 [SERVICE_START_POST] = UNIT_ACTIVATING,
94 [SERVICE_RUNNING] = UNIT_ACTIVE,
95 [SERVICE_EXITED] = UNIT_ACTIVE,
96 [SERVICE_RELOAD] = UNIT_RELOADING,
97 [SERVICE_STOP] = UNIT_DEACTIVATING,
98 [SERVICE_STOP_SIGTERM] = UNIT_DEACTIVATING,
99 [SERVICE_STOP_SIGKILL] = UNIT_DEACTIVATING,
100 [SERVICE_STOP_POST] = UNIT_DEACTIVATING,
101 [SERVICE_FINAL_SIGTERM] = UNIT_DEACTIVATING,
102 [SERVICE_FINAL_SIGKILL] = UNIT_DEACTIVATING,
103 [SERVICE_FAILED] = UNIT_FAILED,
104 [SERVICE_AUTO_RESTART] = UNIT_ACTIVATING
107 static void service_init(Unit *u) {
108 Service *s = SERVICE(u);
111 assert(u->meta.load_state == UNIT_STUB);
113 s->timeout_usec = DEFAULT_TIMEOUT_USEC;
114 s->restart_usec = DEFAULT_RESTART_USEC;
115 s->timer_watch.type = WATCH_INVALID;
116 #ifdef HAVE_SYSV_COMPAT
117 s->sysv_start_priority = -1;
118 s->sysv_start_priority_from_rcnd = -1;
121 s->guess_main_pid = true;
123 exec_context_init(&s->exec_context);
125 RATELIMIT_INIT(s->ratelimit, 10*USEC_PER_SEC, 5);
127 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
130 static void service_unwatch_control_pid(Service *s) {
133 if (s->control_pid <= 0)
136 unit_unwatch_pid(UNIT(s), s->control_pid);
140 static void service_unwatch_main_pid(Service *s) {
143 if (s->main_pid <= 0)
146 unit_unwatch_pid(UNIT(s), s->main_pid);
150 static int service_set_main_pid(Service *s, pid_t pid) {
162 s->main_pid_known = true;
164 if (get_parent_of_pid(pid, &ppid) >= 0 && ppid != getpid()) {
165 log_warning("%s: Supervising process %lu which is not our child. We'll most likely not notice when it exits.",
166 s->meta.id, (unsigned long) pid);
168 s->main_pid_alien = true;
170 s->main_pid_alien = false;
172 exec_status_start(&s->main_exec_status, pid);
177 static void service_close_socket_fd(Service *s) {
180 if (s->socket_fd < 0)
183 close_nointr_nofail(s->socket_fd);
187 static void service_connection_unref(Service *s) {
190 if (!s->accept_socket)
193 socket_connection_unref(s->accept_socket);
194 s->accept_socket = NULL;
197 static void service_done(Unit *u) {
198 Service *s = SERVICE(u);
205 #ifdef HAVE_SYSV_COMPAT
209 free(s->sysv_runlevels);
210 s->sysv_runlevels = NULL;
213 free(s->status_text);
214 s->status_text = NULL;
216 exec_context_done(&s->exec_context);
217 exec_command_free_array(s->exec_command, _SERVICE_EXEC_COMMAND_MAX);
218 s->control_command = NULL;
219 s->main_command = NULL;
221 /* This will leak a process, but at least no memory or any of
223 service_unwatch_main_pid(s);
224 service_unwatch_control_pid(s);
227 unit_unwatch_bus_name(UNIT(u), s->bus_name);
232 service_close_socket_fd(s);
233 service_connection_unref(s);
235 set_free(s->configured_sockets);
237 unit_unwatch_timer(u, &s->timer_watch);
240 #ifdef HAVE_SYSV_COMPAT
241 static char *sysv_translate_name(const char *name) {
244 if (!(r = new(char, strlen(name) + sizeof(".service"))))
247 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU) || defined(TARGET_ANGSTROM)
248 if (endswith(name, ".sh"))
249 /* Drop Debian-style .sh suffix */
250 strcpy(stpcpy(r, name) - 3, ".service");
253 if (startswith(name, "boot."))
254 /* Drop SuSE-style boot. prefix */
255 strcpy(stpcpy(r, name + 5), ".service");
257 #ifdef TARGET_FRUGALWARE
258 if (startswith(name, "rc."))
259 /* Drop Frugalware-style rc. prefix */
260 strcpy(stpcpy(r, name + 3), ".service");
263 /* Normal init scripts */
264 strcpy(stpcpy(r, name), ".service");
269 static int sysv_translate_facility(const char *name, const char *filename, char **_r) {
271 /* We silently ignore the $ prefix here. According to the LSB
272 * spec it simply indicates whether something is a
273 * standardized name or a distribution-specific one. Since we
274 * just follow what already exists and do not introduce new
275 * uses or names we don't care who introduced a new name. */
277 static const char * const table[] = {
278 /* LSB defined facilities */
279 "local_fs", SPECIAL_LOCAL_FS_TARGET,
280 #ifndef TARGET_MANDRIVA
281 /* Due to unfortunate name selection in Mandriva,
282 * $network is provided by network-up which is ordered
283 * after network which actually starts interfaces.
284 * To break the loop, just ignore it */
285 "network", SPECIAL_NETWORK_TARGET,
287 "named", SPECIAL_NSS_LOOKUP_TARGET,
288 "portmap", SPECIAL_RPCBIND_TARGET,
289 "remote_fs", SPECIAL_REMOTE_FS_TARGET,
290 "syslog", SPECIAL_SYSLOG_TARGET,
291 "time", SPECIAL_TIME_SYNC_TARGET,
293 /* common extensions */
294 "mail-transfer-agent", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
295 "x-display-manager", SPECIAL_DISPLAY_MANAGER_SERVICE,
298 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU) || defined(TARGET_ANGSTROM)
299 "mail-transport-agent", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
303 "MTA", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
304 "smtpdaemon", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
305 "httpd", SPECIAL_HTTP_DAEMON_TARGET,
309 "smtp", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
320 n = *name == '$' ? name + 1 : name;
322 for (i = 0; i < ELEMENTSOF(table); i += 2) {
324 if (!streq(table[i], n))
330 if (!(r = strdup(table[i+1])))
336 /* If we don't know this name, fallback heuristics to figure
337 * out whether something is a target or a service alias. */
340 if (!unit_prefix_is_valid(n))
343 /* Facilities starting with $ are most likely targets */
344 r = unit_name_build(n, NULL, ".target");
345 } else if (filename && streq(name, filename))
346 /* Names equaling the file name of the services are redundant */
349 /* Everything else we assume to be normal service names */
350 r = sysv_translate_name(n);
361 static int sysv_fix_order(Service *s) {
367 if (s->sysv_start_priority < 0)
370 /* For each pair of services where at least one lacks a LSB
371 * header, we use the start priority value to order things. */
373 LIST_FOREACH(units_by_type, other, s->meta.manager->units_by_type[UNIT_SERVICE]) {
376 bool special_s, special_t;
378 t = (Service*) other;
383 if (t->meta.load_state != UNIT_LOADED)
386 if (t->sysv_start_priority < 0)
389 /* If both units have modern headers we don't care
390 * about the priorities */
391 if ((s->meta.fragment_path || s->sysv_has_lsb) &&
392 (t->meta.fragment_path || t->sysv_has_lsb))
395 special_s = s->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, s->sysv_runlevels);
396 special_t = t->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, t->sysv_runlevels);
398 if (special_t && !special_s)
400 else if (special_s && !special_t)
402 else if (t->sysv_start_priority < s->sysv_start_priority)
404 else if (t->sysv_start_priority > s->sysv_start_priority)
409 /* FIXME: Maybe we should compare the name here lexicographically? */
411 if ((r = unit_add_dependency(UNIT(s), d, UNIT(t), true)) < 0)
418 static ExecCommand *exec_command_new(const char *path, const char *arg1) {
421 if (!(c = new0(ExecCommand, 1)))
424 if (!(c->path = strdup(path))) {
429 if (!(c->argv = strv_new(path, arg1, NULL))) {
438 static int sysv_exec_commands(Service *s) {
442 assert(s->sysv_path);
444 if (!(c = exec_command_new(s->sysv_path, "start")))
446 exec_command_append_list(s->exec_command+SERVICE_EXEC_START, c);
448 if (!(c = exec_command_new(s->sysv_path, "stop")))
450 exec_command_append_list(s->exec_command+SERVICE_EXEC_STOP, c);
452 if (!(c = exec_command_new(s->sysv_path, "reload")))
454 exec_command_append_list(s->exec_command+SERVICE_EXEC_RELOAD, c);
459 static int service_load_sysv_path(Service *s, const char *path) {
470 char *short_description = NULL, *long_description = NULL, *chkconfig_description = NULL, *description;
478 if (!(f = fopen(path, "re"))) {
479 r = errno == ENOENT ? 0 : -errno;
484 if (fstat(fileno(f), &st) < 0) {
490 if (!(s->sysv_path = strdup(path))) {
495 s->sysv_mtime = timespec_load(&st.st_mtim);
497 if (null_or_empty(&st)) {
498 u->meta.load_state = UNIT_MASKED;
504 char l[LINE_MAX], *t;
506 if (!fgets(l, sizeof(l), f)) {
511 log_error("Failed to read configuration file '%s': %s", path, strerror(-r));
521 if (state == NORMAL && streq(t, "### BEGIN INIT INFO")) {
523 s->sysv_has_lsb = true;
527 if ((state == LSB_DESCRIPTION || state == LSB) && streq(t, "### END INIT INFO")) {
533 t += strspn(t, WHITESPACE);
535 if (state == NORMAL) {
537 /* Try to parse Red Hat style chkconfig headers */
539 if (startswith_no_case(t, "chkconfig:")) {
541 char runlevels[16], *k;
545 if (sscanf(t+10, "%15s %i %*i",
547 &start_priority) != 2) {
549 log_warning("[%s:%u] Failed to parse chkconfig line. Ignoring.", path, line);
553 /* A start priority gathered from the
554 * symlink farms is preferred over the
555 * data from the LSB header. */
556 if (start_priority < 0 || start_priority > 99)
557 log_warning("[%s:%u] Start priority out of range. Ignoring.", path, line);
559 s->sysv_start_priority = start_priority;
561 char_array_0(runlevels);
562 k = delete_chars(runlevels, WHITESPACE "-");
567 if (!(d = strdup(k))) {
572 free(s->sysv_runlevels);
573 s->sysv_runlevels = d;
576 } else if (startswith_no_case(t, "description:")) {
578 size_t k = strlen(t);
582 if (t[k-1] == '\\') {
587 if ((j = strstrip(t+12)) && *j) {
588 if (!(d = strdup(j))) {
595 free(chkconfig_description);
596 chkconfig_description = d;
598 } else if (startswith_no_case(t, "pidfile:")) {
605 if (!path_is_absolute(fn)) {
606 log_warning("[%s:%u] PID file not absolute. Ignoring.", path, line);
610 if (!(fn = strdup(fn))) {
619 } else if (state == DESCRIPTION) {
621 /* Try to parse Red Hat style description
624 size_t k = strlen(t);
632 if ((j = strstrip(t)) && *j) {
635 if (chkconfig_description)
636 d = join(chkconfig_description, " ", j, NULL);
645 free(chkconfig_description);
646 chkconfig_description = d;
649 } else if (state == LSB || state == LSB_DESCRIPTION) {
651 if (startswith_no_case(t, "Provides:")) {
657 FOREACH_WORD_QUOTED(w, z, t+9, i) {
660 if (!(n = strndup(w, z))) {
665 r = sysv_translate_facility(n, file_name_from_path(path), &m);
674 if (unit_name_to_type(m) == UNIT_SERVICE)
675 r = unit_add_name(u, m);
682 * indication that the
684 * now available. This
687 * targets do NOT pull
690 r = unit_add_two_dependencies_by_name(u, UNIT_BEFORE, UNIT_WANTS, m, NULL, true);
693 log_error("[%s:%u] Failed to add LSB Provides name %s, ignoring: %s", path, line, m, strerror(-r));
698 } else if (startswith_no_case(t, "Required-Start:") ||
699 startswith_no_case(t, "Should-Start:") ||
700 startswith_no_case(t, "X-Start-Before:") ||
701 startswith_no_case(t, "X-Start-After:")) {
707 FOREACH_WORD_QUOTED(w, z, strchr(t, ':')+1, i) {
710 if (!(n = strndup(w, z))) {
715 r = sysv_translate_facility(n, file_name_from_path(path), &m);
718 log_error("[%s:%u] Failed to translate LSB dependency %s, ignoring: %s", path, line, n, strerror(-r));
728 r = unit_add_dependency_by_name(u, startswith_no_case(t, "X-Start-Before:") ? UNIT_BEFORE : UNIT_AFTER, m, NULL, true);
731 log_error("[%s:%u] Failed to add dependency on %s, ignoring: %s", path, line, m, strerror(-r));
735 } else if (startswith_no_case(t, "Default-Start:")) {
740 k = delete_chars(t+14, WHITESPACE "-");
743 if (!(d = strdup(k))) {
748 free(s->sysv_runlevels);
749 s->sysv_runlevels = d;
752 } else if (startswith_no_case(t, "Description:")) {
755 state = LSB_DESCRIPTION;
757 if ((j = strstrip(t+12)) && *j) {
758 if (!(d = strdup(j))) {
765 free(long_description);
766 long_description = d;
768 } else if (startswith_no_case(t, "Short-Description:")) {
773 if ((j = strstrip(t+18)) && *j) {
774 if (!(d = strdup(j))) {
781 free(short_description);
782 short_description = d;
784 } else if (state == LSB_DESCRIPTION) {
786 if (startswith(l, "#\t") || startswith(l, "# ")) {
789 if ((j = strstrip(t)) && *j) {
792 if (long_description)
793 d = join(long_description, " ", t, NULL);
802 free(long_description);
803 long_description = d;
812 if ((r = sysv_exec_commands(s)) < 0)
815 if (s->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, s->sysv_runlevels)) {
816 /* If there a runlevels configured for this service
817 * but none of the standard ones, then we assume this
818 * is some special kind of service (which might be
819 * needed for early boot) and don't create any links
822 s->meta.default_dependencies = false;
824 /* Don't timeout special services during boot (like fsck) */
827 s->timeout_usec = DEFAULT_SYSV_TIMEOUT_USEC;
829 /* Special setting for all SysV services */
830 s->type = SERVICE_FORKING;
831 s->remain_after_exit = !s->pid_file;
832 s->restart = SERVICE_RESTART_NO;
834 if (s->meta.manager->sysv_console)
835 s->exec_context.std_output = EXEC_OUTPUT_TTY;
837 s->exec_context.kill_mode = KILL_PROCESS;
839 /* We use the long description only if
840 * no short description is set. */
842 if (short_description)
843 description = short_description;
844 else if (chkconfig_description)
845 description = chkconfig_description;
846 else if (long_description)
847 description = long_description;
854 if (!(d = strappend(s->sysv_has_lsb ? "LSB: " : "SYSV: ", description))) {
859 u->meta.description = d;
862 /* The priority that has been set in /etc/rcN.d/ hierarchies
863 * takes precedence over what is stored as default in the LSB
865 if (s->sysv_start_priority_from_rcnd >= 0)
866 s->sysv_start_priority = s->sysv_start_priority_from_rcnd;
868 u->meta.load_state = UNIT_LOADED;
876 free(short_description);
877 free(long_description);
878 free(chkconfig_description);
883 static int service_load_sysv_name(Service *s, const char *name) {
889 /* For SysV services we strip the boot.*, rc.* and *.sh
890 * prefixes/suffixes. */
891 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU) || defined(TARGET_ANGSTROM)
892 if (endswith(name, ".sh.service"))
897 if (startswith(name, "boot."))
901 #ifdef TARGET_FRUGALWARE
902 if (startswith(name, "rc."))
906 STRV_FOREACH(p, s->meta.manager->lookup_paths.sysvinit_path) {
910 path = join(*p, "/", name, NULL);
914 assert(endswith(path, ".service"));
915 path[strlen(path)-8] = 0;
917 r = service_load_sysv_path(s, path);
919 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU) || defined(TARGET_ANGSTROM)
920 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
921 /* Try Debian style *.sh source'able init scripts */
923 r = service_load_sysv_path(s, path);
929 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
930 /* Try SUSE style boot.* init scripts */
932 path = join(*p, "/boot.", name, NULL);
936 /* Drop .service suffix */
937 path[strlen(path)-8] = 0;
938 r = service_load_sysv_path(s, path);
943 #ifdef TARGET_FRUGALWARE
944 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
945 /* Try Frugalware style rc.* init scripts */
947 path = join(*p, "/rc.", name, NULL);
951 /* Drop .service suffix */
952 path[strlen(path)-8] = 0;
953 r = service_load_sysv_path(s, path);
961 if ((s->meta.load_state != UNIT_STUB))
968 static int service_load_sysv(Service *s) {
975 /* Load service data from SysV init scripts, preferably with
978 if (strv_isempty(s->meta.manager->lookup_paths.sysvinit_path))
981 if ((t = s->meta.id))
982 if ((r = service_load_sysv_name(s, t)) < 0)
985 if (s->meta.load_state == UNIT_STUB)
986 SET_FOREACH(t, s->meta.names, i) {
990 if ((r = service_load_sysv_name(s, t)) < 0)
993 if (s->meta.load_state != UNIT_STUB)
1001 static int fsck_fix_order(Service *s) {
1007 if (s->fsck_passno <= 0)
1010 /* For each pair of services where both have an fsck priority
1011 * we order things based on it. */
1013 LIST_FOREACH(units_by_type, other, s->meta.manager->units_by_type[UNIT_SERVICE]) {
1017 t = (Service*) other;
1022 if (t->meta.load_state != UNIT_LOADED)
1025 if (t->fsck_passno <= 0)
1028 if (t->fsck_passno < s->fsck_passno)
1030 else if (t->fsck_passno > s->fsck_passno)
1035 if ((r = unit_add_dependency(UNIT(s), d, UNIT(t), true)) < 0)
1042 static int service_verify(Service *s) {
1045 if (s->meta.load_state != UNIT_LOADED)
1048 if (!s->exec_command[SERVICE_EXEC_START]) {
1049 log_error("%s lacks ExecStart setting. Refusing.", s->meta.id);
1053 if (s->type != SERVICE_ONESHOT &&
1054 s->exec_command[SERVICE_EXEC_START]->command_next) {
1055 log_error("%s has more than one ExecStart setting, which is only allowed for Type=oneshot services. Refusing.", s->meta.id);
1059 if (s->type == SERVICE_ONESHOT &&
1060 s->exec_command[SERVICE_EXEC_RELOAD]) {
1061 log_error("%s has an ExecReload setting, which is not allowed for Type=oneshot services. Refusing.", s->meta.id);
1065 if (s->type == SERVICE_DBUS && !s->bus_name) {
1066 log_error("%s is of type D-Bus but no D-Bus service name has been specified. Refusing.", s->meta.id);
1070 if (s->exec_context.pam_name && s->exec_context.kill_mode != KILL_CONTROL_GROUP) {
1071 log_error("%s has PAM enabled. Kill mode must be set to 'control-group'. Refusing.", s->meta.id);
1078 static int service_add_default_dependencies(Service *s) {
1083 /* Add a number of automatic dependencies useful for the
1084 * majority of services. */
1086 /* First, pull in base system */
1087 if (s->meta.manager->running_as == MANAGER_SYSTEM) {
1089 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_BASIC_TARGET, NULL, true)) < 0)
1092 } else if (s->meta.manager->running_as == MANAGER_USER) {
1094 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SOCKETS_TARGET, NULL, true)) < 0)
1098 /* Second, activate normal shutdown */
1099 return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true);
1102 static void service_fix_output(Service *s) {
1105 /* If nothing has been explicitly configured, patch default
1106 * output in. If input is socket/tty we avoid this however,
1107 * since in that case we want output to default to the same
1108 * place as we read input from. */
1110 if (s->exec_context.std_error == EXEC_OUTPUT_INHERIT &&
1111 s->exec_context.std_output == EXEC_OUTPUT_INHERIT &&
1112 s->exec_context.std_input == EXEC_INPUT_NULL)
1113 s->exec_context.std_error = s->meta.manager->default_std_error;
1115 if (s->exec_context.std_output == EXEC_OUTPUT_INHERIT &&
1116 s->exec_context.std_input == EXEC_INPUT_NULL)
1117 s->exec_context.std_output = s->meta.manager->default_std_output;
1120 static int service_load(Unit *u) {
1122 Service *s = SERVICE(u);
1126 /* Load a .service file */
1127 if ((r = unit_load_fragment(u)) < 0)
1130 #ifdef HAVE_SYSV_COMPAT
1131 /* Load a classic init script as a fallback, if we couldn't find anything */
1132 if (u->meta.load_state == UNIT_STUB)
1133 if ((r = service_load_sysv(s)) < 0)
1137 /* Still nothing found? Then let's give up */
1138 if (u->meta.load_state == UNIT_STUB)
1141 /* We were able to load something, then let's add in the
1142 * dropin directories. */
1143 if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
1146 /* This is a new unit? Then let's add in some extras */
1147 if (u->meta.load_state == UNIT_LOADED) {
1148 if ((r = unit_add_exec_dependencies(u, &s->exec_context)) < 0)
1151 if ((r = unit_add_default_cgroups(u)) < 0)
1154 #ifdef HAVE_SYSV_COMPAT
1155 if ((r = sysv_fix_order(s)) < 0)
1159 if ((r = fsck_fix_order(s)) < 0)
1163 if ((r = unit_watch_bus_name(u, s->bus_name)) < 0)
1166 if (s->type == SERVICE_NOTIFY && s->notify_access == NOTIFY_NONE)
1167 s->notify_access = NOTIFY_MAIN;
1169 if (s->type == SERVICE_DBUS || s->bus_name)
1170 if ((r = unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_REQUIRES, SPECIAL_DBUS_SOCKET, NULL, true)) < 0)
1173 if (s->meta.default_dependencies)
1174 if ((r = service_add_default_dependencies(s)) < 0)
1177 service_fix_output(s);
1180 return service_verify(s);
1183 static void service_dump(Unit *u, FILE *f, const char *prefix) {
1185 ServiceExecCommand c;
1186 Service *s = SERVICE(u);
1187 const char *prefix2;
1192 p2 = strappend(prefix, "\t");
1193 prefix2 = p2 ? p2 : prefix;
1196 "%sService State: %s\n"
1197 "%sPermissionsStartOnly: %s\n"
1198 "%sRootDirectoryStartOnly: %s\n"
1199 "%sRemainAfterExit: %s\n"
1200 "%sGuessMainPID: %s\n"
1203 "%sNotifyAccess: %s\n",
1204 prefix, service_state_to_string(s->state),
1205 prefix, yes_no(s->permissions_start_only),
1206 prefix, yes_no(s->root_directory_start_only),
1207 prefix, yes_no(s->remain_after_exit),
1208 prefix, yes_no(s->guess_main_pid),
1209 prefix, service_type_to_string(s->type),
1210 prefix, service_restart_to_string(s->restart),
1211 prefix, notify_access_to_string(s->notify_access));
1213 if (s->control_pid > 0)
1215 "%sControl PID: %lu\n",
1216 prefix, (unsigned long) s->control_pid);
1218 if (s->main_pid > 0)
1221 "%sMain PID Known: %s\n"
1222 "%sMain PID Alien: %s\n",
1223 prefix, (unsigned long) s->main_pid,
1224 prefix, yes_no(s->main_pid_known),
1225 prefix, yes_no(s->main_pid_alien));
1230 prefix, s->pid_file);
1235 "%sBus Name Good: %s\n",
1236 prefix, s->bus_name,
1237 prefix, yes_no(s->bus_name_good));
1239 exec_context_dump(&s->exec_context, f, prefix);
1241 for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
1243 if (!s->exec_command[c])
1246 fprintf(f, "%s-> %s:\n",
1247 prefix, service_exec_command_to_string(c));
1249 exec_command_dump_list(s->exec_command[c], f, prefix2);
1252 #ifdef HAVE_SYSV_COMPAT
1255 "%sSysV Init Script Path: %s\n"
1256 "%sSysV Init Script has LSB Header: %s\n"
1257 "%sSysVEnabled: %s\n",
1258 prefix, s->sysv_path,
1259 prefix, yes_no(s->sysv_has_lsb),
1260 prefix, yes_no(s->sysv_enabled));
1262 if (s->sysv_start_priority >= 0)
1264 "%sSysVStartPriority: %i\n",
1265 prefix, s->sysv_start_priority);
1267 if (s->sysv_runlevels)
1268 fprintf(f, "%sSysVRunLevels: %s\n",
1269 prefix, s->sysv_runlevels);
1272 if (s->fsck_passno > 0)
1274 "%sFsckPassNo: %i\n",
1275 prefix, s->fsck_passno);
1278 fprintf(f, "%sStatus Text: %s\n",
1279 prefix, s->status_text);
1284 static int service_load_pid_file(Service *s) {
1294 if ((r = read_one_line_file(s->pid_file, &k)) < 0)
1297 r = parse_pid(k, &pid);
1303 if (kill(pid, 0) < 0 && errno != EPERM) {
1304 log_warning("PID %lu read from file %s does not exist. Your service or init script might be broken.",
1305 (unsigned long) pid, s->pid_file);
1309 if (s->main_pid_known) {
1310 if (pid == s->main_pid)
1313 log_debug("Main PID changing: %lu -> %lu",
1314 (unsigned long) s->main_pid, (unsigned long) pid);
1315 service_unwatch_main_pid(s);
1316 s->main_pid_known = false;
1319 if ((r = service_set_main_pid(s, pid)) < 0)
1322 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1323 /* FIXME: we need to do something here */
1329 static int service_search_main_pid(Service *s) {
1335 /* If we know it anyway, don't ever fallback to unreliable
1337 if (s->main_pid_known)
1340 if (!s->guess_main_pid)
1343 assert(s->main_pid <= 0);
1345 if ((pid = cgroup_bonding_search_main_pid_list(s->meta.cgroup_bondings)) <= 0)
1348 if ((r = service_set_main_pid(s, pid)) < 0)
1351 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1352 /* FIXME: we need to do something here */
1358 static int service_get_sockets(Service *s, Set **_set) {
1367 if (s->socket_fd >= 0)
1370 if (!set_isempty(s->configured_sockets))
1373 /* Collects all Socket objects that belong to this
1374 * service. Note that a service might have multiple sockets
1375 * via multiple names. */
1377 if (!(set = set_new(NULL, NULL)))
1380 SET_FOREACH(t, s->meta.names, i) {
1384 /* Look for all socket objects that go by any of our
1385 * units and collect their fds */
1387 if (!(k = unit_name_change_suffix(t, ".socket"))) {
1392 p = manager_get_unit(s->meta.manager, k);
1398 if ((r = set_put(set, p)) < 0)
1410 static int service_notify_sockets_dead(Service *s) {
1412 Set *set, *free_set = NULL;
1418 /* Notifies all our sockets when we die */
1420 if (s->socket_fd >= 0)
1423 if (!set_isempty(s->configured_sockets))
1424 set = s->configured_sockets;
1426 if ((r = service_get_sockets(s, &free_set)) < 0)
1432 SET_FOREACH(sock, set, i)
1433 socket_notify_service_dead(sock);
1440 static void service_set_state(Service *s, ServiceState state) {
1441 ServiceState old_state;
1444 old_state = s->state;
1447 if (state != SERVICE_START_PRE &&
1448 state != SERVICE_START &&
1449 state != SERVICE_START_POST &&
1450 state != SERVICE_RELOAD &&
1451 state != SERVICE_STOP &&
1452 state != SERVICE_STOP_SIGTERM &&
1453 state != SERVICE_STOP_SIGKILL &&
1454 state != SERVICE_STOP_POST &&
1455 state != SERVICE_FINAL_SIGTERM &&
1456 state != SERVICE_FINAL_SIGKILL &&
1457 state != SERVICE_AUTO_RESTART)
1458 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1460 if (state != SERVICE_START &&
1461 state != SERVICE_START_POST &&
1462 state != SERVICE_RUNNING &&
1463 state != SERVICE_RELOAD &&
1464 state != SERVICE_STOP &&
1465 state != SERVICE_STOP_SIGTERM &&
1466 state != SERVICE_STOP_SIGKILL) {
1467 service_unwatch_main_pid(s);
1468 s->main_command = NULL;
1471 if (state != SERVICE_START_PRE &&
1472 state != SERVICE_START &&
1473 state != SERVICE_START_POST &&
1474 state != SERVICE_RELOAD &&
1475 state != SERVICE_STOP &&
1476 state != SERVICE_STOP_SIGTERM &&
1477 state != SERVICE_STOP_SIGKILL &&
1478 state != SERVICE_STOP_POST &&
1479 state != SERVICE_FINAL_SIGTERM &&
1480 state != SERVICE_FINAL_SIGKILL) {
1481 service_unwatch_control_pid(s);
1482 s->control_command = NULL;
1483 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1486 if (state == SERVICE_DEAD ||
1487 state == SERVICE_STOP ||
1488 state == SERVICE_STOP_SIGTERM ||
1489 state == SERVICE_STOP_SIGKILL ||
1490 state == SERVICE_STOP_POST ||
1491 state == SERVICE_FINAL_SIGTERM ||
1492 state == SERVICE_FINAL_SIGKILL ||
1493 state == SERVICE_FAILED ||
1494 state == SERVICE_AUTO_RESTART)
1495 service_notify_sockets_dead(s);
1497 if (state != SERVICE_START_PRE &&
1498 state != SERVICE_START &&
1499 state != SERVICE_START_POST &&
1500 state != SERVICE_RUNNING &&
1501 state != SERVICE_RELOAD &&
1502 state != SERVICE_STOP &&
1503 state != SERVICE_STOP_SIGTERM &&
1504 state != SERVICE_STOP_SIGKILL &&
1505 state != SERVICE_STOP_POST &&
1506 state != SERVICE_FINAL_SIGTERM &&
1507 state != SERVICE_FINAL_SIGKILL &&
1508 !(state == SERVICE_DEAD && s->meta.job)) {
1509 service_close_socket_fd(s);
1510 service_connection_unref(s);
1513 /* For the inactive states unit_notify() will trim the cgroup,
1514 * but for exit we have to do that ourselves... */
1515 if (state == SERVICE_EXITED && s->meta.manager->n_reloading <= 0)
1516 cgroup_bonding_trim_list(s->meta.cgroup_bondings, true);
1518 if (old_state != state)
1519 log_debug("%s changed %s -> %s", s->meta.id, service_state_to_string(old_state), service_state_to_string(state));
1521 unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state], !s->reload_failure);
1522 s->reload_failure = false;
1525 static int service_coldplug(Unit *u) {
1526 Service *s = SERVICE(u);
1530 assert(s->state == SERVICE_DEAD);
1532 if (s->deserialized_state != s->state) {
1534 if (s->deserialized_state == SERVICE_START_PRE ||
1535 s->deserialized_state == SERVICE_START ||
1536 s->deserialized_state == SERVICE_START_POST ||
1537 s->deserialized_state == SERVICE_RELOAD ||
1538 s->deserialized_state == SERVICE_STOP ||
1539 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1540 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1541 s->deserialized_state == SERVICE_STOP_POST ||
1542 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1543 s->deserialized_state == SERVICE_FINAL_SIGKILL ||
1544 s->deserialized_state == SERVICE_AUTO_RESTART) {
1546 if (s->deserialized_state == SERVICE_AUTO_RESTART || s->timeout_usec > 0) {
1549 k = s->deserialized_state == SERVICE_AUTO_RESTART ? s->restart_usec : s->timeout_usec;
1551 if ((r = unit_watch_timer(UNIT(s), k, &s->timer_watch)) < 0)
1556 if ((s->deserialized_state == SERVICE_START &&
1557 (s->type == SERVICE_FORKING ||
1558 s->type == SERVICE_DBUS ||
1559 s->type == SERVICE_ONESHOT ||
1560 s->type == SERVICE_NOTIFY)) ||
1561 s->deserialized_state == SERVICE_START_POST ||
1562 s->deserialized_state == SERVICE_RUNNING ||
1563 s->deserialized_state == SERVICE_RELOAD ||
1564 s->deserialized_state == SERVICE_STOP ||
1565 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1566 s->deserialized_state == SERVICE_STOP_SIGKILL)
1567 if (s->main_pid > 0)
1568 if ((r = unit_watch_pid(UNIT(s), s->main_pid)) < 0)
1571 if (s->deserialized_state == SERVICE_START_PRE ||
1572 s->deserialized_state == SERVICE_START ||
1573 s->deserialized_state == SERVICE_START_POST ||
1574 s->deserialized_state == SERVICE_RELOAD ||
1575 s->deserialized_state == SERVICE_STOP ||
1576 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1577 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1578 s->deserialized_state == SERVICE_STOP_POST ||
1579 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1580 s->deserialized_state == SERVICE_FINAL_SIGKILL)
1581 if (s->control_pid > 0)
1582 if ((r = unit_watch_pid(UNIT(s), s->control_pid)) < 0)
1585 service_set_state(s, s->deserialized_state);
1591 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
1595 unsigned rn_fds = 0;
1596 Set *set, *free_set = NULL;
1603 if (s->socket_fd >= 0)
1606 if (!set_isempty(s->configured_sockets))
1607 set = s->configured_sockets;
1609 if ((r = service_get_sockets(s, &free_set)) < 0)
1615 SET_FOREACH(sock, set, i) {
1619 if ((r = socket_collect_fds(sock, &cfds, &cn_fds)) < 0)
1631 if (!(t = new(int, rn_fds+cn_fds))) {
1637 memcpy(t, rfds, rn_fds * sizeof(int));
1638 memcpy(t+rn_fds, cfds, cn_fds * sizeof(int));
1643 rn_fds = rn_fds+cn_fds;
1661 static int service_spawn(
1666 bool apply_permissions,
1668 bool apply_tty_stdin,
1669 bool set_notify_socket,
1674 int *fds = NULL, *fdsbuf = NULL;
1675 unsigned n_fds = 0, n_env = 0;
1676 char **argv = NULL, **final_env = NULL, **our_env = NULL;
1683 s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1684 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1685 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
1687 if (s->socket_fd >= 0) {
1688 fds = &s->socket_fd;
1691 if ((r = service_collect_fds(s, &fdsbuf, &n_fds)) < 0)
1698 if (timeout && s->timeout_usec) {
1699 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1702 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1704 if (!(argv = unit_full_printf_strv(UNIT(s), c->argv))) {
1709 if (!(our_env = new0(char*, 4))) {
1714 if (set_notify_socket)
1715 if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=%s", s->meta.manager->notify_socket) < 0) {
1720 if (s->main_pid > 0)
1721 if (asprintf(our_env + n_env++, "MAINPID=%lu", (unsigned long) s->main_pid) < 0) {
1726 if (!(final_env = strv_env_merge(2,
1727 s->meta.manager->environment,
1742 s->meta.manager->confirm_spawn,
1743 s->meta.cgroup_bondings,
1744 s->meta.cgroup_attributes,
1751 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1752 /* FIXME: we need to do something here */
1758 strv_free(final_env);
1768 strv_free(final_env);
1771 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1776 static int main_pid_good(Service *s) {
1779 /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1782 /* If we know the pid file, then lets just check if it is
1784 if (s->main_pid_known) {
1786 /* If it's an alien child let's check if it is still
1788 if (s->main_pid_alien)
1789 return kill(s->main_pid, 0) >= 0 || errno != ESRCH;
1791 /* .. otherwise assume we'll get a SIGCHLD for it,
1792 * which we really should wait for to collect exit
1793 * status and code */
1794 return s->main_pid > 0;
1797 /* We don't know the pid */
1801 static int control_pid_good(Service *s) {
1804 return s->control_pid > 0;
1807 static int cgroup_good(Service *s) {
1812 if ((r = cgroup_bonding_is_empty_list(s->meta.cgroup_bondings)) < 0)
1818 static void service_enter_dead(Service *s, bool success, bool allow_restart) {
1825 if (allow_restart &&
1826 !s->forbid_restart &&
1827 (s->restart == SERVICE_RESTART_ALWAYS ||
1828 (s->restart == SERVICE_RESTART_ON_SUCCESS && !s->failure) ||
1829 (s->restart == SERVICE_RESTART_ON_FAILURE && s->failure) ||
1830 (s->restart == SERVICE_RESTART_ON_ABORT && s->failure &&
1831 (s->main_exec_status.code == CLD_KILLED ||
1832 s->main_exec_status.code == CLD_DUMPED)))) {
1834 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
1837 service_set_state(s, SERVICE_AUTO_RESTART);
1839 service_set_state(s, s->failure ? SERVICE_FAILED : SERVICE_DEAD);
1841 s->forbid_restart = false;
1846 log_warning("%s failed to run install restart timer: %s", s->meta.id, strerror(-r));
1847 service_enter_dead(s, false, false);
1850 static void service_enter_signal(Service *s, ServiceState state, bool success);
1852 static void service_enter_stop_post(Service *s, bool success) {
1859 service_unwatch_control_pid(s);
1861 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST])) {
1862 s->control_command_id = SERVICE_EXEC_STOP_POST;
1864 if ((r = service_spawn(s,
1868 !s->permissions_start_only,
1869 !s->root_directory_start_only,
1872 &s->control_pid)) < 0)
1876 service_set_state(s, SERVICE_STOP_POST);
1878 service_enter_signal(s, SERVICE_FINAL_SIGTERM, true);
1883 log_warning("%s failed to run 'stop-post' task: %s", s->meta.id, strerror(-r));
1884 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1887 static void service_enter_signal(Service *s, ServiceState state, bool success) {
1889 Set *pid_set = NULL;
1890 bool wait_for_exit = false;
1897 if (s->exec_context.kill_mode != KILL_NONE) {
1898 int sig = (state == SERVICE_STOP_SIGTERM || state == SERVICE_FINAL_SIGTERM) ? s->exec_context.kill_signal : SIGKILL;
1900 if (s->main_pid > 0) {
1901 if (kill_and_sigcont(s->main_pid, sig) < 0 && errno != ESRCH)
1902 log_warning("Failed to kill main process %li: %m", (long) s->main_pid);
1904 wait_for_exit = !s->main_pid_alien;
1907 if (s->control_pid > 0) {
1908 if (kill_and_sigcont(s->control_pid, sig) < 0 && errno != ESRCH)
1909 log_warning("Failed to kill control process %li: %m", (long) s->control_pid);
1911 wait_for_exit = true;
1914 if (s->exec_context.kill_mode == KILL_CONTROL_GROUP) {
1916 if (!(pid_set = set_new(trivial_hash_func, trivial_compare_func))) {
1921 /* Exclude the main/control pids from being killed via the cgroup */
1922 if (s->main_pid > 0)
1923 if ((r = set_put(pid_set, LONG_TO_PTR(s->main_pid))) < 0)
1926 if (s->control_pid > 0)
1927 if ((r = set_put(pid_set, LONG_TO_PTR(s->control_pid))) < 0)
1930 if ((r = cgroup_bonding_kill_list(s->meta.cgroup_bondings, sig, true, pid_set)) < 0) {
1931 if (r != -EAGAIN && r != -ESRCH && r != -ENOENT)
1932 log_warning("Failed to kill control group: %s", strerror(-r));
1934 wait_for_exit = true;
1941 if (wait_for_exit) {
1942 if (s->timeout_usec > 0)
1943 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1946 service_set_state(s, state);
1947 } else if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1948 service_enter_stop_post(s, true);
1950 service_enter_dead(s, true, true);
1955 log_warning("%s failed to kill processes: %s", s->meta.id, strerror(-r));
1957 if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1958 service_enter_stop_post(s, false);
1960 service_enter_dead(s, false, true);
1966 static void service_enter_stop(Service *s, bool success) {
1974 service_unwatch_control_pid(s);
1976 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP])) {
1977 s->control_command_id = SERVICE_EXEC_STOP;
1979 if ((r = service_spawn(s,
1983 !s->permissions_start_only,
1984 !s->root_directory_start_only,
1987 &s->control_pid)) < 0)
1990 service_set_state(s, SERVICE_STOP);
1992 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
1997 log_warning("%s failed to run 'stop' task: %s", s->meta.id, strerror(-r));
1998 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
2001 static void service_enter_running(Service *s, bool success) {
2002 int main_pid_ok, cgroup_ok;
2008 main_pid_ok = main_pid_good(s);
2009 cgroup_ok = cgroup_good(s);
2011 if ((main_pid_ok > 0 || (main_pid_ok < 0 && cgroup_ok != 0)) &&
2012 (s->bus_name_good || s->type != SERVICE_DBUS))
2013 service_set_state(s, SERVICE_RUNNING);
2014 else if (s->remain_after_exit)
2015 service_set_state(s, SERVICE_EXITED);
2017 service_enter_stop(s, true);
2020 static void service_enter_start_post(Service *s) {
2024 service_unwatch_control_pid(s);
2026 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_POST])) {
2027 s->control_command_id = SERVICE_EXEC_START_POST;
2029 if ((r = service_spawn(s,
2033 !s->permissions_start_only,
2034 !s->root_directory_start_only,
2037 &s->control_pid)) < 0)
2040 service_set_state(s, SERVICE_START_POST);
2042 service_enter_running(s, true);
2047 log_warning("%s failed to run 'start-post' task: %s", s->meta.id, strerror(-r));
2048 service_enter_stop(s, false);
2051 static void service_enter_start(Service *s) {
2058 assert(s->exec_command[SERVICE_EXEC_START]);
2059 assert(!s->exec_command[SERVICE_EXEC_START]->command_next || s->type == SERVICE_ONESHOT);
2061 if (s->type == SERVICE_FORKING)
2062 service_unwatch_control_pid(s);
2064 service_unwatch_main_pid(s);
2066 if (s->type == SERVICE_FORKING) {
2067 s->control_command_id = SERVICE_EXEC_START;
2068 c = s->control_command = s->exec_command[SERVICE_EXEC_START];
2070 s->main_command = NULL;
2072 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2073 s->control_command = NULL;
2075 c = s->main_command = s->exec_command[SERVICE_EXEC_START];
2078 if ((r = service_spawn(s,
2080 s->type == SERVICE_FORKING || s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY,
2085 s->notify_access != NOTIFY_NONE,
2089 if (s->type == SERVICE_SIMPLE) {
2090 /* For simple services we immediately start
2091 * the START_POST binaries. */
2093 service_set_main_pid(s, pid);
2094 service_enter_start_post(s);
2096 } else if (s->type == SERVICE_FORKING) {
2098 /* For forking services we wait until the start
2099 * process exited. */
2101 s->control_pid = pid;
2102 service_set_state(s, SERVICE_START);
2104 } else if (s->type == SERVICE_ONESHOT ||
2105 s->type == SERVICE_DBUS ||
2106 s->type == SERVICE_NOTIFY) {
2108 /* For oneshot services we wait until the start
2109 * process exited, too, but it is our main process. */
2111 /* For D-Bus services we know the main pid right away,
2112 * but wait for the bus name to appear on the
2113 * bus. Notify services are similar. */
2115 service_set_main_pid(s, pid);
2116 service_set_state(s, SERVICE_START);
2118 assert_not_reached("Unknown service type");
2123 log_warning("%s failed to run 'start' task: %s", s->meta.id, strerror(-r));
2124 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2127 static void service_enter_start_pre(Service *s) {
2132 service_unwatch_control_pid(s);
2134 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_PRE])) {
2135 s->control_command_id = SERVICE_EXEC_START_PRE;
2137 if ((r = service_spawn(s,
2141 !s->permissions_start_only,
2142 !s->root_directory_start_only,
2145 &s->control_pid)) < 0)
2148 service_set_state(s, SERVICE_START_PRE);
2150 service_enter_start(s);
2155 log_warning("%s failed to run 'start-pre' task: %s", s->meta.id, strerror(-r));
2156 service_enter_dead(s, false, true);
2159 static void service_enter_restart(Service *s) {
2164 dbus_error_init(&error);
2167 log_info("Job pending for unit, delaying automatic restart.");
2169 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
2173 service_enter_dead(s, true, false);
2175 if ((r = manager_add_job(s->meta.manager, JOB_START, UNIT(s), JOB_FAIL, false, &error, NULL)) < 0)
2178 log_debug("%s scheduled restart job.", s->meta.id);
2182 log_warning("%s failed to schedule restart job: %s", s->meta.id, bus_error(&error, -r));
2183 service_enter_dead(s, false, false);
2185 dbus_error_free(&error);
2188 static void service_enter_reload(Service *s) {
2193 service_unwatch_control_pid(s);
2195 if ((s->control_command = s->exec_command[SERVICE_EXEC_RELOAD])) {
2196 s->control_command_id = SERVICE_EXEC_RELOAD;
2198 if ((r = service_spawn(s,
2202 !s->permissions_start_only,
2203 !s->root_directory_start_only,
2206 &s->control_pid)) < 0)
2209 service_set_state(s, SERVICE_RELOAD);
2211 service_enter_running(s, true);
2216 log_warning("%s failed to run 'reload' task: %s", s->meta.id, strerror(-r));
2217 s->reload_failure = true;
2218 service_enter_running(s, true);
2221 static void service_run_next_control(Service *s, bool success) {
2225 assert(s->control_command);
2226 assert(s->control_command->command_next);
2231 assert(s->control_command_id != SERVICE_EXEC_START);
2233 s->control_command = s->control_command->command_next;
2234 service_unwatch_control_pid(s);
2236 if ((r = service_spawn(s,
2240 !s->permissions_start_only,
2241 !s->root_directory_start_only,
2242 s->control_command_id == SERVICE_EXEC_START_PRE ||
2243 s->control_command_id == SERVICE_EXEC_STOP_POST,
2245 &s->control_pid)) < 0)
2251 log_warning("%s failed to run next control task: %s", s->meta.id, strerror(-r));
2253 if (s->state == SERVICE_START_PRE)
2254 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2255 else if (s->state == SERVICE_STOP)
2256 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
2257 else if (s->state == SERVICE_STOP_POST)
2258 service_enter_dead(s, false, true);
2259 else if (s->state == SERVICE_RELOAD) {
2260 s->reload_failure = true;
2261 service_enter_running(s, true);
2263 service_enter_stop(s, false);
2266 static void service_run_next_main(Service *s, bool success) {
2271 assert(s->main_command);
2272 assert(s->main_command->command_next);
2273 assert(s->type == SERVICE_ONESHOT);
2278 s->main_command = s->main_command->command_next;
2279 service_unwatch_main_pid(s);
2281 if ((r = service_spawn(s,
2288 s->notify_access != NOTIFY_NONE,
2292 service_set_main_pid(s, pid);
2297 log_warning("%s failed to run next main task: %s", s->meta.id, strerror(-r));
2298 service_enter_stop(s, false);
2301 static int service_start(Unit *u) {
2302 Service *s = SERVICE(u);
2306 /* We cannot fulfill this request right now, try again later
2308 if (s->state == SERVICE_STOP ||
2309 s->state == SERVICE_STOP_SIGTERM ||
2310 s->state == SERVICE_STOP_SIGKILL ||
2311 s->state == SERVICE_STOP_POST ||
2312 s->state == SERVICE_FINAL_SIGTERM ||
2313 s->state == SERVICE_FINAL_SIGKILL)
2316 /* Already on it! */
2317 if (s->state == SERVICE_START_PRE ||
2318 s->state == SERVICE_START ||
2319 s->state == SERVICE_START_POST)
2322 assert(s->state == SERVICE_DEAD || s->state == SERVICE_FAILED || s->state == SERVICE_AUTO_RESTART);
2324 /* Make sure we don't enter a busy loop of some kind. */
2325 if (!ratelimit_test(&s->ratelimit)) {
2326 log_warning("%s start request repeated too quickly, refusing to start.", u->meta.id);
2331 s->main_pid_known = false;
2332 s->main_pid_alien = false;
2333 s->forbid_restart = false;
2335 service_enter_start_pre(s);
2339 static int service_stop(Unit *u) {
2340 Service *s = SERVICE(u);
2344 /* This is a user request, so don't do restarts on this
2346 s->forbid_restart = true;
2349 if (s->state == SERVICE_STOP ||
2350 s->state == SERVICE_STOP_SIGTERM ||
2351 s->state == SERVICE_STOP_SIGKILL ||
2352 s->state == SERVICE_STOP_POST ||
2353 s->state == SERVICE_FINAL_SIGTERM ||
2354 s->state == SERVICE_FINAL_SIGKILL)
2357 /* Don't allow a restart */
2358 if (s->state == SERVICE_AUTO_RESTART) {
2359 service_set_state(s, SERVICE_DEAD);
2363 /* If there's already something running we go directly into
2365 if (s->state == SERVICE_START_PRE ||
2366 s->state == SERVICE_START ||
2367 s->state == SERVICE_START_POST ||
2368 s->state == SERVICE_RELOAD) {
2369 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
2373 assert(s->state == SERVICE_RUNNING ||
2374 s->state == SERVICE_EXITED);
2376 service_enter_stop(s, true);
2380 static int service_reload(Unit *u) {
2381 Service *s = SERVICE(u);
2385 assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
2387 service_enter_reload(s);
2391 static bool service_can_reload(Unit *u) {
2392 Service *s = SERVICE(u);
2396 return !!s->exec_command[SERVICE_EXEC_RELOAD];
2399 static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
2400 Service *s = SERVICE(u);
2406 unit_serialize_item(u, f, "state", service_state_to_string(s->state));
2407 unit_serialize_item(u, f, "failure", yes_no(s->failure));
2409 if (s->control_pid > 0)
2410 unit_serialize_item_format(u, f, "control-pid", "%lu", (unsigned long) s->control_pid);
2412 if (s->main_pid_known && s->main_pid > 0)
2413 unit_serialize_item_format(u, f, "main-pid", "%lu", (unsigned long) s->main_pid);
2415 unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
2418 unit_serialize_item(u, f, "status-text", s->status_text);
2420 /* There's a minor uncleanliness here: if there are multiple
2421 * commands attached here, we will start from the first one
2423 if (s->control_command_id >= 0)
2424 unit_serialize_item(u, f, "control-command", service_exec_command_to_string(s->control_command_id));
2426 if (s->socket_fd >= 0) {
2429 if ((copy = fdset_put_dup(fds, s->socket_fd)) < 0)
2432 unit_serialize_item_format(u, f, "socket-fd", "%i", copy);
2435 if (s->main_exec_status.pid > 0) {
2436 unit_serialize_item_format(u, f, "main-exec-status-pid", "%lu", (unsigned long) s->main_exec_status.pid);
2437 dual_timestamp_serialize(f, "main-exec-status-start", &s->main_exec_status.start_timestamp);
2438 dual_timestamp_serialize(f, "main-exec-status-exit", &s->main_exec_status.exit_timestamp);
2440 if (dual_timestamp_is_set(&s->main_exec_status.exit_timestamp)) {
2441 unit_serialize_item_format(u, f, "main-exec-status-code", "%i", s->main_exec_status.code);
2442 unit_serialize_item_format(u, f, "main-exec-status-status", "%i", s->main_exec_status.status);
2449 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
2450 Service *s = SERVICE(u);
2457 if (streq(key, "state")) {
2460 if ((state = service_state_from_string(value)) < 0)
2461 log_debug("Failed to parse state value %s", value);
2463 s->deserialized_state = state;
2464 } else if (streq(key, "failure")) {
2467 if ((b = parse_boolean(value)) < 0)
2468 log_debug("Failed to parse failure value %s", value);
2470 s->failure = b || s->failure;
2471 } else if (streq(key, "control-pid")) {
2474 if (parse_pid(value, &pid) < 0)
2475 log_debug("Failed to parse control-pid value %s", value);
2477 s->control_pid = pid;
2478 } else if (streq(key, "main-pid")) {
2481 if (parse_pid(value, &pid) < 0)
2482 log_debug("Failed to parse main-pid value %s", value);
2484 service_set_main_pid(s, (pid_t) pid);
2485 } else if (streq(key, "main-pid-known")) {
2488 if ((b = parse_boolean(value)) < 0)
2489 log_debug("Failed to parse main-pid-known value %s", value);
2491 s->main_pid_known = b;
2492 } else if (streq(key, "status-text")) {
2495 if ((t = strdup(value))) {
2496 free(s->status_text);
2500 } else if (streq(key, "control-command")) {
2501 ServiceExecCommand id;
2503 if ((id = service_exec_command_from_string(value)) < 0)
2504 log_debug("Failed to parse exec-command value %s", value);
2506 s->control_command_id = id;
2507 s->control_command = s->exec_command[id];
2509 } else if (streq(key, "socket-fd")) {
2512 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2513 log_debug("Failed to parse socket-fd value %s", value);
2516 if (s->socket_fd >= 0)
2517 close_nointr_nofail(s->socket_fd);
2518 s->socket_fd = fdset_remove(fds, fd);
2520 } else if (streq(key, "main-exec-status-pid")) {
2523 if (parse_pid(value, &pid) < 0)
2524 log_debug("Failed to parse main-exec-status-pid value %s", value);
2526 s->main_exec_status.pid = pid;
2527 } else if (streq(key, "main-exec-status-code")) {
2530 if (safe_atoi(value, &i) < 0)
2531 log_debug("Failed to parse main-exec-status-code value %s", value);
2533 s->main_exec_status.code = i;
2534 } else if (streq(key, "main-exec-status-status")) {
2537 if (safe_atoi(value, &i) < 0)
2538 log_debug("Failed to parse main-exec-status-status value %s", value);
2540 s->main_exec_status.status = i;
2541 } else if (streq(key, "main-exec-status-start"))
2542 dual_timestamp_deserialize(value, &s->main_exec_status.start_timestamp);
2543 else if (streq(key, "main-exec-status-exit"))
2544 dual_timestamp_deserialize(value, &s->main_exec_status.exit_timestamp);
2546 log_debug("Unknown serialization key '%s'", key);
2551 static UnitActiveState service_active_state(Unit *u) {
2554 return state_translation_table[SERVICE(u)->state];
2557 static const char *service_sub_state_to_string(Unit *u) {
2560 return service_state_to_string(SERVICE(u)->state);
2563 static bool service_check_gc(Unit *u) {
2564 Service *s = SERVICE(u);
2568 /* Never clean up services that still have a process around,
2569 * even if the service is formally dead. */
2570 if (cgroup_good(s) > 0 ||
2571 main_pid_good(s) > 0 ||
2572 control_pid_good(s) > 0)
2575 #ifdef HAVE_SYSV_COMPAT
2583 static bool service_check_snapshot(Unit *u) {
2584 Service *s = SERVICE(u);
2588 return !s->got_socket_fd;
2591 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2592 Service *s = SERVICE(u);
2598 if (!s->meta.fragment_path)
2599 success = is_clean_exit_lsb(code, status);
2601 success = is_clean_exit(code, status);
2603 if (s->main_pid == pid) {
2604 /* Forking services may occasionally move to a new PID.
2605 * As long as they update the PID file before exiting the old
2606 * PID, they're fine. */
2607 if (service_load_pid_file(s) == 0)
2611 exec_status_exit(&s->main_exec_status, &s->exec_context, pid, code, status);
2613 /* If this is not a forking service than the main
2614 * process got started and hence we copy the exit
2615 * status so that it is recorded both as main and as
2616 * control process exit status */
2617 if (s->main_command) {
2618 s->main_command->exec_status = s->main_exec_status;
2620 if (s->main_command->ignore)
2624 log_full(success ? LOG_DEBUG : LOG_NOTICE,
2625 "%s: main process exited, code=%s, status=%i", u->meta.id, sigchld_code_to_string(code), status);
2626 s->failure = s->failure || !success;
2628 if (s->main_command &&
2629 s->main_command->command_next &&
2632 /* There is another command to *
2633 * execute, so let's do that. */
2635 log_debug("%s running next main command for state %s", u->meta.id, service_state_to_string(s->state));
2636 service_run_next_main(s, success);
2640 /* The service exited, so the service is officially
2642 s->main_command = NULL;
2646 case SERVICE_START_POST:
2647 case SERVICE_RELOAD:
2649 /* Need to wait until the operation is
2654 if (s->type == SERVICE_ONESHOT) {
2655 /* This was our main goal, so let's go on */
2657 service_enter_start_post(s);
2659 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2662 assert(s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY);
2667 case SERVICE_RUNNING:
2668 service_enter_running(s, success);
2671 case SERVICE_STOP_SIGTERM:
2672 case SERVICE_STOP_SIGKILL:
2674 if (!control_pid_good(s))
2675 service_enter_stop_post(s, success);
2677 /* If there is still a control process, wait for that first */
2681 assert_not_reached("Uh, main process died at wrong time.");
2685 } else if (s->control_pid == pid) {
2689 if (s->control_command) {
2690 exec_status_exit(&s->control_command->exec_status, &s->exec_context, pid, code, status);
2692 if (s->control_command->ignore)
2696 log_full(success ? LOG_DEBUG : LOG_NOTICE,
2697 "%s: control process exited, code=%s status=%i", u->meta.id, sigchld_code_to_string(code), status);
2698 s->failure = s->failure || !success;
2700 if (s->control_command &&
2701 s->control_command->command_next &&
2704 /* There is another command to *
2705 * execute, so let's do that. */
2707 log_debug("%s running next control command for state %s", u->meta.id, service_state_to_string(s->state));
2708 service_run_next_control(s, success);
2711 /* No further commands for this step, so let's
2712 * figure out what to do next */
2714 s->control_command = NULL;
2715 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2717 log_debug("%s got final SIGCHLD for state %s", u->meta.id, service_state_to_string(s->state));
2721 case SERVICE_START_PRE:
2723 service_enter_start(s);
2725 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2729 assert(s->type == SERVICE_FORKING);
2731 /* Let's try to load the pid
2732 * file here if we can. We
2733 * ignore the return value,
2734 * since the PID file might
2735 * actually be created by a
2736 * START_POST script */
2739 service_load_pid_file(s);
2740 service_search_main_pid(s);
2742 service_enter_start_post(s);
2744 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2748 case SERVICE_START_POST:
2750 service_load_pid_file(s);
2751 service_search_main_pid(s);
2754 s->reload_failure = !success;
2755 service_enter_running(s, true);
2758 case SERVICE_RELOAD:
2760 service_load_pid_file(s);
2761 service_search_main_pid(s);
2764 s->reload_failure = !success;
2765 service_enter_running(s, true);
2769 service_enter_signal(s, SERVICE_STOP_SIGTERM, success);
2772 case SERVICE_STOP_SIGTERM:
2773 case SERVICE_STOP_SIGKILL:
2774 if (main_pid_good(s) <= 0)
2775 service_enter_stop_post(s, success);
2777 /* If there is still a service
2778 * process around, wait until
2779 * that one quit, too */
2782 case SERVICE_STOP_POST:
2783 case SERVICE_FINAL_SIGTERM:
2784 case SERVICE_FINAL_SIGKILL:
2785 service_enter_dead(s, success, true);
2789 assert_not_reached("Uh, control process died at wrong time.");
2794 /* Notify clients about changed exit status */
2795 unit_add_to_dbus_queue(u);
2798 static void service_timer_event(Unit *u, uint64_t elapsed, Watch* w) {
2799 Service *s = SERVICE(u);
2802 assert(elapsed == 1);
2804 assert(w == &s->timer_watch);
2808 case SERVICE_START_PRE:
2810 log_warning("%s operation timed out. Terminating.", u->meta.id);
2811 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2814 case SERVICE_START_POST:
2815 log_warning("%s operation timed out. Stopping.", u->meta.id);
2816 service_enter_stop(s, false);
2819 case SERVICE_RELOAD:
2820 log_warning("%s operation timed out. Stopping.", u->meta.id);
2821 s->reload_failure = true;
2822 service_enter_running(s, true);
2826 log_warning("%s stopping timed out. Terminating.", u->meta.id);
2827 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
2830 case SERVICE_STOP_SIGTERM:
2831 if (s->exec_context.send_sigkill) {
2832 log_warning("%s stopping timed out. Killing.", u->meta.id);
2833 service_enter_signal(s, SERVICE_STOP_SIGKILL, false);
2835 log_warning("%s stopping timed out. Skipping SIGKILL.", u->meta.id);
2836 service_enter_stop_post(s, false);
2841 case SERVICE_STOP_SIGKILL:
2842 /* Uh, we sent a SIGKILL and it is still not gone?
2843 * Must be something we cannot kill, so let's just be
2844 * weirded out and continue */
2846 log_warning("%s still around after SIGKILL. Ignoring.", u->meta.id);
2847 service_enter_stop_post(s, false);
2850 case SERVICE_STOP_POST:
2851 log_warning("%s stopping timed out (2). Terminating.", u->meta.id);
2852 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2855 case SERVICE_FINAL_SIGTERM:
2856 if (s->exec_context.send_sigkill) {
2857 log_warning("%s stopping timed out (2). Killing.", u->meta.id);
2858 service_enter_signal(s, SERVICE_FINAL_SIGKILL, false);
2860 log_warning("%s stopping timed out (2). Skipping SIGKILL. Entering failed mode.", u->meta.id);
2861 service_enter_dead(s, false, true);
2866 case SERVICE_FINAL_SIGKILL:
2867 log_warning("%s still around after SIGKILL (2). Entering failed mode.", u->meta.id);
2868 service_enter_dead(s, false, true);
2871 case SERVICE_AUTO_RESTART:
2872 log_info("%s holdoff time over, scheduling restart.", u->meta.id);
2873 service_enter_restart(s);
2877 assert_not_reached("Timeout at wrong time.");
2881 static void service_cgroup_notify_event(Unit *u) {
2882 Service *s = SERVICE(u);
2886 log_debug("%s: cgroup is empty", u->meta.id);
2890 /* Waiting for SIGCHLD is usually more interesting,
2891 * because it includes return codes/signals. Which is
2892 * why we ignore the cgroup events for most cases,
2893 * except when we don't know pid which to expect the
2896 case SERVICE_RUNNING:
2897 service_enter_running(s, true);
2900 case SERVICE_STOP_SIGTERM:
2901 case SERVICE_STOP_SIGKILL:
2903 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2904 service_enter_stop_post(s, true);
2908 case SERVICE_FINAL_SIGTERM:
2909 case SERVICE_FINAL_SIGKILL:
2910 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2911 service_enter_dead(s, true, true);
2920 static void service_notify_message(Unit *u, pid_t pid, char **tags) {
2921 Service *s = SERVICE(u);
2926 if (s->notify_access == NOTIFY_NONE) {
2927 log_warning("%s: Got notification message from PID %lu, but reception is disabled.",
2928 u->meta.id, (unsigned long) pid);
2932 if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
2933 log_warning("%s: Got notification message from PID %lu, but reception only permitted for PID %lu",
2934 u->meta.id, (unsigned long) pid, (unsigned long) s->main_pid);
2938 log_debug("%s: Got message", u->meta.id);
2940 /* Interpret MAINPID= */
2941 if ((e = strv_find_prefix(tags, "MAINPID=")) &&
2942 (s->state == SERVICE_START ||
2943 s->state == SERVICE_START_POST ||
2944 s->state == SERVICE_RUNNING ||
2945 s->state == SERVICE_RELOAD)) {
2947 if (parse_pid(e + 8, &pid) < 0)
2948 log_warning("Failed to parse notification message %s", e);
2950 log_debug("%s: got %s", u->meta.id, e);
2951 service_set_main_pid(s, pid);
2955 /* Interpret READY= */
2956 if (s->type == SERVICE_NOTIFY &&
2957 s->state == SERVICE_START &&
2958 strv_find(tags, "READY=1")) {
2959 log_debug("%s: got READY=1", u->meta.id);
2961 service_enter_start_post(s);
2964 /* Interpret STATUS= */
2965 if ((e = strv_find_prefix(tags, "STATUS="))) {
2969 if (!(t = strdup(e+7))) {
2970 log_error("Failed to allocate string.");
2974 log_debug("%s: got %s", u->meta.id, e);
2976 free(s->status_text);
2979 free(s->status_text);
2980 s->status_text = NULL;
2985 /* Notify clients about changed status or main pid */
2986 unit_add_to_dbus_queue(u);
2989 #ifdef HAVE_SYSV_COMPAT
2992 static void sysv_facility_in_insserv_conf(Manager *mgr) {
2996 if (!(f = fopen("/etc/insserv.conf", "re"))) {
2997 r = errno == ENOENT ? 0 : -errno;
3002 char l[LINE_MAX], *t;
3003 char **parsed = NULL;
3005 if (!fgets(l, sizeof(l), f)) {
3010 log_error("Failed to read configuration file '/etc/insserv.conf': %s", strerror(-r));
3015 if (*t != '$' && *t != '<')
3018 parsed = strv_split(t,WHITESPACE);
3019 /* we ignore <interactive>, not used, equivalent to X-Interactive */
3020 if (parsed && !startswith_no_case (parsed[0], "<interactive>")) {
3023 if (sysv_translate_facility(parsed[0], NULL, &facility) < 0)
3025 if ((u = manager_get_unit(mgr, facility)) && (u->meta.type == UNIT_TARGET)) {
3027 char *dep = NULL, *name, **j;
3029 STRV_FOREACH (j, parsed+1) {
3038 if (sysv_translate_facility(name, NULL, &dep) < 0)
3041 r = unit_add_two_dependencies_by_name(u, UNIT_BEFORE, e, dep, NULL, true);
3056 static int service_enumerate(Manager *m) {
3060 char *path = NULL, *fpath = NULL, *name = NULL;
3061 Set *runlevel_services[ELEMENTSOF(rcnd_table)], *shutdown_services = NULL;
3068 if (m->running_as != MANAGER_SYSTEM)
3071 zero(runlevel_services);
3073 STRV_FOREACH(p, m->lookup_paths.sysvrcnd_path)
3074 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++) {
3078 path = join(*p, "/", rcnd_table[i].path, NULL);
3087 if (!(d = opendir(path))) {
3088 if (errno != ENOENT)
3089 log_warning("opendir() failed on %s: %s", path, strerror(errno));
3094 while ((de = readdir(d))) {
3097 if (ignore_file(de->d_name))
3100 if (de->d_name[0] != 'S' && de->d_name[0] != 'K')
3103 if (strlen(de->d_name) < 4)
3106 a = undecchar(de->d_name[1]);
3107 b = undecchar(de->d_name[2]);
3113 fpath = join(path, "/", de->d_name, NULL);
3119 if (access(fpath, X_OK) < 0) {
3121 if (errno != ENOENT)
3122 log_warning("access() failed on %s: %s", fpath, strerror(errno));
3128 if (!(name = sysv_translate_name(de->d_name + 3))) {
3133 if ((r = manager_load_unit_prepare(m, name, NULL, NULL, &service)) < 0) {
3134 log_warning("Failed to prepare unit %s: %s", name, strerror(-r));
3138 if (de->d_name[0] == 'S') {
3140 if (rcnd_table[i].type == RUNLEVEL_UP || rcnd_table[i].type == RUNLEVEL_SYSINIT) {
3141 SERVICE(service)->sysv_start_priority_from_rcnd =
3142 MAX(a*10 + b, SERVICE(service)->sysv_start_priority_from_rcnd);
3144 SERVICE(service)->sysv_enabled = true;
3147 if ((r = set_ensure_allocated(&runlevel_services[i], trivial_hash_func, trivial_compare_func)) < 0)
3150 if ((r = set_put(runlevel_services[i], service)) < 0)
3153 } else if (de->d_name[0] == 'K' &&
3154 (rcnd_table[i].type == RUNLEVEL_DOWN ||
3155 rcnd_table[i].type == RUNLEVEL_SYSINIT)) {
3157 if ((r = set_ensure_allocated(&shutdown_services, trivial_hash_func, trivial_compare_func)) < 0)
3160 if ((r = set_put(shutdown_services, service)) < 0)
3166 /* Now we loaded all stubs and are aware of the lowest
3167 start-up priority for all services, not let's actually load
3168 the services, this will also tell us which services are
3169 actually native now */
3170 manager_dispatch_load_queue(m);
3172 /* If this is a native service, rely on native ways to pull in
3173 * a service, don't pull it in via sysv rcN.d links. */
3174 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++)
3175 SET_FOREACH(service, runlevel_services[i], j) {
3176 service = unit_follow_merge(service);
3178 if (service->meta.fragment_path)
3181 if ((r = unit_add_two_dependencies_by_name_inverse(service, UNIT_AFTER, UNIT_WANTS, rcnd_table[i].target, NULL, true)) < 0)
3185 /* We honour K links only for halt/reboot. For the normal
3186 * runlevels we assume the stop jobs will be implicitly added
3187 * by the core logic. Also, we don't really distinguish here
3188 * between the runlevels 0 and 6 and just add them to the
3189 * special shutdown target. On SUSE the boot.d/ runlevel is
3190 * also used for shutdown, so we add links for that too to the
3191 * shutdown target.*/
3192 SET_FOREACH(service, shutdown_services, j) {
3193 service = unit_follow_merge(service);
3195 if (service->meta.fragment_path)
3198 if ((r = unit_add_two_dependencies_by_name(service, UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true)) < 0)
3205 sysv_facility_in_insserv_conf (m);
3213 for (i = 0; i < ELEMENTSOF(rcnd_table); i++)
3214 set_free(runlevel_services[i]);
3215 set_free(shutdown_services);
3224 static void service_bus_name_owner_change(
3227 const char *old_owner,
3228 const char *new_owner) {
3230 Service *s = SERVICE(u);
3235 assert(streq(s->bus_name, name));
3236 assert(old_owner || new_owner);
3238 if (old_owner && new_owner)
3239 log_debug("%s's D-Bus name %s changed owner from %s to %s", u->meta.id, name, old_owner, new_owner);
3241 log_debug("%s's D-Bus name %s no longer registered by %s", u->meta.id, name, old_owner);
3243 log_debug("%s's D-Bus name %s now registered by %s", u->meta.id, name, new_owner);
3245 s->bus_name_good = !!new_owner;
3247 if (s->type == SERVICE_DBUS) {
3249 /* service_enter_running() will figure out what to
3251 if (s->state == SERVICE_RUNNING)
3252 service_enter_running(s, true);
3253 else if (s->state == SERVICE_START && new_owner)
3254 service_enter_start_post(s);
3256 } else if (new_owner &&
3258 (s->state == SERVICE_START ||
3259 s->state == SERVICE_START_POST ||
3260 s->state == SERVICE_RUNNING ||
3261 s->state == SERVICE_RELOAD)) {
3263 /* Try to acquire PID from bus service */
3264 log_debug("Trying to acquire PID from D-Bus name...");
3266 bus_query_pid(u->meta.manager, name);
3270 static void service_bus_query_pid_done(
3275 Service *s = SERVICE(u);
3280 log_debug("%s's D-Bus name %s is now owned by process %u", u->meta.id, name, (unsigned) pid);
3282 if (s->main_pid <= 0 &&
3283 (s->state == SERVICE_START ||
3284 s->state == SERVICE_START_POST ||
3285 s->state == SERVICE_RUNNING ||
3286 s->state == SERVICE_RELOAD))
3287 service_set_main_pid(s, pid);
3290 int service_set_socket_fd(Service *s, int fd, Socket *sock) {
3294 /* This is called by the socket code when instantiating a new
3295 * service for a stream socket and the socket needs to be
3298 if (s->meta.load_state != UNIT_LOADED)
3301 if (s->socket_fd >= 0)
3304 if (s->state != SERVICE_DEAD)
3308 s->got_socket_fd = true;
3309 s->accept_socket = sock;
3314 static void service_reset_failed(Unit *u) {
3315 Service *s = SERVICE(u);
3319 if (s->state == SERVICE_FAILED)
3320 service_set_state(s, SERVICE_DEAD);
3325 static bool service_need_daemon_reload(Unit *u) {
3326 Service *s = SERVICE(u);
3330 #ifdef HAVE_SYSV_COMPAT
3335 if (stat(s->sysv_path, &st) < 0)
3336 /* What, cannot access this anymore? */
3339 if (s->sysv_mtime > 0 &&
3340 timespec_load(&st.st_mtim) != s->sysv_mtime)
3348 static int service_kill(Unit *u, KillWho who, KillMode mode, int signo, DBusError *error) {
3349 Service *s = SERVICE(u);
3351 Set *pid_set = NULL;
3355 if (s->main_pid <= 0 && who == KILL_MAIN) {
3356 dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "No main process to kill");
3360 if (s->control_pid <= 0 && who == KILL_CONTROL) {
3361 dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "No control process to kill");
3365 if (who == KILL_CONTROL || who == KILL_ALL)
3366 if (s->control_pid > 0)
3367 if (kill(s->control_pid, signo) < 0)
3370 if (who == KILL_MAIN || who == KILL_ALL)
3371 if (s->main_pid > 0)
3372 if (kill(s->main_pid, signo) < 0)
3375 if (who == KILL_ALL && mode == KILL_CONTROL_GROUP) {
3378 if (!(pid_set = set_new(trivial_hash_func, trivial_compare_func)))
3381 /* Exclude the control/main pid from being killed via the cgroup */
3382 if (s->control_pid > 0)
3383 if ((q = set_put(pid_set, LONG_TO_PTR(s->control_pid))) < 0) {
3388 if (s->main_pid > 0)
3389 if ((q = set_put(pid_set, LONG_TO_PTR(s->main_pid))) < 0) {
3394 if ((q = cgroup_bonding_kill_list(s->meta.cgroup_bondings, signo, false, pid_set)) < 0)
3395 if (q != -EAGAIN && q != -ESRCH && q != -ENOENT)
3406 static const char* const service_state_table[_SERVICE_STATE_MAX] = {
3407 [SERVICE_DEAD] = "dead",
3408 [SERVICE_START_PRE] = "start-pre",
3409 [SERVICE_START] = "start",
3410 [SERVICE_START_POST] = "start-post",
3411 [SERVICE_RUNNING] = "running",
3412 [SERVICE_EXITED] = "exited",
3413 [SERVICE_RELOAD] = "reload",
3414 [SERVICE_STOP] = "stop",
3415 [SERVICE_STOP_SIGTERM] = "stop-sigterm",
3416 [SERVICE_STOP_SIGKILL] = "stop-sigkill",
3417 [SERVICE_STOP_POST] = "stop-post",
3418 [SERVICE_FINAL_SIGTERM] = "final-sigterm",
3419 [SERVICE_FINAL_SIGKILL] = "final-sigkill",
3420 [SERVICE_FAILED] = "failed",
3421 [SERVICE_AUTO_RESTART] = "auto-restart",
3424 DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
3426 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
3427 [SERVICE_RESTART_NO] = "no",
3428 [SERVICE_RESTART_ON_SUCCESS] = "on-success",
3429 [SERVICE_RESTART_ON_FAILURE] = "on-failure",
3430 [SERVICE_RESTART_ON_ABORT] = "on-abort",
3431 [SERVICE_RESTART_ALWAYS] = "always"
3434 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
3436 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
3437 [SERVICE_SIMPLE] = "simple",
3438 [SERVICE_FORKING] = "forking",
3439 [SERVICE_ONESHOT] = "oneshot",
3440 [SERVICE_DBUS] = "dbus",
3441 [SERVICE_NOTIFY] = "notify"
3444 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
3446 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
3447 [SERVICE_EXEC_START_PRE] = "ExecStartPre",
3448 [SERVICE_EXEC_START] = "ExecStart",
3449 [SERVICE_EXEC_START_POST] = "ExecStartPost",
3450 [SERVICE_EXEC_RELOAD] = "ExecReload",
3451 [SERVICE_EXEC_STOP] = "ExecStop",
3452 [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
3455 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
3457 static const char* const notify_access_table[_NOTIFY_ACCESS_MAX] = {
3458 [NOTIFY_NONE] = "none",
3459 [NOTIFY_MAIN] = "main",
3460 [NOTIFY_ALL] = "all"
3463 DEFINE_STRING_TABLE_LOOKUP(notify_access, NotifyAccess);
3465 const UnitVTable service_vtable = {
3466 .suffix = ".service",
3471 .show_status = true,
3473 .init = service_init,
3474 .done = service_done,
3475 .load = service_load,
3477 .coldplug = service_coldplug,
3479 .dump = service_dump,
3481 .start = service_start,
3482 .stop = service_stop,
3483 .reload = service_reload,
3485 .can_reload = service_can_reload,
3487 .kill = service_kill,
3489 .serialize = service_serialize,
3490 .deserialize_item = service_deserialize_item,
3492 .active_state = service_active_state,
3493 .sub_state_to_string = service_sub_state_to_string,
3495 .check_gc = service_check_gc,
3496 .check_snapshot = service_check_snapshot,
3498 .sigchld_event = service_sigchld_event,
3499 .timer_event = service_timer_event,
3501 .reset_failed = service_reset_failed,
3503 .need_daemon_reload = service_need_daemon_reload,
3505 .cgroup_notify_empty = service_cgroup_notify_event,
3506 .notify_message = service_notify_message,
3508 .bus_name_owner_change = service_bus_name_owner_change,
3509 .bus_query_pid_done = service_bus_query_pid_done,
3511 .bus_interface = "org.freedesktop.systemd1.Service",
3512 .bus_message_handler = bus_service_message_handler,
3513 .bus_invalidating_properties = bus_service_invalidating_properties,
3515 #ifdef HAVE_SYSV_COMPAT
3516 .enumerate = service_enumerate