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_FRUGALWARE)
69 /* Debian style rcS.d */
70 { "rcS.d", SPECIAL_SYSINIT_TARGET, RUNLEVEL_SYSINIT },
73 /* Standard SysV runlevels for shutdown */
74 { "rc0.d", SPECIAL_POWEROFF_TARGET, RUNLEVEL_DOWN },
75 { "rc6.d", SPECIAL_REBOOT_TARGET, RUNLEVEL_DOWN }
77 /* Note that the order here matters, as we read the
78 directories in this order, and we want to make sure that
79 sysv_start_priority is known when we first load the
80 unit. And that value we only know from S links. Hence
81 UP/SYSINIT must be read before DOWN */
84 #define RUNLEVELS_UP "12345"
85 /* #define RUNLEVELS_DOWN "06" */
86 /* #define RUNLEVELS_BOOT "bBsS" */
89 static const UnitActiveState state_translation_table[_SERVICE_STATE_MAX] = {
90 [SERVICE_DEAD] = UNIT_INACTIVE,
91 [SERVICE_START_PRE] = UNIT_ACTIVATING,
92 [SERVICE_START] = UNIT_ACTIVATING,
93 [SERVICE_START_POST] = UNIT_ACTIVATING,
94 [SERVICE_RUNNING] = UNIT_ACTIVE,
95 [SERVICE_EXITED] = UNIT_ACTIVE,
96 [SERVICE_RELOAD] = UNIT_RELOADING,
97 [SERVICE_STOP] = UNIT_DEACTIVATING,
98 [SERVICE_STOP_SIGTERM] = UNIT_DEACTIVATING,
99 [SERVICE_STOP_SIGKILL] = UNIT_DEACTIVATING,
100 [SERVICE_STOP_POST] = UNIT_DEACTIVATING,
101 [SERVICE_FINAL_SIGTERM] = UNIT_DEACTIVATING,
102 [SERVICE_FINAL_SIGKILL] = UNIT_DEACTIVATING,
103 [SERVICE_FAILED] = UNIT_FAILED,
104 [SERVICE_AUTO_RESTART] = UNIT_ACTIVATING
107 static void service_init(Unit *u) {
108 Service *s = SERVICE(u);
111 assert(u->meta.load_state == UNIT_STUB);
113 s->timeout_usec = DEFAULT_TIMEOUT_USEC;
114 s->restart_usec = DEFAULT_RESTART_USEC;
115 s->timer_watch.type = WATCH_INVALID;
116 #ifdef HAVE_SYSV_COMPAT
117 s->sysv_start_priority = -1;
120 s->guess_main_pid = true;
122 exec_context_init(&s->exec_context);
123 s->exec_context.std_output = u->meta.manager->default_std_output;
124 s->exec_context.std_error = u->meta.manager->default_std_error;
126 RATELIMIT_INIT(s->ratelimit, 10*USEC_PER_SEC, 5);
128 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
131 static void service_unwatch_control_pid(Service *s) {
134 if (s->control_pid <= 0)
137 unit_unwatch_pid(UNIT(s), s->control_pid);
141 static void service_unwatch_main_pid(Service *s) {
144 if (s->main_pid <= 0)
147 unit_unwatch_pid(UNIT(s), s->main_pid);
151 static int service_set_main_pid(Service *s, pid_t pid) {
162 if (get_parent_of_pid(pid, &ppid) >= 0 && ppid != getpid())
163 log_warning("%s: Supervising process %lu which is not our child. We'll most likely not notice when it exits.",
164 s->meta.id, (unsigned long) pid);
167 s->main_pid_known = true;
169 exec_status_start(&s->main_exec_status, pid);
174 static void service_close_socket_fd(Service *s) {
177 if (s->socket_fd < 0)
180 close_nointr_nofail(s->socket_fd);
184 static void service_connection_unref(Service *s) {
187 if (!s->accept_socket)
190 socket_connection_unref(s->accept_socket);
191 s->accept_socket = NULL;
194 static void service_done(Unit *u) {
195 Service *s = SERVICE(u);
202 #ifdef HAVE_SYSV_COMPAT
206 free(s->sysv_runlevels);
207 s->sysv_runlevels = NULL;
210 free(s->status_text);
211 s->status_text = NULL;
213 exec_context_done(&s->exec_context);
214 exec_command_free_array(s->exec_command, _SERVICE_EXEC_COMMAND_MAX);
215 s->control_command = NULL;
216 s->main_command = NULL;
218 /* This will leak a process, but at least no memory or any of
220 service_unwatch_main_pid(s);
221 service_unwatch_control_pid(s);
224 unit_unwatch_bus_name(UNIT(u), s->bus_name);
229 service_close_socket_fd(s);
230 service_connection_unref(s);
232 set_free(s->configured_sockets);
234 unit_unwatch_timer(u, &s->timer_watch);
237 #ifdef HAVE_SYSV_COMPAT
238 static char *sysv_translate_name(const char *name) {
241 if (!(r = new(char, strlen(name) + sizeof(".service"))))
244 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU)
245 if (endswith(name, ".sh"))
246 /* Drop Debian-style .sh suffix */
247 strcpy(stpcpy(r, name) - 3, ".service");
250 if (startswith(name, "boot."))
251 /* Drop SuSE-style boot. prefix */
252 strcpy(stpcpy(r, name + 5), ".service");
254 #ifdef TARGET_FRUGALWARE
255 if (startswith(name, "rc."))
256 /* Drop Frugalware-style rc. prefix */
257 strcpy(stpcpy(r, name + 3), ".service");
260 /* Normal init scripts */
261 strcpy(stpcpy(r, name), ".service");
266 static int sysv_translate_facility(const char *name, const char *filename, char **_r) {
268 /* We silently ignore the $ prefix here. According to the LSB
269 * spec it simply indicates whether something is a
270 * standardized name or a distribution-specific one. Since we
271 * just follow what already exists and do not introduce new
272 * uses or names we don't care who introduced a new name. */
274 static const char * const table[] = {
275 /* LSB defined facilities */
276 "local_fs", SPECIAL_LOCAL_FS_TARGET,
277 #ifndef TARGET_MANDRIVA
278 /* Due to unfortunate name selection in Mandriva,
279 * $network is provided by network-up which is ordered
280 * after network which actually starts interfaces.
281 * To break the loop, just ignore it */
282 "network", SPECIAL_NETWORK_TARGET,
284 "named", SPECIAL_NSS_LOOKUP_TARGET,
285 "portmap", SPECIAL_RPCBIND_TARGET,
286 "remote_fs", SPECIAL_REMOTE_FS_TARGET,
287 "syslog", SPECIAL_SYSLOG_TARGET,
288 "time", SPECIAL_RTC_SET_TARGET,
290 /* common extensions */
291 "mail-transfer-agent", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
292 "x-display-manager", SPECIAL_DISPLAY_MANAGER_SERVICE,
295 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU)
296 "mail-transport-agent", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
300 "MTA", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
301 "smtpdaemon", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
302 "httpd", SPECIAL_HTTP_DAEMON_TARGET,
306 "smtp", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
317 n = *name == '$' ? name + 1 : name;
319 for (i = 0; i < ELEMENTSOF(table); i += 2) {
321 if (!streq(table[i], n))
327 if (!(r = strdup(table[i+1])))
333 /* If we don't know this name, fallback heuristics to figure
334 * out whether something is a target or a service alias. */
337 if (!unit_prefix_is_valid(n))
340 /* Facilities starting with $ are most likely targets */
341 r = unit_name_build(n, NULL, ".target");
342 } else if (filename && streq(name, filename))
343 /* Names equaling the file name of the services are redundant */
346 /* Everything else we assume to be normal service names */
347 r = sysv_translate_name(n);
358 static int sysv_fix_order(Service *s) {
364 if (s->sysv_start_priority < 0)
367 /* For each pair of services where at least one lacks a LSB
368 * header, we use the start priority value to order things. */
370 LIST_FOREACH(units_per_type, other, s->meta.manager->units_per_type[UNIT_SERVICE]) {
373 bool special_s, special_t;
375 t = (Service*) other;
380 if (t->meta.load_state != UNIT_LOADED)
383 if (t->sysv_start_priority < 0)
386 /* If both units have modern headers we don't care
387 * about the priorities */
388 if ((s->meta.fragment_path || s->sysv_has_lsb) &&
389 (t->meta.fragment_path || t->sysv_has_lsb))
392 special_s = s->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, s->sysv_runlevels);
393 special_t = t->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, t->sysv_runlevels);
395 if (special_t && !special_s)
397 else if (special_s && !special_t)
399 else if (t->sysv_start_priority < s->sysv_start_priority)
401 else if (t->sysv_start_priority > s->sysv_start_priority)
406 /* FIXME: Maybe we should compare the name here lexicographically? */
408 if (!(r = unit_add_dependency(UNIT(s), d, UNIT(t), true)) < 0)
415 static ExecCommand *exec_command_new(const char *path, const char *arg1) {
418 if (!(c = new0(ExecCommand, 1)))
421 if (!(c->path = strdup(path))) {
426 if (!(c->argv = strv_new(path, arg1, NULL))) {
435 static int sysv_exec_commands(Service *s) {
439 assert(s->sysv_path);
441 if (!(c = exec_command_new(s->sysv_path, "start")))
443 exec_command_append_list(s->exec_command+SERVICE_EXEC_START, c);
445 if (!(c = exec_command_new(s->sysv_path, "stop")))
447 exec_command_append_list(s->exec_command+SERVICE_EXEC_STOP, c);
449 if (!(c = exec_command_new(s->sysv_path, "reload")))
451 exec_command_append_list(s->exec_command+SERVICE_EXEC_RELOAD, c);
456 static int service_load_sysv_path(Service *s, const char *path) {
467 char *short_description = NULL, *long_description = NULL, *chkconfig_description = NULL, *description;
474 if (!(f = fopen(path, "re"))) {
475 r = errno == ENOENT ? 0 : -errno;
480 if (!(s->sysv_path = strdup(path))) {
486 char l[LINE_MAX], *t;
488 if (!fgets(l, sizeof(l), f)) {
493 log_error("Failed to read configuration file '%s': %s", path, strerror(-r));
503 if (state == NORMAL && streq(t, "### BEGIN INIT INFO")) {
505 s->sysv_has_lsb = true;
509 if ((state == LSB_DESCRIPTION || state == LSB) && streq(t, "### END INIT INFO")) {
515 t += strspn(t, WHITESPACE);
517 if (state == NORMAL) {
519 /* Try to parse Red Hat style chkconfig headers */
521 if (startswith_no_case(t, "chkconfig:")) {
523 char runlevels[16], *k;
527 if (sscanf(t+10, "%15s %i %*i",
529 &start_priority) != 2) {
531 log_warning("[%s:%u] Failed to parse chkconfig line. Ignoring.", path, line);
535 /* A start priority gathered from the
536 * symlink farms is preferred over the
537 * data from the LSB header. */
538 if (start_priority < 0 || start_priority > 99)
539 log_warning("[%s:%u] Start priority out of range. Ignoring.", path, line);
540 else if (s->sysv_start_priority < 0)
541 s->sysv_start_priority = start_priority;
543 char_array_0(runlevels);
544 k = delete_chars(runlevels, WHITESPACE "-");
549 if (!(d = strdup(k))) {
554 free(s->sysv_runlevels);
555 s->sysv_runlevels = d;
558 } else if (startswith_no_case(t, "description:")) {
560 size_t k = strlen(t);
564 if (t[k-1] == '\\') {
569 if ((j = strstrip(t+12)) && *j) {
570 if (!(d = strdup(j))) {
577 free(chkconfig_description);
578 chkconfig_description = d;
580 } else if (startswith_no_case(t, "pidfile:")) {
587 if (!path_is_absolute(fn)) {
588 log_warning("[%s:%u] PID file not absolute. Ignoring.", path, line);
592 if (!(fn = strdup(fn))) {
601 } else if (state == DESCRIPTION) {
603 /* Try to parse Red Hat style description
606 size_t k = strlen(t);
614 if ((j = strstrip(t)) && *j) {
617 if (chkconfig_description)
618 asprintf(&d, "%s %s", chkconfig_description, j);
627 free(chkconfig_description);
628 chkconfig_description = d;
631 } else if (state == LSB || state == LSB_DESCRIPTION) {
633 if (startswith_no_case(t, "Provides:")) {
639 FOREACH_WORD_QUOTED(w, z, t+9, i) {
642 if (!(n = strndup(w, z))) {
647 r = sysv_translate_facility(n, file_name_from_path(path), &m);
656 if (unit_name_to_type(m) == UNIT_SERVICE)
657 r = unit_add_name(u, m);
659 r = unit_add_dependency_by_name(u, UNIT_BEFORE, m, NULL, true);
661 if (s->sysv_enabled) {
664 if ((k = unit_add_dependency_by_name_inverse(u, UNIT_WANTS, m, NULL, true)) < 0)
670 log_error("[%s:%u] Failed to add LSB Provides name %s, ignoring: %s", path, line, m, strerror(-r));
675 } else if (startswith_no_case(t, "Required-Start:") ||
676 startswith_no_case(t, "Should-Start:") ||
677 startswith_no_case(t, "X-Start-Before:") ||
678 startswith_no_case(t, "X-Start-After:")) {
684 FOREACH_WORD_QUOTED(w, z, strchr(t, ':')+1, i) {
687 if (!(n = strndup(w, z))) {
692 r = sysv_translate_facility(n, file_name_from_path(path), &m);
695 log_error("[%s:%u] Failed to translate LSB dependency %s, ignoring: %s", path, line, n, strerror(-r));
705 r = unit_add_dependency_by_name(u, startswith_no_case(t, "X-Start-Before:") ? UNIT_BEFORE : UNIT_AFTER, m, NULL, true);
708 log_error("[%s:%u] Failed to add dependency on %s, ignoring: %s", path, line, m, strerror(-r));
712 } else if (startswith_no_case(t, "Default-Start:")) {
717 k = delete_chars(t+14, WHITESPACE "-");
720 if (!(d = strdup(k))) {
725 free(s->sysv_runlevels);
726 s->sysv_runlevels = d;
729 } else if (startswith_no_case(t, "Description:")) {
732 state = LSB_DESCRIPTION;
734 if ((j = strstrip(t+12)) && *j) {
735 if (!(d = strdup(j))) {
742 free(long_description);
743 long_description = d;
745 } else if (startswith_no_case(t, "Short-Description:")) {
750 if ((j = strstrip(t+18)) && *j) {
751 if (!(d = strdup(j))) {
758 free(short_description);
759 short_description = d;
761 } else if (startswith_no_case(t, "X-Interactive:")) {
764 if ((b = parse_boolean(strstrip(t+14))) < 0) {
765 log_warning("[%s:%u] Couldn't parse interactive flag. Ignoring.", path, line);
770 s->exec_context.std_input = EXEC_INPUT_TTY;
772 s->exec_context.std_input = EXEC_INPUT_NULL;
774 } else if (state == LSB_DESCRIPTION) {
776 if (startswith(l, "#\t") || startswith(l, "# ")) {
779 if ((j = strstrip(t)) && *j) {
782 if (long_description)
783 asprintf(&d, "%s %s", long_description, t);
792 free(long_description);
793 long_description = d;
802 if ((r = sysv_exec_commands(s)) < 0)
805 if (s->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, s->sysv_runlevels)) {
806 /* If there a runlevels configured for this service
807 * but none of the standard ones, then we assume this
808 * is some special kind of service (which might be
809 * needed for early boot) and don't create any links
812 s->meta.default_dependencies = false;
814 /* Don't timeout special services during boot (like fsck) */
817 s->timeout_usec = DEFAULT_SYSV_TIMEOUT_USEC;
819 /* Special setting for all SysV services */
820 s->type = SERVICE_FORKING;
821 s->remain_after_exit = true;
822 s->restart = SERVICE_RESTART_NO;
823 s->exec_context.std_output =
824 (s->meta.manager->sysv_console || s->exec_context.std_input == EXEC_INPUT_TTY)
825 ? EXEC_OUTPUT_TTY : s->meta.manager->default_std_output;
826 s->exec_context.kill_mode = KILL_PROCESS_GROUP;
828 /* We use the long description only if
829 * no short description is set. */
831 if (short_description)
832 description = short_description;
833 else if (chkconfig_description)
834 description = chkconfig_description;
835 else if (long_description)
836 description = long_description;
843 if (!(d = strappend(s->sysv_has_lsb ? "LSB: " : "SYSV: ", description))) {
848 u->meta.description = d;
851 u->meta.load_state = UNIT_LOADED;
859 free(short_description);
860 free(long_description);
861 free(chkconfig_description);
866 static int service_load_sysv_name(Service *s, const char *name) {
872 /* For SysV services we strip the boot.*, rc.* and *.sh
873 * prefixes/suffixes. */
874 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU)
875 if (endswith(name, ".sh.service"))
880 if (startswith(name, "boot."))
884 #ifdef TARGET_FRUGALWARE
885 if (startswith(name, "rc."))
889 STRV_FOREACH(p, s->meta.manager->lookup_paths.sysvinit_path) {
893 if (asprintf(&path, "%s/%s", *p, name) < 0)
896 assert(endswith(path, ".service"));
897 path[strlen(path)-8] = 0;
899 r = service_load_sysv_path(s, path);
901 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU)
902 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
903 /* Try Debian style *.sh source'able init scripts */
905 r = service_load_sysv_path(s, path);
911 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
912 /* Try SUSE style boot.* init scripts */
914 if (asprintf(&path, "%s/boot.%s", *p, name) < 0)
917 /* Drop .service suffix */
918 path[strlen(path)-8] = 0;
919 r = service_load_sysv_path(s, path);
924 #ifdef TARGET_FRUGALWARE
925 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
926 /* Try Frugalware style rc.* init scripts */
928 if (asprintf(&path, "%s/rc.%s", *p, name) < 0)
931 /* Drop .service suffix */
932 path[strlen(path)-8] = 0;
933 r = service_load_sysv_path(s, path);
941 if ((s->meta.load_state != UNIT_STUB))
948 static int service_load_sysv(Service *s) {
955 /* Load service data from SysV init scripts, preferably with
958 if (strv_isempty(s->meta.manager->lookup_paths.sysvinit_path))
961 if ((t = s->meta.id))
962 if ((r = service_load_sysv_name(s, t)) < 0)
965 if (s->meta.load_state == UNIT_STUB)
966 SET_FOREACH(t, s->meta.names, i) {
970 if ((r = service_load_sysv_name(s, t)) < 0)
973 if (s->meta.load_state != UNIT_STUB)
981 static int fsck_fix_order(Service *s) {
987 if (s->fsck_passno <= 0)
990 /* For each pair of services where both have an fsck priority
991 * we order things based on it. */
993 LIST_FOREACH(units_per_type, other, s->meta.manager->units_per_type[UNIT_SERVICE]) {
997 t = (Service*) other;
1002 if (t->meta.load_state != UNIT_LOADED)
1005 if (t->fsck_passno <= 0)
1008 if (t->fsck_passno < s->fsck_passno)
1010 else if (t->fsck_passno > s->fsck_passno)
1015 if (!(r = unit_add_dependency(UNIT(s), d, UNIT(t), true)) < 0)
1022 static int service_verify(Service *s) {
1025 if (s->meta.load_state != UNIT_LOADED)
1028 if (!s->exec_command[SERVICE_EXEC_START]) {
1029 log_error("%s lacks ExecStart setting. Refusing.", s->meta.id);
1033 if (s->type != SERVICE_ONESHOT &&
1034 s->exec_command[SERVICE_EXEC_START]->command_next) {
1035 log_error("%s has more than one ExecStart setting, which is only allowed for Type=oneshot services. Refusing.", s->meta.id);
1039 if (s->type == SERVICE_ONESHOT &&
1040 s->exec_command[SERVICE_EXEC_RELOAD]) {
1041 log_error("%s has an ExecReload setting, which is not allowed for Type=oneshot services. Refusing.", s->meta.id);
1045 if (s->type == SERVICE_DBUS && !s->bus_name) {
1046 log_error("%s is of type D-Bus but no D-Bus service name has been specified. Refusing.", s->meta.id);
1050 if (s->exec_context.pam_name && s->exec_context.kill_mode != KILL_CONTROL_GROUP) {
1051 log_error("%s has PAM enabled. Kill mode must be set to 'control-group'. Refusing.", s->meta.id);
1058 static int service_add_default_dependencies(Service *s) {
1063 /* Add a number of automatic dependencies useful for the
1064 * majority of services. */
1066 /* First, pull in base system */
1067 if (s->meta.manager->running_as == MANAGER_SYSTEM) {
1069 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_BASIC_TARGET, NULL, true)) < 0)
1072 } else if (s->meta.manager->running_as == MANAGER_USER) {
1074 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SOCKETS_TARGET, NULL, true)) < 0)
1078 /* Second, activate normal shutdown */
1079 return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true);
1082 static int service_load(Unit *u) {
1084 Service *s = SERVICE(u);
1088 /* Load a .service file */
1089 if ((r = unit_load_fragment(u)) < 0)
1092 #ifdef HAVE_SYSV_COMPAT
1093 /* Load a classic init script as a fallback, if we couldn't find anything */
1094 if (u->meta.load_state == UNIT_STUB)
1095 if ((r = service_load_sysv(s)) < 0)
1099 /* Still nothing found? Then let's give up */
1100 if (u->meta.load_state == UNIT_STUB)
1103 /* We were able to load something, then let's add in the
1104 * dropin directories. */
1105 if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
1108 /* This is a new unit? Then let's add in some extras */
1109 if (u->meta.load_state == UNIT_LOADED) {
1110 if ((r = unit_add_exec_dependencies(u, &s->exec_context)) < 0)
1113 if ((r = unit_add_default_cgroups(u)) < 0)
1116 #ifdef HAVE_SYSV_COMPAT
1117 if ((r = sysv_fix_order(s)) < 0)
1121 if ((r = fsck_fix_order(s)) < 0)
1125 if ((r = unit_watch_bus_name(u, s->bus_name)) < 0)
1128 if (s->type == SERVICE_NOTIFY && s->notify_access == NOTIFY_NONE)
1129 s->notify_access = NOTIFY_MAIN;
1131 if (s->type == SERVICE_DBUS || s->bus_name)
1132 if ((r = unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_REQUIRES, SPECIAL_DBUS_SOCKET, NULL, true)) < 0)
1135 if (s->meta.default_dependencies)
1136 if ((r = service_add_default_dependencies(s)) < 0)
1140 return service_verify(s);
1143 static void service_dump(Unit *u, FILE *f, const char *prefix) {
1145 ServiceExecCommand c;
1146 Service *s = SERVICE(u);
1147 const char *prefix2;
1152 p2 = strappend(prefix, "\t");
1153 prefix2 = p2 ? p2 : prefix;
1156 "%sService State: %s\n"
1157 "%sPermissionsStartOnly: %s\n"
1158 "%sRootDirectoryStartOnly: %s\n"
1159 "%sRemainAfterExit: %s\n"
1160 "%sGuessMainPID: %s\n"
1163 "%sNotifyAccess: %s\n",
1164 prefix, service_state_to_string(s->state),
1165 prefix, yes_no(s->permissions_start_only),
1166 prefix, yes_no(s->root_directory_start_only),
1167 prefix, yes_no(s->remain_after_exit),
1168 prefix, yes_no(s->guess_main_pid),
1169 prefix, service_type_to_string(s->type),
1170 prefix, service_restart_to_string(s->restart),
1171 prefix, notify_access_to_string(s->notify_access));
1173 if (s->control_pid > 0)
1175 "%sControl PID: %lu\n",
1176 prefix, (unsigned long) s->control_pid);
1178 if (s->main_pid > 0)
1180 "%sMain PID: %lu\n",
1181 prefix, (unsigned long) s->main_pid);
1186 prefix, s->pid_file);
1191 "%sBus Name Good: %s\n",
1192 prefix, s->bus_name,
1193 prefix, yes_no(s->bus_name_good));
1195 exec_context_dump(&s->exec_context, f, prefix);
1197 for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
1199 if (!s->exec_command[c])
1202 fprintf(f, "%s-> %s:\n",
1203 prefix, service_exec_command_to_string(c));
1205 exec_command_dump_list(s->exec_command[c], f, prefix2);
1208 #ifdef HAVE_SYSV_COMPAT
1211 "%sSysV Init Script Path: %s\n"
1212 "%sSysV Init Script has LSB Header: %s\n"
1213 "%sSysVEnabled: %s\n",
1214 prefix, s->sysv_path,
1215 prefix, yes_no(s->sysv_has_lsb),
1216 prefix, yes_no(s->sysv_enabled));
1218 if (s->sysv_start_priority >= 0)
1220 "%sSysVStartPriority: %i\n",
1221 prefix, s->sysv_start_priority);
1223 if (s->sysv_runlevels)
1224 fprintf(f, "%sSysVRunLevels: %s\n",
1225 prefix, s->sysv_runlevels);
1228 if (s->fsck_passno > 0)
1230 "%sFsckPassNo: %i\n",
1231 prefix, s->fsck_passno);
1234 fprintf(f, "%sStatus Text: %s\n",
1235 prefix, s->status_text);
1240 static int service_load_pid_file(Service *s) {
1250 if ((r = read_one_line_file(s->pid_file, &k)) < 0)
1253 r = parse_pid(k, &pid);
1259 if (kill(pid, 0) < 0 && errno != EPERM) {
1260 log_warning("PID %lu read from file %s does not exist. Your service or init script might be broken.",
1261 (unsigned long) pid, s->pid_file);
1265 if ((r = service_set_main_pid(s, pid)) < 0)
1268 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1269 /* FIXME: we need to do something here */
1275 static int service_search_main_pid(Service *s) {
1281 /* If we know it anyway, don't ever fallback to unreliable
1283 if (s->main_pid_known)
1286 if (!s->guess_main_pid)
1289 assert(s->main_pid <= 0);
1291 if ((pid = cgroup_bonding_search_main_pid_list(s->meta.cgroup_bondings)) <= 0)
1294 if ((r = service_set_main_pid(s, pid)) < 0)
1297 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1298 /* FIXME: we need to do something here */
1304 static int service_get_sockets(Service *s, Set **_set) {
1313 if (s->socket_fd >= 0)
1316 if (!set_isempty(s->configured_sockets))
1319 /* Collects all Socket objects that belong to this
1320 * service. Note that a service might have multiple sockets
1321 * via multiple names. */
1323 if (!(set = set_new(NULL, NULL)))
1326 SET_FOREACH(t, s->meta.names, i) {
1330 /* Look for all socket objects that go by any of our
1331 * units and collect their fds */
1333 if (!(k = unit_name_change_suffix(t, ".socket"))) {
1338 p = manager_get_unit(s->meta.manager, k);
1344 if ((r = set_put(set, p)) < 0)
1356 static int service_notify_sockets_dead(Service *s) {
1358 Set *set, *free_set = NULL;
1364 /* Notifies all our sockets when we die */
1366 if (s->socket_fd >= 0)
1369 if (!set_isempty(s->configured_sockets))
1370 set = s->configured_sockets;
1372 if ((r = service_get_sockets(s, &free_set)) < 0)
1378 SET_FOREACH(sock, set, i)
1379 socket_notify_service_dead(sock);
1386 static void service_set_state(Service *s, ServiceState state) {
1387 ServiceState old_state;
1390 old_state = s->state;
1393 if (state != SERVICE_START_PRE &&
1394 state != SERVICE_START &&
1395 state != SERVICE_START_POST &&
1396 state != SERVICE_RELOAD &&
1397 state != SERVICE_STOP &&
1398 state != SERVICE_STOP_SIGTERM &&
1399 state != SERVICE_STOP_SIGKILL &&
1400 state != SERVICE_STOP_POST &&
1401 state != SERVICE_FINAL_SIGTERM &&
1402 state != SERVICE_FINAL_SIGKILL &&
1403 state != SERVICE_AUTO_RESTART)
1404 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1406 if (state != SERVICE_START &&
1407 state != SERVICE_START_POST &&
1408 state != SERVICE_RUNNING &&
1409 state != SERVICE_RELOAD &&
1410 state != SERVICE_STOP &&
1411 state != SERVICE_STOP_SIGTERM &&
1412 state != SERVICE_STOP_SIGKILL) {
1413 service_unwatch_main_pid(s);
1414 s->main_command = NULL;
1417 if (state != SERVICE_START_PRE &&
1418 state != SERVICE_START &&
1419 state != SERVICE_START_POST &&
1420 state != SERVICE_RELOAD &&
1421 state != SERVICE_STOP &&
1422 state != SERVICE_STOP_SIGTERM &&
1423 state != SERVICE_STOP_SIGKILL &&
1424 state != SERVICE_STOP_POST &&
1425 state != SERVICE_FINAL_SIGTERM &&
1426 state != SERVICE_FINAL_SIGKILL) {
1427 service_unwatch_control_pid(s);
1428 s->control_command = NULL;
1429 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1432 if (state == SERVICE_DEAD ||
1433 state == SERVICE_STOP ||
1434 state == SERVICE_STOP_SIGTERM ||
1435 state == SERVICE_STOP_SIGKILL ||
1436 state == SERVICE_STOP_POST ||
1437 state == SERVICE_FINAL_SIGTERM ||
1438 state == SERVICE_FINAL_SIGKILL ||
1439 state == SERVICE_FAILED ||
1440 state == SERVICE_AUTO_RESTART)
1441 service_notify_sockets_dead(s);
1443 if (state != SERVICE_START_PRE &&
1444 state != SERVICE_START &&
1445 state != SERVICE_START_POST &&
1446 state != SERVICE_RUNNING &&
1447 state != SERVICE_RELOAD &&
1448 state != SERVICE_STOP &&
1449 state != SERVICE_STOP_SIGTERM &&
1450 state != SERVICE_STOP_SIGKILL &&
1451 state != SERVICE_STOP_POST &&
1452 state != SERVICE_FINAL_SIGTERM &&
1453 state != SERVICE_FINAL_SIGKILL &&
1454 !(state == SERVICE_DEAD && s->meta.job)) {
1455 service_close_socket_fd(s);
1456 service_connection_unref(s);
1459 /* For the inactive states unit_notify() will trim the cgroup,
1460 * but for exit we have to do that ourselves... */
1461 if (state == SERVICE_EXITED)
1462 cgroup_bonding_trim_list(s->meta.cgroup_bondings, true);
1464 if (old_state != state)
1465 log_debug("%s changed %s -> %s", s->meta.id, service_state_to_string(old_state), service_state_to_string(state));
1467 unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state], !s->reload_failure);
1468 s->reload_failure = false;
1471 static int service_coldplug(Unit *u) {
1472 Service *s = SERVICE(u);
1476 assert(s->state == SERVICE_DEAD);
1478 if (s->deserialized_state != s->state) {
1480 if (s->deserialized_state == SERVICE_START_PRE ||
1481 s->deserialized_state == SERVICE_START ||
1482 s->deserialized_state == SERVICE_START_POST ||
1483 s->deserialized_state == SERVICE_RELOAD ||
1484 s->deserialized_state == SERVICE_STOP ||
1485 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1486 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1487 s->deserialized_state == SERVICE_STOP_POST ||
1488 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1489 s->deserialized_state == SERVICE_FINAL_SIGKILL ||
1490 s->deserialized_state == SERVICE_AUTO_RESTART) {
1492 if (s->deserialized_state == SERVICE_AUTO_RESTART || s->timeout_usec > 0) {
1495 k = s->deserialized_state == SERVICE_AUTO_RESTART ? s->restart_usec : s->timeout_usec;
1497 if ((r = unit_watch_timer(UNIT(s), k, &s->timer_watch)) < 0)
1502 if ((s->deserialized_state == SERVICE_START &&
1503 (s->type == SERVICE_FORKING ||
1504 s->type == SERVICE_DBUS ||
1505 s->type == SERVICE_ONESHOT ||
1506 s->type == SERVICE_NOTIFY)) ||
1507 s->deserialized_state == SERVICE_START_POST ||
1508 s->deserialized_state == SERVICE_RUNNING ||
1509 s->deserialized_state == SERVICE_RELOAD ||
1510 s->deserialized_state == SERVICE_STOP ||
1511 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1512 s->deserialized_state == SERVICE_STOP_SIGKILL)
1513 if (s->main_pid > 0)
1514 if ((r = unit_watch_pid(UNIT(s), s->main_pid)) < 0)
1517 if (s->deserialized_state == SERVICE_START_PRE ||
1518 s->deserialized_state == SERVICE_START ||
1519 s->deserialized_state == SERVICE_START_POST ||
1520 s->deserialized_state == SERVICE_RELOAD ||
1521 s->deserialized_state == SERVICE_STOP ||
1522 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1523 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1524 s->deserialized_state == SERVICE_STOP_POST ||
1525 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1526 s->deserialized_state == SERVICE_FINAL_SIGKILL)
1527 if (s->control_pid > 0)
1528 if ((r = unit_watch_pid(UNIT(s), s->control_pid)) < 0)
1531 service_set_state(s, s->deserialized_state);
1537 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
1541 unsigned rn_fds = 0;
1542 Set *set, *free_set = NULL;
1549 if (s->socket_fd >= 0)
1552 if (!set_isempty(s->configured_sockets))
1553 set = s->configured_sockets;
1555 if ((r = service_get_sockets(s, &free_set)) < 0)
1561 SET_FOREACH(sock, set, i) {
1565 if ((r = socket_collect_fds(sock, &cfds, &cn_fds)) < 0)
1577 if (!(t = new(int, rn_fds+cn_fds))) {
1583 memcpy(t, rfds, rn_fds);
1584 memcpy(t+rn_fds, cfds, cn_fds);
1589 rn_fds = rn_fds+cn_fds;
1607 static int service_spawn(
1612 bool apply_permissions,
1614 bool apply_tty_stdin,
1615 bool set_notify_socket,
1620 int *fds = NULL, *fdsbuf = NULL;
1621 unsigned n_fds = 0, n_env = 0;
1622 char **argv = NULL, **final_env = NULL, **our_env = NULL;
1629 s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1630 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1631 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
1633 if (s->socket_fd >= 0) {
1634 fds = &s->socket_fd;
1637 if ((r = service_collect_fds(s, &fdsbuf, &n_fds)) < 0)
1644 if (timeout && s->timeout_usec) {
1645 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1648 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1650 if (!(argv = unit_full_printf_strv(UNIT(s), c->argv))) {
1655 if (!(our_env = new0(char*, 4))) {
1660 if (set_notify_socket)
1661 if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=%s", s->meta.manager->notify_socket) < 0) {
1666 if (s->main_pid > 0)
1667 if (asprintf(our_env + n_env++, "MAINPID=%lu", (unsigned long) s->main_pid) < 0) {
1672 if (!(final_env = strv_env_merge(2,
1673 s->meta.manager->environment,
1688 s->meta.manager->confirm_spawn,
1689 s->meta.cgroup_bondings,
1696 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1697 /* FIXME: we need to do something here */
1703 strv_free(final_env);
1713 strv_free(final_env);
1716 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1721 static int main_pid_good(Service *s) {
1724 /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1727 /* If we know the pid file, then lets just check if it is
1729 if (s->main_pid_known)
1730 return s->main_pid > 0;
1732 /* We don't know the pid */
1736 static int control_pid_good(Service *s) {
1739 return s->control_pid > 0;
1742 static int cgroup_good(Service *s) {
1747 if ((r = cgroup_bonding_is_empty_list(s->meta.cgroup_bondings)) < 0)
1753 static void service_enter_dead(Service *s, bool success, bool allow_restart) {
1760 if (allow_restart &&
1761 !s->forbid_restart &&
1762 (s->restart == SERVICE_RESTART_ALWAYS ||
1763 (s->restart == SERVICE_RESTART_ON_SUCCESS && !s->failure) ||
1764 (s->restart == SERVICE_RESTART_ON_FAILURE && s->failure) ||
1765 (s->restart == SERVICE_RESTART_ON_ABORT && s->failure &&
1766 (s->main_exec_status.code == CLD_KILLED ||
1767 s->main_exec_status.code == CLD_DUMPED)))) {
1769 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
1772 service_set_state(s, SERVICE_AUTO_RESTART);
1774 service_set_state(s, s->failure ? SERVICE_FAILED : SERVICE_DEAD);
1776 s->forbid_restart = false;
1781 log_warning("%s failed to run install restart timer: %s", s->meta.id, strerror(-r));
1782 service_enter_dead(s, false, false);
1785 static void service_enter_signal(Service *s, ServiceState state, bool success);
1787 static void service_enter_stop_post(Service *s, bool success) {
1794 service_unwatch_control_pid(s);
1796 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST])) {
1797 s->control_command_id = SERVICE_EXEC_STOP_POST;
1799 if ((r = service_spawn(s,
1803 !s->permissions_start_only,
1804 !s->root_directory_start_only,
1807 &s->control_pid)) < 0)
1811 service_set_state(s, SERVICE_STOP_POST);
1813 service_enter_signal(s, SERVICE_FINAL_SIGTERM, true);
1818 log_warning("%s failed to run 'stop-post' task: %s", s->meta.id, strerror(-r));
1819 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1822 static void service_enter_signal(Service *s, ServiceState state, bool success) {
1824 Set *pid_set = NULL;
1825 bool wait_for_exit = false;
1832 if (s->exec_context.kill_mode != KILL_NONE) {
1833 int sig = (state == SERVICE_STOP_SIGTERM || state == SERVICE_FINAL_SIGTERM) ? s->exec_context.kill_signal : SIGKILL;
1835 if (s->main_pid > 0) {
1836 if (kill_and_sigcont(s->exec_context.kill_mode == KILL_PROCESS_GROUP ?
1838 s->main_pid, sig) < 0 && errno != ESRCH)
1840 log_warning("Failed to kill main process %li: %m", (long) s->main_pid);
1842 wait_for_exit = true;
1845 if (s->control_pid > 0) {
1846 if (kill_and_sigcont(s->exec_context.kill_mode == KILL_PROCESS_GROUP ?
1848 s->control_pid, sig) < 0 && errno != ESRCH)
1850 log_warning("Failed to kill control process %li: %m", (long) s->control_pid);
1852 wait_for_exit = true;
1855 if (s->exec_context.kill_mode == KILL_CONTROL_GROUP) {
1857 if (!(pid_set = set_new(trivial_hash_func, trivial_compare_func))) {
1862 /* Exclude the main/control pids from being killed via the cgroup */
1863 if (s->main_pid > 0)
1864 if ((r = set_put(pid_set, LONG_TO_PTR(s->main_pid))) < 0)
1867 if (s->control_pid > 0)
1868 if ((r = set_put(pid_set, LONG_TO_PTR(s->control_pid))) < 0)
1871 if ((r = cgroup_bonding_kill_list(s->meta.cgroup_bondings, sig, true, pid_set)) < 0) {
1872 if (r != -EAGAIN && r != -ESRCH && r != -ENOENT)
1873 log_warning("Failed to kill control group: %s", strerror(-r));
1875 wait_for_exit = true;
1881 if (wait_for_exit) {
1882 if (s->timeout_usec > 0)
1883 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1886 service_set_state(s, state);
1887 } else if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1888 service_enter_stop_post(s, true);
1890 service_enter_dead(s, true, true);
1895 log_warning("%s failed to kill processes: %s", s->meta.id, strerror(-r));
1897 if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1898 service_enter_stop_post(s, false);
1900 service_enter_dead(s, false, true);
1906 static void service_enter_stop(Service *s, bool success) {
1914 service_unwatch_control_pid(s);
1916 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP])) {
1917 s->control_command_id = SERVICE_EXEC_STOP;
1919 if ((r = service_spawn(s,
1923 !s->permissions_start_only,
1924 !s->root_directory_start_only,
1927 &s->control_pid)) < 0)
1930 service_set_state(s, SERVICE_STOP);
1932 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
1937 log_warning("%s failed to run 'stop' task: %s", s->meta.id, strerror(-r));
1938 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1941 static void service_enter_running(Service *s, bool success) {
1942 int main_pid_ok, cgroup_ok;
1948 main_pid_ok = main_pid_good(s);
1949 cgroup_ok = cgroup_good(s);
1951 if ((main_pid_ok > 0 || (main_pid_ok < 0 && cgroup_ok != 0)) &&
1952 (s->bus_name_good || s->type != SERVICE_DBUS))
1953 service_set_state(s, SERVICE_RUNNING);
1954 else if (s->remain_after_exit)
1955 service_set_state(s, SERVICE_EXITED);
1957 service_enter_stop(s, true);
1960 static void service_enter_start_post(Service *s) {
1964 service_unwatch_control_pid(s);
1966 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_POST])) {
1967 s->control_command_id = SERVICE_EXEC_START_POST;
1969 if ((r = service_spawn(s,
1973 !s->permissions_start_only,
1974 !s->root_directory_start_only,
1977 &s->control_pid)) < 0)
1980 service_set_state(s, SERVICE_START_POST);
1982 service_enter_running(s, true);
1987 log_warning("%s failed to run 'start-post' task: %s", s->meta.id, strerror(-r));
1988 service_enter_stop(s, false);
1991 static void service_enter_start(Service *s) {
1998 assert(s->exec_command[SERVICE_EXEC_START]);
1999 assert(!s->exec_command[SERVICE_EXEC_START]->command_next || s->type == SERVICE_ONESHOT);
2001 if (s->type == SERVICE_FORKING)
2002 service_unwatch_control_pid(s);
2004 service_unwatch_main_pid(s);
2006 if (s->type == SERVICE_FORKING) {
2007 s->control_command_id = SERVICE_EXEC_START;
2008 c = s->control_command = s->exec_command[SERVICE_EXEC_START];
2010 s->main_command = NULL;
2012 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2013 s->control_command = NULL;
2015 c = s->main_command = s->exec_command[SERVICE_EXEC_START];
2018 if ((r = service_spawn(s,
2020 s->type == SERVICE_FORKING || s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY,
2025 s->notify_access != NOTIFY_NONE,
2029 if (s->type == SERVICE_SIMPLE) {
2030 /* For simple services we immediately start
2031 * the START_POST binaries. */
2033 service_set_main_pid(s, pid);
2034 service_enter_start_post(s);
2036 } else if (s->type == SERVICE_FORKING) {
2038 /* For forking services we wait until the start
2039 * process exited. */
2041 s->control_pid = pid;
2042 service_set_state(s, SERVICE_START);
2044 } else if (s->type == SERVICE_ONESHOT ||
2045 s->type == SERVICE_DBUS ||
2046 s->type == SERVICE_NOTIFY) {
2048 /* For oneshot services we wait until the start
2049 * process exited, too, but it is our main process. */
2051 /* For D-Bus services we know the main pid right away,
2052 * but wait for the bus name to appear on the
2053 * bus. Notify services are similar. */
2055 service_set_main_pid(s, pid);
2056 service_set_state(s, SERVICE_START);
2058 assert_not_reached("Unknown service type");
2063 log_warning("%s failed to run 'start' task: %s", s->meta.id, strerror(-r));
2064 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2067 static void service_enter_start_pre(Service *s) {
2072 service_unwatch_control_pid(s);
2074 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_PRE])) {
2075 s->control_command_id = SERVICE_EXEC_START_PRE;
2077 if ((r = service_spawn(s,
2081 !s->permissions_start_only,
2082 !s->root_directory_start_only,
2085 &s->control_pid)) < 0)
2088 service_set_state(s, SERVICE_START_PRE);
2090 service_enter_start(s);
2095 log_warning("%s failed to run 'start-pre' task: %s", s->meta.id, strerror(-r));
2096 service_enter_dead(s, false, true);
2099 static void service_enter_restart(Service *s) {
2104 dbus_error_init(&error);
2107 log_info("Job pending for unit, delaying automatic restart.");
2109 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
2113 service_enter_dead(s, true, false);
2115 if ((r = manager_add_job(s->meta.manager, JOB_START, UNIT(s), JOB_FAIL, false, &error, NULL)) < 0)
2118 log_debug("%s scheduled restart job.", s->meta.id);
2122 log_warning("%s failed to schedule restart job: %s", s->meta.id, bus_error(&error, -r));
2123 service_enter_dead(s, false, false);
2125 dbus_error_free(&error);
2128 static void service_enter_reload(Service *s) {
2133 service_unwatch_control_pid(s);
2135 if ((s->control_command = s->exec_command[SERVICE_EXEC_RELOAD])) {
2136 s->control_command_id = SERVICE_EXEC_RELOAD;
2138 if ((r = service_spawn(s,
2142 !s->permissions_start_only,
2143 !s->root_directory_start_only,
2146 &s->control_pid)) < 0)
2149 service_set_state(s, SERVICE_RELOAD);
2151 service_enter_running(s, true);
2156 log_warning("%s failed to run 'reload' task: %s", s->meta.id, strerror(-r));
2157 s->reload_failure = true;
2158 service_enter_running(s, true);
2161 static void service_run_next_control(Service *s, bool success) {
2165 assert(s->control_command);
2166 assert(s->control_command->command_next);
2171 assert(s->control_command_id != SERVICE_EXEC_START);
2173 s->control_command = s->control_command->command_next;
2174 service_unwatch_control_pid(s);
2176 if ((r = service_spawn(s,
2180 !s->permissions_start_only,
2181 !s->root_directory_start_only,
2182 s->control_command_id == SERVICE_EXEC_START_PRE ||
2183 s->control_command_id == SERVICE_EXEC_STOP_POST,
2185 &s->control_pid)) < 0)
2191 log_warning("%s failed to run next control task: %s", s->meta.id, strerror(-r));
2193 if (s->state == SERVICE_START_PRE)
2194 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2195 else if (s->state == SERVICE_STOP)
2196 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
2197 else if (s->state == SERVICE_STOP_POST)
2198 service_enter_dead(s, false, true);
2199 else if (s->state == SERVICE_RELOAD) {
2200 s->reload_failure = true;
2201 service_enter_running(s, true);
2203 service_enter_stop(s, false);
2206 static void service_run_next_main(Service *s, bool success) {
2211 assert(s->main_command);
2212 assert(s->main_command->command_next);
2213 assert(s->type == SERVICE_ONESHOT);
2218 s->main_command = s->main_command->command_next;
2219 service_unwatch_main_pid(s);
2221 if ((r = service_spawn(s,
2228 s->notify_access != NOTIFY_NONE,
2232 service_set_main_pid(s, pid);
2237 log_warning("%s failed to run next main task: %s", s->meta.id, strerror(-r));
2238 service_enter_stop(s, false);
2241 static int service_start(Unit *u) {
2242 Service *s = SERVICE(u);
2246 /* We cannot fulfill this request right now, try again later
2248 if (s->state == SERVICE_STOP ||
2249 s->state == SERVICE_STOP_SIGTERM ||
2250 s->state == SERVICE_STOP_SIGKILL ||
2251 s->state == SERVICE_STOP_POST ||
2252 s->state == SERVICE_FINAL_SIGTERM ||
2253 s->state == SERVICE_FINAL_SIGKILL)
2256 /* Already on it! */
2257 if (s->state == SERVICE_START_PRE ||
2258 s->state == SERVICE_START ||
2259 s->state == SERVICE_START_POST)
2262 assert(s->state == SERVICE_DEAD || s->state == SERVICE_FAILED || s->state == SERVICE_AUTO_RESTART);
2264 /* Make sure we don't enter a busy loop of some kind. */
2265 if (!ratelimit_test(&s->ratelimit)) {
2266 log_warning("%s start request repeated too quickly, refusing to start.", u->meta.id);
2271 s->main_pid_known = false;
2272 s->forbid_restart = false;
2274 service_enter_start_pre(s);
2278 static int service_stop(Unit *u) {
2279 Service *s = SERVICE(u);
2283 /* This is a user request, so don't do restarts on this
2285 s->forbid_restart = true;
2288 if (s->state == SERVICE_STOP ||
2289 s->state == SERVICE_STOP_SIGTERM ||
2290 s->state == SERVICE_STOP_SIGKILL ||
2291 s->state == SERVICE_STOP_POST ||
2292 s->state == SERVICE_FINAL_SIGTERM ||
2293 s->state == SERVICE_FINAL_SIGKILL)
2296 /* Don't allow a restart */
2297 if (s->state == SERVICE_AUTO_RESTART) {
2298 service_set_state(s, SERVICE_DEAD);
2302 /* If there's already something running we go directly into
2304 if (s->state == SERVICE_START_PRE ||
2305 s->state == SERVICE_START ||
2306 s->state == SERVICE_START_POST ||
2307 s->state == SERVICE_RELOAD) {
2308 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
2312 assert(s->state == SERVICE_RUNNING ||
2313 s->state == SERVICE_EXITED);
2315 service_enter_stop(s, true);
2319 static int service_reload(Unit *u) {
2320 Service *s = SERVICE(u);
2324 assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
2326 service_enter_reload(s);
2330 static bool service_can_reload(Unit *u) {
2331 Service *s = SERVICE(u);
2335 return !!s->exec_command[SERVICE_EXEC_RELOAD];
2338 static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
2339 Service *s = SERVICE(u);
2345 unit_serialize_item(u, f, "state", service_state_to_string(s->state));
2346 unit_serialize_item(u, f, "failure", yes_no(s->failure));
2348 if (s->control_pid > 0)
2349 unit_serialize_item_format(u, f, "control-pid", "%lu", (unsigned long) s->control_pid);
2351 if (s->main_pid_known && s->main_pid > 0)
2352 unit_serialize_item_format(u, f, "main-pid", "%lu", (unsigned long) s->main_pid);
2354 unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
2357 unit_serialize_item(u, f, "status-text", s->status_text);
2359 /* There's a minor uncleanliness here: if there are multiple
2360 * commands attached here, we will start from the first one
2362 if (s->control_command_id >= 0)
2363 unit_serialize_item(u, f, "control-command", service_exec_command_to_string(s->control_command_id));
2365 if (s->socket_fd >= 0) {
2368 if ((copy = fdset_put_dup(fds, s->socket_fd)) < 0)
2371 unit_serialize_item_format(u, f, "socket-fd", "%i", copy);
2374 if (s->main_exec_status.pid > 0) {
2375 unit_serialize_item_format(u, f, "main-exec-status-pid", "%lu", (unsigned long) s->main_exec_status.pid);
2376 dual_timestamp_serialize(f, "main-exec-status-start", &s->main_exec_status.start_timestamp);
2377 dual_timestamp_serialize(f, "main-exec-status-exit", &s->main_exec_status.exit_timestamp);
2379 if (dual_timestamp_is_set(&s->main_exec_status.exit_timestamp)) {
2380 unit_serialize_item_format(u, f, "main-exec-status-code", "%i", s->main_exec_status.code);
2381 unit_serialize_item_format(u, f, "main-exec-status-status", "%i", s->main_exec_status.status);
2388 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
2389 Service *s = SERVICE(u);
2396 if (streq(key, "state")) {
2399 if ((state = service_state_from_string(value)) < 0)
2400 log_debug("Failed to parse state value %s", value);
2402 s->deserialized_state = state;
2403 } else if (streq(key, "failure")) {
2406 if ((b = parse_boolean(value)) < 0)
2407 log_debug("Failed to parse failure value %s", value);
2409 s->failure = b || s->failure;
2410 } else if (streq(key, "control-pid")) {
2413 if (parse_pid(value, &pid) < 0)
2414 log_debug("Failed to parse control-pid value %s", value);
2416 s->control_pid = pid;
2417 } else if (streq(key, "main-pid")) {
2420 if (parse_pid(value, &pid) < 0)
2421 log_debug("Failed to parse main-pid value %s", value);
2423 service_set_main_pid(s, (pid_t) pid);
2424 } else if (streq(key, "main-pid-known")) {
2427 if ((b = parse_boolean(value)) < 0)
2428 log_debug("Failed to parse main-pid-known value %s", value);
2430 s->main_pid_known = b;
2431 } else if (streq(key, "status-text")) {
2434 if ((t = strdup(value))) {
2435 free(s->status_text);
2439 } else if (streq(key, "control-command")) {
2440 ServiceExecCommand id;
2442 if ((id = service_exec_command_from_string(value)) < 0)
2443 log_debug("Failed to parse exec-command value %s", value);
2445 s->control_command_id = id;
2446 s->control_command = s->exec_command[id];
2448 } else if (streq(key, "socket-fd")) {
2451 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2452 log_debug("Failed to parse socket-fd value %s", value);
2455 if (s->socket_fd >= 0)
2456 close_nointr_nofail(s->socket_fd);
2457 s->socket_fd = fdset_remove(fds, fd);
2459 } else if (streq(key, "main-exec-status-pid")) {
2462 if (parse_pid(value, &pid) < 0)
2463 log_debug("Failed to parse main-exec-status-pid value %s", value);
2465 s->main_exec_status.pid = pid;
2466 } else if (streq(key, "main-exec-status-code")) {
2469 if (safe_atoi(value, &i) < 0)
2470 log_debug("Failed to parse main-exec-status-code value %s", value);
2472 s->main_exec_status.code = i;
2473 } else if (streq(key, "main-exec-status-status")) {
2476 if (safe_atoi(value, &i) < 0)
2477 log_debug("Failed to parse main-exec-status-status value %s", value);
2479 s->main_exec_status.status = i;
2480 } else if (streq(key, "main-exec-status-start"))
2481 dual_timestamp_deserialize(value, &s->main_exec_status.start_timestamp);
2482 else if (streq(key, "main-exec-status-exit"))
2483 dual_timestamp_deserialize(value, &s->main_exec_status.exit_timestamp);
2485 log_debug("Unknown serialization key '%s'", key);
2490 static UnitActiveState service_active_state(Unit *u) {
2493 return state_translation_table[SERVICE(u)->state];
2496 static const char *service_sub_state_to_string(Unit *u) {
2499 return service_state_to_string(SERVICE(u)->state);
2502 static bool service_check_gc(Unit *u) {
2503 Service *s = SERVICE(u);
2507 /* Never clean up services that still have a process around,
2508 * even if the service is formally dead. */
2509 if (cgroup_good(s) > 0 ||
2510 main_pid_good(s) > 0 ||
2511 control_pid_good(s) > 0)
2514 #ifdef HAVE_SYSV_COMPAT
2522 static bool service_check_snapshot(Unit *u) {
2523 Service *s = SERVICE(u);
2527 return !s->got_socket_fd;
2530 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2531 Service *s = SERVICE(u);
2537 if (!s->meta.fragment_path)
2538 success = is_clean_exit_lsb(code, status);
2540 success = is_clean_exit(code, status);
2542 if (s->main_pid == pid) {
2545 exec_status_exit(&s->main_exec_status, pid, code, status, s->exec_context.utmp_id);
2547 /* If this is not a forking service than the main
2548 * process got started and hence we copy the exit
2549 * status so that it is recorded both as main and as
2550 * control process exit status */
2551 if (s->main_command) {
2552 s->main_command->exec_status = s->main_exec_status;
2554 if (s->main_command->ignore)
2558 log_full(success ? LOG_DEBUG : LOG_NOTICE,
2559 "%s: main process exited, code=%s, status=%i", u->meta.id, sigchld_code_to_string(code), status);
2560 s->failure = s->failure || !success;
2562 if (s->main_command &&
2563 s->main_command->command_next &&
2566 /* There is another command to *
2567 * execute, so let's do that. */
2569 log_debug("%s running next main command for state %s", u->meta.id, service_state_to_string(s->state));
2570 service_run_next_main(s, success);
2574 /* The service exited, so the service is officially
2576 s->main_command = NULL;
2580 case SERVICE_START_POST:
2581 case SERVICE_RELOAD:
2583 /* Need to wait until the operation is
2588 if (s->type == SERVICE_ONESHOT) {
2589 /* This was our main goal, so let's go on */
2591 service_enter_start_post(s);
2593 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2596 assert(s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY);
2601 case SERVICE_RUNNING:
2602 service_enter_running(s, success);
2605 case SERVICE_STOP_SIGTERM:
2606 case SERVICE_STOP_SIGKILL:
2608 if (!control_pid_good(s))
2609 service_enter_stop_post(s, success);
2611 /* If there is still a control process, wait for that first */
2615 assert_not_reached("Uh, main process died at wrong time.");
2619 } else if (s->control_pid == pid) {
2623 if (s->control_command) {
2624 exec_status_exit(&s->control_command->exec_status, pid, code, status, s->exec_context.utmp_id);
2626 if (s->control_command->ignore)
2630 log_full(success ? LOG_DEBUG : LOG_NOTICE,
2631 "%s: control process exited, code=%s status=%i", u->meta.id, sigchld_code_to_string(code), status);
2632 s->failure = s->failure || !success;
2634 if (s->control_command &&
2635 s->control_command->command_next &&
2638 /* There is another command to *
2639 * execute, so let's do that. */
2641 log_debug("%s running next control command for state %s", u->meta.id, service_state_to_string(s->state));
2642 service_run_next_control(s, success);
2645 /* No further commands for this step, so let's
2646 * figure out what to do next */
2648 s->control_command = NULL;
2649 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2651 log_debug("%s got final SIGCHLD for state %s", u->meta.id, service_state_to_string(s->state));
2655 case SERVICE_START_PRE:
2657 service_enter_start(s);
2659 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2663 assert(s->type == SERVICE_FORKING);
2665 /* Let's try to load the pid
2666 * file here if we can. We
2667 * ignore the return value,
2668 * since the PID file might
2669 * actually be created by a
2670 * START_POST script */
2673 service_load_pid_file(s);
2674 service_search_main_pid(s);
2676 service_enter_start_post(s);
2678 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2682 case SERVICE_START_POST:
2683 if (success && s->pid_file && !s->main_pid_known) {
2686 /* Hmm, let's see if we can
2687 * load the pid now after the
2688 * start-post scripts got
2691 if ((r = service_load_pid_file(s)) < 0)
2692 log_warning("%s: failed to load PID file %s: %s", s->meta.id, s->pid_file, strerror(-r));
2695 s->reload_failure = !success;
2696 service_enter_running(s, true);
2699 case SERVICE_RELOAD:
2701 service_load_pid_file(s);
2702 service_search_main_pid(s);
2705 s->reload_failure = !success;
2706 service_enter_running(s, true);
2710 service_enter_signal(s, SERVICE_STOP_SIGTERM, success);
2713 case SERVICE_STOP_SIGTERM:
2714 case SERVICE_STOP_SIGKILL:
2715 if (main_pid_good(s) <= 0)
2716 service_enter_stop_post(s, success);
2718 /* If there is still a service
2719 * process around, wait until
2720 * that one quit, too */
2723 case SERVICE_STOP_POST:
2724 case SERVICE_FINAL_SIGTERM:
2725 case SERVICE_FINAL_SIGKILL:
2726 service_enter_dead(s, success, true);
2730 assert_not_reached("Uh, control process died at wrong time.");
2735 /* Notify clients about changed exit status */
2736 unit_add_to_dbus_queue(u);
2739 static void service_timer_event(Unit *u, uint64_t elapsed, Watch* w) {
2740 Service *s = SERVICE(u);
2743 assert(elapsed == 1);
2745 assert(w == &s->timer_watch);
2749 case SERVICE_START_PRE:
2751 log_warning("%s operation timed out. Terminating.", u->meta.id);
2752 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2755 case SERVICE_START_POST:
2756 log_warning("%s operation timed out. Stopping.", u->meta.id);
2757 service_enter_stop(s, false);
2760 case SERVICE_RELOAD:
2761 log_warning("%s operation timed out. Stopping.", u->meta.id);
2762 s->reload_failure = true;
2763 service_enter_running(s, true);
2767 log_warning("%s stopping timed out. Terminating.", u->meta.id);
2768 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
2771 case SERVICE_STOP_SIGTERM:
2772 if (s->exec_context.send_sigkill) {
2773 log_warning("%s stopping timed out. Killing.", u->meta.id);
2774 service_enter_signal(s, SERVICE_STOP_SIGKILL, false);
2776 log_warning("%s stopping timed out. Skipping SIGKILL.", u->meta.id);
2777 service_enter_stop_post(s, false);
2782 case SERVICE_STOP_SIGKILL:
2783 /* Uh, we sent a SIGKILL and it is still not gone?
2784 * Must be something we cannot kill, so let's just be
2785 * weirded out and continue */
2787 log_warning("%s still around after SIGKILL. Ignoring.", u->meta.id);
2788 service_enter_stop_post(s, false);
2791 case SERVICE_STOP_POST:
2792 log_warning("%s stopping timed out (2). Terminating.", u->meta.id);
2793 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2796 case SERVICE_FINAL_SIGTERM:
2797 if (s->exec_context.send_sigkill) {
2798 log_warning("%s stopping timed out (2). Killing.", u->meta.id);
2799 service_enter_signal(s, SERVICE_FINAL_SIGKILL, false);
2801 log_warning("%s stopping timed out (2). Skipping SIGKILL. Entering failed mode.", u->meta.id);
2802 service_enter_dead(s, false, true);
2807 case SERVICE_FINAL_SIGKILL:
2808 log_warning("%s still around after SIGKILL (2). Entering failed mode.", u->meta.id);
2809 service_enter_dead(s, false, true);
2812 case SERVICE_AUTO_RESTART:
2813 log_info("%s holdoff time over, scheduling restart.", u->meta.id);
2814 service_enter_restart(s);
2818 assert_not_reached("Timeout at wrong time.");
2822 static void service_cgroup_notify_event(Unit *u) {
2823 Service *s = SERVICE(u);
2827 log_debug("%s: cgroup is empty", u->meta.id);
2831 /* Waiting for SIGCHLD is usually more interesting,
2832 * because it includes return codes/signals. Which is
2833 * why we ignore the cgroup events for most cases,
2834 * except when we don't know pid which to expect the
2837 case SERVICE_RUNNING:
2838 service_enter_running(s, true);
2841 case SERVICE_STOP_SIGTERM:
2842 case SERVICE_STOP_SIGKILL:
2843 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2844 service_enter_stop_post(s, true);
2848 case SERVICE_FINAL_SIGTERM:
2849 case SERVICE_FINAL_SIGKILL:
2850 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2851 service_enter_dead(s, true, true);
2860 static void service_notify_message(Unit *u, pid_t pid, char **tags) {
2861 Service *s = SERVICE(u);
2866 if (s->notify_access == NOTIFY_NONE) {
2867 log_warning("%s: Got notification message from PID %lu, but reception is disabled.",
2868 u->meta.id, (unsigned long) pid);
2872 if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
2873 log_warning("%s: Got notification message from PID %lu, but reception only permitted for PID %lu",
2874 u->meta.id, (unsigned long) pid, (unsigned long) s->main_pid);
2878 log_debug("%s: Got message", u->meta.id);
2880 /* Interpret MAINPID= */
2881 if ((e = strv_find_prefix(tags, "MAINPID=")) &&
2882 (s->state == SERVICE_START ||
2883 s->state == SERVICE_START_POST ||
2884 s->state == SERVICE_RUNNING ||
2885 s->state == SERVICE_RELOAD)) {
2887 if (parse_pid(e + 8, &pid) < 0)
2888 log_warning("Failed to parse notification message %s", e);
2890 log_debug("%s: got %s", u->meta.id, e);
2891 service_set_main_pid(s, pid);
2895 /* Interpret READY= */
2896 if (s->type == SERVICE_NOTIFY &&
2897 s->state == SERVICE_START &&
2898 strv_find(tags, "READY=1")) {
2899 log_debug("%s: got READY=1", u->meta.id);
2901 service_enter_start_post(s);
2904 /* Interpret STATUS= */
2905 if ((e = strv_find_prefix(tags, "STATUS="))) {
2909 if (!(t = strdup(e+7))) {
2910 log_error("Failed to allocate string.");
2914 log_debug("%s: got %s", u->meta.id, e);
2916 free(s->status_text);
2919 free(s->status_text);
2920 s->status_text = NULL;
2925 /* Notify clients about changed status or main pid */
2926 unit_add_to_dbus_queue(u);
2929 #ifdef HAVE_SYSV_COMPAT
2930 static int service_enumerate(Manager *m) {
2934 char *path = NULL, *fpath = NULL, *name = NULL;
2935 Set *runlevel_services[ELEMENTSOF(rcnd_table)], *shutdown_services = NULL;
2942 zero(runlevel_services);
2944 STRV_FOREACH(p, m->lookup_paths.sysvrcnd_path)
2945 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++) {
2950 if (asprintf(&path, "%s/%s", *p, rcnd_table[i].path) < 0) {
2958 if (!(d = opendir(path))) {
2959 if (errno != ENOENT)
2960 log_warning("opendir() failed on %s: %s", path, strerror(errno));
2965 while ((de = readdir(d))) {
2968 if (ignore_file(de->d_name))
2971 if (de->d_name[0] != 'S' && de->d_name[0] != 'K')
2974 if (strlen(de->d_name) < 4)
2977 a = undecchar(de->d_name[1]);
2978 b = undecchar(de->d_name[2]);
2985 if (asprintf(&fpath, "%s/%s/%s", *p, rcnd_table[i].path, de->d_name) < 0) {
2990 if (access(fpath, X_OK) < 0) {
2992 if (errno != ENOENT)
2993 log_warning("access() failed on %s: %s", fpath, strerror(errno));
2999 if (!(name = sysv_translate_name(de->d_name + 3))) {
3004 if ((r = manager_load_unit_prepare(m, name, NULL, NULL, &service)) < 0) {
3005 log_warning("Failed to prepare unit %s: %s", name, strerror(-r));
3009 if (de->d_name[0] == 'S') {
3011 if (rcnd_table[i].type == RUNLEVEL_UP || rcnd_table[i].type == RUNLEVEL_SYSINIT) {
3012 SERVICE(service)->sysv_start_priority =
3013 MAX(a*10 + b, SERVICE(service)->sysv_start_priority);
3015 SERVICE(service)->sysv_enabled = true;
3018 if ((r = set_ensure_allocated(&runlevel_services[i], trivial_hash_func, trivial_compare_func)) < 0)
3021 if ((r = set_put(runlevel_services[i], service)) < 0)
3024 } else if (de->d_name[0] == 'K' &&
3025 (rcnd_table[i].type == RUNLEVEL_DOWN ||
3026 rcnd_table[i].type == RUNLEVEL_SYSINIT)) {
3028 if ((r = set_ensure_allocated(&shutdown_services, trivial_hash_func, trivial_compare_func)) < 0)
3031 if ((r = set_put(shutdown_services, service)) < 0)
3037 /* Now we loaded all stubs and are aware of the lowest
3038 start-up priority for all services, not let's actually load
3039 the services, this will also tell us which services are
3040 actually native now */
3041 manager_dispatch_load_queue(m);
3043 /* If this is a native service, rely on native ways to pull in
3044 * a service, don't pull it in via sysv rcN.d links. */
3045 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++)
3046 SET_FOREACH(service, runlevel_services[i], j) {
3047 service = unit_follow_merge(service);
3049 if (service->meta.fragment_path)
3052 if ((r = unit_add_two_dependencies_by_name_inverse(service, UNIT_AFTER, UNIT_WANTS, rcnd_table[i].target, NULL, true)) < 0)
3056 /* We honour K links only for halt/reboot. For the normal
3057 * runlevels we assume the stop jobs will be implicitly added
3058 * by the core logic. Also, we don't really distinguish here
3059 * between the runlevels 0 and 6 and just add them to the
3060 * special shutdown target. On SUSE the boot.d/ runlevel is
3061 * also used for shutdown, so we add links for that too to the
3062 * shutdown target.*/
3063 SET_FOREACH(service, shutdown_services, j) {
3064 service = unit_follow_merge(service);
3066 if (service->meta.fragment_path)
3069 if ((r = unit_add_two_dependencies_by_name(service, UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true)) < 0)
3080 for (i = 0; i < ELEMENTSOF(rcnd_table); i++)
3081 set_free(runlevel_services[i]);
3082 set_free(shutdown_services);
3091 static void service_bus_name_owner_change(
3094 const char *old_owner,
3095 const char *new_owner) {
3097 Service *s = SERVICE(u);
3102 assert(streq(s->bus_name, name));
3103 assert(old_owner || new_owner);
3105 if (old_owner && new_owner)
3106 log_debug("%s's D-Bus name %s changed owner from %s to %s", u->meta.id, name, old_owner, new_owner);
3108 log_debug("%s's D-Bus name %s no longer registered by %s", u->meta.id, name, old_owner);
3110 log_debug("%s's D-Bus name %s now registered by %s", u->meta.id, name, new_owner);
3112 s->bus_name_good = !!new_owner;
3114 if (s->type == SERVICE_DBUS) {
3116 /* service_enter_running() will figure out what to
3118 if (s->state == SERVICE_RUNNING)
3119 service_enter_running(s, true);
3120 else if (s->state == SERVICE_START && new_owner)
3121 service_enter_start_post(s);
3123 } else if (new_owner &&
3125 (s->state == SERVICE_START ||
3126 s->state == SERVICE_START_POST ||
3127 s->state == SERVICE_RUNNING ||
3128 s->state == SERVICE_RELOAD)) {
3130 /* Try to acquire PID from bus service */
3131 log_debug("Trying to acquire PID from D-Bus name...");
3133 bus_query_pid(u->meta.manager, name);
3137 static void service_bus_query_pid_done(
3142 Service *s = SERVICE(u);
3147 log_debug("%s's D-Bus name %s is now owned by process %u", u->meta.id, name, (unsigned) pid);
3149 if (s->main_pid <= 0 &&
3150 (s->state == SERVICE_START ||
3151 s->state == SERVICE_START_POST ||
3152 s->state == SERVICE_RUNNING ||
3153 s->state == SERVICE_RELOAD))
3154 service_set_main_pid(s, pid);
3157 int service_set_socket_fd(Service *s, int fd, Socket *sock) {
3161 /* This is called by the socket code when instantiating a new
3162 * service for a stream socket and the socket needs to be
3165 if (s->meta.load_state != UNIT_LOADED)
3168 if (s->socket_fd >= 0)
3171 if (s->state != SERVICE_DEAD)
3175 s->got_socket_fd = true;
3176 s->accept_socket = sock;
3181 static void service_reset_failed(Unit *u) {
3182 Service *s = SERVICE(u);
3186 if (s->state == SERVICE_FAILED)
3187 service_set_state(s, SERVICE_DEAD);
3192 static int service_kill(Unit *u, KillWho who, KillMode mode, int signo, DBusError *error) {
3193 Service *s = SERVICE(u);
3195 Set *pid_set = NULL;
3199 if (s->main_pid <= 0 && who == KILL_MAIN) {
3200 dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "No main process to kill");
3204 if (s->control_pid <= 0 && who == KILL_CONTROL) {
3205 dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "No control process to kill");
3209 if (s->control_pid > 0)
3210 if (kill(mode == KILL_PROCESS_GROUP ? -s->control_pid : s->control_pid, signo) < 0)
3213 if (s->main_pid > 0)
3214 if (kill(mode == KILL_PROCESS_GROUP ? -s->main_pid : s->main_pid, signo) < 0)
3217 if (mode == KILL_CONTROL_GROUP) {
3220 if (!(pid_set = set_new(trivial_hash_func, trivial_compare_func)))
3223 /* Exclude the control/main pid from being killed via the cgroup */
3224 if (s->control_pid > 0)
3225 if ((q = set_put(pid_set, LONG_TO_PTR(s->control_pid))) < 0) {
3230 if (s->main_pid > 0)
3231 if ((q = set_put(pid_set, LONG_TO_PTR(s->main_pid))) < 0) {
3236 if ((q = cgroup_bonding_kill_list(s->meta.cgroup_bondings, signo, false, pid_set)) < 0)
3237 if (r != -EAGAIN && r != -ESRCH && r != -ENOENT)
3248 static const char* const service_state_table[_SERVICE_STATE_MAX] = {
3249 [SERVICE_DEAD] = "dead",
3250 [SERVICE_START_PRE] = "start-pre",
3251 [SERVICE_START] = "start",
3252 [SERVICE_START_POST] = "start-post",
3253 [SERVICE_RUNNING] = "running",
3254 [SERVICE_EXITED] = "exited",
3255 [SERVICE_RELOAD] = "reload",
3256 [SERVICE_STOP] = "stop",
3257 [SERVICE_STOP_SIGTERM] = "stop-sigterm",
3258 [SERVICE_STOP_SIGKILL] = "stop-sigkill",
3259 [SERVICE_STOP_POST] = "stop-post",
3260 [SERVICE_FINAL_SIGTERM] = "final-sigterm",
3261 [SERVICE_FINAL_SIGKILL] = "final-sigkill",
3262 [SERVICE_FAILED] = "failed",
3263 [SERVICE_AUTO_RESTART] = "auto-restart",
3266 DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
3268 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
3269 [SERVICE_RESTART_NO] = "no",
3270 [SERVICE_RESTART_ON_SUCCESS] = "on-success",
3271 [SERVICE_RESTART_ON_FAILURE] = "on-failure",
3272 [SERVICE_RESTART_ON_ABORT] = "on-abort",
3273 [SERVICE_RESTART_ALWAYS] = "always"
3276 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
3278 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
3279 [SERVICE_SIMPLE] = "simple",
3280 [SERVICE_FORKING] = "forking",
3281 [SERVICE_ONESHOT] = "oneshot",
3282 [SERVICE_DBUS] = "dbus",
3283 [SERVICE_NOTIFY] = "notify"
3286 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
3288 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
3289 [SERVICE_EXEC_START_PRE] = "ExecStartPre",
3290 [SERVICE_EXEC_START] = "ExecStart",
3291 [SERVICE_EXEC_START_POST] = "ExecStartPost",
3292 [SERVICE_EXEC_RELOAD] = "ExecReload",
3293 [SERVICE_EXEC_STOP] = "ExecStop",
3294 [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
3297 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
3299 static const char* const notify_access_table[_NOTIFY_ACCESS_MAX] = {
3300 [NOTIFY_NONE] = "none",
3301 [NOTIFY_MAIN] = "main",
3302 [NOTIFY_ALL] = "all"
3305 DEFINE_STRING_TABLE_LOOKUP(notify_access, NotifyAccess);
3307 const UnitVTable service_vtable = {
3308 .suffix = ".service",
3309 .show_status = true,
3311 .init = service_init,
3312 .done = service_done,
3313 .load = service_load,
3315 .coldplug = service_coldplug,
3317 .dump = service_dump,
3319 .start = service_start,
3320 .stop = service_stop,
3321 .reload = service_reload,
3323 .can_reload = service_can_reload,
3325 .kill = service_kill,
3327 .serialize = service_serialize,
3328 .deserialize_item = service_deserialize_item,
3330 .active_state = service_active_state,
3331 .sub_state_to_string = service_sub_state_to_string,
3333 .check_gc = service_check_gc,
3334 .check_snapshot = service_check_snapshot,
3336 .sigchld_event = service_sigchld_event,
3337 .timer_event = service_timer_event,
3339 .reset_failed = service_reset_failed,
3341 .cgroup_notify_empty = service_cgroup_notify_event,
3342 .notify_message = service_notify_message,
3344 .bus_name_owner_change = service_bus_name_owner_change,
3345 .bus_query_pid_done = service_bus_query_pid_done,
3347 .bus_interface = "org.freedesktop.systemd1.Service",
3348 .bus_message_handler = bus_service_message_handler,
3349 .bus_invalidating_properties = bus_service_invalidating_properties,
3351 #ifdef HAVE_SYSV_COMPAT
3352 .enumerate = service_enumerate