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 (startswith(name, "boot."))
241 /* Drop SuSE-style boot. prefix */
242 strcpy(stpcpy(r, name + 5), ".service");
243 else if (endswith(name, ".sh"))
244 /* Drop Debian-style .sh suffix */
245 strcpy(stpcpy(r, name) - 3, ".service");
247 else if (startswith(name, "@"))
248 /* Drop Arch-style background prefix */
249 strcpy(stpcpy(r, name + 1), ".service");
252 /* Normal init scripts */
253 strcpy(stpcpy(r, name), ".service");
258 static int sysv_translate_facility(const char *name, const char *filename, char **_r) {
260 /* We silently ignore the $ prefix here. According to the LSB
261 * spec it simply indicates whether something is a
262 * standardized name or a distribution-specific one. Since we
263 * just follow what already exists and do not introduce new
264 * uses or names we don't care who introduced a new name. */
266 static const char * const table[] = {
267 /* LSB defined facilities */
268 "local_fs", SPECIAL_LOCAL_FS_TARGET,
269 "network", SPECIAL_NETWORK_TARGET,
270 "named", SPECIAL_NSS_LOOKUP_TARGET,
271 "portmap", SPECIAL_RPCBIND_TARGET,
272 "remote_fs", SPECIAL_REMOTE_FS_TARGET,
273 "syslog", SPECIAL_SYSLOG_TARGET,
274 "time", SPECIAL_RTC_SET_TARGET,
276 /* common extensions */
277 "mail-transfer-agent", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
278 "x-display-manager", SPECIAL_DISPLAY_MANAGER_SERVICE,
281 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU)
282 "mail-transport-agent", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
286 "MTA", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
287 "smtpdaemon", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
288 "httpd", SPECIAL_HTTP_DAEMON_TARGET,
292 "smtp", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
303 n = *name == '$' ? name + 1 : name;
305 for (i = 0; i < ELEMENTSOF(table); i += 2) {
307 if (!streq(table[i], n))
313 if (!(r = strdup(table[i+1])))
319 /* If we don't know this name, fallback heuristics to figure
320 * out whether something is a target or a service alias. */
323 /* Facilities starting with $ are most likely targets */
324 r = unit_name_build(n, NULL, ".target");
325 else if (filename && streq(name, filename))
326 /* Names equalling the file name of the services are redundant */
329 /* Everything else we assume to be normal service names */
330 r = sysv_translate_name(n);
343 static int sysv_fix_order(Service *s) {
349 if (s->sysv_start_priority < 0)
352 /* For each pair of services where at least one lacks a LSB
353 * header, we use the start priority value to order things. */
355 LIST_FOREACH(units_per_type, other, s->meta.manager->units_per_type[UNIT_SERVICE]) {
358 bool special_s, special_t;
360 t = (Service*) other;
365 if (t->meta.load_state != UNIT_LOADED)
368 if (t->sysv_start_priority < 0)
371 /* If both units have modern headers we don't care
372 * about the priorities */
373 if ((s->meta.fragment_path || s->sysv_has_lsb) &&
374 (t->meta.fragment_path || t->sysv_has_lsb))
377 special_s = s->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, s->sysv_runlevels);
378 special_t = t->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, t->sysv_runlevels);
380 if (special_t && !special_s)
382 else if (special_s && !special_t)
384 else if (t->sysv_start_priority < s->sysv_start_priority)
386 else if (t->sysv_start_priority > s->sysv_start_priority)
391 /* FIXME: Maybe we should compare the name here lexicographically? */
393 if (!(r = unit_add_dependency(UNIT(s), d, UNIT(t), true)) < 0)
400 static ExecCommand *exec_command_new(const char *path, const char *arg1) {
403 if (!(c = new0(ExecCommand, 1)))
406 if (!(c->path = strdup(path))) {
411 if (!(c->argv = strv_new(path, arg1, NULL))) {
420 static int sysv_exec_commands(Service *s) {
424 assert(s->sysv_path);
426 if (!(c = exec_command_new(s->sysv_path, "start")))
428 exec_command_append_list(s->exec_command+SERVICE_EXEC_START, c);
430 if (!(c = exec_command_new(s->sysv_path, "stop")))
432 exec_command_append_list(s->exec_command+SERVICE_EXEC_STOP, c);
434 if (!(c = exec_command_new(s->sysv_path, "reload")))
436 exec_command_append_list(s->exec_command+SERVICE_EXEC_RELOAD, c);
441 static int service_load_sysv_path(Service *s, const char *path) {
452 char *short_description = NULL, *long_description = NULL, *chkconfig_description = NULL, *description;
459 if (!(f = fopen(path, "re"))) {
460 r = errno == ENOENT ? 0 : -errno;
465 if (!(s->sysv_path = strdup(path))) {
471 char l[LINE_MAX], *t;
473 if (!fgets(l, sizeof(l), f)) {
478 log_error("Failed to read configuration file '%s': %s", path, strerror(-r));
488 if (state == NORMAL && streq(t, "### BEGIN INIT INFO")) {
490 s->sysv_has_lsb = true;
494 if ((state == LSB_DESCRIPTION || state == LSB) && streq(t, "### END INIT INFO")) {
500 t += strspn(t, WHITESPACE);
502 if (state == NORMAL) {
504 /* Try to parse Red Hat style chkconfig headers */
506 if (startswith_no_case(t, "chkconfig:")) {
508 char runlevels[16], *k;
512 if (sscanf(t+10, "%15s %i %*i",
514 &start_priority) != 2) {
516 log_warning("[%s:%u] Failed to parse chkconfig line. Ignoring.", path, line);
520 /* A start priority gathered from the
521 * symlink farms is preferred over the
522 * data from the LSB header. */
523 if (start_priority < 0 || start_priority > 99)
524 log_warning("[%s:%u] Start priority out of range. Ignoring.", path, line);
525 else if (s->sysv_start_priority < 0)
526 s->sysv_start_priority = start_priority;
528 char_array_0(runlevels);
529 k = delete_chars(runlevels, WHITESPACE "-");
534 if (!(d = strdup(k))) {
539 free(s->sysv_runlevels);
540 s->sysv_runlevels = d;
543 } else if (startswith_no_case(t, "description:")) {
545 size_t k = strlen(t);
549 if (t[k-1] == '\\') {
554 if ((j = strstrip(t+12)) && *j) {
555 if (!(d = strdup(j))) {
562 free(chkconfig_description);
563 chkconfig_description = d;
565 } else if (startswith_no_case(t, "pidfile:")) {
572 if (!path_is_absolute(fn)) {
573 log_warning("[%s:%u] PID file not absolute. Ignoring.", path, line);
577 if (!(fn = strdup(fn))) {
586 } else if (state == DESCRIPTION) {
588 /* Try to parse Red Hat style description
591 size_t k = strlen(t);
599 if ((j = strstrip(t)) && *j) {
602 if (chkconfig_description)
603 asprintf(&d, "%s %s", chkconfig_description, j);
612 free(chkconfig_description);
613 chkconfig_description = d;
616 } else if (state == LSB || state == LSB_DESCRIPTION) {
618 if (startswith_no_case(t, "Provides:")) {
624 FOREACH_WORD_QUOTED(w, z, t+9, i) {
627 if (!(n = strndup(w, z))) {
632 r = sysv_translate_facility(n, file_name_from_path(path), &m);
641 if (unit_name_to_type(m) == UNIT_SERVICE)
642 r = unit_add_name(u, m);
644 r = unit_add_dependency_by_name(u, UNIT_BEFORE, m, NULL, true);
646 if (s->sysv_enabled) {
649 if ((k = unit_add_dependency_by_name_inverse(u, UNIT_WANTS, m, NULL, true)) < 0)
655 log_error("[%s:%u] Failed to add LSB Provides name %s, ignoring: %s", path, line, m, strerror(-r));
660 } else if (startswith_no_case(t, "Required-Start:") ||
661 startswith_no_case(t, "Should-Start:") ||
662 startswith_no_case(t, "X-Start-Before:") ||
663 startswith_no_case(t, "X-Start-After:")) {
669 FOREACH_WORD_QUOTED(w, z, strchr(t, ':')+1, i) {
672 if (!(n = strndup(w, z))) {
677 r = sysv_translate_facility(n, file_name_from_path(path), &m);
686 r = unit_add_dependency_by_name(u, startswith_no_case(t, "X-Start-Before:") ? UNIT_BEFORE : UNIT_AFTER, m, NULL, true);
689 log_error("[%s:%u] Failed to add dependency on %s, ignoring: %s", path, line, m, strerror(-r));
693 } else if (startswith_no_case(t, "Default-Start:")) {
698 k = delete_chars(t+14, WHITESPACE "-");
701 if (!(d = strdup(k))) {
706 free(s->sysv_runlevels);
707 s->sysv_runlevels = d;
710 } else if (startswith_no_case(t, "Description:")) {
713 state = LSB_DESCRIPTION;
715 if ((j = strstrip(t+12)) && *j) {
716 if (!(d = strdup(j))) {
723 free(long_description);
724 long_description = d;
726 } else if (startswith_no_case(t, "Short-Description:")) {
731 if ((j = strstrip(t+18)) && *j) {
732 if (!(d = strdup(j))) {
739 free(short_description);
740 short_description = d;
742 } else if (startswith_no_case(t, "X-Interactive:")) {
745 if ((b = parse_boolean(strstrip(t+14))) < 0) {
746 log_warning("[%s:%u] Couldn't parse interactive flag. Ignoring.", path, line);
751 s->exec_context.std_input = EXEC_INPUT_TTY;
753 s->exec_context.std_input = EXEC_INPUT_NULL;
755 } else if (state == LSB_DESCRIPTION) {
757 if (startswith(l, "#\t") || startswith(l, "# ")) {
760 if ((j = strstrip(t)) && *j) {
763 if (long_description)
764 asprintf(&d, "%s %s", long_description, t);
773 free(long_description);
774 long_description = d;
783 if ((r = sysv_exec_commands(s)) < 0)
786 if (s->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, s->sysv_runlevels)) {
787 /* If there a runlevels configured for this service
788 * but none of the standard ones, then we assume this
789 * is some special kind of service (which might be
790 * needed for early boot) and don't create any links
793 s->meta.default_dependencies = false;
795 /* Don't timeout special services during boot (like fsck) */
798 s->timeout_usec = DEFAULT_SYSV_TIMEOUT_USEC;
800 /* Special setting for all SysV services */
801 s->type = SERVICE_FORKING;
802 s->remain_after_exit = true;
803 s->restart = SERVICE_RESTART_NO;
804 s->exec_context.std_output =
805 (s->meta.manager->sysv_console || s->exec_context.std_input == EXEC_INPUT_TTY)
806 ? EXEC_OUTPUT_TTY : EXEC_OUTPUT_NULL;
807 s->exec_context.kill_mode = KILL_PROCESS_GROUP;
809 /* We use the long description only if
810 * no short description is set. */
812 if (short_description)
813 description = short_description;
814 else if (chkconfig_description)
815 description = chkconfig_description;
816 else if (long_description)
817 description = long_description;
824 if (!(d = strappend("LSB: ", description))) {
829 u->meta.description = d;
832 u->meta.load_state = UNIT_LOADED;
840 free(short_description);
841 free(long_description);
842 free(chkconfig_description);
847 static int service_load_sysv_name(Service *s, const char *name) {
853 /* For SysV services we strip the boot. or .sh
854 * prefixes/suffixes. */
855 if (startswith(name, "boot.") ||
856 endswith(name, ".sh.service"))
859 STRV_FOREACH(p, s->meta.manager->lookup_paths.sysvinit_path) {
863 if (asprintf(&path, "%s/%s", *p, name) < 0)
866 assert(endswith(path, ".service"));
867 path[strlen(path)-8] = 0;
869 r = service_load_sysv_path(s, path);
871 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
872 /* Try Debian style xxx.sh source'able init scripts */
874 r = service_load_sysv_path(s, path);
879 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
880 /* Try SUSE style boot.xxx init scripts */
882 if (asprintf(&path, "%s/boot.%s", *p, name) < 0)
885 path[strlen(path)-8] = 0;
886 r = service_load_sysv_path(s, path);
893 if ((s->meta.load_state != UNIT_STUB))
900 static int service_load_sysv(Service *s) {
907 /* Load service data from SysV init scripts, preferably with
910 if (strv_isempty(s->meta.manager->lookup_paths.sysvinit_path))
913 if ((t = s->meta.id))
914 if ((r = service_load_sysv_name(s, t)) < 0)
917 if (s->meta.load_state == UNIT_STUB)
918 SET_FOREACH(t, s->meta.names, i) {
922 if ((r = service_load_sysv_name(s, t)) < 0)
925 if (s->meta.load_state != UNIT_STUB)
933 static int fsck_fix_order(Service *s) {
939 if (s->fsck_passno <= 0)
942 /* For each pair of services where both have an fsck priority
943 * we order things based on it. */
945 LIST_FOREACH(units_per_type, other, s->meta.manager->units_per_type[UNIT_SERVICE]) {
949 t = (Service*) other;
954 if (t->meta.load_state != UNIT_LOADED)
957 if (t->fsck_passno <= 0)
960 if (t->fsck_passno < s->fsck_passno)
962 else if (t->fsck_passno > s->fsck_passno)
967 if (!(r = unit_add_dependency(UNIT(s), d, UNIT(t), true)) < 0)
974 static int service_verify(Service *s) {
977 if (s->meta.load_state != UNIT_LOADED)
980 if (!s->exec_command[SERVICE_EXEC_START]) {
981 log_error("%s lacks ExecStart setting. Refusing.", s->meta.id);
985 if (s->type != SERVICE_ONESHOT &&
986 s->exec_command[SERVICE_EXEC_START]->command_next) {
987 log_error("%s has more than one ExecStart setting, which is only allowed for Type=oneshot services. Refusing.", s->meta.id);
991 if (s->type == SERVICE_DBUS && !s->bus_name) {
992 log_error("%s is of type D-Bus but no D-Bus service name has been specified. Refusing.", s->meta.id);
996 if (s->exec_context.pam_name && s->exec_context.kill_mode != KILL_CONTROL_GROUP) {
997 log_error("%s has PAM enabled. Kill mode must be set to 'control-group'. Refusing.", s->meta.id);
1004 static int service_add_default_dependencies(Service *s) {
1009 /* Add a number of automatic dependencies useful for the
1010 * majority of services. */
1012 /* First, pull in base system */
1013 if (s->meta.manager->running_as == MANAGER_SYSTEM) {
1015 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_BASIC_TARGET, NULL, true)) < 0)
1018 } else if (s->meta.manager->running_as == MANAGER_USER) {
1020 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SOCKETS_TARGET, NULL, true)) < 0)
1024 /* Second, activate normal shutdown */
1025 return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true);
1028 static int service_load(Unit *u) {
1030 Service *s = SERVICE(u);
1034 /* Load a .service file */
1035 if ((r = unit_load_fragment(u)) < 0)
1038 #ifdef HAVE_SYSV_COMPAT
1039 /* Load a classic init script as a fallback, if we couldn't find anything */
1040 if (u->meta.load_state == UNIT_STUB)
1041 if ((r = service_load_sysv(s)) < 0)
1045 /* Still nothing found? Then let's give up */
1046 if (u->meta.load_state == UNIT_STUB)
1049 /* We were able to load something, then let's add in the
1050 * dropin directories. */
1051 if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
1054 /* This is a new unit? Then let's add in some extras */
1055 if (u->meta.load_state == UNIT_LOADED) {
1056 if ((r = unit_add_exec_dependencies(u, &s->exec_context)) < 0)
1059 if ((r = unit_add_default_cgroups(u)) < 0)
1062 #ifdef HAVE_SYSV_COMPAT
1063 if ((r = sysv_fix_order(s)) < 0)
1067 if ((r = fsck_fix_order(s)) < 0)
1071 if ((r = unit_watch_bus_name(u, s->bus_name)) < 0)
1074 if (s->type == SERVICE_NOTIFY && s->notify_access == NOTIFY_NONE)
1075 s->notify_access = NOTIFY_MAIN;
1077 if (s->type == SERVICE_DBUS || s->bus_name)
1078 if ((r = unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_REQUIRES, SPECIAL_DBUS_TARGET, NULL, true)) < 0)
1081 if (s->meta.default_dependencies)
1082 if ((r = service_add_default_dependencies(s)) < 0)
1086 return service_verify(s);
1089 static void service_dump(Unit *u, FILE *f, const char *prefix) {
1091 ServiceExecCommand c;
1092 Service *s = SERVICE(u);
1093 const char *prefix2;
1098 p2 = strappend(prefix, "\t");
1099 prefix2 = p2 ? p2 : prefix;
1102 "%sService State: %s\n"
1103 "%sPermissionsStartOnly: %s\n"
1104 "%sRootDirectoryStartOnly: %s\n"
1105 "%sRemainAfterExit: %s\n"
1108 "%sNotifyAccess: %s\n",
1109 prefix, service_state_to_string(s->state),
1110 prefix, yes_no(s->permissions_start_only),
1111 prefix, yes_no(s->root_directory_start_only),
1112 prefix, yes_no(s->remain_after_exit),
1113 prefix, service_type_to_string(s->type),
1114 prefix, service_restart_to_string(s->restart),
1115 prefix, notify_access_to_string(s->notify_access));
1117 if (s->control_pid > 0)
1119 "%sControl PID: %lu\n",
1120 prefix, (unsigned long) s->control_pid);
1122 if (s->main_pid > 0)
1124 "%sMain PID: %lu\n",
1125 prefix, (unsigned long) s->main_pid);
1130 prefix, s->pid_file);
1135 "%sBus Name Good: %s\n",
1136 prefix, s->bus_name,
1137 prefix, yes_no(s->bus_name_good));
1139 exec_context_dump(&s->exec_context, f, prefix);
1141 for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
1143 if (!s->exec_command[c])
1146 fprintf(f, "%s-> %s:\n",
1147 prefix, service_exec_command_to_string(c));
1149 exec_command_dump_list(s->exec_command[c], f, prefix2);
1152 #ifdef HAVE_SYSV_COMPAT
1155 "%sSysV Init Script Path: %s\n"
1156 "%sSysV Init Script has LSB Header: %s\n"
1157 "%sSysVEnabled: %s\n",
1158 prefix, s->sysv_path,
1159 prefix, yes_no(s->sysv_has_lsb),
1160 prefix, yes_no(s->sysv_enabled));
1162 if (s->sysv_start_priority >= 0)
1164 "%sSysVStartPriority: %i\n",
1165 prefix, s->sysv_start_priority);
1167 if (s->sysv_runlevels)
1168 fprintf(f, "%sSysVRunLevels: %s\n",
1169 prefix, s->sysv_runlevels);
1172 if (s->fsck_passno > 0)
1174 "%sFsckPassNo: %i\n",
1175 prefix, s->fsck_passno);
1178 fprintf(f, "%sStatus Text: %s\n",
1179 prefix, s->status_text);
1184 static int service_load_pid_file(Service *s) {
1191 if (s->main_pid_known)
1194 assert(s->main_pid <= 0);
1199 if ((r = read_one_line_file(s->pid_file, &k)) < 0)
1202 r = parse_pid(k, &pid);
1208 if (kill(pid, 0) < 0 && errno != EPERM) {
1209 log_warning("PID %lu read from file %s does not exist. Your service or init script might be broken.",
1210 (unsigned long) pid, s->pid_file);
1214 if ((r = service_set_main_pid(s, pid)) < 0)
1217 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1218 /* FIXME: we need to do something here */
1224 static int service_search_main_pid(Service *s) {
1230 if (s->main_pid_known)
1233 assert(s->main_pid <= 0);
1235 if ((pid = cgroup_bonding_search_main_pid_list(s->meta.cgroup_bondings)) <= 0)
1238 if ((r = service_set_main_pid(s, pid)) < 0)
1241 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1242 /* FIXME: we need to do something here */
1248 static int service_get_sockets(Service *s, Set **_set) {
1257 if (s->socket_fd >= 0)
1260 if (!set_isempty(s->configured_sockets))
1263 /* Collects all Socket objects that belong to this
1264 * service. Note that a service might have multiple sockets
1265 * via multiple names. */
1267 if (!(set = set_new(NULL, NULL)))
1270 SET_FOREACH(t, s->meta.names, i) {
1274 /* Look for all socket objects that go by any of our
1275 * units and collect their fds */
1277 if (!(k = unit_name_change_suffix(t, ".socket"))) {
1282 p = manager_get_unit(s->meta.manager, k);
1288 if ((r = set_put(set, p)) < 0)
1300 static int service_notify_sockets_dead(Service *s) {
1302 Set *set, *free_set = NULL;
1308 /* Notifies all our sockets when we die */
1310 if (s->socket_fd >= 0)
1313 if (!set_isempty(s->configured_sockets))
1314 set = s->configured_sockets;
1316 if ((r = service_get_sockets(s, &free_set)) < 0)
1322 SET_FOREACH(sock, set, i)
1323 socket_notify_service_dead(sock);
1330 static void service_set_state(Service *s, ServiceState state) {
1331 ServiceState old_state;
1334 old_state = s->state;
1337 if (state != SERVICE_START_PRE &&
1338 state != SERVICE_START &&
1339 state != SERVICE_START_POST &&
1340 state != SERVICE_RELOAD &&
1341 state != SERVICE_STOP &&
1342 state != SERVICE_STOP_SIGTERM &&
1343 state != SERVICE_STOP_SIGKILL &&
1344 state != SERVICE_STOP_POST &&
1345 state != SERVICE_FINAL_SIGTERM &&
1346 state != SERVICE_FINAL_SIGKILL &&
1347 state != SERVICE_AUTO_RESTART)
1348 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1350 if (state != SERVICE_START &&
1351 state != SERVICE_START_POST &&
1352 state != SERVICE_RUNNING &&
1353 state != SERVICE_RELOAD &&
1354 state != SERVICE_STOP &&
1355 state != SERVICE_STOP_SIGTERM &&
1356 state != SERVICE_STOP_SIGKILL)
1357 service_unwatch_main_pid(s);
1359 if (state != SERVICE_START_PRE &&
1360 state != SERVICE_START &&
1361 state != SERVICE_START_POST &&
1362 state != SERVICE_RELOAD &&
1363 state != SERVICE_STOP &&
1364 state != SERVICE_STOP_SIGTERM &&
1365 state != SERVICE_STOP_SIGKILL &&
1366 state != SERVICE_STOP_POST &&
1367 state != SERVICE_FINAL_SIGTERM &&
1368 state != SERVICE_FINAL_SIGKILL) {
1369 service_unwatch_control_pid(s);
1370 s->control_command = NULL;
1371 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1374 if (state == SERVICE_DEAD ||
1375 state == SERVICE_STOP ||
1376 state == SERVICE_STOP_SIGTERM ||
1377 state == SERVICE_STOP_SIGKILL ||
1378 state == SERVICE_STOP_POST ||
1379 state == SERVICE_FINAL_SIGTERM ||
1380 state == SERVICE_FINAL_SIGKILL ||
1381 state == SERVICE_FAILED ||
1382 state == SERVICE_AUTO_RESTART)
1383 service_notify_sockets_dead(s);
1385 if (state != SERVICE_START_PRE &&
1386 state != SERVICE_START &&
1387 state != SERVICE_START_POST &&
1388 state != SERVICE_RUNNING &&
1389 state != SERVICE_RELOAD &&
1390 state != SERVICE_STOP &&
1391 state != SERVICE_STOP_SIGTERM &&
1392 state != SERVICE_STOP_SIGKILL &&
1393 state != SERVICE_STOP_POST &&
1394 state != SERVICE_FINAL_SIGTERM &&
1395 state != SERVICE_FINAL_SIGKILL &&
1396 !(state == SERVICE_DEAD && s->meta.job)) {
1397 service_close_socket_fd(s);
1398 service_connection_unref(s);
1401 /* For the inactive states unit_notify() will trim the cgroup,
1402 * but for exit we have to do that ourselves... */
1403 if (state == SERVICE_EXITED)
1404 cgroup_bonding_trim_list(s->meta.cgroup_bondings, true);
1406 if (old_state != state)
1407 log_debug("%s changed %s -> %s", s->meta.id, service_state_to_string(old_state), service_state_to_string(state));
1409 unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state]);
1412 static int service_coldplug(Unit *u) {
1413 Service *s = SERVICE(u);
1417 assert(s->state == SERVICE_DEAD);
1419 if (s->deserialized_state != s->state) {
1421 if (s->deserialized_state == SERVICE_START_PRE ||
1422 s->deserialized_state == SERVICE_START ||
1423 s->deserialized_state == SERVICE_START_POST ||
1424 s->deserialized_state == SERVICE_RELOAD ||
1425 s->deserialized_state == SERVICE_STOP ||
1426 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1427 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1428 s->deserialized_state == SERVICE_STOP_POST ||
1429 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1430 s->deserialized_state == SERVICE_FINAL_SIGKILL ||
1431 s->deserialized_state == SERVICE_AUTO_RESTART) {
1433 if (s->deserialized_state == SERVICE_AUTO_RESTART || s->timeout_usec > 0) {
1436 k = s->deserialized_state == SERVICE_AUTO_RESTART ? s->restart_usec : s->timeout_usec;
1438 if ((r = unit_watch_timer(UNIT(s), k, &s->timer_watch)) < 0)
1443 if ((s->deserialized_state == SERVICE_START &&
1444 (s->type == SERVICE_FORKING ||
1445 s->type == SERVICE_DBUS ||
1446 s->type == SERVICE_ONESHOT ||
1447 s->type == SERVICE_NOTIFY)) ||
1448 s->deserialized_state == SERVICE_START_POST ||
1449 s->deserialized_state == SERVICE_RUNNING ||
1450 s->deserialized_state == SERVICE_RELOAD ||
1451 s->deserialized_state == SERVICE_STOP ||
1452 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1453 s->deserialized_state == SERVICE_STOP_SIGKILL)
1454 if (s->main_pid > 0)
1455 if ((r = unit_watch_pid(UNIT(s), s->main_pid)) < 0)
1458 if (s->deserialized_state == SERVICE_START_PRE ||
1459 s->deserialized_state == SERVICE_START ||
1460 s->deserialized_state == SERVICE_START_POST ||
1461 s->deserialized_state == SERVICE_RELOAD ||
1462 s->deserialized_state == SERVICE_STOP ||
1463 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1464 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1465 s->deserialized_state == SERVICE_STOP_POST ||
1466 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1467 s->deserialized_state == SERVICE_FINAL_SIGKILL)
1468 if (s->control_pid > 0)
1469 if ((r = unit_watch_pid(UNIT(s), s->control_pid)) < 0)
1472 service_set_state(s, s->deserialized_state);
1478 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
1482 unsigned rn_fds = 0;
1483 Set *set, *free_set = NULL;
1490 if (s->socket_fd >= 0)
1493 if (!set_isempty(s->configured_sockets))
1494 set = s->configured_sockets;
1496 if ((r = service_get_sockets(s, &free_set)) < 0)
1502 SET_FOREACH(sock, set, i) {
1506 if ((r = socket_collect_fds(sock, &cfds, &cn_fds)) < 0)
1518 if (!(t = new(int, rn_fds+cn_fds))) {
1524 memcpy(t, rfds, rn_fds);
1525 memcpy(t+rn_fds, cfds, cn_fds);
1530 rn_fds = rn_fds+cn_fds;
1548 static int service_spawn(
1553 bool apply_permissions,
1555 bool apply_tty_stdin,
1556 bool set_notify_socket,
1561 int *fds = NULL, *fdsbuf = NULL;
1562 unsigned n_fds = 0, n_env = 0;
1563 char **argv = NULL, **final_env = NULL, **our_env = NULL;
1570 s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1571 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1572 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
1574 if (s->socket_fd >= 0) {
1575 fds = &s->socket_fd;
1578 if ((r = service_collect_fds(s, &fdsbuf, &n_fds)) < 0)
1585 if (timeout && s->timeout_usec) {
1586 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1589 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1591 if (!(argv = unit_full_printf_strv(UNIT(s), c->argv))) {
1596 if (!(our_env = new0(char*, 4))) {
1601 if (set_notify_socket)
1602 if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=@%s", s->meta.manager->notify_socket) < 0) {
1607 if (s->main_pid > 0)
1608 if (asprintf(our_env + n_env++, "MAINPID=%lu", (unsigned long) s->main_pid) < 0) {
1613 if (!(final_env = strv_env_merge(2,
1614 s->meta.manager->environment,
1629 s->meta.manager->confirm_spawn,
1630 s->meta.cgroup_bondings,
1637 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1638 /* FIXME: we need to do something here */
1644 strv_free(final_env);
1654 strv_free(final_env);
1657 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1662 static int main_pid_good(Service *s) {
1665 /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1668 /* If we know the pid file, then lets just check if it is
1670 if (s->main_pid_known)
1671 return s->main_pid > 0;
1673 /* We don't know the pid */
1677 static int control_pid_good(Service *s) {
1680 return s->control_pid > 0;
1683 static int cgroup_good(Service *s) {
1688 if ((r = cgroup_bonding_is_empty_list(s->meta.cgroup_bondings)) < 0)
1694 static void service_enter_dead(Service *s, bool success, bool allow_restart) {
1701 if (allow_restart &&
1702 !s->forbid_restart &&
1703 (s->restart == SERVICE_RESTART_ALWAYS ||
1704 (s->restart == SERVICE_RESTART_ON_SUCCESS && !s->failure) ||
1705 (s->restart == SERVICE_RESTART_ON_FAILURE && s->failure) ||
1706 (s->restart == SERVICE_RESTART_ON_ABORT && s->failure &&
1707 (s->main_exec_status.code == CLD_KILLED ||
1708 s->main_exec_status.code == CLD_DUMPED)))) {
1710 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
1713 service_set_state(s, SERVICE_AUTO_RESTART);
1715 service_set_state(s, s->failure ? SERVICE_FAILED : SERVICE_DEAD);
1717 s->forbid_restart = false;
1722 log_warning("%s failed to run install restart timer: %s", s->meta.id, strerror(-r));
1723 service_enter_dead(s, false, false);
1726 static void service_enter_signal(Service *s, ServiceState state, bool success);
1728 static void service_enter_stop_post(Service *s, bool success) {
1735 service_unwatch_control_pid(s);
1737 s->control_command_id = SERVICE_EXEC_STOP_POST;
1738 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST])) {
1739 if ((r = service_spawn(s,
1743 !s->permissions_start_only,
1744 !s->root_directory_start_only,
1747 &s->control_pid)) < 0)
1751 service_set_state(s, SERVICE_STOP_POST);
1753 service_enter_signal(s, SERVICE_FINAL_SIGTERM, true);
1758 log_warning("%s failed to run 'stop-post' task: %s", s->meta.id, strerror(-r));
1759 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1762 static void service_enter_signal(Service *s, ServiceState state, bool success) {
1764 Set *pid_set = NULL;
1765 bool wait_for_exit = false;
1772 if (s->exec_context.kill_mode != KILL_NONE) {
1773 int sig = (state == SERVICE_STOP_SIGTERM || state == SERVICE_FINAL_SIGTERM) ? s->exec_context.kill_signal : SIGKILL;
1775 if (s->main_pid > 0) {
1776 if (kill(s->exec_context.kill_mode == KILL_PROCESS_GROUP ?
1778 s->main_pid, sig) < 0 && errno != ESRCH)
1780 log_warning("Failed to kill main process %li: %m", (long) s->main_pid);
1782 wait_for_exit = true;
1785 if (s->control_pid > 0) {
1786 if (kill(s->exec_context.kill_mode == KILL_PROCESS_GROUP ?
1788 s->control_pid, sig) < 0 && errno != ESRCH)
1790 log_warning("Failed to kill control process %li: %m", (long) s->control_pid);
1792 wait_for_exit = true;
1795 if (s->exec_context.kill_mode == KILL_CONTROL_GROUP) {
1797 if (!(pid_set = set_new(trivial_hash_func, trivial_compare_func))) {
1802 /* Exclude the main/control pids from being killed via the cgroup */
1803 if (s->main_pid > 0)
1804 if ((r = set_put(pid_set, LONG_TO_PTR(s->main_pid))) < 0)
1807 if (s->control_pid > 0)
1808 if ((r = set_put(pid_set, LONG_TO_PTR(s->control_pid))) < 0)
1811 if ((r = cgroup_bonding_kill_list(s->meta.cgroup_bondings, sig, pid_set)) < 0) {
1812 if (r != -EAGAIN && r != -ESRCH && r != -ENOENT)
1813 log_warning("Failed to kill control group: %s", strerror(-r));
1815 wait_for_exit = true;
1821 if (wait_for_exit) {
1822 if (s->timeout_usec > 0)
1823 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1826 service_set_state(s, state);
1827 } else if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1828 service_enter_stop_post(s, true);
1830 service_enter_dead(s, true, true);
1835 log_warning("%s failed to kill processes: %s", s->meta.id, strerror(-r));
1837 if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1838 service_enter_stop_post(s, false);
1840 service_enter_dead(s, false, true);
1846 static void service_enter_stop(Service *s, bool success) {
1854 service_unwatch_control_pid(s);
1856 s->control_command_id = SERVICE_EXEC_STOP;
1857 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP])) {
1858 if ((r = service_spawn(s,
1862 !s->permissions_start_only,
1863 !s->root_directory_start_only,
1866 &s->control_pid)) < 0)
1869 service_set_state(s, SERVICE_STOP);
1871 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
1876 log_warning("%s failed to run 'stop' task: %s", s->meta.id, strerror(-r));
1877 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1880 static void service_enter_running(Service *s, bool success) {
1881 int main_pid_ok, cgroup_ok;
1887 main_pid_ok = main_pid_good(s);
1888 cgroup_ok = cgroup_good(s);
1890 if ((main_pid_ok > 0 || (main_pid_ok < 0 && cgroup_ok != 0)) &&
1891 (s->bus_name_good || s->type != SERVICE_DBUS))
1892 service_set_state(s, SERVICE_RUNNING);
1893 else if (s->remain_after_exit)
1894 service_set_state(s, SERVICE_EXITED);
1896 service_enter_stop(s, true);
1899 static void service_enter_start_post(Service *s) {
1903 service_unwatch_control_pid(s);
1905 s->control_command_id = SERVICE_EXEC_START_POST;
1906 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_POST])) {
1907 if ((r = service_spawn(s,
1911 !s->permissions_start_only,
1912 !s->root_directory_start_only,
1915 &s->control_pid)) < 0)
1918 service_set_state(s, SERVICE_START_POST);
1920 service_enter_running(s, true);
1925 log_warning("%s failed to run 'start-post' task: %s", s->meta.id, strerror(-r));
1926 service_enter_stop(s, false);
1929 static void service_enter_start(Service *s) {
1935 assert(s->exec_command[SERVICE_EXEC_START]);
1936 assert(!s->exec_command[SERVICE_EXEC_START]->command_next || s->type == SERVICE_ONESHOT);
1938 if (s->type == SERVICE_FORKING)
1939 service_unwatch_control_pid(s);
1941 service_unwatch_main_pid(s);
1943 s->control_command_id = SERVICE_EXEC_START;
1944 s->control_command = s->exec_command[SERVICE_EXEC_START];
1946 if ((r = service_spawn(s,
1948 s->type == SERVICE_FORKING || s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY,
1953 s->notify_access != NOTIFY_NONE,
1957 if (s->type == SERVICE_SIMPLE) {
1958 /* For simple services we immediately start
1959 * the START_POST binaries. */
1961 service_set_main_pid(s, pid);
1962 service_enter_start_post(s);
1964 } else if (s->type == SERVICE_FORKING) {
1966 /* For forking services we wait until the start
1967 * process exited. */
1969 s->control_pid = pid;
1970 service_set_state(s, SERVICE_START);
1972 } else if (s->type == SERVICE_ONESHOT ||
1973 s->type == SERVICE_DBUS ||
1974 s->type == SERVICE_NOTIFY) {
1976 /* For oneshot services we wait until the start
1977 * process exited, too, but it is our main process. */
1979 /* For D-Bus services we know the main pid right away,
1980 * but wait for the bus name to appear on the
1981 * bus. Notify services are similar. */
1983 service_set_main_pid(s, pid);
1984 service_set_state(s, SERVICE_START);
1986 assert_not_reached("Unknown service type");
1991 log_warning("%s failed to run 'start' task: %s", s->meta.id, strerror(-r));
1992 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1995 static void service_enter_start_pre(Service *s) {
2000 service_unwatch_control_pid(s);
2002 s->control_command_id = SERVICE_EXEC_START_PRE;
2003 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_PRE])) {
2004 if ((r = service_spawn(s,
2008 !s->permissions_start_only,
2009 !s->root_directory_start_only,
2012 &s->control_pid)) < 0)
2015 service_set_state(s, SERVICE_START_PRE);
2017 service_enter_start(s);
2022 log_warning("%s failed to run 'start-pre' task: %s", s->meta.id, strerror(-r));
2023 service_enter_dead(s, false, true);
2026 static void service_enter_restart(Service *s) {
2031 dbus_error_init(&error);
2034 log_info("Job pending for unit, delaying automatic restart.");
2036 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
2040 service_enter_dead(s, true, false);
2042 if ((r = manager_add_job(s->meta.manager, JOB_START, UNIT(s), JOB_FAIL, false, &error, NULL)) < 0)
2045 log_debug("%s scheduled restart job.", s->meta.id);
2049 log_warning("%s failed to schedule restart job: %s", s->meta.id, bus_error(&error, -r));
2050 service_enter_dead(s, false, false);
2052 dbus_error_free(&error);
2055 static void service_enter_reload(Service *s) {
2060 service_unwatch_control_pid(s);
2062 s->control_command_id = SERVICE_EXEC_RELOAD;
2063 if ((s->control_command = s->exec_command[SERVICE_EXEC_RELOAD])) {
2064 if ((r = service_spawn(s,
2068 !s->permissions_start_only,
2069 !s->root_directory_start_only,
2072 &s->control_pid)) < 0)
2075 service_set_state(s, SERVICE_RELOAD);
2077 service_enter_running(s, true);
2082 log_warning("%s failed to run 'reload' task: %s", s->meta.id, strerror(-r));
2083 service_enter_stop(s, false);
2086 static void service_run_next_control(Service *s, bool success) {
2090 assert(s->control_command);
2091 assert(s->control_command->command_next);
2096 assert(s->control_command_id != SERVICE_EXEC_START);
2098 s->control_command = s->control_command->command_next;
2099 service_unwatch_control_pid(s);
2101 if ((r = service_spawn(s,
2105 !s->permissions_start_only,
2106 !s->root_directory_start_only,
2107 s->control_command_id == SERVICE_EXEC_START_PRE ||
2108 s->control_command_id == SERVICE_EXEC_STOP_POST,
2110 &s->control_pid)) < 0)
2116 log_warning("%s failed to run next control task: %s", s->meta.id, strerror(-r));
2118 if (s->state == SERVICE_START_PRE)
2119 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2120 else if (s->state == SERVICE_STOP)
2121 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
2122 else if (s->state == SERVICE_STOP_POST)
2123 service_enter_dead(s, false, true);
2125 service_enter_stop(s, false);
2128 static void service_run_next_main(Service *s, bool success) {
2133 assert(s->control_command);
2134 assert(s->control_command->command_next);
2139 assert(s->control_command_id == SERVICE_EXEC_START);
2140 assert(s->type == SERVICE_ONESHOT);
2142 s->control_command = s->control_command->command_next;
2143 service_unwatch_main_pid(s);
2145 if ((r = service_spawn(s,
2152 s->notify_access != NOTIFY_NONE,
2156 service_set_main_pid(s, pid);
2161 log_warning("%s failed to run next main task: %s", s->meta.id, strerror(-r));
2162 service_enter_stop(s, false);
2165 static int service_start(Unit *u) {
2166 Service *s = SERVICE(u);
2170 /* We cannot fulfill this request right now, try again later
2172 if (s->state == SERVICE_STOP ||
2173 s->state == SERVICE_STOP_SIGTERM ||
2174 s->state == SERVICE_STOP_SIGKILL ||
2175 s->state == SERVICE_STOP_POST ||
2176 s->state == SERVICE_FINAL_SIGTERM ||
2177 s->state == SERVICE_FINAL_SIGKILL)
2180 /* Already on it! */
2181 if (s->state == SERVICE_START_PRE ||
2182 s->state == SERVICE_START ||
2183 s->state == SERVICE_START_POST)
2186 assert(s->state == SERVICE_DEAD || s->state == SERVICE_FAILED || s->state == SERVICE_AUTO_RESTART);
2188 /* Make sure we don't enter a busy loop of some kind. */
2189 if (!ratelimit_test(&s->ratelimit)) {
2190 log_warning("%s start request repeated too quickly, refusing to start.", u->meta.id);
2195 s->main_pid_known = false;
2196 s->forbid_restart = false;
2198 service_enter_start_pre(s);
2202 static int service_stop(Unit *u) {
2203 Service *s = SERVICE(u);
2207 /* This is a user request, so don't do restarts on this
2209 s->forbid_restart = true;
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 /* Don't allow a restart */
2221 if (s->state == SERVICE_AUTO_RESTART) {
2222 service_set_state(s, SERVICE_DEAD);
2226 /* If there's already something running we go directly into
2228 if (s->state == SERVICE_START_PRE ||
2229 s->state == SERVICE_START ||
2230 s->state == SERVICE_START_POST ||
2231 s->state == SERVICE_RELOAD) {
2232 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
2236 assert(s->state == SERVICE_RUNNING ||
2237 s->state == SERVICE_EXITED);
2239 service_enter_stop(s, true);
2243 static int service_reload(Unit *u) {
2244 Service *s = SERVICE(u);
2248 assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
2250 service_enter_reload(s);
2254 static bool service_can_reload(Unit *u) {
2255 Service *s = SERVICE(u);
2259 return !!s->exec_command[SERVICE_EXEC_RELOAD];
2262 static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
2263 Service *s = SERVICE(u);
2269 unit_serialize_item(u, f, "state", service_state_to_string(s->state));
2270 unit_serialize_item(u, f, "failure", yes_no(s->failure));
2272 if (s->control_pid > 0)
2273 unit_serialize_item_format(u, f, "control-pid", "%lu", (unsigned long) s->control_pid);
2275 if (s->main_pid_known && s->main_pid > 0)
2276 unit_serialize_item_format(u, f, "main-pid", "%lu", (unsigned long) s->main_pid);
2278 unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
2281 unit_serialize_item(u, f, "status-text", s->status_text);
2283 /* There's a minor uncleanliness here: if there are multiple
2284 * commands attached here, we will start from the first one
2286 if (s->control_command_id >= 0)
2287 unit_serialize_item(u, f, "control-command", service_exec_command_to_string(s->control_command_id));
2289 if (s->socket_fd >= 0) {
2292 if ((copy = fdset_put_dup(fds, s->socket_fd)) < 0)
2295 unit_serialize_item_format(u, f, "socket-fd", "%i", copy);
2298 if (s->main_exec_status.pid > 0) {
2299 unit_serialize_item_format(u, f, "main-exec-status-pid", "%lu", (unsigned long) s->main_exec_status.pid);
2300 dual_timestamp_serialize(f, "main-exec-status-start", &s->main_exec_status.start_timestamp);
2301 dual_timestamp_serialize(f, "main-exec-status-exit", &s->main_exec_status.exit_timestamp);
2303 if (dual_timestamp_is_set(&s->main_exec_status.exit_timestamp)) {
2304 unit_serialize_item_format(u, f, "main-exec-status-code", "%i", s->main_exec_status.code);
2305 unit_serialize_item_format(u, f, "main-exec-status-status", "%i", s->main_exec_status.status);
2312 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
2313 Service *s = SERVICE(u);
2320 if (streq(key, "state")) {
2323 if ((state = service_state_from_string(value)) < 0)
2324 log_debug("Failed to parse state value %s", value);
2326 s->deserialized_state = state;
2327 } else if (streq(key, "failure")) {
2330 if ((b = parse_boolean(value)) < 0)
2331 log_debug("Failed to parse failure value %s", value);
2333 s->failure = b || s->failure;
2334 } else if (streq(key, "control-pid")) {
2337 if (parse_pid(value, &pid) < 0)
2338 log_debug("Failed to parse control-pid value %s", value);
2340 s->control_pid = pid;
2341 } else if (streq(key, "main-pid")) {
2344 if (parse_pid(value, &pid) < 0)
2345 log_debug("Failed to parse main-pid value %s", value);
2347 service_set_main_pid(s, (pid_t) pid);
2348 } else if (streq(key, "main-pid-known")) {
2351 if ((b = parse_boolean(value)) < 0)
2352 log_debug("Failed to parse main-pid-known value %s", value);
2354 s->main_pid_known = b;
2355 } else if (streq(key, "status-text")) {
2358 if ((t = strdup(value))) {
2359 free(s->status_text);
2363 } else if (streq(key, "control-command")) {
2364 ServiceExecCommand id;
2366 if ((id = service_exec_command_from_string(value)) < 0)
2367 log_debug("Failed to parse exec-command value %s", value);
2369 s->control_command_id = id;
2370 s->control_command = s->exec_command[id];
2372 } else if (streq(key, "socket-fd")) {
2375 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2376 log_debug("Failed to parse socket-fd value %s", value);
2379 if (s->socket_fd >= 0)
2380 close_nointr_nofail(s->socket_fd);
2381 s->socket_fd = fdset_remove(fds, fd);
2383 } else if (streq(key, "main-exec-status-pid")) {
2386 if (parse_pid(value, &pid) < 0)
2387 log_debug("Failed to parse main-exec-status-pid value %s", value);
2389 s->main_exec_status.pid = pid;
2390 } else if (streq(key, "main-exec-status-code")) {
2393 if (safe_atoi(value, &i) < 0)
2394 log_debug("Failed to parse main-exec-status-code value %s", value);
2396 s->main_exec_status.code = i;
2397 } else if (streq(key, "main-exec-status-status")) {
2400 if (safe_atoi(value, &i) < 0)
2401 log_debug("Failed to parse main-exec-status-status value %s", value);
2403 s->main_exec_status.status = i;
2404 } else if (streq(key, "main-exec-status-start"))
2405 dual_timestamp_deserialize(value, &s->main_exec_status.start_timestamp);
2406 else if (streq(key, "main-exec-status-exit"))
2407 dual_timestamp_deserialize(value, &s->main_exec_status.exit_timestamp);
2409 log_debug("Unknown serialization key '%s'", key);
2414 static UnitActiveState service_active_state(Unit *u) {
2417 return state_translation_table[SERVICE(u)->state];
2420 static const char *service_sub_state_to_string(Unit *u) {
2423 return service_state_to_string(SERVICE(u)->state);
2426 #ifdef HAVE_SYSV_COMPAT
2427 static bool service_check_gc(Unit *u) {
2428 Service *s = SERVICE(u);
2432 return !!s->sysv_path;
2436 static bool service_check_snapshot(Unit *u) {
2437 Service *s = SERVICE(u);
2441 return !s->got_socket_fd;
2444 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2445 Service *s = SERVICE(u);
2451 if (!s->meta.fragment_path)
2452 success = is_clean_exit_lsb(code, status);
2454 success = is_clean_exit(code, status);
2456 if (s->main_pid == pid) {
2459 exec_status_exit(&s->main_exec_status, pid, code, status, s->exec_context.utmp_id);
2461 if (s->type != SERVICE_FORKING && s->control_command) {
2462 s->control_command->exec_status = s->main_exec_status;
2464 if (s->control_command->ignore)
2468 log_full(success ? LOG_DEBUG : LOG_NOTICE,
2469 "%s: main process exited, code=%s, status=%i", u->meta.id, sigchld_code_to_string(code), status);
2470 s->failure = s->failure || !success;
2472 if (s->control_command &&
2473 s->control_command->command_next &&
2476 /* There is another command to *
2477 * execute, so let's do that. */
2479 log_debug("%s running next main command for state %s", u->meta.id, service_state_to_string(s->state));
2480 service_run_next_main(s, success);
2484 /* The service exited, so the service is officially
2487 s->control_command = NULL;
2488 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2492 case SERVICE_START_POST:
2493 case SERVICE_RELOAD:
2495 /* Need to wait until the operation is
2500 if (s->type == SERVICE_ONESHOT) {
2501 /* This was our main goal, so let's go on */
2503 service_enter_start_post(s);
2505 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2508 assert(s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY);
2513 case SERVICE_RUNNING:
2514 service_enter_running(s, success);
2517 case SERVICE_STOP_SIGTERM:
2518 case SERVICE_STOP_SIGKILL:
2520 if (!control_pid_good(s))
2521 service_enter_stop_post(s, success);
2523 /* If there is still a control process, wait for that first */
2527 assert_not_reached("Uh, main process died at wrong time.");
2531 } else if (s->control_pid == pid) {
2535 if (s->control_command) {
2536 exec_status_exit(&s->control_command->exec_status, pid, code, status, s->exec_context.utmp_id);
2538 if (s->control_command->ignore)
2542 log_full(success ? LOG_DEBUG : LOG_NOTICE,
2543 "%s: control process exited, code=%s status=%i", u->meta.id, sigchld_code_to_string(code), status);
2544 s->failure = s->failure || !success;
2546 if (s->control_command &&
2547 s->control_command->command_next &&
2550 /* There is another command to *
2551 * execute, so let's do that. */
2553 log_debug("%s running next control command for state %s", u->meta.id, service_state_to_string(s->state));
2554 service_run_next_control(s, success);
2557 /* No further commands for this step, so let's
2558 * figure out what to do next */
2560 s->control_command = NULL;
2561 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2563 log_debug("%s got final SIGCHLD for state %s", u->meta.id, service_state_to_string(s->state));
2567 case SERVICE_START_PRE:
2569 service_enter_start(s);
2571 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2575 assert(s->type == SERVICE_FORKING);
2577 /* Let's try to load the pid
2578 * file here if we can. We
2579 * ignore the return value,
2580 * since the PID file might
2581 * actually be created by a
2582 * START_POST script */
2585 service_load_pid_file(s);
2586 service_search_main_pid(s);
2588 service_enter_start_post(s);
2590 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2594 case SERVICE_START_POST:
2595 if (success && s->pid_file && !s->main_pid_known) {
2598 /* Hmm, let's see if we can
2599 * load the pid now after the
2600 * start-post scripts got
2603 if ((r = service_load_pid_file(s)) < 0)
2604 log_warning("%s: failed to load PID file %s: %s", s->meta.id, s->pid_file, strerror(-r));
2609 case SERVICE_RELOAD:
2611 service_enter_running(s, true);
2613 service_enter_stop(s, false);
2618 service_enter_signal(s, SERVICE_STOP_SIGTERM, success);
2621 case SERVICE_STOP_SIGTERM:
2622 case SERVICE_STOP_SIGKILL:
2623 if (main_pid_good(s) <= 0)
2624 service_enter_stop_post(s, success);
2626 /* If there is still a service
2627 * process around, wait until
2628 * that one quit, too */
2631 case SERVICE_STOP_POST:
2632 case SERVICE_FINAL_SIGTERM:
2633 case SERVICE_FINAL_SIGKILL:
2634 service_enter_dead(s, success, true);
2638 assert_not_reached("Uh, control process died at wrong time.");
2643 /* Notify clients about changed exit status */
2644 unit_add_to_dbus_queue(u);
2647 static void service_timer_event(Unit *u, uint64_t elapsed, Watch* w) {
2648 Service *s = SERVICE(u);
2651 assert(elapsed == 1);
2653 assert(w == &s->timer_watch);
2657 case SERVICE_START_PRE:
2659 log_warning("%s operation timed out. Terminating.", u->meta.id);
2660 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2663 case SERVICE_START_POST:
2664 case SERVICE_RELOAD:
2665 log_warning("%s operation timed out. Stopping.", u->meta.id);
2666 service_enter_stop(s, false);
2670 log_warning("%s stopping timed out. Terminating.", u->meta.id);
2671 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
2674 case SERVICE_STOP_SIGTERM:
2675 log_warning("%s stopping timed out. Killing.", u->meta.id);
2676 service_enter_signal(s, SERVICE_STOP_SIGKILL, false);
2679 case SERVICE_STOP_SIGKILL:
2680 /* Uh, wie sent a SIGKILL and it is still not gone?
2681 * Must be something we cannot kill, so let's just be
2682 * weirded out and continue */
2684 log_warning("%s still around after SIGKILL. Ignoring.", u->meta.id);
2685 service_enter_stop_post(s, false);
2688 case SERVICE_STOP_POST:
2689 log_warning("%s stopping timed out (2). Terminating.", u->meta.id);
2690 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2693 case SERVICE_FINAL_SIGTERM:
2694 log_warning("%s stopping timed out (2). Killing.", u->meta.id);
2695 service_enter_signal(s, SERVICE_FINAL_SIGKILL, false);
2698 case SERVICE_FINAL_SIGKILL:
2699 log_warning("%s still around after SIGKILL (2). Entering failed mode.", u->meta.id);
2700 service_enter_dead(s, false, true);
2703 case SERVICE_AUTO_RESTART:
2704 log_info("%s holdoff time over, scheduling restart.", u->meta.id);
2705 service_enter_restart(s);
2709 assert_not_reached("Timeout at wrong time.");
2713 static void service_cgroup_notify_event(Unit *u) {
2714 Service *s = SERVICE(u);
2718 log_debug("%s: cgroup is empty", u->meta.id);
2722 /* Waiting for SIGCHLD is usually more interesting,
2723 * because it includes return codes/signals. Which is
2724 * why we ignore the cgroup events for most cases,
2725 * except when we don't know pid which to expect the
2728 case SERVICE_RUNNING:
2729 service_enter_running(s, true);
2732 case SERVICE_STOP_SIGTERM:
2733 case SERVICE_STOP_SIGKILL:
2734 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2735 service_enter_stop_post(s, true);
2739 case SERVICE_FINAL_SIGTERM:
2740 case SERVICE_FINAL_SIGKILL:
2741 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2742 service_enter_dead(s, true, true);
2751 static void service_notify_message(Unit *u, pid_t pid, char **tags) {
2752 Service *s = SERVICE(u);
2757 if (s->notify_access == NOTIFY_NONE) {
2758 log_warning("%s: Got notification message from PID %lu, but reception is disabled.",
2759 u->meta.id, (unsigned long) pid);
2763 if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
2764 log_warning("%s: Got notification message from PID %lu, but reception only permitted for PID %lu",
2765 u->meta.id, (unsigned long) pid, (unsigned long) s->main_pid);
2769 log_debug("%s: Got message", u->meta.id);
2771 /* Interpret MAINPID= */
2772 if ((e = strv_find_prefix(tags, "MAINPID=")) &&
2773 (s->state == SERVICE_START ||
2774 s->state == SERVICE_START_POST ||
2775 s->state == SERVICE_RUNNING ||
2776 s->state == SERVICE_RELOAD)) {
2778 if (parse_pid(e + 8, &pid) < 0)
2779 log_warning("Failed to parse notification message %s", e);
2781 log_debug("%s: got %s", u->meta.id, e);
2782 service_set_main_pid(s, pid);
2786 /* Interpret READY= */
2787 if (s->type == SERVICE_NOTIFY &&
2788 s->state == SERVICE_START &&
2789 strv_find(tags, "READY=1")) {
2790 log_debug("%s: got READY=1", u->meta.id);
2792 service_enter_start_post(s);
2795 /* Interpret STATUS= */
2796 if ((e = strv_find_prefix(tags, "STATUS="))) {
2800 if (!(t = strdup(e+7))) {
2801 log_error("Failed to allocate string.");
2805 log_debug("%s: got %s", u->meta.id, e);
2807 free(s->status_text);
2810 free(s->status_text);
2811 s->status_text = NULL;
2816 /* Notify clients about changed status or main pid */
2817 unit_add_to_dbus_queue(u);
2820 #ifdef HAVE_SYSV_COMPAT
2821 static int service_enumerate(Manager *m) {
2825 char *path = NULL, *fpath = NULL, *name = NULL;
2826 Set *runlevel_services[ELEMENTSOF(rcnd_table)], *shutdown_services = NULL;
2831 Unit *previous = NULL;
2832 char *arch_daemons = NULL;
2833 char *arch_daemons_stripped = NULL;
2834 char **arch_daemons_split = NULL;
2840 if ((r = parse_env_file("/etc/rc.conf", NEWLINE,
2841 "DAEMONS", &arch_daemons,
2845 log_warning("Failed to read /etc/rc.conf: %s", strerror(-r));
2847 } else if (arch_daemons) {
2848 if (!(arch_daemons_stripped = strchr(arch_daemons, '(')))
2849 arch_daemons_stripped = arch_daemons;
2851 arch_daemons_stripped++; /* strip start paren */
2853 arch_daemons_stripped[strcspn(arch_daemons_stripped, ")")] = 0; /* strip end paren */
2855 if (!(arch_daemons_split = strv_split_quoted(arch_daemons_stripped))) {
2860 STRV_FOREACH(p, arch_daemons_split) {
2865 if (**p == '!') /* daemons prefixed with ! are disabled, so ignore them */
2868 if (!(name = sysv_translate_name(*p))) {
2873 if ((r = manager_load_unit_prepare(m, name, NULL, NULL, &service)) < 0) {
2874 log_warning("Failed to prepare unit %s: %s", name, strerror(-r));
2878 if ((r = unit_add_two_dependencies_by_name_inverse(service, UNIT_AFTER, UNIT_WANTS, "multi-user.target", NULL, true)) < 0)
2882 if ((r = unit_add_dependency(service, UNIT_AFTER, previous, true)) < 0)
2885 if (**p != '@') /* daemons prefixed with @ can be started in the background */
2891 zero(runlevel_services);
2893 STRV_FOREACH(p, m->lookup_paths.sysvrcnd_path)
2894 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++) {
2899 if (asprintf(&path, "%s/%s", *p, rcnd_table[i].path) < 0) {
2907 if (!(d = opendir(path))) {
2908 if (errno != ENOENT)
2909 log_warning("opendir() failed on %s: %s", path, strerror(errno));
2914 while ((de = readdir(d))) {
2917 if (ignore_file(de->d_name))
2920 if (de->d_name[0] != 'S' && de->d_name[0] != 'K')
2923 if (strlen(de->d_name) < 4)
2926 a = undecchar(de->d_name[1]);
2927 b = undecchar(de->d_name[2]);
2934 if (asprintf(&fpath, "%s/%s/%s", *p, rcnd_table[i].path, de->d_name) < 0) {
2939 if (access(fpath, X_OK) < 0) {
2941 if (errno != ENOENT)
2942 log_warning("access() failed on %s: %s", fpath, strerror(errno));
2948 if (!(name = sysv_translate_name(de->d_name + 3))) {
2953 if ((r = manager_load_unit_prepare(m, name, NULL, NULL, &service)) < 0) {
2954 log_warning("Failed to prepare unit %s: %s", name, strerror(-r));
2958 if (de->d_name[0] == 'S') {
2960 if (rcnd_table[i].type == RUNLEVEL_UP || rcnd_table[i].type == RUNLEVEL_SYSINIT) {
2961 SERVICE(service)->sysv_start_priority =
2962 MAX(a*10 + b, SERVICE(service)->sysv_start_priority);
2964 SERVICE(service)->sysv_enabled = true;
2967 if ((r = set_ensure_allocated(&runlevel_services[i], trivial_hash_func, trivial_compare_func)) < 0)
2970 if ((r = set_put(runlevel_services[i], service)) < 0)
2973 } else if (de->d_name[0] == 'K' &&
2974 (rcnd_table[i].type == RUNLEVEL_DOWN ||
2975 rcnd_table[i].type == RUNLEVEL_SYSINIT)) {
2977 if ((r = set_ensure_allocated(&shutdown_services, trivial_hash_func, trivial_compare_func)) < 0)
2980 if ((r = set_put(shutdown_services, service)) < 0)
2986 /* Now we loaded all stubs and are aware of the lowest
2987 start-up priority for all services, not let's actually load
2988 the services, this will also tell us which services are
2989 actually native now */
2990 manager_dispatch_load_queue(m);
2992 /* If this is a native service, rely on native ways to pull in
2993 * a service, don't pull it in via sysv rcN.d links. */
2994 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++)
2995 SET_FOREACH(service, runlevel_services[i], j) {
2996 service = unit_follow_merge(service);
2998 if (service->meta.fragment_path)
3001 if ((r = unit_add_two_dependencies_by_name_inverse(service, UNIT_AFTER, UNIT_WANTS, rcnd_table[i].target, NULL, true)) < 0)
3005 /* We honour K links only for halt/reboot. For the normal
3006 * runlevels we assume the stop jobs will be implicitly added
3007 * by the core logic. Also, we don't really distuingish here
3008 * between the runlevels 0 and 6 and just add them to the
3009 * special shutdown target. On SUSE the boot.d/ runlevel is
3010 * also used for shutdown, so we add links for that too to the
3011 * shutdown target.*/
3012 SET_FOREACH(service, shutdown_services, j) {
3013 service = unit_follow_merge(service);
3015 if (service->meta.fragment_path)
3018 if ((r = unit_add_two_dependencies_by_name(service, UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true)) < 0)
3030 free(arch_daemons_split);
3033 for (i = 0; i < ELEMENTSOF(rcnd_table); i++)
3034 set_free(runlevel_services[i]);
3035 set_free(shutdown_services);
3044 static void service_bus_name_owner_change(
3047 const char *old_owner,
3048 const char *new_owner) {
3050 Service *s = SERVICE(u);
3055 assert(streq(s->bus_name, name));
3056 assert(old_owner || new_owner);
3058 if (old_owner && new_owner)
3059 log_debug("%s's D-Bus name %s changed owner from %s to %s", u->meta.id, name, old_owner, new_owner);
3061 log_debug("%s's D-Bus name %s no longer registered by %s", u->meta.id, name, old_owner);
3063 log_debug("%s's D-Bus name %s now registered by %s", u->meta.id, name, new_owner);
3065 s->bus_name_good = !!new_owner;
3067 if (s->type == SERVICE_DBUS) {
3069 /* service_enter_running() will figure out what to
3071 if (s->state == SERVICE_RUNNING)
3072 service_enter_running(s, true);
3073 else if (s->state == SERVICE_START && new_owner)
3074 service_enter_start_post(s);
3076 } else if (new_owner &&
3078 (s->state == SERVICE_START ||
3079 s->state == SERVICE_START_POST ||
3080 s->state == SERVICE_RUNNING ||
3081 s->state == SERVICE_RELOAD)) {
3083 /* Try to acquire PID from bus service */
3084 log_debug("Trying to acquire PID from D-Bus name...");
3086 bus_query_pid(u->meta.manager, name);
3090 static void service_bus_query_pid_done(
3095 Service *s = SERVICE(u);
3100 log_debug("%s's D-Bus name %s is now owned by process %u", u->meta.id, name, (unsigned) pid);
3102 if (s->main_pid <= 0 &&
3103 (s->state == SERVICE_START ||
3104 s->state == SERVICE_START_POST ||
3105 s->state == SERVICE_RUNNING ||
3106 s->state == SERVICE_RELOAD))
3107 service_set_main_pid(s, pid);
3110 int service_set_socket_fd(Service *s, int fd, Socket *sock) {
3114 /* This is called by the socket code when instantiating a new
3115 * service for a stream socket and the socket needs to be
3118 if (s->meta.load_state != UNIT_LOADED)
3121 if (s->socket_fd >= 0)
3124 if (s->state != SERVICE_DEAD)
3128 s->got_socket_fd = true;
3129 s->accept_socket = sock;
3134 static void service_reset_failed(Unit *u) {
3135 Service *s = SERVICE(u);
3139 if (s->state == SERVICE_FAILED)
3140 service_set_state(s, SERVICE_DEAD);
3145 static int service_kill(Unit *u, KillWho who, KillMode mode, int signo, DBusError *error) {
3146 Service *s = SERVICE(u);
3148 Set *pid_set = NULL;
3152 if (s->main_pid <= 0 && who == KILL_MAIN) {
3153 dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "No main process to kill");
3157 if (s->control_pid <= 0 && who == KILL_CONTROL) {
3158 dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "No control process to kill");
3162 if (s->control_pid > 0)
3163 if (kill(mode == KILL_PROCESS_GROUP ? -s->control_pid : s->control_pid, signo) < 0)
3166 if (s->main_pid > 0)
3167 if (kill(mode == KILL_PROCESS_GROUP ? -s->main_pid : s->main_pid, signo) < 0)
3170 if (mode == KILL_CONTROL_GROUP) {
3173 if (!(pid_set = set_new(trivial_hash_func, trivial_compare_func)))
3176 /* Exclude the control/main pid from being killed via the cgroup */
3177 if (s->control_pid > 0)
3178 if ((q = set_put(pid_set, LONG_TO_PTR(s->control_pid))) < 0) {
3183 if (s->main_pid > 0)
3184 if ((q = set_put(pid_set, LONG_TO_PTR(s->main_pid))) < 0) {
3189 if ((q = cgroup_bonding_kill_list(s->meta.cgroup_bondings, signo, pid_set)) < 0)
3190 if (r != -EAGAIN && r != -ESRCH && r != -ENOENT)
3201 static const char* const service_state_table[_SERVICE_STATE_MAX] = {
3202 [SERVICE_DEAD] = "dead",
3203 [SERVICE_START_PRE] = "start-pre",
3204 [SERVICE_START] = "start",
3205 [SERVICE_START_POST] = "start-post",
3206 [SERVICE_RUNNING] = "running",
3207 [SERVICE_EXITED] = "exited",
3208 [SERVICE_RELOAD] = "reload",
3209 [SERVICE_STOP] = "stop",
3210 [SERVICE_STOP_SIGTERM] = "stop-sigterm",
3211 [SERVICE_STOP_SIGKILL] = "stop-sigkill",
3212 [SERVICE_STOP_POST] = "stop-post",
3213 [SERVICE_FINAL_SIGTERM] = "final-sigterm",
3214 [SERVICE_FINAL_SIGKILL] = "final-sigkill",
3215 [SERVICE_FAILED] = "failed",
3216 [SERVICE_AUTO_RESTART] = "auto-restart",
3219 DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
3221 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
3222 [SERVICE_RESTART_NO] = "no",
3223 [SERVICE_RESTART_ON_SUCCESS] = "on-success",
3224 [SERVICE_RESTART_ON_FAILURE] = "on-failure",
3225 [SERVICE_RESTART_ON_ABORT] = "on-abort",
3226 [SERVICE_RESTART_ALWAYS] = "always"
3229 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
3231 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
3232 [SERVICE_SIMPLE] = "simple",
3233 [SERVICE_FORKING] = "forking",
3234 [SERVICE_ONESHOT] = "oneshot",
3235 [SERVICE_DBUS] = "dbus",
3236 [SERVICE_NOTIFY] = "notify"
3239 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
3241 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
3242 [SERVICE_EXEC_START_PRE] = "ExecStartPre",
3243 [SERVICE_EXEC_START] = "ExecStart",
3244 [SERVICE_EXEC_START_POST] = "ExecStartPost",
3245 [SERVICE_EXEC_RELOAD] = "ExecReload",
3246 [SERVICE_EXEC_STOP] = "ExecStop",
3247 [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
3250 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
3252 static const char* const notify_access_table[_NOTIFY_ACCESS_MAX] = {
3253 [NOTIFY_NONE] = "none",
3254 [NOTIFY_MAIN] = "main",
3255 [NOTIFY_ALL] = "all"
3258 DEFINE_STRING_TABLE_LOOKUP(notify_access, NotifyAccess);
3260 const UnitVTable service_vtable = {
3261 .suffix = ".service",
3262 .show_status = true,
3264 .init = service_init,
3265 .done = service_done,
3266 .load = service_load,
3268 .coldplug = service_coldplug,
3270 .dump = service_dump,
3272 .start = service_start,
3273 .stop = service_stop,
3274 .reload = service_reload,
3276 .can_reload = service_can_reload,
3278 .kill = service_kill,
3280 .serialize = service_serialize,
3281 .deserialize_item = service_deserialize_item,
3283 .active_state = service_active_state,
3284 .sub_state_to_string = service_sub_state_to_string,
3286 #ifdef HAVE_SYSV_COMPAT
3287 .check_gc = service_check_gc,
3289 .check_snapshot = service_check_snapshot,
3291 .sigchld_event = service_sigchld_event,
3292 .timer_event = service_timer_event,
3294 .reset_failed = service_reset_failed,
3296 .cgroup_notify_empty = service_cgroup_notify_event,
3297 .notify_message = service_notify_message,
3299 .bus_name_owner_change = service_bus_name_owner_change,
3300 .bus_query_pid_done = service_bus_query_pid_done,
3302 .bus_interface = "org.freedesktop.systemd1.Service",
3303 .bus_message_handler = bus_service_message_handler,
3304 .bus_invalidating_properties = bus_service_invalidating_properties,
3306 #ifdef HAVE_SYSV_COMPAT
3307 .enumerate = service_enumerate