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->load_state == UNIT_STUB);
113 s->timeout_usec = DEFAULT_TIMEOUT_USEC;
114 s->restart_usec = DEFAULT_RESTART_USEC;
116 s->watchdog_watch.type = WATCH_INVALID;
118 s->timer_watch.type = WATCH_INVALID;
119 #ifdef HAVE_SYSV_COMPAT
120 s->sysv_start_priority = -1;
121 s->sysv_start_priority_from_rcnd = -1;
124 s->guess_main_pid = true;
126 exec_context_init(&s->exec_context);
128 RATELIMIT_INIT(s->ratelimit, 10*USEC_PER_SEC, 5);
130 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
133 static void service_unwatch_control_pid(Service *s) {
136 if (s->control_pid <= 0)
139 unit_unwatch_pid(UNIT(s), s->control_pid);
143 static void service_unwatch_main_pid(Service *s) {
146 if (s->main_pid <= 0)
149 unit_unwatch_pid(UNIT(s), s->main_pid);
153 static void service_unwatch_pid_file(Service *s) {
154 if (!s->pid_file_pathspec)
157 log_debug("Stopping watch for %s's PID file %s", UNIT(s)->id, s->pid_file_pathspec->path);
158 path_spec_unwatch(s->pid_file_pathspec, UNIT(s));
159 path_spec_done(s->pid_file_pathspec);
160 free(s->pid_file_pathspec);
161 s->pid_file_pathspec = NULL;
164 static int service_set_main_pid(Service *s, pid_t pid) {
176 s->main_pid_known = true;
178 if (get_parent_of_pid(pid, &ppid) >= 0 && ppid != getpid()) {
179 log_warning("%s: Supervising process %lu which is not our child. We'll most likely not notice when it exits.",
180 UNIT(s)->id, (unsigned long) pid);
182 s->main_pid_alien = true;
184 s->main_pid_alien = false;
186 exec_status_start(&s->main_exec_status, pid);
191 static void service_close_socket_fd(Service *s) {
194 if (s->socket_fd < 0)
197 close_nointr_nofail(s->socket_fd);
201 static void service_connection_unref(Service *s) {
204 if (!UNIT_DEREF(s->accept_socket))
207 socket_connection_unref(SOCKET(UNIT_DEREF(s->accept_socket)));
208 unit_ref_unset(&s->accept_socket);
211 static void service_stop_watchdog(Service *s) {
214 unit_unwatch_timer(UNIT(s), &s->watchdog_watch);
215 s->watchdog_timestamp.realtime = 0;
216 s->watchdog_timestamp.monotonic = 0;
219 static void service_enter_dead(Service *s, ServiceResult f, bool allow_restart);
221 static void service_handle_watchdog(Service *s) {
227 if (s->watchdog_usec == 0)
230 offset = now(CLOCK_MONOTONIC) - s->watchdog_timestamp.monotonic;
231 if (offset >= s->watchdog_usec) {
232 log_error("%s watchdog timeout!", UNIT(s)->id);
233 service_enter_dead(s, SERVICE_FAILURE_WATCHDOG, true);
237 r = unit_watch_timer(UNIT(s), s->watchdog_usec - offset, &s->watchdog_watch);
239 log_warning("%s failed to install watchdog timer: %s", UNIT(s)->id, strerror(-r));
242 static void service_reset_watchdog(Service *s) {
245 dual_timestamp_get(&s->watchdog_timestamp);
246 service_handle_watchdog(s);
249 static void service_done(Unit *u) {
250 Service *s = SERVICE(u);
257 #ifdef HAVE_SYSV_COMPAT
261 free(s->sysv_runlevels);
262 s->sysv_runlevels = NULL;
265 free(s->status_text);
266 s->status_text = NULL;
268 exec_context_done(&s->exec_context);
269 exec_command_free_array(s->exec_command, _SERVICE_EXEC_COMMAND_MAX);
270 s->control_command = NULL;
271 s->main_command = NULL;
273 /* This will leak a process, but at least no memory or any of
275 service_unwatch_main_pid(s);
276 service_unwatch_control_pid(s);
277 service_unwatch_pid_file(s);
280 unit_unwatch_bus_name(u, s->bus_name);
285 service_close_socket_fd(s);
286 service_connection_unref(s);
288 unit_ref_unset(&s->accept_socket);
290 service_stop_watchdog(s);
292 unit_unwatch_timer(u, &s->timer_watch);
295 #ifdef HAVE_SYSV_COMPAT
296 static char *sysv_translate_name(const char *name) {
299 if (!(r = new(char, strlen(name) + sizeof(".service"))))
302 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU) || defined(TARGET_ANGSTROM)
303 if (endswith(name, ".sh"))
304 /* Drop Debian-style .sh suffix */
305 strcpy(stpcpy(r, name) - 3, ".service");
308 if (startswith(name, "boot."))
309 /* Drop SuSE-style boot. prefix */
310 strcpy(stpcpy(r, name + 5), ".service");
312 #ifdef TARGET_FRUGALWARE
313 if (startswith(name, "rc."))
314 /* Drop Frugalware-style rc. prefix */
315 strcpy(stpcpy(r, name + 3), ".service");
318 /* Normal init scripts */
319 strcpy(stpcpy(r, name), ".service");
324 static int sysv_translate_facility(const char *name, const char *filename, char **_r) {
326 /* We silently ignore the $ prefix here. According to the LSB
327 * spec it simply indicates whether something is a
328 * standardized name or a distribution-specific one. Since we
329 * just follow what already exists and do not introduce new
330 * uses or names we don't care who introduced a new name. */
332 static const char * const table[] = {
333 /* LSB defined facilities */
334 "local_fs", SPECIAL_LOCAL_FS_TARGET,
335 #if defined(TARGET_MANDRIVA) || defined(TARGET_MAGEIA)
337 /* Due to unfortunate name selection in Mandriva,
338 * $network is provided by network-up which is ordered
339 * after network which actually starts interfaces.
340 * To break the loop, just ignore it */
341 "network", SPECIAL_NETWORK_TARGET,
343 "named", SPECIAL_NSS_LOOKUP_TARGET,
344 "portmap", SPECIAL_RPCBIND_TARGET,
345 "remote_fs", SPECIAL_REMOTE_FS_TARGET,
346 "syslog", SPECIAL_SYSLOG_TARGET,
347 "time", SPECIAL_TIME_SYNC_TARGET,
349 /* common extensions */
350 "mail-transfer-agent", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
351 "x-display-manager", SPECIAL_DISPLAY_MANAGER_SERVICE,
354 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU) || defined(TARGET_ANGSTROM)
355 "mail-transport-agent", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
359 "MTA", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
360 "smtpdaemon", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
361 "httpd", SPECIAL_HTTP_DAEMON_TARGET,
365 "smtp", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
376 n = *name == '$' ? name + 1 : name;
378 for (i = 0; i < ELEMENTSOF(table); i += 2) {
380 if (!streq(table[i], n))
386 if (!(r = strdup(table[i+1])))
392 /* If we don't know this name, fallback heuristics to figure
393 * out whether something is a target or a service alias. */
396 if (!unit_prefix_is_valid(n))
399 /* Facilities starting with $ are most likely targets */
400 r = unit_name_build(n, NULL, ".target");
401 } else if (filename && streq(name, filename))
402 /* Names equaling the file name of the services are redundant */
405 /* Everything else we assume to be normal service names */
406 r = sysv_translate_name(n);
417 static int sysv_fix_order(Service *s) {
423 if (s->sysv_start_priority < 0)
426 /* For each pair of services where at least one lacks a LSB
427 * header, we use the start priority value to order things. */
429 LIST_FOREACH(units_by_type, other, UNIT(s)->manager->units_by_type[UNIT_SERVICE]) {
432 bool special_s, special_t;
439 if (UNIT(t)->load_state != UNIT_LOADED)
442 if (t->sysv_start_priority < 0)
445 /* If both units have modern headers we don't care
446 * about the priorities */
447 if ((UNIT(s)->fragment_path || s->sysv_has_lsb) &&
448 (UNIT(t)->fragment_path || t->sysv_has_lsb))
451 special_s = s->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, s->sysv_runlevels);
452 special_t = t->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, t->sysv_runlevels);
454 if (special_t && !special_s)
456 else if (special_s && !special_t)
458 else if (t->sysv_start_priority < s->sysv_start_priority)
460 else if (t->sysv_start_priority > s->sysv_start_priority)
465 /* FIXME: Maybe we should compare the name here lexicographically? */
467 if ((r = unit_add_dependency(UNIT(s), d, UNIT(t), true)) < 0)
474 static ExecCommand *exec_command_new(const char *path, const char *arg1) {
477 if (!(c = new0(ExecCommand, 1)))
480 if (!(c->path = strdup(path))) {
485 if (!(c->argv = strv_new(path, arg1, NULL))) {
494 static int sysv_exec_commands(Service *s) {
498 assert(s->sysv_path);
500 if (!(c = exec_command_new(s->sysv_path, "start")))
502 exec_command_append_list(s->exec_command+SERVICE_EXEC_START, c);
504 if (!(c = exec_command_new(s->sysv_path, "stop")))
506 exec_command_append_list(s->exec_command+SERVICE_EXEC_STOP, c);
508 if (!(c = exec_command_new(s->sysv_path, "reload")))
510 exec_command_append_list(s->exec_command+SERVICE_EXEC_RELOAD, c);
515 static int service_load_sysv_path(Service *s, const char *path) {
526 char *short_description = NULL, *long_description = NULL, *chkconfig_description = NULL, *description;
534 if (!(f = fopen(path, "re"))) {
535 r = errno == ENOENT ? 0 : -errno;
540 if (fstat(fileno(f), &st) < 0) {
546 if (!(s->sysv_path = strdup(path))) {
551 s->sysv_mtime = timespec_load(&st.st_mtim);
553 if (null_or_empty(&st)) {
554 u->load_state = UNIT_MASKED;
560 char l[LINE_MAX], *t;
562 if (!fgets(l, sizeof(l), f)) {
567 log_error("Failed to read configuration file '%s': %s", path, strerror(-r));
577 if (state == NORMAL && streq(t, "### BEGIN INIT INFO")) {
579 s->sysv_has_lsb = true;
583 if ((state == LSB_DESCRIPTION || state == LSB) && streq(t, "### END INIT INFO")) {
589 t += strspn(t, WHITESPACE);
591 if (state == NORMAL) {
593 /* Try to parse Red Hat style chkconfig headers */
595 if (startswith_no_case(t, "chkconfig:")) {
597 char runlevels[16], *k;
601 if (sscanf(t+10, "%15s %i %*i",
603 &start_priority) != 2) {
605 log_warning("[%s:%u] Failed to parse chkconfig line. Ignoring.", path, line);
609 /* A start priority gathered from the
610 * symlink farms is preferred over the
611 * data from the LSB header. */
612 if (start_priority < 0 || start_priority > 99)
613 log_warning("[%s:%u] Start priority out of range. Ignoring.", path, line);
615 s->sysv_start_priority = start_priority;
617 char_array_0(runlevels);
618 k = delete_chars(runlevels, WHITESPACE "-");
623 if (!(d = strdup(k))) {
628 free(s->sysv_runlevels);
629 s->sysv_runlevels = d;
632 } else if (startswith_no_case(t, "description:")) {
634 size_t k = strlen(t);
638 if (t[k-1] == '\\') {
643 if ((j = strstrip(t+12)) && *j) {
644 if (!(d = strdup(j))) {
651 free(chkconfig_description);
652 chkconfig_description = d;
654 } else if (startswith_no_case(t, "pidfile:")) {
661 if (!path_is_absolute(fn)) {
662 log_warning("[%s:%u] PID file not absolute. Ignoring.", path, line);
666 if (!(fn = strdup(fn))) {
675 } else if (state == DESCRIPTION) {
677 /* Try to parse Red Hat style description
680 size_t k = strlen(t);
688 if ((j = strstrip(t)) && *j) {
691 if (chkconfig_description)
692 d = join(chkconfig_description, " ", j, NULL);
701 free(chkconfig_description);
702 chkconfig_description = d;
705 } else if (state == LSB || state == LSB_DESCRIPTION) {
707 if (startswith_no_case(t, "Provides:")) {
713 FOREACH_WORD_QUOTED(w, z, t+9, i) {
716 if (!(n = strndup(w, z))) {
721 r = sysv_translate_facility(n, file_name_from_path(path), &m);
730 if (unit_name_to_type(m) == UNIT_SERVICE)
731 r = unit_add_name(u, m);
738 * indication that the
740 * now available. This
743 * targets do NOT pull
746 r = unit_add_two_dependencies_by_name(u, UNIT_BEFORE, UNIT_WANTS, m, NULL, true);
749 log_error("[%s:%u] Failed to add LSB Provides name %s, ignoring: %s", path, line, m, strerror(-r));
754 } else if (startswith_no_case(t, "Required-Start:") ||
755 startswith_no_case(t, "Should-Start:") ||
756 startswith_no_case(t, "X-Start-Before:") ||
757 startswith_no_case(t, "X-Start-After:")) {
763 FOREACH_WORD_QUOTED(w, z, strchr(t, ':')+1, i) {
766 if (!(n = strndup(w, z))) {
771 r = sysv_translate_facility(n, file_name_from_path(path), &m);
774 log_error("[%s:%u] Failed to translate LSB dependency %s, ignoring: %s", path, line, n, strerror(-r));
784 r = unit_add_dependency_by_name(u, startswith_no_case(t, "X-Start-Before:") ? UNIT_BEFORE : UNIT_AFTER, m, NULL, true);
787 log_error("[%s:%u] Failed to add dependency on %s, ignoring: %s", path, line, m, strerror(-r));
791 } else if (startswith_no_case(t, "Default-Start:")) {
796 k = delete_chars(t+14, WHITESPACE "-");
799 if (!(d = strdup(k))) {
804 free(s->sysv_runlevels);
805 s->sysv_runlevels = d;
808 } else if (startswith_no_case(t, "Description:")) {
811 state = LSB_DESCRIPTION;
813 if ((j = strstrip(t+12)) && *j) {
814 if (!(d = strdup(j))) {
821 free(long_description);
822 long_description = d;
824 } else if (startswith_no_case(t, "Short-Description:")) {
829 if ((j = strstrip(t+18)) && *j) {
830 if (!(d = strdup(j))) {
837 free(short_description);
838 short_description = d;
840 } else if (state == LSB_DESCRIPTION) {
842 if (startswith(l, "#\t") || startswith(l, "# ")) {
845 if ((j = strstrip(t)) && *j) {
848 if (long_description)
849 d = join(long_description, " ", t, NULL);
858 free(long_description);
859 long_description = d;
868 if ((r = sysv_exec_commands(s)) < 0)
870 if (s->sysv_runlevels &&
871 chars_intersect(RUNLEVELS_BOOT, s->sysv_runlevels) &&
872 chars_intersect(RUNLEVELS_UP, s->sysv_runlevels)) {
873 /* Service has both boot and "up" runlevels
874 configured. Kill the "up" ones. */
875 delete_chars(s->sysv_runlevels, RUNLEVELS_UP);
878 if (s->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, s->sysv_runlevels)) {
879 /* If there a runlevels configured for this service
880 * but none of the standard ones, then we assume this
881 * is some special kind of service (which might be
882 * needed for early boot) and don't create any links
885 UNIT(s)->default_dependencies = false;
887 /* Don't timeout special services during boot (like fsck) */
890 s->timeout_usec = DEFAULT_SYSV_TIMEOUT_USEC;
892 /* Special setting for all SysV services */
893 s->type = SERVICE_FORKING;
894 s->remain_after_exit = !s->pid_file;
895 s->guess_main_pid = false;
896 s->restart = SERVICE_RESTART_NO;
897 s->exec_context.ignore_sigpipe = false;
899 if (UNIT(s)->manager->sysv_console)
900 s->exec_context.std_output = EXEC_OUTPUT_JOURNAL_AND_CONSOLE;
902 s->exec_context.kill_mode = KILL_PROCESS;
904 /* We use the long description only if
905 * no short description is set. */
907 if (short_description)
908 description = short_description;
909 else if (chkconfig_description)
910 description = chkconfig_description;
911 else if (long_description)
912 description = long_description;
919 if (!(d = strappend(s->sysv_has_lsb ? "LSB: " : "SYSV: ", description))) {
927 /* The priority that has been set in /etc/rcN.d/ hierarchies
928 * takes precedence over what is stored as default in the LSB
930 if (s->sysv_start_priority_from_rcnd >= 0)
931 s->sysv_start_priority = s->sysv_start_priority_from_rcnd;
933 u->load_state = UNIT_LOADED;
941 free(short_description);
942 free(long_description);
943 free(chkconfig_description);
948 static int service_load_sysv_name(Service *s, const char *name) {
954 /* For SysV services we strip the boot.*, rc.* and *.sh
955 * prefixes/suffixes. */
956 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU) || defined(TARGET_ANGSTROM)
957 if (endswith(name, ".sh.service"))
962 if (startswith(name, "boot."))
966 #ifdef TARGET_FRUGALWARE
967 if (startswith(name, "rc."))
971 STRV_FOREACH(p, UNIT(s)->manager->lookup_paths.sysvinit_path) {
975 path = join(*p, "/", name, NULL);
979 assert(endswith(path, ".service"));
980 path[strlen(path)-8] = 0;
982 r = service_load_sysv_path(s, path);
984 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU) || defined(TARGET_ANGSTROM)
985 if (r >= 0 && UNIT(s)->load_state == UNIT_STUB) {
986 /* Try Debian style *.sh source'able init scripts */
988 r = service_load_sysv_path(s, path);
994 if (r >= 0 && UNIT(s)->load_state == UNIT_STUB) {
995 /* Try SUSE style boot.* init scripts */
997 path = join(*p, "/boot.", name, NULL);
1001 /* Drop .service suffix */
1002 path[strlen(path)-8] = 0;
1003 r = service_load_sysv_path(s, path);
1008 #ifdef TARGET_FRUGALWARE
1009 if (r >= 0 && UNIT(s)->load_state == UNIT_STUB) {
1010 /* Try Frugalware style rc.* init scripts */
1012 path = join(*p, "/rc.", name, NULL);
1016 /* Drop .service suffix */
1017 path[strlen(path)-8] = 0;
1018 r = service_load_sysv_path(s, path);
1026 if ((UNIT(s)->load_state != UNIT_STUB))
1033 static int service_load_sysv(Service *s) {
1040 /* Load service data from SysV init scripts, preferably with
1041 * LSB headers ... */
1043 if (strv_isempty(UNIT(s)->manager->lookup_paths.sysvinit_path))
1046 if ((t = UNIT(s)->id))
1047 if ((r = service_load_sysv_name(s, t)) < 0)
1050 if (UNIT(s)->load_state == UNIT_STUB)
1051 SET_FOREACH(t, UNIT(s)->names, i) {
1052 if (t == UNIT(s)->id)
1055 if ((r = service_load_sysv_name(s, t)) < 0)
1058 if (UNIT(s)->load_state != UNIT_STUB)
1066 static int fsck_fix_order(Service *s) {
1072 if (s->fsck_passno <= 0)
1075 /* For each pair of services where both have an fsck priority
1076 * we order things based on it. */
1078 LIST_FOREACH(units_by_type, other, UNIT(s)->manager->units_by_type[UNIT_SERVICE]) {
1087 if (UNIT(t)->load_state != UNIT_LOADED)
1090 if (t->fsck_passno <= 0)
1093 if (t->fsck_passno < s->fsck_passno)
1095 else if (t->fsck_passno > s->fsck_passno)
1100 if ((r = unit_add_dependency(UNIT(s), d, UNIT(t), true)) < 0)
1107 static int service_verify(Service *s) {
1110 if (UNIT(s)->load_state != UNIT_LOADED)
1113 if (!s->exec_command[SERVICE_EXEC_START]) {
1114 log_error("%s lacks ExecStart setting. Refusing.", UNIT(s)->id);
1118 if (s->type != SERVICE_ONESHOT &&
1119 s->exec_command[SERVICE_EXEC_START]->command_next) {
1120 log_error("%s has more than one ExecStart setting, which is only allowed for Type=oneshot services. Refusing.", UNIT(s)->id);
1124 if (s->type == SERVICE_ONESHOT &&
1125 s->exec_command[SERVICE_EXEC_RELOAD]) {
1126 log_error("%s has an ExecReload setting, which is not allowed for Type=oneshot services. Refusing.", UNIT(s)->id);
1130 if (s->type == SERVICE_DBUS && !s->bus_name) {
1131 log_error("%s is of type D-Bus but no D-Bus service name has been specified. Refusing.", UNIT(s)->id);
1135 if (s->exec_context.pam_name && s->exec_context.kill_mode != KILL_CONTROL_GROUP) {
1136 log_error("%s has PAM enabled. Kill mode must be set to 'control-group'. Refusing.", UNIT(s)->id);
1143 static int service_add_default_dependencies(Service *s) {
1148 /* Add a number of automatic dependencies useful for the
1149 * majority of services. */
1151 /* First, pull in base system */
1152 if (UNIT(s)->manager->running_as == MANAGER_SYSTEM) {
1154 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_BASIC_TARGET, NULL, true)) < 0)
1157 } else if (UNIT(s)->manager->running_as == MANAGER_USER) {
1159 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SOCKETS_TARGET, NULL, true)) < 0)
1163 /* Second, activate normal shutdown */
1164 return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true);
1167 static void service_fix_output(Service *s) {
1170 /* If nothing has been explicitly configured, patch default
1171 * output in. If input is socket/tty we avoid this however,
1172 * since in that case we want output to default to the same
1173 * place as we read input from. */
1175 if (s->exec_context.std_error == EXEC_OUTPUT_INHERIT &&
1176 s->exec_context.std_output == EXEC_OUTPUT_INHERIT &&
1177 s->exec_context.std_input == EXEC_INPUT_NULL)
1178 s->exec_context.std_error = UNIT(s)->manager->default_std_error;
1180 if (s->exec_context.std_output == EXEC_OUTPUT_INHERIT &&
1181 s->exec_context.std_input == EXEC_INPUT_NULL)
1182 s->exec_context.std_output = UNIT(s)->manager->default_std_output;
1185 static int service_load(Unit *u) {
1187 Service *s = SERVICE(u);
1191 /* Load a .service file */
1192 if ((r = unit_load_fragment(u)) < 0)
1195 #ifdef HAVE_SYSV_COMPAT
1196 /* Load a classic init script as a fallback, if we couldn't find anything */
1197 if (u->load_state == UNIT_STUB)
1198 if ((r = service_load_sysv(s)) < 0)
1202 /* Still nothing found? Then let's give up */
1203 if (u->load_state == UNIT_STUB)
1206 /* We were able to load something, then let's add in the
1207 * dropin directories. */
1208 if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
1211 /* This is a new unit? Then let's add in some extras */
1212 if (u->load_state == UNIT_LOADED) {
1213 service_fix_output(s);
1215 if ((r = unit_add_exec_dependencies(u, &s->exec_context)) < 0)
1218 if ((r = unit_add_default_cgroups(u)) < 0)
1221 #ifdef HAVE_SYSV_COMPAT
1222 if ((r = sysv_fix_order(s)) < 0)
1226 if ((r = fsck_fix_order(s)) < 0)
1230 if ((r = unit_watch_bus_name(u, s->bus_name)) < 0)
1233 if (s->type == SERVICE_NOTIFY && s->notify_access == NOTIFY_NONE)
1234 s->notify_access = NOTIFY_MAIN;
1236 if (s->type == SERVICE_DBUS || s->bus_name)
1237 if ((r = unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_REQUIRES, SPECIAL_DBUS_SOCKET, NULL, true)) < 0)
1240 if (UNIT(s)->default_dependencies)
1241 if ((r = service_add_default_dependencies(s)) < 0)
1245 return service_verify(s);
1248 static void service_dump(Unit *u, FILE *f, const char *prefix) {
1250 ServiceExecCommand c;
1251 Service *s = SERVICE(u);
1252 const char *prefix2;
1257 p2 = strappend(prefix, "\t");
1258 prefix2 = p2 ? p2 : prefix;
1261 "%sService State: %s\n"
1263 "%sReload Result: %s\n"
1264 "%sPermissionsStartOnly: %s\n"
1265 "%sRootDirectoryStartOnly: %s\n"
1266 "%sRemainAfterExit: %s\n"
1267 "%sGuessMainPID: %s\n"
1270 "%sNotifyAccess: %s\n",
1271 prefix, service_state_to_string(s->state),
1272 prefix, service_result_to_string(s->result),
1273 prefix, service_result_to_string(s->reload_result),
1274 prefix, yes_no(s->permissions_start_only),
1275 prefix, yes_no(s->root_directory_start_only),
1276 prefix, yes_no(s->remain_after_exit),
1277 prefix, yes_no(s->guess_main_pid),
1278 prefix, service_type_to_string(s->type),
1279 prefix, service_restart_to_string(s->restart),
1280 prefix, notify_access_to_string(s->notify_access));
1282 if (s->control_pid > 0)
1284 "%sControl PID: %lu\n",
1285 prefix, (unsigned long) s->control_pid);
1287 if (s->main_pid > 0)
1290 "%sMain PID Known: %s\n"
1291 "%sMain PID Alien: %s\n",
1292 prefix, (unsigned long) s->main_pid,
1293 prefix, yes_no(s->main_pid_known),
1294 prefix, yes_no(s->main_pid_alien));
1299 prefix, s->pid_file);
1304 "%sBus Name Good: %s\n",
1305 prefix, s->bus_name,
1306 prefix, yes_no(s->bus_name_good));
1308 exec_context_dump(&s->exec_context, f, prefix);
1310 for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
1312 if (!s->exec_command[c])
1315 fprintf(f, "%s-> %s:\n",
1316 prefix, service_exec_command_to_string(c));
1318 exec_command_dump_list(s->exec_command[c], f, prefix2);
1321 #ifdef HAVE_SYSV_COMPAT
1324 "%sSysV Init Script Path: %s\n"
1325 "%sSysV Init Script has LSB Header: %s\n"
1326 "%sSysVEnabled: %s\n",
1327 prefix, s->sysv_path,
1328 prefix, yes_no(s->sysv_has_lsb),
1329 prefix, yes_no(s->sysv_enabled));
1331 if (s->sysv_start_priority >= 0)
1333 "%sSysVStartPriority: %i\n",
1334 prefix, s->sysv_start_priority);
1336 if (s->sysv_runlevels)
1337 fprintf(f, "%sSysVRunLevels: %s\n",
1338 prefix, s->sysv_runlevels);
1341 if (s->fsck_passno > 0)
1343 "%sFsckPassNo: %i\n",
1344 prefix, s->fsck_passno);
1347 fprintf(f, "%sStatus Text: %s\n",
1348 prefix, s->status_text);
1353 static int service_load_pid_file(Service *s, bool may_warn) {
1363 if ((r = read_one_line_file(s->pid_file, &k)) < 0) {
1365 log_info("PID file %s not readable (yet?) after %s.",
1366 s->pid_file, service_state_to_string(s->state));
1370 r = parse_pid(k, &pid);
1376 if (kill(pid, 0) < 0 && errno != EPERM) {
1378 log_info("PID %lu read from file %s does not exist.",
1379 (unsigned long) pid, s->pid_file);
1383 if (s->main_pid_known) {
1384 if (pid == s->main_pid)
1387 log_debug("Main PID changing: %lu -> %lu",
1388 (unsigned long) s->main_pid, (unsigned long) pid);
1389 service_unwatch_main_pid(s);
1390 s->main_pid_known = false;
1392 log_debug("Main PID loaded: %lu", (unsigned long) pid);
1394 if ((r = service_set_main_pid(s, pid)) < 0)
1397 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1398 /* FIXME: we need to do something here */
1404 static int service_search_main_pid(Service *s) {
1410 /* If we know it anyway, don't ever fallback to unreliable
1412 if (s->main_pid_known)
1415 if (!s->guess_main_pid)
1418 assert(s->main_pid <= 0);
1420 if ((pid = cgroup_bonding_search_main_pid_list(UNIT(s)->cgroup_bondings)) <= 0)
1423 log_debug("Main PID guessed: %lu", (unsigned long) pid);
1424 if ((r = service_set_main_pid(s, pid)) < 0)
1427 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1428 /* FIXME: we need to do something here */
1434 static void service_notify_sockets_dead(Service *s) {
1440 /* Notifies all our sockets when we die */
1442 if (s->socket_fd >= 0)
1445 SET_FOREACH(u, UNIT(s)->dependencies[UNIT_TRIGGERED_BY], i)
1446 if (u->type == UNIT_SOCKET)
1447 socket_notify_service_dead(SOCKET(u));
1452 static void service_set_state(Service *s, ServiceState state) {
1453 ServiceState old_state;
1456 old_state = s->state;
1459 service_unwatch_pid_file(s);
1461 if (state != SERVICE_START_PRE &&
1462 state != SERVICE_START &&
1463 state != SERVICE_START_POST &&
1464 state != SERVICE_RELOAD &&
1465 state != SERVICE_STOP &&
1466 state != SERVICE_STOP_SIGTERM &&
1467 state != SERVICE_STOP_SIGKILL &&
1468 state != SERVICE_STOP_POST &&
1469 state != SERVICE_FINAL_SIGTERM &&
1470 state != SERVICE_FINAL_SIGKILL &&
1471 state != SERVICE_AUTO_RESTART)
1472 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1474 if (state != SERVICE_START &&
1475 state != SERVICE_START_POST &&
1476 state != SERVICE_RUNNING &&
1477 state != SERVICE_RELOAD &&
1478 state != SERVICE_STOP &&
1479 state != SERVICE_STOP_SIGTERM &&
1480 state != SERVICE_STOP_SIGKILL) {
1481 service_unwatch_main_pid(s);
1482 s->main_command = NULL;
1485 if (state != SERVICE_START_PRE &&
1486 state != SERVICE_START &&
1487 state != SERVICE_START_POST &&
1488 state != SERVICE_RELOAD &&
1489 state != SERVICE_STOP &&
1490 state != SERVICE_STOP_SIGTERM &&
1491 state != SERVICE_STOP_SIGKILL &&
1492 state != SERVICE_STOP_POST &&
1493 state != SERVICE_FINAL_SIGTERM &&
1494 state != SERVICE_FINAL_SIGKILL) {
1495 service_unwatch_control_pid(s);
1496 s->control_command = NULL;
1497 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1500 if (state == SERVICE_DEAD ||
1501 state == SERVICE_STOP ||
1502 state == SERVICE_STOP_SIGTERM ||
1503 state == SERVICE_STOP_SIGKILL ||
1504 state == SERVICE_STOP_POST ||
1505 state == SERVICE_FINAL_SIGTERM ||
1506 state == SERVICE_FINAL_SIGKILL ||
1507 state == SERVICE_FAILED ||
1508 state == SERVICE_AUTO_RESTART)
1509 service_notify_sockets_dead(s);
1511 if (state != SERVICE_START_PRE &&
1512 state != SERVICE_START &&
1513 state != SERVICE_START_POST &&
1514 state != SERVICE_RUNNING &&
1515 state != SERVICE_RELOAD &&
1516 state != SERVICE_STOP &&
1517 state != SERVICE_STOP_SIGTERM &&
1518 state != SERVICE_STOP_SIGKILL &&
1519 state != SERVICE_STOP_POST &&
1520 state != SERVICE_FINAL_SIGTERM &&
1521 state != SERVICE_FINAL_SIGKILL &&
1522 !(state == SERVICE_DEAD && UNIT(s)->job)) {
1523 service_close_socket_fd(s);
1524 service_connection_unref(s);
1527 if (state == SERVICE_STOP)
1528 service_stop_watchdog(s);
1530 /* For the inactive states unit_notify() will trim the cgroup,
1531 * but for exit we have to do that ourselves... */
1532 if (state == SERVICE_EXITED && UNIT(s)->manager->n_reloading <= 0)
1533 cgroup_bonding_trim_list(UNIT(s)->cgroup_bondings, true);
1535 if (old_state != state)
1536 log_debug("%s changed %s -> %s", UNIT(s)->id, service_state_to_string(old_state), service_state_to_string(state));
1538 unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state], s->reload_result == SERVICE_SUCCESS);
1539 s->reload_result = SERVICE_SUCCESS;
1542 static int service_coldplug(Unit *u) {
1543 Service *s = SERVICE(u);
1547 assert(s->state == SERVICE_DEAD);
1549 if (s->deserialized_state != s->state) {
1551 if (s->deserialized_state == SERVICE_START_PRE ||
1552 s->deserialized_state == SERVICE_START ||
1553 s->deserialized_state == SERVICE_START_POST ||
1554 s->deserialized_state == SERVICE_RELOAD ||
1555 s->deserialized_state == SERVICE_STOP ||
1556 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1557 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1558 s->deserialized_state == SERVICE_STOP_POST ||
1559 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1560 s->deserialized_state == SERVICE_FINAL_SIGKILL ||
1561 s->deserialized_state == SERVICE_AUTO_RESTART) {
1563 if (s->deserialized_state == SERVICE_AUTO_RESTART || s->timeout_usec > 0) {
1566 k = s->deserialized_state == SERVICE_AUTO_RESTART ? s->restart_usec : s->timeout_usec;
1568 if ((r = unit_watch_timer(UNIT(s), k, &s->timer_watch)) < 0)
1573 if ((s->deserialized_state == SERVICE_START &&
1574 (s->type == SERVICE_FORKING ||
1575 s->type == SERVICE_DBUS ||
1576 s->type == SERVICE_ONESHOT ||
1577 s->type == SERVICE_NOTIFY)) ||
1578 s->deserialized_state == SERVICE_START_POST ||
1579 s->deserialized_state == SERVICE_RUNNING ||
1580 s->deserialized_state == SERVICE_RELOAD ||
1581 s->deserialized_state == SERVICE_STOP ||
1582 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1583 s->deserialized_state == SERVICE_STOP_SIGKILL)
1584 if (s->main_pid > 0)
1585 if ((r = unit_watch_pid(UNIT(s), s->main_pid)) < 0)
1588 if (s->deserialized_state == SERVICE_START_PRE ||
1589 s->deserialized_state == SERVICE_START ||
1590 s->deserialized_state == SERVICE_START_POST ||
1591 s->deserialized_state == SERVICE_RELOAD ||
1592 s->deserialized_state == SERVICE_STOP ||
1593 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1594 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1595 s->deserialized_state == SERVICE_STOP_POST ||
1596 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1597 s->deserialized_state == SERVICE_FINAL_SIGKILL)
1598 if (s->control_pid > 0)
1599 if ((r = unit_watch_pid(UNIT(s), s->control_pid)) < 0)
1602 if (s->deserialized_state == SERVICE_START_POST ||
1603 s->deserialized_state == SERVICE_RUNNING)
1604 service_handle_watchdog(s);
1606 service_set_state(s, s->deserialized_state);
1611 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
1615 unsigned rn_fds = 0;
1622 if (s->socket_fd >= 0)
1625 SET_FOREACH(u, UNIT(s)->dependencies[UNIT_TRIGGERED_BY], i) {
1630 if (u->type != UNIT_SOCKET)
1635 if ((r = socket_collect_fds(sock, &cfds, &cn_fds)) < 0)
1647 if (!(t = new(int, rn_fds+cn_fds))) {
1653 memcpy(t, rfds, rn_fds * sizeof(int));
1654 memcpy(t+rn_fds, cfds, cn_fds * sizeof(int));
1659 rn_fds = rn_fds+cn_fds;
1674 static int service_spawn(
1679 bool apply_permissions,
1681 bool apply_tty_stdin,
1682 bool set_notify_socket,
1687 int *fds = NULL, *fdsbuf = NULL;
1688 unsigned n_fds = 0, n_env = 0;
1689 char **argv = NULL, **final_env = NULL, **our_env = NULL;
1696 s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1697 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1698 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
1700 if (s->socket_fd >= 0) {
1701 fds = &s->socket_fd;
1704 if ((r = service_collect_fds(s, &fdsbuf, &n_fds)) < 0)
1711 if (timeout && s->timeout_usec) {
1712 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1715 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1717 if (!(argv = unit_full_printf_strv(UNIT(s), c->argv))) {
1722 if (!(our_env = new0(char*, 4))) {
1727 if (set_notify_socket)
1728 if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=%s", UNIT(s)->manager->notify_socket) < 0) {
1733 if (s->main_pid > 0)
1734 if (asprintf(our_env + n_env++, "MAINPID=%lu", (unsigned long) s->main_pid) < 0) {
1739 if (s->watchdog_usec > 0)
1740 if (asprintf(our_env + n_env++, "WATCHDOG_USEC=%llu", (unsigned long long) s->watchdog_usec) < 0) {
1745 if (!(final_env = strv_env_merge(2,
1746 UNIT(s)->manager->environment,
1761 UNIT(s)->manager->confirm_spawn,
1762 UNIT(s)->cgroup_bondings,
1763 UNIT(s)->cgroup_attributes,
1770 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1771 /* FIXME: we need to do something here */
1777 strv_free(final_env);
1787 strv_free(final_env);
1790 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1795 static int main_pid_good(Service *s) {
1798 /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1801 /* If we know the pid file, then lets just check if it is
1803 if (s->main_pid_known) {
1805 /* If it's an alien child let's check if it is still
1807 if (s->main_pid_alien)
1808 return kill(s->main_pid, 0) >= 0 || errno != ESRCH;
1810 /* .. otherwise assume we'll get a SIGCHLD for it,
1811 * which we really should wait for to collect exit
1812 * status and code */
1813 return s->main_pid > 0;
1816 /* We don't know the pid */
1820 static int control_pid_good(Service *s) {
1823 return s->control_pid > 0;
1826 static int cgroup_good(Service *s) {
1831 if ((r = cgroup_bonding_is_empty_list(UNIT(s)->cgroup_bondings)) < 0)
1837 static void service_enter_dead(Service *s, ServiceResult f, bool allow_restart) {
1841 if (f != SERVICE_SUCCESS)
1844 if (allow_restart &&
1845 !s->forbid_restart &&
1846 (s->restart == SERVICE_RESTART_ALWAYS ||
1847 (s->restart == SERVICE_RESTART_ON_SUCCESS && s->result == SERVICE_SUCCESS) ||
1848 (s->restart == SERVICE_RESTART_ON_FAILURE && s->result != SERVICE_SUCCESS) ||
1849 (s->restart == SERVICE_RESTART_ON_ABORT && (s->result == SERVICE_FAILURE_SIGNAL ||
1850 s->result == SERVICE_FAILURE_CORE_DUMP)))) {
1852 r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch);
1856 service_set_state(s, SERVICE_AUTO_RESTART);
1858 service_set_state(s, s->result != SERVICE_SUCCESS ? SERVICE_FAILED : SERVICE_DEAD);
1860 s->forbid_restart = false;
1865 log_warning("%s failed to run install restart timer: %s", UNIT(s)->id, strerror(-r));
1866 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, false);
1869 static void service_enter_signal(Service *s, ServiceState state, ServiceResult f);
1871 static void service_enter_stop_post(Service *s, ServiceResult f) {
1875 if (f != SERVICE_SUCCESS)
1878 service_unwatch_control_pid(s);
1880 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST])) {
1881 s->control_command_id = SERVICE_EXEC_STOP_POST;
1883 if ((r = service_spawn(s,
1887 !s->permissions_start_only,
1888 !s->root_directory_start_only,
1891 &s->control_pid)) < 0)
1895 service_set_state(s, SERVICE_STOP_POST);
1897 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_SUCCESS);
1902 log_warning("%s failed to run 'stop-post' task: %s", UNIT(s)->id, strerror(-r));
1903 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
1906 static void service_enter_signal(Service *s, ServiceState state, ServiceResult f) {
1908 Set *pid_set = NULL;
1909 bool wait_for_exit = false;
1913 if (f != SERVICE_SUCCESS)
1916 if (s->exec_context.kill_mode != KILL_NONE) {
1917 int sig = (state == SERVICE_STOP_SIGTERM || state == SERVICE_FINAL_SIGTERM) ? s->exec_context.kill_signal : SIGKILL;
1919 if (s->main_pid > 0) {
1920 if (kill_and_sigcont(s->main_pid, sig) < 0 && errno != ESRCH)
1921 log_warning("Failed to kill main process %li: %m", (long) s->main_pid);
1923 wait_for_exit = !s->main_pid_alien;
1926 if (s->control_pid > 0) {
1927 if (kill_and_sigcont(s->control_pid, sig) < 0 && errno != ESRCH)
1928 log_warning("Failed to kill control process %li: %m", (long) s->control_pid);
1930 wait_for_exit = true;
1933 if (s->exec_context.kill_mode == KILL_CONTROL_GROUP) {
1935 if (!(pid_set = set_new(trivial_hash_func, trivial_compare_func))) {
1940 /* Exclude the main/control pids from being killed via the cgroup */
1941 if (s->main_pid > 0)
1942 if ((r = set_put(pid_set, LONG_TO_PTR(s->main_pid))) < 0)
1945 if (s->control_pid > 0)
1946 if ((r = set_put(pid_set, LONG_TO_PTR(s->control_pid))) < 0)
1949 if ((r = cgroup_bonding_kill_list(UNIT(s)->cgroup_bondings, sig, true, pid_set)) < 0) {
1950 if (r != -EAGAIN && r != -ESRCH && r != -ENOENT)
1951 log_warning("Failed to kill control group: %s", strerror(-r));
1953 wait_for_exit = true;
1960 if (wait_for_exit) {
1961 if (s->timeout_usec > 0)
1962 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1965 service_set_state(s, state);
1966 } else if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1967 service_enter_stop_post(s, SERVICE_SUCCESS);
1969 service_enter_dead(s, SERVICE_SUCCESS, true);
1974 log_warning("%s failed to kill processes: %s", UNIT(s)->id, strerror(-r));
1976 if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1977 service_enter_stop_post(s, SERVICE_FAILURE_RESOURCES);
1979 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
1985 static void service_enter_stop(Service *s, ServiceResult f) {
1990 if (f != SERVICE_SUCCESS)
1993 service_unwatch_control_pid(s);
1995 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP])) {
1996 s->control_command_id = SERVICE_EXEC_STOP;
1998 if ((r = service_spawn(s,
2002 !s->permissions_start_only,
2003 !s->root_directory_start_only,
2006 &s->control_pid)) < 0)
2009 service_set_state(s, SERVICE_STOP);
2011 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
2016 log_warning("%s failed to run 'stop' task: %s", UNIT(s)->id, strerror(-r));
2017 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
2020 static void service_enter_running(Service *s, ServiceResult f) {
2021 int main_pid_ok, cgroup_ok;
2024 if (f != SERVICE_SUCCESS)
2027 main_pid_ok = main_pid_good(s);
2028 cgroup_ok = cgroup_good(s);
2030 if ((main_pid_ok > 0 || (main_pid_ok < 0 && cgroup_ok != 0)) &&
2031 (s->bus_name_good || s->type != SERVICE_DBUS))
2032 service_set_state(s, SERVICE_RUNNING);
2033 else if (s->remain_after_exit)
2034 service_set_state(s, SERVICE_EXITED);
2036 service_enter_stop(s, SERVICE_SUCCESS);
2039 static void service_enter_start_post(Service *s) {
2043 service_unwatch_control_pid(s);
2045 if (s->watchdog_usec > 0)
2046 service_reset_watchdog(s);
2048 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_POST])) {
2049 s->control_command_id = SERVICE_EXEC_START_POST;
2051 if ((r = service_spawn(s,
2055 !s->permissions_start_only,
2056 !s->root_directory_start_only,
2059 &s->control_pid)) < 0)
2062 service_set_state(s, SERVICE_START_POST);
2064 service_enter_running(s, SERVICE_SUCCESS);
2069 log_warning("%s failed to run 'start-post' task: %s", UNIT(s)->id, strerror(-r));
2070 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2073 static void service_enter_start(Service *s) {
2080 assert(s->exec_command[SERVICE_EXEC_START]);
2081 assert(!s->exec_command[SERVICE_EXEC_START]->command_next || s->type == SERVICE_ONESHOT);
2083 if (s->type == SERVICE_FORKING)
2084 service_unwatch_control_pid(s);
2086 service_unwatch_main_pid(s);
2088 /* We want to ensure that nobody leaks processes from
2089 * START_PRE here, so let's go on a killing spree, People
2090 * should not spawn long running processes from START_PRE. */
2091 cgroup_bonding_kill_list(UNIT(s)->cgroup_bondings, SIGKILL, true, NULL);
2093 if (s->type == SERVICE_FORKING) {
2094 s->control_command_id = SERVICE_EXEC_START;
2095 c = s->control_command = s->exec_command[SERVICE_EXEC_START];
2097 s->main_command = NULL;
2099 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2100 s->control_command = NULL;
2102 c = s->main_command = s->exec_command[SERVICE_EXEC_START];
2105 if ((r = service_spawn(s,
2107 s->type == SERVICE_FORKING || s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY,
2112 s->notify_access != NOTIFY_NONE,
2116 if (s->type == SERVICE_SIMPLE) {
2117 /* For simple services we immediately start
2118 * the START_POST binaries. */
2120 service_set_main_pid(s, pid);
2121 service_enter_start_post(s);
2123 } else if (s->type == SERVICE_FORKING) {
2125 /* For forking services we wait until the start
2126 * process exited. */
2128 s->control_pid = pid;
2129 service_set_state(s, SERVICE_START);
2131 } else if (s->type == SERVICE_ONESHOT ||
2132 s->type == SERVICE_DBUS ||
2133 s->type == SERVICE_NOTIFY) {
2135 /* For oneshot services we wait until the start
2136 * process exited, too, but it is our main process. */
2138 /* For D-Bus services we know the main pid right away,
2139 * but wait for the bus name to appear on the
2140 * bus. Notify services are similar. */
2142 service_set_main_pid(s, pid);
2143 service_set_state(s, SERVICE_START);
2145 assert_not_reached("Unknown service type");
2150 log_warning("%s failed to run 'start' task: %s", UNIT(s)->id, strerror(-r));
2151 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
2154 static void service_enter_start_pre(Service *s) {
2159 service_unwatch_control_pid(s);
2161 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_PRE])) {
2163 /* Before we start anything, let's clear up what might
2164 * be left from previous runs. */
2165 cgroup_bonding_kill_list(UNIT(s)->cgroup_bondings, SIGKILL, true, NULL);
2167 s->control_command_id = SERVICE_EXEC_START_PRE;
2169 if ((r = service_spawn(s,
2173 !s->permissions_start_only,
2174 !s->root_directory_start_only,
2177 &s->control_pid)) < 0)
2180 service_set_state(s, SERVICE_START_PRE);
2182 service_enter_start(s);
2187 log_warning("%s failed to run 'start-pre' task: %s", UNIT(s)->id, strerror(-r));
2188 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
2191 static void service_enter_restart(Service *s) {
2196 dbus_error_init(&error);
2199 log_info("Job pending for unit, delaying automatic restart.");
2201 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
2205 service_enter_dead(s, SERVICE_SUCCESS, false);
2207 if ((r = manager_add_job(UNIT(s)->manager, JOB_START, UNIT(s), JOB_FAIL, false, &error, NULL)) < 0)
2210 log_debug("%s scheduled restart job.", UNIT(s)->id);
2214 log_warning("%s failed to schedule restart job: %s", UNIT(s)->id, bus_error(&error, -r));
2215 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, false);
2217 dbus_error_free(&error);
2220 static void service_enter_reload(Service *s) {
2225 service_unwatch_control_pid(s);
2227 if ((s->control_command = s->exec_command[SERVICE_EXEC_RELOAD])) {
2228 s->control_command_id = SERVICE_EXEC_RELOAD;
2230 if ((r = service_spawn(s,
2234 !s->permissions_start_only,
2235 !s->root_directory_start_only,
2238 &s->control_pid)) < 0)
2241 service_set_state(s, SERVICE_RELOAD);
2243 service_enter_running(s, SERVICE_SUCCESS);
2248 log_warning("%s failed to run 'reload' task: %s", UNIT(s)->id, strerror(-r));
2249 s->reload_result = SERVICE_FAILURE_RESOURCES;
2250 service_enter_running(s, SERVICE_SUCCESS);
2253 static void service_run_next_control(Service *s) {
2257 assert(s->control_command);
2258 assert(s->control_command->command_next);
2260 assert(s->control_command_id != SERVICE_EXEC_START);
2262 s->control_command = s->control_command->command_next;
2263 service_unwatch_control_pid(s);
2265 if ((r = service_spawn(s,
2269 !s->permissions_start_only,
2270 !s->root_directory_start_only,
2271 s->control_command_id == SERVICE_EXEC_START_PRE ||
2272 s->control_command_id == SERVICE_EXEC_STOP_POST,
2274 &s->control_pid)) < 0)
2280 log_warning("%s failed to run next control task: %s", UNIT(s)->id, strerror(-r));
2282 if (s->state == SERVICE_START_PRE)
2283 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
2284 else if (s->state == SERVICE_STOP)
2285 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
2286 else if (s->state == SERVICE_STOP_POST)
2287 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
2288 else if (s->state == SERVICE_RELOAD) {
2289 s->reload_result = SERVICE_FAILURE_RESOURCES;
2290 service_enter_running(s, SERVICE_SUCCESS);
2292 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2295 static void service_run_next_main(Service *s) {
2300 assert(s->main_command);
2301 assert(s->main_command->command_next);
2302 assert(s->type == SERVICE_ONESHOT);
2304 s->main_command = s->main_command->command_next;
2305 service_unwatch_main_pid(s);
2307 if ((r = service_spawn(s,
2314 s->notify_access != NOTIFY_NONE,
2318 service_set_main_pid(s, pid);
2323 log_warning("%s failed to run next main task: %s", UNIT(s)->id, strerror(-r));
2324 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2327 static int service_start(Unit *u) {
2328 Service *s = SERVICE(u);
2332 /* We cannot fulfill this request right now, try again later
2334 if (s->state == SERVICE_STOP ||
2335 s->state == SERVICE_STOP_SIGTERM ||
2336 s->state == SERVICE_STOP_SIGKILL ||
2337 s->state == SERVICE_STOP_POST ||
2338 s->state == SERVICE_FINAL_SIGTERM ||
2339 s->state == SERVICE_FINAL_SIGKILL)
2342 /* Already on it! */
2343 if (s->state == SERVICE_START_PRE ||
2344 s->state == SERVICE_START ||
2345 s->state == SERVICE_START_POST)
2348 assert(s->state == SERVICE_DEAD || s->state == SERVICE_FAILED || s->state == SERVICE_AUTO_RESTART);
2350 /* Make sure we don't enter a busy loop of some kind. */
2351 if (!ratelimit_test(&s->ratelimit)) {
2352 log_warning("%s start request repeated too quickly, refusing to start.", u->id);
2356 s->result = SERVICE_SUCCESS;
2357 s->reload_result = SERVICE_SUCCESS;
2358 s->main_pid_known = false;
2359 s->main_pid_alien = false;
2360 s->forbid_restart = false;
2362 service_enter_start_pre(s);
2366 static int service_stop(Unit *u) {
2367 Service *s = SERVICE(u);
2371 /* This is a user request, so don't do restarts on this
2373 s->forbid_restart = true;
2376 if (s->state == SERVICE_STOP ||
2377 s->state == SERVICE_STOP_SIGTERM ||
2378 s->state == SERVICE_STOP_SIGKILL ||
2379 s->state == SERVICE_STOP_POST ||
2380 s->state == SERVICE_FINAL_SIGTERM ||
2381 s->state == SERVICE_FINAL_SIGKILL)
2384 /* Don't allow a restart */
2385 if (s->state == SERVICE_AUTO_RESTART) {
2386 service_set_state(s, SERVICE_DEAD);
2390 /* If there's already something running we go directly into
2392 if (s->state == SERVICE_START_PRE ||
2393 s->state == SERVICE_START ||
2394 s->state == SERVICE_START_POST ||
2395 s->state == SERVICE_RELOAD) {
2396 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
2400 assert(s->state == SERVICE_RUNNING ||
2401 s->state == SERVICE_EXITED);
2403 service_enter_stop(s, SERVICE_SUCCESS);
2407 static int service_reload(Unit *u) {
2408 Service *s = SERVICE(u);
2412 assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
2414 service_enter_reload(s);
2418 static bool service_can_reload(Unit *u) {
2419 Service *s = SERVICE(u);
2423 return !!s->exec_command[SERVICE_EXEC_RELOAD];
2426 static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
2427 Service *s = SERVICE(u);
2433 unit_serialize_item(u, f, "state", service_state_to_string(s->state));
2434 unit_serialize_item(u, f, "result", service_result_to_string(s->result));
2435 unit_serialize_item(u, f, "reload-result", service_result_to_string(s->reload_result));
2437 if (s->control_pid > 0)
2438 unit_serialize_item_format(u, f, "control-pid", "%lu", (unsigned long) s->control_pid);
2440 if (s->main_pid_known && s->main_pid > 0)
2441 unit_serialize_item_format(u, f, "main-pid", "%lu", (unsigned long) s->main_pid);
2443 unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
2446 unit_serialize_item(u, f, "status-text", s->status_text);
2448 /* FIXME: There's a minor uncleanliness here: if there are
2449 * multiple commands attached here, we will start from the
2450 * first one again */
2451 if (s->control_command_id >= 0)
2452 unit_serialize_item(u, f, "control-command", service_exec_command_to_string(s->control_command_id));
2454 if (s->socket_fd >= 0) {
2457 if ((copy = fdset_put_dup(fds, s->socket_fd)) < 0)
2460 unit_serialize_item_format(u, f, "socket-fd", "%i", copy);
2463 if (s->main_exec_status.pid > 0) {
2464 unit_serialize_item_format(u, f, "main-exec-status-pid", "%lu", (unsigned long) s->main_exec_status.pid);
2465 dual_timestamp_serialize(f, "main-exec-status-start", &s->main_exec_status.start_timestamp);
2466 dual_timestamp_serialize(f, "main-exec-status-exit", &s->main_exec_status.exit_timestamp);
2468 if (dual_timestamp_is_set(&s->main_exec_status.exit_timestamp)) {
2469 unit_serialize_item_format(u, f, "main-exec-status-code", "%i", s->main_exec_status.code);
2470 unit_serialize_item_format(u, f, "main-exec-status-status", "%i", s->main_exec_status.status);
2473 if (dual_timestamp_is_set(&s->watchdog_timestamp))
2474 dual_timestamp_serialize(f, "watchdog-timestamp", &s->watchdog_timestamp);
2479 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
2480 Service *s = SERVICE(u);
2487 if (streq(key, "state")) {
2490 if ((state = service_state_from_string(value)) < 0)
2491 log_debug("Failed to parse state value %s", value);
2493 s->deserialized_state = state;
2494 } else if (streq(key, "result")) {
2497 f = service_result_from_string(value);
2499 log_debug("Failed to parse result value %s", value);
2500 else if (f != SERVICE_SUCCESS)
2503 } else if (streq(key, "reload-result")) {
2506 f = service_result_from_string(value);
2508 log_debug("Failed to parse reload result value %s", value);
2509 else if (f != SERVICE_SUCCESS)
2510 s->reload_result = f;
2512 } else if (streq(key, "control-pid")) {
2515 if (parse_pid(value, &pid) < 0)
2516 log_debug("Failed to parse control-pid value %s", value);
2518 s->control_pid = pid;
2519 } else if (streq(key, "main-pid")) {
2522 if (parse_pid(value, &pid) < 0)
2523 log_debug("Failed to parse main-pid value %s", value);
2525 service_set_main_pid(s, (pid_t) pid);
2526 } else if (streq(key, "main-pid-known")) {
2529 if ((b = parse_boolean(value)) < 0)
2530 log_debug("Failed to parse main-pid-known value %s", value);
2532 s->main_pid_known = b;
2533 } else if (streq(key, "status-text")) {
2536 if ((t = strdup(value))) {
2537 free(s->status_text);
2541 } else if (streq(key, "control-command")) {
2542 ServiceExecCommand id;
2544 if ((id = service_exec_command_from_string(value)) < 0)
2545 log_debug("Failed to parse exec-command value %s", value);
2547 s->control_command_id = id;
2548 s->control_command = s->exec_command[id];
2550 } else if (streq(key, "socket-fd")) {
2553 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2554 log_debug("Failed to parse socket-fd value %s", value);
2557 if (s->socket_fd >= 0)
2558 close_nointr_nofail(s->socket_fd);
2559 s->socket_fd = fdset_remove(fds, fd);
2561 } else if (streq(key, "main-exec-status-pid")) {
2564 if (parse_pid(value, &pid) < 0)
2565 log_debug("Failed to parse main-exec-status-pid value %s", value);
2567 s->main_exec_status.pid = pid;
2568 } else if (streq(key, "main-exec-status-code")) {
2571 if (safe_atoi(value, &i) < 0)
2572 log_debug("Failed to parse main-exec-status-code value %s", value);
2574 s->main_exec_status.code = i;
2575 } else if (streq(key, "main-exec-status-status")) {
2578 if (safe_atoi(value, &i) < 0)
2579 log_debug("Failed to parse main-exec-status-status value %s", value);
2581 s->main_exec_status.status = i;
2582 } else if (streq(key, "main-exec-status-start"))
2583 dual_timestamp_deserialize(value, &s->main_exec_status.start_timestamp);
2584 else if (streq(key, "main-exec-status-exit"))
2585 dual_timestamp_deserialize(value, &s->main_exec_status.exit_timestamp);
2586 else if (streq(key, "watchdog-timestamp"))
2587 dual_timestamp_deserialize(value, &s->watchdog_timestamp);
2589 log_debug("Unknown serialization key '%s'", key);
2594 static UnitActiveState service_active_state(Unit *u) {
2597 return state_translation_table[SERVICE(u)->state];
2600 static const char *service_sub_state_to_string(Unit *u) {
2603 return service_state_to_string(SERVICE(u)->state);
2606 static bool service_check_gc(Unit *u) {
2607 Service *s = SERVICE(u);
2611 /* Never clean up services that still have a process around,
2612 * even if the service is formally dead. */
2613 if (cgroup_good(s) > 0 ||
2614 main_pid_good(s) > 0 ||
2615 control_pid_good(s) > 0)
2618 #ifdef HAVE_SYSV_COMPAT
2626 static bool service_check_snapshot(Unit *u) {
2627 Service *s = SERVICE(u);
2631 return !s->got_socket_fd;
2634 static int service_retry_pid_file(Service *s) {
2637 assert(s->pid_file);
2638 assert(s->state == SERVICE_START || s->state == SERVICE_START_POST);
2640 r = service_load_pid_file(s, false);
2644 service_unwatch_pid_file(s);
2646 service_enter_running(s, SERVICE_SUCCESS);
2650 static int service_watch_pid_file(Service *s) {
2653 log_debug("Setting watch for %s's PID file %s", UNIT(s)->id, s->pid_file_pathspec->path);
2654 r = path_spec_watch(s->pid_file_pathspec, UNIT(s));
2658 /* the pidfile might have appeared just before we set the watch */
2659 service_retry_pid_file(s);
2663 log_error("Failed to set a watch for %s's PID file %s: %s",
2664 UNIT(s)->id, s->pid_file_pathspec->path, strerror(-r));
2665 service_unwatch_pid_file(s);
2669 static int service_demand_pid_file(Service *s) {
2672 assert(s->pid_file);
2673 assert(!s->pid_file_pathspec);
2675 ps = new0(PathSpec, 1);
2679 ps->path = strdup(s->pid_file);
2685 path_kill_slashes(ps->path);
2687 /* PATH_CHANGED would not be enough. There are daemons (sendmail) that
2688 * keep their PID file open all the time. */
2689 ps->type = PATH_MODIFIED;
2690 ps->inotify_fd = -1;
2692 s->pid_file_pathspec = ps;
2694 return service_watch_pid_file(s);
2697 static void service_fd_event(Unit *u, int fd, uint32_t events, Watch *w) {
2698 Service *s = SERVICE(u);
2702 assert(s->state == SERVICE_START || s->state == SERVICE_START_POST);
2703 assert(s->pid_file_pathspec);
2704 assert(path_spec_owns_inotify_fd(s->pid_file_pathspec, fd));
2706 log_debug("inotify event for %s", u->id);
2708 if (path_spec_fd_event(s->pid_file_pathspec, events) < 0)
2711 if (service_retry_pid_file(s) == 0)
2714 if (service_watch_pid_file(s) < 0)
2719 service_unwatch_pid_file(s);
2720 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
2723 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2724 Service *s = SERVICE(u);
2730 if (UNIT(s)->fragment_path ? is_clean_exit(code, status) : is_clean_exit_lsb(code, status))
2731 f = SERVICE_SUCCESS;
2732 else if (code == CLD_EXITED)
2733 f = SERVICE_FAILURE_EXIT_CODE;
2734 else if (code == CLD_KILLED)
2735 f = SERVICE_FAILURE_SIGNAL;
2736 else if (code == CLD_DUMPED)
2737 f = SERVICE_FAILURE_CORE_DUMP;
2739 assert_not_reached("Unknown code");
2741 if (s->main_pid == pid) {
2742 /* Forking services may occasionally move to a new PID.
2743 * As long as they update the PID file before exiting the old
2744 * PID, they're fine. */
2745 if (service_load_pid_file(s, false) == 0)
2749 exec_status_exit(&s->main_exec_status, &s->exec_context, pid, code, status);
2751 /* If this is not a forking service than the main
2752 * process got started and hence we copy the exit
2753 * status so that it is recorded both as main and as
2754 * control process exit status */
2755 if (s->main_command) {
2756 s->main_command->exec_status = s->main_exec_status;
2758 if (s->main_command->ignore)
2759 f = SERVICE_SUCCESS;
2762 log_full(f == SERVICE_SUCCESS ? LOG_DEBUG : LOG_NOTICE,
2763 "%s: main process exited, code=%s, status=%i", u->id, sigchld_code_to_string(code), status);
2765 if (f != SERVICE_SUCCESS)
2768 if (s->main_command &&
2769 s->main_command->command_next &&
2770 f == SERVICE_SUCCESS) {
2772 /* There is another command to *
2773 * execute, so let's do that. */
2775 log_debug("%s running next main command for state %s", u->id, service_state_to_string(s->state));
2776 service_run_next_main(s);
2780 /* The service exited, so the service is officially
2782 s->main_command = NULL;
2786 case SERVICE_START_POST:
2787 case SERVICE_RELOAD:
2789 /* Need to wait until the operation is
2794 if (s->type == SERVICE_ONESHOT) {
2795 /* This was our main goal, so let's go on */
2796 if (f == SERVICE_SUCCESS)
2797 service_enter_start_post(s);
2799 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
2802 assert(s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY);
2807 case SERVICE_RUNNING:
2808 service_enter_running(s, f);
2811 case SERVICE_STOP_SIGTERM:
2812 case SERVICE_STOP_SIGKILL:
2814 if (!control_pid_good(s))
2815 service_enter_stop_post(s, f);
2817 /* If there is still a control process, wait for that first */
2821 assert_not_reached("Uh, main process died at wrong time.");
2825 } else if (s->control_pid == pid) {
2829 if (s->control_command) {
2830 exec_status_exit(&s->control_command->exec_status, &s->exec_context, pid, code, status);
2832 if (s->control_command->ignore)
2833 f = SERVICE_SUCCESS;
2836 log_full(f == SERVICE_SUCCESS ? LOG_DEBUG : LOG_NOTICE,
2837 "%s: control process exited, code=%s status=%i", u->id, sigchld_code_to_string(code), status);
2839 if (f != SERVICE_SUCCESS)
2842 if (s->control_command &&
2843 s->control_command->command_next &&
2844 f == SERVICE_SUCCESS) {
2846 /* There is another command to *
2847 * execute, so let's do that. */
2849 log_debug("%s running next control command for state %s", u->id, service_state_to_string(s->state));
2850 service_run_next_control(s);
2853 /* No further commands for this step, so let's
2854 * figure out what to do next */
2856 s->control_command = NULL;
2857 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2859 log_debug("%s got final SIGCHLD for state %s", u->id, service_state_to_string(s->state));
2863 case SERVICE_START_PRE:
2864 if (f == SERVICE_SUCCESS)
2865 service_enter_start(s);
2867 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
2871 assert(s->type == SERVICE_FORKING);
2873 if (f != SERVICE_SUCCESS) {
2874 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
2879 bool has_start_post;
2882 /* Let's try to load the pid file here if we can.
2883 * The PID file might actually be created by a START_POST
2884 * script. In that case don't worry if the loading fails. */
2886 has_start_post = !!s->exec_command[SERVICE_EXEC_START_POST];
2887 r = service_load_pid_file(s, !has_start_post);
2888 if (!has_start_post && r < 0) {
2889 r = service_demand_pid_file(s);
2890 if (r < 0 || !cgroup_good(s))
2891 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
2895 service_search_main_pid(s);
2897 service_enter_start_post(s);
2900 case SERVICE_START_POST:
2901 if (f != SERVICE_SUCCESS) {
2902 service_enter_stop(s, f);
2909 r = service_load_pid_file(s, true);
2911 r = service_demand_pid_file(s);
2912 if (r < 0 || !cgroup_good(s))
2913 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2917 service_search_main_pid(s);
2919 service_enter_running(s, SERVICE_SUCCESS);
2922 case SERVICE_RELOAD:
2923 if (f == SERVICE_SUCCESS) {
2924 service_load_pid_file(s, true);
2925 service_search_main_pid(s);
2928 s->reload_result = f;
2929 service_enter_running(s, SERVICE_SUCCESS);
2933 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
2936 case SERVICE_STOP_SIGTERM:
2937 case SERVICE_STOP_SIGKILL:
2938 if (main_pid_good(s) <= 0)
2939 service_enter_stop_post(s, f);
2941 /* If there is still a service
2942 * process around, wait until
2943 * that one quit, too */
2946 case SERVICE_STOP_POST:
2947 case SERVICE_FINAL_SIGTERM:
2948 case SERVICE_FINAL_SIGKILL:
2949 service_enter_dead(s, f, true);
2953 assert_not_reached("Uh, control process died at wrong time.");
2958 /* Notify clients about changed exit status */
2959 unit_add_to_dbus_queue(u);
2962 static void service_timer_event(Unit *u, uint64_t elapsed, Watch* w) {
2963 Service *s = SERVICE(u);
2966 assert(elapsed == 1);
2968 if (w == &s->watchdog_watch) {
2969 service_handle_watchdog(s);
2973 assert(w == &s->timer_watch);
2977 case SERVICE_START_PRE:
2979 log_warning("%s operation timed out. Terminating.", u->id);
2980 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2983 case SERVICE_START_POST:
2984 log_warning("%s operation timed out. Stopping.", u->id);
2985 service_enter_stop(s, SERVICE_FAILURE_TIMEOUT);
2988 case SERVICE_RELOAD:
2989 log_warning("%s operation timed out. Stopping.", u->id);
2990 s->reload_result = SERVICE_FAILURE_TIMEOUT;
2991 service_enter_running(s, SERVICE_SUCCESS);
2995 log_warning("%s stopping timed out. Terminating.", u->id);
2996 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2999 case SERVICE_STOP_SIGTERM:
3000 if (s->exec_context.send_sigkill) {
3001 log_warning("%s stopping timed out. Killing.", u->id);
3002 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_TIMEOUT);
3004 log_warning("%s stopping timed out. Skipping SIGKILL.", u->id);
3005 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
3010 case SERVICE_STOP_SIGKILL:
3011 /* Uh, we sent a SIGKILL and it is still not gone?
3012 * Must be something we cannot kill, so let's just be
3013 * weirded out and continue */
3015 log_warning("%s still around after SIGKILL. Ignoring.", u->id);
3016 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
3019 case SERVICE_STOP_POST:
3020 log_warning("%s stopping timed out (2). Terminating.", u->id);
3021 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_TIMEOUT);
3024 case SERVICE_FINAL_SIGTERM:
3025 if (s->exec_context.send_sigkill) {
3026 log_warning("%s stopping timed out (2). Killing.", u->id);
3027 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_FAILURE_TIMEOUT);
3029 log_warning("%s stopping timed out (2). Skipping SIGKILL. Entering failed mode.", u->id);
3030 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, false);
3035 case SERVICE_FINAL_SIGKILL:
3036 log_warning("%s still around after SIGKILL (2). Entering failed mode.", u->id);
3037 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, true);
3040 case SERVICE_AUTO_RESTART:
3041 log_info("%s holdoff time over, scheduling restart.", u->id);
3042 service_enter_restart(s);
3046 assert_not_reached("Timeout at wrong time.");
3050 static void service_cgroup_notify_event(Unit *u) {
3051 Service *s = SERVICE(u);
3055 log_debug("%s: cgroup is empty", u->id);
3059 /* Waiting for SIGCHLD is usually more interesting,
3060 * because it includes return codes/signals. Which is
3061 * why we ignore the cgroup events for most cases,
3062 * except when we don't know pid which to expect the
3066 case SERVICE_START_POST:
3067 /* If we were hoping for the daemon to write its PID file,
3068 * we can give up now. */
3069 if (s->pid_file_pathspec) {
3070 log_warning("%s never wrote its PID file. Failing.", UNIT(s)->id);
3071 service_unwatch_pid_file(s);
3072 if (s->state == SERVICE_START)
3073 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
3075 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
3079 case SERVICE_RUNNING:
3080 /* service_enter_running() will figure out what to do */
3081 service_enter_running(s, SERVICE_SUCCESS);
3084 case SERVICE_STOP_SIGTERM:
3085 case SERVICE_STOP_SIGKILL:
3087 if (main_pid_good(s) <= 0 && !control_pid_good(s))
3088 service_enter_stop_post(s, SERVICE_SUCCESS);
3092 case SERVICE_FINAL_SIGTERM:
3093 case SERVICE_FINAL_SIGKILL:
3094 if (main_pid_good(s) <= 0 && !control_pid_good(s))
3095 service_enter_dead(s, SERVICE_SUCCESS, SERVICE_SUCCESS);
3104 static void service_notify_message(Unit *u, pid_t pid, char **tags) {
3105 Service *s = SERVICE(u);
3110 if (s->notify_access == NOTIFY_NONE) {
3111 log_warning("%s: Got notification message from PID %lu, but reception is disabled.",
3112 u->id, (unsigned long) pid);
3116 if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
3117 log_warning("%s: Got notification message from PID %lu, but reception only permitted for PID %lu",
3118 u->id, (unsigned long) pid, (unsigned long) s->main_pid);
3122 log_debug("%s: Got message", u->id);
3124 /* Interpret MAINPID= */
3125 if ((e = strv_find_prefix(tags, "MAINPID=")) &&
3126 (s->state == SERVICE_START ||
3127 s->state == SERVICE_START_POST ||
3128 s->state == SERVICE_RUNNING ||
3129 s->state == SERVICE_RELOAD)) {
3131 if (parse_pid(e + 8, &pid) < 0)
3132 log_warning("Failed to parse notification message %s", e);
3134 log_debug("%s: got %s", u->id, e);
3135 service_set_main_pid(s, pid);
3139 /* Interpret READY= */
3140 if (s->type == SERVICE_NOTIFY &&
3141 s->state == SERVICE_START &&
3142 strv_find(tags, "READY=1")) {
3143 log_debug("%s: got READY=1", u->id);
3145 service_enter_start_post(s);
3148 /* Interpret STATUS= */
3149 if ((e = strv_find_prefix(tags, "STATUS="))) {
3153 if (!(t = strdup(e+7))) {
3154 log_error("Failed to allocate string.");
3158 log_debug("%s: got %s", u->id, e);
3160 free(s->status_text);
3163 free(s->status_text);
3164 s->status_text = NULL;
3168 if (strv_find(tags, "WATCHDOG=1")) {
3169 log_debug("%s: got WATCHDOG=1", u->id);
3170 service_reset_watchdog(s);
3173 /* Notify clients about changed status or main pid */
3174 unit_add_to_dbus_queue(u);
3177 #ifdef HAVE_SYSV_COMPAT
3180 static void sysv_facility_in_insserv_conf(Manager *mgr) {
3184 if (!(f = fopen("/etc/insserv.conf", "re"))) {
3185 r = errno == ENOENT ? 0 : -errno;
3190 char l[LINE_MAX], *t;
3191 char **parsed = NULL;
3193 if (!fgets(l, sizeof(l), f)) {
3198 log_error("Failed to read configuration file '/etc/insserv.conf': %s", strerror(-r));
3203 if (*t != '$' && *t != '<')
3206 parsed = strv_split(t,WHITESPACE);
3207 /* we ignore <interactive>, not used, equivalent to X-Interactive */
3208 if (parsed && !startswith_no_case (parsed[0], "<interactive>")) {
3211 if (sysv_translate_facility(parsed[0], NULL, &facility) < 0)
3213 if ((u = manager_get_unit(mgr, facility)) && (u->type == UNIT_TARGET)) {
3215 char *dep = NULL, *name, **j;
3217 STRV_FOREACH (j, parsed+1) {
3226 if (sysv_translate_facility(name, NULL, &dep) < 0)
3229 r = unit_add_two_dependencies_by_name(u, UNIT_BEFORE, e, dep, NULL, true);
3244 static int service_enumerate(Manager *m) {
3248 char *path = NULL, *fpath = NULL, *name = NULL;
3249 Set *runlevel_services[ELEMENTSOF(rcnd_table)], *shutdown_services = NULL;
3256 if (m->running_as != MANAGER_SYSTEM)
3259 zero(runlevel_services);
3261 STRV_FOREACH(p, m->lookup_paths.sysvrcnd_path)
3262 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++) {
3266 path = join(*p, "/", rcnd_table[i].path, NULL);
3275 if (!(d = opendir(path))) {
3276 if (errno != ENOENT)
3277 log_warning("opendir() failed on %s: %s", path, strerror(errno));
3282 while ((de = readdir(d))) {
3285 if (ignore_file(de->d_name))
3288 if (de->d_name[0] != 'S' && de->d_name[0] != 'K')
3291 if (strlen(de->d_name) < 4)
3294 a = undecchar(de->d_name[1]);
3295 b = undecchar(de->d_name[2]);
3301 fpath = join(path, "/", de->d_name, NULL);
3307 if (access(fpath, X_OK) < 0) {
3309 if (errno != ENOENT)
3310 log_warning("access() failed on %s: %s", fpath, strerror(errno));
3316 if (!(name = sysv_translate_name(de->d_name + 3))) {
3321 if ((r = manager_load_unit_prepare(m, name, NULL, NULL, &service)) < 0) {
3322 log_warning("Failed to prepare unit %s: %s", name, strerror(-r));
3326 if (de->d_name[0] == 'S') {
3328 if (rcnd_table[i].type == RUNLEVEL_UP || rcnd_table[i].type == RUNLEVEL_SYSINIT) {
3329 SERVICE(service)->sysv_start_priority_from_rcnd =
3330 MAX(a*10 + b, SERVICE(service)->sysv_start_priority_from_rcnd);
3332 SERVICE(service)->sysv_enabled = true;
3335 if ((r = set_ensure_allocated(&runlevel_services[i], trivial_hash_func, trivial_compare_func)) < 0)
3338 if ((r = set_put(runlevel_services[i], service)) < 0)
3341 } else if (de->d_name[0] == 'K' &&
3342 (rcnd_table[i].type == RUNLEVEL_DOWN ||
3343 rcnd_table[i].type == RUNLEVEL_SYSINIT)) {
3345 if ((r = set_ensure_allocated(&shutdown_services, trivial_hash_func, trivial_compare_func)) < 0)
3348 if ((r = set_put(shutdown_services, service)) < 0)
3354 /* Now we loaded all stubs and are aware of the lowest
3355 start-up priority for all services, not let's actually load
3356 the services, this will also tell us which services are
3357 actually native now */
3358 manager_dispatch_load_queue(m);
3360 /* If this is a native service, rely on native ways to pull in
3361 * a service, don't pull it in via sysv rcN.d links. */
3362 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++)
3363 SET_FOREACH(service, runlevel_services[i], j) {
3364 service = unit_follow_merge(service);
3366 if (service->fragment_path)
3369 if ((r = unit_add_two_dependencies_by_name_inverse(service, UNIT_AFTER, UNIT_WANTS, rcnd_table[i].target, NULL, true)) < 0)
3373 /* We honour K links only for halt/reboot. For the normal
3374 * runlevels we assume the stop jobs will be implicitly added
3375 * by the core logic. Also, we don't really distinguish here
3376 * between the runlevels 0 and 6 and just add them to the
3377 * special shutdown target. On SUSE the boot.d/ runlevel is
3378 * also used for shutdown, so we add links for that too to the
3379 * shutdown target.*/
3380 SET_FOREACH(service, shutdown_services, j) {
3381 service = unit_follow_merge(service);
3383 if (service->fragment_path)
3386 if ((r = unit_add_two_dependencies_by_name(service, UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true)) < 0)
3393 sysv_facility_in_insserv_conf (m);
3401 for (i = 0; i < ELEMENTSOF(rcnd_table); i++)
3402 set_free(runlevel_services[i]);
3403 set_free(shutdown_services);
3412 static void service_bus_name_owner_change(
3415 const char *old_owner,
3416 const char *new_owner) {
3418 Service *s = SERVICE(u);
3423 assert(streq(s->bus_name, name));
3424 assert(old_owner || new_owner);
3426 if (old_owner && new_owner)
3427 log_debug("%s's D-Bus name %s changed owner from %s to %s", u->id, name, old_owner, new_owner);
3429 log_debug("%s's D-Bus name %s no longer registered by %s", u->id, name, old_owner);
3431 log_debug("%s's D-Bus name %s now registered by %s", u->id, name, new_owner);
3433 s->bus_name_good = !!new_owner;
3435 if (s->type == SERVICE_DBUS) {
3437 /* service_enter_running() will figure out what to
3439 if (s->state == SERVICE_RUNNING)
3440 service_enter_running(s, SERVICE_SUCCESS);
3441 else if (s->state == SERVICE_START && new_owner)
3442 service_enter_start_post(s);
3444 } else if (new_owner &&
3446 (s->state == SERVICE_START ||
3447 s->state == SERVICE_START_POST ||
3448 s->state == SERVICE_RUNNING ||
3449 s->state == SERVICE_RELOAD)) {
3451 /* Try to acquire PID from bus service */
3452 log_debug("Trying to acquire PID from D-Bus name...");
3454 bus_query_pid(u->manager, name);
3458 static void service_bus_query_pid_done(
3463 Service *s = SERVICE(u);
3468 log_debug("%s's D-Bus name %s is now owned by process %u", u->id, name, (unsigned) pid);
3470 if (s->main_pid <= 0 &&
3471 (s->state == SERVICE_START ||
3472 s->state == SERVICE_START_POST ||
3473 s->state == SERVICE_RUNNING ||
3474 s->state == SERVICE_RELOAD))
3475 service_set_main_pid(s, pid);
3478 int service_set_socket_fd(Service *s, int fd, Socket *sock) {
3483 /* This is called by the socket code when instantiating a new
3484 * service for a stream socket and the socket needs to be
3487 if (UNIT(s)->load_state != UNIT_LOADED)
3490 if (s->socket_fd >= 0)
3493 if (s->state != SERVICE_DEAD)
3497 s->got_socket_fd = true;
3499 unit_ref_set(&s->accept_socket, UNIT(sock));
3501 return unit_add_two_dependencies(UNIT(sock), UNIT_BEFORE, UNIT_TRIGGERS, UNIT(s), false);
3504 static void service_reset_failed(Unit *u) {
3505 Service *s = SERVICE(u);
3509 if (s->state == SERVICE_FAILED)
3510 service_set_state(s, SERVICE_DEAD);
3512 s->result = SERVICE_SUCCESS;
3513 s->reload_result = SERVICE_SUCCESS;
3516 static bool service_need_daemon_reload(Unit *u) {
3517 Service *s = SERVICE(u);
3521 #ifdef HAVE_SYSV_COMPAT
3526 if (stat(s->sysv_path, &st) < 0)
3527 /* What, cannot access this anymore? */
3530 if (s->sysv_mtime > 0 &&
3531 timespec_load(&st.st_mtim) != s->sysv_mtime)
3539 static int service_kill(Unit *u, KillWho who, KillMode mode, int signo, DBusError *error) {
3540 Service *s = SERVICE(u);
3542 Set *pid_set = NULL;
3546 if (s->main_pid <= 0 && who == KILL_MAIN) {
3547 dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "No main process to kill");
3551 if (s->control_pid <= 0 && who == KILL_CONTROL) {
3552 dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "No control process to kill");
3556 if (who == KILL_CONTROL || who == KILL_ALL)
3557 if (s->control_pid > 0)
3558 if (kill(s->control_pid, signo) < 0)
3561 if (who == KILL_MAIN || who == KILL_ALL)
3562 if (s->main_pid > 0)
3563 if (kill(s->main_pid, signo) < 0)
3566 if (who == KILL_ALL && mode == KILL_CONTROL_GROUP) {
3569 if (!(pid_set = set_new(trivial_hash_func, trivial_compare_func)))
3572 /* Exclude the control/main pid from being killed via the cgroup */
3573 if (s->control_pid > 0)
3574 if ((q = set_put(pid_set, LONG_TO_PTR(s->control_pid))) < 0) {
3579 if (s->main_pid > 0)
3580 if ((q = set_put(pid_set, LONG_TO_PTR(s->main_pid))) < 0) {
3585 if ((q = cgroup_bonding_kill_list(UNIT(s)->cgroup_bondings, signo, false, pid_set)) < 0)
3586 if (q != -EAGAIN && q != -ESRCH && q != -ENOENT)
3597 static const char* const service_state_table[_SERVICE_STATE_MAX] = {
3598 [SERVICE_DEAD] = "dead",
3599 [SERVICE_START_PRE] = "start-pre",
3600 [SERVICE_START] = "start",
3601 [SERVICE_START_POST] = "start-post",
3602 [SERVICE_RUNNING] = "running",
3603 [SERVICE_EXITED] = "exited",
3604 [SERVICE_RELOAD] = "reload",
3605 [SERVICE_STOP] = "stop",
3606 [SERVICE_STOP_SIGTERM] = "stop-sigterm",
3607 [SERVICE_STOP_SIGKILL] = "stop-sigkill",
3608 [SERVICE_STOP_POST] = "stop-post",
3609 [SERVICE_FINAL_SIGTERM] = "final-sigterm",
3610 [SERVICE_FINAL_SIGKILL] = "final-sigkill",
3611 [SERVICE_FAILED] = "failed",
3612 [SERVICE_AUTO_RESTART] = "auto-restart",
3615 DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
3617 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
3618 [SERVICE_RESTART_NO] = "no",
3619 [SERVICE_RESTART_ON_SUCCESS] = "on-success",
3620 [SERVICE_RESTART_ON_FAILURE] = "on-failure",
3621 [SERVICE_RESTART_ON_ABORT] = "on-abort",
3622 [SERVICE_RESTART_ALWAYS] = "always"
3625 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
3627 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
3628 [SERVICE_SIMPLE] = "simple",
3629 [SERVICE_FORKING] = "forking",
3630 [SERVICE_ONESHOT] = "oneshot",
3631 [SERVICE_DBUS] = "dbus",
3632 [SERVICE_NOTIFY] = "notify"
3635 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
3637 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
3638 [SERVICE_EXEC_START_PRE] = "ExecStartPre",
3639 [SERVICE_EXEC_START] = "ExecStart",
3640 [SERVICE_EXEC_START_POST] = "ExecStartPost",
3641 [SERVICE_EXEC_RELOAD] = "ExecReload",
3642 [SERVICE_EXEC_STOP] = "ExecStop",
3643 [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
3646 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
3648 static const char* const notify_access_table[_NOTIFY_ACCESS_MAX] = {
3649 [NOTIFY_NONE] = "none",
3650 [NOTIFY_MAIN] = "main",
3651 [NOTIFY_ALL] = "all"
3654 DEFINE_STRING_TABLE_LOOKUP(notify_access, NotifyAccess);
3656 static const char* const service_result_table[_SERVICE_RESULT_MAX] = {
3657 [SERVICE_SUCCESS] = "success",
3658 [SERVICE_FAILURE_RESOURCES] = "resources",
3659 [SERVICE_FAILURE_TIMEOUT] = "timeout",
3660 [SERVICE_FAILURE_EXIT_CODE] = "exit-code",
3661 [SERVICE_FAILURE_SIGNAL] = "signal",
3662 [SERVICE_FAILURE_CORE_DUMP] = "core-dump",
3663 [SERVICE_FAILURE_WATCHDOG] = "watchdog"
3666 DEFINE_STRING_TABLE_LOOKUP(service_result, ServiceResult);
3668 const UnitVTable service_vtable = {
3669 .suffix = ".service",
3670 .object_size = sizeof(Service),
3675 .show_status = true,
3677 .init = service_init,
3678 .done = service_done,
3679 .load = service_load,
3681 .coldplug = service_coldplug,
3683 .dump = service_dump,
3685 .start = service_start,
3686 .stop = service_stop,
3687 .reload = service_reload,
3689 .can_reload = service_can_reload,
3691 .kill = service_kill,
3693 .serialize = service_serialize,
3694 .deserialize_item = service_deserialize_item,
3696 .active_state = service_active_state,
3697 .sub_state_to_string = service_sub_state_to_string,
3699 .check_gc = service_check_gc,
3700 .check_snapshot = service_check_snapshot,
3702 .sigchld_event = service_sigchld_event,
3703 .timer_event = service_timer_event,
3704 .fd_event = service_fd_event,
3706 .reset_failed = service_reset_failed,
3708 .need_daemon_reload = service_need_daemon_reload,
3710 .cgroup_notify_empty = service_cgroup_notify_event,
3711 .notify_message = service_notify_message,
3713 .bus_name_owner_change = service_bus_name_owner_change,
3714 .bus_query_pid_done = service_bus_query_pid_done,
3716 .bus_interface = "org.freedesktop.systemd1.Service",
3717 .bus_message_handler = bus_service_message_handler,
3718 .bus_invalidating_properties = bus_service_invalidating_properties,
3720 #ifdef HAVE_SYSV_COMPAT
3721 .enumerate = service_enumerate