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;
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 void service_unwatch_pid_file(Service *s) {
151 if (!s->pid_file_pathspec)
154 log_debug("Stopping watch for %s's PID file %s", UNIT(s)->id, s->pid_file_pathspec->path);
155 path_spec_unwatch(s->pid_file_pathspec, UNIT(s));
156 path_spec_done(s->pid_file_pathspec);
157 free(s->pid_file_pathspec);
158 s->pid_file_pathspec = NULL;
161 static int service_set_main_pid(Service *s, pid_t pid) {
173 s->main_pid_known = true;
175 if (get_parent_of_pid(pid, &ppid) >= 0 && ppid != getpid()) {
176 log_warning("%s: Supervising process %lu which is not our child. We'll most likely not notice when it exits.",
177 UNIT(s)->id, (unsigned long) pid);
179 s->main_pid_alien = true;
181 s->main_pid_alien = false;
183 exec_status_start(&s->main_exec_status, pid);
188 static void service_close_socket_fd(Service *s) {
191 if (s->socket_fd < 0)
194 close_nointr_nofail(s->socket_fd);
198 static void service_connection_unref(Service *s) {
201 if (!UNIT_DEREF(s->accept_socket))
204 socket_connection_unref(SOCKET(UNIT_DEREF(s->accept_socket)));
205 unit_ref_unset(&s->accept_socket);
208 static void service_stop_watchdog(Service *s) {
211 s->watchdog_timestamp.realtime = 0;
212 s->watchdog_timestamp.monotonic = 0;
215 static void service_reset_watchdog(Service *s) {
218 dual_timestamp_get(&s->watchdog_timestamp);
221 static void service_done(Unit *u) {
222 Service *s = SERVICE(u);
229 #ifdef HAVE_SYSV_COMPAT
233 free(s->sysv_runlevels);
234 s->sysv_runlevels = NULL;
237 free(s->status_text);
238 s->status_text = NULL;
240 exec_context_done(&s->exec_context);
241 exec_command_free_array(s->exec_command, _SERVICE_EXEC_COMMAND_MAX);
242 s->control_command = NULL;
243 s->main_command = NULL;
245 /* This will leak a process, but at least no memory or any of
247 service_unwatch_main_pid(s);
248 service_unwatch_control_pid(s);
249 service_unwatch_pid_file(s);
252 unit_unwatch_bus_name(u, s->bus_name);
257 service_close_socket_fd(s);
258 service_connection_unref(s);
260 unit_ref_unset(&s->accept_socket);
262 unit_unwatch_timer(u, &s->timer_watch);
265 #ifdef HAVE_SYSV_COMPAT
266 static char *sysv_translate_name(const char *name) {
269 if (!(r = new(char, strlen(name) + sizeof(".service"))))
272 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU) || defined(TARGET_ANGSTROM)
273 if (endswith(name, ".sh"))
274 /* Drop Debian-style .sh suffix */
275 strcpy(stpcpy(r, name) - 3, ".service");
278 if (startswith(name, "boot."))
279 /* Drop SuSE-style boot. prefix */
280 strcpy(stpcpy(r, name + 5), ".service");
282 #ifdef TARGET_FRUGALWARE
283 if (startswith(name, "rc."))
284 /* Drop Frugalware-style rc. prefix */
285 strcpy(stpcpy(r, name + 3), ".service");
288 /* Normal init scripts */
289 strcpy(stpcpy(r, name), ".service");
294 static int sysv_translate_facility(const char *name, const char *filename, char **_r) {
296 /* We silently ignore the $ prefix here. According to the LSB
297 * spec it simply indicates whether something is a
298 * standardized name or a distribution-specific one. Since we
299 * just follow what already exists and do not introduce new
300 * uses or names we don't care who introduced a new name. */
302 static const char * const table[] = {
303 /* LSB defined facilities */
304 "local_fs", SPECIAL_LOCAL_FS_TARGET,
305 #if defined(TARGET_MANDRIVA) || defined(TARGET_MAGEIA)
307 /* Due to unfortunate name selection in Mandriva,
308 * $network is provided by network-up which is ordered
309 * after network which actually starts interfaces.
310 * To break the loop, just ignore it */
311 "network", SPECIAL_NETWORK_TARGET,
313 "named", SPECIAL_NSS_LOOKUP_TARGET,
314 "portmap", SPECIAL_RPCBIND_TARGET,
315 "remote_fs", SPECIAL_REMOTE_FS_TARGET,
316 "syslog", SPECIAL_SYSLOG_TARGET,
317 "time", SPECIAL_TIME_SYNC_TARGET,
319 /* common extensions */
320 "mail-transfer-agent", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
321 "x-display-manager", SPECIAL_DISPLAY_MANAGER_SERVICE,
324 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU) || defined(TARGET_ANGSTROM)
325 "mail-transport-agent", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
329 "MTA", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
330 "smtpdaemon", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
331 "httpd", SPECIAL_HTTP_DAEMON_TARGET,
335 "smtp", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
346 n = *name == '$' ? name + 1 : name;
348 for (i = 0; i < ELEMENTSOF(table); i += 2) {
350 if (!streq(table[i], n))
356 if (!(r = strdup(table[i+1])))
362 /* If we don't know this name, fallback heuristics to figure
363 * out whether something is a target or a service alias. */
366 if (!unit_prefix_is_valid(n))
369 /* Facilities starting with $ are most likely targets */
370 r = unit_name_build(n, NULL, ".target");
371 } else if (filename && streq(name, filename))
372 /* Names equaling the file name of the services are redundant */
375 /* Everything else we assume to be normal service names */
376 r = sysv_translate_name(n);
387 static int sysv_fix_order(Service *s) {
393 if (s->sysv_start_priority < 0)
396 /* For each pair of services where at least one lacks a LSB
397 * header, we use the start priority value to order things. */
399 LIST_FOREACH(units_by_type, other, UNIT(s)->manager->units_by_type[UNIT_SERVICE]) {
402 bool special_s, special_t;
409 if (UNIT(t)->load_state != UNIT_LOADED)
412 if (t->sysv_start_priority < 0)
415 /* If both units have modern headers we don't care
416 * about the priorities */
417 if ((UNIT(s)->fragment_path || s->sysv_has_lsb) &&
418 (UNIT(t)->fragment_path || t->sysv_has_lsb))
421 special_s = s->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, s->sysv_runlevels);
422 special_t = t->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, t->sysv_runlevels);
424 if (special_t && !special_s)
426 else if (special_s && !special_t)
428 else if (t->sysv_start_priority < s->sysv_start_priority)
430 else if (t->sysv_start_priority > s->sysv_start_priority)
435 /* FIXME: Maybe we should compare the name here lexicographically? */
437 if ((r = unit_add_dependency(UNIT(s), d, UNIT(t), true)) < 0)
444 static ExecCommand *exec_command_new(const char *path, const char *arg1) {
447 if (!(c = new0(ExecCommand, 1)))
450 if (!(c->path = strdup(path))) {
455 if (!(c->argv = strv_new(path, arg1, NULL))) {
464 static int sysv_exec_commands(Service *s) {
468 assert(s->sysv_path);
470 if (!(c = exec_command_new(s->sysv_path, "start")))
472 exec_command_append_list(s->exec_command+SERVICE_EXEC_START, c);
474 if (!(c = exec_command_new(s->sysv_path, "stop")))
476 exec_command_append_list(s->exec_command+SERVICE_EXEC_STOP, c);
478 if (!(c = exec_command_new(s->sysv_path, "reload")))
480 exec_command_append_list(s->exec_command+SERVICE_EXEC_RELOAD, c);
485 static int service_load_sysv_path(Service *s, const char *path) {
496 char *short_description = NULL, *long_description = NULL, *chkconfig_description = NULL, *description;
504 if (!(f = fopen(path, "re"))) {
505 r = errno == ENOENT ? 0 : -errno;
510 if (fstat(fileno(f), &st) < 0) {
516 if (!(s->sysv_path = strdup(path))) {
521 s->sysv_mtime = timespec_load(&st.st_mtim);
523 if (null_or_empty(&st)) {
524 u->load_state = UNIT_MASKED;
530 char l[LINE_MAX], *t;
532 if (!fgets(l, sizeof(l), f)) {
537 log_error("Failed to read configuration file '%s': %s", path, strerror(-r));
547 if (state == NORMAL && streq(t, "### BEGIN INIT INFO")) {
549 s->sysv_has_lsb = true;
553 if ((state == LSB_DESCRIPTION || state == LSB) && streq(t, "### END INIT INFO")) {
559 t += strspn(t, WHITESPACE);
561 if (state == NORMAL) {
563 /* Try to parse Red Hat style chkconfig headers */
565 if (startswith_no_case(t, "chkconfig:")) {
567 char runlevels[16], *k;
571 if (sscanf(t+10, "%15s %i %*i",
573 &start_priority) != 2) {
575 log_warning("[%s:%u] Failed to parse chkconfig line. Ignoring.", path, line);
579 /* A start priority gathered from the
580 * symlink farms is preferred over the
581 * data from the LSB header. */
582 if (start_priority < 0 || start_priority > 99)
583 log_warning("[%s:%u] Start priority out of range. Ignoring.", path, line);
585 s->sysv_start_priority = start_priority;
587 char_array_0(runlevels);
588 k = delete_chars(runlevels, WHITESPACE "-");
593 if (!(d = strdup(k))) {
598 free(s->sysv_runlevels);
599 s->sysv_runlevels = d;
602 } else if (startswith_no_case(t, "description:")) {
604 size_t k = strlen(t);
608 if (t[k-1] == '\\') {
613 if ((j = strstrip(t+12)) && *j) {
614 if (!(d = strdup(j))) {
621 free(chkconfig_description);
622 chkconfig_description = d;
624 } else if (startswith_no_case(t, "pidfile:")) {
631 if (!path_is_absolute(fn)) {
632 log_warning("[%s:%u] PID file not absolute. Ignoring.", path, line);
636 if (!(fn = strdup(fn))) {
645 } else if (state == DESCRIPTION) {
647 /* Try to parse Red Hat style description
650 size_t k = strlen(t);
658 if ((j = strstrip(t)) && *j) {
661 if (chkconfig_description)
662 d = join(chkconfig_description, " ", j, NULL);
671 free(chkconfig_description);
672 chkconfig_description = d;
675 } else if (state == LSB || state == LSB_DESCRIPTION) {
677 if (startswith_no_case(t, "Provides:")) {
683 FOREACH_WORD_QUOTED(w, z, t+9, i) {
686 if (!(n = strndup(w, z))) {
691 r = sysv_translate_facility(n, file_name_from_path(path), &m);
700 if (unit_name_to_type(m) == UNIT_SERVICE)
701 r = unit_add_name(u, m);
708 * indication that the
710 * now available. This
713 * targets do NOT pull
716 r = unit_add_two_dependencies_by_name(u, UNIT_BEFORE, UNIT_WANTS, m, NULL, true);
719 log_error("[%s:%u] Failed to add LSB Provides name %s, ignoring: %s", path, line, m, strerror(-r));
724 } else if (startswith_no_case(t, "Required-Start:") ||
725 startswith_no_case(t, "Should-Start:") ||
726 startswith_no_case(t, "X-Start-Before:") ||
727 startswith_no_case(t, "X-Start-After:")) {
733 FOREACH_WORD_QUOTED(w, z, strchr(t, ':')+1, i) {
736 if (!(n = strndup(w, z))) {
741 r = sysv_translate_facility(n, file_name_from_path(path), &m);
744 log_error("[%s:%u] Failed to translate LSB dependency %s, ignoring: %s", path, line, n, strerror(-r));
754 r = unit_add_dependency_by_name(u, startswith_no_case(t, "X-Start-Before:") ? UNIT_BEFORE : UNIT_AFTER, m, NULL, true);
757 log_error("[%s:%u] Failed to add dependency on %s, ignoring: %s", path, line, m, strerror(-r));
761 } else if (startswith_no_case(t, "Default-Start:")) {
766 k = delete_chars(t+14, WHITESPACE "-");
769 if (!(d = strdup(k))) {
774 free(s->sysv_runlevels);
775 s->sysv_runlevels = d;
778 } else if (startswith_no_case(t, "Description:")) {
781 state = LSB_DESCRIPTION;
783 if ((j = strstrip(t+12)) && *j) {
784 if (!(d = strdup(j))) {
791 free(long_description);
792 long_description = d;
794 } else if (startswith_no_case(t, "Short-Description:")) {
799 if ((j = strstrip(t+18)) && *j) {
800 if (!(d = strdup(j))) {
807 free(short_description);
808 short_description = d;
810 } else if (state == LSB_DESCRIPTION) {
812 if (startswith(l, "#\t") || startswith(l, "# ")) {
815 if ((j = strstrip(t)) && *j) {
818 if (long_description)
819 d = join(long_description, " ", t, NULL);
828 free(long_description);
829 long_description = d;
838 if ((r = sysv_exec_commands(s)) < 0)
840 if (s->sysv_runlevels &&
841 chars_intersect(RUNLEVELS_BOOT, s->sysv_runlevels) &&
842 chars_intersect(RUNLEVELS_UP, s->sysv_runlevels)) {
843 /* Service has both boot and "up" runlevels
844 configured. Kill the "up" ones. */
845 delete_chars(s->sysv_runlevels, RUNLEVELS_UP);
848 if (s->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, s->sysv_runlevels)) {
849 /* If there a runlevels configured for this service
850 * but none of the standard ones, then we assume this
851 * is some special kind of service (which might be
852 * needed for early boot) and don't create any links
855 UNIT(s)->default_dependencies = false;
857 /* Don't timeout special services during boot (like fsck) */
860 s->timeout_usec = DEFAULT_SYSV_TIMEOUT_USEC;
862 /* Special setting for all SysV services */
863 s->type = SERVICE_FORKING;
864 s->remain_after_exit = !s->pid_file;
865 s->guess_main_pid = false;
866 s->restart = SERVICE_RESTART_NO;
868 if (UNIT(s)->manager->sysv_console)
869 s->exec_context.std_output = EXEC_OUTPUT_JOURNAL_AND_CONSOLE;
871 s->exec_context.kill_mode = KILL_PROCESS;
873 /* We use the long description only if
874 * no short description is set. */
876 if (short_description)
877 description = short_description;
878 else if (chkconfig_description)
879 description = chkconfig_description;
880 else if (long_description)
881 description = long_description;
888 if (!(d = strappend(s->sysv_has_lsb ? "LSB: " : "SYSV: ", description))) {
896 /* The priority that has been set in /etc/rcN.d/ hierarchies
897 * takes precedence over what is stored as default in the LSB
899 if (s->sysv_start_priority_from_rcnd >= 0)
900 s->sysv_start_priority = s->sysv_start_priority_from_rcnd;
902 u->load_state = UNIT_LOADED;
910 free(short_description);
911 free(long_description);
912 free(chkconfig_description);
917 static int service_load_sysv_name(Service *s, const char *name) {
923 /* For SysV services we strip the boot.*, rc.* and *.sh
924 * prefixes/suffixes. */
925 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU) || defined(TARGET_ANGSTROM)
926 if (endswith(name, ".sh.service"))
931 if (startswith(name, "boot."))
935 #ifdef TARGET_FRUGALWARE
936 if (startswith(name, "rc."))
940 STRV_FOREACH(p, UNIT(s)->manager->lookup_paths.sysvinit_path) {
944 path = join(*p, "/", name, NULL);
948 assert(endswith(path, ".service"));
949 path[strlen(path)-8] = 0;
951 r = service_load_sysv_path(s, path);
953 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU) || defined(TARGET_ANGSTROM)
954 if (r >= 0 && UNIT(s)->load_state == UNIT_STUB) {
955 /* Try Debian style *.sh source'able init scripts */
957 r = service_load_sysv_path(s, path);
963 if (r >= 0 && UNIT(s)->load_state == UNIT_STUB) {
964 /* Try SUSE style boot.* init scripts */
966 path = join(*p, "/boot.", name, NULL);
970 /* Drop .service suffix */
971 path[strlen(path)-8] = 0;
972 r = service_load_sysv_path(s, path);
977 #ifdef TARGET_FRUGALWARE
978 if (r >= 0 && UNIT(s)->load_state == UNIT_STUB) {
979 /* Try Frugalware style rc.* init scripts */
981 path = join(*p, "/rc.", name, NULL);
985 /* Drop .service suffix */
986 path[strlen(path)-8] = 0;
987 r = service_load_sysv_path(s, path);
995 if ((UNIT(s)->load_state != UNIT_STUB))
1002 static int service_load_sysv(Service *s) {
1009 /* Load service data from SysV init scripts, preferably with
1010 * LSB headers ... */
1012 if (strv_isempty(UNIT(s)->manager->lookup_paths.sysvinit_path))
1015 if ((t = UNIT(s)->id))
1016 if ((r = service_load_sysv_name(s, t)) < 0)
1019 if (UNIT(s)->load_state == UNIT_STUB)
1020 SET_FOREACH(t, UNIT(s)->names, i) {
1021 if (t == UNIT(s)->id)
1024 if ((r = service_load_sysv_name(s, t)) < 0)
1027 if (UNIT(s)->load_state != UNIT_STUB)
1035 static int fsck_fix_order(Service *s) {
1041 if (s->fsck_passno <= 0)
1044 /* For each pair of services where both have an fsck priority
1045 * we order things based on it. */
1047 LIST_FOREACH(units_by_type, other, UNIT(s)->manager->units_by_type[UNIT_SERVICE]) {
1056 if (UNIT(t)->load_state != UNIT_LOADED)
1059 if (t->fsck_passno <= 0)
1062 if (t->fsck_passno < s->fsck_passno)
1064 else if (t->fsck_passno > s->fsck_passno)
1069 if ((r = unit_add_dependency(UNIT(s), d, UNIT(t), true)) < 0)
1076 static int service_verify(Service *s) {
1079 if (UNIT(s)->load_state != UNIT_LOADED)
1082 if (!s->exec_command[SERVICE_EXEC_START]) {
1083 log_error("%s lacks ExecStart setting. Refusing.", UNIT(s)->id);
1087 if (s->type != SERVICE_ONESHOT &&
1088 s->exec_command[SERVICE_EXEC_START]->command_next) {
1089 log_error("%s has more than one ExecStart setting, which is only allowed for Type=oneshot services. Refusing.", UNIT(s)->id);
1093 if (s->type == SERVICE_ONESHOT &&
1094 s->exec_command[SERVICE_EXEC_RELOAD]) {
1095 log_error("%s has an ExecReload setting, which is not allowed for Type=oneshot services. Refusing.", UNIT(s)->id);
1099 if (s->type == SERVICE_DBUS && !s->bus_name) {
1100 log_error("%s is of type D-Bus but no D-Bus service name has been specified. Refusing.", UNIT(s)->id);
1104 if (s->exec_context.pam_name && s->exec_context.kill_mode != KILL_CONTROL_GROUP) {
1105 log_error("%s has PAM enabled. Kill mode must be set to 'control-group'. Refusing.", UNIT(s)->id);
1112 static int service_add_default_dependencies(Service *s) {
1117 /* Add a number of automatic dependencies useful for the
1118 * majority of services. */
1120 /* First, pull in base system */
1121 if (UNIT(s)->manager->running_as == MANAGER_SYSTEM) {
1123 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_BASIC_TARGET, NULL, true)) < 0)
1126 } else if (UNIT(s)->manager->running_as == MANAGER_USER) {
1128 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SOCKETS_TARGET, NULL, true)) < 0)
1132 /* Second, activate normal shutdown */
1133 return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true);
1136 static void service_fix_output(Service *s) {
1139 /* If nothing has been explicitly configured, patch default
1140 * output in. If input is socket/tty we avoid this however,
1141 * since in that case we want output to default to the same
1142 * place as we read input from. */
1144 if (s->exec_context.std_error == EXEC_OUTPUT_INHERIT &&
1145 s->exec_context.std_output == EXEC_OUTPUT_INHERIT &&
1146 s->exec_context.std_input == EXEC_INPUT_NULL)
1147 s->exec_context.std_error = UNIT(s)->manager->default_std_error;
1149 if (s->exec_context.std_output == EXEC_OUTPUT_INHERIT &&
1150 s->exec_context.std_input == EXEC_INPUT_NULL)
1151 s->exec_context.std_output = UNIT(s)->manager->default_std_output;
1154 static int service_load(Unit *u) {
1156 Service *s = SERVICE(u);
1160 /* Load a .service file */
1161 if ((r = unit_load_fragment(u)) < 0)
1164 #ifdef HAVE_SYSV_COMPAT
1165 /* Load a classic init script as a fallback, if we couldn't find anything */
1166 if (u->load_state == UNIT_STUB)
1167 if ((r = service_load_sysv(s)) < 0)
1171 /* Still nothing found? Then let's give up */
1172 if (u->load_state == UNIT_STUB)
1175 /* We were able to load something, then let's add in the
1176 * dropin directories. */
1177 if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
1180 /* This is a new unit? Then let's add in some extras */
1181 if (u->load_state == UNIT_LOADED) {
1182 service_fix_output(s);
1184 if ((r = unit_add_exec_dependencies(u, &s->exec_context)) < 0)
1187 if ((r = unit_add_default_cgroups(u)) < 0)
1190 #ifdef HAVE_SYSV_COMPAT
1191 if ((r = sysv_fix_order(s)) < 0)
1195 if ((r = fsck_fix_order(s)) < 0)
1199 if ((r = unit_watch_bus_name(u, s->bus_name)) < 0)
1202 if (s->type == SERVICE_NOTIFY && s->notify_access == NOTIFY_NONE)
1203 s->notify_access = NOTIFY_MAIN;
1205 if (s->type == SERVICE_DBUS || s->bus_name)
1206 if ((r = unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_REQUIRES, SPECIAL_DBUS_SOCKET, NULL, true)) < 0)
1209 if (UNIT(s)->default_dependencies)
1210 if ((r = service_add_default_dependencies(s)) < 0)
1214 return service_verify(s);
1217 static void service_dump(Unit *u, FILE *f, const char *prefix) {
1219 ServiceExecCommand c;
1220 Service *s = SERVICE(u);
1221 const char *prefix2;
1226 p2 = strappend(prefix, "\t");
1227 prefix2 = p2 ? p2 : prefix;
1230 "%sService State: %s\n"
1232 "%sReload Result: %s\n"
1233 "%sPermissionsStartOnly: %s\n"
1234 "%sRootDirectoryStartOnly: %s\n"
1235 "%sRemainAfterExit: %s\n"
1236 "%sGuessMainPID: %s\n"
1239 "%sNotifyAccess: %s\n",
1240 prefix, service_state_to_string(s->state),
1241 prefix, service_result_to_string(s->result),
1242 prefix, service_result_to_string(s->reload_result),
1243 prefix, yes_no(s->permissions_start_only),
1244 prefix, yes_no(s->root_directory_start_only),
1245 prefix, yes_no(s->remain_after_exit),
1246 prefix, yes_no(s->guess_main_pid),
1247 prefix, service_type_to_string(s->type),
1248 prefix, service_restart_to_string(s->restart),
1249 prefix, notify_access_to_string(s->notify_access));
1251 if (s->control_pid > 0)
1253 "%sControl PID: %lu\n",
1254 prefix, (unsigned long) s->control_pid);
1256 if (s->main_pid > 0)
1259 "%sMain PID Known: %s\n"
1260 "%sMain PID Alien: %s\n",
1261 prefix, (unsigned long) s->main_pid,
1262 prefix, yes_no(s->main_pid_known),
1263 prefix, yes_no(s->main_pid_alien));
1268 prefix, s->pid_file);
1273 "%sBus Name Good: %s\n",
1274 prefix, s->bus_name,
1275 prefix, yes_no(s->bus_name_good));
1277 exec_context_dump(&s->exec_context, f, prefix);
1279 for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
1281 if (!s->exec_command[c])
1284 fprintf(f, "%s-> %s:\n",
1285 prefix, service_exec_command_to_string(c));
1287 exec_command_dump_list(s->exec_command[c], f, prefix2);
1290 #ifdef HAVE_SYSV_COMPAT
1293 "%sSysV Init Script Path: %s\n"
1294 "%sSysV Init Script has LSB Header: %s\n"
1295 "%sSysVEnabled: %s\n",
1296 prefix, s->sysv_path,
1297 prefix, yes_no(s->sysv_has_lsb),
1298 prefix, yes_no(s->sysv_enabled));
1300 if (s->sysv_start_priority >= 0)
1302 "%sSysVStartPriority: %i\n",
1303 prefix, s->sysv_start_priority);
1305 if (s->sysv_runlevels)
1306 fprintf(f, "%sSysVRunLevels: %s\n",
1307 prefix, s->sysv_runlevels);
1310 if (s->fsck_passno > 0)
1312 "%sFsckPassNo: %i\n",
1313 prefix, s->fsck_passno);
1316 fprintf(f, "%sStatus Text: %s\n",
1317 prefix, s->status_text);
1322 static int service_load_pid_file(Service *s, bool may_warn) {
1332 if ((r = read_one_line_file(s->pid_file, &k)) < 0) {
1334 log_info("PID file %s not readable (yet?) after %s.",
1335 s->pid_file, service_state_to_string(s->state));
1339 r = parse_pid(k, &pid);
1345 if (kill(pid, 0) < 0 && errno != EPERM) {
1347 log_info("PID %lu read from file %s does not exist.",
1348 (unsigned long) pid, s->pid_file);
1352 if (s->main_pid_known) {
1353 if (pid == s->main_pid)
1356 log_debug("Main PID changing: %lu -> %lu",
1357 (unsigned long) s->main_pid, (unsigned long) pid);
1358 service_unwatch_main_pid(s);
1359 s->main_pid_known = false;
1361 log_debug("Main PID loaded: %lu", (unsigned long) pid);
1363 if ((r = service_set_main_pid(s, pid)) < 0)
1366 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1367 /* FIXME: we need to do something here */
1373 static int service_search_main_pid(Service *s) {
1379 /* If we know it anyway, don't ever fallback to unreliable
1381 if (s->main_pid_known)
1384 if (!s->guess_main_pid)
1387 assert(s->main_pid <= 0);
1389 if ((pid = cgroup_bonding_search_main_pid_list(UNIT(s)->cgroup_bondings)) <= 0)
1392 log_debug("Main PID guessed: %lu", (unsigned long) pid);
1393 if ((r = service_set_main_pid(s, pid)) < 0)
1396 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1397 /* FIXME: we need to do something here */
1403 static void service_notify_sockets_dead(Service *s) {
1409 /* Notifies all our sockets when we die */
1411 if (s->socket_fd >= 0)
1414 SET_FOREACH(u, UNIT(s)->dependencies[UNIT_TRIGGERED_BY], i)
1415 if (u->type == UNIT_SOCKET)
1416 socket_notify_service_dead(SOCKET(u));
1421 static void service_set_state(Service *s, ServiceState state) {
1422 ServiceState old_state;
1425 old_state = s->state;
1428 service_unwatch_pid_file(s);
1430 if (state != SERVICE_START_PRE &&
1431 state != SERVICE_START &&
1432 state != SERVICE_START_POST &&
1433 state != SERVICE_RELOAD &&
1434 state != SERVICE_STOP &&
1435 state != SERVICE_STOP_SIGTERM &&
1436 state != SERVICE_STOP_SIGKILL &&
1437 state != SERVICE_STOP_POST &&
1438 state != SERVICE_FINAL_SIGTERM &&
1439 state != SERVICE_FINAL_SIGKILL &&
1440 state != SERVICE_AUTO_RESTART)
1441 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1443 if (state != SERVICE_START &&
1444 state != SERVICE_START_POST &&
1445 state != SERVICE_RUNNING &&
1446 state != SERVICE_RELOAD &&
1447 state != SERVICE_STOP &&
1448 state != SERVICE_STOP_SIGTERM &&
1449 state != SERVICE_STOP_SIGKILL) {
1450 service_unwatch_main_pid(s);
1451 s->main_command = NULL;
1454 if (state != SERVICE_START_PRE &&
1455 state != SERVICE_START &&
1456 state != SERVICE_START_POST &&
1457 state != SERVICE_RELOAD &&
1458 state != SERVICE_STOP &&
1459 state != SERVICE_STOP_SIGTERM &&
1460 state != SERVICE_STOP_SIGKILL &&
1461 state != SERVICE_STOP_POST &&
1462 state != SERVICE_FINAL_SIGTERM &&
1463 state != SERVICE_FINAL_SIGKILL) {
1464 service_unwatch_control_pid(s);
1465 s->control_command = NULL;
1466 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1469 if (state == SERVICE_DEAD ||
1470 state == SERVICE_STOP ||
1471 state == SERVICE_STOP_SIGTERM ||
1472 state == SERVICE_STOP_SIGKILL ||
1473 state == SERVICE_STOP_POST ||
1474 state == SERVICE_FINAL_SIGTERM ||
1475 state == SERVICE_FINAL_SIGKILL ||
1476 state == SERVICE_FAILED ||
1477 state == SERVICE_AUTO_RESTART)
1478 service_notify_sockets_dead(s);
1480 if (state != SERVICE_START_PRE &&
1481 state != SERVICE_START &&
1482 state != SERVICE_START_POST &&
1483 state != SERVICE_RUNNING &&
1484 state != SERVICE_RELOAD &&
1485 state != SERVICE_STOP &&
1486 state != SERVICE_STOP_SIGTERM &&
1487 state != SERVICE_STOP_SIGKILL &&
1488 state != SERVICE_STOP_POST &&
1489 state != SERVICE_FINAL_SIGTERM &&
1490 state != SERVICE_FINAL_SIGKILL &&
1491 !(state == SERVICE_DEAD && UNIT(s)->job)) {
1492 service_close_socket_fd(s);
1493 service_connection_unref(s);
1496 if (state == SERVICE_STOP)
1497 service_stop_watchdog(s);
1499 /* For the inactive states unit_notify() will trim the cgroup,
1500 * but for exit we have to do that ourselves... */
1501 if (state == SERVICE_EXITED && UNIT(s)->manager->n_reloading <= 0)
1502 cgroup_bonding_trim_list(UNIT(s)->cgroup_bondings, true);
1504 if (old_state != state)
1505 log_debug("%s changed %s -> %s", UNIT(s)->id, service_state_to_string(old_state), service_state_to_string(state));
1507 unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state], s->reload_result == SERVICE_SUCCESS);
1508 s->reload_result = SERVICE_SUCCESS;
1511 static int service_coldplug(Unit *u) {
1512 Service *s = SERVICE(u);
1516 assert(s->state == SERVICE_DEAD);
1518 if (s->deserialized_state != s->state) {
1520 if (s->deserialized_state == SERVICE_START_PRE ||
1521 s->deserialized_state == SERVICE_START ||
1522 s->deserialized_state == SERVICE_START_POST ||
1523 s->deserialized_state == SERVICE_RELOAD ||
1524 s->deserialized_state == SERVICE_STOP ||
1525 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1526 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1527 s->deserialized_state == SERVICE_STOP_POST ||
1528 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1529 s->deserialized_state == SERVICE_FINAL_SIGKILL ||
1530 s->deserialized_state == SERVICE_AUTO_RESTART) {
1532 if (s->deserialized_state == SERVICE_AUTO_RESTART || s->timeout_usec > 0) {
1535 k = s->deserialized_state == SERVICE_AUTO_RESTART ? s->restart_usec : s->timeout_usec;
1537 if ((r = unit_watch_timer(UNIT(s), k, &s->timer_watch)) < 0)
1542 if ((s->deserialized_state == SERVICE_START &&
1543 (s->type == SERVICE_FORKING ||
1544 s->type == SERVICE_DBUS ||
1545 s->type == SERVICE_ONESHOT ||
1546 s->type == SERVICE_NOTIFY)) ||
1547 s->deserialized_state == SERVICE_START_POST ||
1548 s->deserialized_state == SERVICE_RUNNING ||
1549 s->deserialized_state == SERVICE_RELOAD ||
1550 s->deserialized_state == SERVICE_STOP ||
1551 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1552 s->deserialized_state == SERVICE_STOP_SIGKILL)
1553 if (s->main_pid > 0)
1554 if ((r = unit_watch_pid(UNIT(s), s->main_pid)) < 0)
1557 if (s->deserialized_state == SERVICE_START_PRE ||
1558 s->deserialized_state == SERVICE_START ||
1559 s->deserialized_state == SERVICE_START_POST ||
1560 s->deserialized_state == SERVICE_RELOAD ||
1561 s->deserialized_state == SERVICE_STOP ||
1562 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1563 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1564 s->deserialized_state == SERVICE_STOP_POST ||
1565 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1566 s->deserialized_state == SERVICE_FINAL_SIGKILL)
1567 if (s->control_pid > 0)
1568 if ((r = unit_watch_pid(UNIT(s), s->control_pid)) < 0)
1571 service_set_state(s, s->deserialized_state);
1577 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
1581 unsigned rn_fds = 0;
1588 if (s->socket_fd >= 0)
1591 SET_FOREACH(u, UNIT(s)->dependencies[UNIT_TRIGGERED_BY], i) {
1596 if (u->type != UNIT_SOCKET)
1601 if ((r = socket_collect_fds(sock, &cfds, &cn_fds)) < 0)
1613 if (!(t = new(int, rn_fds+cn_fds))) {
1619 memcpy(t, rfds, rn_fds * sizeof(int));
1620 memcpy(t+rn_fds, cfds, cn_fds * sizeof(int));
1625 rn_fds = rn_fds+cn_fds;
1640 static int service_spawn(
1645 bool apply_permissions,
1647 bool apply_tty_stdin,
1648 bool set_notify_socket,
1653 int *fds = NULL, *fdsbuf = NULL;
1654 unsigned n_fds = 0, n_env = 0;
1655 char **argv = NULL, **final_env = NULL, **our_env = NULL;
1662 s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1663 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1664 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
1666 if (s->socket_fd >= 0) {
1667 fds = &s->socket_fd;
1670 if ((r = service_collect_fds(s, &fdsbuf, &n_fds)) < 0)
1677 if (timeout && s->timeout_usec) {
1678 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1681 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1683 if (!(argv = unit_full_printf_strv(UNIT(s), c->argv))) {
1688 if (!(our_env = new0(char*, 4))) {
1693 if (set_notify_socket)
1694 if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=%s", UNIT(s)->manager->notify_socket) < 0) {
1699 if (s->main_pid > 0)
1700 if (asprintf(our_env + n_env++, "MAINPID=%lu", (unsigned long) s->main_pid) < 0) {
1705 if (!(final_env = strv_env_merge(2,
1706 UNIT(s)->manager->environment,
1721 UNIT(s)->manager->confirm_spawn,
1722 UNIT(s)->cgroup_bondings,
1723 UNIT(s)->cgroup_attributes,
1730 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1731 /* FIXME: we need to do something here */
1737 strv_free(final_env);
1747 strv_free(final_env);
1750 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1755 static int main_pid_good(Service *s) {
1758 /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1761 /* If we know the pid file, then lets just check if it is
1763 if (s->main_pid_known) {
1765 /* If it's an alien child let's check if it is still
1767 if (s->main_pid_alien)
1768 return kill(s->main_pid, 0) >= 0 || errno != ESRCH;
1770 /* .. otherwise assume we'll get a SIGCHLD for it,
1771 * which we really should wait for to collect exit
1772 * status and code */
1773 return s->main_pid > 0;
1776 /* We don't know the pid */
1780 static int control_pid_good(Service *s) {
1783 return s->control_pid > 0;
1786 static int cgroup_good(Service *s) {
1791 if ((r = cgroup_bonding_is_empty_list(UNIT(s)->cgroup_bondings)) < 0)
1797 static void service_enter_dead(Service *s, ServiceResult f, bool allow_restart) {
1801 if (f != SERVICE_SUCCESS)
1804 if (allow_restart &&
1805 !s->forbid_restart &&
1806 (s->restart == SERVICE_RESTART_ALWAYS ||
1807 (s->restart == SERVICE_RESTART_ON_SUCCESS && s->result == SERVICE_SUCCESS) ||
1808 (s->restart == SERVICE_RESTART_ON_FAILURE && s->result != SERVICE_SUCCESS) ||
1809 (s->restart == SERVICE_RESTART_ON_ABORT && (s->result == SERVICE_FAILURE_SIGNAL ||
1810 s->result == SERVICE_FAILURE_CORE_DUMP)))) {
1812 r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch);
1816 service_set_state(s, SERVICE_AUTO_RESTART);
1818 service_set_state(s, s->result != SERVICE_SUCCESS ? SERVICE_FAILED : SERVICE_DEAD);
1820 s->forbid_restart = false;
1825 log_warning("%s failed to run install restart timer: %s", UNIT(s)->id, strerror(-r));
1826 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, false);
1829 static void service_enter_signal(Service *s, ServiceState state, ServiceResult f);
1831 static void service_enter_stop_post(Service *s, ServiceResult f) {
1835 if (f != SERVICE_SUCCESS)
1838 service_unwatch_control_pid(s);
1840 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST])) {
1841 s->control_command_id = SERVICE_EXEC_STOP_POST;
1843 if ((r = service_spawn(s,
1847 !s->permissions_start_only,
1848 !s->root_directory_start_only,
1851 &s->control_pid)) < 0)
1855 service_set_state(s, SERVICE_STOP_POST);
1857 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_SUCCESS);
1862 log_warning("%s failed to run 'stop-post' task: %s", UNIT(s)->id, strerror(-r));
1863 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
1866 static void service_enter_signal(Service *s, ServiceState state, ServiceResult f) {
1868 Set *pid_set = NULL;
1869 bool wait_for_exit = false;
1873 if (f != SERVICE_SUCCESS)
1876 if (s->exec_context.kill_mode != KILL_NONE) {
1877 int sig = (state == SERVICE_STOP_SIGTERM || state == SERVICE_FINAL_SIGTERM) ? s->exec_context.kill_signal : SIGKILL;
1879 if (s->main_pid > 0) {
1880 if (kill_and_sigcont(s->main_pid, sig) < 0 && errno != ESRCH)
1881 log_warning("Failed to kill main process %li: %m", (long) s->main_pid);
1883 wait_for_exit = !s->main_pid_alien;
1886 if (s->control_pid > 0) {
1887 if (kill_and_sigcont(s->control_pid, sig) < 0 && errno != ESRCH)
1888 log_warning("Failed to kill control process %li: %m", (long) s->control_pid);
1890 wait_for_exit = true;
1893 if (s->exec_context.kill_mode == KILL_CONTROL_GROUP) {
1895 if (!(pid_set = set_new(trivial_hash_func, trivial_compare_func))) {
1900 /* Exclude the main/control pids from being killed via the cgroup */
1901 if (s->main_pid > 0)
1902 if ((r = set_put(pid_set, LONG_TO_PTR(s->main_pid))) < 0)
1905 if (s->control_pid > 0)
1906 if ((r = set_put(pid_set, LONG_TO_PTR(s->control_pid))) < 0)
1909 if ((r = cgroup_bonding_kill_list(UNIT(s)->cgroup_bondings, sig, true, pid_set)) < 0) {
1910 if (r != -EAGAIN && r != -ESRCH && r != -ENOENT)
1911 log_warning("Failed to kill control group: %s", strerror(-r));
1913 wait_for_exit = true;
1920 if (wait_for_exit) {
1921 if (s->timeout_usec > 0)
1922 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1925 service_set_state(s, state);
1926 } else if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1927 service_enter_stop_post(s, SERVICE_SUCCESS);
1929 service_enter_dead(s, SERVICE_SUCCESS, true);
1934 log_warning("%s failed to kill processes: %s", UNIT(s)->id, strerror(-r));
1936 if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1937 service_enter_stop_post(s, SERVICE_FAILURE_RESOURCES);
1939 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
1945 static void service_enter_stop(Service *s, ServiceResult f) {
1950 if (f != SERVICE_SUCCESS)
1953 service_unwatch_control_pid(s);
1955 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP])) {
1956 s->control_command_id = SERVICE_EXEC_STOP;
1958 if ((r = service_spawn(s,
1962 !s->permissions_start_only,
1963 !s->root_directory_start_only,
1966 &s->control_pid)) < 0)
1969 service_set_state(s, SERVICE_STOP);
1971 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
1976 log_warning("%s failed to run 'stop' task: %s", UNIT(s)->id, strerror(-r));
1977 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
1980 static void service_enter_running(Service *s, ServiceResult f) {
1981 int main_pid_ok, cgroup_ok;
1984 if (f != SERVICE_SUCCESS)
1987 main_pid_ok = main_pid_good(s);
1988 cgroup_ok = cgroup_good(s);
1990 if ((main_pid_ok > 0 || (main_pid_ok < 0 && cgroup_ok != 0)) &&
1991 (s->bus_name_good || s->type != SERVICE_DBUS))
1992 service_set_state(s, SERVICE_RUNNING);
1993 else if (s->remain_after_exit)
1994 service_set_state(s, SERVICE_EXITED);
1996 service_enter_stop(s, SERVICE_SUCCESS);
1999 static void service_enter_start_post(Service *s) {
2003 service_unwatch_control_pid(s);
2005 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_POST])) {
2006 s->control_command_id = SERVICE_EXEC_START_POST;
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_START_POST);
2021 service_enter_running(s, SERVICE_SUCCESS);
2026 log_warning("%s failed to run 'start-post' task: %s", UNIT(s)->id, strerror(-r));
2027 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2030 static void service_enter_start(Service *s) {
2037 assert(s->exec_command[SERVICE_EXEC_START]);
2038 assert(!s->exec_command[SERVICE_EXEC_START]->command_next || s->type == SERVICE_ONESHOT);
2040 if (s->type == SERVICE_FORKING)
2041 service_unwatch_control_pid(s);
2043 service_unwatch_main_pid(s);
2045 /* We want to ensure that nobody leaks processes from
2046 * START_PRE here, so let's go on a killing spree, People
2047 * should not spawn long running processes from START_PRE. */
2048 cgroup_bonding_kill_list(UNIT(s)->cgroup_bondings, SIGKILL, true, NULL);
2050 if (s->type == SERVICE_FORKING) {
2051 s->control_command_id = SERVICE_EXEC_START;
2052 c = s->control_command = s->exec_command[SERVICE_EXEC_START];
2054 s->main_command = NULL;
2056 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2057 s->control_command = NULL;
2059 c = s->main_command = s->exec_command[SERVICE_EXEC_START];
2062 if ((r = service_spawn(s,
2064 s->type == SERVICE_FORKING || s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY,
2069 s->notify_access != NOTIFY_NONE,
2073 if (s->type == SERVICE_SIMPLE) {
2074 /* For simple services we immediately start
2075 * the START_POST binaries. */
2077 service_set_main_pid(s, pid);
2078 service_enter_start_post(s);
2080 } else if (s->type == SERVICE_FORKING) {
2082 /* For forking services we wait until the start
2083 * process exited. */
2085 s->control_pid = pid;
2086 service_set_state(s, SERVICE_START);
2088 } else if (s->type == SERVICE_ONESHOT ||
2089 s->type == SERVICE_DBUS ||
2090 s->type == SERVICE_NOTIFY) {
2092 /* For oneshot services we wait until the start
2093 * process exited, too, but it is our main process. */
2095 /* For D-Bus services we know the main pid right away,
2096 * but wait for the bus name to appear on the
2097 * bus. Notify services are similar. */
2099 service_set_main_pid(s, pid);
2100 service_set_state(s, SERVICE_START);
2102 assert_not_reached("Unknown service type");
2107 log_warning("%s failed to run 'start' task: %s", UNIT(s)->id, strerror(-r));
2108 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
2111 static void service_enter_start_pre(Service *s) {
2116 service_unwatch_control_pid(s);
2118 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_PRE])) {
2120 /* Before we start anything, let's clear up what might
2121 * be left from previous runs. */
2122 cgroup_bonding_kill_list(UNIT(s)->cgroup_bondings, SIGKILL, true, NULL);
2124 s->control_command_id = SERVICE_EXEC_START_PRE;
2126 if ((r = service_spawn(s,
2130 !s->permissions_start_only,
2131 !s->root_directory_start_only,
2134 &s->control_pid)) < 0)
2137 service_set_state(s, SERVICE_START_PRE);
2139 service_enter_start(s);
2144 log_warning("%s failed to run 'start-pre' task: %s", UNIT(s)->id, strerror(-r));
2145 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
2148 static void service_enter_restart(Service *s) {
2153 dbus_error_init(&error);
2156 log_info("Job pending for unit, delaying automatic restart.");
2158 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
2162 service_enter_dead(s, SERVICE_SUCCESS, false);
2164 if ((r = manager_add_job(UNIT(s)->manager, JOB_START, UNIT(s), JOB_FAIL, false, &error, NULL)) < 0)
2167 log_debug("%s scheduled restart job.", UNIT(s)->id);
2171 log_warning("%s failed to schedule restart job: %s", UNIT(s)->id, bus_error(&error, -r));
2172 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, false);
2174 dbus_error_free(&error);
2177 static void service_enter_reload(Service *s) {
2182 service_unwatch_control_pid(s);
2184 if ((s->control_command = s->exec_command[SERVICE_EXEC_RELOAD])) {
2185 s->control_command_id = SERVICE_EXEC_RELOAD;
2187 if ((r = service_spawn(s,
2191 !s->permissions_start_only,
2192 !s->root_directory_start_only,
2195 &s->control_pid)) < 0)
2198 service_set_state(s, SERVICE_RELOAD);
2200 service_enter_running(s, SERVICE_SUCCESS);
2205 log_warning("%s failed to run 'reload' task: %s", UNIT(s)->id, strerror(-r));
2206 s->reload_result = SERVICE_FAILURE_RESOURCES;
2207 service_enter_running(s, SERVICE_SUCCESS);
2210 static void service_run_next_control(Service *s) {
2214 assert(s->control_command);
2215 assert(s->control_command->command_next);
2217 assert(s->control_command_id != SERVICE_EXEC_START);
2219 s->control_command = s->control_command->command_next;
2220 service_unwatch_control_pid(s);
2222 if ((r = service_spawn(s,
2226 !s->permissions_start_only,
2227 !s->root_directory_start_only,
2228 s->control_command_id == SERVICE_EXEC_START_PRE ||
2229 s->control_command_id == SERVICE_EXEC_STOP_POST,
2231 &s->control_pid)) < 0)
2237 log_warning("%s failed to run next control task: %s", UNIT(s)->id, strerror(-r));
2239 if (s->state == SERVICE_START_PRE)
2240 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
2241 else if (s->state == SERVICE_STOP)
2242 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
2243 else if (s->state == SERVICE_STOP_POST)
2244 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
2245 else if (s->state == SERVICE_RELOAD) {
2246 s->reload_result = SERVICE_FAILURE_RESOURCES;
2247 service_enter_running(s, SERVICE_SUCCESS);
2249 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2252 static void service_run_next_main(Service *s) {
2257 assert(s->main_command);
2258 assert(s->main_command->command_next);
2259 assert(s->type == SERVICE_ONESHOT);
2261 s->main_command = s->main_command->command_next;
2262 service_unwatch_main_pid(s);
2264 if ((r = service_spawn(s,
2271 s->notify_access != NOTIFY_NONE,
2275 service_set_main_pid(s, pid);
2280 log_warning("%s failed to run next main task: %s", UNIT(s)->id, strerror(-r));
2281 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2284 static int service_start(Unit *u) {
2285 Service *s = SERVICE(u);
2289 /* We cannot fulfill this request right now, try again later
2291 if (s->state == SERVICE_STOP ||
2292 s->state == SERVICE_STOP_SIGTERM ||
2293 s->state == SERVICE_STOP_SIGKILL ||
2294 s->state == SERVICE_STOP_POST ||
2295 s->state == SERVICE_FINAL_SIGTERM ||
2296 s->state == SERVICE_FINAL_SIGKILL)
2299 /* Already on it! */
2300 if (s->state == SERVICE_START_PRE ||
2301 s->state == SERVICE_START ||
2302 s->state == SERVICE_START_POST)
2305 assert(s->state == SERVICE_DEAD || s->state == SERVICE_FAILED || s->state == SERVICE_AUTO_RESTART);
2307 /* Make sure we don't enter a busy loop of some kind. */
2308 if (!ratelimit_test(&s->ratelimit)) {
2309 log_warning("%s start request repeated too quickly, refusing to start.", u->id);
2313 s->result = SERVICE_SUCCESS;
2314 s->reload_result = SERVICE_SUCCESS;
2315 s->main_pid_known = false;
2316 s->main_pid_alien = false;
2317 s->forbid_restart = false;
2319 service_enter_start_pre(s);
2323 static int service_stop(Unit *u) {
2324 Service *s = SERVICE(u);
2328 /* This is a user request, so don't do restarts on this
2330 s->forbid_restart = true;
2333 if (s->state == SERVICE_STOP ||
2334 s->state == SERVICE_STOP_SIGTERM ||
2335 s->state == SERVICE_STOP_SIGKILL ||
2336 s->state == SERVICE_STOP_POST ||
2337 s->state == SERVICE_FINAL_SIGTERM ||
2338 s->state == SERVICE_FINAL_SIGKILL)
2341 /* Don't allow a restart */
2342 if (s->state == SERVICE_AUTO_RESTART) {
2343 service_set_state(s, SERVICE_DEAD);
2347 /* If there's already something running we go directly into
2349 if (s->state == SERVICE_START_PRE ||
2350 s->state == SERVICE_START ||
2351 s->state == SERVICE_START_POST ||
2352 s->state == SERVICE_RELOAD) {
2353 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
2357 assert(s->state == SERVICE_RUNNING ||
2358 s->state == SERVICE_EXITED);
2360 service_enter_stop(s, SERVICE_SUCCESS);
2364 static int service_reload(Unit *u) {
2365 Service *s = SERVICE(u);
2369 assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
2371 service_enter_reload(s);
2375 static bool service_can_reload(Unit *u) {
2376 Service *s = SERVICE(u);
2380 return !!s->exec_command[SERVICE_EXEC_RELOAD];
2383 static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
2384 Service *s = SERVICE(u);
2390 unit_serialize_item(u, f, "state", service_state_to_string(s->state));
2391 unit_serialize_item(u, f, "result", service_result_to_string(s->result));
2392 unit_serialize_item(u, f, "reload-result", service_result_to_string(s->reload_result));
2394 if (s->control_pid > 0)
2395 unit_serialize_item_format(u, f, "control-pid", "%lu", (unsigned long) s->control_pid);
2397 if (s->main_pid_known && s->main_pid > 0)
2398 unit_serialize_item_format(u, f, "main-pid", "%lu", (unsigned long) s->main_pid);
2400 unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
2403 unit_serialize_item(u, f, "status-text", s->status_text);
2405 /* FIXME: There's a minor uncleanliness here: if there are
2406 * multiple commands attached here, we will start from the
2407 * first one again */
2408 if (s->control_command_id >= 0)
2409 unit_serialize_item(u, f, "control-command", service_exec_command_to_string(s->control_command_id));
2411 if (s->socket_fd >= 0) {
2414 if ((copy = fdset_put_dup(fds, s->socket_fd)) < 0)
2417 unit_serialize_item_format(u, f, "socket-fd", "%i", copy);
2420 if (s->main_exec_status.pid > 0) {
2421 unit_serialize_item_format(u, f, "main-exec-status-pid", "%lu", (unsigned long) s->main_exec_status.pid);
2422 dual_timestamp_serialize(f, "main-exec-status-start", &s->main_exec_status.start_timestamp);
2423 dual_timestamp_serialize(f, "main-exec-status-exit", &s->main_exec_status.exit_timestamp);
2425 if (dual_timestamp_is_set(&s->main_exec_status.exit_timestamp)) {
2426 unit_serialize_item_format(u, f, "main-exec-status-code", "%i", s->main_exec_status.code);
2427 unit_serialize_item_format(u, f, "main-exec-status-status", "%i", s->main_exec_status.status);
2430 if (dual_timestamp_is_set(&s->watchdog_timestamp))
2431 dual_timestamp_serialize(f, "watchdog-timestamp", &s->watchdog_timestamp);
2436 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
2437 Service *s = SERVICE(u);
2444 if (streq(key, "state")) {
2447 if ((state = service_state_from_string(value)) < 0)
2448 log_debug("Failed to parse state value %s", value);
2450 s->deserialized_state = state;
2451 } else if (streq(key, "result")) {
2454 f = service_result_from_string(value);
2456 log_debug("Failed to parse result value %s", value);
2457 else if (f != SERVICE_SUCCESS)
2460 } else if (streq(key, "reload-result")) {
2463 f = service_result_from_string(value);
2465 log_debug("Failed to parse reload result value %s", value);
2466 else if (f != SERVICE_SUCCESS)
2467 s->reload_result = f;
2469 } else if (streq(key, "control-pid")) {
2472 if (parse_pid(value, &pid) < 0)
2473 log_debug("Failed to parse control-pid value %s", value);
2475 s->control_pid = pid;
2476 } else if (streq(key, "main-pid")) {
2479 if (parse_pid(value, &pid) < 0)
2480 log_debug("Failed to parse main-pid value %s", value);
2482 service_set_main_pid(s, (pid_t) pid);
2483 } else if (streq(key, "main-pid-known")) {
2486 if ((b = parse_boolean(value)) < 0)
2487 log_debug("Failed to parse main-pid-known value %s", value);
2489 s->main_pid_known = b;
2490 } else if (streq(key, "status-text")) {
2493 if ((t = strdup(value))) {
2494 free(s->status_text);
2498 } else if (streq(key, "control-command")) {
2499 ServiceExecCommand id;
2501 if ((id = service_exec_command_from_string(value)) < 0)
2502 log_debug("Failed to parse exec-command value %s", value);
2504 s->control_command_id = id;
2505 s->control_command = s->exec_command[id];
2507 } else if (streq(key, "socket-fd")) {
2510 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2511 log_debug("Failed to parse socket-fd value %s", value);
2514 if (s->socket_fd >= 0)
2515 close_nointr_nofail(s->socket_fd);
2516 s->socket_fd = fdset_remove(fds, fd);
2518 } else if (streq(key, "main-exec-status-pid")) {
2521 if (parse_pid(value, &pid) < 0)
2522 log_debug("Failed to parse main-exec-status-pid value %s", value);
2524 s->main_exec_status.pid = pid;
2525 } else if (streq(key, "main-exec-status-code")) {
2528 if (safe_atoi(value, &i) < 0)
2529 log_debug("Failed to parse main-exec-status-code value %s", value);
2531 s->main_exec_status.code = i;
2532 } else if (streq(key, "main-exec-status-status")) {
2535 if (safe_atoi(value, &i) < 0)
2536 log_debug("Failed to parse main-exec-status-status value %s", value);
2538 s->main_exec_status.status = i;
2539 } else if (streq(key, "main-exec-status-start"))
2540 dual_timestamp_deserialize(value, &s->main_exec_status.start_timestamp);
2541 else if (streq(key, "main-exec-status-exit"))
2542 dual_timestamp_deserialize(value, &s->main_exec_status.exit_timestamp);
2543 else if (streq(key, "watchdog-timestamp"))
2544 dual_timestamp_deserialize(value, &s->watchdog_timestamp);
2546 log_debug("Unknown serialization key '%s'", key);
2551 static UnitActiveState service_active_state(Unit *u) {
2554 return state_translation_table[SERVICE(u)->state];
2557 static const char *service_sub_state_to_string(Unit *u) {
2560 return service_state_to_string(SERVICE(u)->state);
2563 static bool service_check_gc(Unit *u) {
2564 Service *s = SERVICE(u);
2568 /* Never clean up services that still have a process around,
2569 * even if the service is formally dead. */
2570 if (cgroup_good(s) > 0 ||
2571 main_pid_good(s) > 0 ||
2572 control_pid_good(s) > 0)
2575 #ifdef HAVE_SYSV_COMPAT
2583 static bool service_check_snapshot(Unit *u) {
2584 Service *s = SERVICE(u);
2588 return !s->got_socket_fd;
2591 static int service_retry_pid_file(Service *s) {
2594 assert(s->pid_file);
2595 assert(s->state == SERVICE_START || s->state == SERVICE_START_POST);
2597 r = service_load_pid_file(s, false);
2601 service_unwatch_pid_file(s);
2603 service_enter_running(s, SERVICE_SUCCESS);
2607 static int service_watch_pid_file(Service *s) {
2610 log_debug("Setting watch for %s's PID file %s", UNIT(s)->id, s->pid_file_pathspec->path);
2611 r = path_spec_watch(s->pid_file_pathspec, UNIT(s));
2615 /* the pidfile might have appeared just before we set the watch */
2616 service_retry_pid_file(s);
2620 log_error("Failed to set a watch for %s's PID file %s: %s",
2621 UNIT(s)->id, s->pid_file_pathspec->path, strerror(-r));
2622 service_unwatch_pid_file(s);
2626 static int service_demand_pid_file(Service *s) {
2629 assert(s->pid_file);
2630 assert(!s->pid_file_pathspec);
2632 ps = new0(PathSpec, 1);
2636 ps->path = strdup(s->pid_file);
2642 path_kill_slashes(ps->path);
2644 /* PATH_CHANGED would not be enough. There are daemons (sendmail) that
2645 * keep their PID file open all the time. */
2646 ps->type = PATH_MODIFIED;
2647 ps->inotify_fd = -1;
2649 s->pid_file_pathspec = ps;
2651 return service_watch_pid_file(s);
2654 static void service_fd_event(Unit *u, int fd, uint32_t events, Watch *w) {
2655 Service *s = SERVICE(u);
2659 assert(s->state == SERVICE_START || s->state == SERVICE_START_POST);
2660 assert(s->pid_file_pathspec);
2661 assert(path_spec_owns_inotify_fd(s->pid_file_pathspec, fd));
2663 log_debug("inotify event for %s", u->id);
2665 if (path_spec_fd_event(s->pid_file_pathspec, events) < 0)
2668 if (service_retry_pid_file(s) == 0)
2671 if (service_watch_pid_file(s) < 0)
2676 service_unwatch_pid_file(s);
2677 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
2680 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2681 Service *s = SERVICE(u);
2687 if (UNIT(s)->fragment_path ? is_clean_exit(code, status) : is_clean_exit_lsb(code, status))
2688 f = SERVICE_SUCCESS;
2689 else if (code == CLD_EXITED)
2690 f = SERVICE_FAILURE_EXIT_CODE;
2691 else if (code == CLD_KILLED)
2692 f = SERVICE_FAILURE_SIGNAL;
2693 else if (code == CLD_DUMPED)
2694 f = SERVICE_FAILURE_CORE_DUMP;
2696 assert_not_reached("Unknown code");
2698 if (s->main_pid == pid) {
2699 /* Forking services may occasionally move to a new PID.
2700 * As long as they update the PID file before exiting the old
2701 * PID, they're fine. */
2702 if (service_load_pid_file(s, false) == 0)
2706 exec_status_exit(&s->main_exec_status, &s->exec_context, pid, code, status);
2708 /* If this is not a forking service than the main
2709 * process got started and hence we copy the exit
2710 * status so that it is recorded both as main and as
2711 * control process exit status */
2712 if (s->main_command) {
2713 s->main_command->exec_status = s->main_exec_status;
2715 if (s->main_command->ignore)
2716 f = SERVICE_SUCCESS;
2719 log_full(f == SERVICE_SUCCESS ? LOG_DEBUG : LOG_NOTICE,
2720 "%s: main process exited, code=%s, status=%i", u->id, sigchld_code_to_string(code), status);
2722 if (f != SERVICE_SUCCESS)
2725 if (s->main_command &&
2726 s->main_command->command_next &&
2727 f == SERVICE_SUCCESS) {
2729 /* There is another command to *
2730 * execute, so let's do that. */
2732 log_debug("%s running next main command for state %s", u->id, service_state_to_string(s->state));
2733 service_run_next_main(s);
2737 /* The service exited, so the service is officially
2739 s->main_command = NULL;
2743 case SERVICE_START_POST:
2744 case SERVICE_RELOAD:
2746 /* Need to wait until the operation is
2751 if (s->type == SERVICE_ONESHOT) {
2752 /* This was our main goal, so let's go on */
2753 if (f == SERVICE_SUCCESS)
2754 service_enter_start_post(s);
2756 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
2759 assert(s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY);
2764 case SERVICE_RUNNING:
2765 service_enter_running(s, f);
2768 case SERVICE_STOP_SIGTERM:
2769 case SERVICE_STOP_SIGKILL:
2771 if (!control_pid_good(s))
2772 service_enter_stop_post(s, f);
2774 /* If there is still a control process, wait for that first */
2778 assert_not_reached("Uh, main process died at wrong time.");
2782 } else if (s->control_pid == pid) {
2786 if (s->control_command) {
2787 exec_status_exit(&s->control_command->exec_status, &s->exec_context, pid, code, status);
2789 if (s->control_command->ignore)
2790 f = SERVICE_SUCCESS;
2793 log_full(f == SERVICE_SUCCESS ? LOG_DEBUG : LOG_NOTICE,
2794 "%s: control process exited, code=%s status=%i", u->id, sigchld_code_to_string(code), status);
2796 if (f != SERVICE_SUCCESS)
2799 if (s->control_command &&
2800 s->control_command->command_next &&
2801 f == SERVICE_SUCCESS) {
2803 /* There is another command to *
2804 * execute, so let's do that. */
2806 log_debug("%s running next control command for state %s", u->id, service_state_to_string(s->state));
2807 service_run_next_control(s);
2810 /* No further commands for this step, so let's
2811 * figure out what to do next */
2813 s->control_command = NULL;
2814 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2816 log_debug("%s got final SIGCHLD for state %s", u->id, service_state_to_string(s->state));
2820 case SERVICE_START_PRE:
2821 if (f == SERVICE_SUCCESS)
2822 service_enter_start(s);
2824 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
2828 assert(s->type == SERVICE_FORKING);
2830 if (f != SERVICE_SUCCESS) {
2831 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
2836 bool has_start_post;
2839 /* Let's try to load the pid file here if we can.
2840 * The PID file might actually be created by a START_POST
2841 * script. In that case don't worry if the loading fails. */
2843 has_start_post = !!s->exec_command[SERVICE_EXEC_START_POST];
2844 r = service_load_pid_file(s, !has_start_post);
2845 if (!has_start_post && r < 0) {
2846 r = service_demand_pid_file(s);
2847 if (r < 0 || !cgroup_good(s))
2848 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
2852 service_search_main_pid(s);
2854 service_enter_start_post(s);
2857 case SERVICE_START_POST:
2858 if (f != SERVICE_SUCCESS) {
2859 service_enter_stop(s, f);
2866 r = service_load_pid_file(s, true);
2868 r = service_demand_pid_file(s);
2869 if (r < 0 || !cgroup_good(s))
2870 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2874 service_search_main_pid(s);
2876 service_enter_running(s, SERVICE_SUCCESS);
2879 case SERVICE_RELOAD:
2880 if (f == SERVICE_SUCCESS) {
2881 service_load_pid_file(s, true);
2882 service_search_main_pid(s);
2885 s->reload_result = f;
2886 service_enter_running(s, SERVICE_SUCCESS);
2890 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
2893 case SERVICE_STOP_SIGTERM:
2894 case SERVICE_STOP_SIGKILL:
2895 if (main_pid_good(s) <= 0)
2896 service_enter_stop_post(s, f);
2898 /* If there is still a service
2899 * process around, wait until
2900 * that one quit, too */
2903 case SERVICE_STOP_POST:
2904 case SERVICE_FINAL_SIGTERM:
2905 case SERVICE_FINAL_SIGKILL:
2906 service_enter_dead(s, f, true);
2910 assert_not_reached("Uh, control process died at wrong time.");
2915 /* Notify clients about changed exit status */
2916 unit_add_to_dbus_queue(u);
2919 static void service_timer_event(Unit *u, uint64_t elapsed, Watch* w) {
2920 Service *s = SERVICE(u);
2923 assert(elapsed == 1);
2925 assert(w == &s->timer_watch);
2929 case SERVICE_START_PRE:
2931 log_warning("%s operation timed out. Terminating.", u->id);
2932 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2935 case SERVICE_START_POST:
2936 log_warning("%s operation timed out. Stopping.", u->id);
2937 service_enter_stop(s, SERVICE_FAILURE_TIMEOUT);
2940 case SERVICE_RELOAD:
2941 log_warning("%s operation timed out. Stopping.", u->id);
2942 s->reload_result = SERVICE_FAILURE_TIMEOUT;
2943 service_enter_running(s, SERVICE_SUCCESS);
2947 log_warning("%s stopping timed out. Terminating.", u->id);
2948 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2951 case SERVICE_STOP_SIGTERM:
2952 if (s->exec_context.send_sigkill) {
2953 log_warning("%s stopping timed out. Killing.", u->id);
2954 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_TIMEOUT);
2956 log_warning("%s stopping timed out. Skipping SIGKILL.", u->id);
2957 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
2962 case SERVICE_STOP_SIGKILL:
2963 /* Uh, we sent a SIGKILL and it is still not gone?
2964 * Must be something we cannot kill, so let's just be
2965 * weirded out and continue */
2967 log_warning("%s still around after SIGKILL. Ignoring.", u->id);
2968 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
2971 case SERVICE_STOP_POST:
2972 log_warning("%s stopping timed out (2). Terminating.", u->id);
2973 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2976 case SERVICE_FINAL_SIGTERM:
2977 if (s->exec_context.send_sigkill) {
2978 log_warning("%s stopping timed out (2). Killing.", u->id);
2979 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_FAILURE_TIMEOUT);
2981 log_warning("%s stopping timed out (2). Skipping SIGKILL. Entering failed mode.", u->id);
2982 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, false);
2987 case SERVICE_FINAL_SIGKILL:
2988 log_warning("%s still around after SIGKILL (2). Entering failed mode.", u->id);
2989 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, true);
2992 case SERVICE_AUTO_RESTART:
2993 log_info("%s holdoff time over, scheduling restart.", u->id);
2994 service_enter_restart(s);
2998 assert_not_reached("Timeout at wrong time.");
3002 static void service_cgroup_notify_event(Unit *u) {
3003 Service *s = SERVICE(u);
3007 log_debug("%s: cgroup is empty", u->id);
3011 /* Waiting for SIGCHLD is usually more interesting,
3012 * because it includes return codes/signals. Which is
3013 * why we ignore the cgroup events for most cases,
3014 * except when we don't know pid which to expect the
3018 case SERVICE_START_POST:
3019 /* If we were hoping for the daemon to write its PID file,
3020 * we can give up now. */
3021 if (s->pid_file_pathspec) {
3022 log_warning("%s never wrote its PID file. Failing.", UNIT(s)->id);
3023 service_unwatch_pid_file(s);
3024 if (s->state == SERVICE_START)
3025 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
3027 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
3031 case SERVICE_RUNNING:
3032 /* service_enter_running() will figure out what to do */
3033 service_enter_running(s, SERVICE_SUCCESS);
3036 case SERVICE_STOP_SIGTERM:
3037 case SERVICE_STOP_SIGKILL:
3039 if (main_pid_good(s) <= 0 && !control_pid_good(s))
3040 service_enter_stop_post(s, SERVICE_SUCCESS);
3044 case SERVICE_FINAL_SIGTERM:
3045 case SERVICE_FINAL_SIGKILL:
3046 if (main_pid_good(s) <= 0 && !control_pid_good(s))
3047 service_enter_dead(s, SERVICE_SUCCESS, SERVICE_SUCCESS);
3056 static void service_notify_message(Unit *u, pid_t pid, char **tags) {
3057 Service *s = SERVICE(u);
3062 if (s->notify_access == NOTIFY_NONE) {
3063 log_warning("%s: Got notification message from PID %lu, but reception is disabled.",
3064 u->id, (unsigned long) pid);
3068 if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
3069 log_warning("%s: Got notification message from PID %lu, but reception only permitted for PID %lu",
3070 u->id, (unsigned long) pid, (unsigned long) s->main_pid);
3074 log_debug("%s: Got message", u->id);
3076 /* Interpret MAINPID= */
3077 if ((e = strv_find_prefix(tags, "MAINPID=")) &&
3078 (s->state == SERVICE_START ||
3079 s->state == SERVICE_START_POST ||
3080 s->state == SERVICE_RUNNING ||
3081 s->state == SERVICE_RELOAD)) {
3083 if (parse_pid(e + 8, &pid) < 0)
3084 log_warning("Failed to parse notification message %s", e);
3086 log_debug("%s: got %s", u->id, e);
3087 service_set_main_pid(s, pid);
3091 /* Interpret READY= */
3092 if (s->type == SERVICE_NOTIFY &&
3093 s->state == SERVICE_START &&
3094 strv_find(tags, "READY=1")) {
3095 log_debug("%s: got READY=1", u->id);
3097 service_enter_start_post(s);
3100 /* Interpret STATUS= */
3101 if ((e = strv_find_prefix(tags, "STATUS="))) {
3105 if (!(t = strdup(e+7))) {
3106 log_error("Failed to allocate string.");
3110 log_debug("%s: got %s", u->id, e);
3112 free(s->status_text);
3115 free(s->status_text);
3116 s->status_text = NULL;
3120 if (strv_find(tags, "WATCHDOG=1")) {
3121 log_debug("%s: got WATCHDOG=1", u->id);
3122 service_reset_watchdog(s);
3125 /* Notify clients about changed status or main pid */
3126 unit_add_to_dbus_queue(u);
3129 #ifdef HAVE_SYSV_COMPAT
3132 static void sysv_facility_in_insserv_conf(Manager *mgr) {
3136 if (!(f = fopen("/etc/insserv.conf", "re"))) {
3137 r = errno == ENOENT ? 0 : -errno;
3142 char l[LINE_MAX], *t;
3143 char **parsed = NULL;
3145 if (!fgets(l, sizeof(l), f)) {
3150 log_error("Failed to read configuration file '/etc/insserv.conf': %s", strerror(-r));
3155 if (*t != '$' && *t != '<')
3158 parsed = strv_split(t,WHITESPACE);
3159 /* we ignore <interactive>, not used, equivalent to X-Interactive */
3160 if (parsed && !startswith_no_case (parsed[0], "<interactive>")) {
3163 if (sysv_translate_facility(parsed[0], NULL, &facility) < 0)
3165 if ((u = manager_get_unit(mgr, facility)) && (u->type == UNIT_TARGET)) {
3167 char *dep = NULL, *name, **j;
3169 STRV_FOREACH (j, parsed+1) {
3178 if (sysv_translate_facility(name, NULL, &dep) < 0)
3181 r = unit_add_two_dependencies_by_name(u, UNIT_BEFORE, e, dep, NULL, true);
3196 static int service_enumerate(Manager *m) {
3200 char *path = NULL, *fpath = NULL, *name = NULL;
3201 Set *runlevel_services[ELEMENTSOF(rcnd_table)], *shutdown_services = NULL;
3208 if (m->running_as != MANAGER_SYSTEM)
3211 zero(runlevel_services);
3213 STRV_FOREACH(p, m->lookup_paths.sysvrcnd_path)
3214 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++) {
3218 path = join(*p, "/", rcnd_table[i].path, NULL);
3227 if (!(d = opendir(path))) {
3228 if (errno != ENOENT)
3229 log_warning("opendir() failed on %s: %s", path, strerror(errno));
3234 while ((de = readdir(d))) {
3237 if (ignore_file(de->d_name))
3240 if (de->d_name[0] != 'S' && de->d_name[0] != 'K')
3243 if (strlen(de->d_name) < 4)
3246 a = undecchar(de->d_name[1]);
3247 b = undecchar(de->d_name[2]);
3253 fpath = join(path, "/", de->d_name, NULL);
3259 if (access(fpath, X_OK) < 0) {
3261 if (errno != ENOENT)
3262 log_warning("access() failed on %s: %s", fpath, strerror(errno));
3268 if (!(name = sysv_translate_name(de->d_name + 3))) {
3273 if ((r = manager_load_unit_prepare(m, name, NULL, NULL, &service)) < 0) {
3274 log_warning("Failed to prepare unit %s: %s", name, strerror(-r));
3278 if (de->d_name[0] == 'S') {
3280 if (rcnd_table[i].type == RUNLEVEL_UP || rcnd_table[i].type == RUNLEVEL_SYSINIT) {
3281 SERVICE(service)->sysv_start_priority_from_rcnd =
3282 MAX(a*10 + b, SERVICE(service)->sysv_start_priority_from_rcnd);
3284 SERVICE(service)->sysv_enabled = true;
3287 if ((r = set_ensure_allocated(&runlevel_services[i], trivial_hash_func, trivial_compare_func)) < 0)
3290 if ((r = set_put(runlevel_services[i], service)) < 0)
3293 } else if (de->d_name[0] == 'K' &&
3294 (rcnd_table[i].type == RUNLEVEL_DOWN ||
3295 rcnd_table[i].type == RUNLEVEL_SYSINIT)) {
3297 if ((r = set_ensure_allocated(&shutdown_services, trivial_hash_func, trivial_compare_func)) < 0)
3300 if ((r = set_put(shutdown_services, service)) < 0)
3306 /* Now we loaded all stubs and are aware of the lowest
3307 start-up priority for all services, not let's actually load
3308 the services, this will also tell us which services are
3309 actually native now */
3310 manager_dispatch_load_queue(m);
3312 /* If this is a native service, rely on native ways to pull in
3313 * a service, don't pull it in via sysv rcN.d links. */
3314 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++)
3315 SET_FOREACH(service, runlevel_services[i], j) {
3316 service = unit_follow_merge(service);
3318 if (service->fragment_path)
3321 if ((r = unit_add_two_dependencies_by_name_inverse(service, UNIT_AFTER, UNIT_WANTS, rcnd_table[i].target, NULL, true)) < 0)
3325 /* We honour K links only for halt/reboot. For the normal
3326 * runlevels we assume the stop jobs will be implicitly added
3327 * by the core logic. Also, we don't really distinguish here
3328 * between the runlevels 0 and 6 and just add them to the
3329 * special shutdown target. On SUSE the boot.d/ runlevel is
3330 * also used for shutdown, so we add links for that too to the
3331 * shutdown target.*/
3332 SET_FOREACH(service, shutdown_services, j) {
3333 service = unit_follow_merge(service);
3335 if (service->fragment_path)
3338 if ((r = unit_add_two_dependencies_by_name(service, UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true)) < 0)
3345 sysv_facility_in_insserv_conf (m);
3353 for (i = 0; i < ELEMENTSOF(rcnd_table); i++)
3354 set_free(runlevel_services[i]);
3355 set_free(shutdown_services);
3364 static void service_bus_name_owner_change(
3367 const char *old_owner,
3368 const char *new_owner) {
3370 Service *s = SERVICE(u);
3375 assert(streq(s->bus_name, name));
3376 assert(old_owner || new_owner);
3378 if (old_owner && new_owner)
3379 log_debug("%s's D-Bus name %s changed owner from %s to %s", u->id, name, old_owner, new_owner);
3381 log_debug("%s's D-Bus name %s no longer registered by %s", u->id, name, old_owner);
3383 log_debug("%s's D-Bus name %s now registered by %s", u->id, name, new_owner);
3385 s->bus_name_good = !!new_owner;
3387 if (s->type == SERVICE_DBUS) {
3389 /* service_enter_running() will figure out what to
3391 if (s->state == SERVICE_RUNNING)
3392 service_enter_running(s, SERVICE_SUCCESS);
3393 else if (s->state == SERVICE_START && new_owner)
3394 service_enter_start_post(s);
3396 } else if (new_owner &&
3398 (s->state == SERVICE_START ||
3399 s->state == SERVICE_START_POST ||
3400 s->state == SERVICE_RUNNING ||
3401 s->state == SERVICE_RELOAD)) {
3403 /* Try to acquire PID from bus service */
3404 log_debug("Trying to acquire PID from D-Bus name...");
3406 bus_query_pid(u->manager, name);
3410 static void service_bus_query_pid_done(
3415 Service *s = SERVICE(u);
3420 log_debug("%s's D-Bus name %s is now owned by process %u", u->id, name, (unsigned) pid);
3422 if (s->main_pid <= 0 &&
3423 (s->state == SERVICE_START ||
3424 s->state == SERVICE_START_POST ||
3425 s->state == SERVICE_RUNNING ||
3426 s->state == SERVICE_RELOAD))
3427 service_set_main_pid(s, pid);
3430 int service_set_socket_fd(Service *s, int fd, Socket *sock) {
3435 /* This is called by the socket code when instantiating a new
3436 * service for a stream socket and the socket needs to be
3439 if (UNIT(s)->load_state != UNIT_LOADED)
3442 if (s->socket_fd >= 0)
3445 if (s->state != SERVICE_DEAD)
3449 s->got_socket_fd = true;
3451 unit_ref_set(&s->accept_socket, UNIT(sock));
3453 return unit_add_two_dependencies(UNIT(sock), UNIT_BEFORE, UNIT_TRIGGERS, UNIT(s), false);
3456 static void service_reset_failed(Unit *u) {
3457 Service *s = SERVICE(u);
3461 if (s->state == SERVICE_FAILED)
3462 service_set_state(s, SERVICE_DEAD);
3464 s->result = SERVICE_SUCCESS;
3465 s->reload_result = SERVICE_SUCCESS;
3468 static bool service_need_daemon_reload(Unit *u) {
3469 Service *s = SERVICE(u);
3473 #ifdef HAVE_SYSV_COMPAT
3478 if (stat(s->sysv_path, &st) < 0)
3479 /* What, cannot access this anymore? */
3482 if (s->sysv_mtime > 0 &&
3483 timespec_load(&st.st_mtim) != s->sysv_mtime)
3491 static int service_kill(Unit *u, KillWho who, KillMode mode, int signo, DBusError *error) {
3492 Service *s = SERVICE(u);
3494 Set *pid_set = NULL;
3498 if (s->main_pid <= 0 && who == KILL_MAIN) {
3499 dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "No main process to kill");
3503 if (s->control_pid <= 0 && who == KILL_CONTROL) {
3504 dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "No control process to kill");
3508 if (who == KILL_CONTROL || who == KILL_ALL)
3509 if (s->control_pid > 0)
3510 if (kill(s->control_pid, signo) < 0)
3513 if (who == KILL_MAIN || who == KILL_ALL)
3514 if (s->main_pid > 0)
3515 if (kill(s->main_pid, signo) < 0)
3518 if (who == KILL_ALL && mode == KILL_CONTROL_GROUP) {
3521 if (!(pid_set = set_new(trivial_hash_func, trivial_compare_func)))
3524 /* Exclude the control/main pid from being killed via the cgroup */
3525 if (s->control_pid > 0)
3526 if ((q = set_put(pid_set, LONG_TO_PTR(s->control_pid))) < 0) {
3531 if (s->main_pid > 0)
3532 if ((q = set_put(pid_set, LONG_TO_PTR(s->main_pid))) < 0) {
3537 if ((q = cgroup_bonding_kill_list(UNIT(s)->cgroup_bondings, signo, false, pid_set)) < 0)
3538 if (q != -EAGAIN && q != -ESRCH && q != -ENOENT)
3549 static const char* const service_state_table[_SERVICE_STATE_MAX] = {
3550 [SERVICE_DEAD] = "dead",
3551 [SERVICE_START_PRE] = "start-pre",
3552 [SERVICE_START] = "start",
3553 [SERVICE_START_POST] = "start-post",
3554 [SERVICE_RUNNING] = "running",
3555 [SERVICE_EXITED] = "exited",
3556 [SERVICE_RELOAD] = "reload",
3557 [SERVICE_STOP] = "stop",
3558 [SERVICE_STOP_SIGTERM] = "stop-sigterm",
3559 [SERVICE_STOP_SIGKILL] = "stop-sigkill",
3560 [SERVICE_STOP_POST] = "stop-post",
3561 [SERVICE_FINAL_SIGTERM] = "final-sigterm",
3562 [SERVICE_FINAL_SIGKILL] = "final-sigkill",
3563 [SERVICE_FAILED] = "failed",
3564 [SERVICE_AUTO_RESTART] = "auto-restart",
3567 DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
3569 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
3570 [SERVICE_RESTART_NO] = "no",
3571 [SERVICE_RESTART_ON_SUCCESS] = "on-success",
3572 [SERVICE_RESTART_ON_FAILURE] = "on-failure",
3573 [SERVICE_RESTART_ON_ABORT] = "on-abort",
3574 [SERVICE_RESTART_ALWAYS] = "always"
3577 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
3579 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
3580 [SERVICE_SIMPLE] = "simple",
3581 [SERVICE_FORKING] = "forking",
3582 [SERVICE_ONESHOT] = "oneshot",
3583 [SERVICE_DBUS] = "dbus",
3584 [SERVICE_NOTIFY] = "notify"
3587 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
3589 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
3590 [SERVICE_EXEC_START_PRE] = "ExecStartPre",
3591 [SERVICE_EXEC_START] = "ExecStart",
3592 [SERVICE_EXEC_START_POST] = "ExecStartPost",
3593 [SERVICE_EXEC_RELOAD] = "ExecReload",
3594 [SERVICE_EXEC_STOP] = "ExecStop",
3595 [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
3598 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
3600 static const char* const notify_access_table[_NOTIFY_ACCESS_MAX] = {
3601 [NOTIFY_NONE] = "none",
3602 [NOTIFY_MAIN] = "main",
3603 [NOTIFY_ALL] = "all"
3606 DEFINE_STRING_TABLE_LOOKUP(notify_access, NotifyAccess);
3608 static const char* const service_result_table[_SERVICE_RESULT_MAX] = {
3609 [SERVICE_SUCCESS] = "success",
3610 [SERVICE_FAILURE_RESOURCES] = "resources",
3611 [SERVICE_FAILURE_TIMEOUT] = "timeout",
3612 [SERVICE_FAILURE_EXIT_CODE] = "exit-code",
3613 [SERVICE_FAILURE_SIGNAL] = "signal",
3614 [SERVICE_FAILURE_CORE_DUMP] = "core-dump"
3617 DEFINE_STRING_TABLE_LOOKUP(service_result, ServiceResult);
3619 const UnitVTable service_vtable = {
3620 .suffix = ".service",
3621 .object_size = sizeof(Service),
3626 .show_status = true,
3628 .init = service_init,
3629 .done = service_done,
3630 .load = service_load,
3632 .coldplug = service_coldplug,
3634 .dump = service_dump,
3636 .start = service_start,
3637 .stop = service_stop,
3638 .reload = service_reload,
3640 .can_reload = service_can_reload,
3642 .kill = service_kill,
3644 .serialize = service_serialize,
3645 .deserialize_item = service_deserialize_item,
3647 .active_state = service_active_state,
3648 .sub_state_to_string = service_sub_state_to_string,
3650 .check_gc = service_check_gc,
3651 .check_snapshot = service_check_snapshot,
3653 .sigchld_event = service_sigchld_event,
3654 .timer_event = service_timer_event,
3655 .fd_event = service_fd_event,
3657 .reset_failed = service_reset_failed,
3659 .need_daemon_reload = service_need_daemon_reload,
3661 .cgroup_notify_empty = service_cgroup_notify_event,
3662 .notify_message = service_notify_message,
3664 .bus_name_owner_change = service_bus_name_owner_change,
3665 .bus_query_pid_done = service_bus_query_pid_done,
3667 .bus_interface = "org.freedesktop.systemd1.Service",
3668 .bus_message_handler = bus_service_message_handler,
3669 .bus_invalidating_properties = bus_service_invalidating_properties,
3671 #ifdef HAVE_SYSV_COMPAT
3672 .enumerate = service_enumerate