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)
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 /* Debian extensions */
277 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU)
278 "mail-transport-agent", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
280 "mail-transfer-agent", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
281 "x-display-manager", SPECIAL_DISPLAY_MANAGER_SERVICE,
284 /* Fedora extensions */
285 "MTA", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
286 "smtpdaemon", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
287 "httpd", SPECIAL_HTTP_DAEMON_TARGET,
290 /* SuSE extensions */
302 n = *name == '$' ? name + 1 : name;
304 for (i = 0; i < ELEMENTSOF(table); i += 2) {
306 if (!streq(table[i], n))
312 if (!(r = strdup(table[i+1])))
318 /* If we don't know this name, fallback heuristics to figure
319 * out whether something is a target or a service alias. */
322 /* Facilities starting with $ are most likely targets */
323 r = unit_name_build(n, NULL, ".target");
324 else if (filename && streq(name, filename))
325 /* Names equalling the file name of the services are redundant */
328 /* Everything else we assume to be normal service names */
329 r = sysv_translate_name(n);
342 static int sysv_fix_order(Service *s) {
348 if (s->sysv_start_priority < 0)
351 /* For each pair of services where at least one lacks a LSB
352 * header, we use the start priority value to order things. */
354 LIST_FOREACH(units_per_type, other, s->meta.manager->units_per_type[UNIT_SERVICE]) {
357 bool special_s, special_t;
359 t = (Service*) other;
364 if (t->meta.load_state != UNIT_LOADED)
367 if (t->sysv_start_priority < 0)
370 /* If both units have modern headers we don't care
371 * about the priorities */
372 if ((s->meta.fragment_path || s->sysv_has_lsb) &&
373 (t->meta.fragment_path || t->sysv_has_lsb))
376 special_s = s->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, s->sysv_runlevels);
377 special_t = t->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, t->sysv_runlevels);
379 if (special_t && !special_s)
381 else if (special_s && !special_t)
383 else if (t->sysv_start_priority < s->sysv_start_priority)
385 else if (t->sysv_start_priority > s->sysv_start_priority)
390 /* FIXME: Maybe we should compare the name here lexicographically? */
392 if (!(r = unit_add_dependency(UNIT(s), d, UNIT(t), true)) < 0)
399 static ExecCommand *exec_command_new(const char *path, const char *arg1) {
402 if (!(c = new0(ExecCommand, 1)))
405 if (!(c->path = strdup(path))) {
410 if (!(c->argv = strv_new(path, arg1, NULL))) {
419 static int sysv_exec_commands(Service *s) {
423 assert(s->sysv_path);
425 if (!(c = exec_command_new(s->sysv_path, "start")))
427 exec_command_append_list(s->exec_command+SERVICE_EXEC_START, c);
429 if (!(c = exec_command_new(s->sysv_path, "stop")))
431 exec_command_append_list(s->exec_command+SERVICE_EXEC_STOP, c);
433 if (!(c = exec_command_new(s->sysv_path, "reload")))
435 exec_command_append_list(s->exec_command+SERVICE_EXEC_RELOAD, c);
440 static int service_load_sysv_path(Service *s, const char *path) {
451 char *short_description = NULL, *long_description = NULL, *chkconfig_description = NULL, *description;
458 if (!(f = fopen(path, "re"))) {
459 r = errno == ENOENT ? 0 : -errno;
464 if (!(s->sysv_path = strdup(path))) {
470 char l[LINE_MAX], *t;
472 if (!fgets(l, sizeof(l), f)) {
477 log_error("Failed to read configuration file '%s': %s", path, strerror(-r));
487 if (state == NORMAL && streq(t, "### BEGIN INIT INFO")) {
489 s->sysv_has_lsb = true;
493 if ((state == LSB_DESCRIPTION || state == LSB) && streq(t, "### END INIT INFO")) {
499 t += strspn(t, WHITESPACE);
501 if (state == NORMAL) {
503 /* Try to parse Red Hat style chkconfig headers */
505 if (startswith_no_case(t, "chkconfig:")) {
507 char runlevels[16], *k;
511 if (sscanf(t+10, "%15s %i %*i",
513 &start_priority) != 2) {
515 log_warning("[%s:%u] Failed to parse chkconfig line. Ignoring.", path, line);
519 /* A start priority gathered from the
520 * symlink farms is preferred over the
521 * data from the LSB header. */
522 if (start_priority < 0 || start_priority > 99)
523 log_warning("[%s:%u] Start priority out of range. Ignoring.", path, line);
524 else if (s->sysv_start_priority < 0)
525 s->sysv_start_priority = start_priority;
527 char_array_0(runlevels);
528 k = delete_chars(runlevels, WHITESPACE "-");
533 if (!(d = strdup(k))) {
538 free(s->sysv_runlevels);
539 s->sysv_runlevels = d;
542 } else if (startswith_no_case(t, "description:")) {
544 size_t k = strlen(t);
548 if (t[k-1] == '\\') {
553 if ((j = strstrip(t+12)) && *j) {
554 if (!(d = strdup(j))) {
561 free(chkconfig_description);
562 chkconfig_description = d;
564 } else if (startswith_no_case(t, "pidfile:")) {
571 if (!path_is_absolute(fn)) {
572 log_warning("[%s:%u] PID file not absolute. Ignoring.", path, line);
576 if (!(fn = strdup(fn))) {
585 } else if (state == DESCRIPTION) {
587 /* Try to parse Red Hat style description
590 size_t k = strlen(t);
598 if ((j = strstrip(t)) && *j) {
601 if (chkconfig_description)
602 asprintf(&d, "%s %s", chkconfig_description, j);
611 free(chkconfig_description);
612 chkconfig_description = d;
615 } else if (state == LSB || state == LSB_DESCRIPTION) {
617 if (startswith_no_case(t, "Provides:")) {
623 FOREACH_WORD_QUOTED(w, z, t+9, i) {
626 if (!(n = strndup(w, z))) {
631 r = sysv_translate_facility(n, file_name_from_path(path), &m);
640 if (unit_name_to_type(m) == UNIT_SERVICE)
641 r = unit_add_name(u, m);
643 r = unit_add_dependency_by_name(u, UNIT_BEFORE, m, NULL, true);
645 if (s->sysv_enabled) {
648 if ((k = unit_add_dependency_by_name_inverse(u, UNIT_WANTS, m, NULL, true)) < 0)
654 log_error("[%s:%u] Failed to add LSB Provides name %s, ignoring: %s", path, line, m, strerror(-r));
659 } else if (startswith_no_case(t, "Required-Start:") ||
660 startswith_no_case(t, "Should-Start:") ||
661 startswith_no_case(t, "X-Start-Before:") ||
662 startswith_no_case(t, "X-Start-After:")) {
668 FOREACH_WORD_QUOTED(w, z, strchr(t, ':')+1, i) {
671 if (!(n = strndup(w, z))) {
676 r = sysv_translate_facility(n, file_name_from_path(path), &m);
685 r = unit_add_dependency_by_name(u, startswith_no_case(t, "X-Start-Before:") ? UNIT_BEFORE : UNIT_AFTER, m, NULL, true);
688 log_error("[%s:%u] Failed to add dependency on %s, ignoring: %s", path, line, m, strerror(-r));
692 } else if (startswith_no_case(t, "Default-Start:")) {
697 k = delete_chars(t+14, WHITESPACE "-");
700 if (!(d = strdup(k))) {
705 free(s->sysv_runlevels);
706 s->sysv_runlevels = d;
709 } else if (startswith_no_case(t, "Description:")) {
712 state = LSB_DESCRIPTION;
714 if ((j = strstrip(t+12)) && *j) {
715 if (!(d = strdup(j))) {
722 free(long_description);
723 long_description = d;
725 } else if (startswith_no_case(t, "Short-Description:")) {
730 if ((j = strstrip(t+18)) && *j) {
731 if (!(d = strdup(j))) {
738 free(short_description);
739 short_description = d;
741 } else if (startswith_no_case(t, "X-Interactive:")) {
744 if ((b = parse_boolean(strstrip(t+14))) < 0) {
745 log_warning("[%s:%u] Couldn't parse interactive flag. Ignoring.", path, line);
750 s->exec_context.std_input = EXEC_INPUT_TTY;
752 s->exec_context.std_input = EXEC_INPUT_NULL;
754 } else if (state == LSB_DESCRIPTION) {
756 if (startswith(l, "#\t") || startswith(l, "# ")) {
759 if ((j = strstrip(t)) && *j) {
762 if (long_description)
763 asprintf(&d, "%s %s", long_description, t);
772 free(long_description);
773 long_description = d;
782 if ((r = sysv_exec_commands(s)) < 0)
785 if (s->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, s->sysv_runlevels)) {
786 /* If there a runlevels configured for this service
787 * but none of the standard ones, then we assume this
788 * is some special kind of service (which might be
789 * needed for early boot) and don't create any links
792 s->meta.default_dependencies = false;
794 /* Don't timeout special services during boot (like fsck) */
797 s->timeout_usec = DEFAULT_SYSV_TIMEOUT_USEC;
799 /* Special setting for all SysV services */
800 s->type = SERVICE_FORKING;
801 s->remain_after_exit = true;
802 s->restart = SERVICE_RESTART_NO;
803 s->exec_context.std_output =
804 (s->meta.manager->sysv_console || s->exec_context.std_input == EXEC_INPUT_TTY)
805 ? EXEC_OUTPUT_TTY : EXEC_OUTPUT_NULL;
806 s->exec_context.kill_mode = KILL_PROCESS_GROUP;
808 /* We use the long description only if
809 * no short description is set. */
811 if (short_description)
812 description = short_description;
813 else if (chkconfig_description)
814 description = chkconfig_description;
815 else if (long_description)
816 description = long_description;
823 if (!(d = strappend("LSB: ", description))) {
828 u->meta.description = d;
831 u->meta.load_state = UNIT_LOADED;
839 free(short_description);
840 free(long_description);
841 free(chkconfig_description);
846 static int service_load_sysv_name(Service *s, const char *name) {
852 /* For SysV services we strip the boot. or .sh
853 * prefixes/suffixes. */
854 if (startswith(name, "boot.") ||
855 endswith(name, ".sh.service"))
858 STRV_FOREACH(p, s->meta.manager->lookup_paths.sysvinit_path) {
862 if (asprintf(&path, "%s/%s", *p, name) < 0)
865 assert(endswith(path, ".service"));
866 path[strlen(path)-8] = 0;
868 r = service_load_sysv_path(s, path);
870 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
871 /* Try Debian style xxx.sh source'able init scripts */
873 r = service_load_sysv_path(s, path);
878 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
879 /* Try SUSE style boot.xxx init scripts */
881 if (asprintf(&path, "%s/boot.%s", *p, name) < 0)
884 path[strlen(path)-8] = 0;
885 r = service_load_sysv_path(s, path);
892 if ((s->meta.load_state != UNIT_STUB))
899 static int service_load_sysv(Service *s) {
906 /* Load service data from SysV init scripts, preferably with
909 if (strv_isempty(s->meta.manager->lookup_paths.sysvinit_path))
912 if ((t = s->meta.id))
913 if ((r = service_load_sysv_name(s, t)) < 0)
916 if (s->meta.load_state == UNIT_STUB)
917 SET_FOREACH(t, s->meta.names, i) {
921 if ((r = service_load_sysv_name(s, t)) < 0)
924 if (s->meta.load_state != UNIT_STUB)
932 static int fsck_fix_order(Service *s) {
938 if (s->fsck_passno <= 0)
941 /* For each pair of services where both have an fsck priority
942 * we order things based on it. */
944 LIST_FOREACH(units_per_type, other, s->meta.manager->units_per_type[UNIT_SERVICE]) {
948 t = (Service*) other;
953 if (t->meta.load_state != UNIT_LOADED)
956 if (t->fsck_passno <= 0)
959 if (t->fsck_passno < s->fsck_passno)
961 else if (t->fsck_passno > s->fsck_passno)
966 if (!(r = unit_add_dependency(UNIT(s), d, UNIT(t), true)) < 0)
973 static int service_verify(Service *s) {
976 if (s->meta.load_state != UNIT_LOADED)
979 if (!s->exec_command[SERVICE_EXEC_START]) {
980 log_error("%s lacks ExecStart setting. Refusing.", s->meta.id);
984 if (s->type != SERVICE_ONESHOT &&
985 s->exec_command[SERVICE_EXEC_START]->command_next) {
986 log_error("%s has more than one ExecStart setting, which is only allowed for Type=oneshot services. Refusing.", s->meta.id);
990 if (s->type == SERVICE_DBUS && !s->bus_name) {
991 log_error("%s is of type D-Bus but no D-Bus service name has been specified. Refusing.", s->meta.id);
995 if (s->exec_context.pam_name && s->exec_context.kill_mode != KILL_CONTROL_GROUP) {
996 log_error("%s has PAM enabled. Kill mode must be set to 'control-group'. Refusing.", s->meta.id);
1003 static int service_add_default_dependencies(Service *s) {
1008 /* Add a number of automatic dependencies useful for the
1009 * majority of services. */
1011 /* First, pull in base system */
1012 if (s->meta.manager->running_as == MANAGER_SYSTEM) {
1014 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_BASIC_TARGET, NULL, true)) < 0)
1017 } else if (s->meta.manager->running_as == MANAGER_SESSION) {
1019 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SOCKETS_TARGET, NULL, true)) < 0)
1023 /* Second, activate normal shutdown */
1024 return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true);
1027 static int service_load(Unit *u) {
1029 Service *s = SERVICE(u);
1033 /* Load a .service file */
1034 if ((r = unit_load_fragment(u)) < 0)
1037 #ifdef HAVE_SYSV_COMPAT
1038 /* Load a classic init script as a fallback, if we couldn't find anything */
1039 if (u->meta.load_state == UNIT_STUB)
1040 if ((r = service_load_sysv(s)) < 0)
1044 /* Still nothing found? Then let's give up */
1045 if (u->meta.load_state == UNIT_STUB)
1048 /* We were able to load something, then let's add in the
1049 * dropin directories. */
1050 if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
1053 /* This is a new unit? Then let's add in some extras */
1054 if (u->meta.load_state == UNIT_LOADED) {
1055 if ((r = unit_add_exec_dependencies(u, &s->exec_context)) < 0)
1058 if ((r = unit_add_default_cgroup(u)) < 0)
1061 #ifdef HAVE_SYSV_COMPAT
1062 if ((r = sysv_fix_order(s)) < 0)
1066 if ((r = fsck_fix_order(s)) < 0)
1070 if ((r = unit_watch_bus_name(u, s->bus_name)) < 0)
1073 if (s->type == SERVICE_NOTIFY && s->notify_access == NOTIFY_NONE)
1074 s->notify_access = NOTIFY_MAIN;
1076 if (s->type == SERVICE_DBUS || s->bus_name)
1077 if ((r = unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_REQUIRES, SPECIAL_DBUS_TARGET, NULL, true)) < 0)
1080 if (s->meta.default_dependencies)
1081 if ((r = service_add_default_dependencies(s)) < 0)
1085 return service_verify(s);
1088 static void service_dump(Unit *u, FILE *f, const char *prefix) {
1090 ServiceExecCommand c;
1091 Service *s = SERVICE(u);
1092 const char *prefix2;
1097 p2 = strappend(prefix, "\t");
1098 prefix2 = p2 ? p2 : prefix;
1101 "%sService State: %s\n"
1102 "%sPermissionsStartOnly: %s\n"
1103 "%sRootDirectoryStartOnly: %s\n"
1104 "%sRemainAfterExit: %s\n"
1107 "%sNotifyAccess: %s\n",
1108 prefix, service_state_to_string(s->state),
1109 prefix, yes_no(s->permissions_start_only),
1110 prefix, yes_no(s->root_directory_start_only),
1111 prefix, yes_no(s->remain_after_exit),
1112 prefix, service_type_to_string(s->type),
1113 prefix, service_restart_to_string(s->restart),
1114 prefix, notify_access_to_string(s->notify_access));
1116 if (s->control_pid > 0)
1118 "%sControl PID: %lu\n",
1119 prefix, (unsigned long) s->control_pid);
1121 if (s->main_pid > 0)
1123 "%sMain PID: %lu\n",
1124 prefix, (unsigned long) s->main_pid);
1129 prefix, s->pid_file);
1134 "%sBus Name Good: %s\n",
1135 prefix, s->bus_name,
1136 prefix, yes_no(s->bus_name_good));
1138 exec_context_dump(&s->exec_context, f, prefix);
1140 for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
1142 if (!s->exec_command[c])
1145 fprintf(f, "%s-> %s:\n",
1146 prefix, service_exec_command_to_string(c));
1148 exec_command_dump_list(s->exec_command[c], f, prefix2);
1151 #ifdef HAVE_SYSV_COMPAT
1154 "%sSysV Init Script Path: %s\n"
1155 "%sSysV Init Script has LSB Header: %s\n"
1156 "%sSysVEnabled: %s\n",
1157 prefix, s->sysv_path,
1158 prefix, yes_no(s->sysv_has_lsb),
1159 prefix, yes_no(s->sysv_enabled));
1161 if (s->sysv_start_priority >= 0)
1163 "%sSysVStartPriority: %i\n",
1164 prefix, s->sysv_start_priority);
1166 if (s->sysv_runlevels)
1167 fprintf(f, "%sSysVRunLevels: %s\n",
1168 prefix, s->sysv_runlevels);
1171 if (s->fsck_passno > 0)
1173 "%sFsckPassNo: %i\n",
1174 prefix, s->fsck_passno);
1177 fprintf(f, "%sStatus Text: %s\n",
1178 prefix, s->status_text);
1183 static int service_load_pid_file(Service *s) {
1190 if (s->main_pid_known)
1193 assert(s->main_pid <= 0);
1198 if ((r = read_one_line_file(s->pid_file, &k)) < 0)
1201 r = parse_pid(k, &pid);
1207 if (kill(pid, 0) < 0 && errno != EPERM) {
1208 log_warning("PID %lu read from file %s does not exist. Your service or init script might be broken.",
1209 (unsigned long) pid, s->pid_file);
1213 if ((r = service_set_main_pid(s, pid)) < 0)
1216 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1217 /* FIXME: we need to do something here */
1223 static int service_search_main_pid(Service *s) {
1229 if (s->main_pid_known)
1232 assert(s->main_pid <= 0);
1234 if ((pid = cgroup_bonding_search_main_pid_list(s->meta.cgroup_bondings)) <= 0)
1237 if ((r = service_set_main_pid(s, pid)) < 0)
1240 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1241 /* FIXME: we need to do something here */
1247 static int service_get_sockets(Service *s, Set **_set) {
1256 if (s->socket_fd >= 0)
1259 if (!set_isempty(s->configured_sockets))
1262 /* Collects all Socket objects that belong to this
1263 * service. Note that a service might have multiple sockets
1264 * via multiple names. */
1266 if (!(set = set_new(NULL, NULL)))
1269 SET_FOREACH(t, s->meta.names, i) {
1273 /* Look for all socket objects that go by any of our
1274 * units and collect their fds */
1276 if (!(k = unit_name_change_suffix(t, ".socket"))) {
1281 p = manager_get_unit(s->meta.manager, k);
1287 if ((r = set_put(set, p)) < 0)
1299 static int service_notify_sockets_dead(Service *s) {
1301 Set *set, *free_set = NULL;
1307 /* Notifies all our sockets when we die */
1309 if (s->socket_fd >= 0)
1312 if (!set_isempty(s->configured_sockets))
1313 set = s->configured_sockets;
1315 if ((r = service_get_sockets(s, &free_set)) < 0)
1321 SET_FOREACH(sock, set, i)
1322 socket_notify_service_dead(sock);
1329 static void service_set_state(Service *s, ServiceState state) {
1330 ServiceState old_state;
1333 old_state = s->state;
1336 if (state != SERVICE_START_PRE &&
1337 state != SERVICE_START &&
1338 state != SERVICE_START_POST &&
1339 state != SERVICE_RELOAD &&
1340 state != SERVICE_STOP &&
1341 state != SERVICE_STOP_SIGTERM &&
1342 state != SERVICE_STOP_SIGKILL &&
1343 state != SERVICE_STOP_POST &&
1344 state != SERVICE_FINAL_SIGTERM &&
1345 state != SERVICE_FINAL_SIGKILL &&
1346 state != SERVICE_AUTO_RESTART)
1347 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1349 if (state != SERVICE_START &&
1350 state != SERVICE_START_POST &&
1351 state != SERVICE_RUNNING &&
1352 state != SERVICE_RELOAD &&
1353 state != SERVICE_STOP &&
1354 state != SERVICE_STOP_SIGTERM &&
1355 state != SERVICE_STOP_SIGKILL)
1356 service_unwatch_main_pid(s);
1358 if (state != SERVICE_START_PRE &&
1359 state != SERVICE_START &&
1360 state != SERVICE_START_POST &&
1361 state != SERVICE_RELOAD &&
1362 state != SERVICE_STOP &&
1363 state != SERVICE_STOP_SIGTERM &&
1364 state != SERVICE_STOP_SIGKILL &&
1365 state != SERVICE_STOP_POST &&
1366 state != SERVICE_FINAL_SIGTERM &&
1367 state != SERVICE_FINAL_SIGKILL) {
1368 service_unwatch_control_pid(s);
1369 s->control_command = NULL;
1370 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1373 if (state == SERVICE_DEAD ||
1374 state == SERVICE_STOP ||
1375 state == SERVICE_STOP_SIGTERM ||
1376 state == SERVICE_STOP_SIGKILL ||
1377 state == SERVICE_STOP_POST ||
1378 state == SERVICE_FINAL_SIGTERM ||
1379 state == SERVICE_FINAL_SIGKILL ||
1380 state == SERVICE_FAILED ||
1381 state == SERVICE_AUTO_RESTART)
1382 service_notify_sockets_dead(s);
1384 if (state != SERVICE_START_PRE &&
1385 state != SERVICE_START &&
1386 state != SERVICE_START_POST &&
1387 state != SERVICE_RUNNING &&
1388 state != SERVICE_RELOAD &&
1389 state != SERVICE_STOP &&
1390 state != SERVICE_STOP_SIGTERM &&
1391 state != SERVICE_STOP_SIGKILL &&
1392 state != SERVICE_STOP_POST &&
1393 state != SERVICE_FINAL_SIGTERM &&
1394 state != SERVICE_FINAL_SIGKILL &&
1395 !(state == SERVICE_DEAD && s->meta.job)) {
1396 service_close_socket_fd(s);
1397 service_connection_unref(s);
1400 /* For the inactive states unit_notify() will trim the cgroup,
1401 * but for exit we have to do that ourselves... */
1402 if (state == SERVICE_EXITED)
1403 cgroup_bonding_trim_list(s->meta.cgroup_bondings, true);
1405 if (old_state != state)
1406 log_debug("%s changed %s -> %s", s->meta.id, service_state_to_string(old_state), service_state_to_string(state));
1408 unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state]);
1411 static int service_coldplug(Unit *u) {
1412 Service *s = SERVICE(u);
1416 assert(s->state == SERVICE_DEAD);
1418 if (s->deserialized_state != s->state) {
1420 if (s->deserialized_state == SERVICE_START_PRE ||
1421 s->deserialized_state == SERVICE_START ||
1422 s->deserialized_state == SERVICE_START_POST ||
1423 s->deserialized_state == SERVICE_RELOAD ||
1424 s->deserialized_state == SERVICE_STOP ||
1425 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1426 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1427 s->deserialized_state == SERVICE_STOP_POST ||
1428 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1429 s->deserialized_state == SERVICE_FINAL_SIGKILL ||
1430 s->deserialized_state == SERVICE_AUTO_RESTART) {
1432 if (s->deserialized_state == SERVICE_AUTO_RESTART || s->timeout_usec > 0) {
1435 k = s->deserialized_state == SERVICE_AUTO_RESTART ? s->restart_usec : s->timeout_usec;
1437 if ((r = unit_watch_timer(UNIT(s), k, &s->timer_watch)) < 0)
1442 if ((s->deserialized_state == SERVICE_START &&
1443 (s->type == SERVICE_FORKING ||
1444 s->type == SERVICE_DBUS ||
1445 s->type == SERVICE_ONESHOT ||
1446 s->type == SERVICE_NOTIFY)) ||
1447 s->deserialized_state == SERVICE_START_POST ||
1448 s->deserialized_state == SERVICE_RUNNING ||
1449 s->deserialized_state == SERVICE_RELOAD ||
1450 s->deserialized_state == SERVICE_STOP ||
1451 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1452 s->deserialized_state == SERVICE_STOP_SIGKILL)
1453 if (s->main_pid > 0)
1454 if ((r = unit_watch_pid(UNIT(s), s->main_pid)) < 0)
1457 if (s->deserialized_state == SERVICE_START_PRE ||
1458 s->deserialized_state == SERVICE_START ||
1459 s->deserialized_state == SERVICE_START_POST ||
1460 s->deserialized_state == SERVICE_RELOAD ||
1461 s->deserialized_state == SERVICE_STOP ||
1462 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1463 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1464 s->deserialized_state == SERVICE_STOP_POST ||
1465 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1466 s->deserialized_state == SERVICE_FINAL_SIGKILL)
1467 if (s->control_pid > 0)
1468 if ((r = unit_watch_pid(UNIT(s), s->control_pid)) < 0)
1471 service_set_state(s, s->deserialized_state);
1477 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
1481 unsigned rn_fds = 0;
1482 Set *set, *free_set = NULL;
1489 if (s->socket_fd >= 0)
1492 if (!set_isempty(s->configured_sockets))
1493 set = s->configured_sockets;
1495 if ((r = service_get_sockets(s, &free_set)) < 0)
1501 SET_FOREACH(sock, set, i) {
1505 if ((r = socket_collect_fds(sock, &cfds, &cn_fds)) < 0)
1517 if (!(t = new(int, rn_fds+cn_fds))) {
1523 memcpy(t, rfds, rn_fds);
1524 memcpy(t+rn_fds, cfds, cn_fds);
1529 rn_fds = rn_fds+cn_fds;
1547 static int service_spawn(
1552 bool apply_permissions,
1554 bool apply_tty_stdin,
1555 bool set_notify_socket,
1560 int *fds = NULL, *fdsbuf = NULL;
1561 unsigned n_fds = 0, n_env = 0;
1562 char **argv = NULL, **final_env = NULL, **our_env = NULL;
1569 s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1570 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1571 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
1573 if (s->socket_fd >= 0) {
1574 fds = &s->socket_fd;
1577 if ((r = service_collect_fds(s, &fdsbuf, &n_fds)) < 0)
1584 if (timeout && s->timeout_usec) {
1585 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1588 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1590 if (!(argv = unit_full_printf_strv(UNIT(s), c->argv))) {
1595 if (!(our_env = new0(char*, 4))) {
1600 if (set_notify_socket)
1601 if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=@%s", s->meta.manager->notify_socket) < 0) {
1606 if (s->main_pid > 0)
1607 if (asprintf(our_env + n_env++, "MAINPID=%lu", (unsigned long) s->main_pid) < 0) {
1612 #ifdef HAVE_SYSV_COMPAT
1613 /* Make sure we set TERM=linux for SysV scripts, since some
1614 * require it to be set from the kernel */
1615 if (s->sysv_path && !strv_env_get(s->meta.manager->environment, "TERM"))
1616 if (!(our_env[n_env++] = strdup("TERM=linux"))) {
1622 if (!(final_env = strv_env_merge(2,
1623 s->meta.manager->environment,
1638 s->meta.manager->confirm_spawn,
1639 s->meta.cgroup_bondings,
1646 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1647 /* FIXME: we need to do something here */
1653 strv_free(final_env);
1663 strv_free(final_env);
1666 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1671 static int main_pid_good(Service *s) {
1674 /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1677 /* If we know the pid file, then lets just check if it is
1679 if (s->main_pid_known)
1680 return s->main_pid > 0;
1682 /* We don't know the pid */
1686 static int control_pid_good(Service *s) {
1689 return s->control_pid > 0;
1692 static int cgroup_good(Service *s) {
1697 if ((r = cgroup_bonding_is_empty_list(s->meta.cgroup_bondings)) < 0)
1703 static void service_enter_dead(Service *s, bool success, bool allow_restart) {
1710 if (allow_restart &&
1711 !s->forbid_restart &&
1712 (s->restart == SERVICE_RESTART_ALWAYS ||
1713 (s->restart == SERVICE_RESTART_ON_SUCCESS && !s->failure) ||
1714 (s->restart == SERVICE_RESTART_ON_FAILURE && s->failure) ||
1715 (s->restart == SERVICE_RESTART_ON_ABORT && s->failure &&
1716 (s->main_exec_status.code == CLD_KILLED ||
1717 s->main_exec_status.code == CLD_DUMPED)))) {
1719 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
1722 service_set_state(s, SERVICE_AUTO_RESTART);
1724 service_set_state(s, s->failure ? SERVICE_FAILED : SERVICE_DEAD);
1726 s->forbid_restart = false;
1731 log_warning("%s failed to run install restart timer: %s", s->meta.id, strerror(-r));
1732 service_enter_dead(s, false, false);
1735 static void service_enter_signal(Service *s, ServiceState state, bool success);
1737 static void service_enter_stop_post(Service *s, bool success) {
1744 service_unwatch_control_pid(s);
1746 s->control_command_id = SERVICE_EXEC_STOP_POST;
1747 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST])) {
1748 if ((r = service_spawn(s,
1752 !s->permissions_start_only,
1753 !s->root_directory_start_only,
1756 &s->control_pid)) < 0)
1760 service_set_state(s, SERVICE_STOP_POST);
1762 service_enter_signal(s, SERVICE_FINAL_SIGTERM, true);
1767 log_warning("%s failed to run 'stop-post' task: %s", s->meta.id, strerror(-r));
1768 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1771 static void service_enter_signal(Service *s, ServiceState state, bool success) {
1773 Set *pid_set = NULL;
1774 bool wait_for_exit = false;
1781 if (s->exec_context.kill_mode != KILL_NONE) {
1782 int sig = (state == SERVICE_STOP_SIGTERM || state == SERVICE_FINAL_SIGTERM) ? s->exec_context.kill_signal : SIGKILL;
1784 if (s->main_pid > 0) {
1785 if (kill(s->exec_context.kill_mode == KILL_PROCESS_GROUP ?
1787 s->main_pid, sig) < 0 && errno != ESRCH)
1789 log_warning("Failed to kill main process %li: %m", (long) s->main_pid);
1791 wait_for_exit = true;
1794 if (s->control_pid > 0) {
1795 if (kill(s->exec_context.kill_mode == KILL_PROCESS_GROUP ?
1797 s->control_pid, sig) < 0 && errno != ESRCH)
1799 log_warning("Failed to kill control process %li: %m", (long) s->control_pid);
1801 wait_for_exit = true;
1804 if (s->exec_context.kill_mode == KILL_CONTROL_GROUP) {
1806 if (!(pid_set = set_new(trivial_hash_func, trivial_compare_func))) {
1811 /* Exclude the main/control pids from being killed via the cgroup */
1812 if (s->main_pid > 0)
1813 if ((r = set_put(pid_set, LONG_TO_PTR(s->main_pid))) < 0)
1816 if (s->control_pid > 0)
1817 if ((r = set_put(pid_set, LONG_TO_PTR(s->control_pid))) < 0)
1820 if ((r = cgroup_bonding_kill_list(s->meta.cgroup_bondings, sig, pid_set)) < 0) {
1821 if (r != -EAGAIN && r != -ESRCH && r != -ENOENT)
1822 log_warning("Failed to kill control group: %s", strerror(-r));
1824 wait_for_exit = true;
1830 if (wait_for_exit) {
1831 if (s->timeout_usec > 0)
1832 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1835 service_set_state(s, state);
1836 } else if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1837 service_enter_stop_post(s, true);
1839 service_enter_dead(s, true, true);
1844 log_warning("%s failed to kill processes: %s", s->meta.id, strerror(-r));
1846 if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1847 service_enter_stop_post(s, false);
1849 service_enter_dead(s, false, true);
1855 static void service_enter_stop(Service *s, bool success) {
1863 service_unwatch_control_pid(s);
1865 s->control_command_id = SERVICE_EXEC_STOP;
1866 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP])) {
1867 if ((r = service_spawn(s,
1871 !s->permissions_start_only,
1872 !s->root_directory_start_only,
1875 &s->control_pid)) < 0)
1878 service_set_state(s, SERVICE_STOP);
1880 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
1885 log_warning("%s failed to run 'stop' task: %s", s->meta.id, strerror(-r));
1886 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1889 static void service_enter_running(Service *s, bool success) {
1890 int main_pid_ok, cgroup_ok;
1896 main_pid_ok = main_pid_good(s);
1897 cgroup_ok = cgroup_good(s);
1899 if ((main_pid_ok > 0 || (main_pid_ok < 0 && cgroup_ok != 0)) &&
1900 (s->bus_name_good || s->type != SERVICE_DBUS))
1901 service_set_state(s, SERVICE_RUNNING);
1902 else if (s->remain_after_exit)
1903 service_set_state(s, SERVICE_EXITED);
1905 service_enter_stop(s, true);
1908 static void service_enter_start_post(Service *s) {
1912 service_unwatch_control_pid(s);
1914 s->control_command_id = SERVICE_EXEC_START_POST;
1915 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_POST])) {
1916 if ((r = service_spawn(s,
1920 !s->permissions_start_only,
1921 !s->root_directory_start_only,
1924 &s->control_pid)) < 0)
1927 service_set_state(s, SERVICE_START_POST);
1929 service_enter_running(s, true);
1934 log_warning("%s failed to run 'start-post' task: %s", s->meta.id, strerror(-r));
1935 service_enter_stop(s, false);
1938 static void service_enter_start(Service *s) {
1944 assert(s->exec_command[SERVICE_EXEC_START]);
1945 assert(!s->exec_command[SERVICE_EXEC_START]->command_next || s->type == SERVICE_ONESHOT);
1947 if (s->type == SERVICE_FORKING)
1948 service_unwatch_control_pid(s);
1950 service_unwatch_main_pid(s);
1952 s->control_command_id = SERVICE_EXEC_START;
1953 s->control_command = s->exec_command[SERVICE_EXEC_START];
1955 if ((r = service_spawn(s,
1957 s->type == SERVICE_FORKING || s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY,
1962 s->notify_access != NOTIFY_NONE,
1966 if (s->type == SERVICE_SIMPLE) {
1967 /* For simple services we immediately start
1968 * the START_POST binaries. */
1970 service_set_main_pid(s, pid);
1971 service_enter_start_post(s);
1973 } else if (s->type == SERVICE_FORKING) {
1975 /* For forking services we wait until the start
1976 * process exited. */
1978 s->control_pid = pid;
1979 service_set_state(s, SERVICE_START);
1981 } else if (s->type == SERVICE_ONESHOT ||
1982 s->type == SERVICE_DBUS ||
1983 s->type == SERVICE_NOTIFY) {
1985 /* For oneshot services we wait until the start
1986 * process exited, too, but it is our main process. */
1988 /* For D-Bus services we know the main pid right away,
1989 * but wait for the bus name to appear on the
1990 * bus. Notify services are similar. */
1992 service_set_main_pid(s, pid);
1993 service_set_state(s, SERVICE_START);
1995 assert_not_reached("Unknown service type");
2000 log_warning("%s failed to run 'start' task: %s", s->meta.id, strerror(-r));
2001 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2004 static void service_enter_start_pre(Service *s) {
2009 service_unwatch_control_pid(s);
2011 s->control_command_id = SERVICE_EXEC_START_PRE;
2012 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_PRE])) {
2013 if ((r = service_spawn(s,
2017 !s->permissions_start_only,
2018 !s->root_directory_start_only,
2021 &s->control_pid)) < 0)
2024 service_set_state(s, SERVICE_START_PRE);
2026 service_enter_start(s);
2031 log_warning("%s failed to run 'start-pre' task: %s", s->meta.id, strerror(-r));
2032 service_enter_dead(s, false, true);
2035 static void service_enter_restart(Service *s) {
2040 dbus_error_init(&error);
2042 service_enter_dead(s, true, false);
2044 if ((r = manager_add_job(s->meta.manager, JOB_START, UNIT(s), JOB_FAIL, false, &error, NULL)) < 0)
2047 log_debug("%s scheduled restart job.", s->meta.id);
2051 log_warning("%s failed to schedule restart job: %s", s->meta.id, bus_error(&error, -r));
2052 service_enter_dead(s, false, false);
2054 dbus_error_free(&error);
2057 static void service_enter_reload(Service *s) {
2062 service_unwatch_control_pid(s);
2064 s->control_command_id = SERVICE_EXEC_RELOAD;
2065 if ((s->control_command = s->exec_command[SERVICE_EXEC_RELOAD])) {
2066 if ((r = service_spawn(s,
2070 !s->permissions_start_only,
2071 !s->root_directory_start_only,
2074 &s->control_pid)) < 0)
2077 service_set_state(s, SERVICE_RELOAD);
2079 service_enter_running(s, true);
2084 log_warning("%s failed to run 'reload' task: %s", s->meta.id, strerror(-r));
2085 service_enter_stop(s, false);
2088 static void service_run_next_control(Service *s, bool success) {
2092 assert(s->control_command);
2093 assert(s->control_command->command_next);
2098 assert(s->control_command_id != SERVICE_EXEC_START);
2100 s->control_command = s->control_command->command_next;
2101 service_unwatch_control_pid(s);
2103 if ((r = service_spawn(s,
2107 !s->permissions_start_only,
2108 !s->root_directory_start_only,
2109 s->control_command_id == SERVICE_EXEC_START_PRE ||
2110 s->control_command_id == SERVICE_EXEC_STOP_POST,
2112 &s->control_pid)) < 0)
2118 log_warning("%s failed to run next control task: %s", s->meta.id, strerror(-r));
2120 if (s->state == SERVICE_START_PRE)
2121 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2122 else if (s->state == SERVICE_STOP)
2123 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
2124 else if (s->state == SERVICE_STOP_POST)
2125 service_enter_dead(s, false, true);
2127 service_enter_stop(s, false);
2130 static void service_run_next_main(Service *s, bool success) {
2135 assert(s->control_command);
2136 assert(s->control_command->command_next);
2141 assert(s->control_command_id == SERVICE_EXEC_START);
2142 assert(s->type == SERVICE_ONESHOT);
2144 s->control_command = s->control_command->command_next;
2145 service_unwatch_main_pid(s);
2147 if ((r = service_spawn(s,
2154 s->notify_access != NOTIFY_NONE,
2158 service_set_main_pid(s, pid);
2163 log_warning("%s failed to run next main task: %s", s->meta.id, strerror(-r));
2164 service_enter_stop(s, false);
2167 static int service_start(Unit *u) {
2168 Service *s = SERVICE(u);
2172 /* We cannot fulfill this request right now, try again later
2174 if (s->state == SERVICE_STOP ||
2175 s->state == SERVICE_STOP_SIGTERM ||
2176 s->state == SERVICE_STOP_SIGKILL ||
2177 s->state == SERVICE_STOP_POST ||
2178 s->state == SERVICE_FINAL_SIGTERM ||
2179 s->state == SERVICE_FINAL_SIGKILL)
2182 /* Already on it! */
2183 if (s->state == SERVICE_START_PRE ||
2184 s->state == SERVICE_START ||
2185 s->state == SERVICE_START_POST)
2188 assert(s->state == SERVICE_DEAD || s->state == SERVICE_FAILED || s->state == SERVICE_AUTO_RESTART);
2190 /* Make sure we don't enter a busy loop of some kind. */
2191 if (!ratelimit_test(&s->ratelimit)) {
2192 log_warning("%s start request repeated too quickly, refusing to start.", u->meta.id);
2197 s->main_pid_known = false;
2198 s->forbid_restart = false;
2200 service_enter_start_pre(s);
2204 static int service_stop(Unit *u) {
2205 Service *s = SERVICE(u);
2209 /* This is a user request, so don't do restarts on this
2211 s->forbid_restart = true;
2214 if (s->state == SERVICE_STOP ||
2215 s->state == SERVICE_STOP_SIGTERM ||
2216 s->state == SERVICE_STOP_SIGKILL ||
2217 s->state == SERVICE_STOP_POST ||
2218 s->state == SERVICE_FINAL_SIGTERM ||
2219 s->state == SERVICE_FINAL_SIGKILL)
2222 /* Don't allow a restart */
2223 if (s->state == SERVICE_AUTO_RESTART) {
2224 service_set_state(s, SERVICE_DEAD);
2228 /* If there's already something running we go directly into
2230 if (s->state == SERVICE_START_PRE ||
2231 s->state == SERVICE_START ||
2232 s->state == SERVICE_START_POST ||
2233 s->state == SERVICE_RELOAD) {
2234 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
2238 assert(s->state == SERVICE_RUNNING ||
2239 s->state == SERVICE_EXITED);
2241 service_enter_stop(s, true);
2245 static int service_reload(Unit *u) {
2246 Service *s = SERVICE(u);
2250 assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
2252 service_enter_reload(s);
2256 static bool service_can_reload(Unit *u) {
2257 Service *s = SERVICE(u);
2261 return !!s->exec_command[SERVICE_EXEC_RELOAD];
2264 static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
2265 Service *s = SERVICE(u);
2271 unit_serialize_item(u, f, "state", service_state_to_string(s->state));
2272 unit_serialize_item(u, f, "failure", yes_no(s->failure));
2274 if (s->control_pid > 0)
2275 unit_serialize_item_format(u, f, "control-pid", "%lu", (unsigned long) s->control_pid);
2277 if (s->main_pid_known && s->main_pid > 0)
2278 unit_serialize_item_format(u, f, "main-pid", "%lu", (unsigned long) s->main_pid);
2280 unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
2283 unit_serialize_item(u, f, "status-text", s->status_text);
2285 /* There's a minor uncleanliness here: if there are multiple
2286 * commands attached here, we will start from the first one
2288 if (s->control_command_id >= 0)
2289 unit_serialize_item(u, f, "control-command", service_exec_command_to_string(s->control_command_id));
2291 if (s->socket_fd >= 0) {
2294 if ((copy = fdset_put_dup(fds, s->socket_fd)) < 0)
2297 unit_serialize_item_format(u, f, "socket-fd", "%i", copy);
2300 if (s->main_exec_status.pid > 0) {
2301 unit_serialize_item_format(u, f, "main-exec-status-pid", "%lu", (unsigned long) s->main_exec_status.pid);
2302 dual_timestamp_serialize(f, "main-exec-status-start", &s->main_exec_status.start_timestamp);
2303 dual_timestamp_serialize(f, "main-exec-status-exit", &s->main_exec_status.exit_timestamp);
2305 if (dual_timestamp_is_set(&s->main_exec_status.exit_timestamp)) {
2306 unit_serialize_item_format(u, f, "main-exec-status-code", "%i", s->main_exec_status.code);
2307 unit_serialize_item_format(u, f, "main-exec-status-status", "%i", s->main_exec_status.status);
2314 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
2315 Service *s = SERVICE(u);
2322 if (streq(key, "state")) {
2325 if ((state = service_state_from_string(value)) < 0)
2326 log_debug("Failed to parse state value %s", value);
2328 s->deserialized_state = state;
2329 } else if (streq(key, "failure")) {
2332 if ((b = parse_boolean(value)) < 0)
2333 log_debug("Failed to parse failure value %s", value);
2335 s->failure = b || s->failure;
2336 } else if (streq(key, "control-pid")) {
2339 if (parse_pid(value, &pid) < 0)
2340 log_debug("Failed to parse control-pid value %s", value);
2342 s->control_pid = pid;
2343 } else if (streq(key, "main-pid")) {
2346 if (parse_pid(value, &pid) < 0)
2347 log_debug("Failed to parse main-pid value %s", value);
2349 service_set_main_pid(s, (pid_t) pid);
2350 } else if (streq(key, "main-pid-known")) {
2353 if ((b = parse_boolean(value)) < 0)
2354 log_debug("Failed to parse main-pid-known value %s", value);
2356 s->main_pid_known = b;
2357 } else if (streq(key, "status-text")) {
2360 if ((t = strdup(value))) {
2361 free(s->status_text);
2365 } else if (streq(key, "control-command")) {
2366 ServiceExecCommand id;
2368 if ((id = service_exec_command_from_string(value)) < 0)
2369 log_debug("Failed to parse exec-command value %s", value);
2371 s->control_command_id = id;
2372 s->control_command = s->exec_command[id];
2374 } else if (streq(key, "socket-fd")) {
2377 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2378 log_debug("Failed to parse socket-fd value %s", value);
2381 if (s->socket_fd >= 0)
2382 close_nointr_nofail(s->socket_fd);
2383 s->socket_fd = fdset_remove(fds, fd);
2385 } else if (streq(key, "main-exec-status-pid")) {
2388 if (parse_pid(value, &pid) < 0)
2389 log_debug("Failed to parse main-exec-status-pid value %s", value);
2391 s->main_exec_status.pid = pid;
2392 } else if (streq(key, "main-exec-status-code")) {
2395 if (safe_atoi(value, &i) < 0)
2396 log_debug("Failed to parse main-exec-status-code value %s", value);
2398 s->main_exec_status.code = i;
2399 } else if (streq(key, "main-exec-status-status")) {
2402 if (safe_atoi(value, &i) < 0)
2403 log_debug("Failed to parse main-exec-status-status value %s", value);
2405 s->main_exec_status.status = i;
2406 } else if (streq(key, "main-exec-status-start"))
2407 dual_timestamp_deserialize(value, &s->main_exec_status.start_timestamp);
2408 else if (streq(key, "main-exec-status-exit"))
2409 dual_timestamp_deserialize(value, &s->main_exec_status.exit_timestamp);
2411 log_debug("Unknown serialization key '%s'", key);
2416 static UnitActiveState service_active_state(Unit *u) {
2419 return state_translation_table[SERVICE(u)->state];
2422 static const char *service_sub_state_to_string(Unit *u) {
2425 return service_state_to_string(SERVICE(u)->state);
2428 #ifdef HAVE_SYSV_COMPAT
2429 static bool service_check_gc(Unit *u) {
2430 Service *s = SERVICE(u);
2434 return !!s->sysv_path;
2438 static bool service_check_snapshot(Unit *u) {
2439 Service *s = SERVICE(u);
2443 return !s->got_socket_fd;
2446 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2447 Service *s = SERVICE(u);
2453 if (!s->meta.fragment_path)
2454 success = is_clean_exit_lsb(code, status);
2456 success = is_clean_exit(code, status);
2458 if (s->main_pid == pid) {
2461 exec_status_exit(&s->main_exec_status, pid, code, status, s->exec_context.utmp_id);
2463 if (s->type != SERVICE_FORKING && s->control_command) {
2464 s->control_command->exec_status = s->main_exec_status;
2466 if (s->control_command->ignore)
2470 log_full(success ? LOG_DEBUG : LOG_NOTICE,
2471 "%s: main process exited, code=%s, status=%i", u->meta.id, sigchld_code_to_string(code), status);
2472 s->failure = s->failure || !success;
2474 if (s->control_command &&
2475 s->control_command->command_next &&
2478 /* There is another command to *
2479 * execute, so let's do that. */
2481 log_debug("%s running next main command for state %s", u->meta.id, service_state_to_string(s->state));
2482 service_run_next_main(s, success);
2486 /* The service exited, so the service is officially
2489 s->control_command = NULL;
2490 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2494 case SERVICE_START_POST:
2495 case SERVICE_RELOAD:
2497 /* Need to wait until the operation is
2502 if (s->type == SERVICE_ONESHOT) {
2503 /* This was our main goal, so let's go on */
2505 service_enter_start_post(s);
2507 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2510 assert(s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY);
2515 case SERVICE_RUNNING:
2516 service_enter_running(s, success);
2519 case SERVICE_STOP_SIGTERM:
2520 case SERVICE_STOP_SIGKILL:
2522 if (!control_pid_good(s))
2523 service_enter_stop_post(s, success);
2525 /* If there is still a control process, wait for that first */
2529 assert_not_reached("Uh, main process died at wrong time.");
2533 } else if (s->control_pid == pid) {
2537 if (s->control_command) {
2538 exec_status_exit(&s->control_command->exec_status, pid, code, status, s->exec_context.utmp_id);
2540 if (s->control_command->ignore)
2544 log_full(success ? LOG_DEBUG : LOG_NOTICE,
2545 "%s: control process exited, code=%s status=%i", u->meta.id, sigchld_code_to_string(code), status);
2546 s->failure = s->failure || !success;
2548 if (s->control_command &&
2549 s->control_command->command_next &&
2552 /* There is another command to *
2553 * execute, so let's do that. */
2555 log_debug("%s running next control command for state %s", u->meta.id, service_state_to_string(s->state));
2556 service_run_next_control(s, success);
2559 /* No further commands for this step, so let's
2560 * figure out what to do next */
2562 s->control_command = NULL;
2563 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2565 log_debug("%s got final SIGCHLD for state %s", u->meta.id, service_state_to_string(s->state));
2569 case SERVICE_START_PRE:
2571 service_enter_start(s);
2573 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2577 assert(s->type == SERVICE_FORKING);
2579 /* Let's try to load the pid
2580 * file here if we can. We
2581 * ignore the return value,
2582 * since the PID file might
2583 * actually be created by a
2584 * START_POST script */
2587 service_load_pid_file(s);
2588 service_search_main_pid(s);
2590 service_enter_start_post(s);
2592 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2596 case SERVICE_START_POST:
2597 if (success && s->pid_file && !s->main_pid_known) {
2600 /* Hmm, let's see if we can
2601 * load the pid now after the
2602 * start-post scripts got
2605 if ((r = service_load_pid_file(s)) < 0)
2606 log_warning("%s: failed to load PID file %s: %s", s->meta.id, s->pid_file, strerror(-r));
2611 case SERVICE_RELOAD:
2613 service_enter_running(s, true);
2615 service_enter_stop(s, false);
2620 service_enter_signal(s, SERVICE_STOP_SIGTERM, success);
2623 case SERVICE_STOP_SIGTERM:
2624 case SERVICE_STOP_SIGKILL:
2625 if (main_pid_good(s) <= 0)
2626 service_enter_stop_post(s, success);
2628 /* If there is still a service
2629 * process around, wait until
2630 * that one quit, too */
2633 case SERVICE_STOP_POST:
2634 case SERVICE_FINAL_SIGTERM:
2635 case SERVICE_FINAL_SIGKILL:
2636 service_enter_dead(s, success, true);
2640 assert_not_reached("Uh, control process died at wrong time.");
2645 /* Notify clients about changed exit status */
2646 unit_add_to_dbus_queue(u);
2649 static void service_timer_event(Unit *u, uint64_t elapsed, Watch* w) {
2650 Service *s = SERVICE(u);
2653 assert(elapsed == 1);
2655 assert(w == &s->timer_watch);
2659 case SERVICE_START_PRE:
2661 log_warning("%s operation timed out. Terminating.", u->meta.id);
2662 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2665 case SERVICE_START_POST:
2666 case SERVICE_RELOAD:
2667 log_warning("%s operation timed out. Stopping.", u->meta.id);
2668 service_enter_stop(s, false);
2672 log_warning("%s stopping timed out. Terminating.", u->meta.id);
2673 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
2676 case SERVICE_STOP_SIGTERM:
2677 log_warning("%s stopping timed out. Killing.", u->meta.id);
2678 service_enter_signal(s, SERVICE_STOP_SIGKILL, false);
2681 case SERVICE_STOP_SIGKILL:
2682 /* Uh, wie sent a SIGKILL and it is still not gone?
2683 * Must be something we cannot kill, so let's just be
2684 * weirded out and continue */
2686 log_warning("%s still around after SIGKILL. Ignoring.", u->meta.id);
2687 service_enter_stop_post(s, false);
2690 case SERVICE_STOP_POST:
2691 log_warning("%s stopping timed out (2). Terminating.", u->meta.id);
2692 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2695 case SERVICE_FINAL_SIGTERM:
2696 log_warning("%s stopping timed out (2). Killing.", u->meta.id);
2697 service_enter_signal(s, SERVICE_FINAL_SIGKILL, false);
2700 case SERVICE_FINAL_SIGKILL:
2701 log_warning("%s still around after SIGKILL (2). Entering failed mode.", u->meta.id);
2702 service_enter_dead(s, false, true);
2705 case SERVICE_AUTO_RESTART:
2706 log_info("%s holdoff time over, scheduling restart.", u->meta.id);
2707 service_enter_restart(s);
2711 assert_not_reached("Timeout at wrong time.");
2715 static void service_cgroup_notify_event(Unit *u) {
2716 Service *s = SERVICE(u);
2720 log_debug("%s: cgroup is empty", u->meta.id);
2724 /* Waiting for SIGCHLD is usually more interesting,
2725 * because it includes return codes/signals. Which is
2726 * why we ignore the cgroup events for most cases,
2727 * except when we don't know pid which to expect the
2730 case SERVICE_RUNNING:
2731 service_enter_running(s, true);
2734 case SERVICE_STOP_SIGTERM:
2735 case SERVICE_STOP_SIGKILL:
2736 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2737 service_enter_stop_post(s, true);
2741 case SERVICE_FINAL_SIGTERM:
2742 case SERVICE_FINAL_SIGKILL:
2743 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2744 service_enter_dead(s, true, true);
2753 static void service_notify_message(Unit *u, pid_t pid, char **tags) {
2754 Service *s = SERVICE(u);
2759 if (s->notify_access == NOTIFY_NONE) {
2760 log_warning("%s: Got notification message from PID %lu, but reception is disabled.",
2761 u->meta.id, (unsigned long) pid);
2765 if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
2766 log_warning("%s: Got notification message from PID %lu, but reception only permitted for PID %lu",
2767 u->meta.id, (unsigned long) pid, (unsigned long) s->main_pid);
2771 log_debug("%s: Got message", u->meta.id);
2773 /* Interpret MAINPID= */
2774 if ((e = strv_find_prefix(tags, "MAINPID=")) &&
2775 (s->state == SERVICE_START ||
2776 s->state == SERVICE_START_POST ||
2777 s->state == SERVICE_RUNNING ||
2778 s->state == SERVICE_RELOAD)) {
2780 if (parse_pid(e + 8, &pid) < 0)
2781 log_warning("Failed to parse notification message %s", e);
2783 log_debug("%s: got %s", u->meta.id, e);
2784 service_set_main_pid(s, pid);
2788 /* Interpret READY= */
2789 if (s->type == SERVICE_NOTIFY &&
2790 s->state == SERVICE_START &&
2791 strv_find(tags, "READY=1")) {
2792 log_debug("%s: got READY=1", u->meta.id);
2794 service_enter_start_post(s);
2797 /* Interpret STATUS= */
2798 if ((e = strv_find_prefix(tags, "STATUS="))) {
2802 if (!(t = strdup(e+7))) {
2803 log_error("Failed to allocate string.");
2807 log_debug("%s: got %s", u->meta.id, e);
2809 free(s->status_text);
2812 free(s->status_text);
2813 s->status_text = NULL;
2818 /* Notify clients about changed status or main pid */
2819 unit_add_to_dbus_queue(u);
2822 #ifdef HAVE_SYSV_COMPAT
2823 static int service_enumerate(Manager *m) {
2827 char *path = NULL, *fpath = NULL, *name = NULL;
2828 Set *runlevel_services[ELEMENTSOF(rcnd_table)], *shutdown_services = NULL;
2833 Unit *previous = NULL;
2834 char *arch_daemons = NULL;
2835 char *arch_daemons_stripped = NULL;
2836 char **arch_daemons_split = NULL;
2842 if ((r = parse_env_file("/etc/rc.conf", NEWLINE,
2843 "DAEMONS", &arch_daemons,
2847 log_warning("Failed to read /etc/rc.conf: %s", strerror(-r));
2849 } else if (arch_daemons) {
2850 if (!(arch_daemons_stripped = strchr(arch_daemons, '(')))
2851 arch_daemons_stripped = arch_daemons;
2853 arch_daemons_stripped++; /* strip start paren */
2855 arch_daemons_stripped[strcspn(arch_daemons_stripped, ")")] = 0; /* strip end paren */
2857 if (!(arch_daemons_split = strv_split_quoted(arch_daemons_stripped))) {
2862 STRV_FOREACH(p, arch_daemons_split) {
2867 if (**p == '!') /* daemons prefixed with ! are disabled, so ignore them */
2870 if (!(name = sysv_translate_name(*p))) {
2875 if ((r = manager_load_unit_prepare(m, name, NULL, NULL, &service)) < 0) {
2876 log_warning("Failed to prepare unit %s: %s", name, strerror(-r));
2880 if ((r = unit_add_two_dependencies_by_name_inverse(service, UNIT_AFTER, UNIT_WANTS, "multi-user.target", NULL, true)) < 0)
2884 if ((r = unit_add_dependency(service, UNIT_AFTER, previous, true)) < 0)
2887 if (**p != '@') /* daemons prefixed with @ can be started in the background */
2893 zero(runlevel_services);
2895 STRV_FOREACH(p, m->lookup_paths.sysvrcnd_path)
2896 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++) {
2901 if (asprintf(&path, "%s/%s", *p, rcnd_table[i].path) < 0) {
2909 if (!(d = opendir(path))) {
2910 if (errno != ENOENT)
2911 log_warning("opendir() failed on %s: %s", path, strerror(errno));
2916 while ((de = readdir(d))) {
2919 if (ignore_file(de->d_name))
2922 if (de->d_name[0] != 'S' && de->d_name[0] != 'K')
2925 if (strlen(de->d_name) < 4)
2928 a = undecchar(de->d_name[1]);
2929 b = undecchar(de->d_name[2]);
2936 if (asprintf(&fpath, "%s/%s/%s", *p, rcnd_table[i].path, de->d_name) < 0) {
2941 if (access(fpath, X_OK) < 0) {
2943 if (errno != ENOENT)
2944 log_warning("access() failed on %s: %s", fpath, strerror(errno));
2950 if (!(name = sysv_translate_name(de->d_name + 3))) {
2955 if ((r = manager_load_unit_prepare(m, name, NULL, NULL, &service)) < 0) {
2956 log_warning("Failed to prepare unit %s: %s", name, strerror(-r));
2960 if (de->d_name[0] == 'S') {
2962 if (rcnd_table[i].type == RUNLEVEL_UP || rcnd_table[i].type == RUNLEVEL_SYSINIT) {
2963 SERVICE(service)->sysv_start_priority =
2964 MAX(a*10 + b, SERVICE(service)->sysv_start_priority);
2966 SERVICE(service)->sysv_enabled = true;
2969 if ((r = set_ensure_allocated(&runlevel_services[i], trivial_hash_func, trivial_compare_func)) < 0)
2972 if ((r = set_put(runlevel_services[i], service)) < 0)
2975 } else if (de->d_name[0] == 'K' &&
2976 (rcnd_table[i].type == RUNLEVEL_DOWN ||
2977 rcnd_table[i].type == RUNLEVEL_SYSINIT)) {
2979 if ((r = set_ensure_allocated(&shutdown_services, trivial_hash_func, trivial_compare_func)) < 0)
2982 if ((r = set_put(shutdown_services, service)) < 0)
2988 /* Now we loaded all stubs and are aware of the lowest
2989 start-up priority for all services, not let's actually load
2990 the services, this will also tell us which services are
2991 actually native now */
2992 manager_dispatch_load_queue(m);
2994 /* If this is a native service, rely on native ways to pull in
2995 * a service, don't pull it in via sysv rcN.d links. */
2996 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++)
2997 SET_FOREACH(service, runlevel_services[i], j) {
2998 service = unit_follow_merge(service);
3000 if (service->meta.fragment_path)
3003 if ((r = unit_add_two_dependencies_by_name_inverse(service, UNIT_AFTER, UNIT_WANTS, rcnd_table[i].target, NULL, true)) < 0)
3007 /* We honour K links only for halt/reboot. For the normal
3008 * runlevels we assume the stop jobs will be implicitly added
3009 * by the core logic. Also, we don't really distuingish here
3010 * between the runlevels 0 and 6 and just add them to the
3011 * special shutdown target. On SUSE the boot.d/ runlevel is
3012 * also used for shutdown, so we add links for that too to the
3013 * shutdown target.*/
3014 SET_FOREACH(service, shutdown_services, j) {
3015 service = unit_follow_merge(service);
3017 if (service->meta.fragment_path)
3020 if ((r = unit_add_two_dependencies_by_name(service, UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true)) < 0)
3032 free(arch_daemons_split);
3035 for (i = 0; i < ELEMENTSOF(rcnd_table); i++)
3036 set_free(runlevel_services[i]);
3037 set_free(shutdown_services);
3046 static void service_bus_name_owner_change(
3049 const char *old_owner,
3050 const char *new_owner) {
3052 Service *s = SERVICE(u);
3057 assert(streq(s->bus_name, name));
3058 assert(old_owner || new_owner);
3060 if (old_owner && new_owner)
3061 log_debug("%s's D-Bus name %s changed owner from %s to %s", u->meta.id, name, old_owner, new_owner);
3063 log_debug("%s's D-Bus name %s no longer registered by %s", u->meta.id, name, old_owner);
3065 log_debug("%s's D-Bus name %s now registered by %s", u->meta.id, name, new_owner);
3067 s->bus_name_good = !!new_owner;
3069 if (s->type == SERVICE_DBUS) {
3071 /* service_enter_running() will figure out what to
3073 if (s->state == SERVICE_RUNNING)
3074 service_enter_running(s, true);
3075 else if (s->state == SERVICE_START && new_owner)
3076 service_enter_start_post(s);
3078 } else if (new_owner &&
3080 (s->state == SERVICE_START ||
3081 s->state == SERVICE_START_POST ||
3082 s->state == SERVICE_RUNNING ||
3083 s->state == SERVICE_RELOAD)) {
3085 /* Try to acquire PID from bus service */
3086 log_debug("Trying to acquire PID from D-Bus name...");
3088 bus_query_pid(u->meta.manager, name);
3092 static void service_bus_query_pid_done(
3097 Service *s = SERVICE(u);
3102 log_debug("%s's D-Bus name %s is now owned by process %u", u->meta.id, name, (unsigned) pid);
3104 if (s->main_pid <= 0 &&
3105 (s->state == SERVICE_START ||
3106 s->state == SERVICE_START_POST ||
3107 s->state == SERVICE_RUNNING ||
3108 s->state == SERVICE_RELOAD))
3109 service_set_main_pid(s, pid);
3112 int service_set_socket_fd(Service *s, int fd, Socket *sock) {
3116 /* This is called by the socket code when instantiating a new
3117 * service for a stream socket and the socket needs to be
3120 if (s->meta.load_state != UNIT_LOADED)
3123 if (s->socket_fd >= 0)
3126 if (s->state != SERVICE_DEAD)
3130 s->got_socket_fd = true;
3131 s->accept_socket = sock;
3136 static void service_reset_failed(Unit *u) {
3137 Service *s = SERVICE(u);
3141 if (s->state == SERVICE_FAILED)
3142 service_set_state(s, SERVICE_DEAD);
3147 static int service_kill(Unit *u, KillWho who, KillMode mode, int signo, DBusError *error) {
3148 Service *s = SERVICE(u);
3150 Set *pid_set = NULL;
3154 if (s->main_pid <= 0 && who == KILL_MAIN) {
3155 dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "No main process to kill");
3159 if (s->control_pid <= 0 && who == KILL_CONTROL) {
3160 dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "No control process to kill");
3164 if (s->control_pid > 0)
3165 if (kill(mode == KILL_PROCESS_GROUP ? -s->control_pid : s->control_pid, signo) < 0)
3168 if (s->main_pid > 0)
3169 if (kill(mode == KILL_PROCESS_GROUP ? -s->main_pid : s->main_pid, signo) < 0)
3172 if (mode == KILL_CONTROL_GROUP) {
3175 if (!(pid_set = set_new(trivial_hash_func, trivial_compare_func)))
3178 /* Exclude the control/main pid from being killed via the cgroup */
3179 if (s->control_pid > 0)
3180 if ((q = set_put(pid_set, LONG_TO_PTR(s->control_pid))) < 0) {
3185 if (s->main_pid > 0)
3186 if ((q = set_put(pid_set, LONG_TO_PTR(s->main_pid))) < 0) {
3191 if ((q = cgroup_bonding_kill_list(s->meta.cgroup_bondings, signo, pid_set)) < 0)
3192 if (r != -EAGAIN && r != -ESRCH && r != -ENOENT)
3203 static const char* const service_state_table[_SERVICE_STATE_MAX] = {
3204 [SERVICE_DEAD] = "dead",
3205 [SERVICE_START_PRE] = "start-pre",
3206 [SERVICE_START] = "start",
3207 [SERVICE_START_POST] = "start-post",
3208 [SERVICE_RUNNING] = "running",
3209 [SERVICE_EXITED] = "exited",
3210 [SERVICE_RELOAD] = "reload",
3211 [SERVICE_STOP] = "stop",
3212 [SERVICE_STOP_SIGTERM] = "stop-sigterm",
3213 [SERVICE_STOP_SIGKILL] = "stop-sigkill",
3214 [SERVICE_STOP_POST] = "stop-post",
3215 [SERVICE_FINAL_SIGTERM] = "final-sigterm",
3216 [SERVICE_FINAL_SIGKILL] = "final-sigkill",
3217 [SERVICE_FAILED] = "failed",
3218 [SERVICE_AUTO_RESTART] = "auto-restart",
3221 DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
3223 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
3224 [SERVICE_RESTART_NO] = "no",
3225 [SERVICE_RESTART_ON_SUCCESS] = "on-success",
3226 [SERVICE_RESTART_ON_FAILURE] = "on-failure",
3227 [SERVICE_RESTART_ON_ABORT] = "on-abort",
3228 [SERVICE_RESTART_ALWAYS] = "always"
3231 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
3233 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
3234 [SERVICE_SIMPLE] = "simple",
3235 [SERVICE_FORKING] = "forking",
3236 [SERVICE_ONESHOT] = "oneshot",
3237 [SERVICE_DBUS] = "dbus",
3238 [SERVICE_NOTIFY] = "notify"
3241 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
3243 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
3244 [SERVICE_EXEC_START_PRE] = "ExecStartPre",
3245 [SERVICE_EXEC_START] = "ExecStart",
3246 [SERVICE_EXEC_START_POST] = "ExecStartPost",
3247 [SERVICE_EXEC_RELOAD] = "ExecReload",
3248 [SERVICE_EXEC_STOP] = "ExecStop",
3249 [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
3252 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
3254 static const char* const notify_access_table[_NOTIFY_ACCESS_MAX] = {
3255 [NOTIFY_NONE] = "none",
3256 [NOTIFY_MAIN] = "main",
3257 [NOTIFY_ALL] = "all"
3260 DEFINE_STRING_TABLE_LOOKUP(notify_access, NotifyAccess);
3262 const UnitVTable service_vtable = {
3263 .suffix = ".service",
3264 .show_status = true,
3266 .init = service_init,
3267 .done = service_done,
3268 .load = service_load,
3270 .coldplug = service_coldplug,
3272 .dump = service_dump,
3274 .start = service_start,
3275 .stop = service_stop,
3276 .reload = service_reload,
3278 .can_reload = service_can_reload,
3280 .kill = service_kill,
3282 .serialize = service_serialize,
3283 .deserialize_item = service_deserialize_item,
3285 .active_state = service_active_state,
3286 .sub_state_to_string = service_sub_state_to_string,
3288 #ifdef HAVE_SYSV_COMPAT
3289 .check_gc = service_check_gc,
3291 .check_snapshot = service_check_snapshot,
3293 .sigchld_event = service_sigchld_event,
3294 .timer_event = service_timer_event,
3296 .reset_failed = service_reset_failed,
3298 .cgroup_notify_empty = service_cgroup_notify_event,
3299 .notify_message = service_notify_message,
3301 .bus_name_owner_change = service_bus_name_owner_change,
3302 .bus_query_pid_done = service_bus_query_pid_done,
3304 .bus_interface = "org.freedesktop.systemd1.Service",
3305 .bus_message_handler = bus_service_message_handler,
3306 .bus_invalidating_properties = bus_service_invalidating_properties,
3308 #ifdef HAVE_SYSV_COMPAT
3309 .enumerate = service_enumerate