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_done(Unit *u) {
209 Service *s = SERVICE(u);
216 #ifdef HAVE_SYSV_COMPAT
220 free(s->sysv_runlevels);
221 s->sysv_runlevels = NULL;
224 free(s->status_text);
225 s->status_text = NULL;
227 exec_context_done(&s->exec_context);
228 exec_command_free_array(s->exec_command, _SERVICE_EXEC_COMMAND_MAX);
229 s->control_command = NULL;
230 s->main_command = NULL;
232 /* This will leak a process, but at least no memory or any of
234 service_unwatch_main_pid(s);
235 service_unwatch_control_pid(s);
236 service_unwatch_pid_file(s);
239 unit_unwatch_bus_name(u, s->bus_name);
244 service_close_socket_fd(s);
245 service_connection_unref(s);
247 unit_ref_unset(&s->accept_socket);
249 unit_unwatch_timer(u, &s->timer_watch);
252 #ifdef HAVE_SYSV_COMPAT
253 static char *sysv_translate_name(const char *name) {
256 if (!(r = new(char, strlen(name) + sizeof(".service"))))
259 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU) || defined(TARGET_ANGSTROM)
260 if (endswith(name, ".sh"))
261 /* Drop Debian-style .sh suffix */
262 strcpy(stpcpy(r, name) - 3, ".service");
265 if (startswith(name, "boot."))
266 /* Drop SuSE-style boot. prefix */
267 strcpy(stpcpy(r, name + 5), ".service");
269 #ifdef TARGET_FRUGALWARE
270 if (startswith(name, "rc."))
271 /* Drop Frugalware-style rc. prefix */
272 strcpy(stpcpy(r, name + 3), ".service");
275 /* Normal init scripts */
276 strcpy(stpcpy(r, name), ".service");
281 static int sysv_translate_facility(const char *name, const char *filename, char **_r) {
283 /* We silently ignore the $ prefix here. According to the LSB
284 * spec it simply indicates whether something is a
285 * standardized name or a distribution-specific one. Since we
286 * just follow what already exists and do not introduce new
287 * uses or names we don't care who introduced a new name. */
289 static const char * const table[] = {
290 /* LSB defined facilities */
291 "local_fs", SPECIAL_LOCAL_FS_TARGET,
292 #if defined(TARGET_MANDRIVA) || defined(TARGET_MAGEIA)
294 /* Due to unfortunate name selection in Mandriva,
295 * $network is provided by network-up which is ordered
296 * after network which actually starts interfaces.
297 * To break the loop, just ignore it */
298 "network", SPECIAL_NETWORK_TARGET,
300 "named", SPECIAL_NSS_LOOKUP_TARGET,
301 "portmap", SPECIAL_RPCBIND_TARGET,
302 "remote_fs", SPECIAL_REMOTE_FS_TARGET,
303 "syslog", SPECIAL_SYSLOG_TARGET,
304 "time", SPECIAL_TIME_SYNC_TARGET,
306 /* common extensions */
307 "mail-transfer-agent", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
308 "x-display-manager", SPECIAL_DISPLAY_MANAGER_SERVICE,
311 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU) || defined(TARGET_ANGSTROM)
312 "mail-transport-agent", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
316 "MTA", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
317 "smtpdaemon", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
318 "httpd", SPECIAL_HTTP_DAEMON_TARGET,
322 "smtp", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
333 n = *name == '$' ? name + 1 : name;
335 for (i = 0; i < ELEMENTSOF(table); i += 2) {
337 if (!streq(table[i], n))
343 if (!(r = strdup(table[i+1])))
349 /* If we don't know this name, fallback heuristics to figure
350 * out whether something is a target or a service alias. */
353 if (!unit_prefix_is_valid(n))
356 /* Facilities starting with $ are most likely targets */
357 r = unit_name_build(n, NULL, ".target");
358 } else if (filename && streq(name, filename))
359 /* Names equaling the file name of the services are redundant */
362 /* Everything else we assume to be normal service names */
363 r = sysv_translate_name(n);
374 static int sysv_fix_order(Service *s) {
380 if (s->sysv_start_priority < 0)
383 /* For each pair of services where at least one lacks a LSB
384 * header, we use the start priority value to order things. */
386 LIST_FOREACH(units_by_type, other, UNIT(s)->manager->units_by_type[UNIT_SERVICE]) {
389 bool special_s, special_t;
396 if (UNIT(t)->load_state != UNIT_LOADED)
399 if (t->sysv_start_priority < 0)
402 /* If both units have modern headers we don't care
403 * about the priorities */
404 if ((UNIT(s)->fragment_path || s->sysv_has_lsb) &&
405 (UNIT(t)->fragment_path || t->sysv_has_lsb))
408 special_s = s->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, s->sysv_runlevels);
409 special_t = t->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, t->sysv_runlevels);
411 if (special_t && !special_s)
413 else if (special_s && !special_t)
415 else if (t->sysv_start_priority < s->sysv_start_priority)
417 else if (t->sysv_start_priority > s->sysv_start_priority)
422 /* FIXME: Maybe we should compare the name here lexicographically? */
424 if ((r = unit_add_dependency(UNIT(s), d, UNIT(t), true)) < 0)
431 static ExecCommand *exec_command_new(const char *path, const char *arg1) {
434 if (!(c = new0(ExecCommand, 1)))
437 if (!(c->path = strdup(path))) {
442 if (!(c->argv = strv_new(path, arg1, NULL))) {
451 static int sysv_exec_commands(Service *s) {
455 assert(s->sysv_path);
457 if (!(c = exec_command_new(s->sysv_path, "start")))
459 exec_command_append_list(s->exec_command+SERVICE_EXEC_START, c);
461 if (!(c = exec_command_new(s->sysv_path, "stop")))
463 exec_command_append_list(s->exec_command+SERVICE_EXEC_STOP, c);
465 if (!(c = exec_command_new(s->sysv_path, "reload")))
467 exec_command_append_list(s->exec_command+SERVICE_EXEC_RELOAD, c);
472 static int service_load_sysv_path(Service *s, const char *path) {
483 char *short_description = NULL, *long_description = NULL, *chkconfig_description = NULL, *description;
491 if (!(f = fopen(path, "re"))) {
492 r = errno == ENOENT ? 0 : -errno;
497 if (fstat(fileno(f), &st) < 0) {
503 if (!(s->sysv_path = strdup(path))) {
508 s->sysv_mtime = timespec_load(&st.st_mtim);
510 if (null_or_empty(&st)) {
511 u->load_state = UNIT_MASKED;
517 char l[LINE_MAX], *t;
519 if (!fgets(l, sizeof(l), f)) {
524 log_error("Failed to read configuration file '%s': %s", path, strerror(-r));
534 if (state == NORMAL && streq(t, "### BEGIN INIT INFO")) {
536 s->sysv_has_lsb = true;
540 if ((state == LSB_DESCRIPTION || state == LSB) && streq(t, "### END INIT INFO")) {
546 t += strspn(t, WHITESPACE);
548 if (state == NORMAL) {
550 /* Try to parse Red Hat style chkconfig headers */
552 if (startswith_no_case(t, "chkconfig:")) {
554 char runlevels[16], *k;
558 if (sscanf(t+10, "%15s %i %*i",
560 &start_priority) != 2) {
562 log_warning("[%s:%u] Failed to parse chkconfig line. Ignoring.", path, line);
566 /* A start priority gathered from the
567 * symlink farms is preferred over the
568 * data from the LSB header. */
569 if (start_priority < 0 || start_priority > 99)
570 log_warning("[%s:%u] Start priority out of range. Ignoring.", path, line);
572 s->sysv_start_priority = start_priority;
574 char_array_0(runlevels);
575 k = delete_chars(runlevels, WHITESPACE "-");
580 if (!(d = strdup(k))) {
585 free(s->sysv_runlevels);
586 s->sysv_runlevels = d;
589 } else if (startswith_no_case(t, "description:")) {
591 size_t k = strlen(t);
595 if (t[k-1] == '\\') {
600 if ((j = strstrip(t+12)) && *j) {
601 if (!(d = strdup(j))) {
608 free(chkconfig_description);
609 chkconfig_description = d;
611 } else if (startswith_no_case(t, "pidfile:")) {
618 if (!path_is_absolute(fn)) {
619 log_warning("[%s:%u] PID file not absolute. Ignoring.", path, line);
623 if (!(fn = strdup(fn))) {
632 } else if (state == DESCRIPTION) {
634 /* Try to parse Red Hat style description
637 size_t k = strlen(t);
645 if ((j = strstrip(t)) && *j) {
648 if (chkconfig_description)
649 d = join(chkconfig_description, " ", j, NULL);
658 free(chkconfig_description);
659 chkconfig_description = d;
662 } else if (state == LSB || state == LSB_DESCRIPTION) {
664 if (startswith_no_case(t, "Provides:")) {
670 FOREACH_WORD_QUOTED(w, z, t+9, i) {
673 if (!(n = strndup(w, z))) {
678 r = sysv_translate_facility(n, file_name_from_path(path), &m);
687 if (unit_name_to_type(m) == UNIT_SERVICE)
688 r = unit_add_name(u, m);
695 * indication that the
697 * now available. This
700 * targets do NOT pull
703 r = unit_add_two_dependencies_by_name(u, UNIT_BEFORE, UNIT_WANTS, m, NULL, true);
706 log_error("[%s:%u] Failed to add LSB Provides name %s, ignoring: %s", path, line, m, strerror(-r));
711 } else if (startswith_no_case(t, "Required-Start:") ||
712 startswith_no_case(t, "Should-Start:") ||
713 startswith_no_case(t, "X-Start-Before:") ||
714 startswith_no_case(t, "X-Start-After:")) {
720 FOREACH_WORD_QUOTED(w, z, strchr(t, ':')+1, i) {
723 if (!(n = strndup(w, z))) {
728 r = sysv_translate_facility(n, file_name_from_path(path), &m);
731 log_error("[%s:%u] Failed to translate LSB dependency %s, ignoring: %s", path, line, n, strerror(-r));
741 r = unit_add_dependency_by_name(u, startswith_no_case(t, "X-Start-Before:") ? UNIT_BEFORE : UNIT_AFTER, m, NULL, true);
744 log_error("[%s:%u] Failed to add dependency on %s, ignoring: %s", path, line, m, strerror(-r));
748 } else if (startswith_no_case(t, "Default-Start:")) {
753 k = delete_chars(t+14, WHITESPACE "-");
756 if (!(d = strdup(k))) {
761 free(s->sysv_runlevels);
762 s->sysv_runlevels = d;
765 } else if (startswith_no_case(t, "Description:")) {
768 state = LSB_DESCRIPTION;
770 if ((j = strstrip(t+12)) && *j) {
771 if (!(d = strdup(j))) {
778 free(long_description);
779 long_description = d;
781 } else if (startswith_no_case(t, "Short-Description:")) {
786 if ((j = strstrip(t+18)) && *j) {
787 if (!(d = strdup(j))) {
794 free(short_description);
795 short_description = d;
797 } else if (state == LSB_DESCRIPTION) {
799 if (startswith(l, "#\t") || startswith(l, "# ")) {
802 if ((j = strstrip(t)) && *j) {
805 if (long_description)
806 d = join(long_description, " ", t, NULL);
815 free(long_description);
816 long_description = d;
825 if ((r = sysv_exec_commands(s)) < 0)
827 if (s->sysv_runlevels &&
828 chars_intersect(RUNLEVELS_BOOT, s->sysv_runlevels) &&
829 chars_intersect(RUNLEVELS_UP, s->sysv_runlevels)) {
830 /* Service has both boot and "up" runlevels
831 configured. Kill the "up" ones. */
832 delete_chars(s->sysv_runlevels, RUNLEVELS_UP);
835 if (s->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, s->sysv_runlevels)) {
836 /* If there a runlevels configured for this service
837 * but none of the standard ones, then we assume this
838 * is some special kind of service (which might be
839 * needed for early boot) and don't create any links
842 UNIT(s)->default_dependencies = false;
844 /* Don't timeout special services during boot (like fsck) */
847 s->timeout_usec = DEFAULT_SYSV_TIMEOUT_USEC;
849 /* Special setting for all SysV services */
850 s->type = SERVICE_FORKING;
851 s->remain_after_exit = !s->pid_file;
852 s->guess_main_pid = false;
853 s->restart = SERVICE_RESTART_NO;
855 if (UNIT(s)->manager->sysv_console)
856 s->exec_context.std_output = EXEC_OUTPUT_JOURNAL_AND_CONSOLE;
858 s->exec_context.kill_mode = KILL_PROCESS;
860 /* We use the long description only if
861 * no short description is set. */
863 if (short_description)
864 description = short_description;
865 else if (chkconfig_description)
866 description = chkconfig_description;
867 else if (long_description)
868 description = long_description;
875 if (!(d = strappend(s->sysv_has_lsb ? "LSB: " : "SYSV: ", description))) {
883 /* The priority that has been set in /etc/rcN.d/ hierarchies
884 * takes precedence over what is stored as default in the LSB
886 if (s->sysv_start_priority_from_rcnd >= 0)
887 s->sysv_start_priority = s->sysv_start_priority_from_rcnd;
889 u->load_state = UNIT_LOADED;
897 free(short_description);
898 free(long_description);
899 free(chkconfig_description);
904 static int service_load_sysv_name(Service *s, const char *name) {
910 /* For SysV services we strip the boot.*, rc.* and *.sh
911 * prefixes/suffixes. */
912 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU) || defined(TARGET_ANGSTROM)
913 if (endswith(name, ".sh.service"))
918 if (startswith(name, "boot."))
922 #ifdef TARGET_FRUGALWARE
923 if (startswith(name, "rc."))
927 STRV_FOREACH(p, UNIT(s)->manager->lookup_paths.sysvinit_path) {
931 path = join(*p, "/", name, NULL);
935 assert(endswith(path, ".service"));
936 path[strlen(path)-8] = 0;
938 r = service_load_sysv_path(s, path);
940 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU) || defined(TARGET_ANGSTROM)
941 if (r >= 0 && UNIT(s)->load_state == UNIT_STUB) {
942 /* Try Debian style *.sh source'able init scripts */
944 r = service_load_sysv_path(s, path);
950 if (r >= 0 && UNIT(s)->load_state == UNIT_STUB) {
951 /* Try SUSE style boot.* init scripts */
953 path = join(*p, "/boot.", name, NULL);
957 /* Drop .service suffix */
958 path[strlen(path)-8] = 0;
959 r = service_load_sysv_path(s, path);
964 #ifdef TARGET_FRUGALWARE
965 if (r >= 0 && UNIT(s)->load_state == UNIT_STUB) {
966 /* Try Frugalware style rc.* init scripts */
968 path = join(*p, "/rc.", name, NULL);
972 /* Drop .service suffix */
973 path[strlen(path)-8] = 0;
974 r = service_load_sysv_path(s, path);
982 if ((UNIT(s)->load_state != UNIT_STUB))
989 static int service_load_sysv(Service *s) {
996 /* Load service data from SysV init scripts, preferably with
999 if (strv_isempty(UNIT(s)->manager->lookup_paths.sysvinit_path))
1002 if ((t = UNIT(s)->id))
1003 if ((r = service_load_sysv_name(s, t)) < 0)
1006 if (UNIT(s)->load_state == UNIT_STUB)
1007 SET_FOREACH(t, UNIT(s)->names, i) {
1008 if (t == UNIT(s)->id)
1011 if ((r = service_load_sysv_name(s, t)) < 0)
1014 if (UNIT(s)->load_state != UNIT_STUB)
1022 static int fsck_fix_order(Service *s) {
1028 if (s->fsck_passno <= 0)
1031 /* For each pair of services where both have an fsck priority
1032 * we order things based on it. */
1034 LIST_FOREACH(units_by_type, other, UNIT(s)->manager->units_by_type[UNIT_SERVICE]) {
1043 if (UNIT(t)->load_state != UNIT_LOADED)
1046 if (t->fsck_passno <= 0)
1049 if (t->fsck_passno < s->fsck_passno)
1051 else if (t->fsck_passno > s->fsck_passno)
1056 if ((r = unit_add_dependency(UNIT(s), d, UNIT(t), true)) < 0)
1063 static int service_verify(Service *s) {
1066 if (UNIT(s)->load_state != UNIT_LOADED)
1069 if (!s->exec_command[SERVICE_EXEC_START]) {
1070 log_error("%s lacks ExecStart setting. Refusing.", UNIT(s)->id);
1074 if (s->type != SERVICE_ONESHOT &&
1075 s->exec_command[SERVICE_EXEC_START]->command_next) {
1076 log_error("%s has more than one ExecStart setting, which is only allowed for Type=oneshot services. Refusing.", UNIT(s)->id);
1080 if (s->type == SERVICE_ONESHOT &&
1081 s->exec_command[SERVICE_EXEC_RELOAD]) {
1082 log_error("%s has an ExecReload setting, which is not allowed for Type=oneshot services. Refusing.", UNIT(s)->id);
1086 if (s->type == SERVICE_DBUS && !s->bus_name) {
1087 log_error("%s is of type D-Bus but no D-Bus service name has been specified. Refusing.", UNIT(s)->id);
1091 if (s->exec_context.pam_name && s->exec_context.kill_mode != KILL_CONTROL_GROUP) {
1092 log_error("%s has PAM enabled. Kill mode must be set to 'control-group'. Refusing.", UNIT(s)->id);
1099 static int service_add_default_dependencies(Service *s) {
1104 /* Add a number of automatic dependencies useful for the
1105 * majority of services. */
1107 /* First, pull in base system */
1108 if (UNIT(s)->manager->running_as == MANAGER_SYSTEM) {
1110 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_BASIC_TARGET, NULL, true)) < 0)
1113 } else if (UNIT(s)->manager->running_as == MANAGER_USER) {
1115 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SOCKETS_TARGET, NULL, true)) < 0)
1119 /* Second, activate normal shutdown */
1120 return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true);
1123 static void service_fix_output(Service *s) {
1126 /* If nothing has been explicitly configured, patch default
1127 * output in. If input is socket/tty we avoid this however,
1128 * since in that case we want output to default to the same
1129 * place as we read input from. */
1131 if (s->exec_context.std_error == EXEC_OUTPUT_INHERIT &&
1132 s->exec_context.std_output == EXEC_OUTPUT_INHERIT &&
1133 s->exec_context.std_input == EXEC_INPUT_NULL)
1134 s->exec_context.std_error = UNIT(s)->manager->default_std_error;
1136 if (s->exec_context.std_output == EXEC_OUTPUT_INHERIT &&
1137 s->exec_context.std_input == EXEC_INPUT_NULL)
1138 s->exec_context.std_output = UNIT(s)->manager->default_std_output;
1141 static int service_load(Unit *u) {
1143 Service *s = SERVICE(u);
1147 /* Load a .service file */
1148 if ((r = unit_load_fragment(u)) < 0)
1151 #ifdef HAVE_SYSV_COMPAT
1152 /* Load a classic init script as a fallback, if we couldn't find anything */
1153 if (u->load_state == UNIT_STUB)
1154 if ((r = service_load_sysv(s)) < 0)
1158 /* Still nothing found? Then let's give up */
1159 if (u->load_state == UNIT_STUB)
1162 /* We were able to load something, then let's add in the
1163 * dropin directories. */
1164 if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
1167 /* This is a new unit? Then let's add in some extras */
1168 if (u->load_state == UNIT_LOADED) {
1169 service_fix_output(s);
1171 if ((r = unit_add_exec_dependencies(u, &s->exec_context)) < 0)
1174 if ((r = unit_add_default_cgroups(u)) < 0)
1177 #ifdef HAVE_SYSV_COMPAT
1178 if ((r = sysv_fix_order(s)) < 0)
1182 if ((r = fsck_fix_order(s)) < 0)
1186 if ((r = unit_watch_bus_name(u, s->bus_name)) < 0)
1189 if (s->type == SERVICE_NOTIFY && s->notify_access == NOTIFY_NONE)
1190 s->notify_access = NOTIFY_MAIN;
1192 if (s->type == SERVICE_DBUS || s->bus_name)
1193 if ((r = unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_REQUIRES, SPECIAL_DBUS_SOCKET, NULL, true)) < 0)
1196 if (UNIT(s)->default_dependencies)
1197 if ((r = service_add_default_dependencies(s)) < 0)
1201 return service_verify(s);
1204 static void service_dump(Unit *u, FILE *f, const char *prefix) {
1206 ServiceExecCommand c;
1207 Service *s = SERVICE(u);
1208 const char *prefix2;
1213 p2 = strappend(prefix, "\t");
1214 prefix2 = p2 ? p2 : prefix;
1217 "%sService State: %s\n"
1218 "%sPermissionsStartOnly: %s\n"
1219 "%sRootDirectoryStartOnly: %s\n"
1220 "%sRemainAfterExit: %s\n"
1221 "%sGuessMainPID: %s\n"
1224 "%sNotifyAccess: %s\n",
1225 prefix, service_state_to_string(s->state),
1226 prefix, yes_no(s->permissions_start_only),
1227 prefix, yes_no(s->root_directory_start_only),
1228 prefix, yes_no(s->remain_after_exit),
1229 prefix, yes_no(s->guess_main_pid),
1230 prefix, service_type_to_string(s->type),
1231 prefix, service_restart_to_string(s->restart),
1232 prefix, notify_access_to_string(s->notify_access));
1234 if (s->control_pid > 0)
1236 "%sControl PID: %lu\n",
1237 prefix, (unsigned long) s->control_pid);
1239 if (s->main_pid > 0)
1242 "%sMain PID Known: %s\n"
1243 "%sMain PID Alien: %s\n",
1244 prefix, (unsigned long) s->main_pid,
1245 prefix, yes_no(s->main_pid_known),
1246 prefix, yes_no(s->main_pid_alien));
1251 prefix, s->pid_file);
1256 "%sBus Name Good: %s\n",
1257 prefix, s->bus_name,
1258 prefix, yes_no(s->bus_name_good));
1260 exec_context_dump(&s->exec_context, f, prefix);
1262 for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
1264 if (!s->exec_command[c])
1267 fprintf(f, "%s-> %s:\n",
1268 prefix, service_exec_command_to_string(c));
1270 exec_command_dump_list(s->exec_command[c], f, prefix2);
1273 #ifdef HAVE_SYSV_COMPAT
1276 "%sSysV Init Script Path: %s\n"
1277 "%sSysV Init Script has LSB Header: %s\n"
1278 "%sSysVEnabled: %s\n",
1279 prefix, s->sysv_path,
1280 prefix, yes_no(s->sysv_has_lsb),
1281 prefix, yes_no(s->sysv_enabled));
1283 if (s->sysv_start_priority >= 0)
1285 "%sSysVStartPriority: %i\n",
1286 prefix, s->sysv_start_priority);
1288 if (s->sysv_runlevels)
1289 fprintf(f, "%sSysVRunLevels: %s\n",
1290 prefix, s->sysv_runlevels);
1293 if (s->fsck_passno > 0)
1295 "%sFsckPassNo: %i\n",
1296 prefix, s->fsck_passno);
1299 fprintf(f, "%sStatus Text: %s\n",
1300 prefix, s->status_text);
1305 static int service_load_pid_file(Service *s, bool may_warn) {
1315 if ((r = read_one_line_file(s->pid_file, &k)) < 0) {
1317 log_info("PID file %s not readable (yet?) after %s.",
1318 s->pid_file, service_state_to_string(s->state));
1322 r = parse_pid(k, &pid);
1328 if (kill(pid, 0) < 0 && errno != EPERM) {
1330 log_info("PID %lu read from file %s does not exist.",
1331 (unsigned long) pid, s->pid_file);
1335 if (s->main_pid_known) {
1336 if (pid == s->main_pid)
1339 log_debug("Main PID changing: %lu -> %lu",
1340 (unsigned long) s->main_pid, (unsigned long) pid);
1341 service_unwatch_main_pid(s);
1342 s->main_pid_known = false;
1344 log_debug("Main PID loaded: %lu", (unsigned long) pid);
1346 if ((r = service_set_main_pid(s, pid)) < 0)
1349 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1350 /* FIXME: we need to do something here */
1356 static int service_search_main_pid(Service *s) {
1362 /* If we know it anyway, don't ever fallback to unreliable
1364 if (s->main_pid_known)
1367 if (!s->guess_main_pid)
1370 assert(s->main_pid <= 0);
1372 if ((pid = cgroup_bonding_search_main_pid_list(UNIT(s)->cgroup_bondings)) <= 0)
1375 log_debug("Main PID guessed: %lu", (unsigned long) pid);
1376 if ((r = service_set_main_pid(s, pid)) < 0)
1379 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1380 /* FIXME: we need to do something here */
1386 static void service_notify_sockets_dead(Service *s) {
1392 /* Notifies all our sockets when we die */
1394 if (s->socket_fd >= 0)
1397 SET_FOREACH(u, UNIT(s)->dependencies[UNIT_TRIGGERED_BY], i)
1398 if (u->type == UNIT_SOCKET)
1399 socket_notify_service_dead(SOCKET(u));
1404 static void service_set_state(Service *s, ServiceState state) {
1405 ServiceState old_state;
1408 old_state = s->state;
1411 service_unwatch_pid_file(s);
1413 if (state != SERVICE_START_PRE &&
1414 state != SERVICE_START &&
1415 state != SERVICE_START_POST &&
1416 state != SERVICE_RELOAD &&
1417 state != SERVICE_STOP &&
1418 state != SERVICE_STOP_SIGTERM &&
1419 state != SERVICE_STOP_SIGKILL &&
1420 state != SERVICE_STOP_POST &&
1421 state != SERVICE_FINAL_SIGTERM &&
1422 state != SERVICE_FINAL_SIGKILL &&
1423 state != SERVICE_AUTO_RESTART)
1424 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1426 if (state != SERVICE_START &&
1427 state != SERVICE_START_POST &&
1428 state != SERVICE_RUNNING &&
1429 state != SERVICE_RELOAD &&
1430 state != SERVICE_STOP &&
1431 state != SERVICE_STOP_SIGTERM &&
1432 state != SERVICE_STOP_SIGKILL) {
1433 service_unwatch_main_pid(s);
1434 s->main_command = NULL;
1437 if (state != SERVICE_START_PRE &&
1438 state != SERVICE_START &&
1439 state != SERVICE_START_POST &&
1440 state != SERVICE_RELOAD &&
1441 state != SERVICE_STOP &&
1442 state != SERVICE_STOP_SIGTERM &&
1443 state != SERVICE_STOP_SIGKILL &&
1444 state != SERVICE_STOP_POST &&
1445 state != SERVICE_FINAL_SIGTERM &&
1446 state != SERVICE_FINAL_SIGKILL) {
1447 service_unwatch_control_pid(s);
1448 s->control_command = NULL;
1449 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1452 if (state == SERVICE_DEAD ||
1453 state == SERVICE_STOP ||
1454 state == SERVICE_STOP_SIGTERM ||
1455 state == SERVICE_STOP_SIGKILL ||
1456 state == SERVICE_STOP_POST ||
1457 state == SERVICE_FINAL_SIGTERM ||
1458 state == SERVICE_FINAL_SIGKILL ||
1459 state == SERVICE_FAILED ||
1460 state == SERVICE_AUTO_RESTART)
1461 service_notify_sockets_dead(s);
1463 if (state != SERVICE_START_PRE &&
1464 state != SERVICE_START &&
1465 state != SERVICE_START_POST &&
1466 state != SERVICE_RUNNING &&
1467 state != SERVICE_RELOAD &&
1468 state != SERVICE_STOP &&
1469 state != SERVICE_STOP_SIGTERM &&
1470 state != SERVICE_STOP_SIGKILL &&
1471 state != SERVICE_STOP_POST &&
1472 state != SERVICE_FINAL_SIGTERM &&
1473 state != SERVICE_FINAL_SIGKILL &&
1474 !(state == SERVICE_DEAD && UNIT(s)->job)) {
1475 service_close_socket_fd(s);
1476 service_connection_unref(s);
1479 /* For the inactive states unit_notify() will trim the cgroup,
1480 * but for exit we have to do that ourselves... */
1481 if (state == SERVICE_EXITED && UNIT(s)->manager->n_reloading <= 0)
1482 cgroup_bonding_trim_list(UNIT(s)->cgroup_bondings, true);
1484 if (old_state != state)
1485 log_debug("%s changed %s -> %s", UNIT(s)->id, service_state_to_string(old_state), service_state_to_string(state));
1487 unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state], !s->reload_failure);
1488 s->reload_failure = false;
1491 static int service_coldplug(Unit *u) {
1492 Service *s = SERVICE(u);
1496 assert(s->state == SERVICE_DEAD);
1498 if (s->deserialized_state != s->state) {
1500 if (s->deserialized_state == SERVICE_START_PRE ||
1501 s->deserialized_state == SERVICE_START ||
1502 s->deserialized_state == SERVICE_START_POST ||
1503 s->deserialized_state == SERVICE_RELOAD ||
1504 s->deserialized_state == SERVICE_STOP ||
1505 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1506 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1507 s->deserialized_state == SERVICE_STOP_POST ||
1508 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1509 s->deserialized_state == SERVICE_FINAL_SIGKILL ||
1510 s->deserialized_state == SERVICE_AUTO_RESTART) {
1512 if (s->deserialized_state == SERVICE_AUTO_RESTART || s->timeout_usec > 0) {
1515 k = s->deserialized_state == SERVICE_AUTO_RESTART ? s->restart_usec : s->timeout_usec;
1517 if ((r = unit_watch_timer(UNIT(s), k, &s->timer_watch)) < 0)
1522 if ((s->deserialized_state == SERVICE_START &&
1523 (s->type == SERVICE_FORKING ||
1524 s->type == SERVICE_DBUS ||
1525 s->type == SERVICE_ONESHOT ||
1526 s->type == SERVICE_NOTIFY)) ||
1527 s->deserialized_state == SERVICE_START_POST ||
1528 s->deserialized_state == SERVICE_RUNNING ||
1529 s->deserialized_state == SERVICE_RELOAD ||
1530 s->deserialized_state == SERVICE_STOP ||
1531 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1532 s->deserialized_state == SERVICE_STOP_SIGKILL)
1533 if (s->main_pid > 0)
1534 if ((r = unit_watch_pid(UNIT(s), s->main_pid)) < 0)
1537 if (s->deserialized_state == SERVICE_START_PRE ||
1538 s->deserialized_state == SERVICE_START ||
1539 s->deserialized_state == SERVICE_START_POST ||
1540 s->deserialized_state == SERVICE_RELOAD ||
1541 s->deserialized_state == SERVICE_STOP ||
1542 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1543 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1544 s->deserialized_state == SERVICE_STOP_POST ||
1545 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1546 s->deserialized_state == SERVICE_FINAL_SIGKILL)
1547 if (s->control_pid > 0)
1548 if ((r = unit_watch_pid(UNIT(s), s->control_pid)) < 0)
1551 service_set_state(s, s->deserialized_state);
1557 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
1561 unsigned rn_fds = 0;
1568 if (s->socket_fd >= 0)
1571 SET_FOREACH(u, UNIT(s)->dependencies[UNIT_TRIGGERED_BY], i) {
1576 if (u->type != UNIT_SOCKET)
1581 if ((r = socket_collect_fds(sock, &cfds, &cn_fds)) < 0)
1593 if (!(t = new(int, rn_fds+cn_fds))) {
1599 memcpy(t, rfds, rn_fds * sizeof(int));
1600 memcpy(t+rn_fds, cfds, cn_fds * sizeof(int));
1605 rn_fds = rn_fds+cn_fds;
1620 static int service_spawn(
1625 bool apply_permissions,
1627 bool apply_tty_stdin,
1628 bool set_notify_socket,
1633 int *fds = NULL, *fdsbuf = NULL;
1634 unsigned n_fds = 0, n_env = 0;
1635 char **argv = NULL, **final_env = NULL, **our_env = NULL;
1642 s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1643 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1644 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
1646 if (s->socket_fd >= 0) {
1647 fds = &s->socket_fd;
1650 if ((r = service_collect_fds(s, &fdsbuf, &n_fds)) < 0)
1657 if (timeout && s->timeout_usec) {
1658 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1661 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1663 if (!(argv = unit_full_printf_strv(UNIT(s), c->argv))) {
1668 if (!(our_env = new0(char*, 4))) {
1673 if (set_notify_socket)
1674 if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=%s", UNIT(s)->manager->notify_socket) < 0) {
1679 if (s->main_pid > 0)
1680 if (asprintf(our_env + n_env++, "MAINPID=%lu", (unsigned long) s->main_pid) < 0) {
1685 if (!(final_env = strv_env_merge(2,
1686 UNIT(s)->manager->environment,
1701 UNIT(s)->manager->confirm_spawn,
1702 UNIT(s)->cgroup_bondings,
1703 UNIT(s)->cgroup_attributes,
1710 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1711 /* FIXME: we need to do something here */
1717 strv_free(final_env);
1727 strv_free(final_env);
1730 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1735 static int main_pid_good(Service *s) {
1738 /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1741 /* If we know the pid file, then lets just check if it is
1743 if (s->main_pid_known) {
1745 /* If it's an alien child let's check if it is still
1747 if (s->main_pid_alien)
1748 return kill(s->main_pid, 0) >= 0 || errno != ESRCH;
1750 /* .. otherwise assume we'll get a SIGCHLD for it,
1751 * which we really should wait for to collect exit
1752 * status and code */
1753 return s->main_pid > 0;
1756 /* We don't know the pid */
1760 static int control_pid_good(Service *s) {
1763 return s->control_pid > 0;
1766 static int cgroup_good(Service *s) {
1771 if ((r = cgroup_bonding_is_empty_list(UNIT(s)->cgroup_bondings)) < 0)
1777 static void service_enter_dead(Service *s, bool success, bool allow_restart) {
1784 if (allow_restart &&
1785 !s->forbid_restart &&
1786 (s->restart == SERVICE_RESTART_ALWAYS ||
1787 (s->restart == SERVICE_RESTART_ON_SUCCESS && !s->failure) ||
1788 (s->restart == SERVICE_RESTART_ON_FAILURE && s->failure) ||
1789 (s->restart == SERVICE_RESTART_ON_ABORT && s->failure &&
1790 (s->main_exec_status.code == CLD_KILLED ||
1791 s->main_exec_status.code == CLD_DUMPED)))) {
1793 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
1796 service_set_state(s, SERVICE_AUTO_RESTART);
1798 service_set_state(s, s->failure ? SERVICE_FAILED : SERVICE_DEAD);
1800 s->forbid_restart = false;
1805 log_warning("%s failed to run install restart timer: %s", UNIT(s)->id, strerror(-r));
1806 service_enter_dead(s, false, false);
1809 static void service_enter_signal(Service *s, ServiceState state, bool success);
1811 static void service_enter_stop_post(Service *s, bool success) {
1818 service_unwatch_control_pid(s);
1820 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST])) {
1821 s->control_command_id = SERVICE_EXEC_STOP_POST;
1823 if ((r = service_spawn(s,
1827 !s->permissions_start_only,
1828 !s->root_directory_start_only,
1831 &s->control_pid)) < 0)
1835 service_set_state(s, SERVICE_STOP_POST);
1837 service_enter_signal(s, SERVICE_FINAL_SIGTERM, true);
1842 log_warning("%s failed to run 'stop-post' task: %s", UNIT(s)->id, strerror(-r));
1843 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1846 static void service_enter_signal(Service *s, ServiceState state, bool success) {
1848 Set *pid_set = NULL;
1849 bool wait_for_exit = false;
1856 if (s->exec_context.kill_mode != KILL_NONE) {
1857 int sig = (state == SERVICE_STOP_SIGTERM || state == SERVICE_FINAL_SIGTERM) ? s->exec_context.kill_signal : SIGKILL;
1859 if (s->main_pid > 0) {
1860 if (kill_and_sigcont(s->main_pid, sig) < 0 && errno != ESRCH)
1861 log_warning("Failed to kill main process %li: %m", (long) s->main_pid);
1863 wait_for_exit = !s->main_pid_alien;
1866 if (s->control_pid > 0) {
1867 if (kill_and_sigcont(s->control_pid, sig) < 0 && errno != ESRCH)
1868 log_warning("Failed to kill control process %li: %m", (long) s->control_pid);
1870 wait_for_exit = true;
1873 if (s->exec_context.kill_mode == KILL_CONTROL_GROUP) {
1875 if (!(pid_set = set_new(trivial_hash_func, trivial_compare_func))) {
1880 /* Exclude the main/control pids from being killed via the cgroup */
1881 if (s->main_pid > 0)
1882 if ((r = set_put(pid_set, LONG_TO_PTR(s->main_pid))) < 0)
1885 if (s->control_pid > 0)
1886 if ((r = set_put(pid_set, LONG_TO_PTR(s->control_pid))) < 0)
1889 if ((r = cgroup_bonding_kill_list(UNIT(s)->cgroup_bondings, sig, true, pid_set)) < 0) {
1890 if (r != -EAGAIN && r != -ESRCH && r != -ENOENT)
1891 log_warning("Failed to kill control group: %s", strerror(-r));
1893 wait_for_exit = true;
1900 if (wait_for_exit) {
1901 if (s->timeout_usec > 0)
1902 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1905 service_set_state(s, state);
1906 } else if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1907 service_enter_stop_post(s, true);
1909 service_enter_dead(s, true, true);
1914 log_warning("%s failed to kill processes: %s", UNIT(s)->id, strerror(-r));
1916 if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1917 service_enter_stop_post(s, false);
1919 service_enter_dead(s, false, true);
1925 static void service_enter_stop(Service *s, bool success) {
1933 service_unwatch_control_pid(s);
1935 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP])) {
1936 s->control_command_id = SERVICE_EXEC_STOP;
1938 if ((r = service_spawn(s,
1942 !s->permissions_start_only,
1943 !s->root_directory_start_only,
1946 &s->control_pid)) < 0)
1949 service_set_state(s, SERVICE_STOP);
1951 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
1956 log_warning("%s failed to run 'stop' task: %s", UNIT(s)->id, strerror(-r));
1957 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1960 static void service_enter_running(Service *s, bool success) {
1961 int main_pid_ok, cgroup_ok;
1967 main_pid_ok = main_pid_good(s);
1968 cgroup_ok = cgroup_good(s);
1970 if ((main_pid_ok > 0 || (main_pid_ok < 0 && cgroup_ok != 0)) &&
1971 (s->bus_name_good || s->type != SERVICE_DBUS))
1972 service_set_state(s, SERVICE_RUNNING);
1973 else if (s->remain_after_exit)
1974 service_set_state(s, SERVICE_EXITED);
1976 service_enter_stop(s, true);
1979 static void service_enter_start_post(Service *s) {
1983 service_unwatch_control_pid(s);
1985 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_POST])) {
1986 s->control_command_id = SERVICE_EXEC_START_POST;
1988 if ((r = service_spawn(s,
1992 !s->permissions_start_only,
1993 !s->root_directory_start_only,
1996 &s->control_pid)) < 0)
1999 service_set_state(s, SERVICE_START_POST);
2001 service_enter_running(s, true);
2006 log_warning("%s failed to run 'start-post' task: %s", UNIT(s)->id, strerror(-r));
2007 service_enter_stop(s, false);
2010 static void service_enter_start(Service *s) {
2017 assert(s->exec_command[SERVICE_EXEC_START]);
2018 assert(!s->exec_command[SERVICE_EXEC_START]->command_next || s->type == SERVICE_ONESHOT);
2020 if (s->type == SERVICE_FORKING)
2021 service_unwatch_control_pid(s);
2023 service_unwatch_main_pid(s);
2025 /* We want to ensure that nobody leaks processes from
2026 * START_PRE here, so let's go on a killing spree, People
2027 * should not spawn long running processes from START_PRE. */
2028 cgroup_bonding_kill_list(UNIT(s)->cgroup_bondings, SIGKILL, true, NULL);
2030 if (s->type == SERVICE_FORKING) {
2031 s->control_command_id = SERVICE_EXEC_START;
2032 c = s->control_command = s->exec_command[SERVICE_EXEC_START];
2034 s->main_command = NULL;
2036 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2037 s->control_command = NULL;
2039 c = s->main_command = s->exec_command[SERVICE_EXEC_START];
2042 if ((r = service_spawn(s,
2044 s->type == SERVICE_FORKING || s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY,
2049 s->notify_access != NOTIFY_NONE,
2053 if (s->type == SERVICE_SIMPLE) {
2054 /* For simple services we immediately start
2055 * the START_POST binaries. */
2057 service_set_main_pid(s, pid);
2058 service_enter_start_post(s);
2060 } else if (s->type == SERVICE_FORKING) {
2062 /* For forking services we wait until the start
2063 * process exited. */
2065 s->control_pid = pid;
2066 service_set_state(s, SERVICE_START);
2068 } else if (s->type == SERVICE_ONESHOT ||
2069 s->type == SERVICE_DBUS ||
2070 s->type == SERVICE_NOTIFY) {
2072 /* For oneshot services we wait until the start
2073 * process exited, too, but it is our main process. */
2075 /* For D-Bus services we know the main pid right away,
2076 * but wait for the bus name to appear on the
2077 * bus. Notify services are similar. */
2079 service_set_main_pid(s, pid);
2080 service_set_state(s, SERVICE_START);
2082 assert_not_reached("Unknown service type");
2087 log_warning("%s failed to run 'start' task: %s", UNIT(s)->id, strerror(-r));
2088 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2091 static void service_enter_start_pre(Service *s) {
2096 service_unwatch_control_pid(s);
2098 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_PRE])) {
2100 /* Before we start anything, let's clear up what might
2101 * be left from previous runs. */
2102 cgroup_bonding_kill_list(UNIT(s)->cgroup_bondings, SIGKILL, true, NULL);
2104 s->control_command_id = SERVICE_EXEC_START_PRE;
2106 if ((r = service_spawn(s,
2110 !s->permissions_start_only,
2111 !s->root_directory_start_only,
2114 &s->control_pid)) < 0)
2117 service_set_state(s, SERVICE_START_PRE);
2119 service_enter_start(s);
2124 log_warning("%s failed to run 'start-pre' task: %s", UNIT(s)->id, strerror(-r));
2125 service_enter_dead(s, false, true);
2128 static void service_enter_restart(Service *s) {
2133 dbus_error_init(&error);
2136 log_info("Job pending for unit, delaying automatic restart.");
2138 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
2142 service_enter_dead(s, true, false);
2144 if ((r = manager_add_job(UNIT(s)->manager, JOB_START, UNIT(s), JOB_FAIL, false, &error, NULL)) < 0)
2147 log_debug("%s scheduled restart job.", UNIT(s)->id);
2151 log_warning("%s failed to schedule restart job: %s", UNIT(s)->id, bus_error(&error, -r));
2152 service_enter_dead(s, false, false);
2154 dbus_error_free(&error);
2157 static void service_enter_reload(Service *s) {
2162 service_unwatch_control_pid(s);
2164 if ((s->control_command = s->exec_command[SERVICE_EXEC_RELOAD])) {
2165 s->control_command_id = SERVICE_EXEC_RELOAD;
2167 if ((r = service_spawn(s,
2171 !s->permissions_start_only,
2172 !s->root_directory_start_only,
2175 &s->control_pid)) < 0)
2178 service_set_state(s, SERVICE_RELOAD);
2180 service_enter_running(s, true);
2185 log_warning("%s failed to run 'reload' task: %s", UNIT(s)->id, strerror(-r));
2186 s->reload_failure = true;
2187 service_enter_running(s, true);
2190 static void service_run_next_control(Service *s, bool success) {
2194 assert(s->control_command);
2195 assert(s->control_command->command_next);
2200 assert(s->control_command_id != SERVICE_EXEC_START);
2202 s->control_command = s->control_command->command_next;
2203 service_unwatch_control_pid(s);
2205 if ((r = service_spawn(s,
2209 !s->permissions_start_only,
2210 !s->root_directory_start_only,
2211 s->control_command_id == SERVICE_EXEC_START_PRE ||
2212 s->control_command_id == SERVICE_EXEC_STOP_POST,
2214 &s->control_pid)) < 0)
2220 log_warning("%s failed to run next control task: %s", UNIT(s)->id, strerror(-r));
2222 if (s->state == SERVICE_START_PRE)
2223 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2224 else if (s->state == SERVICE_STOP)
2225 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
2226 else if (s->state == SERVICE_STOP_POST)
2227 service_enter_dead(s, false, true);
2228 else if (s->state == SERVICE_RELOAD) {
2229 s->reload_failure = true;
2230 service_enter_running(s, true);
2232 service_enter_stop(s, false);
2235 static void service_run_next_main(Service *s, bool success) {
2240 assert(s->main_command);
2241 assert(s->main_command->command_next);
2242 assert(s->type == SERVICE_ONESHOT);
2247 s->main_command = s->main_command->command_next;
2248 service_unwatch_main_pid(s);
2250 if ((r = service_spawn(s,
2257 s->notify_access != NOTIFY_NONE,
2261 service_set_main_pid(s, pid);
2266 log_warning("%s failed to run next main task: %s", UNIT(s)->id, strerror(-r));
2267 service_enter_stop(s, false);
2270 static int service_start(Unit *u) {
2271 Service *s = SERVICE(u);
2275 /* We cannot fulfill this request right now, try again later
2277 if (s->state == SERVICE_STOP ||
2278 s->state == SERVICE_STOP_SIGTERM ||
2279 s->state == SERVICE_STOP_SIGKILL ||
2280 s->state == SERVICE_STOP_POST ||
2281 s->state == SERVICE_FINAL_SIGTERM ||
2282 s->state == SERVICE_FINAL_SIGKILL)
2285 /* Already on it! */
2286 if (s->state == SERVICE_START_PRE ||
2287 s->state == SERVICE_START ||
2288 s->state == SERVICE_START_POST)
2291 assert(s->state == SERVICE_DEAD || s->state == SERVICE_FAILED || s->state == SERVICE_AUTO_RESTART);
2293 /* Make sure we don't enter a busy loop of some kind. */
2294 if (!ratelimit_test(&s->ratelimit)) {
2295 log_warning("%s start request repeated too quickly, refusing to start.", u->id);
2300 s->main_pid_known = false;
2301 s->main_pid_alien = false;
2302 s->forbid_restart = false;
2304 service_enter_start_pre(s);
2308 static int service_stop(Unit *u) {
2309 Service *s = SERVICE(u);
2313 /* This is a user request, so don't do restarts on this
2315 s->forbid_restart = true;
2318 if (s->state == SERVICE_STOP ||
2319 s->state == SERVICE_STOP_SIGTERM ||
2320 s->state == SERVICE_STOP_SIGKILL ||
2321 s->state == SERVICE_STOP_POST ||
2322 s->state == SERVICE_FINAL_SIGTERM ||
2323 s->state == SERVICE_FINAL_SIGKILL)
2326 /* Don't allow a restart */
2327 if (s->state == SERVICE_AUTO_RESTART) {
2328 service_set_state(s, SERVICE_DEAD);
2332 /* If there's already something running we go directly into
2334 if (s->state == SERVICE_START_PRE ||
2335 s->state == SERVICE_START ||
2336 s->state == SERVICE_START_POST ||
2337 s->state == SERVICE_RELOAD) {
2338 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
2342 assert(s->state == SERVICE_RUNNING ||
2343 s->state == SERVICE_EXITED);
2345 service_enter_stop(s, true);
2349 static int service_reload(Unit *u) {
2350 Service *s = SERVICE(u);
2354 assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
2356 service_enter_reload(s);
2360 static bool service_can_reload(Unit *u) {
2361 Service *s = SERVICE(u);
2365 return !!s->exec_command[SERVICE_EXEC_RELOAD];
2368 static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
2369 Service *s = SERVICE(u);
2375 unit_serialize_item(u, f, "state", service_state_to_string(s->state));
2376 unit_serialize_item(u, f, "failure", yes_no(s->failure));
2378 if (s->control_pid > 0)
2379 unit_serialize_item_format(u, f, "control-pid", "%lu", (unsigned long) s->control_pid);
2381 if (s->main_pid_known && s->main_pid > 0)
2382 unit_serialize_item_format(u, f, "main-pid", "%lu", (unsigned long) s->main_pid);
2384 unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
2387 unit_serialize_item(u, f, "status-text", s->status_text);
2389 /* There's a minor uncleanliness here: if there are multiple
2390 * commands attached here, we will start from the first one
2392 if (s->control_command_id >= 0)
2393 unit_serialize_item(u, f, "control-command", service_exec_command_to_string(s->control_command_id));
2395 if (s->socket_fd >= 0) {
2398 if ((copy = fdset_put_dup(fds, s->socket_fd)) < 0)
2401 unit_serialize_item_format(u, f, "socket-fd", "%i", copy);
2404 if (s->main_exec_status.pid > 0) {
2405 unit_serialize_item_format(u, f, "main-exec-status-pid", "%lu", (unsigned long) s->main_exec_status.pid);
2406 dual_timestamp_serialize(f, "main-exec-status-start", &s->main_exec_status.start_timestamp);
2407 dual_timestamp_serialize(f, "main-exec-status-exit", &s->main_exec_status.exit_timestamp);
2409 if (dual_timestamp_is_set(&s->main_exec_status.exit_timestamp)) {
2410 unit_serialize_item_format(u, f, "main-exec-status-code", "%i", s->main_exec_status.code);
2411 unit_serialize_item_format(u, f, "main-exec-status-status", "%i", s->main_exec_status.status);
2418 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
2419 Service *s = SERVICE(u);
2426 if (streq(key, "state")) {
2429 if ((state = service_state_from_string(value)) < 0)
2430 log_debug("Failed to parse state value %s", value);
2432 s->deserialized_state = state;
2433 } else if (streq(key, "failure")) {
2436 if ((b = parse_boolean(value)) < 0)
2437 log_debug("Failed to parse failure value %s", value);
2439 s->failure = b || s->failure;
2440 } else if (streq(key, "control-pid")) {
2443 if (parse_pid(value, &pid) < 0)
2444 log_debug("Failed to parse control-pid value %s", value);
2446 s->control_pid = pid;
2447 } else if (streq(key, "main-pid")) {
2450 if (parse_pid(value, &pid) < 0)
2451 log_debug("Failed to parse main-pid value %s", value);
2453 service_set_main_pid(s, (pid_t) pid);
2454 } else if (streq(key, "main-pid-known")) {
2457 if ((b = parse_boolean(value)) < 0)
2458 log_debug("Failed to parse main-pid-known value %s", value);
2460 s->main_pid_known = b;
2461 } else if (streq(key, "status-text")) {
2464 if ((t = strdup(value))) {
2465 free(s->status_text);
2469 } else if (streq(key, "control-command")) {
2470 ServiceExecCommand id;
2472 if ((id = service_exec_command_from_string(value)) < 0)
2473 log_debug("Failed to parse exec-command value %s", value);
2475 s->control_command_id = id;
2476 s->control_command = s->exec_command[id];
2478 } else if (streq(key, "socket-fd")) {
2481 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2482 log_debug("Failed to parse socket-fd value %s", value);
2485 if (s->socket_fd >= 0)
2486 close_nointr_nofail(s->socket_fd);
2487 s->socket_fd = fdset_remove(fds, fd);
2489 } else if (streq(key, "main-exec-status-pid")) {
2492 if (parse_pid(value, &pid) < 0)
2493 log_debug("Failed to parse main-exec-status-pid value %s", value);
2495 s->main_exec_status.pid = pid;
2496 } else if (streq(key, "main-exec-status-code")) {
2499 if (safe_atoi(value, &i) < 0)
2500 log_debug("Failed to parse main-exec-status-code value %s", value);
2502 s->main_exec_status.code = i;
2503 } else if (streq(key, "main-exec-status-status")) {
2506 if (safe_atoi(value, &i) < 0)
2507 log_debug("Failed to parse main-exec-status-status value %s", value);
2509 s->main_exec_status.status = i;
2510 } else if (streq(key, "main-exec-status-start"))
2511 dual_timestamp_deserialize(value, &s->main_exec_status.start_timestamp);
2512 else if (streq(key, "main-exec-status-exit"))
2513 dual_timestamp_deserialize(value, &s->main_exec_status.exit_timestamp);
2515 log_debug("Unknown serialization key '%s'", key);
2520 static UnitActiveState service_active_state(Unit *u) {
2523 return state_translation_table[SERVICE(u)->state];
2526 static const char *service_sub_state_to_string(Unit *u) {
2529 return service_state_to_string(SERVICE(u)->state);
2532 static bool service_check_gc(Unit *u) {
2533 Service *s = SERVICE(u);
2537 /* Never clean up services that still have a process around,
2538 * even if the service is formally dead. */
2539 if (cgroup_good(s) > 0 ||
2540 main_pid_good(s) > 0 ||
2541 control_pid_good(s) > 0)
2544 #ifdef HAVE_SYSV_COMPAT
2552 static bool service_check_snapshot(Unit *u) {
2553 Service *s = SERVICE(u);
2557 return !s->got_socket_fd;
2560 static int service_retry_pid_file(Service *s) {
2563 assert(s->pid_file);
2564 assert(s->state == SERVICE_START || s->state == SERVICE_START_POST);
2566 r = service_load_pid_file(s, false);
2570 service_unwatch_pid_file(s);
2572 service_enter_running(s, true);
2576 static int service_watch_pid_file(Service *s) {
2579 log_debug("Setting watch for %s's PID file %s", UNIT(s)->id, s->pid_file_pathspec->path);
2580 r = path_spec_watch(s->pid_file_pathspec, UNIT(s));
2584 /* the pidfile might have appeared just before we set the watch */
2585 service_retry_pid_file(s);
2589 log_error("Failed to set a watch for %s's PID file %s: %s",
2590 UNIT(s)->id, s->pid_file_pathspec->path, strerror(-r));
2591 service_unwatch_pid_file(s);
2595 static int service_demand_pid_file(Service *s) {
2598 assert(s->pid_file);
2599 assert(!s->pid_file_pathspec);
2601 ps = new0(PathSpec, 1);
2605 ps->path = strdup(s->pid_file);
2611 path_kill_slashes(ps->path);
2613 /* PATH_CHANGED would not be enough. There are daemons (sendmail) that
2614 * keep their PID file open all the time. */
2615 ps->type = PATH_MODIFIED;
2616 ps->inotify_fd = -1;
2618 s->pid_file_pathspec = ps;
2620 return service_watch_pid_file(s);
2623 static void service_fd_event(Unit *u, int fd, uint32_t events, Watch *w) {
2624 Service *s = SERVICE(u);
2628 assert(s->state == SERVICE_START || s->state == SERVICE_START_POST);
2629 assert(s->pid_file_pathspec);
2630 assert(path_spec_owns_inotify_fd(s->pid_file_pathspec, fd));
2632 log_debug("inotify event for %s", u->id);
2634 if (path_spec_fd_event(s->pid_file_pathspec, events) < 0)
2637 if (service_retry_pid_file(s) == 0)
2640 if (service_watch_pid_file(s) < 0)
2645 service_unwatch_pid_file(s);
2646 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
2649 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2650 Service *s = SERVICE(u);
2656 if (!UNIT(s)->fragment_path)
2657 success = is_clean_exit_lsb(code, status);
2659 success = is_clean_exit(code, status);
2661 if (s->main_pid == pid) {
2662 /* Forking services may occasionally move to a new PID.
2663 * As long as they update the PID file before exiting the old
2664 * PID, they're fine. */
2665 if (service_load_pid_file(s, false) == 0)
2669 exec_status_exit(&s->main_exec_status, &s->exec_context, pid, code, status);
2671 /* If this is not a forking service than the main
2672 * process got started and hence we copy the exit
2673 * status so that it is recorded both as main and as
2674 * control process exit status */
2675 if (s->main_command) {
2676 s->main_command->exec_status = s->main_exec_status;
2678 if (s->main_command->ignore)
2682 log_full(success ? LOG_DEBUG : LOG_NOTICE,
2683 "%s: main process exited, code=%s, status=%i", u->id, sigchld_code_to_string(code), status);
2684 s->failure = s->failure || !success;
2686 if (s->main_command &&
2687 s->main_command->command_next &&
2690 /* There is another command to *
2691 * execute, so let's do that. */
2693 log_debug("%s running next main command for state %s", u->id, service_state_to_string(s->state));
2694 service_run_next_main(s, success);
2698 /* The service exited, so the service is officially
2700 s->main_command = NULL;
2704 case SERVICE_START_POST:
2705 case SERVICE_RELOAD:
2707 /* Need to wait until the operation is
2712 if (s->type == SERVICE_ONESHOT) {
2713 /* This was our main goal, so let's go on */
2715 service_enter_start_post(s);
2717 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2720 assert(s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY);
2725 case SERVICE_RUNNING:
2726 service_enter_running(s, success);
2729 case SERVICE_STOP_SIGTERM:
2730 case SERVICE_STOP_SIGKILL:
2732 if (!control_pid_good(s))
2733 service_enter_stop_post(s, success);
2735 /* If there is still a control process, wait for that first */
2739 assert_not_reached("Uh, main process died at wrong time.");
2743 } else if (s->control_pid == pid) {
2747 if (s->control_command) {
2748 exec_status_exit(&s->control_command->exec_status, &s->exec_context, pid, code, status);
2750 if (s->control_command->ignore)
2754 log_full(success ? LOG_DEBUG : LOG_NOTICE,
2755 "%s: control process exited, code=%s status=%i", u->id, sigchld_code_to_string(code), status);
2756 s->failure = s->failure || !success;
2758 if (s->control_command &&
2759 s->control_command->command_next &&
2762 /* There is another command to *
2763 * execute, so let's do that. */
2765 log_debug("%s running next control command for state %s", u->id, service_state_to_string(s->state));
2766 service_run_next_control(s, success);
2769 /* No further commands for this step, so let's
2770 * figure out what to do next */
2772 s->control_command = NULL;
2773 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2775 log_debug("%s got final SIGCHLD for state %s", u->id, service_state_to_string(s->state));
2779 case SERVICE_START_PRE:
2781 service_enter_start(s);
2783 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2787 assert(s->type == SERVICE_FORKING);
2790 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2795 /* Let's try to load the pid file here if we can.
2796 * The PID file might actually be created by a START_POST
2797 * script. In that case don't worry if the loading fails. */
2798 bool has_start_post = !!s->exec_command[SERVICE_EXEC_START_POST];
2799 int r = service_load_pid_file(s, !has_start_post);
2800 if (!has_start_post && r < 0) {
2801 r = service_demand_pid_file(s);
2802 if (r < 0 || !cgroup_good(s))
2803 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2807 service_search_main_pid(s);
2809 service_enter_start_post(s);
2812 case SERVICE_START_POST:
2814 service_enter_stop(s, false);
2819 int r = service_load_pid_file(s, true);
2821 r = service_demand_pid_file(s);
2822 if (r < 0 || !cgroup_good(s))
2823 service_enter_stop(s, false);
2827 service_search_main_pid(s);
2829 service_enter_running(s, true);
2832 case SERVICE_RELOAD:
2834 service_load_pid_file(s, true);
2835 service_search_main_pid(s);
2838 s->reload_failure = !success;
2839 service_enter_running(s, true);
2843 service_enter_signal(s, SERVICE_STOP_SIGTERM, success);
2846 case SERVICE_STOP_SIGTERM:
2847 case SERVICE_STOP_SIGKILL:
2848 if (main_pid_good(s) <= 0)
2849 service_enter_stop_post(s, success);
2851 /* If there is still a service
2852 * process around, wait until
2853 * that one quit, too */
2856 case SERVICE_STOP_POST:
2857 case SERVICE_FINAL_SIGTERM:
2858 case SERVICE_FINAL_SIGKILL:
2859 service_enter_dead(s, success, true);
2863 assert_not_reached("Uh, control process died at wrong time.");
2868 /* Notify clients about changed exit status */
2869 unit_add_to_dbus_queue(u);
2872 static void service_timer_event(Unit *u, uint64_t elapsed, Watch* w) {
2873 Service *s = SERVICE(u);
2876 assert(elapsed == 1);
2878 assert(w == &s->timer_watch);
2882 case SERVICE_START_PRE:
2884 log_warning("%s operation timed out. Terminating.", u->id);
2885 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2888 case SERVICE_START_POST:
2889 log_warning("%s operation timed out. Stopping.", u->id);
2890 service_enter_stop(s, false);
2893 case SERVICE_RELOAD:
2894 log_warning("%s operation timed out. Stopping.", u->id);
2895 s->reload_failure = true;
2896 service_enter_running(s, true);
2900 log_warning("%s stopping timed out. Terminating.", u->id);
2901 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
2904 case SERVICE_STOP_SIGTERM:
2905 if (s->exec_context.send_sigkill) {
2906 log_warning("%s stopping timed out. Killing.", u->id);
2907 service_enter_signal(s, SERVICE_STOP_SIGKILL, false);
2909 log_warning("%s stopping timed out. Skipping SIGKILL.", u->id);
2910 service_enter_stop_post(s, false);
2915 case SERVICE_STOP_SIGKILL:
2916 /* Uh, we sent a SIGKILL and it is still not gone?
2917 * Must be something we cannot kill, so let's just be
2918 * weirded out and continue */
2920 log_warning("%s still around after SIGKILL. Ignoring.", u->id);
2921 service_enter_stop_post(s, false);
2924 case SERVICE_STOP_POST:
2925 log_warning("%s stopping timed out (2). Terminating.", u->id);
2926 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2929 case SERVICE_FINAL_SIGTERM:
2930 if (s->exec_context.send_sigkill) {
2931 log_warning("%s stopping timed out (2). Killing.", u->id);
2932 service_enter_signal(s, SERVICE_FINAL_SIGKILL, false);
2934 log_warning("%s stopping timed out (2). Skipping SIGKILL. Entering failed mode.", u->id);
2935 service_enter_dead(s, false, true);
2940 case SERVICE_FINAL_SIGKILL:
2941 log_warning("%s still around after SIGKILL (2). Entering failed mode.", u->id);
2942 service_enter_dead(s, false, true);
2945 case SERVICE_AUTO_RESTART:
2946 log_info("%s holdoff time over, scheduling restart.", u->id);
2947 service_enter_restart(s);
2951 assert_not_reached("Timeout at wrong time.");
2955 static void service_cgroup_notify_event(Unit *u) {
2956 Service *s = SERVICE(u);
2960 log_debug("%s: cgroup is empty", u->id);
2964 /* Waiting for SIGCHLD is usually more interesting,
2965 * because it includes return codes/signals. Which is
2966 * why we ignore the cgroup events for most cases,
2967 * except when we don't know pid which to expect the
2971 case SERVICE_START_POST:
2972 /* If we were hoping for the daemon to write its PID file,
2973 * we can give up now. */
2974 if (s->pid_file_pathspec) {
2975 log_warning("%s never wrote its PID file. Failing.", UNIT(s)->id);
2976 service_unwatch_pid_file(s);
2977 if (s->state == SERVICE_START)
2978 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2980 service_enter_stop(s, false);
2984 case SERVICE_RUNNING:
2985 service_enter_running(s, true);
2988 case SERVICE_STOP_SIGTERM:
2989 case SERVICE_STOP_SIGKILL:
2991 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2992 service_enter_stop_post(s, true);
2996 case SERVICE_FINAL_SIGTERM:
2997 case SERVICE_FINAL_SIGKILL:
2998 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2999 service_enter_dead(s, true, true);
3008 static void service_notify_message(Unit *u, pid_t pid, char **tags) {
3009 Service *s = SERVICE(u);
3014 if (s->notify_access == NOTIFY_NONE) {
3015 log_warning("%s: Got notification message from PID %lu, but reception is disabled.",
3016 u->id, (unsigned long) pid);
3020 if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
3021 log_warning("%s: Got notification message from PID %lu, but reception only permitted for PID %lu",
3022 u->id, (unsigned long) pid, (unsigned long) s->main_pid);
3026 log_debug("%s: Got message", u->id);
3028 /* Interpret MAINPID= */
3029 if ((e = strv_find_prefix(tags, "MAINPID=")) &&
3030 (s->state == SERVICE_START ||
3031 s->state == SERVICE_START_POST ||
3032 s->state == SERVICE_RUNNING ||
3033 s->state == SERVICE_RELOAD)) {
3035 if (parse_pid(e + 8, &pid) < 0)
3036 log_warning("Failed to parse notification message %s", e);
3038 log_debug("%s: got %s", u->id, e);
3039 service_set_main_pid(s, pid);
3043 /* Interpret READY= */
3044 if (s->type == SERVICE_NOTIFY &&
3045 s->state == SERVICE_START &&
3046 strv_find(tags, "READY=1")) {
3047 log_debug("%s: got READY=1", u->id);
3049 service_enter_start_post(s);
3052 /* Interpret STATUS= */
3053 if ((e = strv_find_prefix(tags, "STATUS="))) {
3057 if (!(t = strdup(e+7))) {
3058 log_error("Failed to allocate string.");
3062 log_debug("%s: got %s", u->id, e);
3064 free(s->status_text);
3067 free(s->status_text);
3068 s->status_text = NULL;
3073 /* Notify clients about changed status or main pid */
3074 unit_add_to_dbus_queue(u);
3077 #ifdef HAVE_SYSV_COMPAT
3080 static void sysv_facility_in_insserv_conf(Manager *mgr) {
3084 if (!(f = fopen("/etc/insserv.conf", "re"))) {
3085 r = errno == ENOENT ? 0 : -errno;
3090 char l[LINE_MAX], *t;
3091 char **parsed = NULL;
3093 if (!fgets(l, sizeof(l), f)) {
3098 log_error("Failed to read configuration file '/etc/insserv.conf': %s", strerror(-r));
3103 if (*t != '$' && *t != '<')
3106 parsed = strv_split(t,WHITESPACE);
3107 /* we ignore <interactive>, not used, equivalent to X-Interactive */
3108 if (parsed && !startswith_no_case (parsed[0], "<interactive>")) {
3111 if (sysv_translate_facility(parsed[0], NULL, &facility) < 0)
3113 if ((u = manager_get_unit(mgr, facility)) && (u->type == UNIT_TARGET)) {
3115 char *dep = NULL, *name, **j;
3117 STRV_FOREACH (j, parsed+1) {
3126 if (sysv_translate_facility(name, NULL, &dep) < 0)
3129 r = unit_add_two_dependencies_by_name(u, UNIT_BEFORE, e, dep, NULL, true);
3144 static int service_enumerate(Manager *m) {
3148 char *path = NULL, *fpath = NULL, *name = NULL;
3149 Set *runlevel_services[ELEMENTSOF(rcnd_table)], *shutdown_services = NULL;
3156 if (m->running_as != MANAGER_SYSTEM)
3159 zero(runlevel_services);
3161 STRV_FOREACH(p, m->lookup_paths.sysvrcnd_path)
3162 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++) {
3166 path = join(*p, "/", rcnd_table[i].path, NULL);
3175 if (!(d = opendir(path))) {
3176 if (errno != ENOENT)
3177 log_warning("opendir() failed on %s: %s", path, strerror(errno));
3182 while ((de = readdir(d))) {
3185 if (ignore_file(de->d_name))
3188 if (de->d_name[0] != 'S' && de->d_name[0] != 'K')
3191 if (strlen(de->d_name) < 4)
3194 a = undecchar(de->d_name[1]);
3195 b = undecchar(de->d_name[2]);
3201 fpath = join(path, "/", de->d_name, NULL);
3207 if (access(fpath, X_OK) < 0) {
3209 if (errno != ENOENT)
3210 log_warning("access() failed on %s: %s", fpath, strerror(errno));
3216 if (!(name = sysv_translate_name(de->d_name + 3))) {
3221 if ((r = manager_load_unit_prepare(m, name, NULL, NULL, &service)) < 0) {
3222 log_warning("Failed to prepare unit %s: %s", name, strerror(-r));
3226 if (de->d_name[0] == 'S') {
3228 if (rcnd_table[i].type == RUNLEVEL_UP || rcnd_table[i].type == RUNLEVEL_SYSINIT) {
3229 SERVICE(service)->sysv_start_priority_from_rcnd =
3230 MAX(a*10 + b, SERVICE(service)->sysv_start_priority_from_rcnd);
3232 SERVICE(service)->sysv_enabled = true;
3235 if ((r = set_ensure_allocated(&runlevel_services[i], trivial_hash_func, trivial_compare_func)) < 0)
3238 if ((r = set_put(runlevel_services[i], service)) < 0)
3241 } else if (de->d_name[0] == 'K' &&
3242 (rcnd_table[i].type == RUNLEVEL_DOWN ||
3243 rcnd_table[i].type == RUNLEVEL_SYSINIT)) {
3245 if ((r = set_ensure_allocated(&shutdown_services, trivial_hash_func, trivial_compare_func)) < 0)
3248 if ((r = set_put(shutdown_services, service)) < 0)
3254 /* Now we loaded all stubs and are aware of the lowest
3255 start-up priority for all services, not let's actually load
3256 the services, this will also tell us which services are
3257 actually native now */
3258 manager_dispatch_load_queue(m);
3260 /* If this is a native service, rely on native ways to pull in
3261 * a service, don't pull it in via sysv rcN.d links. */
3262 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++)
3263 SET_FOREACH(service, runlevel_services[i], j) {
3264 service = unit_follow_merge(service);
3266 if (service->fragment_path)
3269 if ((r = unit_add_two_dependencies_by_name_inverse(service, UNIT_AFTER, UNIT_WANTS, rcnd_table[i].target, NULL, true)) < 0)
3273 /* We honour K links only for halt/reboot. For the normal
3274 * runlevels we assume the stop jobs will be implicitly added
3275 * by the core logic. Also, we don't really distinguish here
3276 * between the runlevels 0 and 6 and just add them to the
3277 * special shutdown target. On SUSE the boot.d/ runlevel is
3278 * also used for shutdown, so we add links for that too to the
3279 * shutdown target.*/
3280 SET_FOREACH(service, shutdown_services, j) {
3281 service = unit_follow_merge(service);
3283 if (service->fragment_path)
3286 if ((r = unit_add_two_dependencies_by_name(service, UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true)) < 0)
3293 sysv_facility_in_insserv_conf (m);
3301 for (i = 0; i < ELEMENTSOF(rcnd_table); i++)
3302 set_free(runlevel_services[i]);
3303 set_free(shutdown_services);
3312 static void service_bus_name_owner_change(
3315 const char *old_owner,
3316 const char *new_owner) {
3318 Service *s = SERVICE(u);
3323 assert(streq(s->bus_name, name));
3324 assert(old_owner || new_owner);
3326 if (old_owner && new_owner)
3327 log_debug("%s's D-Bus name %s changed owner from %s to %s", u->id, name, old_owner, new_owner);
3329 log_debug("%s's D-Bus name %s no longer registered by %s", u->id, name, old_owner);
3331 log_debug("%s's D-Bus name %s now registered by %s", u->id, name, new_owner);
3333 s->bus_name_good = !!new_owner;
3335 if (s->type == SERVICE_DBUS) {
3337 /* service_enter_running() will figure out what to
3339 if (s->state == SERVICE_RUNNING)
3340 service_enter_running(s, true);
3341 else if (s->state == SERVICE_START && new_owner)
3342 service_enter_start_post(s);
3344 } else if (new_owner &&
3346 (s->state == SERVICE_START ||
3347 s->state == SERVICE_START_POST ||
3348 s->state == SERVICE_RUNNING ||
3349 s->state == SERVICE_RELOAD)) {
3351 /* Try to acquire PID from bus service */
3352 log_debug("Trying to acquire PID from D-Bus name...");
3354 bus_query_pid(u->manager, name);
3358 static void service_bus_query_pid_done(
3363 Service *s = SERVICE(u);
3368 log_debug("%s's D-Bus name %s is now owned by process %u", u->id, name, (unsigned) pid);
3370 if (s->main_pid <= 0 &&
3371 (s->state == SERVICE_START ||
3372 s->state == SERVICE_START_POST ||
3373 s->state == SERVICE_RUNNING ||
3374 s->state == SERVICE_RELOAD))
3375 service_set_main_pid(s, pid);
3378 int service_set_socket_fd(Service *s, int fd, Socket *sock) {
3383 /* This is called by the socket code when instantiating a new
3384 * service for a stream socket and the socket needs to be
3387 if (UNIT(s)->load_state != UNIT_LOADED)
3390 if (s->socket_fd >= 0)
3393 if (s->state != SERVICE_DEAD)
3397 s->got_socket_fd = true;
3399 unit_ref_set(&s->accept_socket, UNIT(sock));
3401 return unit_add_two_dependencies(UNIT(sock), UNIT_BEFORE, UNIT_TRIGGERS, UNIT(s), false);
3404 static void service_reset_failed(Unit *u) {
3405 Service *s = SERVICE(u);
3409 if (s->state == SERVICE_FAILED)
3410 service_set_state(s, SERVICE_DEAD);
3415 static bool service_need_daemon_reload(Unit *u) {
3416 Service *s = SERVICE(u);
3420 #ifdef HAVE_SYSV_COMPAT
3425 if (stat(s->sysv_path, &st) < 0)
3426 /* What, cannot access this anymore? */
3429 if (s->sysv_mtime > 0 &&
3430 timespec_load(&st.st_mtim) != s->sysv_mtime)
3438 static int service_kill(Unit *u, KillWho who, KillMode mode, int signo, DBusError *error) {
3439 Service *s = SERVICE(u);
3441 Set *pid_set = NULL;
3445 if (s->main_pid <= 0 && who == KILL_MAIN) {
3446 dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "No main process to kill");
3450 if (s->control_pid <= 0 && who == KILL_CONTROL) {
3451 dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "No control process to kill");
3455 if (who == KILL_CONTROL || who == KILL_ALL)
3456 if (s->control_pid > 0)
3457 if (kill(s->control_pid, signo) < 0)
3460 if (who == KILL_MAIN || who == KILL_ALL)
3461 if (s->main_pid > 0)
3462 if (kill(s->main_pid, signo) < 0)
3465 if (who == KILL_ALL && mode == KILL_CONTROL_GROUP) {
3468 if (!(pid_set = set_new(trivial_hash_func, trivial_compare_func)))
3471 /* Exclude the control/main pid from being killed via the cgroup */
3472 if (s->control_pid > 0)
3473 if ((q = set_put(pid_set, LONG_TO_PTR(s->control_pid))) < 0) {
3478 if (s->main_pid > 0)
3479 if ((q = set_put(pid_set, LONG_TO_PTR(s->main_pid))) < 0) {
3484 if ((q = cgroup_bonding_kill_list(UNIT(s)->cgroup_bondings, signo, false, pid_set)) < 0)
3485 if (q != -EAGAIN && q != -ESRCH && q != -ENOENT)
3496 static const char* const service_state_table[_SERVICE_STATE_MAX] = {
3497 [SERVICE_DEAD] = "dead",
3498 [SERVICE_START_PRE] = "start-pre",
3499 [SERVICE_START] = "start",
3500 [SERVICE_START_POST] = "start-post",
3501 [SERVICE_RUNNING] = "running",
3502 [SERVICE_EXITED] = "exited",
3503 [SERVICE_RELOAD] = "reload",
3504 [SERVICE_STOP] = "stop",
3505 [SERVICE_STOP_SIGTERM] = "stop-sigterm",
3506 [SERVICE_STOP_SIGKILL] = "stop-sigkill",
3507 [SERVICE_STOP_POST] = "stop-post",
3508 [SERVICE_FINAL_SIGTERM] = "final-sigterm",
3509 [SERVICE_FINAL_SIGKILL] = "final-sigkill",
3510 [SERVICE_FAILED] = "failed",
3511 [SERVICE_AUTO_RESTART] = "auto-restart",
3514 DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
3516 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
3517 [SERVICE_RESTART_NO] = "no",
3518 [SERVICE_RESTART_ON_SUCCESS] = "on-success",
3519 [SERVICE_RESTART_ON_FAILURE] = "on-failure",
3520 [SERVICE_RESTART_ON_ABORT] = "on-abort",
3521 [SERVICE_RESTART_ALWAYS] = "always"
3524 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
3526 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
3527 [SERVICE_SIMPLE] = "simple",
3528 [SERVICE_FORKING] = "forking",
3529 [SERVICE_ONESHOT] = "oneshot",
3530 [SERVICE_DBUS] = "dbus",
3531 [SERVICE_NOTIFY] = "notify"
3534 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
3536 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
3537 [SERVICE_EXEC_START_PRE] = "ExecStartPre",
3538 [SERVICE_EXEC_START] = "ExecStart",
3539 [SERVICE_EXEC_START_POST] = "ExecStartPost",
3540 [SERVICE_EXEC_RELOAD] = "ExecReload",
3541 [SERVICE_EXEC_STOP] = "ExecStop",
3542 [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
3545 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
3547 static const char* const notify_access_table[_NOTIFY_ACCESS_MAX] = {
3548 [NOTIFY_NONE] = "none",
3549 [NOTIFY_MAIN] = "main",
3550 [NOTIFY_ALL] = "all"
3553 DEFINE_STRING_TABLE_LOOKUP(notify_access, NotifyAccess);
3555 const UnitVTable service_vtable = {
3556 .suffix = ".service",
3557 .object_size = sizeof(Service),
3562 .show_status = true,
3564 .init = service_init,
3565 .done = service_done,
3566 .load = service_load,
3568 .coldplug = service_coldplug,
3570 .dump = service_dump,
3572 .start = service_start,
3573 .stop = service_stop,
3574 .reload = service_reload,
3576 .can_reload = service_can_reload,
3578 .kill = service_kill,
3580 .serialize = service_serialize,
3581 .deserialize_item = service_deserialize_item,
3583 .active_state = service_active_state,
3584 .sub_state_to_string = service_sub_state_to_string,
3586 .check_gc = service_check_gc,
3587 .check_snapshot = service_check_snapshot,
3589 .sigchld_event = service_sigchld_event,
3590 .timer_event = service_timer_event,
3591 .fd_event = service_fd_event,
3593 .reset_failed = service_reset_failed,
3595 .need_daemon_reload = service_need_daemon_reload,
3597 .cgroup_notify_empty = service_cgroup_notify_event,
3598 .notify_message = service_notify_message,
3600 .bus_name_owner_change = service_bus_name_owner_change,
3601 .bus_query_pid_done = service_bus_query_pid_done,
3603 .bus_interface = "org.freedesktop.systemd1.Service",
3604 .bus_message_handler = bus_service_message_handler,
3605 .bus_invalidating_properties = bus_service_invalidating_properties,
3607 #ifdef HAVE_SYSV_COMPAT
3608 .enumerate = service_enumerate