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");
250 #ifdef TARGET_FRUGALWARE
251 if (startswith(name, "rc."))
252 /* Drop Frugalware-style rc. prefix */
253 strcpy(stpcpy(r, name + 3), ".service");
256 /* Normal init scripts */
257 strcpy(stpcpy(r, name), ".service");
262 static int sysv_translate_facility(const char *name, const char *filename, char **_r) {
264 /* We silently ignore the $ prefix here. According to the LSB
265 * spec it simply indicates whether something is a
266 * standardized name or a distribution-specific one. Since we
267 * just follow what already exists and do not introduce new
268 * uses or names we don't care who introduced a new name. */
270 static const char * const table[] = {
271 /* LSB defined facilities */
272 "local_fs", SPECIAL_LOCAL_FS_TARGET,
273 "network", SPECIAL_NETWORK_TARGET,
274 "named", SPECIAL_NSS_LOOKUP_TARGET,
275 "portmap", SPECIAL_RPCBIND_TARGET,
276 "remote_fs", SPECIAL_REMOTE_FS_TARGET,
277 "syslog", SPECIAL_SYSLOG_TARGET,
278 "time", SPECIAL_RTC_SET_TARGET,
280 /* common extensions */
281 "mail-transfer-agent", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
282 "x-display-manager", SPECIAL_DISPLAY_MANAGER_SERVICE,
285 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU)
286 "mail-transport-agent", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
290 "MTA", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
291 "smtpdaemon", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
292 "httpd", SPECIAL_HTTP_DAEMON_TARGET,
296 "smtp", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
307 n = *name == '$' ? name + 1 : name;
309 for (i = 0; i < ELEMENTSOF(table); i += 2) {
311 if (!streq(table[i], n))
317 if (!(r = strdup(table[i+1])))
323 /* If we don't know this name, fallback heuristics to figure
324 * out whether something is a target or a service alias. */
327 if (!unit_prefix_is_valid(n))
330 /* Facilities starting with $ are most likely targets */
331 r = unit_name_build(n, NULL, ".target");
332 } else if (filename && streq(name, filename))
333 /* Names equalling the file name of the services are redundant */
336 /* Everything else we assume to be normal service names */
337 r = sysv_translate_name(n);
350 static int sysv_fix_order(Service *s) {
356 if (s->sysv_start_priority < 0)
359 /* For each pair of services where at least one lacks a LSB
360 * header, we use the start priority value to order things. */
362 LIST_FOREACH(units_per_type, other, s->meta.manager->units_per_type[UNIT_SERVICE]) {
365 bool special_s, special_t;
367 t = (Service*) other;
372 if (t->meta.load_state != UNIT_LOADED)
375 if (t->sysv_start_priority < 0)
378 /* If both units have modern headers we don't care
379 * about the priorities */
380 if ((s->meta.fragment_path || s->sysv_has_lsb) &&
381 (t->meta.fragment_path || t->sysv_has_lsb))
384 special_s = s->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, s->sysv_runlevels);
385 special_t = t->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, t->sysv_runlevels);
387 if (special_t && !special_s)
389 else if (special_s && !special_t)
391 else if (t->sysv_start_priority < s->sysv_start_priority)
393 else if (t->sysv_start_priority > s->sysv_start_priority)
398 /* FIXME: Maybe we should compare the name here lexicographically? */
400 if (!(r = unit_add_dependency(UNIT(s), d, UNIT(t), true)) < 0)
407 static ExecCommand *exec_command_new(const char *path, const char *arg1) {
410 if (!(c = new0(ExecCommand, 1)))
413 if (!(c->path = strdup(path))) {
418 if (!(c->argv = strv_new(path, arg1, NULL))) {
427 static int sysv_exec_commands(Service *s) {
431 assert(s->sysv_path);
433 if (!(c = exec_command_new(s->sysv_path, "start")))
435 exec_command_append_list(s->exec_command+SERVICE_EXEC_START, c);
437 if (!(c = exec_command_new(s->sysv_path, "stop")))
439 exec_command_append_list(s->exec_command+SERVICE_EXEC_STOP, c);
441 if (!(c = exec_command_new(s->sysv_path, "reload")))
443 exec_command_append_list(s->exec_command+SERVICE_EXEC_RELOAD, c);
448 static int service_load_sysv_path(Service *s, const char *path) {
459 char *short_description = NULL, *long_description = NULL, *chkconfig_description = NULL, *description;
466 if (!(f = fopen(path, "re"))) {
467 r = errno == ENOENT ? 0 : -errno;
472 if (!(s->sysv_path = strdup(path))) {
478 char l[LINE_MAX], *t;
480 if (!fgets(l, sizeof(l), f)) {
485 log_error("Failed to read configuration file '%s': %s", path, strerror(-r));
495 if (state == NORMAL && streq(t, "### BEGIN INIT INFO")) {
497 s->sysv_has_lsb = true;
501 if ((state == LSB_DESCRIPTION || state == LSB) && streq(t, "### END INIT INFO")) {
507 t += strspn(t, WHITESPACE);
509 if (state == NORMAL) {
511 /* Try to parse Red Hat style chkconfig headers */
513 if (startswith_no_case(t, "chkconfig:")) {
515 char runlevels[16], *k;
519 if (sscanf(t+10, "%15s %i %*i",
521 &start_priority) != 2) {
523 log_warning("[%s:%u] Failed to parse chkconfig line. Ignoring.", path, line);
527 /* A start priority gathered from the
528 * symlink farms is preferred over the
529 * data from the LSB header. */
530 if (start_priority < 0 || start_priority > 99)
531 log_warning("[%s:%u] Start priority out of range. Ignoring.", path, line);
532 else if (s->sysv_start_priority < 0)
533 s->sysv_start_priority = start_priority;
535 char_array_0(runlevels);
536 k = delete_chars(runlevels, WHITESPACE "-");
541 if (!(d = strdup(k))) {
546 free(s->sysv_runlevels);
547 s->sysv_runlevels = d;
550 } else if (startswith_no_case(t, "description:")) {
552 size_t k = strlen(t);
556 if (t[k-1] == '\\') {
561 if ((j = strstrip(t+12)) && *j) {
562 if (!(d = strdup(j))) {
569 free(chkconfig_description);
570 chkconfig_description = d;
572 } else if (startswith_no_case(t, "pidfile:")) {
579 if (!path_is_absolute(fn)) {
580 log_warning("[%s:%u] PID file not absolute. Ignoring.", path, line);
584 if (!(fn = strdup(fn))) {
593 } else if (state == DESCRIPTION) {
595 /* Try to parse Red Hat style description
598 size_t k = strlen(t);
606 if ((j = strstrip(t)) && *j) {
609 if (chkconfig_description)
610 asprintf(&d, "%s %s", chkconfig_description, j);
619 free(chkconfig_description);
620 chkconfig_description = d;
623 } else if (state == LSB || state == LSB_DESCRIPTION) {
625 if (startswith_no_case(t, "Provides:")) {
631 FOREACH_WORD_QUOTED(w, z, t+9, i) {
634 if (!(n = strndup(w, z))) {
639 r = sysv_translate_facility(n, file_name_from_path(path), &m);
648 if (unit_name_to_type(m) == UNIT_SERVICE)
649 r = unit_add_name(u, m);
651 r = unit_add_dependency_by_name(u, UNIT_BEFORE, m, NULL, true);
653 if (s->sysv_enabled) {
656 if ((k = unit_add_dependency_by_name_inverse(u, UNIT_WANTS, m, NULL, true)) < 0)
662 log_error("[%s:%u] Failed to add LSB Provides name %s, ignoring: %s", path, line, m, strerror(-r));
667 } else if (startswith_no_case(t, "Required-Start:") ||
668 startswith_no_case(t, "Should-Start:") ||
669 startswith_no_case(t, "X-Start-Before:") ||
670 startswith_no_case(t, "X-Start-After:")) {
676 FOREACH_WORD_QUOTED(w, z, strchr(t, ':')+1, i) {
679 if (!(n = strndup(w, z))) {
684 r = sysv_translate_facility(n, file_name_from_path(path), &m);
687 log_error("[%s:%u] Failed to translate LSB dependency %s, ignoring: %s", path, line, n, strerror(-r));
697 r = unit_add_dependency_by_name(u, startswith_no_case(t, "X-Start-Before:") ? UNIT_BEFORE : UNIT_AFTER, m, NULL, true);
700 log_error("[%s:%u] Failed to add dependency on %s, ignoring: %s", path, line, m, strerror(-r));
704 } else if (startswith_no_case(t, "Default-Start:")) {
709 k = delete_chars(t+14, WHITESPACE "-");
712 if (!(d = strdup(k))) {
717 free(s->sysv_runlevels);
718 s->sysv_runlevels = d;
721 } else if (startswith_no_case(t, "Description:")) {
724 state = LSB_DESCRIPTION;
726 if ((j = strstrip(t+12)) && *j) {
727 if (!(d = strdup(j))) {
734 free(long_description);
735 long_description = d;
737 } else if (startswith_no_case(t, "Short-Description:")) {
742 if ((j = strstrip(t+18)) && *j) {
743 if (!(d = strdup(j))) {
750 free(short_description);
751 short_description = d;
753 } else if (startswith_no_case(t, "X-Interactive:")) {
756 if ((b = parse_boolean(strstrip(t+14))) < 0) {
757 log_warning("[%s:%u] Couldn't parse interactive flag. Ignoring.", path, line);
762 s->exec_context.std_input = EXEC_INPUT_TTY;
764 s->exec_context.std_input = EXEC_INPUT_NULL;
766 } else if (state == LSB_DESCRIPTION) {
768 if (startswith(l, "#\t") || startswith(l, "# ")) {
771 if ((j = strstrip(t)) && *j) {
774 if (long_description)
775 asprintf(&d, "%s %s", long_description, t);
784 free(long_description);
785 long_description = d;
794 if ((r = sysv_exec_commands(s)) < 0)
797 if (s->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, s->sysv_runlevels)) {
798 /* If there a runlevels configured for this service
799 * but none of the standard ones, then we assume this
800 * is some special kind of service (which might be
801 * needed for early boot) and don't create any links
804 s->meta.default_dependencies = false;
806 /* Don't timeout special services during boot (like fsck) */
809 s->timeout_usec = DEFAULT_SYSV_TIMEOUT_USEC;
811 /* Special setting for all SysV services */
812 s->type = SERVICE_FORKING;
813 s->remain_after_exit = true;
814 s->restart = SERVICE_RESTART_NO;
815 s->exec_context.std_output =
816 (s->meta.manager->sysv_console || s->exec_context.std_input == EXEC_INPUT_TTY)
817 ? EXEC_OUTPUT_TTY : EXEC_OUTPUT_NULL;
818 s->exec_context.kill_mode = KILL_PROCESS_GROUP;
820 /* We use the long description only if
821 * no short description is set. */
823 if (short_description)
824 description = short_description;
825 else if (chkconfig_description)
826 description = chkconfig_description;
827 else if (long_description)
828 description = long_description;
835 if (!(d = strappend("LSB: ", description))) {
840 u->meta.description = d;
843 u->meta.load_state = UNIT_LOADED;
851 free(short_description);
852 free(long_description);
853 free(chkconfig_description);
858 static int service_load_sysv_name(Service *s, const char *name) {
864 /* For SysV services we strip the boot.*, rc.* and *.sh
865 * prefixes/suffixes. */
866 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU)
867 if (endswith(name, ".sh.service"))
872 if (startswith(name, "boot."))
876 #ifdef TARGET_FRUGALWARE
877 if (startswith(name, "rc."))
881 STRV_FOREACH(p, s->meta.manager->lookup_paths.sysvinit_path) {
885 if (asprintf(&path, "%s/%s", *p, name) < 0)
888 assert(endswith(path, ".service"));
889 path[strlen(path)-8] = 0;
891 r = service_load_sysv_path(s, path);
893 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU)
894 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
895 /* Try Debian style *.sh source'able init scripts */
897 r = service_load_sysv_path(s, path);
903 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
904 /* Try SUSE style boot.* init scripts */
906 if (asprintf(&path, "%s/boot.%s", *p, name) < 0)
909 /* Drop .service suffix */
910 path[strlen(path)-8] = 0;
911 r = service_load_sysv_path(s, path);
916 #ifdef TARGET_FRUGALWARE
917 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
918 /* Try Frugalware style rc.* init scripts */
920 if (asprintf(&path, "%s/rc.%s", *p, name) < 0)
923 /* Drop .service suffix */
924 path[strlen(path)-8] = 0;
925 r = service_load_sysv_path(s, path);
933 if ((s->meta.load_state != UNIT_STUB))
940 static int service_load_sysv(Service *s) {
947 /* Load service data from SysV init scripts, preferably with
950 if (strv_isempty(s->meta.manager->lookup_paths.sysvinit_path))
953 if ((t = s->meta.id))
954 if ((r = service_load_sysv_name(s, t)) < 0)
957 if (s->meta.load_state == UNIT_STUB)
958 SET_FOREACH(t, s->meta.names, i) {
962 if ((r = service_load_sysv_name(s, t)) < 0)
965 if (s->meta.load_state != UNIT_STUB)
973 static int fsck_fix_order(Service *s) {
979 if (s->fsck_passno <= 0)
982 /* For each pair of services where both have an fsck priority
983 * we order things based on it. */
985 LIST_FOREACH(units_per_type, other, s->meta.manager->units_per_type[UNIT_SERVICE]) {
989 t = (Service*) other;
994 if (t->meta.load_state != UNIT_LOADED)
997 if (t->fsck_passno <= 0)
1000 if (t->fsck_passno < s->fsck_passno)
1002 else if (t->fsck_passno > s->fsck_passno)
1007 if (!(r = unit_add_dependency(UNIT(s), d, UNIT(t), true)) < 0)
1014 static int service_verify(Service *s) {
1017 if (s->meta.load_state != UNIT_LOADED)
1020 if (!s->exec_command[SERVICE_EXEC_START]) {
1021 log_error("%s lacks ExecStart setting. Refusing.", s->meta.id);
1025 if (s->type != SERVICE_ONESHOT &&
1026 s->exec_command[SERVICE_EXEC_START]->command_next) {
1027 log_error("%s has more than one ExecStart setting, which is only allowed for Type=oneshot services. Refusing.", s->meta.id);
1031 if (s->type == SERVICE_DBUS && !s->bus_name) {
1032 log_error("%s is of type D-Bus but no D-Bus service name has been specified. Refusing.", s->meta.id);
1036 if (s->exec_context.pam_name && s->exec_context.kill_mode != KILL_CONTROL_GROUP) {
1037 log_error("%s has PAM enabled. Kill mode must be set to 'control-group'. Refusing.", s->meta.id);
1044 static int service_add_default_dependencies(Service *s) {
1049 /* Add a number of automatic dependencies useful for the
1050 * majority of services. */
1052 /* First, pull in base system */
1053 if (s->meta.manager->running_as == MANAGER_SYSTEM) {
1055 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_BASIC_TARGET, NULL, true)) < 0)
1058 } else if (s->meta.manager->running_as == MANAGER_USER) {
1060 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SOCKETS_TARGET, NULL, true)) < 0)
1064 /* Second, activate normal shutdown */
1065 return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true);
1068 static int service_load(Unit *u) {
1070 Service *s = SERVICE(u);
1074 /* Load a .service file */
1075 if ((r = unit_load_fragment(u)) < 0)
1078 #ifdef HAVE_SYSV_COMPAT
1079 /* Load a classic init script as a fallback, if we couldn't find anything */
1080 if (u->meta.load_state == UNIT_STUB)
1081 if ((r = service_load_sysv(s)) < 0)
1085 /* Still nothing found? Then let's give up */
1086 if (u->meta.load_state == UNIT_STUB)
1089 /* We were able to load something, then let's add in the
1090 * dropin directories. */
1091 if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
1094 /* This is a new unit? Then let's add in some extras */
1095 if (u->meta.load_state == UNIT_LOADED) {
1096 if ((r = unit_add_exec_dependencies(u, &s->exec_context)) < 0)
1099 if ((r = unit_add_default_cgroups(u)) < 0)
1102 #ifdef HAVE_SYSV_COMPAT
1103 if ((r = sysv_fix_order(s)) < 0)
1107 if ((r = fsck_fix_order(s)) < 0)
1111 if ((r = unit_watch_bus_name(u, s->bus_name)) < 0)
1114 if (s->type == SERVICE_NOTIFY && s->notify_access == NOTIFY_NONE)
1115 s->notify_access = NOTIFY_MAIN;
1117 if (s->type == SERVICE_DBUS || s->bus_name)
1118 if ((r = unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_REQUIRES, SPECIAL_DBUS_TARGET, NULL, true)) < 0)
1121 if (s->meta.default_dependencies)
1122 if ((r = service_add_default_dependencies(s)) < 0)
1126 return service_verify(s);
1129 static void service_dump(Unit *u, FILE *f, const char *prefix) {
1131 ServiceExecCommand c;
1132 Service *s = SERVICE(u);
1133 const char *prefix2;
1138 p2 = strappend(prefix, "\t");
1139 prefix2 = p2 ? p2 : prefix;
1142 "%sService State: %s\n"
1143 "%sPermissionsStartOnly: %s\n"
1144 "%sRootDirectoryStartOnly: %s\n"
1145 "%sRemainAfterExit: %s\n"
1148 "%sNotifyAccess: %s\n",
1149 prefix, service_state_to_string(s->state),
1150 prefix, yes_no(s->permissions_start_only),
1151 prefix, yes_no(s->root_directory_start_only),
1152 prefix, yes_no(s->remain_after_exit),
1153 prefix, service_type_to_string(s->type),
1154 prefix, service_restart_to_string(s->restart),
1155 prefix, notify_access_to_string(s->notify_access));
1157 if (s->control_pid > 0)
1159 "%sControl PID: %lu\n",
1160 prefix, (unsigned long) s->control_pid);
1162 if (s->main_pid > 0)
1164 "%sMain PID: %lu\n",
1165 prefix, (unsigned long) s->main_pid);
1170 prefix, s->pid_file);
1175 "%sBus Name Good: %s\n",
1176 prefix, s->bus_name,
1177 prefix, yes_no(s->bus_name_good));
1179 exec_context_dump(&s->exec_context, f, prefix);
1181 for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
1183 if (!s->exec_command[c])
1186 fprintf(f, "%s-> %s:\n",
1187 prefix, service_exec_command_to_string(c));
1189 exec_command_dump_list(s->exec_command[c], f, prefix2);
1192 #ifdef HAVE_SYSV_COMPAT
1195 "%sSysV Init Script Path: %s\n"
1196 "%sSysV Init Script has LSB Header: %s\n"
1197 "%sSysVEnabled: %s\n",
1198 prefix, s->sysv_path,
1199 prefix, yes_no(s->sysv_has_lsb),
1200 prefix, yes_no(s->sysv_enabled));
1202 if (s->sysv_start_priority >= 0)
1204 "%sSysVStartPriority: %i\n",
1205 prefix, s->sysv_start_priority);
1207 if (s->sysv_runlevels)
1208 fprintf(f, "%sSysVRunLevels: %s\n",
1209 prefix, s->sysv_runlevels);
1212 if (s->fsck_passno > 0)
1214 "%sFsckPassNo: %i\n",
1215 prefix, s->fsck_passno);
1218 fprintf(f, "%sStatus Text: %s\n",
1219 prefix, s->status_text);
1224 static int service_load_pid_file(Service *s) {
1231 if (s->main_pid_known)
1234 assert(s->main_pid <= 0);
1239 if ((r = read_one_line_file(s->pid_file, &k)) < 0)
1242 r = parse_pid(k, &pid);
1248 if (kill(pid, 0) < 0 && errno != EPERM) {
1249 log_warning("PID %lu read from file %s does not exist. Your service or init script might be broken.",
1250 (unsigned long) pid, s->pid_file);
1254 if ((r = service_set_main_pid(s, pid)) < 0)
1257 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1258 /* FIXME: we need to do something here */
1264 static int service_search_main_pid(Service *s) {
1270 if (s->main_pid_known)
1273 assert(s->main_pid <= 0);
1275 if ((pid = cgroup_bonding_search_main_pid_list(s->meta.cgroup_bondings)) <= 0)
1278 if ((r = service_set_main_pid(s, pid)) < 0)
1281 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1282 /* FIXME: we need to do something here */
1288 static int service_get_sockets(Service *s, Set **_set) {
1297 if (s->socket_fd >= 0)
1300 if (!set_isempty(s->configured_sockets))
1303 /* Collects all Socket objects that belong to this
1304 * service. Note that a service might have multiple sockets
1305 * via multiple names. */
1307 if (!(set = set_new(NULL, NULL)))
1310 SET_FOREACH(t, s->meta.names, i) {
1314 /* Look for all socket objects that go by any of our
1315 * units and collect their fds */
1317 if (!(k = unit_name_change_suffix(t, ".socket"))) {
1322 p = manager_get_unit(s->meta.manager, k);
1328 if ((r = set_put(set, p)) < 0)
1340 static int service_notify_sockets_dead(Service *s) {
1342 Set *set, *free_set = NULL;
1348 /* Notifies all our sockets when we die */
1350 if (s->socket_fd >= 0)
1353 if (!set_isempty(s->configured_sockets))
1354 set = s->configured_sockets;
1356 if ((r = service_get_sockets(s, &free_set)) < 0)
1362 SET_FOREACH(sock, set, i)
1363 socket_notify_service_dead(sock);
1370 static void service_set_state(Service *s, ServiceState state) {
1371 ServiceState old_state;
1374 old_state = s->state;
1377 if (state != SERVICE_START_PRE &&
1378 state != SERVICE_START &&
1379 state != SERVICE_START_POST &&
1380 state != SERVICE_RELOAD &&
1381 state != SERVICE_STOP &&
1382 state != SERVICE_STOP_SIGTERM &&
1383 state != SERVICE_STOP_SIGKILL &&
1384 state != SERVICE_STOP_POST &&
1385 state != SERVICE_FINAL_SIGTERM &&
1386 state != SERVICE_FINAL_SIGKILL &&
1387 state != SERVICE_AUTO_RESTART)
1388 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1390 if (state != SERVICE_START &&
1391 state != SERVICE_START_POST &&
1392 state != SERVICE_RUNNING &&
1393 state != SERVICE_RELOAD &&
1394 state != SERVICE_STOP &&
1395 state != SERVICE_STOP_SIGTERM &&
1396 state != SERVICE_STOP_SIGKILL)
1397 service_unwatch_main_pid(s);
1399 if (state != SERVICE_START_PRE &&
1400 state != SERVICE_START &&
1401 state != SERVICE_START_POST &&
1402 state != SERVICE_RELOAD &&
1403 state != SERVICE_STOP &&
1404 state != SERVICE_STOP_SIGTERM &&
1405 state != SERVICE_STOP_SIGKILL &&
1406 state != SERVICE_STOP_POST &&
1407 state != SERVICE_FINAL_SIGTERM &&
1408 state != SERVICE_FINAL_SIGKILL) {
1409 service_unwatch_control_pid(s);
1410 s->control_command = NULL;
1411 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1414 if (state == SERVICE_DEAD ||
1415 state == SERVICE_STOP ||
1416 state == SERVICE_STOP_SIGTERM ||
1417 state == SERVICE_STOP_SIGKILL ||
1418 state == SERVICE_STOP_POST ||
1419 state == SERVICE_FINAL_SIGTERM ||
1420 state == SERVICE_FINAL_SIGKILL ||
1421 state == SERVICE_FAILED ||
1422 state == SERVICE_AUTO_RESTART)
1423 service_notify_sockets_dead(s);
1425 if (state != SERVICE_START_PRE &&
1426 state != SERVICE_START &&
1427 state != SERVICE_START_POST &&
1428 state != SERVICE_RUNNING &&
1429 state != SERVICE_RELOAD &&
1430 state != SERVICE_STOP &&
1431 state != SERVICE_STOP_SIGTERM &&
1432 state != SERVICE_STOP_SIGKILL &&
1433 state != SERVICE_STOP_POST &&
1434 state != SERVICE_FINAL_SIGTERM &&
1435 state != SERVICE_FINAL_SIGKILL &&
1436 !(state == SERVICE_DEAD && s->meta.job)) {
1437 service_close_socket_fd(s);
1438 service_connection_unref(s);
1441 /* For the inactive states unit_notify() will trim the cgroup,
1442 * but for exit we have to do that ourselves... */
1443 if (state == SERVICE_EXITED)
1444 cgroup_bonding_trim_list(s->meta.cgroup_bondings, true);
1446 if (old_state != state)
1447 log_debug("%s changed %s -> %s", s->meta.id, service_state_to_string(old_state), service_state_to_string(state));
1449 unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state]);
1452 static int service_coldplug(Unit *u) {
1453 Service *s = SERVICE(u);
1457 assert(s->state == SERVICE_DEAD);
1459 if (s->deserialized_state != s->state) {
1461 if (s->deserialized_state == SERVICE_START_PRE ||
1462 s->deserialized_state == SERVICE_START ||
1463 s->deserialized_state == SERVICE_START_POST ||
1464 s->deserialized_state == SERVICE_RELOAD ||
1465 s->deserialized_state == SERVICE_STOP ||
1466 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1467 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1468 s->deserialized_state == SERVICE_STOP_POST ||
1469 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1470 s->deserialized_state == SERVICE_FINAL_SIGKILL ||
1471 s->deserialized_state == SERVICE_AUTO_RESTART) {
1473 if (s->deserialized_state == SERVICE_AUTO_RESTART || s->timeout_usec > 0) {
1476 k = s->deserialized_state == SERVICE_AUTO_RESTART ? s->restart_usec : s->timeout_usec;
1478 if ((r = unit_watch_timer(UNIT(s), k, &s->timer_watch)) < 0)
1483 if ((s->deserialized_state == SERVICE_START &&
1484 (s->type == SERVICE_FORKING ||
1485 s->type == SERVICE_DBUS ||
1486 s->type == SERVICE_ONESHOT ||
1487 s->type == SERVICE_NOTIFY)) ||
1488 s->deserialized_state == SERVICE_START_POST ||
1489 s->deserialized_state == SERVICE_RUNNING ||
1490 s->deserialized_state == SERVICE_RELOAD ||
1491 s->deserialized_state == SERVICE_STOP ||
1492 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1493 s->deserialized_state == SERVICE_STOP_SIGKILL)
1494 if (s->main_pid > 0)
1495 if ((r = unit_watch_pid(UNIT(s), s->main_pid)) < 0)
1498 if (s->deserialized_state == SERVICE_START_PRE ||
1499 s->deserialized_state == SERVICE_START ||
1500 s->deserialized_state == SERVICE_START_POST ||
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 s->deserialized_state == SERVICE_STOP_POST ||
1506 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1507 s->deserialized_state == SERVICE_FINAL_SIGKILL)
1508 if (s->control_pid > 0)
1509 if ((r = unit_watch_pid(UNIT(s), s->control_pid)) < 0)
1512 service_set_state(s, s->deserialized_state);
1518 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
1522 unsigned rn_fds = 0;
1523 Set *set, *free_set = NULL;
1530 if (s->socket_fd >= 0)
1533 if (!set_isempty(s->configured_sockets))
1534 set = s->configured_sockets;
1536 if ((r = service_get_sockets(s, &free_set)) < 0)
1542 SET_FOREACH(sock, set, i) {
1546 if ((r = socket_collect_fds(sock, &cfds, &cn_fds)) < 0)
1558 if (!(t = new(int, rn_fds+cn_fds))) {
1564 memcpy(t, rfds, rn_fds);
1565 memcpy(t+rn_fds, cfds, cn_fds);
1570 rn_fds = rn_fds+cn_fds;
1588 static int service_spawn(
1593 bool apply_permissions,
1595 bool apply_tty_stdin,
1596 bool set_notify_socket,
1601 int *fds = NULL, *fdsbuf = NULL;
1602 unsigned n_fds = 0, n_env = 0;
1603 char **argv = NULL, **final_env = NULL, **our_env = NULL;
1610 s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1611 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1612 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
1614 if (s->socket_fd >= 0) {
1615 fds = &s->socket_fd;
1618 if ((r = service_collect_fds(s, &fdsbuf, &n_fds)) < 0)
1625 if (timeout && s->timeout_usec) {
1626 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1629 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1631 if (!(argv = unit_full_printf_strv(UNIT(s), c->argv))) {
1636 if (!(our_env = new0(char*, 4))) {
1641 if (set_notify_socket)
1642 if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=@%s", s->meta.manager->notify_socket) < 0) {
1647 if (s->main_pid > 0)
1648 if (asprintf(our_env + n_env++, "MAINPID=%lu", (unsigned long) s->main_pid) < 0) {
1653 if (!(final_env = strv_env_merge(2,
1654 s->meta.manager->environment,
1669 s->meta.manager->confirm_spawn,
1670 s->meta.cgroup_bondings,
1677 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1678 /* FIXME: we need to do something here */
1684 strv_free(final_env);
1694 strv_free(final_env);
1697 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1702 static int main_pid_good(Service *s) {
1705 /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1708 /* If we know the pid file, then lets just check if it is
1710 if (s->main_pid_known)
1711 return s->main_pid > 0;
1713 /* We don't know the pid */
1717 static int control_pid_good(Service *s) {
1720 return s->control_pid > 0;
1723 static int cgroup_good(Service *s) {
1728 if ((r = cgroup_bonding_is_empty_list(s->meta.cgroup_bondings)) < 0)
1734 static void service_enter_dead(Service *s, bool success, bool allow_restart) {
1741 if (allow_restart &&
1742 !s->forbid_restart &&
1743 (s->restart == SERVICE_RESTART_ALWAYS ||
1744 (s->restart == SERVICE_RESTART_ON_SUCCESS && !s->failure) ||
1745 (s->restart == SERVICE_RESTART_ON_FAILURE && s->failure) ||
1746 (s->restart == SERVICE_RESTART_ON_ABORT && s->failure &&
1747 (s->main_exec_status.code == CLD_KILLED ||
1748 s->main_exec_status.code == CLD_DUMPED)))) {
1750 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
1753 service_set_state(s, SERVICE_AUTO_RESTART);
1755 service_set_state(s, s->failure ? SERVICE_FAILED : SERVICE_DEAD);
1757 s->forbid_restart = false;
1762 log_warning("%s failed to run install restart timer: %s", s->meta.id, strerror(-r));
1763 service_enter_dead(s, false, false);
1766 static void service_enter_signal(Service *s, ServiceState state, bool success);
1768 static void service_enter_stop_post(Service *s, bool success) {
1775 service_unwatch_control_pid(s);
1777 s->control_command_id = SERVICE_EXEC_STOP_POST;
1778 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST])) {
1779 if ((r = service_spawn(s,
1783 !s->permissions_start_only,
1784 !s->root_directory_start_only,
1787 &s->control_pid)) < 0)
1791 service_set_state(s, SERVICE_STOP_POST);
1793 service_enter_signal(s, SERVICE_FINAL_SIGTERM, true);
1798 log_warning("%s failed to run 'stop-post' task: %s", s->meta.id, strerror(-r));
1799 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1802 static void service_enter_signal(Service *s, ServiceState state, bool success) {
1804 Set *pid_set = NULL;
1805 bool wait_for_exit = false;
1812 if (s->exec_context.kill_mode != KILL_NONE) {
1813 int sig = (state == SERVICE_STOP_SIGTERM || state == SERVICE_FINAL_SIGTERM) ? s->exec_context.kill_signal : SIGKILL;
1815 if (s->main_pid > 0) {
1816 if (kill(s->exec_context.kill_mode == KILL_PROCESS_GROUP ?
1818 s->main_pid, sig) < 0 && errno != ESRCH)
1820 log_warning("Failed to kill main process %li: %m", (long) s->main_pid);
1822 wait_for_exit = true;
1825 if (s->control_pid > 0) {
1826 if (kill(s->exec_context.kill_mode == KILL_PROCESS_GROUP ?
1828 s->control_pid, sig) < 0 && errno != ESRCH)
1830 log_warning("Failed to kill control process %li: %m", (long) s->control_pid);
1832 wait_for_exit = true;
1835 if (s->exec_context.kill_mode == KILL_CONTROL_GROUP) {
1837 if (!(pid_set = set_new(trivial_hash_func, trivial_compare_func))) {
1842 /* Exclude the main/control pids from being killed via the cgroup */
1843 if (s->main_pid > 0)
1844 if ((r = set_put(pid_set, LONG_TO_PTR(s->main_pid))) < 0)
1847 if (s->control_pid > 0)
1848 if ((r = set_put(pid_set, LONG_TO_PTR(s->control_pid))) < 0)
1851 if ((r = cgroup_bonding_kill_list(s->meta.cgroup_bondings, sig, pid_set)) < 0) {
1852 if (r != -EAGAIN && r != -ESRCH && r != -ENOENT)
1853 log_warning("Failed to kill control group: %s", strerror(-r));
1855 wait_for_exit = true;
1861 if (wait_for_exit) {
1862 if (s->timeout_usec > 0)
1863 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1866 service_set_state(s, state);
1867 } else if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1868 service_enter_stop_post(s, true);
1870 service_enter_dead(s, true, true);
1875 log_warning("%s failed to kill processes: %s", s->meta.id, strerror(-r));
1877 if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1878 service_enter_stop_post(s, false);
1880 service_enter_dead(s, false, true);
1886 static void service_enter_stop(Service *s, bool success) {
1894 service_unwatch_control_pid(s);
1896 s->control_command_id = SERVICE_EXEC_STOP;
1897 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP])) {
1898 if ((r = service_spawn(s,
1902 !s->permissions_start_only,
1903 !s->root_directory_start_only,
1906 &s->control_pid)) < 0)
1909 service_set_state(s, SERVICE_STOP);
1911 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
1916 log_warning("%s failed to run 'stop' task: %s", s->meta.id, strerror(-r));
1917 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1920 static void service_enter_running(Service *s, bool success) {
1921 int main_pid_ok, cgroup_ok;
1927 main_pid_ok = main_pid_good(s);
1928 cgroup_ok = cgroup_good(s);
1930 if ((main_pid_ok > 0 || (main_pid_ok < 0 && cgroup_ok != 0)) &&
1931 (s->bus_name_good || s->type != SERVICE_DBUS))
1932 service_set_state(s, SERVICE_RUNNING);
1933 else if (s->remain_after_exit)
1934 service_set_state(s, SERVICE_EXITED);
1936 service_enter_stop(s, true);
1939 static void service_enter_start_post(Service *s) {
1943 service_unwatch_control_pid(s);
1945 s->control_command_id = SERVICE_EXEC_START_POST;
1946 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_POST])) {
1947 if ((r = service_spawn(s,
1951 !s->permissions_start_only,
1952 !s->root_directory_start_only,
1955 &s->control_pid)) < 0)
1958 service_set_state(s, SERVICE_START_POST);
1960 service_enter_running(s, true);
1965 log_warning("%s failed to run 'start-post' task: %s", s->meta.id, strerror(-r));
1966 service_enter_stop(s, false);
1969 static void service_enter_start(Service *s) {
1975 assert(s->exec_command[SERVICE_EXEC_START]);
1976 assert(!s->exec_command[SERVICE_EXEC_START]->command_next || s->type == SERVICE_ONESHOT);
1978 if (s->type == SERVICE_FORKING)
1979 service_unwatch_control_pid(s);
1981 service_unwatch_main_pid(s);
1983 s->control_command_id = SERVICE_EXEC_START;
1984 s->control_command = s->exec_command[SERVICE_EXEC_START];
1986 if ((r = service_spawn(s,
1988 s->type == SERVICE_FORKING || s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY,
1993 s->notify_access != NOTIFY_NONE,
1997 if (s->type == SERVICE_SIMPLE) {
1998 /* For simple services we immediately start
1999 * the START_POST binaries. */
2001 service_set_main_pid(s, pid);
2002 service_enter_start_post(s);
2004 } else if (s->type == SERVICE_FORKING) {
2006 /* For forking services we wait until the start
2007 * process exited. */
2009 s->control_pid = pid;
2010 service_set_state(s, SERVICE_START);
2012 } else if (s->type == SERVICE_ONESHOT ||
2013 s->type == SERVICE_DBUS ||
2014 s->type == SERVICE_NOTIFY) {
2016 /* For oneshot services we wait until the start
2017 * process exited, too, but it is our main process. */
2019 /* For D-Bus services we know the main pid right away,
2020 * but wait for the bus name to appear on the
2021 * bus. Notify services are similar. */
2023 service_set_main_pid(s, pid);
2024 service_set_state(s, SERVICE_START);
2026 assert_not_reached("Unknown service type");
2031 log_warning("%s failed to run 'start' task: %s", s->meta.id, strerror(-r));
2032 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2035 static void service_enter_start_pre(Service *s) {
2040 service_unwatch_control_pid(s);
2042 s->control_command_id = SERVICE_EXEC_START_PRE;
2043 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_PRE])) {
2044 if ((r = service_spawn(s,
2048 !s->permissions_start_only,
2049 !s->root_directory_start_only,
2052 &s->control_pid)) < 0)
2055 service_set_state(s, SERVICE_START_PRE);
2057 service_enter_start(s);
2062 log_warning("%s failed to run 'start-pre' task: %s", s->meta.id, strerror(-r));
2063 service_enter_dead(s, false, true);
2066 static void service_enter_restart(Service *s) {
2071 dbus_error_init(&error);
2074 log_info("Job pending for unit, delaying automatic restart.");
2076 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
2080 service_enter_dead(s, true, false);
2082 if ((r = manager_add_job(s->meta.manager, JOB_START, UNIT(s), JOB_FAIL, false, &error, NULL)) < 0)
2085 log_debug("%s scheduled restart job.", s->meta.id);
2089 log_warning("%s failed to schedule restart job: %s", s->meta.id, bus_error(&error, -r));
2090 service_enter_dead(s, false, false);
2092 dbus_error_free(&error);
2095 static void service_enter_reload(Service *s) {
2100 service_unwatch_control_pid(s);
2102 s->control_command_id = SERVICE_EXEC_RELOAD;
2103 if ((s->control_command = s->exec_command[SERVICE_EXEC_RELOAD])) {
2104 if ((r = service_spawn(s,
2108 !s->permissions_start_only,
2109 !s->root_directory_start_only,
2112 &s->control_pid)) < 0)
2115 service_set_state(s, SERVICE_RELOAD);
2117 service_enter_running(s, true);
2122 log_warning("%s failed to run 'reload' task: %s", s->meta.id, strerror(-r));
2123 service_enter_stop(s, false);
2126 static void service_run_next_control(Service *s, bool success) {
2130 assert(s->control_command);
2131 assert(s->control_command->command_next);
2136 assert(s->control_command_id != SERVICE_EXEC_START);
2138 s->control_command = s->control_command->command_next;
2139 service_unwatch_control_pid(s);
2141 if ((r = service_spawn(s,
2145 !s->permissions_start_only,
2146 !s->root_directory_start_only,
2147 s->control_command_id == SERVICE_EXEC_START_PRE ||
2148 s->control_command_id == SERVICE_EXEC_STOP_POST,
2150 &s->control_pid)) < 0)
2156 log_warning("%s failed to run next control task: %s", s->meta.id, strerror(-r));
2158 if (s->state == SERVICE_START_PRE)
2159 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2160 else if (s->state == SERVICE_STOP)
2161 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
2162 else if (s->state == SERVICE_STOP_POST)
2163 service_enter_dead(s, false, true);
2165 service_enter_stop(s, false);
2168 static void service_run_next_main(Service *s, bool success) {
2173 assert(s->control_command);
2174 assert(s->control_command->command_next);
2179 assert(s->control_command_id == SERVICE_EXEC_START);
2180 assert(s->type == SERVICE_ONESHOT);
2182 s->control_command = s->control_command->command_next;
2183 service_unwatch_main_pid(s);
2185 if ((r = service_spawn(s,
2192 s->notify_access != NOTIFY_NONE,
2196 service_set_main_pid(s, pid);
2201 log_warning("%s failed to run next main task: %s", s->meta.id, strerror(-r));
2202 service_enter_stop(s, false);
2205 static int service_start(Unit *u) {
2206 Service *s = SERVICE(u);
2210 /* We cannot fulfill this request right now, try again later
2212 if (s->state == SERVICE_STOP ||
2213 s->state == SERVICE_STOP_SIGTERM ||
2214 s->state == SERVICE_STOP_SIGKILL ||
2215 s->state == SERVICE_STOP_POST ||
2216 s->state == SERVICE_FINAL_SIGTERM ||
2217 s->state == SERVICE_FINAL_SIGKILL)
2220 /* Already on it! */
2221 if (s->state == SERVICE_START_PRE ||
2222 s->state == SERVICE_START ||
2223 s->state == SERVICE_START_POST)
2226 assert(s->state == SERVICE_DEAD || s->state == SERVICE_FAILED || s->state == SERVICE_AUTO_RESTART);
2228 /* Make sure we don't enter a busy loop of some kind. */
2229 if (!ratelimit_test(&s->ratelimit)) {
2230 log_warning("%s start request repeated too quickly, refusing to start.", u->meta.id);
2235 s->main_pid_known = false;
2236 s->forbid_restart = false;
2238 service_enter_start_pre(s);
2242 static int service_stop(Unit *u) {
2243 Service *s = SERVICE(u);
2247 /* This is a user request, so don't do restarts on this
2249 s->forbid_restart = true;
2252 if (s->state == SERVICE_STOP ||
2253 s->state == SERVICE_STOP_SIGTERM ||
2254 s->state == SERVICE_STOP_SIGKILL ||
2255 s->state == SERVICE_STOP_POST ||
2256 s->state == SERVICE_FINAL_SIGTERM ||
2257 s->state == SERVICE_FINAL_SIGKILL)
2260 /* Don't allow a restart */
2261 if (s->state == SERVICE_AUTO_RESTART) {
2262 service_set_state(s, SERVICE_DEAD);
2266 /* If there's already something running we go directly into
2268 if (s->state == SERVICE_START_PRE ||
2269 s->state == SERVICE_START ||
2270 s->state == SERVICE_START_POST ||
2271 s->state == SERVICE_RELOAD) {
2272 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
2276 assert(s->state == SERVICE_RUNNING ||
2277 s->state == SERVICE_EXITED);
2279 service_enter_stop(s, true);
2283 static int service_reload(Unit *u) {
2284 Service *s = SERVICE(u);
2288 assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
2290 service_enter_reload(s);
2294 static bool service_can_reload(Unit *u) {
2295 Service *s = SERVICE(u);
2299 return !!s->exec_command[SERVICE_EXEC_RELOAD];
2302 static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
2303 Service *s = SERVICE(u);
2309 unit_serialize_item(u, f, "state", service_state_to_string(s->state));
2310 unit_serialize_item(u, f, "failure", yes_no(s->failure));
2312 if (s->control_pid > 0)
2313 unit_serialize_item_format(u, f, "control-pid", "%lu", (unsigned long) s->control_pid);
2315 if (s->main_pid_known && s->main_pid > 0)
2316 unit_serialize_item_format(u, f, "main-pid", "%lu", (unsigned long) s->main_pid);
2318 unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
2321 unit_serialize_item(u, f, "status-text", s->status_text);
2323 /* There's a minor uncleanliness here: if there are multiple
2324 * commands attached here, we will start from the first one
2326 if (s->control_command_id >= 0)
2327 unit_serialize_item(u, f, "control-command", service_exec_command_to_string(s->control_command_id));
2329 if (s->socket_fd >= 0) {
2332 if ((copy = fdset_put_dup(fds, s->socket_fd)) < 0)
2335 unit_serialize_item_format(u, f, "socket-fd", "%i", copy);
2338 if (s->main_exec_status.pid > 0) {
2339 unit_serialize_item_format(u, f, "main-exec-status-pid", "%lu", (unsigned long) s->main_exec_status.pid);
2340 dual_timestamp_serialize(f, "main-exec-status-start", &s->main_exec_status.start_timestamp);
2341 dual_timestamp_serialize(f, "main-exec-status-exit", &s->main_exec_status.exit_timestamp);
2343 if (dual_timestamp_is_set(&s->main_exec_status.exit_timestamp)) {
2344 unit_serialize_item_format(u, f, "main-exec-status-code", "%i", s->main_exec_status.code);
2345 unit_serialize_item_format(u, f, "main-exec-status-status", "%i", s->main_exec_status.status);
2352 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
2353 Service *s = SERVICE(u);
2360 if (streq(key, "state")) {
2363 if ((state = service_state_from_string(value)) < 0)
2364 log_debug("Failed to parse state value %s", value);
2366 s->deserialized_state = state;
2367 } else if (streq(key, "failure")) {
2370 if ((b = parse_boolean(value)) < 0)
2371 log_debug("Failed to parse failure value %s", value);
2373 s->failure = b || s->failure;
2374 } else if (streq(key, "control-pid")) {
2377 if (parse_pid(value, &pid) < 0)
2378 log_debug("Failed to parse control-pid value %s", value);
2380 s->control_pid = pid;
2381 } else if (streq(key, "main-pid")) {
2384 if (parse_pid(value, &pid) < 0)
2385 log_debug("Failed to parse main-pid value %s", value);
2387 service_set_main_pid(s, (pid_t) pid);
2388 } else if (streq(key, "main-pid-known")) {
2391 if ((b = parse_boolean(value)) < 0)
2392 log_debug("Failed to parse main-pid-known value %s", value);
2394 s->main_pid_known = b;
2395 } else if (streq(key, "status-text")) {
2398 if ((t = strdup(value))) {
2399 free(s->status_text);
2403 } else if (streq(key, "control-command")) {
2404 ServiceExecCommand id;
2406 if ((id = service_exec_command_from_string(value)) < 0)
2407 log_debug("Failed to parse exec-command value %s", value);
2409 s->control_command_id = id;
2410 s->control_command = s->exec_command[id];
2412 } else if (streq(key, "socket-fd")) {
2415 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2416 log_debug("Failed to parse socket-fd value %s", value);
2419 if (s->socket_fd >= 0)
2420 close_nointr_nofail(s->socket_fd);
2421 s->socket_fd = fdset_remove(fds, fd);
2423 } else if (streq(key, "main-exec-status-pid")) {
2426 if (parse_pid(value, &pid) < 0)
2427 log_debug("Failed to parse main-exec-status-pid value %s", value);
2429 s->main_exec_status.pid = pid;
2430 } else if (streq(key, "main-exec-status-code")) {
2433 if (safe_atoi(value, &i) < 0)
2434 log_debug("Failed to parse main-exec-status-code value %s", value);
2436 s->main_exec_status.code = i;
2437 } else if (streq(key, "main-exec-status-status")) {
2440 if (safe_atoi(value, &i) < 0)
2441 log_debug("Failed to parse main-exec-status-status value %s", value);
2443 s->main_exec_status.status = i;
2444 } else if (streq(key, "main-exec-status-start"))
2445 dual_timestamp_deserialize(value, &s->main_exec_status.start_timestamp);
2446 else if (streq(key, "main-exec-status-exit"))
2447 dual_timestamp_deserialize(value, &s->main_exec_status.exit_timestamp);
2449 log_debug("Unknown serialization key '%s'", key);
2454 static UnitActiveState service_active_state(Unit *u) {
2457 return state_translation_table[SERVICE(u)->state];
2460 static const char *service_sub_state_to_string(Unit *u) {
2463 return service_state_to_string(SERVICE(u)->state);
2466 #ifdef HAVE_SYSV_COMPAT
2467 static bool service_check_gc(Unit *u) {
2468 Service *s = SERVICE(u);
2472 return !!s->sysv_path;
2476 static bool service_check_snapshot(Unit *u) {
2477 Service *s = SERVICE(u);
2481 return !s->got_socket_fd;
2484 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2485 Service *s = SERVICE(u);
2491 if (!s->meta.fragment_path)
2492 success = is_clean_exit_lsb(code, status);
2494 success = is_clean_exit(code, status);
2496 if (s->main_pid == pid) {
2499 exec_status_exit(&s->main_exec_status, pid, code, status, s->exec_context.utmp_id);
2501 if (s->type != SERVICE_FORKING && s->control_command) {
2502 s->control_command->exec_status = s->main_exec_status;
2504 if (s->control_command->ignore)
2508 log_full(success ? LOG_DEBUG : LOG_NOTICE,
2509 "%s: main process exited, code=%s, status=%i", u->meta.id, sigchld_code_to_string(code), status);
2510 s->failure = s->failure || !success;
2512 if (s->control_command &&
2513 s->control_command->command_next &&
2516 /* There is another command to *
2517 * execute, so let's do that. */
2519 log_debug("%s running next main command for state %s", u->meta.id, service_state_to_string(s->state));
2520 service_run_next_main(s, success);
2524 /* The service exited, so the service is officially
2527 s->control_command = NULL;
2528 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2532 case SERVICE_START_POST:
2533 case SERVICE_RELOAD:
2535 /* Need to wait until the operation is
2540 if (s->type == SERVICE_ONESHOT) {
2541 /* This was our main goal, so let's go on */
2543 service_enter_start_post(s);
2545 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2548 assert(s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY);
2553 case SERVICE_RUNNING:
2554 service_enter_running(s, success);
2557 case SERVICE_STOP_SIGTERM:
2558 case SERVICE_STOP_SIGKILL:
2560 if (!control_pid_good(s))
2561 service_enter_stop_post(s, success);
2563 /* If there is still a control process, wait for that first */
2567 assert_not_reached("Uh, main process died at wrong time.");
2571 } else if (s->control_pid == pid) {
2575 if (s->control_command) {
2576 exec_status_exit(&s->control_command->exec_status, pid, code, status, s->exec_context.utmp_id);
2578 if (s->control_command->ignore)
2582 log_full(success ? LOG_DEBUG : LOG_NOTICE,
2583 "%s: control process exited, code=%s status=%i", u->meta.id, sigchld_code_to_string(code), status);
2584 s->failure = s->failure || !success;
2586 if (s->control_command &&
2587 s->control_command->command_next &&
2590 /* There is another command to *
2591 * execute, so let's do that. */
2593 log_debug("%s running next control command for state %s", u->meta.id, service_state_to_string(s->state));
2594 service_run_next_control(s, success);
2597 /* No further commands for this step, so let's
2598 * figure out what to do next */
2600 s->control_command = NULL;
2601 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2603 log_debug("%s got final SIGCHLD for state %s", u->meta.id, service_state_to_string(s->state));
2607 case SERVICE_START_PRE:
2609 service_enter_start(s);
2611 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2615 assert(s->type == SERVICE_FORKING);
2617 /* Let's try to load the pid
2618 * file here if we can. We
2619 * ignore the return value,
2620 * since the PID file might
2621 * actually be created by a
2622 * START_POST script */
2625 service_load_pid_file(s);
2626 service_search_main_pid(s);
2628 service_enter_start_post(s);
2630 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2634 case SERVICE_START_POST:
2635 if (success && s->pid_file && !s->main_pid_known) {
2638 /* Hmm, let's see if we can
2639 * load the pid now after the
2640 * start-post scripts got
2643 if ((r = service_load_pid_file(s)) < 0)
2644 log_warning("%s: failed to load PID file %s: %s", s->meta.id, s->pid_file, strerror(-r));
2649 case SERVICE_RELOAD:
2651 service_enter_running(s, true);
2653 service_enter_stop(s, false);
2658 service_enter_signal(s, SERVICE_STOP_SIGTERM, success);
2661 case SERVICE_STOP_SIGTERM:
2662 case SERVICE_STOP_SIGKILL:
2663 if (main_pid_good(s) <= 0)
2664 service_enter_stop_post(s, success);
2666 /* If there is still a service
2667 * process around, wait until
2668 * that one quit, too */
2671 case SERVICE_STOP_POST:
2672 case SERVICE_FINAL_SIGTERM:
2673 case SERVICE_FINAL_SIGKILL:
2674 service_enter_dead(s, success, true);
2678 assert_not_reached("Uh, control process died at wrong time.");
2683 /* Notify clients about changed exit status */
2684 unit_add_to_dbus_queue(u);
2687 static void service_timer_event(Unit *u, uint64_t elapsed, Watch* w) {
2688 Service *s = SERVICE(u);
2691 assert(elapsed == 1);
2693 assert(w == &s->timer_watch);
2697 case SERVICE_START_PRE:
2699 log_warning("%s operation timed out. Terminating.", u->meta.id);
2700 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2703 case SERVICE_START_POST:
2704 case SERVICE_RELOAD:
2705 log_warning("%s operation timed out. Stopping.", u->meta.id);
2706 service_enter_stop(s, false);
2710 log_warning("%s stopping timed out. Terminating.", u->meta.id);
2711 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
2714 case SERVICE_STOP_SIGTERM:
2715 log_warning("%s stopping timed out. Killing.", u->meta.id);
2716 service_enter_signal(s, SERVICE_STOP_SIGKILL, false);
2719 case SERVICE_STOP_SIGKILL:
2720 /* Uh, wie sent a SIGKILL and it is still not gone?
2721 * Must be something we cannot kill, so let's just be
2722 * weirded out and continue */
2724 log_warning("%s still around after SIGKILL. Ignoring.", u->meta.id);
2725 service_enter_stop_post(s, false);
2728 case SERVICE_STOP_POST:
2729 log_warning("%s stopping timed out (2). Terminating.", u->meta.id);
2730 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2733 case SERVICE_FINAL_SIGTERM:
2734 log_warning("%s stopping timed out (2). Killing.", u->meta.id);
2735 service_enter_signal(s, SERVICE_FINAL_SIGKILL, false);
2738 case SERVICE_FINAL_SIGKILL:
2739 log_warning("%s still around after SIGKILL (2). Entering failed mode.", u->meta.id);
2740 service_enter_dead(s, false, true);
2743 case SERVICE_AUTO_RESTART:
2744 log_info("%s holdoff time over, scheduling restart.", u->meta.id);
2745 service_enter_restart(s);
2749 assert_not_reached("Timeout at wrong time.");
2753 static void service_cgroup_notify_event(Unit *u) {
2754 Service *s = SERVICE(u);
2758 log_debug("%s: cgroup is empty", u->meta.id);
2762 /* Waiting for SIGCHLD is usually more interesting,
2763 * because it includes return codes/signals. Which is
2764 * why we ignore the cgroup events for most cases,
2765 * except when we don't know pid which to expect the
2768 case SERVICE_RUNNING:
2769 service_enter_running(s, true);
2772 case SERVICE_STOP_SIGTERM:
2773 case SERVICE_STOP_SIGKILL:
2774 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2775 service_enter_stop_post(s, true);
2779 case SERVICE_FINAL_SIGTERM:
2780 case SERVICE_FINAL_SIGKILL:
2781 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2782 service_enter_dead(s, true, true);
2791 static void service_notify_message(Unit *u, pid_t pid, char **tags) {
2792 Service *s = SERVICE(u);
2797 if (s->notify_access == NOTIFY_NONE) {
2798 log_warning("%s: Got notification message from PID %lu, but reception is disabled.",
2799 u->meta.id, (unsigned long) pid);
2803 if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
2804 log_warning("%s: Got notification message from PID %lu, but reception only permitted for PID %lu",
2805 u->meta.id, (unsigned long) pid, (unsigned long) s->main_pid);
2809 log_debug("%s: Got message", u->meta.id);
2811 /* Interpret MAINPID= */
2812 if ((e = strv_find_prefix(tags, "MAINPID=")) &&
2813 (s->state == SERVICE_START ||
2814 s->state == SERVICE_START_POST ||
2815 s->state == SERVICE_RUNNING ||
2816 s->state == SERVICE_RELOAD)) {
2818 if (parse_pid(e + 8, &pid) < 0)
2819 log_warning("Failed to parse notification message %s", e);
2821 log_debug("%s: got %s", u->meta.id, e);
2822 service_set_main_pid(s, pid);
2826 /* Interpret READY= */
2827 if (s->type == SERVICE_NOTIFY &&
2828 s->state == SERVICE_START &&
2829 strv_find(tags, "READY=1")) {
2830 log_debug("%s: got READY=1", u->meta.id);
2832 service_enter_start_post(s);
2835 /* Interpret STATUS= */
2836 if ((e = strv_find_prefix(tags, "STATUS="))) {
2840 if (!(t = strdup(e+7))) {
2841 log_error("Failed to allocate string.");
2845 log_debug("%s: got %s", u->meta.id, e);
2847 free(s->status_text);
2850 free(s->status_text);
2851 s->status_text = NULL;
2856 /* Notify clients about changed status or main pid */
2857 unit_add_to_dbus_queue(u);
2860 #ifdef HAVE_SYSV_COMPAT
2861 static int service_enumerate(Manager *m) {
2865 char *path = NULL, *fpath = NULL, *name = NULL;
2866 Set *runlevel_services[ELEMENTSOF(rcnd_table)], *shutdown_services = NULL;
2873 zero(runlevel_services);
2875 STRV_FOREACH(p, m->lookup_paths.sysvrcnd_path)
2876 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++) {
2881 if (asprintf(&path, "%s/%s", *p, rcnd_table[i].path) < 0) {
2889 if (!(d = opendir(path))) {
2890 if (errno != ENOENT)
2891 log_warning("opendir() failed on %s: %s", path, strerror(errno));
2896 while ((de = readdir(d))) {
2899 if (ignore_file(de->d_name))
2902 if (de->d_name[0] != 'S' && de->d_name[0] != 'K')
2905 if (strlen(de->d_name) < 4)
2908 a = undecchar(de->d_name[1]);
2909 b = undecchar(de->d_name[2]);
2916 if (asprintf(&fpath, "%s/%s/%s", *p, rcnd_table[i].path, de->d_name) < 0) {
2921 if (access(fpath, X_OK) < 0) {
2923 if (errno != ENOENT)
2924 log_warning("access() failed on %s: %s", fpath, strerror(errno));
2930 if (!(name = sysv_translate_name(de->d_name + 3))) {
2935 if ((r = manager_load_unit_prepare(m, name, NULL, NULL, &service)) < 0) {
2936 log_warning("Failed to prepare unit %s: %s", name, strerror(-r));
2940 if (de->d_name[0] == 'S') {
2942 if (rcnd_table[i].type == RUNLEVEL_UP || rcnd_table[i].type == RUNLEVEL_SYSINIT) {
2943 SERVICE(service)->sysv_start_priority =
2944 MAX(a*10 + b, SERVICE(service)->sysv_start_priority);
2946 SERVICE(service)->sysv_enabled = true;
2949 if ((r = set_ensure_allocated(&runlevel_services[i], trivial_hash_func, trivial_compare_func)) < 0)
2952 if ((r = set_put(runlevel_services[i], service)) < 0)
2955 } else if (de->d_name[0] == 'K' &&
2956 (rcnd_table[i].type == RUNLEVEL_DOWN ||
2957 rcnd_table[i].type == RUNLEVEL_SYSINIT)) {
2959 if ((r = set_ensure_allocated(&shutdown_services, trivial_hash_func, trivial_compare_func)) < 0)
2962 if ((r = set_put(shutdown_services, service)) < 0)
2968 /* Now we loaded all stubs and are aware of the lowest
2969 start-up priority for all services, not let's actually load
2970 the services, this will also tell us which services are
2971 actually native now */
2972 manager_dispatch_load_queue(m);
2974 /* If this is a native service, rely on native ways to pull in
2975 * a service, don't pull it in via sysv rcN.d links. */
2976 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++)
2977 SET_FOREACH(service, runlevel_services[i], j) {
2978 service = unit_follow_merge(service);
2980 if (service->meta.fragment_path)
2983 if ((r = unit_add_two_dependencies_by_name_inverse(service, UNIT_AFTER, UNIT_WANTS, rcnd_table[i].target, NULL, true)) < 0)
2987 /* We honour K links only for halt/reboot. For the normal
2988 * runlevels we assume the stop jobs will be implicitly added
2989 * by the core logic. Also, we don't really distuingish here
2990 * between the runlevels 0 and 6 and just add them to the
2991 * special shutdown target. On SUSE the boot.d/ runlevel is
2992 * also used for shutdown, so we add links for that too to the
2993 * shutdown target.*/
2994 SET_FOREACH(service, shutdown_services, j) {
2995 service = unit_follow_merge(service);
2997 if (service->meta.fragment_path)
3000 if ((r = unit_add_two_dependencies_by_name(service, UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true)) < 0)
3011 for (i = 0; i < ELEMENTSOF(rcnd_table); i++)
3012 set_free(runlevel_services[i]);
3013 set_free(shutdown_services);
3022 static void service_bus_name_owner_change(
3025 const char *old_owner,
3026 const char *new_owner) {
3028 Service *s = SERVICE(u);
3033 assert(streq(s->bus_name, name));
3034 assert(old_owner || new_owner);
3036 if (old_owner && new_owner)
3037 log_debug("%s's D-Bus name %s changed owner from %s to %s", u->meta.id, name, old_owner, new_owner);
3039 log_debug("%s's D-Bus name %s no longer registered by %s", u->meta.id, name, old_owner);
3041 log_debug("%s's D-Bus name %s now registered by %s", u->meta.id, name, new_owner);
3043 s->bus_name_good = !!new_owner;
3045 if (s->type == SERVICE_DBUS) {
3047 /* service_enter_running() will figure out what to
3049 if (s->state == SERVICE_RUNNING)
3050 service_enter_running(s, true);
3051 else if (s->state == SERVICE_START && new_owner)
3052 service_enter_start_post(s);
3054 } else if (new_owner &&
3056 (s->state == SERVICE_START ||
3057 s->state == SERVICE_START_POST ||
3058 s->state == SERVICE_RUNNING ||
3059 s->state == SERVICE_RELOAD)) {
3061 /* Try to acquire PID from bus service */
3062 log_debug("Trying to acquire PID from D-Bus name...");
3064 bus_query_pid(u->meta.manager, name);
3068 static void service_bus_query_pid_done(
3073 Service *s = SERVICE(u);
3078 log_debug("%s's D-Bus name %s is now owned by process %u", u->meta.id, name, (unsigned) pid);
3080 if (s->main_pid <= 0 &&
3081 (s->state == SERVICE_START ||
3082 s->state == SERVICE_START_POST ||
3083 s->state == SERVICE_RUNNING ||
3084 s->state == SERVICE_RELOAD))
3085 service_set_main_pid(s, pid);
3088 int service_set_socket_fd(Service *s, int fd, Socket *sock) {
3092 /* This is called by the socket code when instantiating a new
3093 * service for a stream socket and the socket needs to be
3096 if (s->meta.load_state != UNIT_LOADED)
3099 if (s->socket_fd >= 0)
3102 if (s->state != SERVICE_DEAD)
3106 s->got_socket_fd = true;
3107 s->accept_socket = sock;
3112 static void service_reset_failed(Unit *u) {
3113 Service *s = SERVICE(u);
3117 if (s->state == SERVICE_FAILED)
3118 service_set_state(s, SERVICE_DEAD);
3123 static int service_kill(Unit *u, KillWho who, KillMode mode, int signo, DBusError *error) {
3124 Service *s = SERVICE(u);
3126 Set *pid_set = NULL;
3130 if (s->main_pid <= 0 && who == KILL_MAIN) {
3131 dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "No main process to kill");
3135 if (s->control_pid <= 0 && who == KILL_CONTROL) {
3136 dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "No control process to kill");
3140 if (s->control_pid > 0)
3141 if (kill(mode == KILL_PROCESS_GROUP ? -s->control_pid : s->control_pid, signo) < 0)
3144 if (s->main_pid > 0)
3145 if (kill(mode == KILL_PROCESS_GROUP ? -s->main_pid : s->main_pid, signo) < 0)
3148 if (mode == KILL_CONTROL_GROUP) {
3151 if (!(pid_set = set_new(trivial_hash_func, trivial_compare_func)))
3154 /* Exclude the control/main pid from being killed via the cgroup */
3155 if (s->control_pid > 0)
3156 if ((q = set_put(pid_set, LONG_TO_PTR(s->control_pid))) < 0) {
3161 if (s->main_pid > 0)
3162 if ((q = set_put(pid_set, LONG_TO_PTR(s->main_pid))) < 0) {
3167 if ((q = cgroup_bonding_kill_list(s->meta.cgroup_bondings, signo, pid_set)) < 0)
3168 if (r != -EAGAIN && r != -ESRCH && r != -ENOENT)
3179 static const char* const service_state_table[_SERVICE_STATE_MAX] = {
3180 [SERVICE_DEAD] = "dead",
3181 [SERVICE_START_PRE] = "start-pre",
3182 [SERVICE_START] = "start",
3183 [SERVICE_START_POST] = "start-post",
3184 [SERVICE_RUNNING] = "running",
3185 [SERVICE_EXITED] = "exited",
3186 [SERVICE_RELOAD] = "reload",
3187 [SERVICE_STOP] = "stop",
3188 [SERVICE_STOP_SIGTERM] = "stop-sigterm",
3189 [SERVICE_STOP_SIGKILL] = "stop-sigkill",
3190 [SERVICE_STOP_POST] = "stop-post",
3191 [SERVICE_FINAL_SIGTERM] = "final-sigterm",
3192 [SERVICE_FINAL_SIGKILL] = "final-sigkill",
3193 [SERVICE_FAILED] = "failed",
3194 [SERVICE_AUTO_RESTART] = "auto-restart",
3197 DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
3199 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
3200 [SERVICE_RESTART_NO] = "no",
3201 [SERVICE_RESTART_ON_SUCCESS] = "on-success",
3202 [SERVICE_RESTART_ON_FAILURE] = "on-failure",
3203 [SERVICE_RESTART_ON_ABORT] = "on-abort",
3204 [SERVICE_RESTART_ALWAYS] = "always"
3207 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
3209 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
3210 [SERVICE_SIMPLE] = "simple",
3211 [SERVICE_FORKING] = "forking",
3212 [SERVICE_ONESHOT] = "oneshot",
3213 [SERVICE_DBUS] = "dbus",
3214 [SERVICE_NOTIFY] = "notify"
3217 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
3219 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
3220 [SERVICE_EXEC_START_PRE] = "ExecStartPre",
3221 [SERVICE_EXEC_START] = "ExecStart",
3222 [SERVICE_EXEC_START_POST] = "ExecStartPost",
3223 [SERVICE_EXEC_RELOAD] = "ExecReload",
3224 [SERVICE_EXEC_STOP] = "ExecStop",
3225 [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
3228 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
3230 static const char* const notify_access_table[_NOTIFY_ACCESS_MAX] = {
3231 [NOTIFY_NONE] = "none",
3232 [NOTIFY_MAIN] = "main",
3233 [NOTIFY_ALL] = "all"
3236 DEFINE_STRING_TABLE_LOOKUP(notify_access, NotifyAccess);
3238 const UnitVTable service_vtable = {
3239 .suffix = ".service",
3240 .show_status = true,
3242 .init = service_init,
3243 .done = service_done,
3244 .load = service_load,
3246 .coldplug = service_coldplug,
3248 .dump = service_dump,
3250 .start = service_start,
3251 .stop = service_stop,
3252 .reload = service_reload,
3254 .can_reload = service_can_reload,
3256 .kill = service_kill,
3258 .serialize = service_serialize,
3259 .deserialize_item = service_deserialize_item,
3261 .active_state = service_active_state,
3262 .sub_state_to_string = service_sub_state_to_string,
3264 #ifdef HAVE_SYSV_COMPAT
3265 .check_gc = service_check_gc,
3267 .check_snapshot = service_check_snapshot,
3269 .sigchld_event = service_sigchld_event,
3270 .timer_event = service_timer_event,
3272 .reset_failed = service_reset_failed,
3274 .cgroup_notify_empty = service_cgroup_notify_event,
3275 .notify_message = service_notify_message,
3277 .bus_name_owner_change = service_bus_name_owner_change,
3278 .bus_query_pid_done = service_bus_query_pid_done,
3280 .bus_interface = "org.freedesktop.systemd1.Service",
3281 .bus_message_handler = bus_service_message_handler,
3282 .bus_invalidating_properties = bus_service_invalidating_properties,
3284 #ifdef HAVE_SYSV_COMPAT
3285 .enumerate = service_enumerate