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"
38 #define COMMENTS "#;\n"
39 #define NEWLINES "\n\r"
41 #ifdef HAVE_SYSV_COMPAT
43 #define DEFAULT_SYSV_TIMEOUT_USEC (3*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;
121 exec_context_init(&s->exec_context);
123 RATELIMIT_INIT(s->ratelimit, 10*USEC_PER_SEC, 5);
125 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
128 static void service_unwatch_control_pid(Service *s) {
131 if (s->control_pid <= 0)
134 unit_unwatch_pid(UNIT(s), s->control_pid);
138 static void service_unwatch_main_pid(Service *s) {
141 if (s->main_pid <= 0)
144 unit_unwatch_pid(UNIT(s), s->main_pid);
148 static int service_set_main_pid(Service *s, pid_t pid) {
159 if (get_parent_of_pid(pid, &ppid) >= 0 && ppid != getpid())
160 log_warning("%s: Supervising process %lu which is not our child. We'll most likely not notice when it exits.",
161 s->meta.id, (unsigned long) pid);
164 s->main_pid_known = true;
166 exec_status_start(&s->main_exec_status, pid);
171 static void service_close_socket_fd(Service *s) {
174 if (s->socket_fd < 0)
177 close_nointr_nofail(s->socket_fd);
181 static void service_connection_unref(Service *s) {
184 if (!s->accept_socket)
187 socket_connection_unref(s->accept_socket);
188 s->accept_socket = NULL;
191 static void service_done(Unit *u) {
192 Service *s = SERVICE(u);
199 #ifdef HAVE_SYSV_COMPAT
203 free(s->sysv_runlevels);
204 s->sysv_runlevels = NULL;
207 free(s->status_text);
208 s->status_text = NULL;
210 exec_context_done(&s->exec_context);
211 exec_command_free_array(s->exec_command, _SERVICE_EXEC_COMMAND_MAX);
212 s->control_command = NULL;
214 /* This will leak a process, but at least no memory or any of
216 service_unwatch_main_pid(s);
217 service_unwatch_control_pid(s);
220 unit_unwatch_bus_name(UNIT(u), s->bus_name);
225 service_close_socket_fd(s);
226 service_connection_unref(s);
228 set_free(s->configured_sockets);
230 unit_unwatch_timer(u, &s->timer_watch);
233 #ifdef HAVE_SYSV_COMPAT
234 static char *sysv_translate_name(const char *name) {
237 if (!(r = new(char, strlen(name) + sizeof(".service"))))
240 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU)
241 if (endswith(name, ".sh"))
242 /* Drop Debian-style .sh suffix */
243 strcpy(stpcpy(r, name) - 3, ".service");
246 if (startswith(name, "boot."))
247 /* Drop SuSE-style boot. prefix */
248 strcpy(stpcpy(r, name + 5), ".service");
251 if (startswith(name, "@"))
252 /* Drop Arch-style background prefix */
253 strcpy(stpcpy(r, name + 1), ".service");
255 #ifdef TARGET_FRUGALWARE
256 if (startswith(name, "rc."))
257 /* Drop Frugalware-style rc. prefix */
258 strcpy(stpcpy(r, name + 3), ".service");
261 /* Normal init scripts */
262 strcpy(stpcpy(r, name), ".service");
267 static int sysv_translate_facility(const char *name, const char *filename, char **_r) {
269 /* We silently ignore the $ prefix here. According to the LSB
270 * spec it simply indicates whether something is a
271 * standardized name or a distribution-specific one. Since we
272 * just follow what already exists and do not introduce new
273 * uses or names we don't care who introduced a new name. */
275 static const char * const table[] = {
276 /* LSB defined facilities */
277 "local_fs", SPECIAL_LOCAL_FS_TARGET,
278 "network", SPECIAL_NETWORK_TARGET,
279 "named", SPECIAL_NSS_LOOKUP_TARGET,
280 "portmap", SPECIAL_RPCBIND_TARGET,
281 "remote_fs", SPECIAL_REMOTE_FS_TARGET,
282 "syslog", SPECIAL_SYSLOG_TARGET,
283 "time", SPECIAL_RTC_SET_TARGET,
285 /* common extensions */
286 "mail-transfer-agent", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
287 "x-display-manager", SPECIAL_DISPLAY_MANAGER_SERVICE,
290 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU)
291 "mail-transport-agent", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
295 "MTA", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
296 "smtpdaemon", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
297 "httpd", SPECIAL_HTTP_DAEMON_TARGET,
301 "smtp", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
312 n = *name == '$' ? name + 1 : name;
314 for (i = 0; i < ELEMENTSOF(table); i += 2) {
316 if (!streq(table[i], n))
322 if (!(r = strdup(table[i+1])))
328 /* If we don't know this name, fallback heuristics to figure
329 * out whether something is a target or a service alias. */
332 /* Facilities starting with $ are most likely targets */
333 r = unit_name_build(n, NULL, ".target");
334 else if (filename && streq(name, filename))
335 /* Names equalling the file name of the services are redundant */
338 /* Everything else we assume to be normal service names */
339 r = sysv_translate_name(n);
352 static int sysv_fix_order(Service *s) {
358 if (s->sysv_start_priority < 0)
361 /* For each pair of services where at least one lacks a LSB
362 * header, we use the start priority value to order things. */
364 LIST_FOREACH(units_per_type, other, s->meta.manager->units_per_type[UNIT_SERVICE]) {
367 bool special_s, special_t;
369 t = (Service*) other;
374 if (t->meta.load_state != UNIT_LOADED)
377 if (t->sysv_start_priority < 0)
380 /* If both units have modern headers we don't care
381 * about the priorities */
382 if ((s->meta.fragment_path || s->sysv_has_lsb) &&
383 (t->meta.fragment_path || t->sysv_has_lsb))
386 special_s = s->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, s->sysv_runlevels);
387 special_t = t->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, t->sysv_runlevels);
389 if (special_t && !special_s)
391 else if (special_s && !special_t)
393 else if (t->sysv_start_priority < s->sysv_start_priority)
395 else if (t->sysv_start_priority > s->sysv_start_priority)
400 /* FIXME: Maybe we should compare the name here lexicographically? */
402 if (!(r = unit_add_dependency(UNIT(s), d, UNIT(t), true)) < 0)
409 static ExecCommand *exec_command_new(const char *path, const char *arg1) {
412 if (!(c = new0(ExecCommand, 1)))
415 if (!(c->path = strdup(path))) {
420 if (!(c->argv = strv_new(path, arg1, NULL))) {
429 static int sysv_exec_commands(Service *s) {
433 assert(s->sysv_path);
435 if (!(c = exec_command_new(s->sysv_path, "start")))
437 exec_command_append_list(s->exec_command+SERVICE_EXEC_START, c);
439 if (!(c = exec_command_new(s->sysv_path, "stop")))
441 exec_command_append_list(s->exec_command+SERVICE_EXEC_STOP, c);
443 if (!(c = exec_command_new(s->sysv_path, "reload")))
445 exec_command_append_list(s->exec_command+SERVICE_EXEC_RELOAD, c);
450 static int service_load_sysv_path(Service *s, const char *path) {
461 char *short_description = NULL, *long_description = NULL, *chkconfig_description = NULL, *description;
468 if (!(f = fopen(path, "re"))) {
469 r = errno == ENOENT ? 0 : -errno;
474 if (!(s->sysv_path = strdup(path))) {
480 char l[LINE_MAX], *t;
482 if (!fgets(l, sizeof(l), f)) {
487 log_error("Failed to read configuration file '%s': %s", path, strerror(-r));
497 if (state == NORMAL && streq(t, "### BEGIN INIT INFO")) {
499 s->sysv_has_lsb = true;
503 if ((state == LSB_DESCRIPTION || state == LSB) && streq(t, "### END INIT INFO")) {
509 t += strspn(t, WHITESPACE);
511 if (state == NORMAL) {
513 /* Try to parse Red Hat style chkconfig headers */
515 if (startswith_no_case(t, "chkconfig:")) {
517 char runlevels[16], *k;
521 if (sscanf(t+10, "%15s %i %*i",
523 &start_priority) != 2) {
525 log_warning("[%s:%u] Failed to parse chkconfig line. Ignoring.", path, line);
529 /* A start priority gathered from the
530 * symlink farms is preferred over the
531 * data from the LSB header. */
532 if (start_priority < 0 || start_priority > 99)
533 log_warning("[%s:%u] Start priority out of range. Ignoring.", path, line);
534 else if (s->sysv_start_priority < 0)
535 s->sysv_start_priority = start_priority;
537 char_array_0(runlevels);
538 k = delete_chars(runlevels, WHITESPACE "-");
543 if (!(d = strdup(k))) {
548 free(s->sysv_runlevels);
549 s->sysv_runlevels = d;
552 } else if (startswith_no_case(t, "description:")) {
554 size_t k = strlen(t);
558 if (t[k-1] == '\\') {
563 if ((j = strstrip(t+12)) && *j) {
564 if (!(d = strdup(j))) {
571 free(chkconfig_description);
572 chkconfig_description = d;
574 } else if (startswith_no_case(t, "pidfile:")) {
581 if (!path_is_absolute(fn)) {
582 log_warning("[%s:%u] PID file not absolute. Ignoring.", path, line);
586 if (!(fn = strdup(fn))) {
595 } else if (state == DESCRIPTION) {
597 /* Try to parse Red Hat style description
600 size_t k = strlen(t);
608 if ((j = strstrip(t)) && *j) {
611 if (chkconfig_description)
612 asprintf(&d, "%s %s", chkconfig_description, j);
621 free(chkconfig_description);
622 chkconfig_description = d;
625 } else if (state == LSB || state == LSB_DESCRIPTION) {
627 if (startswith_no_case(t, "Provides:")) {
633 FOREACH_WORD_QUOTED(w, z, t+9, i) {
636 if (!(n = strndup(w, z))) {
641 r = sysv_translate_facility(n, file_name_from_path(path), &m);
650 if (unit_name_to_type(m) == UNIT_SERVICE)
651 r = unit_add_name(u, m);
653 r = unit_add_dependency_by_name(u, UNIT_BEFORE, m, NULL, true);
655 if (s->sysv_enabled) {
658 if ((k = unit_add_dependency_by_name_inverse(u, UNIT_WANTS, m, NULL, true)) < 0)
664 log_error("[%s:%u] Failed to add LSB Provides name %s, ignoring: %s", path, line, m, strerror(-r));
669 } else if (startswith_no_case(t, "Required-Start:") ||
670 startswith_no_case(t, "Should-Start:") ||
671 startswith_no_case(t, "X-Start-Before:") ||
672 startswith_no_case(t, "X-Start-After:")) {
678 FOREACH_WORD_QUOTED(w, z, strchr(t, ':')+1, i) {
681 if (!(n = strndup(w, z))) {
686 r = sysv_translate_facility(n, file_name_from_path(path), &m);
695 r = unit_add_dependency_by_name(u, startswith_no_case(t, "X-Start-Before:") ? UNIT_BEFORE : UNIT_AFTER, m, NULL, true);
698 log_error("[%s:%u] Failed to add dependency on %s, ignoring: %s", path, line, m, strerror(-r));
702 } else if (startswith_no_case(t, "Default-Start:")) {
707 k = delete_chars(t+14, WHITESPACE "-");
710 if (!(d = strdup(k))) {
715 free(s->sysv_runlevels);
716 s->sysv_runlevels = d;
719 } else if (startswith_no_case(t, "Description:")) {
722 state = LSB_DESCRIPTION;
724 if ((j = strstrip(t+12)) && *j) {
725 if (!(d = strdup(j))) {
732 free(long_description);
733 long_description = d;
735 } else if (startswith_no_case(t, "Short-Description:")) {
740 if ((j = strstrip(t+18)) && *j) {
741 if (!(d = strdup(j))) {
748 free(short_description);
749 short_description = d;
751 } else if (startswith_no_case(t, "X-Interactive:")) {
754 if ((b = parse_boolean(strstrip(t+14))) < 0) {
755 log_warning("[%s:%u] Couldn't parse interactive flag. Ignoring.", path, line);
760 s->exec_context.std_input = EXEC_INPUT_TTY;
762 s->exec_context.std_input = EXEC_INPUT_NULL;
764 } else if (state == LSB_DESCRIPTION) {
766 if (startswith(l, "#\t") || startswith(l, "# ")) {
769 if ((j = strstrip(t)) && *j) {
772 if (long_description)
773 asprintf(&d, "%s %s", long_description, t);
782 free(long_description);
783 long_description = d;
792 if ((r = sysv_exec_commands(s)) < 0)
795 if (s->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, s->sysv_runlevels)) {
796 /* If there a runlevels configured for this service
797 * but none of the standard ones, then we assume this
798 * is some special kind of service (which might be
799 * needed for early boot) and don't create any links
802 s->meta.default_dependencies = false;
804 /* Don't timeout special services during boot (like fsck) */
807 s->timeout_usec = DEFAULT_SYSV_TIMEOUT_USEC;
809 /* Special setting for all SysV services */
810 s->type = SERVICE_FORKING;
811 s->remain_after_exit = true;
812 s->restart = SERVICE_RESTART_NO;
813 s->exec_context.std_output =
814 (s->meta.manager->sysv_console || s->exec_context.std_input == EXEC_INPUT_TTY)
815 ? EXEC_OUTPUT_TTY : EXEC_OUTPUT_NULL;
816 s->exec_context.kill_mode = KILL_PROCESS_GROUP;
818 /* We use the long description only if
819 * no short description is set. */
821 if (short_description)
822 description = short_description;
823 else if (chkconfig_description)
824 description = chkconfig_description;
825 else if (long_description)
826 description = long_description;
833 if (!(d = strappend("LSB: ", description))) {
838 u->meta.description = d;
841 u->meta.load_state = UNIT_LOADED;
849 free(short_description);
850 free(long_description);
851 free(chkconfig_description);
856 static int service_load_sysv_name(Service *s, const char *name) {
862 /* For SysV services we strip the boot.*, rc.* and *.sh
863 * prefixes/suffixes. */
864 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU)
865 if (endswith(name, ".sh.service"))
870 if (startswith(name, "boot."))
874 #ifdef TARGET_FRUGALWARE
875 if (startswith(name, "rc."))
879 STRV_FOREACH(p, s->meta.manager->lookup_paths.sysvinit_path) {
883 if (asprintf(&path, "%s/%s", *p, name) < 0)
886 assert(endswith(path, ".service"));
887 path[strlen(path)-8] = 0;
889 r = service_load_sysv_path(s, path);
891 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU)
892 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
893 /* Try Debian style *.sh source'able init scripts */
895 r = service_load_sysv_path(s, path);
901 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
902 /* Try SUSE style boot.* init scripts */
904 if (asprintf(&path, "%s/boot.%s", *p, name) < 0)
907 /* Drop .service suffix */
908 path[strlen(path)-8] = 0;
909 r = service_load_sysv_path(s, path);
914 #ifdef TARGET_FRUGALWARE
915 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
916 /* Try Frugalware style rc.* init scripts */
918 if (asprintf(&path, "%s/rc.%s", *p, name) < 0)
921 /* Drop .service suffix */
922 path[strlen(path)-8] = 0;
923 r = service_load_sysv_path(s, path);
931 if ((s->meta.load_state != UNIT_STUB))
938 static int service_load_sysv(Service *s) {
945 /* Load service data from SysV init scripts, preferably with
948 if (strv_isempty(s->meta.manager->lookup_paths.sysvinit_path))
951 if ((t = s->meta.id))
952 if ((r = service_load_sysv_name(s, t)) < 0)
955 if (s->meta.load_state == UNIT_STUB)
956 SET_FOREACH(t, s->meta.names, i) {
960 if ((r = service_load_sysv_name(s, t)) < 0)
963 if (s->meta.load_state != UNIT_STUB)
971 static int fsck_fix_order(Service *s) {
977 if (s->fsck_passno <= 0)
980 /* For each pair of services where both have an fsck priority
981 * we order things based on it. */
983 LIST_FOREACH(units_per_type, other, s->meta.manager->units_per_type[UNIT_SERVICE]) {
987 t = (Service*) other;
992 if (t->meta.load_state != UNIT_LOADED)
995 if (t->fsck_passno <= 0)
998 if (t->fsck_passno < s->fsck_passno)
1000 else if (t->fsck_passno > s->fsck_passno)
1005 if (!(r = unit_add_dependency(UNIT(s), d, UNIT(t), true)) < 0)
1012 static int service_verify(Service *s) {
1015 if (s->meta.load_state != UNIT_LOADED)
1018 if (!s->exec_command[SERVICE_EXEC_START]) {
1019 log_error("%s lacks ExecStart setting. Refusing.", s->meta.id);
1023 if (s->type != SERVICE_ONESHOT &&
1024 s->exec_command[SERVICE_EXEC_START]->command_next) {
1025 log_error("%s has more than one ExecStart setting, which is only allowed for Type=oneshot services. Refusing.", s->meta.id);
1029 if (s->type == SERVICE_DBUS && !s->bus_name) {
1030 log_error("%s is of type D-Bus but no D-Bus service name has been specified. Refusing.", s->meta.id);
1034 if (s->exec_context.pam_name && s->exec_context.kill_mode != KILL_CONTROL_GROUP) {
1035 log_error("%s has PAM enabled. Kill mode must be set to 'control-group'. Refusing.", s->meta.id);
1042 static int service_add_default_dependencies(Service *s) {
1047 /* Add a number of automatic dependencies useful for the
1048 * majority of services. */
1050 /* First, pull in base system */
1051 if (s->meta.manager->running_as == MANAGER_SYSTEM) {
1053 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_BASIC_TARGET, NULL, true)) < 0)
1056 } else if (s->meta.manager->running_as == MANAGER_USER) {
1058 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SOCKETS_TARGET, NULL, true)) < 0)
1062 /* Second, activate normal shutdown */
1063 return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true);
1066 static int service_load(Unit *u) {
1068 Service *s = SERVICE(u);
1072 /* Load a .service file */
1073 if ((r = unit_load_fragment(u)) < 0)
1076 #ifdef HAVE_SYSV_COMPAT
1077 /* Load a classic init script as a fallback, if we couldn't find anything */
1078 if (u->meta.load_state == UNIT_STUB)
1079 if ((r = service_load_sysv(s)) < 0)
1083 /* Still nothing found? Then let's give up */
1084 if (u->meta.load_state == UNIT_STUB)
1087 /* We were able to load something, then let's add in the
1088 * dropin directories. */
1089 if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
1092 /* This is a new unit? Then let's add in some extras */
1093 if (u->meta.load_state == UNIT_LOADED) {
1094 if ((r = unit_add_exec_dependencies(u, &s->exec_context)) < 0)
1097 if ((r = unit_add_default_cgroups(u)) < 0)
1100 #ifdef HAVE_SYSV_COMPAT
1101 if ((r = sysv_fix_order(s)) < 0)
1105 if ((r = fsck_fix_order(s)) < 0)
1109 if ((r = unit_watch_bus_name(u, s->bus_name)) < 0)
1112 if (s->type == SERVICE_NOTIFY && s->notify_access == NOTIFY_NONE)
1113 s->notify_access = NOTIFY_MAIN;
1115 if (s->type == SERVICE_DBUS || s->bus_name)
1116 if ((r = unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_REQUIRES, SPECIAL_DBUS_TARGET, NULL, true)) < 0)
1119 if (s->meta.default_dependencies)
1120 if ((r = service_add_default_dependencies(s)) < 0)
1124 return service_verify(s);
1127 static void service_dump(Unit *u, FILE *f, const char *prefix) {
1129 ServiceExecCommand c;
1130 Service *s = SERVICE(u);
1131 const char *prefix2;
1136 p2 = strappend(prefix, "\t");
1137 prefix2 = p2 ? p2 : prefix;
1140 "%sService State: %s\n"
1141 "%sPermissionsStartOnly: %s\n"
1142 "%sRootDirectoryStartOnly: %s\n"
1143 "%sRemainAfterExit: %s\n"
1146 "%sNotifyAccess: %s\n",
1147 prefix, service_state_to_string(s->state),
1148 prefix, yes_no(s->permissions_start_only),
1149 prefix, yes_no(s->root_directory_start_only),
1150 prefix, yes_no(s->remain_after_exit),
1151 prefix, service_type_to_string(s->type),
1152 prefix, service_restart_to_string(s->restart),
1153 prefix, notify_access_to_string(s->notify_access));
1155 if (s->control_pid > 0)
1157 "%sControl PID: %lu\n",
1158 prefix, (unsigned long) s->control_pid);
1160 if (s->main_pid > 0)
1162 "%sMain PID: %lu\n",
1163 prefix, (unsigned long) s->main_pid);
1168 prefix, s->pid_file);
1173 "%sBus Name Good: %s\n",
1174 prefix, s->bus_name,
1175 prefix, yes_no(s->bus_name_good));
1177 exec_context_dump(&s->exec_context, f, prefix);
1179 for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
1181 if (!s->exec_command[c])
1184 fprintf(f, "%s-> %s:\n",
1185 prefix, service_exec_command_to_string(c));
1187 exec_command_dump_list(s->exec_command[c], f, prefix2);
1190 #ifdef HAVE_SYSV_COMPAT
1193 "%sSysV Init Script Path: %s\n"
1194 "%sSysV Init Script has LSB Header: %s\n"
1195 "%sSysVEnabled: %s\n",
1196 prefix, s->sysv_path,
1197 prefix, yes_no(s->sysv_has_lsb),
1198 prefix, yes_no(s->sysv_enabled));
1200 if (s->sysv_start_priority >= 0)
1202 "%sSysVStartPriority: %i\n",
1203 prefix, s->sysv_start_priority);
1205 if (s->sysv_runlevels)
1206 fprintf(f, "%sSysVRunLevels: %s\n",
1207 prefix, s->sysv_runlevels);
1210 if (s->fsck_passno > 0)
1212 "%sFsckPassNo: %i\n",
1213 prefix, s->fsck_passno);
1216 fprintf(f, "%sStatus Text: %s\n",
1217 prefix, s->status_text);
1222 static int service_load_pid_file(Service *s) {
1229 if (s->main_pid_known)
1232 assert(s->main_pid <= 0);
1237 if ((r = read_one_line_file(s->pid_file, &k)) < 0)
1240 r = parse_pid(k, &pid);
1246 if (kill(pid, 0) < 0 && errno != EPERM) {
1247 log_warning("PID %lu read from file %s does not exist. Your service or init script might be broken.",
1248 (unsigned long) pid, s->pid_file);
1252 if ((r = service_set_main_pid(s, pid)) < 0)
1255 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1256 /* FIXME: we need to do something here */
1262 static int service_search_main_pid(Service *s) {
1268 if (s->main_pid_known)
1271 assert(s->main_pid <= 0);
1273 if ((pid = cgroup_bonding_search_main_pid_list(s->meta.cgroup_bondings)) <= 0)
1276 if ((r = service_set_main_pid(s, pid)) < 0)
1279 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1280 /* FIXME: we need to do something here */
1286 static int service_get_sockets(Service *s, Set **_set) {
1295 if (s->socket_fd >= 0)
1298 if (!set_isempty(s->configured_sockets))
1301 /* Collects all Socket objects that belong to this
1302 * service. Note that a service might have multiple sockets
1303 * via multiple names. */
1305 if (!(set = set_new(NULL, NULL)))
1308 SET_FOREACH(t, s->meta.names, i) {
1312 /* Look for all socket objects that go by any of our
1313 * units and collect their fds */
1315 if (!(k = unit_name_change_suffix(t, ".socket"))) {
1320 p = manager_get_unit(s->meta.manager, k);
1326 if ((r = set_put(set, p)) < 0)
1338 static int service_notify_sockets_dead(Service *s) {
1340 Set *set, *free_set = NULL;
1346 /* Notifies all our sockets when we die */
1348 if (s->socket_fd >= 0)
1351 if (!set_isempty(s->configured_sockets))
1352 set = s->configured_sockets;
1354 if ((r = service_get_sockets(s, &free_set)) < 0)
1360 SET_FOREACH(sock, set, i)
1361 socket_notify_service_dead(sock);
1368 static void service_set_state(Service *s, ServiceState state) {
1369 ServiceState old_state;
1372 old_state = s->state;
1375 if (state != SERVICE_START_PRE &&
1376 state != SERVICE_START &&
1377 state != SERVICE_START_POST &&
1378 state != SERVICE_RELOAD &&
1379 state != SERVICE_STOP &&
1380 state != SERVICE_STOP_SIGTERM &&
1381 state != SERVICE_STOP_SIGKILL &&
1382 state != SERVICE_STOP_POST &&
1383 state != SERVICE_FINAL_SIGTERM &&
1384 state != SERVICE_FINAL_SIGKILL &&
1385 state != SERVICE_AUTO_RESTART)
1386 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1388 if (state != SERVICE_START &&
1389 state != SERVICE_START_POST &&
1390 state != SERVICE_RUNNING &&
1391 state != SERVICE_RELOAD &&
1392 state != SERVICE_STOP &&
1393 state != SERVICE_STOP_SIGTERM &&
1394 state != SERVICE_STOP_SIGKILL)
1395 service_unwatch_main_pid(s);
1397 if (state != SERVICE_START_PRE &&
1398 state != SERVICE_START &&
1399 state != SERVICE_START_POST &&
1400 state != SERVICE_RELOAD &&
1401 state != SERVICE_STOP &&
1402 state != SERVICE_STOP_SIGTERM &&
1403 state != SERVICE_STOP_SIGKILL &&
1404 state != SERVICE_STOP_POST &&
1405 state != SERVICE_FINAL_SIGTERM &&
1406 state != SERVICE_FINAL_SIGKILL) {
1407 service_unwatch_control_pid(s);
1408 s->control_command = NULL;
1409 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1412 if (state == SERVICE_DEAD ||
1413 state == SERVICE_STOP ||
1414 state == SERVICE_STOP_SIGTERM ||
1415 state == SERVICE_STOP_SIGKILL ||
1416 state == SERVICE_STOP_POST ||
1417 state == SERVICE_FINAL_SIGTERM ||
1418 state == SERVICE_FINAL_SIGKILL ||
1419 state == SERVICE_FAILED ||
1420 state == SERVICE_AUTO_RESTART)
1421 service_notify_sockets_dead(s);
1423 if (state != SERVICE_START_PRE &&
1424 state != SERVICE_START &&
1425 state != SERVICE_START_POST &&
1426 state != SERVICE_RUNNING &&
1427 state != SERVICE_RELOAD &&
1428 state != SERVICE_STOP &&
1429 state != SERVICE_STOP_SIGTERM &&
1430 state != SERVICE_STOP_SIGKILL &&
1431 state != SERVICE_STOP_POST &&
1432 state != SERVICE_FINAL_SIGTERM &&
1433 state != SERVICE_FINAL_SIGKILL &&
1434 !(state == SERVICE_DEAD && s->meta.job)) {
1435 service_close_socket_fd(s);
1436 service_connection_unref(s);
1439 /* For the inactive states unit_notify() will trim the cgroup,
1440 * but for exit we have to do that ourselves... */
1441 if (state == SERVICE_EXITED)
1442 cgroup_bonding_trim_list(s->meta.cgroup_bondings, true);
1444 if (old_state != state)
1445 log_debug("%s changed %s -> %s", s->meta.id, service_state_to_string(old_state), service_state_to_string(state));
1447 unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state]);
1450 static int service_coldplug(Unit *u) {
1451 Service *s = SERVICE(u);
1455 assert(s->state == SERVICE_DEAD);
1457 if (s->deserialized_state != s->state) {
1459 if (s->deserialized_state == SERVICE_START_PRE ||
1460 s->deserialized_state == SERVICE_START ||
1461 s->deserialized_state == SERVICE_START_POST ||
1462 s->deserialized_state == SERVICE_RELOAD ||
1463 s->deserialized_state == SERVICE_STOP ||
1464 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1465 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1466 s->deserialized_state == SERVICE_STOP_POST ||
1467 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1468 s->deserialized_state == SERVICE_FINAL_SIGKILL ||
1469 s->deserialized_state == SERVICE_AUTO_RESTART) {
1471 if (s->deserialized_state == SERVICE_AUTO_RESTART || s->timeout_usec > 0) {
1474 k = s->deserialized_state == SERVICE_AUTO_RESTART ? s->restart_usec : s->timeout_usec;
1476 if ((r = unit_watch_timer(UNIT(s), k, &s->timer_watch)) < 0)
1481 if ((s->deserialized_state == SERVICE_START &&
1482 (s->type == SERVICE_FORKING ||
1483 s->type == SERVICE_DBUS ||
1484 s->type == SERVICE_ONESHOT ||
1485 s->type == SERVICE_NOTIFY)) ||
1486 s->deserialized_state == SERVICE_START_POST ||
1487 s->deserialized_state == SERVICE_RUNNING ||
1488 s->deserialized_state == SERVICE_RELOAD ||
1489 s->deserialized_state == SERVICE_STOP ||
1490 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1491 s->deserialized_state == SERVICE_STOP_SIGKILL)
1492 if (s->main_pid > 0)
1493 if ((r = unit_watch_pid(UNIT(s), s->main_pid)) < 0)
1496 if (s->deserialized_state == SERVICE_START_PRE ||
1497 s->deserialized_state == SERVICE_START ||
1498 s->deserialized_state == SERVICE_START_POST ||
1499 s->deserialized_state == SERVICE_RELOAD ||
1500 s->deserialized_state == SERVICE_STOP ||
1501 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1502 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1503 s->deserialized_state == SERVICE_STOP_POST ||
1504 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1505 s->deserialized_state == SERVICE_FINAL_SIGKILL)
1506 if (s->control_pid > 0)
1507 if ((r = unit_watch_pid(UNIT(s), s->control_pid)) < 0)
1510 service_set_state(s, s->deserialized_state);
1516 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
1520 unsigned rn_fds = 0;
1521 Set *set, *free_set = NULL;
1528 if (s->socket_fd >= 0)
1531 if (!set_isempty(s->configured_sockets))
1532 set = s->configured_sockets;
1534 if ((r = service_get_sockets(s, &free_set)) < 0)
1540 SET_FOREACH(sock, set, i) {
1544 if ((r = socket_collect_fds(sock, &cfds, &cn_fds)) < 0)
1556 if (!(t = new(int, rn_fds+cn_fds))) {
1562 memcpy(t, rfds, rn_fds);
1563 memcpy(t+rn_fds, cfds, cn_fds);
1568 rn_fds = rn_fds+cn_fds;
1586 static int service_spawn(
1591 bool apply_permissions,
1593 bool apply_tty_stdin,
1594 bool set_notify_socket,
1599 int *fds = NULL, *fdsbuf = NULL;
1600 unsigned n_fds = 0, n_env = 0;
1601 char **argv = NULL, **final_env = NULL, **our_env = NULL;
1608 s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1609 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1610 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
1612 if (s->socket_fd >= 0) {
1613 fds = &s->socket_fd;
1616 if ((r = service_collect_fds(s, &fdsbuf, &n_fds)) < 0)
1623 if (timeout && s->timeout_usec) {
1624 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1627 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1629 if (!(argv = unit_full_printf_strv(UNIT(s), c->argv))) {
1634 if (!(our_env = new0(char*, 4))) {
1639 if (set_notify_socket)
1640 if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=@%s", s->meta.manager->notify_socket) < 0) {
1645 if (s->main_pid > 0)
1646 if (asprintf(our_env + n_env++, "MAINPID=%lu", (unsigned long) s->main_pid) < 0) {
1651 if (!(final_env = strv_env_merge(2,
1652 s->meta.manager->environment,
1667 s->meta.manager->confirm_spawn,
1668 s->meta.cgroup_bondings,
1675 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1676 /* FIXME: we need to do something here */
1682 strv_free(final_env);
1692 strv_free(final_env);
1695 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1700 static int main_pid_good(Service *s) {
1703 /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1706 /* If we know the pid file, then lets just check if it is
1708 if (s->main_pid_known)
1709 return s->main_pid > 0;
1711 /* We don't know the pid */
1715 static int control_pid_good(Service *s) {
1718 return s->control_pid > 0;
1721 static int cgroup_good(Service *s) {
1726 if ((r = cgroup_bonding_is_empty_list(s->meta.cgroup_bondings)) < 0)
1732 static void service_enter_dead(Service *s, bool success, bool allow_restart) {
1739 if (allow_restart &&
1740 !s->forbid_restart &&
1741 (s->restart == SERVICE_RESTART_ALWAYS ||
1742 (s->restart == SERVICE_RESTART_ON_SUCCESS && !s->failure) ||
1743 (s->restart == SERVICE_RESTART_ON_FAILURE && s->failure) ||
1744 (s->restart == SERVICE_RESTART_ON_ABORT && s->failure &&
1745 (s->main_exec_status.code == CLD_KILLED ||
1746 s->main_exec_status.code == CLD_DUMPED)))) {
1748 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
1751 service_set_state(s, SERVICE_AUTO_RESTART);
1753 service_set_state(s, s->failure ? SERVICE_FAILED : SERVICE_DEAD);
1755 s->forbid_restart = false;
1760 log_warning("%s failed to run install restart timer: %s", s->meta.id, strerror(-r));
1761 service_enter_dead(s, false, false);
1764 static void service_enter_signal(Service *s, ServiceState state, bool success);
1766 static void service_enter_stop_post(Service *s, bool success) {
1773 service_unwatch_control_pid(s);
1775 s->control_command_id = SERVICE_EXEC_STOP_POST;
1776 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST])) {
1777 if ((r = service_spawn(s,
1781 !s->permissions_start_only,
1782 !s->root_directory_start_only,
1785 &s->control_pid)) < 0)
1789 service_set_state(s, SERVICE_STOP_POST);
1791 service_enter_signal(s, SERVICE_FINAL_SIGTERM, true);
1796 log_warning("%s failed to run 'stop-post' task: %s", s->meta.id, strerror(-r));
1797 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1800 static void service_enter_signal(Service *s, ServiceState state, bool success) {
1802 Set *pid_set = NULL;
1803 bool wait_for_exit = false;
1810 if (s->exec_context.kill_mode != KILL_NONE) {
1811 int sig = (state == SERVICE_STOP_SIGTERM || state == SERVICE_FINAL_SIGTERM) ? s->exec_context.kill_signal : SIGKILL;
1813 if (s->main_pid > 0) {
1814 if (kill(s->exec_context.kill_mode == KILL_PROCESS_GROUP ?
1816 s->main_pid, sig) < 0 && errno != ESRCH)
1818 log_warning("Failed to kill main process %li: %m", (long) s->main_pid);
1820 wait_for_exit = true;
1823 if (s->control_pid > 0) {
1824 if (kill(s->exec_context.kill_mode == KILL_PROCESS_GROUP ?
1826 s->control_pid, sig) < 0 && errno != ESRCH)
1828 log_warning("Failed to kill control process %li: %m", (long) s->control_pid);
1830 wait_for_exit = true;
1833 if (s->exec_context.kill_mode == KILL_CONTROL_GROUP) {
1835 if (!(pid_set = set_new(trivial_hash_func, trivial_compare_func))) {
1840 /* Exclude the main/control pids from being killed via the cgroup */
1841 if (s->main_pid > 0)
1842 if ((r = set_put(pid_set, LONG_TO_PTR(s->main_pid))) < 0)
1845 if (s->control_pid > 0)
1846 if ((r = set_put(pid_set, LONG_TO_PTR(s->control_pid))) < 0)
1849 if ((r = cgroup_bonding_kill_list(s->meta.cgroup_bondings, sig, pid_set)) < 0) {
1850 if (r != -EAGAIN && r != -ESRCH && r != -ENOENT)
1851 log_warning("Failed to kill control group: %s", strerror(-r));
1853 wait_for_exit = true;
1859 if (wait_for_exit) {
1860 if (s->timeout_usec > 0)
1861 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1864 service_set_state(s, state);
1865 } else if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1866 service_enter_stop_post(s, true);
1868 service_enter_dead(s, true, true);
1873 log_warning("%s failed to kill processes: %s", s->meta.id, strerror(-r));
1875 if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1876 service_enter_stop_post(s, false);
1878 service_enter_dead(s, false, true);
1884 static void service_enter_stop(Service *s, bool success) {
1892 service_unwatch_control_pid(s);
1894 s->control_command_id = SERVICE_EXEC_STOP;
1895 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP])) {
1896 if ((r = service_spawn(s,
1900 !s->permissions_start_only,
1901 !s->root_directory_start_only,
1904 &s->control_pid)) < 0)
1907 service_set_state(s, SERVICE_STOP);
1909 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
1914 log_warning("%s failed to run 'stop' task: %s", s->meta.id, strerror(-r));
1915 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1918 static void service_enter_running(Service *s, bool success) {
1919 int main_pid_ok, cgroup_ok;
1925 main_pid_ok = main_pid_good(s);
1926 cgroup_ok = cgroup_good(s);
1928 if ((main_pid_ok > 0 || (main_pid_ok < 0 && cgroup_ok != 0)) &&
1929 (s->bus_name_good || s->type != SERVICE_DBUS))
1930 service_set_state(s, SERVICE_RUNNING);
1931 else if (s->remain_after_exit)
1932 service_set_state(s, SERVICE_EXITED);
1934 service_enter_stop(s, true);
1937 static void service_enter_start_post(Service *s) {
1941 service_unwatch_control_pid(s);
1943 s->control_command_id = SERVICE_EXEC_START_POST;
1944 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_POST])) {
1945 if ((r = service_spawn(s,
1949 !s->permissions_start_only,
1950 !s->root_directory_start_only,
1953 &s->control_pid)) < 0)
1956 service_set_state(s, SERVICE_START_POST);
1958 service_enter_running(s, true);
1963 log_warning("%s failed to run 'start-post' task: %s", s->meta.id, strerror(-r));
1964 service_enter_stop(s, false);
1967 static void service_enter_start(Service *s) {
1973 assert(s->exec_command[SERVICE_EXEC_START]);
1974 assert(!s->exec_command[SERVICE_EXEC_START]->command_next || s->type == SERVICE_ONESHOT);
1976 if (s->type == SERVICE_FORKING)
1977 service_unwatch_control_pid(s);
1979 service_unwatch_main_pid(s);
1981 s->control_command_id = SERVICE_EXEC_START;
1982 s->control_command = s->exec_command[SERVICE_EXEC_START];
1984 if ((r = service_spawn(s,
1986 s->type == SERVICE_FORKING || s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY,
1991 s->notify_access != NOTIFY_NONE,
1995 if (s->type == SERVICE_SIMPLE) {
1996 /* For simple services we immediately start
1997 * the START_POST binaries. */
1999 service_set_main_pid(s, pid);
2000 service_enter_start_post(s);
2002 } else if (s->type == SERVICE_FORKING) {
2004 /* For forking services we wait until the start
2005 * process exited. */
2007 s->control_pid = pid;
2008 service_set_state(s, SERVICE_START);
2010 } else if (s->type == SERVICE_ONESHOT ||
2011 s->type == SERVICE_DBUS ||
2012 s->type == SERVICE_NOTIFY) {
2014 /* For oneshot services we wait until the start
2015 * process exited, too, but it is our main process. */
2017 /* For D-Bus services we know the main pid right away,
2018 * but wait for the bus name to appear on the
2019 * bus. Notify services are similar. */
2021 service_set_main_pid(s, pid);
2022 service_set_state(s, SERVICE_START);
2024 assert_not_reached("Unknown service type");
2029 log_warning("%s failed to run 'start' task: %s", s->meta.id, strerror(-r));
2030 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2033 static void service_enter_start_pre(Service *s) {
2038 service_unwatch_control_pid(s);
2040 s->control_command_id = SERVICE_EXEC_START_PRE;
2041 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_PRE])) {
2042 if ((r = service_spawn(s,
2046 !s->permissions_start_only,
2047 !s->root_directory_start_only,
2050 &s->control_pid)) < 0)
2053 service_set_state(s, SERVICE_START_PRE);
2055 service_enter_start(s);
2060 log_warning("%s failed to run 'start-pre' task: %s", s->meta.id, strerror(-r));
2061 service_enter_dead(s, false, true);
2064 static void service_enter_restart(Service *s) {
2069 dbus_error_init(&error);
2072 log_info("Job pending for unit, delaying automatic restart.");
2074 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
2078 service_enter_dead(s, true, false);
2080 if ((r = manager_add_job(s->meta.manager, JOB_START, UNIT(s), JOB_FAIL, false, &error, NULL)) < 0)
2083 log_debug("%s scheduled restart job.", s->meta.id);
2087 log_warning("%s failed to schedule restart job: %s", s->meta.id, bus_error(&error, -r));
2088 service_enter_dead(s, false, false);
2090 dbus_error_free(&error);
2093 static void service_enter_reload(Service *s) {
2098 service_unwatch_control_pid(s);
2100 s->control_command_id = SERVICE_EXEC_RELOAD;
2101 if ((s->control_command = s->exec_command[SERVICE_EXEC_RELOAD])) {
2102 if ((r = service_spawn(s,
2106 !s->permissions_start_only,
2107 !s->root_directory_start_only,
2110 &s->control_pid)) < 0)
2113 service_set_state(s, SERVICE_RELOAD);
2115 service_enter_running(s, true);
2120 log_warning("%s failed to run 'reload' task: %s", s->meta.id, strerror(-r));
2121 service_enter_stop(s, false);
2124 static void service_run_next_control(Service *s, bool success) {
2128 assert(s->control_command);
2129 assert(s->control_command->command_next);
2134 assert(s->control_command_id != SERVICE_EXEC_START);
2136 s->control_command = s->control_command->command_next;
2137 service_unwatch_control_pid(s);
2139 if ((r = service_spawn(s,
2143 !s->permissions_start_only,
2144 !s->root_directory_start_only,
2145 s->control_command_id == SERVICE_EXEC_START_PRE ||
2146 s->control_command_id == SERVICE_EXEC_STOP_POST,
2148 &s->control_pid)) < 0)
2154 log_warning("%s failed to run next control task: %s", s->meta.id, strerror(-r));
2156 if (s->state == SERVICE_START_PRE)
2157 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2158 else if (s->state == SERVICE_STOP)
2159 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
2160 else if (s->state == SERVICE_STOP_POST)
2161 service_enter_dead(s, false, true);
2163 service_enter_stop(s, false);
2166 static void service_run_next_main(Service *s, bool success) {
2171 assert(s->control_command);
2172 assert(s->control_command->command_next);
2177 assert(s->control_command_id == SERVICE_EXEC_START);
2178 assert(s->type == SERVICE_ONESHOT);
2180 s->control_command = s->control_command->command_next;
2181 service_unwatch_main_pid(s);
2183 if ((r = service_spawn(s,
2190 s->notify_access != NOTIFY_NONE,
2194 service_set_main_pid(s, pid);
2199 log_warning("%s failed to run next main task: %s", s->meta.id, strerror(-r));
2200 service_enter_stop(s, false);
2203 static int service_start(Unit *u) {
2204 Service *s = SERVICE(u);
2208 /* We cannot fulfill this request right now, try again later
2210 if (s->state == SERVICE_STOP ||
2211 s->state == SERVICE_STOP_SIGTERM ||
2212 s->state == SERVICE_STOP_SIGKILL ||
2213 s->state == SERVICE_STOP_POST ||
2214 s->state == SERVICE_FINAL_SIGTERM ||
2215 s->state == SERVICE_FINAL_SIGKILL)
2218 /* Already on it! */
2219 if (s->state == SERVICE_START_PRE ||
2220 s->state == SERVICE_START ||
2221 s->state == SERVICE_START_POST)
2224 assert(s->state == SERVICE_DEAD || s->state == SERVICE_FAILED || s->state == SERVICE_AUTO_RESTART);
2226 /* Make sure we don't enter a busy loop of some kind. */
2227 if (!ratelimit_test(&s->ratelimit)) {
2228 log_warning("%s start request repeated too quickly, refusing to start.", u->meta.id);
2233 s->main_pid_known = false;
2234 s->forbid_restart = false;
2236 service_enter_start_pre(s);
2240 static int service_stop(Unit *u) {
2241 Service *s = SERVICE(u);
2245 /* This is a user request, so don't do restarts on this
2247 s->forbid_restart = true;
2250 if (s->state == SERVICE_STOP ||
2251 s->state == SERVICE_STOP_SIGTERM ||
2252 s->state == SERVICE_STOP_SIGKILL ||
2253 s->state == SERVICE_STOP_POST ||
2254 s->state == SERVICE_FINAL_SIGTERM ||
2255 s->state == SERVICE_FINAL_SIGKILL)
2258 /* Don't allow a restart */
2259 if (s->state == SERVICE_AUTO_RESTART) {
2260 service_set_state(s, SERVICE_DEAD);
2264 /* If there's already something running we go directly into
2266 if (s->state == SERVICE_START_PRE ||
2267 s->state == SERVICE_START ||
2268 s->state == SERVICE_START_POST ||
2269 s->state == SERVICE_RELOAD) {
2270 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
2274 assert(s->state == SERVICE_RUNNING ||
2275 s->state == SERVICE_EXITED);
2277 service_enter_stop(s, true);
2281 static int service_reload(Unit *u) {
2282 Service *s = SERVICE(u);
2286 assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
2288 service_enter_reload(s);
2292 static bool service_can_reload(Unit *u) {
2293 Service *s = SERVICE(u);
2297 return !!s->exec_command[SERVICE_EXEC_RELOAD];
2300 static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
2301 Service *s = SERVICE(u);
2307 unit_serialize_item(u, f, "state", service_state_to_string(s->state));
2308 unit_serialize_item(u, f, "failure", yes_no(s->failure));
2310 if (s->control_pid > 0)
2311 unit_serialize_item_format(u, f, "control-pid", "%lu", (unsigned long) s->control_pid);
2313 if (s->main_pid_known && s->main_pid > 0)
2314 unit_serialize_item_format(u, f, "main-pid", "%lu", (unsigned long) s->main_pid);
2316 unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
2319 unit_serialize_item(u, f, "status-text", s->status_text);
2321 /* There's a minor uncleanliness here: if there are multiple
2322 * commands attached here, we will start from the first one
2324 if (s->control_command_id >= 0)
2325 unit_serialize_item(u, f, "control-command", service_exec_command_to_string(s->control_command_id));
2327 if (s->socket_fd >= 0) {
2330 if ((copy = fdset_put_dup(fds, s->socket_fd)) < 0)
2333 unit_serialize_item_format(u, f, "socket-fd", "%i", copy);
2336 if (s->main_exec_status.pid > 0) {
2337 unit_serialize_item_format(u, f, "main-exec-status-pid", "%lu", (unsigned long) s->main_exec_status.pid);
2338 dual_timestamp_serialize(f, "main-exec-status-start", &s->main_exec_status.start_timestamp);
2339 dual_timestamp_serialize(f, "main-exec-status-exit", &s->main_exec_status.exit_timestamp);
2341 if (dual_timestamp_is_set(&s->main_exec_status.exit_timestamp)) {
2342 unit_serialize_item_format(u, f, "main-exec-status-code", "%i", s->main_exec_status.code);
2343 unit_serialize_item_format(u, f, "main-exec-status-status", "%i", s->main_exec_status.status);
2350 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
2351 Service *s = SERVICE(u);
2358 if (streq(key, "state")) {
2361 if ((state = service_state_from_string(value)) < 0)
2362 log_debug("Failed to parse state value %s", value);
2364 s->deserialized_state = state;
2365 } else if (streq(key, "failure")) {
2368 if ((b = parse_boolean(value)) < 0)
2369 log_debug("Failed to parse failure value %s", value);
2371 s->failure = b || s->failure;
2372 } else if (streq(key, "control-pid")) {
2375 if (parse_pid(value, &pid) < 0)
2376 log_debug("Failed to parse control-pid value %s", value);
2378 s->control_pid = pid;
2379 } else if (streq(key, "main-pid")) {
2382 if (parse_pid(value, &pid) < 0)
2383 log_debug("Failed to parse main-pid value %s", value);
2385 service_set_main_pid(s, (pid_t) pid);
2386 } else if (streq(key, "main-pid-known")) {
2389 if ((b = parse_boolean(value)) < 0)
2390 log_debug("Failed to parse main-pid-known value %s", value);
2392 s->main_pid_known = b;
2393 } else if (streq(key, "status-text")) {
2396 if ((t = strdup(value))) {
2397 free(s->status_text);
2401 } else if (streq(key, "control-command")) {
2402 ServiceExecCommand id;
2404 if ((id = service_exec_command_from_string(value)) < 0)
2405 log_debug("Failed to parse exec-command value %s", value);
2407 s->control_command_id = id;
2408 s->control_command = s->exec_command[id];
2410 } else if (streq(key, "socket-fd")) {
2413 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2414 log_debug("Failed to parse socket-fd value %s", value);
2417 if (s->socket_fd >= 0)
2418 close_nointr_nofail(s->socket_fd);
2419 s->socket_fd = fdset_remove(fds, fd);
2421 } else if (streq(key, "main-exec-status-pid")) {
2424 if (parse_pid(value, &pid) < 0)
2425 log_debug("Failed to parse main-exec-status-pid value %s", value);
2427 s->main_exec_status.pid = pid;
2428 } else if (streq(key, "main-exec-status-code")) {
2431 if (safe_atoi(value, &i) < 0)
2432 log_debug("Failed to parse main-exec-status-code value %s", value);
2434 s->main_exec_status.code = i;
2435 } else if (streq(key, "main-exec-status-status")) {
2438 if (safe_atoi(value, &i) < 0)
2439 log_debug("Failed to parse main-exec-status-status value %s", value);
2441 s->main_exec_status.status = i;
2442 } else if (streq(key, "main-exec-status-start"))
2443 dual_timestamp_deserialize(value, &s->main_exec_status.start_timestamp);
2444 else if (streq(key, "main-exec-status-exit"))
2445 dual_timestamp_deserialize(value, &s->main_exec_status.exit_timestamp);
2447 log_debug("Unknown serialization key '%s'", key);
2452 static UnitActiveState service_active_state(Unit *u) {
2455 return state_translation_table[SERVICE(u)->state];
2458 static const char *service_sub_state_to_string(Unit *u) {
2461 return service_state_to_string(SERVICE(u)->state);
2464 #ifdef HAVE_SYSV_COMPAT
2465 static bool service_check_gc(Unit *u) {
2466 Service *s = SERVICE(u);
2470 return !!s->sysv_path;
2474 static bool service_check_snapshot(Unit *u) {
2475 Service *s = SERVICE(u);
2479 return !s->got_socket_fd;
2482 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2483 Service *s = SERVICE(u);
2489 if (!s->meta.fragment_path)
2490 success = is_clean_exit_lsb(code, status);
2492 success = is_clean_exit(code, status);
2494 if (s->main_pid == pid) {
2497 exec_status_exit(&s->main_exec_status, pid, code, status, s->exec_context.utmp_id);
2499 if (s->type != SERVICE_FORKING && s->control_command) {
2500 s->control_command->exec_status = s->main_exec_status;
2502 if (s->control_command->ignore)
2506 log_full(success ? LOG_DEBUG : LOG_NOTICE,
2507 "%s: main process exited, code=%s, status=%i", u->meta.id, sigchld_code_to_string(code), status);
2508 s->failure = s->failure || !success;
2510 if (s->control_command &&
2511 s->control_command->command_next &&
2514 /* There is another command to *
2515 * execute, so let's do that. */
2517 log_debug("%s running next main command for state %s", u->meta.id, service_state_to_string(s->state));
2518 service_run_next_main(s, success);
2522 /* The service exited, so the service is officially
2525 s->control_command = NULL;
2526 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2530 case SERVICE_START_POST:
2531 case SERVICE_RELOAD:
2533 /* Need to wait until the operation is
2538 if (s->type == SERVICE_ONESHOT) {
2539 /* This was our main goal, so let's go on */
2541 service_enter_start_post(s);
2543 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2546 assert(s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY);
2551 case SERVICE_RUNNING:
2552 service_enter_running(s, success);
2555 case SERVICE_STOP_SIGTERM:
2556 case SERVICE_STOP_SIGKILL:
2558 if (!control_pid_good(s))
2559 service_enter_stop_post(s, success);
2561 /* If there is still a control process, wait for that first */
2565 assert_not_reached("Uh, main process died at wrong time.");
2569 } else if (s->control_pid == pid) {
2573 if (s->control_command) {
2574 exec_status_exit(&s->control_command->exec_status, pid, code, status, s->exec_context.utmp_id);
2576 if (s->control_command->ignore)
2580 log_full(success ? LOG_DEBUG : LOG_NOTICE,
2581 "%s: control process exited, code=%s status=%i", u->meta.id, sigchld_code_to_string(code), status);
2582 s->failure = s->failure || !success;
2584 if (s->control_command &&
2585 s->control_command->command_next &&
2588 /* There is another command to *
2589 * execute, so let's do that. */
2591 log_debug("%s running next control command for state %s", u->meta.id, service_state_to_string(s->state));
2592 service_run_next_control(s, success);
2595 /* No further commands for this step, so let's
2596 * figure out what to do next */
2598 s->control_command = NULL;
2599 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2601 log_debug("%s got final SIGCHLD for state %s", u->meta.id, service_state_to_string(s->state));
2605 case SERVICE_START_PRE:
2607 service_enter_start(s);
2609 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2613 assert(s->type == SERVICE_FORKING);
2615 /* Let's try to load the pid
2616 * file here if we can. We
2617 * ignore the return value,
2618 * since the PID file might
2619 * actually be created by a
2620 * START_POST script */
2623 service_load_pid_file(s);
2624 service_search_main_pid(s);
2626 service_enter_start_post(s);
2628 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2632 case SERVICE_START_POST:
2633 if (success && s->pid_file && !s->main_pid_known) {
2636 /* Hmm, let's see if we can
2637 * load the pid now after the
2638 * start-post scripts got
2641 if ((r = service_load_pid_file(s)) < 0)
2642 log_warning("%s: failed to load PID file %s: %s", s->meta.id, s->pid_file, strerror(-r));
2647 case SERVICE_RELOAD:
2649 service_enter_running(s, true);
2651 service_enter_stop(s, false);
2656 service_enter_signal(s, SERVICE_STOP_SIGTERM, success);
2659 case SERVICE_STOP_SIGTERM:
2660 case SERVICE_STOP_SIGKILL:
2661 if (main_pid_good(s) <= 0)
2662 service_enter_stop_post(s, success);
2664 /* If there is still a service
2665 * process around, wait until
2666 * that one quit, too */
2669 case SERVICE_STOP_POST:
2670 case SERVICE_FINAL_SIGTERM:
2671 case SERVICE_FINAL_SIGKILL:
2672 service_enter_dead(s, success, true);
2676 assert_not_reached("Uh, control process died at wrong time.");
2681 /* Notify clients about changed exit status */
2682 unit_add_to_dbus_queue(u);
2685 static void service_timer_event(Unit *u, uint64_t elapsed, Watch* w) {
2686 Service *s = SERVICE(u);
2689 assert(elapsed == 1);
2691 assert(w == &s->timer_watch);
2695 case SERVICE_START_PRE:
2697 log_warning("%s operation timed out. Terminating.", u->meta.id);
2698 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2701 case SERVICE_START_POST:
2702 case SERVICE_RELOAD:
2703 log_warning("%s operation timed out. Stopping.", u->meta.id);
2704 service_enter_stop(s, false);
2708 log_warning("%s stopping timed out. Terminating.", u->meta.id);
2709 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
2712 case SERVICE_STOP_SIGTERM:
2713 log_warning("%s stopping timed out. Killing.", u->meta.id);
2714 service_enter_signal(s, SERVICE_STOP_SIGKILL, false);
2717 case SERVICE_STOP_SIGKILL:
2718 /* Uh, wie sent a SIGKILL and it is still not gone?
2719 * Must be something we cannot kill, so let's just be
2720 * weirded out and continue */
2722 log_warning("%s still around after SIGKILL. Ignoring.", u->meta.id);
2723 service_enter_stop_post(s, false);
2726 case SERVICE_STOP_POST:
2727 log_warning("%s stopping timed out (2). Terminating.", u->meta.id);
2728 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2731 case SERVICE_FINAL_SIGTERM:
2732 log_warning("%s stopping timed out (2). Killing.", u->meta.id);
2733 service_enter_signal(s, SERVICE_FINAL_SIGKILL, false);
2736 case SERVICE_FINAL_SIGKILL:
2737 log_warning("%s still around after SIGKILL (2). Entering failed mode.", u->meta.id);
2738 service_enter_dead(s, false, true);
2741 case SERVICE_AUTO_RESTART:
2742 log_info("%s holdoff time over, scheduling restart.", u->meta.id);
2743 service_enter_restart(s);
2747 assert_not_reached("Timeout at wrong time.");
2751 static void service_cgroup_notify_event(Unit *u) {
2752 Service *s = SERVICE(u);
2756 log_debug("%s: cgroup is empty", u->meta.id);
2760 /* Waiting for SIGCHLD is usually more interesting,
2761 * because it includes return codes/signals. Which is
2762 * why we ignore the cgroup events for most cases,
2763 * except when we don't know pid which to expect the
2766 case SERVICE_RUNNING:
2767 service_enter_running(s, true);
2770 case SERVICE_STOP_SIGTERM:
2771 case SERVICE_STOP_SIGKILL:
2772 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2773 service_enter_stop_post(s, true);
2777 case SERVICE_FINAL_SIGTERM:
2778 case SERVICE_FINAL_SIGKILL:
2779 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2780 service_enter_dead(s, true, true);
2789 static void service_notify_message(Unit *u, pid_t pid, char **tags) {
2790 Service *s = SERVICE(u);
2795 if (s->notify_access == NOTIFY_NONE) {
2796 log_warning("%s: Got notification message from PID %lu, but reception is disabled.",
2797 u->meta.id, (unsigned long) pid);
2801 if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
2802 log_warning("%s: Got notification message from PID %lu, but reception only permitted for PID %lu",
2803 u->meta.id, (unsigned long) pid, (unsigned long) s->main_pid);
2807 log_debug("%s: Got message", u->meta.id);
2809 /* Interpret MAINPID= */
2810 if ((e = strv_find_prefix(tags, "MAINPID=")) &&
2811 (s->state == SERVICE_START ||
2812 s->state == SERVICE_START_POST ||
2813 s->state == SERVICE_RUNNING ||
2814 s->state == SERVICE_RELOAD)) {
2816 if (parse_pid(e + 8, &pid) < 0)
2817 log_warning("Failed to parse notification message %s", e);
2819 log_debug("%s: got %s", u->meta.id, e);
2820 service_set_main_pid(s, pid);
2824 /* Interpret READY= */
2825 if (s->type == SERVICE_NOTIFY &&
2826 s->state == SERVICE_START &&
2827 strv_find(tags, "READY=1")) {
2828 log_debug("%s: got READY=1", u->meta.id);
2830 service_enter_start_post(s);
2833 /* Interpret STATUS= */
2834 if ((e = strv_find_prefix(tags, "STATUS="))) {
2838 if (!(t = strdup(e+7))) {
2839 log_error("Failed to allocate string.");
2843 log_debug("%s: got %s", u->meta.id, e);
2845 free(s->status_text);
2848 free(s->status_text);
2849 s->status_text = NULL;
2854 /* Notify clients about changed status or main pid */
2855 unit_add_to_dbus_queue(u);
2858 #ifdef HAVE_SYSV_COMPAT
2859 static int service_enumerate(Manager *m) {
2863 char *path = NULL, *fpath = NULL, *name = NULL;
2864 Set *runlevel_services[ELEMENTSOF(rcnd_table)], *shutdown_services = NULL;
2869 Unit *previous = NULL;
2870 char *arch_daemons = NULL;
2871 char *arch_daemons_stripped = NULL;
2872 char **arch_daemons_split = NULL;
2878 if ((r = parse_env_file("/etc/rc.conf", NEWLINE,
2879 "DAEMONS", &arch_daemons,
2883 log_warning("Failed to read /etc/rc.conf: %s", strerror(-r));
2885 } else if (arch_daemons) {
2886 if (!(arch_daemons_stripped = strchr(arch_daemons, '(')))
2887 arch_daemons_stripped = arch_daemons;
2889 arch_daemons_stripped++; /* strip start paren */
2891 arch_daemons_stripped[strcspn(arch_daemons_stripped, ")")] = 0; /* strip end paren */
2893 if (!(arch_daemons_split = strv_split_quoted(arch_daemons_stripped))) {
2898 STRV_FOREACH(p, arch_daemons_split) {
2903 if (**p == '!') /* daemons prefixed with ! are disabled, so ignore them */
2906 if (!(name = sysv_translate_name(*p))) {
2911 if ((r = manager_load_unit_prepare(m, name, NULL, NULL, &service)) < 0) {
2912 log_warning("Failed to prepare unit %s: %s", name, strerror(-r));
2916 if ((r = unit_add_two_dependencies_by_name_inverse(service, UNIT_AFTER, UNIT_WANTS, "multi-user.target", NULL, true)) < 0)
2920 if ((r = unit_add_dependency(service, UNIT_AFTER, previous, true)) < 0)
2923 if (**p != '@') /* daemons prefixed with @ can be started in the background */
2929 zero(runlevel_services);
2931 STRV_FOREACH(p, m->lookup_paths.sysvrcnd_path)
2932 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++) {
2937 if (asprintf(&path, "%s/%s", *p, rcnd_table[i].path) < 0) {
2945 if (!(d = opendir(path))) {
2946 if (errno != ENOENT)
2947 log_warning("opendir() failed on %s: %s", path, strerror(errno));
2952 while ((de = readdir(d))) {
2955 if (ignore_file(de->d_name))
2958 if (de->d_name[0] != 'S' && de->d_name[0] != 'K')
2961 if (strlen(de->d_name) < 4)
2964 a = undecchar(de->d_name[1]);
2965 b = undecchar(de->d_name[2]);
2972 if (asprintf(&fpath, "%s/%s/%s", *p, rcnd_table[i].path, de->d_name) < 0) {
2977 if (access(fpath, X_OK) < 0) {
2979 if (errno != ENOENT)
2980 log_warning("access() failed on %s: %s", fpath, strerror(errno));
2986 if (!(name = sysv_translate_name(de->d_name + 3))) {
2991 if ((r = manager_load_unit_prepare(m, name, NULL, NULL, &service)) < 0) {
2992 log_warning("Failed to prepare unit %s: %s", name, strerror(-r));
2996 if (de->d_name[0] == 'S') {
2998 if (rcnd_table[i].type == RUNLEVEL_UP || rcnd_table[i].type == RUNLEVEL_SYSINIT) {
2999 SERVICE(service)->sysv_start_priority =
3000 MAX(a*10 + b, SERVICE(service)->sysv_start_priority);
3002 SERVICE(service)->sysv_enabled = true;
3005 if ((r = set_ensure_allocated(&runlevel_services[i], trivial_hash_func, trivial_compare_func)) < 0)
3008 if ((r = set_put(runlevel_services[i], service)) < 0)
3011 } else if (de->d_name[0] == 'K' &&
3012 (rcnd_table[i].type == RUNLEVEL_DOWN ||
3013 rcnd_table[i].type == RUNLEVEL_SYSINIT)) {
3015 if ((r = set_ensure_allocated(&shutdown_services, trivial_hash_func, trivial_compare_func)) < 0)
3018 if ((r = set_put(shutdown_services, service)) < 0)
3024 /* Now we loaded all stubs and are aware of the lowest
3025 start-up priority for all services, not let's actually load
3026 the services, this will also tell us which services are
3027 actually native now */
3028 manager_dispatch_load_queue(m);
3030 /* If this is a native service, rely on native ways to pull in
3031 * a service, don't pull it in via sysv rcN.d links. */
3032 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++)
3033 SET_FOREACH(service, runlevel_services[i], j) {
3034 service = unit_follow_merge(service);
3036 if (service->meta.fragment_path)
3039 if ((r = unit_add_two_dependencies_by_name_inverse(service, UNIT_AFTER, UNIT_WANTS, rcnd_table[i].target, NULL, true)) < 0)
3043 /* We honour K links only for halt/reboot. For the normal
3044 * runlevels we assume the stop jobs will be implicitly added
3045 * by the core logic. Also, we don't really distuingish here
3046 * between the runlevels 0 and 6 and just add them to the
3047 * special shutdown target. On SUSE the boot.d/ runlevel is
3048 * also used for shutdown, so we add links for that too to the
3049 * shutdown target.*/
3050 SET_FOREACH(service, shutdown_services, j) {
3051 service = unit_follow_merge(service);
3053 if (service->meta.fragment_path)
3056 if ((r = unit_add_two_dependencies_by_name(service, UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true)) < 0)
3068 free(arch_daemons_split);
3071 for (i = 0; i < ELEMENTSOF(rcnd_table); i++)
3072 set_free(runlevel_services[i]);
3073 set_free(shutdown_services);
3082 static void service_bus_name_owner_change(
3085 const char *old_owner,
3086 const char *new_owner) {
3088 Service *s = SERVICE(u);
3093 assert(streq(s->bus_name, name));
3094 assert(old_owner || new_owner);
3096 if (old_owner && new_owner)
3097 log_debug("%s's D-Bus name %s changed owner from %s to %s", u->meta.id, name, old_owner, new_owner);
3099 log_debug("%s's D-Bus name %s no longer registered by %s", u->meta.id, name, old_owner);
3101 log_debug("%s's D-Bus name %s now registered by %s", u->meta.id, name, new_owner);
3103 s->bus_name_good = !!new_owner;
3105 if (s->type == SERVICE_DBUS) {
3107 /* service_enter_running() will figure out what to
3109 if (s->state == SERVICE_RUNNING)
3110 service_enter_running(s, true);
3111 else if (s->state == SERVICE_START && new_owner)
3112 service_enter_start_post(s);
3114 } else if (new_owner &&
3116 (s->state == SERVICE_START ||
3117 s->state == SERVICE_START_POST ||
3118 s->state == SERVICE_RUNNING ||
3119 s->state == SERVICE_RELOAD)) {
3121 /* Try to acquire PID from bus service */
3122 log_debug("Trying to acquire PID from D-Bus name...");
3124 bus_query_pid(u->meta.manager, name);
3128 static void service_bus_query_pid_done(
3133 Service *s = SERVICE(u);
3138 log_debug("%s's D-Bus name %s is now owned by process %u", u->meta.id, name, (unsigned) pid);
3140 if (s->main_pid <= 0 &&
3141 (s->state == SERVICE_START ||
3142 s->state == SERVICE_START_POST ||
3143 s->state == SERVICE_RUNNING ||
3144 s->state == SERVICE_RELOAD))
3145 service_set_main_pid(s, pid);
3148 int service_set_socket_fd(Service *s, int fd, Socket *sock) {
3152 /* This is called by the socket code when instantiating a new
3153 * service for a stream socket and the socket needs to be
3156 if (s->meta.load_state != UNIT_LOADED)
3159 if (s->socket_fd >= 0)
3162 if (s->state != SERVICE_DEAD)
3166 s->got_socket_fd = true;
3167 s->accept_socket = sock;
3172 static void service_reset_failed(Unit *u) {
3173 Service *s = SERVICE(u);
3177 if (s->state == SERVICE_FAILED)
3178 service_set_state(s, SERVICE_DEAD);
3183 static int service_kill(Unit *u, KillWho who, KillMode mode, int signo, DBusError *error) {
3184 Service *s = SERVICE(u);
3186 Set *pid_set = NULL;
3190 if (s->main_pid <= 0 && who == KILL_MAIN) {
3191 dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "No main process to kill");
3195 if (s->control_pid <= 0 && who == KILL_CONTROL) {
3196 dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "No control process to kill");
3200 if (s->control_pid > 0)
3201 if (kill(mode == KILL_PROCESS_GROUP ? -s->control_pid : s->control_pid, signo) < 0)
3204 if (s->main_pid > 0)
3205 if (kill(mode == KILL_PROCESS_GROUP ? -s->main_pid : s->main_pid, signo) < 0)
3208 if (mode == KILL_CONTROL_GROUP) {
3211 if (!(pid_set = set_new(trivial_hash_func, trivial_compare_func)))
3214 /* Exclude the control/main pid from being killed via the cgroup */
3215 if (s->control_pid > 0)
3216 if ((q = set_put(pid_set, LONG_TO_PTR(s->control_pid))) < 0) {
3221 if (s->main_pid > 0)
3222 if ((q = set_put(pid_set, LONG_TO_PTR(s->main_pid))) < 0) {
3227 if ((q = cgroup_bonding_kill_list(s->meta.cgroup_bondings, signo, pid_set)) < 0)
3228 if (r != -EAGAIN && r != -ESRCH && r != -ENOENT)
3239 static const char* const service_state_table[_SERVICE_STATE_MAX] = {
3240 [SERVICE_DEAD] = "dead",
3241 [SERVICE_START_PRE] = "start-pre",
3242 [SERVICE_START] = "start",
3243 [SERVICE_START_POST] = "start-post",
3244 [SERVICE_RUNNING] = "running",
3245 [SERVICE_EXITED] = "exited",
3246 [SERVICE_RELOAD] = "reload",
3247 [SERVICE_STOP] = "stop",
3248 [SERVICE_STOP_SIGTERM] = "stop-sigterm",
3249 [SERVICE_STOP_SIGKILL] = "stop-sigkill",
3250 [SERVICE_STOP_POST] = "stop-post",
3251 [SERVICE_FINAL_SIGTERM] = "final-sigterm",
3252 [SERVICE_FINAL_SIGKILL] = "final-sigkill",
3253 [SERVICE_FAILED] = "failed",
3254 [SERVICE_AUTO_RESTART] = "auto-restart",
3257 DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
3259 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
3260 [SERVICE_RESTART_NO] = "no",
3261 [SERVICE_RESTART_ON_SUCCESS] = "on-success",
3262 [SERVICE_RESTART_ON_FAILURE] = "on-failure",
3263 [SERVICE_RESTART_ON_ABORT] = "on-abort",
3264 [SERVICE_RESTART_ALWAYS] = "always"
3267 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
3269 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
3270 [SERVICE_SIMPLE] = "simple",
3271 [SERVICE_FORKING] = "forking",
3272 [SERVICE_ONESHOT] = "oneshot",
3273 [SERVICE_DBUS] = "dbus",
3274 [SERVICE_NOTIFY] = "notify"
3277 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
3279 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
3280 [SERVICE_EXEC_START_PRE] = "ExecStartPre",
3281 [SERVICE_EXEC_START] = "ExecStart",
3282 [SERVICE_EXEC_START_POST] = "ExecStartPost",
3283 [SERVICE_EXEC_RELOAD] = "ExecReload",
3284 [SERVICE_EXEC_STOP] = "ExecStop",
3285 [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
3288 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
3290 static const char* const notify_access_table[_NOTIFY_ACCESS_MAX] = {
3291 [NOTIFY_NONE] = "none",
3292 [NOTIFY_MAIN] = "main",
3293 [NOTIFY_ALL] = "all"
3296 DEFINE_STRING_TABLE_LOOKUP(notify_access, NotifyAccess);
3298 const UnitVTable service_vtable = {
3299 .suffix = ".service",
3300 .show_status = true,
3302 .init = service_init,
3303 .done = service_done,
3304 .load = service_load,
3306 .coldplug = service_coldplug,
3308 .dump = service_dump,
3310 .start = service_start,
3311 .stop = service_stop,
3312 .reload = service_reload,
3314 .can_reload = service_can_reload,
3316 .kill = service_kill,
3318 .serialize = service_serialize,
3319 .deserialize_item = service_deserialize_item,
3321 .active_state = service_active_state,
3322 .sub_state_to_string = service_sub_state_to_string,
3324 #ifdef HAVE_SYSV_COMPAT
3325 .check_gc = service_check_gc,
3327 .check_snapshot = service_check_snapshot,
3329 .sigchld_event = service_sigchld_event,
3330 .timer_event = service_timer_event,
3332 .reset_failed = service_reset_failed,
3334 .cgroup_notify_empty = service_cgroup_notify_event,
3335 .notify_message = service_notify_message,
3337 .bus_name_owner_change = service_bus_name_owner_change,
3338 .bus_query_pid_done = service_bus_query_pid_done,
3340 .bus_interface = "org.freedesktop.systemd1.Service",
3341 .bus_message_handler = bus_service_message_handler,
3342 .bus_invalidating_properties = bus_service_invalidating_properties,
3344 #ifdef HAVE_SYSV_COMPAT
3345 .enumerate = service_enumerate