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 #if defined(TARGET_MANDRIVA) || defined(TARGET_MAGEIA)
282 /* Due to unfortunate name selection in Mandriva,
283 * $network is provided by network-up which is ordered
284 * after network which actually starts interfaces.
285 * To break the loop, just ignore it */
286 "network", SPECIAL_NETWORK_TARGET,
288 "named", SPECIAL_NSS_LOOKUP_TARGET,
289 "portmap", SPECIAL_RPCBIND_TARGET,
290 "remote_fs", SPECIAL_REMOTE_FS_TARGET,
291 "syslog", SPECIAL_SYSLOG_TARGET,
292 "time", SPECIAL_TIME_SYNC_TARGET,
294 /* common extensions */
295 "mail-transfer-agent", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
296 "x-display-manager", SPECIAL_DISPLAY_MANAGER_SERVICE,
299 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU) || defined(TARGET_ANGSTROM)
300 "mail-transport-agent", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
304 "MTA", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
305 "smtpdaemon", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
306 "httpd", SPECIAL_HTTP_DAEMON_TARGET,
310 "smtp", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
321 n = *name == '$' ? name + 1 : name;
323 for (i = 0; i < ELEMENTSOF(table); i += 2) {
325 if (!streq(table[i], n))
331 if (!(r = strdup(table[i+1])))
337 /* If we don't know this name, fallback heuristics to figure
338 * out whether something is a target or a service alias. */
341 if (!unit_prefix_is_valid(n))
344 /* Facilities starting with $ are most likely targets */
345 r = unit_name_build(n, NULL, ".target");
346 } else if (filename && streq(name, filename))
347 /* Names equaling the file name of the services are redundant */
350 /* Everything else we assume to be normal service names */
351 r = sysv_translate_name(n);
362 static int sysv_fix_order(Service *s) {
368 if (s->sysv_start_priority < 0)
371 /* For each pair of services where at least one lacks a LSB
372 * header, we use the start priority value to order things. */
374 LIST_FOREACH(units_by_type, other, s->meta.manager->units_by_type[UNIT_SERVICE]) {
377 bool special_s, special_t;
379 t = (Service*) other;
384 if (t->meta.load_state != UNIT_LOADED)
387 if (t->sysv_start_priority < 0)
390 /* If both units have modern headers we don't care
391 * about the priorities */
392 if ((s->meta.fragment_path || s->sysv_has_lsb) &&
393 (t->meta.fragment_path || t->sysv_has_lsb))
396 special_s = s->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, s->sysv_runlevels);
397 special_t = t->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, t->sysv_runlevels);
399 if (special_t && !special_s)
401 else if (special_s && !special_t)
403 else if (t->sysv_start_priority < s->sysv_start_priority)
405 else if (t->sysv_start_priority > s->sysv_start_priority)
410 /* FIXME: Maybe we should compare the name here lexicographically? */
412 if ((r = unit_add_dependency(UNIT(s), d, UNIT(t), true)) < 0)
419 static ExecCommand *exec_command_new(const char *path, const char *arg1) {
422 if (!(c = new0(ExecCommand, 1)))
425 if (!(c->path = strdup(path))) {
430 if (!(c->argv = strv_new(path, arg1, NULL))) {
439 static int sysv_exec_commands(Service *s) {
443 assert(s->sysv_path);
445 if (!(c = exec_command_new(s->sysv_path, "start")))
447 exec_command_append_list(s->exec_command+SERVICE_EXEC_START, c);
449 if (!(c = exec_command_new(s->sysv_path, "stop")))
451 exec_command_append_list(s->exec_command+SERVICE_EXEC_STOP, c);
453 if (!(c = exec_command_new(s->sysv_path, "reload")))
455 exec_command_append_list(s->exec_command+SERVICE_EXEC_RELOAD, c);
460 static int service_load_sysv_path(Service *s, const char *path) {
471 char *short_description = NULL, *long_description = NULL, *chkconfig_description = NULL, *description;
479 if (!(f = fopen(path, "re"))) {
480 r = errno == ENOENT ? 0 : -errno;
485 if (fstat(fileno(f), &st) < 0) {
491 if (!(s->sysv_path = strdup(path))) {
496 s->sysv_mtime = timespec_load(&st.st_mtim);
498 if (null_or_empty(&st)) {
499 u->meta.load_state = UNIT_MASKED;
505 char l[LINE_MAX], *t;
507 if (!fgets(l, sizeof(l), f)) {
512 log_error("Failed to read configuration file '%s': %s", path, strerror(-r));
522 if (state == NORMAL && streq(t, "### BEGIN INIT INFO")) {
524 s->sysv_has_lsb = true;
528 if ((state == LSB_DESCRIPTION || state == LSB) && streq(t, "### END INIT INFO")) {
534 t += strspn(t, WHITESPACE);
536 if (state == NORMAL) {
538 /* Try to parse Red Hat style chkconfig headers */
540 if (startswith_no_case(t, "chkconfig:")) {
542 char runlevels[16], *k;
546 if (sscanf(t+10, "%15s %i %*i",
548 &start_priority) != 2) {
550 log_warning("[%s:%u] Failed to parse chkconfig line. Ignoring.", path, line);
554 /* A start priority gathered from the
555 * symlink farms is preferred over the
556 * data from the LSB header. */
557 if (start_priority < 0 || start_priority > 99)
558 log_warning("[%s:%u] Start priority out of range. Ignoring.", path, line);
560 s->sysv_start_priority = start_priority;
562 char_array_0(runlevels);
563 k = delete_chars(runlevels, WHITESPACE "-");
568 if (!(d = strdup(k))) {
573 free(s->sysv_runlevels);
574 s->sysv_runlevels = d;
577 } else if (startswith_no_case(t, "description:")) {
579 size_t k = strlen(t);
583 if (t[k-1] == '\\') {
588 if ((j = strstrip(t+12)) && *j) {
589 if (!(d = strdup(j))) {
596 free(chkconfig_description);
597 chkconfig_description = d;
599 } else if (startswith_no_case(t, "pidfile:")) {
606 if (!path_is_absolute(fn)) {
607 log_warning("[%s:%u] PID file not absolute. Ignoring.", path, line);
611 if (!(fn = strdup(fn))) {
620 } else if (state == DESCRIPTION) {
622 /* Try to parse Red Hat style description
625 size_t k = strlen(t);
633 if ((j = strstrip(t)) && *j) {
636 if (chkconfig_description)
637 d = join(chkconfig_description, " ", j, NULL);
646 free(chkconfig_description);
647 chkconfig_description = d;
650 } else if (state == LSB || state == LSB_DESCRIPTION) {
652 if (startswith_no_case(t, "Provides:")) {
658 FOREACH_WORD_QUOTED(w, z, t+9, i) {
661 if (!(n = strndup(w, z))) {
666 r = sysv_translate_facility(n, file_name_from_path(path), &m);
675 if (unit_name_to_type(m) == UNIT_SERVICE)
676 r = unit_add_name(u, m);
683 * indication that the
685 * now available. This
688 * targets do NOT pull
691 r = unit_add_two_dependencies_by_name(u, UNIT_BEFORE, UNIT_WANTS, m, NULL, true);
694 log_error("[%s:%u] Failed to add LSB Provides name %s, ignoring: %s", path, line, m, strerror(-r));
699 } else if (startswith_no_case(t, "Required-Start:") ||
700 startswith_no_case(t, "Should-Start:") ||
701 startswith_no_case(t, "X-Start-Before:") ||
702 startswith_no_case(t, "X-Start-After:")) {
708 FOREACH_WORD_QUOTED(w, z, strchr(t, ':')+1, i) {
711 if (!(n = strndup(w, z))) {
716 r = sysv_translate_facility(n, file_name_from_path(path), &m);
719 log_error("[%s:%u] Failed to translate LSB dependency %s, ignoring: %s", path, line, n, strerror(-r));
729 r = unit_add_dependency_by_name(u, startswith_no_case(t, "X-Start-Before:") ? UNIT_BEFORE : UNIT_AFTER, m, NULL, true);
732 log_error("[%s:%u] Failed to add dependency on %s, ignoring: %s", path, line, m, strerror(-r));
736 } else if (startswith_no_case(t, "Default-Start:")) {
741 k = delete_chars(t+14, WHITESPACE "-");
744 if (!(d = strdup(k))) {
749 free(s->sysv_runlevels);
750 s->sysv_runlevels = d;
753 } else if (startswith_no_case(t, "Description:")) {
756 state = LSB_DESCRIPTION;
758 if ((j = strstrip(t+12)) && *j) {
759 if (!(d = strdup(j))) {
766 free(long_description);
767 long_description = d;
769 } else if (startswith_no_case(t, "Short-Description:")) {
774 if ((j = strstrip(t+18)) && *j) {
775 if (!(d = strdup(j))) {
782 free(short_description);
783 short_description = d;
785 } else if (state == LSB_DESCRIPTION) {
787 if (startswith(l, "#\t") || startswith(l, "# ")) {
790 if ((j = strstrip(t)) && *j) {
793 if (long_description)
794 d = join(long_description, " ", t, NULL);
803 free(long_description);
804 long_description = d;
813 if ((r = sysv_exec_commands(s)) < 0)
815 if (s->sysv_runlevels &&
816 chars_intersect(RUNLEVELS_BOOT, s->sysv_runlevels) &&
817 chars_intersect(RUNLEVELS_UP, s->sysv_runlevels)) {
818 /* Service has both boot and "up" runlevels
819 configured. Kill the "up" ones. */
820 delete_chars(s->sysv_runlevels, RUNLEVELS_UP);
823 if (s->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, s->sysv_runlevels)) {
824 /* If there a runlevels configured for this service
825 * but none of the standard ones, then we assume this
826 * is some special kind of service (which might be
827 * needed for early boot) and don't create any links
830 s->meta.default_dependencies = false;
832 /* Don't timeout special services during boot (like fsck) */
835 s->timeout_usec = DEFAULT_SYSV_TIMEOUT_USEC;
837 /* Special setting for all SysV services */
838 s->type = SERVICE_FORKING;
839 s->remain_after_exit = !s->pid_file;
840 s->guess_main_pid = false;
841 s->restart = SERVICE_RESTART_NO;
843 if (s->meta.manager->sysv_console)
844 s->exec_context.std_output = EXEC_OUTPUT_SYSLOG_AND_CONSOLE;
846 s->exec_context.kill_mode = KILL_PROCESS;
848 /* We use the long description only if
849 * no short description is set. */
851 if (short_description)
852 description = short_description;
853 else if (chkconfig_description)
854 description = chkconfig_description;
855 else if (long_description)
856 description = long_description;
863 if (!(d = strappend(s->sysv_has_lsb ? "LSB: " : "SYSV: ", description))) {
868 u->meta.description = d;
871 /* The priority that has been set in /etc/rcN.d/ hierarchies
872 * takes precedence over what is stored as default in the LSB
874 if (s->sysv_start_priority_from_rcnd >= 0)
875 s->sysv_start_priority = s->sysv_start_priority_from_rcnd;
877 u->meta.load_state = UNIT_LOADED;
885 free(short_description);
886 free(long_description);
887 free(chkconfig_description);
892 static int service_load_sysv_name(Service *s, const char *name) {
898 /* For SysV services we strip the boot.*, rc.* and *.sh
899 * prefixes/suffixes. */
900 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU) || defined(TARGET_ANGSTROM)
901 if (endswith(name, ".sh.service"))
906 if (startswith(name, "boot."))
910 #ifdef TARGET_FRUGALWARE
911 if (startswith(name, "rc."))
915 STRV_FOREACH(p, s->meta.manager->lookup_paths.sysvinit_path) {
919 path = join(*p, "/", name, NULL);
923 assert(endswith(path, ".service"));
924 path[strlen(path)-8] = 0;
926 r = service_load_sysv_path(s, path);
928 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU) || defined(TARGET_ANGSTROM)
929 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
930 /* Try Debian style *.sh source'able init scripts */
932 r = service_load_sysv_path(s, path);
938 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
939 /* Try SUSE style boot.* init scripts */
941 path = join(*p, "/boot.", name, NULL);
945 /* Drop .service suffix */
946 path[strlen(path)-8] = 0;
947 r = service_load_sysv_path(s, path);
952 #ifdef TARGET_FRUGALWARE
953 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
954 /* Try Frugalware style rc.* init scripts */
956 path = join(*p, "/rc.", name, NULL);
960 /* Drop .service suffix */
961 path[strlen(path)-8] = 0;
962 r = service_load_sysv_path(s, path);
970 if ((s->meta.load_state != UNIT_STUB))
977 static int service_load_sysv(Service *s) {
984 /* Load service data from SysV init scripts, preferably with
987 if (strv_isempty(s->meta.manager->lookup_paths.sysvinit_path))
990 if ((t = s->meta.id))
991 if ((r = service_load_sysv_name(s, t)) < 0)
994 if (s->meta.load_state == UNIT_STUB)
995 SET_FOREACH(t, s->meta.names, i) {
999 if ((r = service_load_sysv_name(s, t)) < 0)
1002 if (s->meta.load_state != UNIT_STUB)
1010 static int fsck_fix_order(Service *s) {
1016 if (s->fsck_passno <= 0)
1019 /* For each pair of services where both have an fsck priority
1020 * we order things based on it. */
1022 LIST_FOREACH(units_by_type, other, s->meta.manager->units_by_type[UNIT_SERVICE]) {
1026 t = (Service*) other;
1031 if (t->meta.load_state != UNIT_LOADED)
1034 if (t->fsck_passno <= 0)
1037 if (t->fsck_passno < s->fsck_passno)
1039 else if (t->fsck_passno > s->fsck_passno)
1044 if ((r = unit_add_dependency(UNIT(s), d, UNIT(t), true)) < 0)
1051 static int service_verify(Service *s) {
1054 if (s->meta.load_state != UNIT_LOADED)
1057 if (!s->exec_command[SERVICE_EXEC_START]) {
1058 log_error("%s lacks ExecStart setting. Refusing.", s->meta.id);
1062 if (s->type != SERVICE_ONESHOT &&
1063 s->exec_command[SERVICE_EXEC_START]->command_next) {
1064 log_error("%s has more than one ExecStart setting, which is only allowed for Type=oneshot services. Refusing.", s->meta.id);
1068 if (s->type == SERVICE_ONESHOT &&
1069 s->exec_command[SERVICE_EXEC_RELOAD]) {
1070 log_error("%s has an ExecReload setting, which is not allowed for Type=oneshot services. Refusing.", s->meta.id);
1074 if (s->type == SERVICE_DBUS && !s->bus_name) {
1075 log_error("%s is of type D-Bus but no D-Bus service name has been specified. Refusing.", s->meta.id);
1079 if (s->exec_context.pam_name && s->exec_context.kill_mode != KILL_CONTROL_GROUP) {
1080 log_error("%s has PAM enabled. Kill mode must be set to 'control-group'. Refusing.", s->meta.id);
1087 static int service_add_default_dependencies(Service *s) {
1092 /* Add a number of automatic dependencies useful for the
1093 * majority of services. */
1095 /* First, pull in base system */
1096 if (s->meta.manager->running_as == MANAGER_SYSTEM) {
1098 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_BASIC_TARGET, NULL, true)) < 0)
1101 } else if (s->meta.manager->running_as == MANAGER_USER) {
1103 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SOCKETS_TARGET, NULL, true)) < 0)
1107 /* Second, activate normal shutdown */
1108 return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true);
1111 static void service_fix_output(Service *s) {
1114 /* If nothing has been explicitly configured, patch default
1115 * output in. If input is socket/tty we avoid this however,
1116 * since in that case we want output to default to the same
1117 * place as we read input from. */
1119 if (s->exec_context.std_error == EXEC_OUTPUT_INHERIT &&
1120 s->exec_context.std_output == EXEC_OUTPUT_INHERIT &&
1121 s->exec_context.std_input == EXEC_INPUT_NULL)
1122 s->exec_context.std_error = s->meta.manager->default_std_error;
1124 if (s->exec_context.std_output == EXEC_OUTPUT_INHERIT &&
1125 s->exec_context.std_input == EXEC_INPUT_NULL)
1126 s->exec_context.std_output = s->meta.manager->default_std_output;
1129 static int service_load(Unit *u) {
1131 Service *s = SERVICE(u);
1135 /* Load a .service file */
1136 if ((r = unit_load_fragment(u)) < 0)
1139 #ifdef HAVE_SYSV_COMPAT
1140 /* Load a classic init script as a fallback, if we couldn't find anything */
1141 if (u->meta.load_state == UNIT_STUB)
1142 if ((r = service_load_sysv(s)) < 0)
1146 /* Still nothing found? Then let's give up */
1147 if (u->meta.load_state == UNIT_STUB)
1150 /* We were able to load something, then let's add in the
1151 * dropin directories. */
1152 if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
1155 /* This is a new unit? Then let's add in some extras */
1156 if (u->meta.load_state == UNIT_LOADED) {
1157 service_fix_output(s);
1159 if ((r = unit_add_exec_dependencies(u, &s->exec_context)) < 0)
1162 if ((r = unit_add_default_cgroups(u)) < 0)
1165 #ifdef HAVE_SYSV_COMPAT
1166 if ((r = sysv_fix_order(s)) < 0)
1170 if ((r = fsck_fix_order(s)) < 0)
1174 if ((r = unit_watch_bus_name(u, s->bus_name)) < 0)
1177 if (s->type == SERVICE_NOTIFY && s->notify_access == NOTIFY_NONE)
1178 s->notify_access = NOTIFY_MAIN;
1180 if (s->type == SERVICE_DBUS || s->bus_name)
1181 if ((r = unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_REQUIRES, SPECIAL_DBUS_SOCKET, NULL, true)) < 0)
1184 if (s->meta.default_dependencies)
1185 if ((r = service_add_default_dependencies(s)) < 0)
1189 return service_verify(s);
1192 static void service_dump(Unit *u, FILE *f, const char *prefix) {
1194 ServiceExecCommand c;
1195 Service *s = SERVICE(u);
1196 const char *prefix2;
1201 p2 = strappend(prefix, "\t");
1202 prefix2 = p2 ? p2 : prefix;
1205 "%sService State: %s\n"
1206 "%sPermissionsStartOnly: %s\n"
1207 "%sRootDirectoryStartOnly: %s\n"
1208 "%sRemainAfterExit: %s\n"
1209 "%sGuessMainPID: %s\n"
1212 "%sNotifyAccess: %s\n",
1213 prefix, service_state_to_string(s->state),
1214 prefix, yes_no(s->permissions_start_only),
1215 prefix, yes_no(s->root_directory_start_only),
1216 prefix, yes_no(s->remain_after_exit),
1217 prefix, yes_no(s->guess_main_pid),
1218 prefix, service_type_to_string(s->type),
1219 prefix, service_restart_to_string(s->restart),
1220 prefix, notify_access_to_string(s->notify_access));
1222 if (s->control_pid > 0)
1224 "%sControl PID: %lu\n",
1225 prefix, (unsigned long) s->control_pid);
1227 if (s->main_pid > 0)
1230 "%sMain PID Known: %s\n"
1231 "%sMain PID Alien: %s\n",
1232 prefix, (unsigned long) s->main_pid,
1233 prefix, yes_no(s->main_pid_known),
1234 prefix, yes_no(s->main_pid_alien));
1239 prefix, s->pid_file);
1244 "%sBus Name Good: %s\n",
1245 prefix, s->bus_name,
1246 prefix, yes_no(s->bus_name_good));
1248 exec_context_dump(&s->exec_context, f, prefix);
1250 for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
1252 if (!s->exec_command[c])
1255 fprintf(f, "%s-> %s:\n",
1256 prefix, service_exec_command_to_string(c));
1258 exec_command_dump_list(s->exec_command[c], f, prefix2);
1261 #ifdef HAVE_SYSV_COMPAT
1264 "%sSysV Init Script Path: %s\n"
1265 "%sSysV Init Script has LSB Header: %s\n"
1266 "%sSysVEnabled: %s\n",
1267 prefix, s->sysv_path,
1268 prefix, yes_no(s->sysv_has_lsb),
1269 prefix, yes_no(s->sysv_enabled));
1271 if (s->sysv_start_priority >= 0)
1273 "%sSysVStartPriority: %i\n",
1274 prefix, s->sysv_start_priority);
1276 if (s->sysv_runlevels)
1277 fprintf(f, "%sSysVRunLevels: %s\n",
1278 prefix, s->sysv_runlevels);
1281 if (s->fsck_passno > 0)
1283 "%sFsckPassNo: %i\n",
1284 prefix, s->fsck_passno);
1287 fprintf(f, "%sStatus Text: %s\n",
1288 prefix, s->status_text);
1293 static int service_load_pid_file(Service *s, bool may_warn) {
1303 if ((r = read_one_line_file(s->pid_file, &k)) < 0) {
1305 log_info("PID file %s not readable (yet?) after %s.",
1306 s->pid_file, service_state_to_string(s->state));
1310 r = parse_pid(k, &pid);
1316 if (kill(pid, 0) < 0 && errno != EPERM) {
1318 log_info("PID %lu read from file %s does not exist.",
1319 (unsigned long) pid, s->pid_file);
1323 if (s->main_pid_known) {
1324 if (pid == s->main_pid)
1327 log_debug("Main PID changing: %lu -> %lu",
1328 (unsigned long) s->main_pid, (unsigned long) pid);
1329 service_unwatch_main_pid(s);
1330 s->main_pid_known = false;
1332 log_debug("Main PID loaded: %lu", (unsigned long) pid);
1334 if ((r = service_set_main_pid(s, pid)) < 0)
1337 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1338 /* FIXME: we need to do something here */
1344 static int service_search_main_pid(Service *s) {
1350 /* If we know it anyway, don't ever fallback to unreliable
1352 if (s->main_pid_known)
1355 if (!s->guess_main_pid)
1358 assert(s->main_pid <= 0);
1360 if ((pid = cgroup_bonding_search_main_pid_list(s->meta.cgroup_bondings)) <= 0)
1363 log_debug("Main PID guessed: %lu", (unsigned long) pid);
1364 if ((r = service_set_main_pid(s, pid)) < 0)
1367 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1368 /* FIXME: we need to do something here */
1374 static int service_get_sockets(Service *s, Set **_set) {
1383 if (s->socket_fd >= 0)
1386 if (!set_isempty(s->configured_sockets))
1389 /* Collects all Socket objects that belong to this
1390 * service. Note that a service might have multiple sockets
1391 * via multiple names. */
1393 if (!(set = set_new(NULL, NULL)))
1396 SET_FOREACH(t, s->meta.names, i) {
1400 /* Look for all socket objects that go by any of our
1401 * units and collect their fds */
1403 if (!(k = unit_name_change_suffix(t, ".socket"))) {
1408 p = manager_get_unit(s->meta.manager, k);
1414 if ((r = set_put(set, p)) < 0)
1426 static int service_notify_sockets_dead(Service *s) {
1428 Set *set, *free_set = NULL;
1434 /* Notifies all our sockets when we die */
1436 if (s->socket_fd >= 0)
1439 if (!set_isempty(s->configured_sockets))
1440 set = s->configured_sockets;
1442 if ((r = service_get_sockets(s, &free_set)) < 0)
1448 SET_FOREACH(sock, set, i)
1449 socket_notify_service_dead(sock);
1456 static void service_unwatch_pid_file(Service *s) {
1457 if (!s->pid_file_pathspec)
1460 log_debug("Stopping watch for %s's PID file %s", s->meta.id, s->pid_file_pathspec->path);
1461 pathspec_unwatch(s->pid_file_pathspec, UNIT(s));
1462 pathspec_done(s->pid_file_pathspec);
1463 free(s->pid_file_pathspec);
1464 s->pid_file_pathspec = NULL;
1467 static void service_set_state(Service *s, ServiceState state) {
1468 ServiceState old_state;
1471 old_state = s->state;
1474 service_unwatch_pid_file(s);
1476 if (state != SERVICE_START_PRE &&
1477 state != SERVICE_START &&
1478 state != SERVICE_START_POST &&
1479 state != SERVICE_RELOAD &&
1480 state != SERVICE_STOP &&
1481 state != SERVICE_STOP_SIGTERM &&
1482 state != SERVICE_STOP_SIGKILL &&
1483 state != SERVICE_STOP_POST &&
1484 state != SERVICE_FINAL_SIGTERM &&
1485 state != SERVICE_FINAL_SIGKILL &&
1486 state != SERVICE_AUTO_RESTART)
1487 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1489 if (state != SERVICE_START &&
1490 state != SERVICE_START_POST &&
1491 state != SERVICE_RUNNING &&
1492 state != SERVICE_RELOAD &&
1493 state != SERVICE_STOP &&
1494 state != SERVICE_STOP_SIGTERM &&
1495 state != SERVICE_STOP_SIGKILL) {
1496 service_unwatch_main_pid(s);
1497 s->main_command = NULL;
1500 if (state != SERVICE_START_PRE &&
1501 state != SERVICE_START &&
1502 state != SERVICE_START_POST &&
1503 state != SERVICE_RELOAD &&
1504 state != SERVICE_STOP &&
1505 state != SERVICE_STOP_SIGTERM &&
1506 state != SERVICE_STOP_SIGKILL &&
1507 state != SERVICE_STOP_POST &&
1508 state != SERVICE_FINAL_SIGTERM &&
1509 state != SERVICE_FINAL_SIGKILL) {
1510 service_unwatch_control_pid(s);
1511 s->control_command = NULL;
1512 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1515 if (state == SERVICE_DEAD ||
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_FAILED ||
1523 state == SERVICE_AUTO_RESTART)
1524 service_notify_sockets_dead(s);
1526 if (state != SERVICE_START_PRE &&
1527 state != SERVICE_START &&
1528 state != SERVICE_START_POST &&
1529 state != SERVICE_RUNNING &&
1530 state != SERVICE_RELOAD &&
1531 state != SERVICE_STOP &&
1532 state != SERVICE_STOP_SIGTERM &&
1533 state != SERVICE_STOP_SIGKILL &&
1534 state != SERVICE_STOP_POST &&
1535 state != SERVICE_FINAL_SIGTERM &&
1536 state != SERVICE_FINAL_SIGKILL &&
1537 !(state == SERVICE_DEAD && s->meta.job)) {
1538 service_close_socket_fd(s);
1539 service_connection_unref(s);
1542 /* For the inactive states unit_notify() will trim the cgroup,
1543 * but for exit we have to do that ourselves... */
1544 if (state == SERVICE_EXITED && s->meta.manager->n_reloading <= 0)
1545 cgroup_bonding_trim_list(s->meta.cgroup_bondings, true);
1547 if (old_state != state)
1548 log_debug("%s changed %s -> %s", s->meta.id, service_state_to_string(old_state), service_state_to_string(state));
1550 unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state], !s->reload_failure);
1551 s->reload_failure = false;
1554 static int service_coldplug(Unit *u) {
1555 Service *s = SERVICE(u);
1559 assert(s->state == SERVICE_DEAD);
1561 if (s->deserialized_state != s->state) {
1563 if (s->deserialized_state == SERVICE_START_PRE ||
1564 s->deserialized_state == SERVICE_START ||
1565 s->deserialized_state == SERVICE_START_POST ||
1566 s->deserialized_state == SERVICE_RELOAD ||
1567 s->deserialized_state == SERVICE_STOP ||
1568 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1569 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1570 s->deserialized_state == SERVICE_STOP_POST ||
1571 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1572 s->deserialized_state == SERVICE_FINAL_SIGKILL ||
1573 s->deserialized_state == SERVICE_AUTO_RESTART) {
1575 if (s->deserialized_state == SERVICE_AUTO_RESTART || s->timeout_usec > 0) {
1578 k = s->deserialized_state == SERVICE_AUTO_RESTART ? s->restart_usec : s->timeout_usec;
1580 if ((r = unit_watch_timer(UNIT(s), k, &s->timer_watch)) < 0)
1585 if ((s->deserialized_state == SERVICE_START &&
1586 (s->type == SERVICE_FORKING ||
1587 s->type == SERVICE_DBUS ||
1588 s->type == SERVICE_ONESHOT ||
1589 s->type == SERVICE_NOTIFY)) ||
1590 s->deserialized_state == SERVICE_START_POST ||
1591 s->deserialized_state == SERVICE_RUNNING ||
1592 s->deserialized_state == SERVICE_RELOAD ||
1593 s->deserialized_state == SERVICE_STOP ||
1594 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1595 s->deserialized_state == SERVICE_STOP_SIGKILL)
1596 if (s->main_pid > 0)
1597 if ((r = unit_watch_pid(UNIT(s), s->main_pid)) < 0)
1600 if (s->deserialized_state == SERVICE_START_PRE ||
1601 s->deserialized_state == SERVICE_START ||
1602 s->deserialized_state == SERVICE_START_POST ||
1603 s->deserialized_state == SERVICE_RELOAD ||
1604 s->deserialized_state == SERVICE_STOP ||
1605 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1606 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1607 s->deserialized_state == SERVICE_STOP_POST ||
1608 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1609 s->deserialized_state == SERVICE_FINAL_SIGKILL)
1610 if (s->control_pid > 0)
1611 if ((r = unit_watch_pid(UNIT(s), s->control_pid)) < 0)
1614 service_set_state(s, s->deserialized_state);
1620 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
1624 unsigned rn_fds = 0;
1625 Set *set, *free_set = NULL;
1632 if (s->socket_fd >= 0)
1635 if (!set_isempty(s->configured_sockets))
1636 set = s->configured_sockets;
1638 if ((r = service_get_sockets(s, &free_set)) < 0)
1644 SET_FOREACH(sock, set, i) {
1648 if ((r = socket_collect_fds(sock, &cfds, &cn_fds)) < 0)
1660 if (!(t = new(int, rn_fds+cn_fds))) {
1666 memcpy(t, rfds, rn_fds * sizeof(int));
1667 memcpy(t+rn_fds, cfds, cn_fds * sizeof(int));
1672 rn_fds = rn_fds+cn_fds;
1690 static int service_spawn(
1695 bool apply_permissions,
1697 bool apply_tty_stdin,
1698 bool set_notify_socket,
1703 int *fds = NULL, *fdsbuf = NULL;
1704 unsigned n_fds = 0, n_env = 0;
1705 char **argv = NULL, **final_env = NULL, **our_env = NULL;
1712 s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1713 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1714 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
1716 if (s->socket_fd >= 0) {
1717 fds = &s->socket_fd;
1720 if ((r = service_collect_fds(s, &fdsbuf, &n_fds)) < 0)
1727 if (timeout && s->timeout_usec) {
1728 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1731 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1733 if (!(argv = unit_full_printf_strv(UNIT(s), c->argv))) {
1738 if (!(our_env = new0(char*, 4))) {
1743 if (set_notify_socket)
1744 if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=%s", s->meta.manager->notify_socket) < 0) {
1749 if (s->main_pid > 0)
1750 if (asprintf(our_env + n_env++, "MAINPID=%lu", (unsigned long) s->main_pid) < 0) {
1755 if (!(final_env = strv_env_merge(2,
1756 s->meta.manager->environment,
1771 s->meta.manager->confirm_spawn,
1772 s->meta.cgroup_bondings,
1773 s->meta.cgroup_attributes,
1780 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1781 /* FIXME: we need to do something here */
1787 strv_free(final_env);
1797 strv_free(final_env);
1800 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1805 static int main_pid_good(Service *s) {
1808 /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1811 /* If we know the pid file, then lets just check if it is
1813 if (s->main_pid_known) {
1815 /* If it's an alien child let's check if it is still
1817 if (s->main_pid_alien)
1818 return kill(s->main_pid, 0) >= 0 || errno != ESRCH;
1820 /* .. otherwise assume we'll get a SIGCHLD for it,
1821 * which we really should wait for to collect exit
1822 * status and code */
1823 return s->main_pid > 0;
1826 /* We don't know the pid */
1830 static int control_pid_good(Service *s) {
1833 return s->control_pid > 0;
1836 static int cgroup_good(Service *s) {
1841 if ((r = cgroup_bonding_is_empty_list(s->meta.cgroup_bondings)) < 0)
1847 static void service_enter_dead(Service *s, bool success, bool allow_restart) {
1854 if (allow_restart &&
1855 !s->forbid_restart &&
1856 (s->restart == SERVICE_RESTART_ALWAYS ||
1857 (s->restart == SERVICE_RESTART_ON_SUCCESS && !s->failure) ||
1858 (s->restart == SERVICE_RESTART_ON_FAILURE && s->failure) ||
1859 (s->restart == SERVICE_RESTART_ON_ABORT && s->failure &&
1860 (s->main_exec_status.code == CLD_KILLED ||
1861 s->main_exec_status.code == CLD_DUMPED)))) {
1863 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
1866 service_set_state(s, SERVICE_AUTO_RESTART);
1868 service_set_state(s, s->failure ? SERVICE_FAILED : SERVICE_DEAD);
1870 s->forbid_restart = false;
1875 log_warning("%s failed to run install restart timer: %s", s->meta.id, strerror(-r));
1876 service_enter_dead(s, false, false);
1879 static void service_enter_signal(Service *s, ServiceState state, bool success);
1881 static void service_enter_stop_post(Service *s, bool success) {
1888 service_unwatch_control_pid(s);
1890 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST])) {
1891 s->control_command_id = SERVICE_EXEC_STOP_POST;
1893 if ((r = service_spawn(s,
1897 !s->permissions_start_only,
1898 !s->root_directory_start_only,
1901 &s->control_pid)) < 0)
1905 service_set_state(s, SERVICE_STOP_POST);
1907 service_enter_signal(s, SERVICE_FINAL_SIGTERM, true);
1912 log_warning("%s failed to run 'stop-post' task: %s", s->meta.id, strerror(-r));
1913 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1916 static void service_enter_signal(Service *s, ServiceState state, bool success) {
1918 Set *pid_set = NULL;
1919 bool wait_for_exit = false;
1926 if (s->exec_context.kill_mode != KILL_NONE) {
1927 int sig = (state == SERVICE_STOP_SIGTERM || state == SERVICE_FINAL_SIGTERM) ? s->exec_context.kill_signal : SIGKILL;
1929 if (s->main_pid > 0) {
1930 if (kill_and_sigcont(s->main_pid, sig) < 0 && errno != ESRCH)
1931 log_warning("Failed to kill main process %li: %m", (long) s->main_pid);
1933 wait_for_exit = !s->main_pid_alien;
1936 if (s->control_pid > 0) {
1937 if (kill_and_sigcont(s->control_pid, sig) < 0 && errno != ESRCH)
1938 log_warning("Failed to kill control process %li: %m", (long) s->control_pid);
1940 wait_for_exit = true;
1943 if (s->exec_context.kill_mode == KILL_CONTROL_GROUP) {
1945 if (!(pid_set = set_new(trivial_hash_func, trivial_compare_func))) {
1950 /* Exclude the main/control pids from being killed via the cgroup */
1951 if (s->main_pid > 0)
1952 if ((r = set_put(pid_set, LONG_TO_PTR(s->main_pid))) < 0)
1955 if (s->control_pid > 0)
1956 if ((r = set_put(pid_set, LONG_TO_PTR(s->control_pid))) < 0)
1959 if ((r = cgroup_bonding_kill_list(s->meta.cgroup_bondings, sig, true, pid_set)) < 0) {
1960 if (r != -EAGAIN && r != -ESRCH && r != -ENOENT)
1961 log_warning("Failed to kill control group: %s", strerror(-r));
1963 wait_for_exit = true;
1970 if (wait_for_exit) {
1971 if (s->timeout_usec > 0)
1972 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1975 service_set_state(s, state);
1976 } else if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1977 service_enter_stop_post(s, true);
1979 service_enter_dead(s, true, true);
1984 log_warning("%s failed to kill processes: %s", s->meta.id, strerror(-r));
1986 if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1987 service_enter_stop_post(s, false);
1989 service_enter_dead(s, false, true);
1995 static void service_enter_stop(Service *s, bool success) {
2003 service_unwatch_control_pid(s);
2005 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP])) {
2006 s->control_command_id = SERVICE_EXEC_STOP;
2008 if ((r = service_spawn(s,
2012 !s->permissions_start_only,
2013 !s->root_directory_start_only,
2016 &s->control_pid)) < 0)
2019 service_set_state(s, SERVICE_STOP);
2021 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
2026 log_warning("%s failed to run 'stop' task: %s", s->meta.id, strerror(-r));
2027 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
2030 static void service_enter_running(Service *s, bool success) {
2031 int main_pid_ok, cgroup_ok;
2037 main_pid_ok = main_pid_good(s);
2038 cgroup_ok = cgroup_good(s);
2040 if ((main_pid_ok > 0 || (main_pid_ok < 0 && cgroup_ok != 0)) &&
2041 (s->bus_name_good || s->type != SERVICE_DBUS))
2042 service_set_state(s, SERVICE_RUNNING);
2043 else if (s->remain_after_exit)
2044 service_set_state(s, SERVICE_EXITED);
2046 service_enter_stop(s, true);
2049 static void service_enter_start_post(Service *s) {
2053 service_unwatch_control_pid(s);
2055 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_POST])) {
2056 s->control_command_id = SERVICE_EXEC_START_POST;
2058 if ((r = service_spawn(s,
2062 !s->permissions_start_only,
2063 !s->root_directory_start_only,
2066 &s->control_pid)) < 0)
2069 service_set_state(s, SERVICE_START_POST);
2071 service_enter_running(s, true);
2076 log_warning("%s failed to run 'start-post' task: %s", s->meta.id, strerror(-r));
2077 service_enter_stop(s, false);
2080 static void service_enter_start(Service *s) {
2087 assert(s->exec_command[SERVICE_EXEC_START]);
2088 assert(!s->exec_command[SERVICE_EXEC_START]->command_next || s->type == SERVICE_ONESHOT);
2090 if (s->type == SERVICE_FORKING)
2091 service_unwatch_control_pid(s);
2093 service_unwatch_main_pid(s);
2095 if (s->type == SERVICE_FORKING) {
2096 s->control_command_id = SERVICE_EXEC_START;
2097 c = s->control_command = s->exec_command[SERVICE_EXEC_START];
2099 s->main_command = NULL;
2101 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2102 s->control_command = NULL;
2104 c = s->main_command = s->exec_command[SERVICE_EXEC_START];
2107 if ((r = service_spawn(s,
2109 s->type == SERVICE_FORKING || s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY,
2114 s->notify_access != NOTIFY_NONE,
2118 if (s->type == SERVICE_SIMPLE) {
2119 /* For simple services we immediately start
2120 * the START_POST binaries. */
2122 service_set_main_pid(s, pid);
2123 service_enter_start_post(s);
2125 } else if (s->type == SERVICE_FORKING) {
2127 /* For forking services we wait until the start
2128 * process exited. */
2130 s->control_pid = pid;
2131 service_set_state(s, SERVICE_START);
2133 } else if (s->type == SERVICE_ONESHOT ||
2134 s->type == SERVICE_DBUS ||
2135 s->type == SERVICE_NOTIFY) {
2137 /* For oneshot services we wait until the start
2138 * process exited, too, but it is our main process. */
2140 /* For D-Bus services we know the main pid right away,
2141 * but wait for the bus name to appear on the
2142 * bus. Notify services are similar. */
2144 service_set_main_pid(s, pid);
2145 service_set_state(s, SERVICE_START);
2147 assert_not_reached("Unknown service type");
2152 log_warning("%s failed to run 'start' task: %s", s->meta.id, strerror(-r));
2153 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2156 static void service_enter_start_pre(Service *s) {
2161 service_unwatch_control_pid(s);
2163 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_PRE])) {
2164 s->control_command_id = SERVICE_EXEC_START_PRE;
2166 if ((r = service_spawn(s,
2170 !s->permissions_start_only,
2171 !s->root_directory_start_only,
2174 &s->control_pid)) < 0)
2177 service_set_state(s, SERVICE_START_PRE);
2179 service_enter_start(s);
2184 log_warning("%s failed to run 'start-pre' task: %s", s->meta.id, strerror(-r));
2185 service_enter_dead(s, false, true);
2188 static void service_enter_restart(Service *s) {
2193 dbus_error_init(&error);
2196 log_info("Job pending for unit, delaying automatic restart.");
2198 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
2202 service_enter_dead(s, true, false);
2204 if ((r = manager_add_job(s->meta.manager, JOB_START, UNIT(s), JOB_FAIL, false, &error, NULL)) < 0)
2207 log_debug("%s scheduled restart job.", s->meta.id);
2211 log_warning("%s failed to schedule restart job: %s", s->meta.id, bus_error(&error, -r));
2212 service_enter_dead(s, false, false);
2214 dbus_error_free(&error);
2217 static void service_enter_reload(Service *s) {
2222 service_unwatch_control_pid(s);
2224 if ((s->control_command = s->exec_command[SERVICE_EXEC_RELOAD])) {
2225 s->control_command_id = SERVICE_EXEC_RELOAD;
2227 if ((r = service_spawn(s,
2231 !s->permissions_start_only,
2232 !s->root_directory_start_only,
2235 &s->control_pid)) < 0)
2238 service_set_state(s, SERVICE_RELOAD);
2240 service_enter_running(s, true);
2245 log_warning("%s failed to run 'reload' task: %s", s->meta.id, strerror(-r));
2246 s->reload_failure = true;
2247 service_enter_running(s, true);
2250 static void service_run_next_control(Service *s, bool success) {
2254 assert(s->control_command);
2255 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", s->meta.id, strerror(-r));
2282 if (s->state == SERVICE_START_PRE)
2283 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2284 else if (s->state == SERVICE_STOP)
2285 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
2286 else if (s->state == SERVICE_STOP_POST)
2287 service_enter_dead(s, false, true);
2288 else if (s->state == SERVICE_RELOAD) {
2289 s->reload_failure = true;
2290 service_enter_running(s, true);
2292 service_enter_stop(s, false);
2295 static void service_run_next_main(Service *s, bool success) {
2300 assert(s->main_command);
2301 assert(s->main_command->command_next);
2302 assert(s->type == SERVICE_ONESHOT);
2307 s->main_command = s->main_command->command_next;
2308 service_unwatch_main_pid(s);
2310 if ((r = service_spawn(s,
2317 s->notify_access != NOTIFY_NONE,
2321 service_set_main_pid(s, pid);
2326 log_warning("%s failed to run next main task: %s", s->meta.id, strerror(-r));
2327 service_enter_stop(s, false);
2330 static int service_start(Unit *u) {
2331 Service *s = SERVICE(u);
2335 /* We cannot fulfill this request right now, try again later
2337 if (s->state == SERVICE_STOP ||
2338 s->state == SERVICE_STOP_SIGTERM ||
2339 s->state == SERVICE_STOP_SIGKILL ||
2340 s->state == SERVICE_STOP_POST ||
2341 s->state == SERVICE_FINAL_SIGTERM ||
2342 s->state == SERVICE_FINAL_SIGKILL)
2345 /* Already on it! */
2346 if (s->state == SERVICE_START_PRE ||
2347 s->state == SERVICE_START ||
2348 s->state == SERVICE_START_POST)
2351 assert(s->state == SERVICE_DEAD || s->state == SERVICE_FAILED || s->state == SERVICE_AUTO_RESTART);
2353 /* Make sure we don't enter a busy loop of some kind. */
2354 if (!ratelimit_test(&s->ratelimit)) {
2355 log_warning("%s start request repeated too quickly, refusing to start.", u->meta.id);
2360 s->main_pid_known = false;
2361 s->main_pid_alien = false;
2362 s->forbid_restart = false;
2364 service_enter_start_pre(s);
2368 static int service_stop(Unit *u) {
2369 Service *s = SERVICE(u);
2373 /* This is a user request, so don't do restarts on this
2375 s->forbid_restart = true;
2378 if (s->state == SERVICE_STOP ||
2379 s->state == SERVICE_STOP_SIGTERM ||
2380 s->state == SERVICE_STOP_SIGKILL ||
2381 s->state == SERVICE_STOP_POST ||
2382 s->state == SERVICE_FINAL_SIGTERM ||
2383 s->state == SERVICE_FINAL_SIGKILL)
2386 /* Don't allow a restart */
2387 if (s->state == SERVICE_AUTO_RESTART) {
2388 service_set_state(s, SERVICE_DEAD);
2392 /* If there's already something running we go directly into
2394 if (s->state == SERVICE_START_PRE ||
2395 s->state == SERVICE_START ||
2396 s->state == SERVICE_START_POST ||
2397 s->state == SERVICE_RELOAD) {
2398 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
2402 assert(s->state == SERVICE_RUNNING ||
2403 s->state == SERVICE_EXITED);
2405 service_enter_stop(s, true);
2409 static int service_reload(Unit *u) {
2410 Service *s = SERVICE(u);
2414 assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
2416 service_enter_reload(s);
2420 static bool service_can_reload(Unit *u) {
2421 Service *s = SERVICE(u);
2425 return !!s->exec_command[SERVICE_EXEC_RELOAD];
2428 static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
2429 Service *s = SERVICE(u);
2435 unit_serialize_item(u, f, "state", service_state_to_string(s->state));
2436 unit_serialize_item(u, f, "failure", yes_no(s->failure));
2438 if (s->control_pid > 0)
2439 unit_serialize_item_format(u, f, "control-pid", "%lu", (unsigned long) s->control_pid);
2441 if (s->main_pid_known && s->main_pid > 0)
2442 unit_serialize_item_format(u, f, "main-pid", "%lu", (unsigned long) s->main_pid);
2444 unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
2447 unit_serialize_item(u, f, "status-text", s->status_text);
2449 /* There's a minor uncleanliness here: if there are multiple
2450 * commands attached here, we will start from the first one
2452 if (s->control_command_id >= 0)
2453 unit_serialize_item(u, f, "control-command", service_exec_command_to_string(s->control_command_id));
2455 if (s->socket_fd >= 0) {
2458 if ((copy = fdset_put_dup(fds, s->socket_fd)) < 0)
2461 unit_serialize_item_format(u, f, "socket-fd", "%i", copy);
2464 if (s->main_exec_status.pid > 0) {
2465 unit_serialize_item_format(u, f, "main-exec-status-pid", "%lu", (unsigned long) s->main_exec_status.pid);
2466 dual_timestamp_serialize(f, "main-exec-status-start", &s->main_exec_status.start_timestamp);
2467 dual_timestamp_serialize(f, "main-exec-status-exit", &s->main_exec_status.exit_timestamp);
2469 if (dual_timestamp_is_set(&s->main_exec_status.exit_timestamp)) {
2470 unit_serialize_item_format(u, f, "main-exec-status-code", "%i", s->main_exec_status.code);
2471 unit_serialize_item_format(u, f, "main-exec-status-status", "%i", s->main_exec_status.status);
2478 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
2479 Service *s = SERVICE(u);
2486 if (streq(key, "state")) {
2489 if ((state = service_state_from_string(value)) < 0)
2490 log_debug("Failed to parse state value %s", value);
2492 s->deserialized_state = state;
2493 } else if (streq(key, "failure")) {
2496 if ((b = parse_boolean(value)) < 0)
2497 log_debug("Failed to parse failure value %s", value);
2499 s->failure = b || s->failure;
2500 } else if (streq(key, "control-pid")) {
2503 if (parse_pid(value, &pid) < 0)
2504 log_debug("Failed to parse control-pid value %s", value);
2506 s->control_pid = pid;
2507 } else if (streq(key, "main-pid")) {
2510 if (parse_pid(value, &pid) < 0)
2511 log_debug("Failed to parse main-pid value %s", value);
2513 service_set_main_pid(s, (pid_t) pid);
2514 } else if (streq(key, "main-pid-known")) {
2517 if ((b = parse_boolean(value)) < 0)
2518 log_debug("Failed to parse main-pid-known value %s", value);
2520 s->main_pid_known = b;
2521 } else if (streq(key, "status-text")) {
2524 if ((t = strdup(value))) {
2525 free(s->status_text);
2529 } else if (streq(key, "control-command")) {
2530 ServiceExecCommand id;
2532 if ((id = service_exec_command_from_string(value)) < 0)
2533 log_debug("Failed to parse exec-command value %s", value);
2535 s->control_command_id = id;
2536 s->control_command = s->exec_command[id];
2538 } else if (streq(key, "socket-fd")) {
2541 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2542 log_debug("Failed to parse socket-fd value %s", value);
2545 if (s->socket_fd >= 0)
2546 close_nointr_nofail(s->socket_fd);
2547 s->socket_fd = fdset_remove(fds, fd);
2549 } else if (streq(key, "main-exec-status-pid")) {
2552 if (parse_pid(value, &pid) < 0)
2553 log_debug("Failed to parse main-exec-status-pid value %s", value);
2555 s->main_exec_status.pid = pid;
2556 } else if (streq(key, "main-exec-status-code")) {
2559 if (safe_atoi(value, &i) < 0)
2560 log_debug("Failed to parse main-exec-status-code value %s", value);
2562 s->main_exec_status.code = i;
2563 } else if (streq(key, "main-exec-status-status")) {
2566 if (safe_atoi(value, &i) < 0)
2567 log_debug("Failed to parse main-exec-status-status value %s", value);
2569 s->main_exec_status.status = i;
2570 } else if (streq(key, "main-exec-status-start"))
2571 dual_timestamp_deserialize(value, &s->main_exec_status.start_timestamp);
2572 else if (streq(key, "main-exec-status-exit"))
2573 dual_timestamp_deserialize(value, &s->main_exec_status.exit_timestamp);
2575 log_debug("Unknown serialization key '%s'", key);
2580 static UnitActiveState service_active_state(Unit *u) {
2583 return state_translation_table[SERVICE(u)->state];
2586 static const char *service_sub_state_to_string(Unit *u) {
2589 return service_state_to_string(SERVICE(u)->state);
2592 static bool service_check_gc(Unit *u) {
2593 Service *s = SERVICE(u);
2597 /* Never clean up services that still have a process around,
2598 * even if the service is formally dead. */
2599 if (cgroup_good(s) > 0 ||
2600 main_pid_good(s) > 0 ||
2601 control_pid_good(s) > 0)
2604 #ifdef HAVE_SYSV_COMPAT
2612 static bool service_check_snapshot(Unit *u) {
2613 Service *s = SERVICE(u);
2617 return !s->got_socket_fd;
2620 static int service_retry_pid_file(Service *s) {
2623 assert(s->pid_file);
2624 assert(s->state == SERVICE_START || s->state == SERVICE_START_POST);
2626 r = service_load_pid_file(s, false);
2630 service_unwatch_pid_file(s);
2632 service_enter_running(s, true);
2636 static int service_watch_pid_file(Service *s) {
2639 log_debug("Setting watch for %s's PID file %s", s->meta.id, s->pid_file_pathspec->path);
2640 r = pathspec_watch(s->pid_file_pathspec, UNIT(s));
2644 /* the pidfile might have appeared just before we set the watch */
2645 service_retry_pid_file(s);
2649 log_error("Failed to set a watch for %s's PID file %s: %s",
2650 s->meta.id, s->pid_file_pathspec->path, strerror(-r));
2651 service_unwatch_pid_file(s);
2655 static int service_demand_pid_file(Service *s) {
2658 assert(s->pid_file);
2659 assert(!s->pid_file_pathspec);
2661 ps = new0(PathSpec, 1);
2665 ps->path = strdup(s->pid_file);
2671 path_kill_slashes(ps->path);
2673 /* PATH_CHANGED would not be enough. There are daemons (sendmail) that
2674 * keep their PID file open all the time. */
2675 ps->type = PATH_MODIFIED;
2676 ps->inotify_fd = -1;
2678 s->pid_file_pathspec = ps;
2680 return service_watch_pid_file(s);
2683 static void service_fd_event(Unit *u, int fd, uint32_t events, Watch *w) {
2684 Service *s = SERVICE(u);
2688 assert(s->state == SERVICE_START || s->state == SERVICE_START_POST);
2689 assert(s->pid_file_pathspec);
2690 assert(pathspec_owns_inotify_fd(s->pid_file_pathspec, fd));
2692 log_debug("inotify event for %s", u->meta.id);
2694 if (pathspec_fd_event(s->pid_file_pathspec, events) < 0)
2697 if (service_retry_pid_file(s) == 0)
2700 if (service_watch_pid_file(s) < 0)
2705 service_unwatch_pid_file(s);
2706 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
2709 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2710 Service *s = SERVICE(u);
2716 if (!s->meta.fragment_path)
2717 success = is_clean_exit_lsb(code, status);
2719 success = is_clean_exit(code, status);
2721 if (s->main_pid == pid) {
2722 /* Forking services may occasionally move to a new PID.
2723 * As long as they update the PID file before exiting the old
2724 * PID, they're fine. */
2725 if (service_load_pid_file(s, false) == 0)
2729 exec_status_exit(&s->main_exec_status, &s->exec_context, pid, code, status);
2731 /* If this is not a forking service than the main
2732 * process got started and hence we copy the exit
2733 * status so that it is recorded both as main and as
2734 * control process exit status */
2735 if (s->main_command) {
2736 s->main_command->exec_status = s->main_exec_status;
2738 if (s->main_command->ignore)
2742 log_full(success ? LOG_DEBUG : LOG_NOTICE,
2743 "%s: main process exited, code=%s, status=%i", u->meta.id, sigchld_code_to_string(code), status);
2744 s->failure = s->failure || !success;
2746 if (s->main_command &&
2747 s->main_command->command_next &&
2750 /* There is another command to *
2751 * execute, so let's do that. */
2753 log_debug("%s running next main command for state %s", u->meta.id, service_state_to_string(s->state));
2754 service_run_next_main(s, success);
2758 /* The service exited, so the service is officially
2760 s->main_command = NULL;
2764 case SERVICE_START_POST:
2765 case SERVICE_RELOAD:
2767 /* Need to wait until the operation is
2772 if (s->type == SERVICE_ONESHOT) {
2773 /* This was our main goal, so let's go on */
2775 service_enter_start_post(s);
2777 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2780 assert(s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY);
2785 case SERVICE_RUNNING:
2786 service_enter_running(s, success);
2789 case SERVICE_STOP_SIGTERM:
2790 case SERVICE_STOP_SIGKILL:
2792 if (!control_pid_good(s))
2793 service_enter_stop_post(s, success);
2795 /* If there is still a control process, wait for that first */
2799 assert_not_reached("Uh, main process died at wrong time.");
2803 } else if (s->control_pid == pid) {
2807 if (s->control_command) {
2808 exec_status_exit(&s->control_command->exec_status, &s->exec_context, pid, code, status);
2810 if (s->control_command->ignore)
2814 log_full(success ? LOG_DEBUG : LOG_NOTICE,
2815 "%s: control process exited, code=%s status=%i", u->meta.id, sigchld_code_to_string(code), status);
2816 s->failure = s->failure || !success;
2818 if (s->control_command &&
2819 s->control_command->command_next &&
2822 /* There is another command to *
2823 * execute, so let's do that. */
2825 log_debug("%s running next control command for state %s", u->meta.id, service_state_to_string(s->state));
2826 service_run_next_control(s, success);
2829 /* No further commands for this step, so let's
2830 * figure out what to do next */
2832 s->control_command = NULL;
2833 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2835 log_debug("%s got final SIGCHLD for state %s", u->meta.id, service_state_to_string(s->state));
2839 case SERVICE_START_PRE:
2841 service_enter_start(s);
2843 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2847 assert(s->type == SERVICE_FORKING);
2850 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2855 /* Let's try to load the pid file here if we can.
2856 * The PID file might actually be created by a START_POST
2857 * script. In that case don't worry if the loading fails. */
2858 bool has_start_post = !!s->exec_command[SERVICE_EXEC_START_POST];
2859 int r = service_load_pid_file(s, !has_start_post);
2860 if (!has_start_post && r < 0) {
2861 r = service_demand_pid_file(s);
2862 if (r < 0 || !cgroup_good(s))
2863 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2867 service_search_main_pid(s);
2869 service_enter_start_post(s);
2872 case SERVICE_START_POST:
2874 service_enter_stop(s, false);
2879 int r = service_load_pid_file(s, true);
2881 r = service_demand_pid_file(s);
2882 if (r < 0 || !cgroup_good(s))
2883 service_enter_stop(s, false);
2887 service_search_main_pid(s);
2889 service_enter_running(s, true);
2892 case SERVICE_RELOAD:
2894 service_load_pid_file(s, true);
2895 service_search_main_pid(s);
2898 s->reload_failure = !success;
2899 service_enter_running(s, true);
2903 service_enter_signal(s, SERVICE_STOP_SIGTERM, success);
2906 case SERVICE_STOP_SIGTERM:
2907 case SERVICE_STOP_SIGKILL:
2908 if (main_pid_good(s) <= 0)
2909 service_enter_stop_post(s, success);
2911 /* If there is still a service
2912 * process around, wait until
2913 * that one quit, too */
2916 case SERVICE_STOP_POST:
2917 case SERVICE_FINAL_SIGTERM:
2918 case SERVICE_FINAL_SIGKILL:
2919 service_enter_dead(s, success, true);
2923 assert_not_reached("Uh, control process died at wrong time.");
2928 /* Notify clients about changed exit status */
2929 unit_add_to_dbus_queue(u);
2932 static void service_timer_event(Unit *u, uint64_t elapsed, Watch* w) {
2933 Service *s = SERVICE(u);
2936 assert(elapsed == 1);
2938 assert(w == &s->timer_watch);
2942 case SERVICE_START_PRE:
2944 log_warning("%s operation timed out. Terminating.", u->meta.id);
2945 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2948 case SERVICE_START_POST:
2949 log_warning("%s operation timed out. Stopping.", u->meta.id);
2950 service_enter_stop(s, false);
2953 case SERVICE_RELOAD:
2954 log_warning("%s operation timed out. Stopping.", u->meta.id);
2955 s->reload_failure = true;
2956 service_enter_running(s, true);
2960 log_warning("%s stopping timed out. Terminating.", u->meta.id);
2961 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
2964 case SERVICE_STOP_SIGTERM:
2965 if (s->exec_context.send_sigkill) {
2966 log_warning("%s stopping timed out. Killing.", u->meta.id);
2967 service_enter_signal(s, SERVICE_STOP_SIGKILL, false);
2969 log_warning("%s stopping timed out. Skipping SIGKILL.", u->meta.id);
2970 service_enter_stop_post(s, false);
2975 case SERVICE_STOP_SIGKILL:
2976 /* Uh, we sent a SIGKILL and it is still not gone?
2977 * Must be something we cannot kill, so let's just be
2978 * weirded out and continue */
2980 log_warning("%s still around after SIGKILL. Ignoring.", u->meta.id);
2981 service_enter_stop_post(s, false);
2984 case SERVICE_STOP_POST:
2985 log_warning("%s stopping timed out (2). Terminating.", u->meta.id);
2986 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2989 case SERVICE_FINAL_SIGTERM:
2990 if (s->exec_context.send_sigkill) {
2991 log_warning("%s stopping timed out (2). Killing.", u->meta.id);
2992 service_enter_signal(s, SERVICE_FINAL_SIGKILL, false);
2994 log_warning("%s stopping timed out (2). Skipping SIGKILL. Entering failed mode.", u->meta.id);
2995 service_enter_dead(s, false, true);
3000 case SERVICE_FINAL_SIGKILL:
3001 log_warning("%s still around after SIGKILL (2). Entering failed mode.", u->meta.id);
3002 service_enter_dead(s, false, true);
3005 case SERVICE_AUTO_RESTART:
3006 log_info("%s holdoff time over, scheduling restart.", u->meta.id);
3007 service_enter_restart(s);
3011 assert_not_reached("Timeout at wrong time.");
3015 static void service_cgroup_notify_event(Unit *u) {
3016 Service *s = SERVICE(u);
3020 log_debug("%s: cgroup is empty", u->meta.id);
3024 /* Waiting for SIGCHLD is usually more interesting,
3025 * because it includes return codes/signals. Which is
3026 * why we ignore the cgroup events for most cases,
3027 * except when we don't know pid which to expect the
3031 case SERVICE_START_POST:
3032 /* If we were hoping for the daemon to write its PID file,
3033 * we can give up now. */
3034 if (s->pid_file_pathspec) {
3035 log_warning("%s never wrote its PID file. Failing.", s->meta.id);
3036 service_unwatch_pid_file(s);
3037 if (s->state == SERVICE_START)
3038 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
3040 service_enter_stop(s, false);
3044 case SERVICE_RUNNING:
3045 service_enter_running(s, true);
3048 case SERVICE_STOP_SIGTERM:
3049 case SERVICE_STOP_SIGKILL:
3051 if (main_pid_good(s) <= 0 && !control_pid_good(s))
3052 service_enter_stop_post(s, true);
3056 case SERVICE_FINAL_SIGTERM:
3057 case SERVICE_FINAL_SIGKILL:
3058 if (main_pid_good(s) <= 0 && !control_pid_good(s))
3059 service_enter_dead(s, true, true);
3068 static void service_notify_message(Unit *u, pid_t pid, char **tags) {
3069 Service *s = SERVICE(u);
3074 if (s->notify_access == NOTIFY_NONE) {
3075 log_warning("%s: Got notification message from PID %lu, but reception is disabled.",
3076 u->meta.id, (unsigned long) pid);
3080 if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
3081 log_warning("%s: Got notification message from PID %lu, but reception only permitted for PID %lu",
3082 u->meta.id, (unsigned long) pid, (unsigned long) s->main_pid);
3086 log_debug("%s: Got message", u->meta.id);
3088 /* Interpret MAINPID= */
3089 if ((e = strv_find_prefix(tags, "MAINPID=")) &&
3090 (s->state == SERVICE_START ||
3091 s->state == SERVICE_START_POST ||
3092 s->state == SERVICE_RUNNING ||
3093 s->state == SERVICE_RELOAD)) {
3095 if (parse_pid(e + 8, &pid) < 0)
3096 log_warning("Failed to parse notification message %s", e);
3098 log_debug("%s: got %s", u->meta.id, e);
3099 service_set_main_pid(s, pid);
3103 /* Interpret READY= */
3104 if (s->type == SERVICE_NOTIFY &&
3105 s->state == SERVICE_START &&
3106 strv_find(tags, "READY=1")) {
3107 log_debug("%s: got READY=1", u->meta.id);
3109 service_enter_start_post(s);
3112 /* Interpret STATUS= */
3113 if ((e = strv_find_prefix(tags, "STATUS="))) {
3117 if (!(t = strdup(e+7))) {
3118 log_error("Failed to allocate string.");
3122 log_debug("%s: got %s", u->meta.id, e);
3124 free(s->status_text);
3127 free(s->status_text);
3128 s->status_text = NULL;
3133 /* Notify clients about changed status or main pid */
3134 unit_add_to_dbus_queue(u);
3137 #ifdef HAVE_SYSV_COMPAT
3140 static void sysv_facility_in_insserv_conf(Manager *mgr) {
3144 if (!(f = fopen("/etc/insserv.conf", "re"))) {
3145 r = errno == ENOENT ? 0 : -errno;
3150 char l[LINE_MAX], *t;
3151 char **parsed = NULL;
3153 if (!fgets(l, sizeof(l), f)) {
3158 log_error("Failed to read configuration file '/etc/insserv.conf': %s", strerror(-r));
3163 if (*t != '$' && *t != '<')
3166 parsed = strv_split(t,WHITESPACE);
3167 /* we ignore <interactive>, not used, equivalent to X-Interactive */
3168 if (parsed && !startswith_no_case (parsed[0], "<interactive>")) {
3171 if (sysv_translate_facility(parsed[0], NULL, &facility) < 0)
3173 if ((u = manager_get_unit(mgr, facility)) && (u->meta.type == UNIT_TARGET)) {
3175 char *dep = NULL, *name, **j;
3177 STRV_FOREACH (j, parsed+1) {
3186 if (sysv_translate_facility(name, NULL, &dep) < 0)
3189 r = unit_add_two_dependencies_by_name(u, UNIT_BEFORE, e, dep, NULL, true);
3204 static int service_enumerate(Manager *m) {
3208 char *path = NULL, *fpath = NULL, *name = NULL;
3209 Set *runlevel_services[ELEMENTSOF(rcnd_table)], *shutdown_services = NULL;
3216 if (m->running_as != MANAGER_SYSTEM)
3219 zero(runlevel_services);
3221 STRV_FOREACH(p, m->lookup_paths.sysvrcnd_path)
3222 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++) {
3226 path = join(*p, "/", rcnd_table[i].path, NULL);
3235 if (!(d = opendir(path))) {
3236 if (errno != ENOENT)
3237 log_warning("opendir() failed on %s: %s", path, strerror(errno));
3242 while ((de = readdir(d))) {
3245 if (ignore_file(de->d_name))
3248 if (de->d_name[0] != 'S' && de->d_name[0] != 'K')
3251 if (strlen(de->d_name) < 4)
3254 a = undecchar(de->d_name[1]);
3255 b = undecchar(de->d_name[2]);
3261 fpath = join(path, "/", de->d_name, NULL);
3267 if (access(fpath, X_OK) < 0) {
3269 if (errno != ENOENT)
3270 log_warning("access() failed on %s: %s", fpath, strerror(errno));
3276 if (!(name = sysv_translate_name(de->d_name + 3))) {
3281 if ((r = manager_load_unit_prepare(m, name, NULL, NULL, &service)) < 0) {
3282 log_warning("Failed to prepare unit %s: %s", name, strerror(-r));
3286 if (de->d_name[0] == 'S') {
3288 if (rcnd_table[i].type == RUNLEVEL_UP || rcnd_table[i].type == RUNLEVEL_SYSINIT) {
3289 SERVICE(service)->sysv_start_priority_from_rcnd =
3290 MAX(a*10 + b, SERVICE(service)->sysv_start_priority_from_rcnd);
3292 SERVICE(service)->sysv_enabled = true;
3295 if ((r = set_ensure_allocated(&runlevel_services[i], trivial_hash_func, trivial_compare_func)) < 0)
3298 if ((r = set_put(runlevel_services[i], service)) < 0)
3301 } else if (de->d_name[0] == 'K' &&
3302 (rcnd_table[i].type == RUNLEVEL_DOWN ||
3303 rcnd_table[i].type == RUNLEVEL_SYSINIT)) {
3305 if ((r = set_ensure_allocated(&shutdown_services, trivial_hash_func, trivial_compare_func)) < 0)
3308 if ((r = set_put(shutdown_services, service)) < 0)
3314 /* Now we loaded all stubs and are aware of the lowest
3315 start-up priority for all services, not let's actually load
3316 the services, this will also tell us which services are
3317 actually native now */
3318 manager_dispatch_load_queue(m);
3320 /* If this is a native service, rely on native ways to pull in
3321 * a service, don't pull it in via sysv rcN.d links. */
3322 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++)
3323 SET_FOREACH(service, runlevel_services[i], j) {
3324 service = unit_follow_merge(service);
3326 if (service->meta.fragment_path)
3329 if ((r = unit_add_two_dependencies_by_name_inverse(service, UNIT_AFTER, UNIT_WANTS, rcnd_table[i].target, NULL, true)) < 0)
3333 /* We honour K links only for halt/reboot. For the normal
3334 * runlevels we assume the stop jobs will be implicitly added
3335 * by the core logic. Also, we don't really distinguish here
3336 * between the runlevels 0 and 6 and just add them to the
3337 * special shutdown target. On SUSE the boot.d/ runlevel is
3338 * also used for shutdown, so we add links for that too to the
3339 * shutdown target.*/
3340 SET_FOREACH(service, shutdown_services, j) {
3341 service = unit_follow_merge(service);
3343 if (service->meta.fragment_path)
3346 if ((r = unit_add_two_dependencies_by_name(service, UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true)) < 0)
3353 sysv_facility_in_insserv_conf (m);
3361 for (i = 0; i < ELEMENTSOF(rcnd_table); i++)
3362 set_free(runlevel_services[i]);
3363 set_free(shutdown_services);
3372 static void service_bus_name_owner_change(
3375 const char *old_owner,
3376 const char *new_owner) {
3378 Service *s = SERVICE(u);
3383 assert(streq(s->bus_name, name));
3384 assert(old_owner || new_owner);
3386 if (old_owner && new_owner)
3387 log_debug("%s's D-Bus name %s changed owner from %s to %s", u->meta.id, name, old_owner, new_owner);
3389 log_debug("%s's D-Bus name %s no longer registered by %s", u->meta.id, name, old_owner);
3391 log_debug("%s's D-Bus name %s now registered by %s", u->meta.id, name, new_owner);
3393 s->bus_name_good = !!new_owner;
3395 if (s->type == SERVICE_DBUS) {
3397 /* service_enter_running() will figure out what to
3399 if (s->state == SERVICE_RUNNING)
3400 service_enter_running(s, true);
3401 else if (s->state == SERVICE_START && new_owner)
3402 service_enter_start_post(s);
3404 } else if (new_owner &&
3406 (s->state == SERVICE_START ||
3407 s->state == SERVICE_START_POST ||
3408 s->state == SERVICE_RUNNING ||
3409 s->state == SERVICE_RELOAD)) {
3411 /* Try to acquire PID from bus service */
3412 log_debug("Trying to acquire PID from D-Bus name...");
3414 bus_query_pid(u->meta.manager, name);
3418 static void service_bus_query_pid_done(
3423 Service *s = SERVICE(u);
3428 log_debug("%s's D-Bus name %s is now owned by process %u", u->meta.id, name, (unsigned) pid);
3430 if (s->main_pid <= 0 &&
3431 (s->state == SERVICE_START ||
3432 s->state == SERVICE_START_POST ||
3433 s->state == SERVICE_RUNNING ||
3434 s->state == SERVICE_RELOAD))
3435 service_set_main_pid(s, pid);
3438 int service_set_socket_fd(Service *s, int fd, Socket *sock) {
3442 /* This is called by the socket code when instantiating a new
3443 * service for a stream socket and the socket needs to be
3446 if (s->meta.load_state != UNIT_LOADED)
3449 if (s->socket_fd >= 0)
3452 if (s->state != SERVICE_DEAD)
3456 s->got_socket_fd = true;
3457 s->accept_socket = sock;
3462 static void service_reset_failed(Unit *u) {
3463 Service *s = SERVICE(u);
3467 if (s->state == SERVICE_FAILED)
3468 service_set_state(s, SERVICE_DEAD);
3473 static bool service_need_daemon_reload(Unit *u) {
3474 Service *s = SERVICE(u);
3478 #ifdef HAVE_SYSV_COMPAT
3483 if (stat(s->sysv_path, &st) < 0)
3484 /* What, cannot access this anymore? */
3487 if (s->sysv_mtime > 0 &&
3488 timespec_load(&st.st_mtim) != s->sysv_mtime)
3496 static int service_kill(Unit *u, KillWho who, KillMode mode, int signo, DBusError *error) {
3497 Service *s = SERVICE(u);
3499 Set *pid_set = NULL;
3503 if (s->main_pid <= 0 && who == KILL_MAIN) {
3504 dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "No main process to kill");
3508 if (s->control_pid <= 0 && who == KILL_CONTROL) {
3509 dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "No control process to kill");
3513 if (who == KILL_CONTROL || who == KILL_ALL)
3514 if (s->control_pid > 0)
3515 if (kill(s->control_pid, signo) < 0)
3518 if (who == KILL_MAIN || who == KILL_ALL)
3519 if (s->main_pid > 0)
3520 if (kill(s->main_pid, signo) < 0)
3523 if (who == KILL_ALL && mode == KILL_CONTROL_GROUP) {
3526 if (!(pid_set = set_new(trivial_hash_func, trivial_compare_func)))
3529 /* Exclude the control/main pid from being killed via the cgroup */
3530 if (s->control_pid > 0)
3531 if ((q = set_put(pid_set, LONG_TO_PTR(s->control_pid))) < 0) {
3536 if (s->main_pid > 0)
3537 if ((q = set_put(pid_set, LONG_TO_PTR(s->main_pid))) < 0) {
3542 if ((q = cgroup_bonding_kill_list(s->meta.cgroup_bondings, signo, false, pid_set)) < 0)
3543 if (q != -EAGAIN && q != -ESRCH && q != -ENOENT)
3554 static const char* const service_state_table[_SERVICE_STATE_MAX] = {
3555 [SERVICE_DEAD] = "dead",
3556 [SERVICE_START_PRE] = "start-pre",
3557 [SERVICE_START] = "start",
3558 [SERVICE_START_POST] = "start-post",
3559 [SERVICE_RUNNING] = "running",
3560 [SERVICE_EXITED] = "exited",
3561 [SERVICE_RELOAD] = "reload",
3562 [SERVICE_STOP] = "stop",
3563 [SERVICE_STOP_SIGTERM] = "stop-sigterm",
3564 [SERVICE_STOP_SIGKILL] = "stop-sigkill",
3565 [SERVICE_STOP_POST] = "stop-post",
3566 [SERVICE_FINAL_SIGTERM] = "final-sigterm",
3567 [SERVICE_FINAL_SIGKILL] = "final-sigkill",
3568 [SERVICE_FAILED] = "failed",
3569 [SERVICE_AUTO_RESTART] = "auto-restart",
3572 DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
3574 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
3575 [SERVICE_RESTART_NO] = "no",
3576 [SERVICE_RESTART_ON_SUCCESS] = "on-success",
3577 [SERVICE_RESTART_ON_FAILURE] = "on-failure",
3578 [SERVICE_RESTART_ON_ABORT] = "on-abort",
3579 [SERVICE_RESTART_ALWAYS] = "always"
3582 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
3584 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
3585 [SERVICE_SIMPLE] = "simple",
3586 [SERVICE_FORKING] = "forking",
3587 [SERVICE_ONESHOT] = "oneshot",
3588 [SERVICE_DBUS] = "dbus",
3589 [SERVICE_NOTIFY] = "notify"
3592 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
3594 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
3595 [SERVICE_EXEC_START_PRE] = "ExecStartPre",
3596 [SERVICE_EXEC_START] = "ExecStart",
3597 [SERVICE_EXEC_START_POST] = "ExecStartPost",
3598 [SERVICE_EXEC_RELOAD] = "ExecReload",
3599 [SERVICE_EXEC_STOP] = "ExecStop",
3600 [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
3603 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
3605 static const char* const notify_access_table[_NOTIFY_ACCESS_MAX] = {
3606 [NOTIFY_NONE] = "none",
3607 [NOTIFY_MAIN] = "main",
3608 [NOTIFY_ALL] = "all"
3611 DEFINE_STRING_TABLE_LOOKUP(notify_access, NotifyAccess);
3613 const UnitVTable service_vtable = {
3614 .suffix = ".service",
3619 .show_status = true,
3621 .init = service_init,
3622 .done = service_done,
3623 .load = service_load,
3625 .coldplug = service_coldplug,
3627 .dump = service_dump,
3629 .start = service_start,
3630 .stop = service_stop,
3631 .reload = service_reload,
3633 .can_reload = service_can_reload,
3635 .kill = service_kill,
3637 .serialize = service_serialize,
3638 .deserialize_item = service_deserialize_item,
3640 .active_state = service_active_state,
3641 .sub_state_to_string = service_sub_state_to_string,
3643 .check_gc = service_check_gc,
3644 .check_snapshot = service_check_snapshot,
3646 .sigchld_event = service_sigchld_event,
3647 .timer_event = service_timer_event,
3648 .fd_event = service_fd_event,
3650 .reset_failed = service_reset_failed,
3652 .need_daemon_reload = service_need_daemon_reload,
3654 .cgroup_notify_empty = service_cgroup_notify_event,
3655 .notify_message = service_notify_message,
3657 .bus_name_owner_change = service_bus_name_owner_change,
3658 .bus_query_pid_done = service_bus_query_pid_done,
3660 .bus_interface = "org.freedesktop.systemd1.Service",
3661 .bus_message_handler = bus_service_message_handler,
3662 .bus_invalidating_properties = bus_service_invalidating_properties,
3664 #ifdef HAVE_SYSV_COMPAT
3665 .enumerate = service_enumerate