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"
39 #define COMMENTS "#;\n"
40 #define NEWLINES "\n\r"
42 #ifdef HAVE_SYSV_COMPAT
44 #define DEFAULT_SYSV_TIMEOUT_USEC (3*USEC_PER_MINUTE)
46 typedef enum RunlevelType {
55 const RunlevelType type;
57 /* Standard SysV runlevels for start-up */
58 { "rc1.d", SPECIAL_RESCUE_TARGET, RUNLEVEL_UP },
59 { "rc2.d", SPECIAL_RUNLEVEL2_TARGET, RUNLEVEL_UP },
60 { "rc3.d", SPECIAL_RUNLEVEL3_TARGET, RUNLEVEL_UP },
61 { "rc4.d", SPECIAL_RUNLEVEL4_TARGET, RUNLEVEL_UP },
62 { "rc5.d", SPECIAL_RUNLEVEL5_TARGET, RUNLEVEL_UP },
65 /* SUSE style boot.d */
66 { "boot.d", SPECIAL_SYSINIT_TARGET, RUNLEVEL_SYSINIT },
69 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU) || defined(TARGET_FRUGALWARE)
70 /* Debian style rcS.d */
71 { "rcS.d", SPECIAL_SYSINIT_TARGET, RUNLEVEL_SYSINIT },
74 /* Standard SysV runlevels for shutdown */
75 { "rc0.d", SPECIAL_POWEROFF_TARGET, RUNLEVEL_DOWN },
76 { "rc6.d", SPECIAL_REBOOT_TARGET, RUNLEVEL_DOWN }
78 /* Note that the order here matters, as we read the
79 directories in this order, and we want to make sure that
80 sysv_start_priority is known when we first load the
81 unit. And that value we only know from S links. Hence
82 UP/SYSINIT must be read before DOWN */
85 #define RUNLEVELS_UP "12345"
86 /* #define RUNLEVELS_DOWN "06" */
87 /* #define RUNLEVELS_BOOT "bBsS" */
90 static const UnitActiveState state_translation_table[_SERVICE_STATE_MAX] = {
91 [SERVICE_DEAD] = UNIT_INACTIVE,
92 [SERVICE_START_PRE] = UNIT_ACTIVATING,
93 [SERVICE_START] = UNIT_ACTIVATING,
94 [SERVICE_START_POST] = UNIT_ACTIVATING,
95 [SERVICE_RUNNING] = UNIT_ACTIVE,
96 [SERVICE_EXITED] = UNIT_ACTIVE,
97 [SERVICE_RELOAD] = UNIT_RELOADING,
98 [SERVICE_STOP] = UNIT_DEACTIVATING,
99 [SERVICE_STOP_SIGTERM] = UNIT_DEACTIVATING,
100 [SERVICE_STOP_SIGKILL] = UNIT_DEACTIVATING,
101 [SERVICE_STOP_POST] = UNIT_DEACTIVATING,
102 [SERVICE_FINAL_SIGTERM] = UNIT_DEACTIVATING,
103 [SERVICE_FINAL_SIGKILL] = UNIT_DEACTIVATING,
104 [SERVICE_FAILED] = UNIT_FAILED,
105 [SERVICE_AUTO_RESTART] = UNIT_ACTIVATING
108 static void service_init(Unit *u) {
109 Service *s = SERVICE(u);
112 assert(u->meta.load_state == UNIT_STUB);
114 s->timeout_usec = DEFAULT_TIMEOUT_USEC;
115 s->restart_usec = DEFAULT_RESTART_USEC;
116 s->timer_watch.type = WATCH_INVALID;
117 #ifdef HAVE_SYSV_COMPAT
118 s->sysv_start_priority = -1;
122 exec_context_init(&s->exec_context);
124 RATELIMIT_INIT(s->ratelimit, 10*USEC_PER_SEC, 5);
126 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
129 static void service_unwatch_control_pid(Service *s) {
132 if (s->control_pid <= 0)
135 unit_unwatch_pid(UNIT(s), s->control_pid);
139 static void service_unwatch_main_pid(Service *s) {
142 if (s->main_pid <= 0)
145 unit_unwatch_pid(UNIT(s), s->main_pid);
149 static int service_set_main_pid(Service *s, pid_t pid) {
160 if (get_parent_of_pid(pid, &ppid) >= 0 && ppid != getpid())
161 log_warning("%s: Supervising process %lu which is not our child. We'll most likely not notice when it exits.",
162 s->meta.id, (unsigned long) pid);
165 s->main_pid_known = true;
167 exec_status_start(&s->main_exec_status, pid);
172 static void service_close_socket_fd(Service *s) {
175 if (s->socket_fd < 0)
178 close_nointr_nofail(s->socket_fd);
182 static void service_connection_unref(Service *s) {
185 if (!s->accept_socket)
188 socket_connection_unref(s->accept_socket);
189 s->accept_socket = NULL;
192 static void service_done(Unit *u) {
193 Service *s = SERVICE(u);
200 #ifdef HAVE_SYSV_COMPAT
204 free(s->sysv_runlevels);
205 s->sysv_runlevels = NULL;
208 free(s->status_text);
209 s->status_text = NULL;
211 exec_context_done(&s->exec_context);
212 exec_command_free_array(s->exec_command, _SERVICE_EXEC_COMMAND_MAX);
213 s->control_command = NULL;
214 s->main_command = NULL;
216 /* This will leak a process, but at least no memory or any of
218 service_unwatch_main_pid(s);
219 service_unwatch_control_pid(s);
222 unit_unwatch_bus_name(UNIT(u), s->bus_name);
227 service_close_socket_fd(s);
228 service_connection_unref(s);
230 set_free(s->configured_sockets);
232 unit_unwatch_timer(u, &s->timer_watch);
235 #ifdef HAVE_SYSV_COMPAT
236 static char *sysv_translate_name(const char *name) {
239 if (!(r = new(char, strlen(name) + sizeof(".service"))))
242 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU)
243 if (endswith(name, ".sh"))
244 /* Drop Debian-style .sh suffix */
245 strcpy(stpcpy(r, name) - 3, ".service");
248 if (startswith(name, "boot."))
249 /* Drop SuSE-style boot. prefix */
250 strcpy(stpcpy(r, name + 5), ".service");
252 #ifdef TARGET_FRUGALWARE
253 if (startswith(name, "rc."))
254 /* Drop Frugalware-style rc. prefix */
255 strcpy(stpcpy(r, name + 3), ".service");
258 /* Normal init scripts */
259 strcpy(stpcpy(r, name), ".service");
264 static int sysv_translate_facility(const char *name, const char *filename, char **_r) {
266 /* We silently ignore the $ prefix here. According to the LSB
267 * spec it simply indicates whether something is a
268 * standardized name or a distribution-specific one. Since we
269 * just follow what already exists and do not introduce new
270 * uses or names we don't care who introduced a new name. */
272 static const char * const table[] = {
273 /* LSB defined facilities */
274 "local_fs", SPECIAL_LOCAL_FS_TARGET,
275 "network", SPECIAL_NETWORK_TARGET,
276 "named", SPECIAL_NSS_LOOKUP_TARGET,
277 "portmap", SPECIAL_RPCBIND_TARGET,
278 "remote_fs", SPECIAL_REMOTE_FS_TARGET,
279 "syslog", SPECIAL_SYSLOG_TARGET,
280 "time", SPECIAL_RTC_SET_TARGET,
282 /* common extensions */
283 "mail-transfer-agent", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
284 "x-display-manager", SPECIAL_DISPLAY_MANAGER_SERVICE,
287 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU)
288 "mail-transport-agent", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
292 "MTA", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
293 "smtpdaemon", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
294 "httpd", SPECIAL_HTTP_DAEMON_TARGET,
298 "smtp", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
309 n = *name == '$' ? name + 1 : name;
311 for (i = 0; i < ELEMENTSOF(table); i += 2) {
313 if (!streq(table[i], n))
319 if (!(r = strdup(table[i+1])))
325 /* If we don't know this name, fallback heuristics to figure
326 * out whether something is a target or a service alias. */
329 if (!unit_prefix_is_valid(n))
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);
689 log_error("[%s:%u] Failed to translate LSB dependency %s, ignoring: %s", path, line, n, strerror(-r));
699 r = unit_add_dependency_by_name(u, startswith_no_case(t, "X-Start-Before:") ? UNIT_BEFORE : UNIT_AFTER, m, NULL, true);
702 log_error("[%s:%u] Failed to add dependency on %s, ignoring: %s", path, line, m, strerror(-r));
706 } else if (startswith_no_case(t, "Default-Start:")) {
711 k = delete_chars(t+14, WHITESPACE "-");
714 if (!(d = strdup(k))) {
719 free(s->sysv_runlevels);
720 s->sysv_runlevels = d;
723 } else if (startswith_no_case(t, "Description:")) {
726 state = LSB_DESCRIPTION;
728 if ((j = strstrip(t+12)) && *j) {
729 if (!(d = strdup(j))) {
736 free(long_description);
737 long_description = d;
739 } else if (startswith_no_case(t, "Short-Description:")) {
744 if ((j = strstrip(t+18)) && *j) {
745 if (!(d = strdup(j))) {
752 free(short_description);
753 short_description = d;
755 } else if (startswith_no_case(t, "X-Interactive:")) {
758 if ((b = parse_boolean(strstrip(t+14))) < 0) {
759 log_warning("[%s:%u] Couldn't parse interactive flag. Ignoring.", path, line);
764 s->exec_context.std_input = EXEC_INPUT_TTY;
766 s->exec_context.std_input = EXEC_INPUT_NULL;
768 } else if (state == LSB_DESCRIPTION) {
770 if (startswith(l, "#\t") || startswith(l, "# ")) {
773 if ((j = strstrip(t)) && *j) {
776 if (long_description)
777 asprintf(&d, "%s %s", long_description, t);
786 free(long_description);
787 long_description = d;
796 if ((r = sysv_exec_commands(s)) < 0)
799 if (s->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, s->sysv_runlevels)) {
800 /* If there a runlevels configured for this service
801 * but none of the standard ones, then we assume this
802 * is some special kind of service (which might be
803 * needed for early boot) and don't create any links
806 s->meta.default_dependencies = false;
808 /* Don't timeout special services during boot (like fsck) */
811 s->timeout_usec = DEFAULT_SYSV_TIMEOUT_USEC;
813 /* Special setting for all SysV services */
814 s->type = SERVICE_FORKING;
815 s->remain_after_exit = true;
816 s->restart = SERVICE_RESTART_NO;
817 s->exec_context.std_output =
818 (s->meta.manager->sysv_console || s->exec_context.std_input == EXEC_INPUT_TTY)
819 ? EXEC_OUTPUT_TTY : EXEC_OUTPUT_NULL;
820 s->exec_context.kill_mode = KILL_PROCESS_GROUP;
822 /* We use the long description only if
823 * no short description is set. */
825 if (short_description)
826 description = short_description;
827 else if (chkconfig_description)
828 description = chkconfig_description;
829 else if (long_description)
830 description = long_description;
837 if (!(d = strappend("LSB: ", description))) {
842 u->meta.description = d;
845 u->meta.load_state = UNIT_LOADED;
853 free(short_description);
854 free(long_description);
855 free(chkconfig_description);
860 static int service_load_sysv_name(Service *s, const char *name) {
866 /* For SysV services we strip the boot.*, rc.* and *.sh
867 * prefixes/suffixes. */
868 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU)
869 if (endswith(name, ".sh.service"))
874 if (startswith(name, "boot."))
878 #ifdef TARGET_FRUGALWARE
879 if (startswith(name, "rc."))
883 STRV_FOREACH(p, s->meta.manager->lookup_paths.sysvinit_path) {
887 if (asprintf(&path, "%s/%s", *p, name) < 0)
890 assert(endswith(path, ".service"));
891 path[strlen(path)-8] = 0;
893 r = service_load_sysv_path(s, path);
895 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU)
896 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
897 /* Try Debian style *.sh source'able init scripts */
899 r = service_load_sysv_path(s, path);
905 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
906 /* Try SUSE style boot.* init scripts */
908 if (asprintf(&path, "%s/boot.%s", *p, name) < 0)
911 /* Drop .service suffix */
912 path[strlen(path)-8] = 0;
913 r = service_load_sysv_path(s, path);
918 #ifdef TARGET_FRUGALWARE
919 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
920 /* Try Frugalware style rc.* init scripts */
922 if (asprintf(&path, "%s/rc.%s", *p, name) < 0)
925 /* Drop .service suffix */
926 path[strlen(path)-8] = 0;
927 r = service_load_sysv_path(s, path);
935 if ((s->meta.load_state != UNIT_STUB))
942 static int service_load_sysv(Service *s) {
949 /* Load service data from SysV init scripts, preferably with
952 if (strv_isempty(s->meta.manager->lookup_paths.sysvinit_path))
955 if ((t = s->meta.id))
956 if ((r = service_load_sysv_name(s, t)) < 0)
959 if (s->meta.load_state == UNIT_STUB)
960 SET_FOREACH(t, s->meta.names, i) {
964 if ((r = service_load_sysv_name(s, t)) < 0)
967 if (s->meta.load_state != UNIT_STUB)
975 static int fsck_fix_order(Service *s) {
981 if (s->fsck_passno <= 0)
984 /* For each pair of services where both have an fsck priority
985 * we order things based on it. */
987 LIST_FOREACH(units_per_type, other, s->meta.manager->units_per_type[UNIT_SERVICE]) {
991 t = (Service*) other;
996 if (t->meta.load_state != UNIT_LOADED)
999 if (t->fsck_passno <= 0)
1002 if (t->fsck_passno < s->fsck_passno)
1004 else if (t->fsck_passno > s->fsck_passno)
1009 if (!(r = unit_add_dependency(UNIT(s), d, UNIT(t), true)) < 0)
1016 static int service_verify(Service *s) {
1019 if (s->meta.load_state != UNIT_LOADED)
1022 if (!s->exec_command[SERVICE_EXEC_START]) {
1023 log_error("%s lacks ExecStart setting. Refusing.", s->meta.id);
1027 if (s->type != SERVICE_ONESHOT &&
1028 s->exec_command[SERVICE_EXEC_START]->command_next) {
1029 log_error("%s has more than one ExecStart setting, which is only allowed for Type=oneshot services. Refusing.", s->meta.id);
1033 if (s->type == SERVICE_ONESHOT &&
1034 s->exec_command[SERVICE_EXEC_RELOAD]) {
1035 log_error("%s has an ExecReload setting, which is not allowed for Type=oneshot services. Refusing.", s->meta.id);
1039 if (s->type == SERVICE_DBUS && !s->bus_name) {
1040 log_error("%s is of type D-Bus but no D-Bus service name has been specified. Refusing.", s->meta.id);
1044 if (s->exec_context.pam_name && s->exec_context.kill_mode != KILL_CONTROL_GROUP) {
1045 log_error("%s has PAM enabled. Kill mode must be set to 'control-group'. Refusing.", s->meta.id);
1052 static int service_add_default_dependencies(Service *s) {
1057 /* Add a number of automatic dependencies useful for the
1058 * majority of services. */
1060 /* First, pull in base system */
1061 if (s->meta.manager->running_as == MANAGER_SYSTEM) {
1063 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_BASIC_TARGET, NULL, true)) < 0)
1066 } else if (s->meta.manager->running_as == MANAGER_USER) {
1068 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SOCKETS_TARGET, NULL, true)) < 0)
1072 /* Second, activate normal shutdown */
1073 return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true);
1076 static int service_load(Unit *u) {
1078 Service *s = SERVICE(u);
1082 /* Load a .service file */
1083 if ((r = unit_load_fragment(u)) < 0)
1086 #ifdef HAVE_SYSV_COMPAT
1087 /* Load a classic init script as a fallback, if we couldn't find anything */
1088 if (u->meta.load_state == UNIT_STUB)
1089 if ((r = service_load_sysv(s)) < 0)
1093 /* Still nothing found? Then let's give up */
1094 if (u->meta.load_state == UNIT_STUB)
1097 /* We were able to load something, then let's add in the
1098 * dropin directories. */
1099 if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
1102 /* This is a new unit? Then let's add in some extras */
1103 if (u->meta.load_state == UNIT_LOADED) {
1104 if ((r = unit_add_exec_dependencies(u, &s->exec_context)) < 0)
1107 if ((r = unit_add_default_cgroups(u)) < 0)
1110 #ifdef HAVE_SYSV_COMPAT
1111 if ((r = sysv_fix_order(s)) < 0)
1115 if ((r = fsck_fix_order(s)) < 0)
1119 if ((r = unit_watch_bus_name(u, s->bus_name)) < 0)
1122 if (s->type == SERVICE_NOTIFY && s->notify_access == NOTIFY_NONE)
1123 s->notify_access = NOTIFY_MAIN;
1125 if (s->type == SERVICE_DBUS || s->bus_name)
1126 if ((r = unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_REQUIRES, SPECIAL_DBUS_TARGET, NULL, true)) < 0)
1129 if (s->meta.default_dependencies)
1130 if ((r = service_add_default_dependencies(s)) < 0)
1134 return service_verify(s);
1137 static void service_dump(Unit *u, FILE *f, const char *prefix) {
1139 ServiceExecCommand c;
1140 Service *s = SERVICE(u);
1141 const char *prefix2;
1146 p2 = strappend(prefix, "\t");
1147 prefix2 = p2 ? p2 : prefix;
1150 "%sService State: %s\n"
1151 "%sPermissionsStartOnly: %s\n"
1152 "%sRootDirectoryStartOnly: %s\n"
1153 "%sRemainAfterExit: %s\n"
1156 "%sNotifyAccess: %s\n",
1157 prefix, service_state_to_string(s->state),
1158 prefix, yes_no(s->permissions_start_only),
1159 prefix, yes_no(s->root_directory_start_only),
1160 prefix, yes_no(s->remain_after_exit),
1161 prefix, service_type_to_string(s->type),
1162 prefix, service_restart_to_string(s->restart),
1163 prefix, notify_access_to_string(s->notify_access));
1165 if (s->control_pid > 0)
1167 "%sControl PID: %lu\n",
1168 prefix, (unsigned long) s->control_pid);
1170 if (s->main_pid > 0)
1172 "%sMain PID: %lu\n",
1173 prefix, (unsigned long) s->main_pid);
1178 prefix, s->pid_file);
1183 "%sBus Name Good: %s\n",
1184 prefix, s->bus_name,
1185 prefix, yes_no(s->bus_name_good));
1187 exec_context_dump(&s->exec_context, f, prefix);
1189 for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
1191 if (!s->exec_command[c])
1194 fprintf(f, "%s-> %s:\n",
1195 prefix, service_exec_command_to_string(c));
1197 exec_command_dump_list(s->exec_command[c], f, prefix2);
1200 #ifdef HAVE_SYSV_COMPAT
1203 "%sSysV Init Script Path: %s\n"
1204 "%sSysV Init Script has LSB Header: %s\n"
1205 "%sSysVEnabled: %s\n",
1206 prefix, s->sysv_path,
1207 prefix, yes_no(s->sysv_has_lsb),
1208 prefix, yes_no(s->sysv_enabled));
1210 if (s->sysv_start_priority >= 0)
1212 "%sSysVStartPriority: %i\n",
1213 prefix, s->sysv_start_priority);
1215 if (s->sysv_runlevels)
1216 fprintf(f, "%sSysVRunLevels: %s\n",
1217 prefix, s->sysv_runlevels);
1220 if (s->fsck_passno > 0)
1222 "%sFsckPassNo: %i\n",
1223 prefix, s->fsck_passno);
1226 fprintf(f, "%sStatus Text: %s\n",
1227 prefix, s->status_text);
1232 static int service_load_pid_file(Service *s) {
1239 if (s->main_pid_known)
1242 assert(s->main_pid <= 0);
1247 if ((r = read_one_line_file(s->pid_file, &k)) < 0)
1250 r = parse_pid(k, &pid);
1256 if (kill(pid, 0) < 0 && errno != EPERM) {
1257 log_warning("PID %lu read from file %s does not exist. Your service or init script might be broken.",
1258 (unsigned long) pid, s->pid_file);
1262 if ((r = service_set_main_pid(s, pid)) < 0)
1265 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1266 /* FIXME: we need to do something here */
1272 static int service_search_main_pid(Service *s) {
1278 if (s->main_pid_known)
1281 assert(s->main_pid <= 0);
1283 if ((pid = cgroup_bonding_search_main_pid_list(s->meta.cgroup_bondings)) <= 0)
1286 if ((r = service_set_main_pid(s, pid)) < 0)
1289 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1290 /* FIXME: we need to do something here */
1296 static int service_get_sockets(Service *s, Set **_set) {
1305 if (s->socket_fd >= 0)
1308 if (!set_isempty(s->configured_sockets))
1311 /* Collects all Socket objects that belong to this
1312 * service. Note that a service might have multiple sockets
1313 * via multiple names. */
1315 if (!(set = set_new(NULL, NULL)))
1318 SET_FOREACH(t, s->meta.names, i) {
1322 /* Look for all socket objects that go by any of our
1323 * units and collect their fds */
1325 if (!(k = unit_name_change_suffix(t, ".socket"))) {
1330 p = manager_get_unit(s->meta.manager, k);
1336 if ((r = set_put(set, p)) < 0)
1348 static int service_notify_sockets_dead(Service *s) {
1350 Set *set, *free_set = NULL;
1356 /* Notifies all our sockets when we die */
1358 if (s->socket_fd >= 0)
1361 if (!set_isempty(s->configured_sockets))
1362 set = s->configured_sockets;
1364 if ((r = service_get_sockets(s, &free_set)) < 0)
1370 SET_FOREACH(sock, set, i)
1371 socket_notify_service_dead(sock);
1378 static void service_set_state(Service *s, ServiceState state) {
1379 ServiceState old_state;
1382 old_state = s->state;
1385 if (state != SERVICE_START_PRE &&
1386 state != SERVICE_START &&
1387 state != SERVICE_START_POST &&
1388 state != SERVICE_RELOAD &&
1389 state != SERVICE_STOP &&
1390 state != SERVICE_STOP_SIGTERM &&
1391 state != SERVICE_STOP_SIGKILL &&
1392 state != SERVICE_STOP_POST &&
1393 state != SERVICE_FINAL_SIGTERM &&
1394 state != SERVICE_FINAL_SIGKILL &&
1395 state != SERVICE_AUTO_RESTART)
1396 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1398 if (state != SERVICE_START &&
1399 state != SERVICE_START_POST &&
1400 state != SERVICE_RUNNING &&
1401 state != SERVICE_RELOAD &&
1402 state != SERVICE_STOP &&
1403 state != SERVICE_STOP_SIGTERM &&
1404 state != SERVICE_STOP_SIGKILL) {
1405 service_unwatch_main_pid(s);
1406 s->main_command = NULL;
1409 if (state != SERVICE_START_PRE &&
1410 state != SERVICE_START &&
1411 state != SERVICE_START_POST &&
1412 state != SERVICE_RELOAD &&
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 service_unwatch_control_pid(s);
1420 s->control_command = NULL;
1421 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1424 if (state == SERVICE_DEAD ||
1425 state == SERVICE_STOP ||
1426 state == SERVICE_STOP_SIGTERM ||
1427 state == SERVICE_STOP_SIGKILL ||
1428 state == SERVICE_STOP_POST ||
1429 state == SERVICE_FINAL_SIGTERM ||
1430 state == SERVICE_FINAL_SIGKILL ||
1431 state == SERVICE_FAILED ||
1432 state == SERVICE_AUTO_RESTART)
1433 service_notify_sockets_dead(s);
1435 if (state != SERVICE_START_PRE &&
1436 state != SERVICE_START &&
1437 state != SERVICE_START_POST &&
1438 state != SERVICE_RUNNING &&
1439 state != SERVICE_RELOAD &&
1440 state != SERVICE_STOP &&
1441 state != SERVICE_STOP_SIGTERM &&
1442 state != SERVICE_STOP_SIGKILL &&
1443 state != SERVICE_STOP_POST &&
1444 state != SERVICE_FINAL_SIGTERM &&
1445 state != SERVICE_FINAL_SIGKILL &&
1446 !(state == SERVICE_DEAD && s->meta.job)) {
1447 service_close_socket_fd(s);
1448 service_connection_unref(s);
1451 /* For the inactive states unit_notify() will trim the cgroup,
1452 * but for exit we have to do that ourselves... */
1453 if (state == SERVICE_EXITED)
1454 cgroup_bonding_trim_list(s->meta.cgroup_bondings, true);
1456 if (old_state != state)
1457 log_debug("%s changed %s -> %s", s->meta.id, service_state_to_string(old_state), service_state_to_string(state));
1459 unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state], !s->reload_failure);
1460 s->reload_failure = false;
1463 static int service_coldplug(Unit *u) {
1464 Service *s = SERVICE(u);
1468 assert(s->state == SERVICE_DEAD);
1470 if (s->deserialized_state != s->state) {
1472 if (s->deserialized_state == SERVICE_START_PRE ||
1473 s->deserialized_state == SERVICE_START ||
1474 s->deserialized_state == SERVICE_START_POST ||
1475 s->deserialized_state == SERVICE_RELOAD ||
1476 s->deserialized_state == SERVICE_STOP ||
1477 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1478 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1479 s->deserialized_state == SERVICE_STOP_POST ||
1480 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1481 s->deserialized_state == SERVICE_FINAL_SIGKILL ||
1482 s->deserialized_state == SERVICE_AUTO_RESTART) {
1484 if (s->deserialized_state == SERVICE_AUTO_RESTART || s->timeout_usec > 0) {
1487 k = s->deserialized_state == SERVICE_AUTO_RESTART ? s->restart_usec : s->timeout_usec;
1489 if ((r = unit_watch_timer(UNIT(s), k, &s->timer_watch)) < 0)
1494 if ((s->deserialized_state == SERVICE_START &&
1495 (s->type == SERVICE_FORKING ||
1496 s->type == SERVICE_DBUS ||
1497 s->type == SERVICE_ONESHOT ||
1498 s->type == SERVICE_NOTIFY)) ||
1499 s->deserialized_state == SERVICE_START_POST ||
1500 s->deserialized_state == SERVICE_RUNNING ||
1501 s->deserialized_state == SERVICE_RELOAD ||
1502 s->deserialized_state == SERVICE_STOP ||
1503 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1504 s->deserialized_state == SERVICE_STOP_SIGKILL)
1505 if (s->main_pid > 0)
1506 if ((r = unit_watch_pid(UNIT(s), s->main_pid)) < 0)
1509 if (s->deserialized_state == SERVICE_START_PRE ||
1510 s->deserialized_state == SERVICE_START ||
1511 s->deserialized_state == SERVICE_START_POST ||
1512 s->deserialized_state == SERVICE_RELOAD ||
1513 s->deserialized_state == SERVICE_STOP ||
1514 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1515 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1516 s->deserialized_state == SERVICE_STOP_POST ||
1517 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1518 s->deserialized_state == SERVICE_FINAL_SIGKILL)
1519 if (s->control_pid > 0)
1520 if ((r = unit_watch_pid(UNIT(s), s->control_pid)) < 0)
1523 service_set_state(s, s->deserialized_state);
1529 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
1533 unsigned rn_fds = 0;
1534 Set *set, *free_set = NULL;
1541 if (s->socket_fd >= 0)
1544 if (!set_isempty(s->configured_sockets))
1545 set = s->configured_sockets;
1547 if ((r = service_get_sockets(s, &free_set)) < 0)
1553 SET_FOREACH(sock, set, i) {
1557 if ((r = socket_collect_fds(sock, &cfds, &cn_fds)) < 0)
1569 if (!(t = new(int, rn_fds+cn_fds))) {
1575 memcpy(t, rfds, rn_fds);
1576 memcpy(t+rn_fds, cfds, cn_fds);
1581 rn_fds = rn_fds+cn_fds;
1599 static int service_spawn(
1604 bool apply_permissions,
1606 bool apply_tty_stdin,
1607 bool set_notify_socket,
1612 int *fds = NULL, *fdsbuf = NULL;
1613 unsigned n_fds = 0, n_env = 0;
1614 char **argv = NULL, **final_env = NULL, **our_env = NULL;
1621 s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1622 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1623 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
1625 if (s->socket_fd >= 0) {
1626 fds = &s->socket_fd;
1629 if ((r = service_collect_fds(s, &fdsbuf, &n_fds)) < 0)
1636 if (timeout && s->timeout_usec) {
1637 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1640 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1642 if (!(argv = unit_full_printf_strv(UNIT(s), c->argv))) {
1647 if (!(our_env = new0(char*, 4))) {
1652 if (set_notify_socket)
1653 if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=@%s", s->meta.manager->notify_socket) < 0) {
1658 if (s->main_pid > 0)
1659 if (asprintf(our_env + n_env++, "MAINPID=%lu", (unsigned long) s->main_pid) < 0) {
1664 if (!(final_env = strv_env_merge(2,
1665 s->meta.manager->environment,
1680 s->meta.manager->confirm_spawn,
1681 s->meta.cgroup_bondings,
1688 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1689 /* FIXME: we need to do something here */
1695 strv_free(final_env);
1705 strv_free(final_env);
1708 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1713 static int main_pid_good(Service *s) {
1716 /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1719 /* If we know the pid file, then lets just check if it is
1721 if (s->main_pid_known)
1722 return s->main_pid > 0;
1724 /* We don't know the pid */
1728 static int control_pid_good(Service *s) {
1731 return s->control_pid > 0;
1734 static int cgroup_good(Service *s) {
1739 if ((r = cgroup_bonding_is_empty_list(s->meta.cgroup_bondings)) < 0)
1745 static void service_enter_dead(Service *s, bool success, bool allow_restart) {
1752 if (allow_restart &&
1753 !s->forbid_restart &&
1754 (s->restart == SERVICE_RESTART_ALWAYS ||
1755 (s->restart == SERVICE_RESTART_ON_SUCCESS && !s->failure) ||
1756 (s->restart == SERVICE_RESTART_ON_FAILURE && s->failure) ||
1757 (s->restart == SERVICE_RESTART_ON_ABORT && s->failure &&
1758 (s->main_exec_status.code == CLD_KILLED ||
1759 s->main_exec_status.code == CLD_DUMPED)))) {
1761 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
1764 service_set_state(s, SERVICE_AUTO_RESTART);
1766 service_set_state(s, s->failure ? SERVICE_FAILED : SERVICE_DEAD);
1768 s->forbid_restart = false;
1773 log_warning("%s failed to run install restart timer: %s", s->meta.id, strerror(-r));
1774 service_enter_dead(s, false, false);
1777 static void service_enter_signal(Service *s, ServiceState state, bool success);
1779 static void service_enter_stop_post(Service *s, bool success) {
1786 service_unwatch_control_pid(s);
1788 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST])) {
1789 s->control_command_id = SERVICE_EXEC_STOP_POST;
1791 if ((r = service_spawn(s,
1795 !s->permissions_start_only,
1796 !s->root_directory_start_only,
1799 &s->control_pid)) < 0)
1803 service_set_state(s, SERVICE_STOP_POST);
1805 service_enter_signal(s, SERVICE_FINAL_SIGTERM, true);
1810 log_warning("%s failed to run 'stop-post' task: %s", s->meta.id, strerror(-r));
1811 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1814 static void service_enter_signal(Service *s, ServiceState state, bool success) {
1816 Set *pid_set = NULL;
1817 bool wait_for_exit = false;
1824 if (s->exec_context.kill_mode != KILL_NONE) {
1825 int sig = (state == SERVICE_STOP_SIGTERM || state == SERVICE_FINAL_SIGTERM) ? s->exec_context.kill_signal : SIGKILL;
1827 if (s->main_pid > 0) {
1828 if (kill(s->exec_context.kill_mode == KILL_PROCESS_GROUP ?
1830 s->main_pid, sig) < 0 && errno != ESRCH)
1832 log_warning("Failed to kill main process %li: %m", (long) s->main_pid);
1834 wait_for_exit = true;
1837 if (s->control_pid > 0) {
1838 if (kill(s->exec_context.kill_mode == KILL_PROCESS_GROUP ?
1840 s->control_pid, sig) < 0 && errno != ESRCH)
1842 log_warning("Failed to kill control process %li: %m", (long) s->control_pid);
1844 wait_for_exit = true;
1847 if (s->exec_context.kill_mode == KILL_CONTROL_GROUP) {
1849 if (!(pid_set = set_new(trivial_hash_func, trivial_compare_func))) {
1854 /* Exclude the main/control pids from being killed via the cgroup */
1855 if (s->main_pid > 0)
1856 if ((r = set_put(pid_set, LONG_TO_PTR(s->main_pid))) < 0)
1859 if (s->control_pid > 0)
1860 if ((r = set_put(pid_set, LONG_TO_PTR(s->control_pid))) < 0)
1863 if ((r = cgroup_bonding_kill_list(s->meta.cgroup_bondings, sig, pid_set)) < 0) {
1864 if (r != -EAGAIN && r != -ESRCH && r != -ENOENT)
1865 log_warning("Failed to kill control group: %s", strerror(-r));
1867 wait_for_exit = true;
1873 if (wait_for_exit) {
1874 if (s->timeout_usec > 0)
1875 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1878 service_set_state(s, state);
1879 } else if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1880 service_enter_stop_post(s, true);
1882 service_enter_dead(s, true, true);
1887 log_warning("%s failed to kill processes: %s", s->meta.id, strerror(-r));
1889 if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1890 service_enter_stop_post(s, false);
1892 service_enter_dead(s, false, true);
1898 static void service_enter_stop(Service *s, bool success) {
1906 service_unwatch_control_pid(s);
1908 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP])) {
1909 s->control_command_id = SERVICE_EXEC_STOP;
1911 if ((r = service_spawn(s,
1915 !s->permissions_start_only,
1916 !s->root_directory_start_only,
1919 &s->control_pid)) < 0)
1922 service_set_state(s, SERVICE_STOP);
1924 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
1929 log_warning("%s failed to run 'stop' task: %s", s->meta.id, strerror(-r));
1930 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1933 static void service_enter_running(Service *s, bool success) {
1934 int main_pid_ok, cgroup_ok;
1940 main_pid_ok = main_pid_good(s);
1941 cgroup_ok = cgroup_good(s);
1943 if ((main_pid_ok > 0 || (main_pid_ok < 0 && cgroup_ok != 0)) &&
1944 (s->bus_name_good || s->type != SERVICE_DBUS))
1945 service_set_state(s, SERVICE_RUNNING);
1946 else if (s->remain_after_exit)
1947 service_set_state(s, SERVICE_EXITED);
1949 service_enter_stop(s, true);
1952 static void service_enter_start_post(Service *s) {
1956 service_unwatch_control_pid(s);
1958 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_POST])) {
1959 s->control_command_id = SERVICE_EXEC_START_POST;
1961 if ((r = service_spawn(s,
1965 !s->permissions_start_only,
1966 !s->root_directory_start_only,
1969 &s->control_pid)) < 0)
1972 service_set_state(s, SERVICE_START_POST);
1974 service_enter_running(s, true);
1979 log_warning("%s failed to run 'start-post' task: %s", s->meta.id, strerror(-r));
1980 service_enter_stop(s, false);
1983 static void service_enter_start(Service *s) {
1990 assert(s->exec_command[SERVICE_EXEC_START]);
1991 assert(!s->exec_command[SERVICE_EXEC_START]->command_next || s->type == SERVICE_ONESHOT);
1993 if (s->type == SERVICE_FORKING)
1994 service_unwatch_control_pid(s);
1996 service_unwatch_main_pid(s);
1998 if (s->type == SERVICE_FORKING) {
1999 s->control_command_id = SERVICE_EXEC_START;
2000 c = s->control_command = s->exec_command[SERVICE_EXEC_START];
2002 s->main_command = NULL;
2004 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2005 s->control_command = NULL;
2007 c = s->main_command = s->exec_command[SERVICE_EXEC_START];
2010 if ((r = service_spawn(s,
2012 s->type == SERVICE_FORKING || s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY,
2017 s->notify_access != NOTIFY_NONE,
2021 if (s->type == SERVICE_SIMPLE) {
2022 /* For simple services we immediately start
2023 * the START_POST binaries. */
2025 service_set_main_pid(s, pid);
2026 service_enter_start_post(s);
2028 } else if (s->type == SERVICE_FORKING) {
2030 /* For forking services we wait until the start
2031 * process exited. */
2033 s->control_pid = pid;
2034 service_set_state(s, SERVICE_START);
2036 } else if (s->type == SERVICE_ONESHOT ||
2037 s->type == SERVICE_DBUS ||
2038 s->type == SERVICE_NOTIFY) {
2040 /* For oneshot services we wait until the start
2041 * process exited, too, but it is our main process. */
2043 /* For D-Bus services we know the main pid right away,
2044 * but wait for the bus name to appear on the
2045 * bus. Notify services are similar. */
2047 service_set_main_pid(s, pid);
2048 service_set_state(s, SERVICE_START);
2050 assert_not_reached("Unknown service type");
2055 log_warning("%s failed to run 'start' task: %s", s->meta.id, strerror(-r));
2056 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2059 static void service_enter_start_pre(Service *s) {
2064 service_unwatch_control_pid(s);
2066 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_PRE])) {
2067 s->control_command_id = SERVICE_EXEC_START_PRE;
2069 if ((r = service_spawn(s,
2073 !s->permissions_start_only,
2074 !s->root_directory_start_only,
2077 &s->control_pid)) < 0)
2080 service_set_state(s, SERVICE_START_PRE);
2082 service_enter_start(s);
2087 log_warning("%s failed to run 'start-pre' task: %s", s->meta.id, strerror(-r));
2088 service_enter_dead(s, false, true);
2091 static void service_enter_restart(Service *s) {
2096 dbus_error_init(&error);
2099 log_info("Job pending for unit, delaying automatic restart.");
2101 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
2105 service_enter_dead(s, true, false);
2107 if ((r = manager_add_job(s->meta.manager, JOB_START, UNIT(s), JOB_FAIL, false, &error, NULL)) < 0)
2110 log_debug("%s scheduled restart job.", s->meta.id);
2114 log_warning("%s failed to schedule restart job: %s", s->meta.id, bus_error(&error, -r));
2115 service_enter_dead(s, false, false);
2117 dbus_error_free(&error);
2120 static void service_enter_reload(Service *s) {
2125 service_unwatch_control_pid(s);
2127 if ((s->control_command = s->exec_command[SERVICE_EXEC_RELOAD])) {
2128 s->control_command_id = SERVICE_EXEC_RELOAD;
2130 if ((r = service_spawn(s,
2134 !s->permissions_start_only,
2135 !s->root_directory_start_only,
2138 &s->control_pid)) < 0)
2141 service_set_state(s, SERVICE_RELOAD);
2143 service_enter_running(s, true);
2148 log_warning("%s failed to run 'reload' task: %s", s->meta.id, strerror(-r));
2149 s->reload_failure = true;
2150 service_enter_running(s, true);
2153 static void service_run_next_control(Service *s, bool success) {
2157 assert(s->control_command);
2158 assert(s->control_command->command_next);
2163 assert(s->control_command_id != SERVICE_EXEC_START);
2165 s->control_command = s->control_command->command_next;
2166 service_unwatch_control_pid(s);
2168 if ((r = service_spawn(s,
2172 !s->permissions_start_only,
2173 !s->root_directory_start_only,
2174 s->control_command_id == SERVICE_EXEC_START_PRE ||
2175 s->control_command_id == SERVICE_EXEC_STOP_POST,
2177 &s->control_pid)) < 0)
2183 log_warning("%s failed to run next control task: %s", s->meta.id, strerror(-r));
2185 if (s->state == SERVICE_START_PRE)
2186 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2187 else if (s->state == SERVICE_STOP)
2188 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
2189 else if (s->state == SERVICE_STOP_POST)
2190 service_enter_dead(s, false, true);
2191 else if (s->state == SERVICE_RELOAD) {
2192 s->reload_failure = true;
2193 service_enter_running(s, true);
2195 service_enter_stop(s, false);
2198 static void service_run_next_main(Service *s, bool success) {
2203 assert(s->main_command);
2204 assert(s->main_command->command_next);
2205 assert(s->type == SERVICE_ONESHOT);
2210 s->main_command = s->main_command->command_next;
2211 service_unwatch_main_pid(s);
2213 if ((r = service_spawn(s,
2220 s->notify_access != NOTIFY_NONE,
2224 service_set_main_pid(s, pid);
2229 log_warning("%s failed to run next main task: %s", s->meta.id, strerror(-r));
2230 service_enter_stop(s, false);
2233 static int service_start(Unit *u) {
2234 Service *s = SERVICE(u);
2238 /* We cannot fulfill this request right now, try again later
2240 if (s->state == SERVICE_STOP ||
2241 s->state == SERVICE_STOP_SIGTERM ||
2242 s->state == SERVICE_STOP_SIGKILL ||
2243 s->state == SERVICE_STOP_POST ||
2244 s->state == SERVICE_FINAL_SIGTERM ||
2245 s->state == SERVICE_FINAL_SIGKILL)
2248 /* Already on it! */
2249 if (s->state == SERVICE_START_PRE ||
2250 s->state == SERVICE_START ||
2251 s->state == SERVICE_START_POST)
2254 assert(s->state == SERVICE_DEAD || s->state == SERVICE_FAILED || s->state == SERVICE_AUTO_RESTART);
2256 /* Make sure we don't enter a busy loop of some kind. */
2257 if (!ratelimit_test(&s->ratelimit)) {
2258 log_warning("%s start request repeated too quickly, refusing to start.", u->meta.id);
2263 s->main_pid_known = false;
2264 s->forbid_restart = false;
2266 service_enter_start_pre(s);
2270 static int service_stop(Unit *u) {
2271 Service *s = SERVICE(u);
2275 /* This is a user request, so don't do restarts on this
2277 s->forbid_restart = true;
2280 if (s->state == SERVICE_STOP ||
2281 s->state == SERVICE_STOP_SIGTERM ||
2282 s->state == SERVICE_STOP_SIGKILL ||
2283 s->state == SERVICE_STOP_POST ||
2284 s->state == SERVICE_FINAL_SIGTERM ||
2285 s->state == SERVICE_FINAL_SIGKILL)
2288 /* Don't allow a restart */
2289 if (s->state == SERVICE_AUTO_RESTART) {
2290 service_set_state(s, SERVICE_DEAD);
2294 /* If there's already something running we go directly into
2296 if (s->state == SERVICE_START_PRE ||
2297 s->state == SERVICE_START ||
2298 s->state == SERVICE_START_POST ||
2299 s->state == SERVICE_RELOAD) {
2300 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
2304 assert(s->state == SERVICE_RUNNING ||
2305 s->state == SERVICE_EXITED);
2307 service_enter_stop(s, true);
2311 static int service_reload(Unit *u) {
2312 Service *s = SERVICE(u);
2316 assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
2318 service_enter_reload(s);
2322 static bool service_can_reload(Unit *u) {
2323 Service *s = SERVICE(u);
2327 return !!s->exec_command[SERVICE_EXEC_RELOAD];
2330 static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
2331 Service *s = SERVICE(u);
2337 unit_serialize_item(u, f, "state", service_state_to_string(s->state));
2338 unit_serialize_item(u, f, "failure", yes_no(s->failure));
2340 if (s->control_pid > 0)
2341 unit_serialize_item_format(u, f, "control-pid", "%lu", (unsigned long) s->control_pid);
2343 if (s->main_pid_known && s->main_pid > 0)
2344 unit_serialize_item_format(u, f, "main-pid", "%lu", (unsigned long) s->main_pid);
2346 unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
2349 unit_serialize_item(u, f, "status-text", s->status_text);
2351 /* There's a minor uncleanliness here: if there are multiple
2352 * commands attached here, we will start from the first one
2354 if (s->control_command_id >= 0)
2355 unit_serialize_item(u, f, "control-command", service_exec_command_to_string(s->control_command_id));
2357 if (s->socket_fd >= 0) {
2360 if ((copy = fdset_put_dup(fds, s->socket_fd)) < 0)
2363 unit_serialize_item_format(u, f, "socket-fd", "%i", copy);
2366 if (s->main_exec_status.pid > 0) {
2367 unit_serialize_item_format(u, f, "main-exec-status-pid", "%lu", (unsigned long) s->main_exec_status.pid);
2368 dual_timestamp_serialize(f, "main-exec-status-start", &s->main_exec_status.start_timestamp);
2369 dual_timestamp_serialize(f, "main-exec-status-exit", &s->main_exec_status.exit_timestamp);
2371 if (dual_timestamp_is_set(&s->main_exec_status.exit_timestamp)) {
2372 unit_serialize_item_format(u, f, "main-exec-status-code", "%i", s->main_exec_status.code);
2373 unit_serialize_item_format(u, f, "main-exec-status-status", "%i", s->main_exec_status.status);
2380 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
2381 Service *s = SERVICE(u);
2388 if (streq(key, "state")) {
2391 if ((state = service_state_from_string(value)) < 0)
2392 log_debug("Failed to parse state value %s", value);
2394 s->deserialized_state = state;
2395 } else if (streq(key, "failure")) {
2398 if ((b = parse_boolean(value)) < 0)
2399 log_debug("Failed to parse failure value %s", value);
2401 s->failure = b || s->failure;
2402 } else if (streq(key, "control-pid")) {
2405 if (parse_pid(value, &pid) < 0)
2406 log_debug("Failed to parse control-pid value %s", value);
2408 s->control_pid = pid;
2409 } else if (streq(key, "main-pid")) {
2412 if (parse_pid(value, &pid) < 0)
2413 log_debug("Failed to parse main-pid value %s", value);
2415 service_set_main_pid(s, (pid_t) pid);
2416 } else if (streq(key, "main-pid-known")) {
2419 if ((b = parse_boolean(value)) < 0)
2420 log_debug("Failed to parse main-pid-known value %s", value);
2422 s->main_pid_known = b;
2423 } else if (streq(key, "status-text")) {
2426 if ((t = strdup(value))) {
2427 free(s->status_text);
2431 } else if (streq(key, "control-command")) {
2432 ServiceExecCommand id;
2434 if ((id = service_exec_command_from_string(value)) < 0)
2435 log_debug("Failed to parse exec-command value %s", value);
2437 s->control_command_id = id;
2438 s->control_command = s->exec_command[id];
2440 } else if (streq(key, "socket-fd")) {
2443 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2444 log_debug("Failed to parse socket-fd value %s", value);
2447 if (s->socket_fd >= 0)
2448 close_nointr_nofail(s->socket_fd);
2449 s->socket_fd = fdset_remove(fds, fd);
2451 } else if (streq(key, "main-exec-status-pid")) {
2454 if (parse_pid(value, &pid) < 0)
2455 log_debug("Failed to parse main-exec-status-pid value %s", value);
2457 s->main_exec_status.pid = pid;
2458 } else if (streq(key, "main-exec-status-code")) {
2461 if (safe_atoi(value, &i) < 0)
2462 log_debug("Failed to parse main-exec-status-code value %s", value);
2464 s->main_exec_status.code = i;
2465 } else if (streq(key, "main-exec-status-status")) {
2468 if (safe_atoi(value, &i) < 0)
2469 log_debug("Failed to parse main-exec-status-status value %s", value);
2471 s->main_exec_status.status = i;
2472 } else if (streq(key, "main-exec-status-start"))
2473 dual_timestamp_deserialize(value, &s->main_exec_status.start_timestamp);
2474 else if (streq(key, "main-exec-status-exit"))
2475 dual_timestamp_deserialize(value, &s->main_exec_status.exit_timestamp);
2477 log_debug("Unknown serialization key '%s'", key);
2482 static UnitActiveState service_active_state(Unit *u) {
2485 return state_translation_table[SERVICE(u)->state];
2488 static const char *service_sub_state_to_string(Unit *u) {
2491 return service_state_to_string(SERVICE(u)->state);
2494 #ifdef HAVE_SYSV_COMPAT
2495 static bool service_check_gc(Unit *u) {
2496 Service *s = SERVICE(u);
2500 return !!s->sysv_path;
2504 static bool service_check_snapshot(Unit *u) {
2505 Service *s = SERVICE(u);
2509 return !s->got_socket_fd;
2512 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2513 Service *s = SERVICE(u);
2519 if (!s->meta.fragment_path)
2520 success = is_clean_exit_lsb(code, status);
2522 success = is_clean_exit(code, status);
2524 if (s->main_pid == pid) {
2527 exec_status_exit(&s->main_exec_status, pid, code, status, s->exec_context.utmp_id);
2529 /* If this is not a forking service than the main
2530 * process got started and hence we copy the exit
2531 * status so that it is recorded both as main and as
2532 * control process exit status */
2533 if (s->main_command) {
2534 s->main_command->exec_status = s->main_exec_status;
2536 if (s->main_command->ignore)
2540 log_full(success ? LOG_DEBUG : LOG_NOTICE,
2541 "%s: main process exited, code=%s, status=%i", u->meta.id, sigchld_code_to_string(code), status);
2542 s->failure = s->failure || !success;
2544 if (s->main_command &&
2545 s->main_command->command_next &&
2548 /* There is another command to *
2549 * execute, so let's do that. */
2551 log_debug("%s running next main command for state %s", u->meta.id, service_state_to_string(s->state));
2552 service_run_next_main(s, success);
2556 /* The service exited, so the service is officially
2558 s->main_command = NULL;
2562 case SERVICE_START_POST:
2563 case SERVICE_RELOAD:
2565 /* Need to wait until the operation is
2570 if (s->type == SERVICE_ONESHOT) {
2571 /* This was our main goal, so let's go on */
2573 service_enter_start_post(s);
2575 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2578 assert(s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY);
2583 case SERVICE_RUNNING:
2584 service_enter_running(s, success);
2587 case SERVICE_STOP_SIGTERM:
2588 case SERVICE_STOP_SIGKILL:
2590 if (!control_pid_good(s))
2591 service_enter_stop_post(s, success);
2593 /* If there is still a control process, wait for that first */
2597 assert_not_reached("Uh, main process died at wrong time.");
2601 } else if (s->control_pid == pid) {
2605 if (s->control_command) {
2606 exec_status_exit(&s->control_command->exec_status, pid, code, status, s->exec_context.utmp_id);
2608 if (s->control_command->ignore)
2612 log_full(success ? LOG_DEBUG : LOG_NOTICE,
2613 "%s: control process exited, code=%s status=%i", u->meta.id, sigchld_code_to_string(code), status);
2614 s->failure = s->failure || !success;
2616 if (s->control_command &&
2617 s->control_command->command_next &&
2620 /* There is another command to *
2621 * execute, so let's do that. */
2623 log_debug("%s running next control command for state %s", u->meta.id, service_state_to_string(s->state));
2624 service_run_next_control(s, success);
2627 /* No further commands for this step, so let's
2628 * figure out what to do next */
2630 s->control_command = NULL;
2631 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2633 log_debug("%s got final SIGCHLD for state %s", u->meta.id, service_state_to_string(s->state));
2637 case SERVICE_START_PRE:
2639 service_enter_start(s);
2641 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2645 assert(s->type == SERVICE_FORKING);
2647 /* Let's try to load the pid
2648 * file here if we can. We
2649 * ignore the return value,
2650 * since the PID file might
2651 * actually be created by a
2652 * START_POST script */
2655 service_load_pid_file(s);
2656 service_search_main_pid(s);
2658 service_enter_start_post(s);
2660 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2664 case SERVICE_START_POST:
2665 if (success && s->pid_file && !s->main_pid_known) {
2668 /* Hmm, let's see if we can
2669 * load the pid now after the
2670 * start-post scripts got
2673 if ((r = service_load_pid_file(s)) < 0)
2674 log_warning("%s: failed to load PID file %s: %s", s->meta.id, s->pid_file, strerror(-r));
2679 case SERVICE_RELOAD:
2680 s->reload_failure = !success;
2681 service_enter_running(s, true);
2685 service_enter_signal(s, SERVICE_STOP_SIGTERM, success);
2688 case SERVICE_STOP_SIGTERM:
2689 case SERVICE_STOP_SIGKILL:
2690 if (main_pid_good(s) <= 0)
2691 service_enter_stop_post(s, success);
2693 /* If there is still a service
2694 * process around, wait until
2695 * that one quit, too */
2698 case SERVICE_STOP_POST:
2699 case SERVICE_FINAL_SIGTERM:
2700 case SERVICE_FINAL_SIGKILL:
2701 service_enter_dead(s, success, true);
2705 assert_not_reached("Uh, control process died at wrong time.");
2710 /* Notify clients about changed exit status */
2711 unit_add_to_dbus_queue(u);
2714 static void service_timer_event(Unit *u, uint64_t elapsed, Watch* w) {
2715 Service *s = SERVICE(u);
2718 assert(elapsed == 1);
2720 assert(w == &s->timer_watch);
2724 case SERVICE_START_PRE:
2726 log_warning("%s operation timed out. Terminating.", u->meta.id);
2727 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2730 case SERVICE_START_POST:
2731 log_warning("%s operation timed out. Stopping.", u->meta.id);
2732 service_enter_stop(s, false);
2735 case SERVICE_RELOAD:
2736 log_warning("%s operation timed out. Stopping.", u->meta.id);
2737 s->reload_failure = true;
2738 service_enter_running(s, true);
2742 log_warning("%s stopping timed out. Terminating.", u->meta.id);
2743 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
2746 case SERVICE_STOP_SIGTERM:
2747 if (s->exec_context.send_sigkill) {
2748 log_warning("%s stopping timed out. Killing.", u->meta.id);
2749 service_enter_signal(s, SERVICE_STOP_SIGKILL, false);
2751 log_warning("%s stopping timed out. Skipping SIGKILL.", u->meta.id);
2752 service_enter_stop_post(s, false);
2757 case SERVICE_STOP_SIGKILL:
2758 /* Uh, wie sent a SIGKILL and it is still not gone?
2759 * Must be something we cannot kill, so let's just be
2760 * weirded out and continue */
2762 log_warning("%s still around after SIGKILL. Ignoring.", u->meta.id);
2763 service_enter_stop_post(s, false);
2766 case SERVICE_STOP_POST:
2767 log_warning("%s stopping timed out (2). Terminating.", u->meta.id);
2768 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2771 case SERVICE_FINAL_SIGTERM:
2772 if (s->exec_context.send_sigkill) {
2773 log_warning("%s stopping timed out (2). Killing.", u->meta.id);
2774 service_enter_signal(s, SERVICE_FINAL_SIGKILL, false);
2776 log_warning("%s stopping timed out (2). Skipping SIGKILL. Entering failed mode.", u->meta.id);
2777 service_enter_dead(s, false, true);
2782 case SERVICE_FINAL_SIGKILL:
2783 log_warning("%s still around after SIGKILL (2). Entering failed mode.", u->meta.id);
2784 service_enter_dead(s, false, true);
2787 case SERVICE_AUTO_RESTART:
2788 log_info("%s holdoff time over, scheduling restart.", u->meta.id);
2789 service_enter_restart(s);
2793 assert_not_reached("Timeout at wrong time.");
2797 static void service_cgroup_notify_event(Unit *u) {
2798 Service *s = SERVICE(u);
2802 log_debug("%s: cgroup is empty", u->meta.id);
2806 /* Waiting for SIGCHLD is usually more interesting,
2807 * because it includes return codes/signals. Which is
2808 * why we ignore the cgroup events for most cases,
2809 * except when we don't know pid which to expect the
2812 case SERVICE_RUNNING:
2813 service_enter_running(s, true);
2816 case SERVICE_STOP_SIGTERM:
2817 case SERVICE_STOP_SIGKILL:
2818 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2819 service_enter_stop_post(s, true);
2823 case SERVICE_FINAL_SIGTERM:
2824 case SERVICE_FINAL_SIGKILL:
2825 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2826 service_enter_dead(s, true, true);
2835 static void service_notify_message(Unit *u, pid_t pid, char **tags) {
2836 Service *s = SERVICE(u);
2841 if (s->notify_access == NOTIFY_NONE) {
2842 log_warning("%s: Got notification message from PID %lu, but reception is disabled.",
2843 u->meta.id, (unsigned long) pid);
2847 if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
2848 log_warning("%s: Got notification message from PID %lu, but reception only permitted for PID %lu",
2849 u->meta.id, (unsigned long) pid, (unsigned long) s->main_pid);
2853 log_debug("%s: Got message", u->meta.id);
2855 /* Interpret MAINPID= */
2856 if ((e = strv_find_prefix(tags, "MAINPID=")) &&
2857 (s->state == SERVICE_START ||
2858 s->state == SERVICE_START_POST ||
2859 s->state == SERVICE_RUNNING ||
2860 s->state == SERVICE_RELOAD)) {
2862 if (parse_pid(e + 8, &pid) < 0)
2863 log_warning("Failed to parse notification message %s", e);
2865 log_debug("%s: got %s", u->meta.id, e);
2866 service_set_main_pid(s, pid);
2870 /* Interpret READY= */
2871 if (s->type == SERVICE_NOTIFY &&
2872 s->state == SERVICE_START &&
2873 strv_find(tags, "READY=1")) {
2874 log_debug("%s: got READY=1", u->meta.id);
2876 service_enter_start_post(s);
2879 /* Interpret STATUS= */
2880 if ((e = strv_find_prefix(tags, "STATUS="))) {
2884 if (!(t = strdup(e+7))) {
2885 log_error("Failed to allocate string.");
2889 log_debug("%s: got %s", u->meta.id, e);
2891 free(s->status_text);
2894 free(s->status_text);
2895 s->status_text = NULL;
2900 /* Notify clients about changed status or main pid */
2901 unit_add_to_dbus_queue(u);
2904 #ifdef HAVE_SYSV_COMPAT
2905 static int service_enumerate(Manager *m) {
2909 char *path = NULL, *fpath = NULL, *name = NULL;
2910 Set *runlevel_services[ELEMENTSOF(rcnd_table)], *shutdown_services = NULL;
2917 zero(runlevel_services);
2919 STRV_FOREACH(p, m->lookup_paths.sysvrcnd_path)
2920 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++) {
2925 if (asprintf(&path, "%s/%s", *p, rcnd_table[i].path) < 0) {
2933 if (!(d = opendir(path))) {
2934 if (errno != ENOENT)
2935 log_warning("opendir() failed on %s: %s", path, strerror(errno));
2940 while ((de = readdir(d))) {
2943 if (ignore_file(de->d_name))
2946 if (de->d_name[0] != 'S' && de->d_name[0] != 'K')
2949 if (strlen(de->d_name) < 4)
2952 a = undecchar(de->d_name[1]);
2953 b = undecchar(de->d_name[2]);
2960 if (asprintf(&fpath, "%s/%s/%s", *p, rcnd_table[i].path, de->d_name) < 0) {
2965 if (access(fpath, X_OK) < 0) {
2967 if (errno != ENOENT)
2968 log_warning("access() failed on %s: %s", fpath, strerror(errno));
2974 if (!(name = sysv_translate_name(de->d_name + 3))) {
2979 if ((r = manager_load_unit_prepare(m, name, NULL, NULL, &service)) < 0) {
2980 log_warning("Failed to prepare unit %s: %s", name, strerror(-r));
2984 if (de->d_name[0] == 'S') {
2986 if (rcnd_table[i].type == RUNLEVEL_UP || rcnd_table[i].type == RUNLEVEL_SYSINIT) {
2987 SERVICE(service)->sysv_start_priority =
2988 MAX(a*10 + b, SERVICE(service)->sysv_start_priority);
2990 SERVICE(service)->sysv_enabled = true;
2993 if ((r = set_ensure_allocated(&runlevel_services[i], trivial_hash_func, trivial_compare_func)) < 0)
2996 if ((r = set_put(runlevel_services[i], service)) < 0)
2999 } else if (de->d_name[0] == 'K' &&
3000 (rcnd_table[i].type == RUNLEVEL_DOWN ||
3001 rcnd_table[i].type == RUNLEVEL_SYSINIT)) {
3003 if ((r = set_ensure_allocated(&shutdown_services, trivial_hash_func, trivial_compare_func)) < 0)
3006 if ((r = set_put(shutdown_services, service)) < 0)
3012 /* Now we loaded all stubs and are aware of the lowest
3013 start-up priority for all services, not let's actually load
3014 the services, this will also tell us which services are
3015 actually native now */
3016 manager_dispatch_load_queue(m);
3018 /* If this is a native service, rely on native ways to pull in
3019 * a service, don't pull it in via sysv rcN.d links. */
3020 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++)
3021 SET_FOREACH(service, runlevel_services[i], j) {
3022 service = unit_follow_merge(service);
3024 if (service->meta.fragment_path)
3027 if ((r = unit_add_two_dependencies_by_name_inverse(service, UNIT_AFTER, UNIT_WANTS, rcnd_table[i].target, NULL, true)) < 0)
3031 /* We honour K links only for halt/reboot. For the normal
3032 * runlevels we assume the stop jobs will be implicitly added
3033 * by the core logic. Also, we don't really distuingish here
3034 * between the runlevels 0 and 6 and just add them to the
3035 * special shutdown target. On SUSE the boot.d/ runlevel is
3036 * also used for shutdown, so we add links for that too to the
3037 * shutdown target.*/
3038 SET_FOREACH(service, shutdown_services, j) {
3039 service = unit_follow_merge(service);
3041 if (service->meta.fragment_path)
3044 if ((r = unit_add_two_dependencies_by_name(service, UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true)) < 0)
3055 for (i = 0; i < ELEMENTSOF(rcnd_table); i++)
3056 set_free(runlevel_services[i]);
3057 set_free(shutdown_services);
3066 static void service_bus_name_owner_change(
3069 const char *old_owner,
3070 const char *new_owner) {
3072 Service *s = SERVICE(u);
3077 assert(streq(s->bus_name, name));
3078 assert(old_owner || new_owner);
3080 if (old_owner && new_owner)
3081 log_debug("%s's D-Bus name %s changed owner from %s to %s", u->meta.id, name, old_owner, new_owner);
3083 log_debug("%s's D-Bus name %s no longer registered by %s", u->meta.id, name, old_owner);
3085 log_debug("%s's D-Bus name %s now registered by %s", u->meta.id, name, new_owner);
3087 s->bus_name_good = !!new_owner;
3089 if (s->type == SERVICE_DBUS) {
3091 /* service_enter_running() will figure out what to
3093 if (s->state == SERVICE_RUNNING)
3094 service_enter_running(s, true);
3095 else if (s->state == SERVICE_START && new_owner)
3096 service_enter_start_post(s);
3098 } else if (new_owner &&
3100 (s->state == SERVICE_START ||
3101 s->state == SERVICE_START_POST ||
3102 s->state == SERVICE_RUNNING ||
3103 s->state == SERVICE_RELOAD)) {
3105 /* Try to acquire PID from bus service */
3106 log_debug("Trying to acquire PID from D-Bus name...");
3108 bus_query_pid(u->meta.manager, name);
3112 static void service_bus_query_pid_done(
3117 Service *s = SERVICE(u);
3122 log_debug("%s's D-Bus name %s is now owned by process %u", u->meta.id, name, (unsigned) pid);
3124 if (s->main_pid <= 0 &&
3125 (s->state == SERVICE_START ||
3126 s->state == SERVICE_START_POST ||
3127 s->state == SERVICE_RUNNING ||
3128 s->state == SERVICE_RELOAD))
3129 service_set_main_pid(s, pid);
3132 int service_set_socket_fd(Service *s, int fd, Socket *sock) {
3136 /* This is called by the socket code when instantiating a new
3137 * service for a stream socket and the socket needs to be
3140 if (s->meta.load_state != UNIT_LOADED)
3143 if (s->socket_fd >= 0)
3146 if (s->state != SERVICE_DEAD)
3150 s->got_socket_fd = true;
3151 s->accept_socket = sock;
3156 static void service_reset_failed(Unit *u) {
3157 Service *s = SERVICE(u);
3161 if (s->state == SERVICE_FAILED)
3162 service_set_state(s, SERVICE_DEAD);
3167 static int service_kill(Unit *u, KillWho who, KillMode mode, int signo, DBusError *error) {
3168 Service *s = SERVICE(u);
3170 Set *pid_set = NULL;
3174 if (s->main_pid <= 0 && who == KILL_MAIN) {
3175 dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "No main process to kill");
3179 if (s->control_pid <= 0 && who == KILL_CONTROL) {
3180 dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "No control process to kill");
3184 if (s->control_pid > 0)
3185 if (kill(mode == KILL_PROCESS_GROUP ? -s->control_pid : s->control_pid, signo) < 0)
3188 if (s->main_pid > 0)
3189 if (kill(mode == KILL_PROCESS_GROUP ? -s->main_pid : s->main_pid, signo) < 0)
3192 if (mode == KILL_CONTROL_GROUP) {
3195 if (!(pid_set = set_new(trivial_hash_func, trivial_compare_func)))
3198 /* Exclude the control/main pid from being killed via the cgroup */
3199 if (s->control_pid > 0)
3200 if ((q = set_put(pid_set, LONG_TO_PTR(s->control_pid))) < 0) {
3205 if (s->main_pid > 0)
3206 if ((q = set_put(pid_set, LONG_TO_PTR(s->main_pid))) < 0) {
3211 if ((q = cgroup_bonding_kill_list(s->meta.cgroup_bondings, signo, pid_set)) < 0)
3212 if (r != -EAGAIN && r != -ESRCH && r != -ENOENT)
3223 static const char* const service_state_table[_SERVICE_STATE_MAX] = {
3224 [SERVICE_DEAD] = "dead",
3225 [SERVICE_START_PRE] = "start-pre",
3226 [SERVICE_START] = "start",
3227 [SERVICE_START_POST] = "start-post",
3228 [SERVICE_RUNNING] = "running",
3229 [SERVICE_EXITED] = "exited",
3230 [SERVICE_RELOAD] = "reload",
3231 [SERVICE_STOP] = "stop",
3232 [SERVICE_STOP_SIGTERM] = "stop-sigterm",
3233 [SERVICE_STOP_SIGKILL] = "stop-sigkill",
3234 [SERVICE_STOP_POST] = "stop-post",
3235 [SERVICE_FINAL_SIGTERM] = "final-sigterm",
3236 [SERVICE_FINAL_SIGKILL] = "final-sigkill",
3237 [SERVICE_FAILED] = "failed",
3238 [SERVICE_AUTO_RESTART] = "auto-restart",
3241 DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
3243 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
3244 [SERVICE_RESTART_NO] = "no",
3245 [SERVICE_RESTART_ON_SUCCESS] = "on-success",
3246 [SERVICE_RESTART_ON_FAILURE] = "on-failure",
3247 [SERVICE_RESTART_ON_ABORT] = "on-abort",
3248 [SERVICE_RESTART_ALWAYS] = "always"
3251 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
3253 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
3254 [SERVICE_SIMPLE] = "simple",
3255 [SERVICE_FORKING] = "forking",
3256 [SERVICE_ONESHOT] = "oneshot",
3257 [SERVICE_DBUS] = "dbus",
3258 [SERVICE_NOTIFY] = "notify"
3261 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
3263 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
3264 [SERVICE_EXEC_START_PRE] = "ExecStartPre",
3265 [SERVICE_EXEC_START] = "ExecStart",
3266 [SERVICE_EXEC_START_POST] = "ExecStartPost",
3267 [SERVICE_EXEC_RELOAD] = "ExecReload",
3268 [SERVICE_EXEC_STOP] = "ExecStop",
3269 [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
3272 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
3274 static const char* const notify_access_table[_NOTIFY_ACCESS_MAX] = {
3275 [NOTIFY_NONE] = "none",
3276 [NOTIFY_MAIN] = "main",
3277 [NOTIFY_ALL] = "all"
3280 DEFINE_STRING_TABLE_LOOKUP(notify_access, NotifyAccess);
3282 const UnitVTable service_vtable = {
3283 .suffix = ".service",
3284 .show_status = true,
3286 .init = service_init,
3287 .done = service_done,
3288 .load = service_load,
3290 .coldplug = service_coldplug,
3292 .dump = service_dump,
3294 .start = service_start,
3295 .stop = service_stop,
3296 .reload = service_reload,
3298 .can_reload = service_can_reload,
3300 .kill = service_kill,
3302 .serialize = service_serialize,
3303 .deserialize_item = service_deserialize_item,
3305 .active_state = service_active_state,
3306 .sub_state_to_string = service_sub_state_to_string,
3308 #ifdef HAVE_SYSV_COMPAT
3309 .check_gc = service_check_gc,
3311 .check_snapshot = service_check_snapshot,
3313 .sigchld_event = service_sigchld_event,
3314 .timer_event = service_timer_event,
3316 .reset_failed = service_reset_failed,
3318 .cgroup_notify_empty = service_cgroup_notify_event,
3319 .notify_message = service_notify_message,
3321 .bus_name_owner_change = service_bus_name_owner_change,
3322 .bus_query_pid_done = service_bus_query_pid_done,
3324 .bus_interface = "org.freedesktop.systemd1.Service",
3325 .bus_message_handler = bus_service_message_handler,
3326 .bus_invalidating_properties = bus_service_invalidating_properties,
3328 #ifdef HAVE_SYSV_COMPAT
3329 .enumerate = service_enumerate