1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
29 #include "load-fragment.h"
30 #include "load-dropin.h"
33 #include "unit-name.h"
34 #include "dbus-service.h"
36 #include "bus-errors.h"
37 #include "exit-status.h"
41 #ifdef HAVE_SYSV_COMPAT
43 #define DEFAULT_SYSV_TIMEOUT_USEC (5*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) || defined(TARGET_ANGSTROM)
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;
118 s->sysv_start_priority_from_rcnd = -1;
121 s->guess_main_pid = true;
123 exec_context_init(&s->exec_context);
124 s->exec_context.std_output = u->meta.manager->default_std_output;
125 s->exec_context.std_error = u->meta.manager->default_std_error;
127 RATELIMIT_INIT(s->ratelimit, 10*USEC_PER_SEC, 5);
129 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
132 static void service_unwatch_control_pid(Service *s) {
135 if (s->control_pid <= 0)
138 unit_unwatch_pid(UNIT(s), s->control_pid);
142 static void service_unwatch_main_pid(Service *s) {
145 if (s->main_pid <= 0)
148 unit_unwatch_pid(UNIT(s), s->main_pid);
152 static int service_set_main_pid(Service *s, pid_t pid) {
164 s->main_pid_known = true;
166 if (get_parent_of_pid(pid, &ppid) >= 0 && ppid != getpid()) {
167 log_warning("%s: Supervising process %lu which is not our child. We'll most likely not notice when it exits.",
168 s->meta.id, (unsigned long) pid);
170 s->main_pid_alien = true;
172 s->main_pid_alien = false;
174 exec_status_start(&s->main_exec_status, pid);
179 static void service_close_socket_fd(Service *s) {
182 if (s->socket_fd < 0)
185 close_nointr_nofail(s->socket_fd);
189 static void service_connection_unref(Service *s) {
192 if (!s->accept_socket)
195 socket_connection_unref(s->accept_socket);
196 s->accept_socket = NULL;
199 static void service_done(Unit *u) {
200 Service *s = SERVICE(u);
207 #ifdef HAVE_SYSV_COMPAT
211 free(s->sysv_runlevels);
212 s->sysv_runlevels = NULL;
215 free(s->status_text);
216 s->status_text = NULL;
218 exec_context_done(&s->exec_context);
219 exec_command_free_array(s->exec_command, _SERVICE_EXEC_COMMAND_MAX);
220 s->control_command = NULL;
221 s->main_command = NULL;
223 /* This will leak a process, but at least no memory or any of
225 service_unwatch_main_pid(s);
226 service_unwatch_control_pid(s);
229 unit_unwatch_bus_name(UNIT(u), s->bus_name);
234 service_close_socket_fd(s);
235 service_connection_unref(s);
237 set_free(s->configured_sockets);
239 unit_unwatch_timer(u, &s->timer_watch);
242 #ifdef HAVE_SYSV_COMPAT
243 static char *sysv_translate_name(const char *name) {
246 if (!(r = new(char, strlen(name) + sizeof(".service"))))
249 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU) || defined(TARGET_ANGSTROM)
250 if (endswith(name, ".sh"))
251 /* Drop Debian-style .sh suffix */
252 strcpy(stpcpy(r, name) - 3, ".service");
255 if (startswith(name, "boot."))
256 /* Drop SuSE-style boot. prefix */
257 strcpy(stpcpy(r, name + 5), ".service");
259 #ifdef TARGET_FRUGALWARE
260 if (startswith(name, "rc."))
261 /* Drop Frugalware-style rc. prefix */
262 strcpy(stpcpy(r, name + 3), ".service");
265 /* Normal init scripts */
266 strcpy(stpcpy(r, name), ".service");
271 static int sysv_translate_facility(const char *name, const char *filename, char **_r) {
273 /* We silently ignore the $ prefix here. According to the LSB
274 * spec it simply indicates whether something is a
275 * standardized name or a distribution-specific one. Since we
276 * just follow what already exists and do not introduce new
277 * uses or names we don't care who introduced a new name. */
279 static const char * const table[] = {
280 /* LSB defined facilities */
281 "local_fs", SPECIAL_LOCAL_FS_TARGET,
282 #ifndef TARGET_MANDRIVA
283 /* Due to unfortunate name selection in Mandriva,
284 * $network is provided by network-up which is ordered
285 * after network which actually starts interfaces.
286 * To break the loop, just ignore it */
287 "network", SPECIAL_NETWORK_TARGET,
289 "named", SPECIAL_NSS_LOOKUP_TARGET,
290 "portmap", SPECIAL_RPCBIND_TARGET,
291 "remote_fs", SPECIAL_REMOTE_FS_TARGET,
292 "syslog", SPECIAL_SYSLOG_TARGET,
293 "time", SPECIAL_TIME_SYNC_TARGET,
295 /* common extensions */
296 "mail-transfer-agent", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
297 "x-display-manager", SPECIAL_DISPLAY_MANAGER_SERVICE,
300 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU) || defined(TARGET_ANGSTROM)
301 "mail-transport-agent", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
305 "MTA", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
306 "smtpdaemon", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
307 "httpd", SPECIAL_HTTP_DAEMON_TARGET,
311 "smtp", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
322 n = *name == '$' ? name + 1 : name;
324 for (i = 0; i < ELEMENTSOF(table); i += 2) {
326 if (!streq(table[i], n))
332 if (!(r = strdup(table[i+1])))
338 /* If we don't know this name, fallback heuristics to figure
339 * out whether something is a target or a service alias. */
342 if (!unit_prefix_is_valid(n))
345 /* Facilities starting with $ are most likely targets */
346 r = unit_name_build(n, NULL, ".target");
347 } else if (filename && streq(name, filename))
348 /* Names equaling the file name of the services are redundant */
351 /* Everything else we assume to be normal service names */
352 r = sysv_translate_name(n);
363 static int sysv_fix_order(Service *s) {
369 if (s->sysv_start_priority < 0)
372 /* For each pair of services where at least one lacks a LSB
373 * header, we use the start priority value to order things. */
375 LIST_FOREACH(units_by_type, other, s->meta.manager->units_by_type[UNIT_SERVICE]) {
378 bool special_s, special_t;
380 t = (Service*) other;
385 if (t->meta.load_state != UNIT_LOADED)
388 if (t->sysv_start_priority < 0)
391 /* If both units have modern headers we don't care
392 * about the priorities */
393 if ((s->meta.fragment_path || s->sysv_has_lsb) &&
394 (t->meta.fragment_path || t->sysv_has_lsb))
397 special_s = s->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, s->sysv_runlevels);
398 special_t = t->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, t->sysv_runlevels);
400 if (special_t && !special_s)
402 else if (special_s && !special_t)
404 else if (t->sysv_start_priority < s->sysv_start_priority)
406 else if (t->sysv_start_priority > s->sysv_start_priority)
411 /* FIXME: Maybe we should compare the name here lexicographically? */
413 if ((r = unit_add_dependency(UNIT(s), d, UNIT(t), true)) < 0)
420 static ExecCommand *exec_command_new(const char *path, const char *arg1) {
423 if (!(c = new0(ExecCommand, 1)))
426 if (!(c->path = strdup(path))) {
431 if (!(c->argv = strv_new(path, arg1, NULL))) {
440 static int sysv_exec_commands(Service *s) {
444 assert(s->sysv_path);
446 if (!(c = exec_command_new(s->sysv_path, "start")))
448 exec_command_append_list(s->exec_command+SERVICE_EXEC_START, c);
450 if (!(c = exec_command_new(s->sysv_path, "stop")))
452 exec_command_append_list(s->exec_command+SERVICE_EXEC_STOP, c);
454 if (!(c = exec_command_new(s->sysv_path, "reload")))
456 exec_command_append_list(s->exec_command+SERVICE_EXEC_RELOAD, c);
461 static int service_load_sysv_path(Service *s, const char *path) {
472 char *short_description = NULL, *long_description = NULL, *chkconfig_description = NULL, *description;
480 if (!(f = fopen(path, "re"))) {
481 r = errno == ENOENT ? 0 : -errno;
486 if (fstat(fileno(f), &st) < 0) {
492 if (!(s->sysv_path = strdup(path))) {
497 s->sysv_mtime = timespec_load(&st.st_mtim);
499 if (null_or_empty(&st)) {
500 u->meta.load_state = UNIT_MASKED;
506 char l[LINE_MAX], *t;
508 if (!fgets(l, sizeof(l), f)) {
513 log_error("Failed to read configuration file '%s': %s", path, strerror(-r));
523 if (state == NORMAL && streq(t, "### BEGIN INIT INFO")) {
525 s->sysv_has_lsb = true;
529 if ((state == LSB_DESCRIPTION || state == LSB) && streq(t, "### END INIT INFO")) {
535 t += strspn(t, WHITESPACE);
537 if (state == NORMAL) {
539 /* Try to parse Red Hat style chkconfig headers */
541 if (startswith_no_case(t, "chkconfig:")) {
543 char runlevels[16], *k;
547 if (sscanf(t+10, "%15s %i %*i",
549 &start_priority) != 2) {
551 log_warning("[%s:%u] Failed to parse chkconfig line. Ignoring.", path, line);
555 /* A start priority gathered from the
556 * symlink farms is preferred over the
557 * data from the LSB header. */
558 if (start_priority < 0 || start_priority > 99)
559 log_warning("[%s:%u] Start priority out of range. Ignoring.", path, line);
561 s->sysv_start_priority = start_priority;
563 char_array_0(runlevels);
564 k = delete_chars(runlevels, WHITESPACE "-");
569 if (!(d = strdup(k))) {
574 free(s->sysv_runlevels);
575 s->sysv_runlevels = d;
578 } else if (startswith_no_case(t, "description:")) {
580 size_t k = strlen(t);
584 if (t[k-1] == '\\') {
589 if ((j = strstrip(t+12)) && *j) {
590 if (!(d = strdup(j))) {
597 free(chkconfig_description);
598 chkconfig_description = d;
600 } else if (startswith_no_case(t, "pidfile:")) {
607 if (!path_is_absolute(fn)) {
608 log_warning("[%s:%u] PID file not absolute. Ignoring.", path, line);
612 if (!(fn = strdup(fn))) {
621 } else if (state == DESCRIPTION) {
623 /* Try to parse Red Hat style description
626 size_t k = strlen(t);
634 if ((j = strstrip(t)) && *j) {
637 if (chkconfig_description)
638 d = join(chkconfig_description, " ", j, NULL);
647 free(chkconfig_description);
648 chkconfig_description = d;
651 } else if (state == LSB || state == LSB_DESCRIPTION) {
653 if (startswith_no_case(t, "Provides:")) {
659 FOREACH_WORD_QUOTED(w, z, t+9, i) {
662 if (!(n = strndup(w, z))) {
667 r = sysv_translate_facility(n, file_name_from_path(path), &m);
676 if (unit_name_to_type(m) == UNIT_SERVICE)
677 r = unit_add_name(u, m);
684 * indication that the
686 * now available. This
689 * targets do NOT pull
692 r = unit_add_two_dependencies_by_name(u, UNIT_BEFORE, UNIT_WANTS, m, NULL, true);
695 log_error("[%s:%u] Failed to add LSB Provides name %s, ignoring: %s", path, line, m, strerror(-r));
700 } else if (startswith_no_case(t, "Required-Start:") ||
701 startswith_no_case(t, "Should-Start:") ||
702 startswith_no_case(t, "X-Start-Before:") ||
703 startswith_no_case(t, "X-Start-After:")) {
709 FOREACH_WORD_QUOTED(w, z, strchr(t, ':')+1, i) {
712 if (!(n = strndup(w, z))) {
717 r = sysv_translate_facility(n, file_name_from_path(path), &m);
720 log_error("[%s:%u] Failed to translate LSB dependency %s, ignoring: %s", path, line, n, strerror(-r));
730 r = unit_add_dependency_by_name(u, startswith_no_case(t, "X-Start-Before:") ? UNIT_BEFORE : UNIT_AFTER, m, NULL, true);
733 log_error("[%s:%u] Failed to add dependency on %s, ignoring: %s", path, line, m, strerror(-r));
737 } else if (startswith_no_case(t, "Default-Start:")) {
742 k = delete_chars(t+14, WHITESPACE "-");
745 if (!(d = strdup(k))) {
750 free(s->sysv_runlevels);
751 s->sysv_runlevels = d;
754 } else if (startswith_no_case(t, "Description:")) {
757 state = LSB_DESCRIPTION;
759 if ((j = strstrip(t+12)) && *j) {
760 if (!(d = strdup(j))) {
767 free(long_description);
768 long_description = d;
770 } else if (startswith_no_case(t, "Short-Description:")) {
775 if ((j = strstrip(t+18)) && *j) {
776 if (!(d = strdup(j))) {
783 free(short_description);
784 short_description = d;
786 } else if (startswith_no_case(t, "X-Interactive:")) {
789 if ((b = parse_boolean(strstrip(t+14))) < 0) {
790 log_warning("[%s:%u] Couldn't parse interactive flag. Ignoring.", path, line);
795 s->exec_context.std_input = EXEC_INPUT_TTY;
797 s->exec_context.std_input = EXEC_INPUT_NULL;
799 } else if (state == LSB_DESCRIPTION) {
801 if (startswith(l, "#\t") || startswith(l, "# ")) {
804 if ((j = strstrip(t)) && *j) {
807 if (long_description)
808 d = join(long_description, " ", t, NULL);
817 free(long_description);
818 long_description = d;
827 if ((r = sysv_exec_commands(s)) < 0)
830 if (s->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, s->sysv_runlevels)) {
831 /* If there a runlevels configured for this service
832 * but none of the standard ones, then we assume this
833 * is some special kind of service (which might be
834 * needed for early boot) and don't create any links
837 s->meta.default_dependencies = false;
839 /* Don't timeout special services during boot (like fsck) */
842 s->timeout_usec = DEFAULT_SYSV_TIMEOUT_USEC;
844 /* Special setting for all SysV services */
845 s->type = SERVICE_FORKING;
846 s->remain_after_exit = !s->pid_file;
847 s->restart = SERVICE_RESTART_NO;
848 s->exec_context.std_output =
849 (s->meta.manager->sysv_console || s->exec_context.std_input == EXEC_INPUT_TTY)
850 ? EXEC_OUTPUT_TTY : s->meta.manager->default_std_output;
851 s->exec_context.kill_mode = KILL_PROCESS;
853 /* We use the long description only if
854 * no short description is set. */
856 if (short_description)
857 description = short_description;
858 else if (chkconfig_description)
859 description = chkconfig_description;
860 else if (long_description)
861 description = long_description;
868 if (!(d = strappend(s->sysv_has_lsb ? "LSB: " : "SYSV: ", description))) {
873 u->meta.description = d;
876 /* The priority that has been set in /etc/rcN.d/ hierarchies
877 * takes precedence over what is stored as default in the LSB
879 if (s->sysv_start_priority_from_rcnd >= 0)
880 s->sysv_start_priority = s->sysv_start_priority_from_rcnd;
882 u->meta.load_state = UNIT_LOADED;
890 free(short_description);
891 free(long_description);
892 free(chkconfig_description);
897 static int service_load_sysv_name(Service *s, const char *name) {
903 /* For SysV services we strip the boot.*, rc.* and *.sh
904 * prefixes/suffixes. */
905 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU) || defined(TARGET_ANGSTROM)
906 if (endswith(name, ".sh.service"))
911 if (startswith(name, "boot."))
915 #ifdef TARGET_FRUGALWARE
916 if (startswith(name, "rc."))
920 STRV_FOREACH(p, s->meta.manager->lookup_paths.sysvinit_path) {
924 path = join(*p, "/", name, NULL);
928 assert(endswith(path, ".service"));
929 path[strlen(path)-8] = 0;
931 r = service_load_sysv_path(s, path);
933 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU) || defined(TARGET_ANGSTROM)
934 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
935 /* Try Debian style *.sh source'able init scripts */
937 r = service_load_sysv_path(s, path);
943 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
944 /* Try SUSE style boot.* init scripts */
946 path = join(*p, "/boot.", name, NULL);
950 /* Drop .service suffix */
951 path[strlen(path)-8] = 0;
952 r = service_load_sysv_path(s, path);
957 #ifdef TARGET_FRUGALWARE
958 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
959 /* Try Frugalware style rc.* init scripts */
961 path = join(*p, "/rc.", name, NULL);
965 /* Drop .service suffix */
966 path[strlen(path)-8] = 0;
967 r = service_load_sysv_path(s, path);
975 if ((s->meta.load_state != UNIT_STUB))
982 static int service_load_sysv(Service *s) {
989 /* Load service data from SysV init scripts, preferably with
992 if (strv_isempty(s->meta.manager->lookup_paths.sysvinit_path))
995 if ((t = s->meta.id))
996 if ((r = service_load_sysv_name(s, t)) < 0)
999 if (s->meta.load_state == UNIT_STUB)
1000 SET_FOREACH(t, s->meta.names, i) {
1001 if (t == s->meta.id)
1004 if ((r = service_load_sysv_name(s, t)) < 0)
1007 if (s->meta.load_state != UNIT_STUB)
1015 static int fsck_fix_order(Service *s) {
1021 if (s->fsck_passno <= 0)
1024 /* For each pair of services where both have an fsck priority
1025 * we order things based on it. */
1027 LIST_FOREACH(units_by_type, other, s->meta.manager->units_by_type[UNIT_SERVICE]) {
1031 t = (Service*) other;
1036 if (t->meta.load_state != UNIT_LOADED)
1039 if (t->fsck_passno <= 0)
1042 if (t->fsck_passno < s->fsck_passno)
1044 else if (t->fsck_passno > s->fsck_passno)
1049 if ((r = unit_add_dependency(UNIT(s), d, UNIT(t), true)) < 0)
1056 static int service_verify(Service *s) {
1059 if (s->meta.load_state != UNIT_LOADED)
1062 if (!s->exec_command[SERVICE_EXEC_START]) {
1063 log_error("%s lacks ExecStart setting. Refusing.", s->meta.id);
1067 if (s->type != SERVICE_ONESHOT &&
1068 s->exec_command[SERVICE_EXEC_START]->command_next) {
1069 log_error("%s has more than one ExecStart setting, which is only allowed for Type=oneshot services. Refusing.", s->meta.id);
1073 if (s->type == SERVICE_ONESHOT &&
1074 s->exec_command[SERVICE_EXEC_RELOAD]) {
1075 log_error("%s has an ExecReload setting, which is not allowed for Type=oneshot services. Refusing.", s->meta.id);
1079 if (s->type == SERVICE_DBUS && !s->bus_name) {
1080 log_error("%s is of type D-Bus but no D-Bus service name has been specified. Refusing.", s->meta.id);
1084 if (s->exec_context.pam_name && s->exec_context.kill_mode != KILL_CONTROL_GROUP) {
1085 log_error("%s has PAM enabled. Kill mode must be set to 'control-group'. Refusing.", s->meta.id);
1092 static int service_add_default_dependencies(Service *s) {
1097 /* Add a number of automatic dependencies useful for the
1098 * majority of services. */
1100 /* First, pull in base system */
1101 if (s->meta.manager->running_as == MANAGER_SYSTEM) {
1103 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_BASIC_TARGET, NULL, true)) < 0)
1106 } else if (s->meta.manager->running_as == MANAGER_USER) {
1108 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SOCKETS_TARGET, NULL, true)) < 0)
1112 /* Second, activate normal shutdown */
1113 return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true);
1116 static int service_load(Unit *u) {
1118 Service *s = SERVICE(u);
1122 /* Load a .service file */
1123 if ((r = unit_load_fragment(u)) < 0)
1126 #ifdef HAVE_SYSV_COMPAT
1127 /* Load a classic init script as a fallback, if we couldn't find anything */
1128 if (u->meta.load_state == UNIT_STUB)
1129 if ((r = service_load_sysv(s)) < 0)
1133 /* Still nothing found? Then let's give up */
1134 if (u->meta.load_state == UNIT_STUB)
1137 /* We were able to load something, then let's add in the
1138 * dropin directories. */
1139 if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
1142 /* This is a new unit? Then let's add in some extras */
1143 if (u->meta.load_state == UNIT_LOADED) {
1144 if ((r = unit_add_exec_dependencies(u, &s->exec_context)) < 0)
1147 if ((r = unit_add_default_cgroups(u)) < 0)
1150 #ifdef HAVE_SYSV_COMPAT
1151 if ((r = sysv_fix_order(s)) < 0)
1155 if ((r = fsck_fix_order(s)) < 0)
1159 if ((r = unit_watch_bus_name(u, s->bus_name)) < 0)
1162 if (s->type == SERVICE_NOTIFY && s->notify_access == NOTIFY_NONE)
1163 s->notify_access = NOTIFY_MAIN;
1165 if (s->type == SERVICE_DBUS || s->bus_name)
1166 if ((r = unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_REQUIRES, SPECIAL_DBUS_SOCKET, NULL, true)) < 0)
1169 if (s->meta.default_dependencies)
1170 if ((r = service_add_default_dependencies(s)) < 0)
1174 return service_verify(s);
1177 static void service_dump(Unit *u, FILE *f, const char *prefix) {
1179 ServiceExecCommand c;
1180 Service *s = SERVICE(u);
1181 const char *prefix2;
1186 p2 = strappend(prefix, "\t");
1187 prefix2 = p2 ? p2 : prefix;
1190 "%sService State: %s\n"
1191 "%sPermissionsStartOnly: %s\n"
1192 "%sRootDirectoryStartOnly: %s\n"
1193 "%sRemainAfterExit: %s\n"
1194 "%sGuessMainPID: %s\n"
1197 "%sNotifyAccess: %s\n",
1198 prefix, service_state_to_string(s->state),
1199 prefix, yes_no(s->permissions_start_only),
1200 prefix, yes_no(s->root_directory_start_only),
1201 prefix, yes_no(s->remain_after_exit),
1202 prefix, yes_no(s->guess_main_pid),
1203 prefix, service_type_to_string(s->type),
1204 prefix, service_restart_to_string(s->restart),
1205 prefix, notify_access_to_string(s->notify_access));
1207 if (s->control_pid > 0)
1209 "%sControl PID: %lu\n",
1210 prefix, (unsigned long) s->control_pid);
1212 if (s->main_pid > 0)
1215 "%sMain PID Known: %s\n"
1216 "%sMain PID Alien: %s\n",
1217 prefix, (unsigned long) s->main_pid,
1218 prefix, yes_no(s->main_pid_known),
1219 prefix, yes_no(s->main_pid_alien));
1224 prefix, s->pid_file);
1229 "%sBus Name Good: %s\n",
1230 prefix, s->bus_name,
1231 prefix, yes_no(s->bus_name_good));
1233 exec_context_dump(&s->exec_context, f, prefix);
1235 for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
1237 if (!s->exec_command[c])
1240 fprintf(f, "%s-> %s:\n",
1241 prefix, service_exec_command_to_string(c));
1243 exec_command_dump_list(s->exec_command[c], f, prefix2);
1246 #ifdef HAVE_SYSV_COMPAT
1249 "%sSysV Init Script Path: %s\n"
1250 "%sSysV Init Script has LSB Header: %s\n"
1251 "%sSysVEnabled: %s\n",
1252 prefix, s->sysv_path,
1253 prefix, yes_no(s->sysv_has_lsb),
1254 prefix, yes_no(s->sysv_enabled));
1256 if (s->sysv_start_priority >= 0)
1258 "%sSysVStartPriority: %i\n",
1259 prefix, s->sysv_start_priority);
1261 if (s->sysv_runlevels)
1262 fprintf(f, "%sSysVRunLevels: %s\n",
1263 prefix, s->sysv_runlevels);
1266 if (s->fsck_passno > 0)
1268 "%sFsckPassNo: %i\n",
1269 prefix, s->fsck_passno);
1272 fprintf(f, "%sStatus Text: %s\n",
1273 prefix, s->status_text);
1278 static int service_load_pid_file(Service *s) {
1285 if (s->main_pid_known)
1291 if ((r = read_one_line_file(s->pid_file, &k)) < 0)
1294 r = parse_pid(k, &pid);
1300 if (kill(pid, 0) < 0 && errno != EPERM) {
1301 log_warning("PID %lu read from file %s does not exist. Your service or init script might be broken.",
1302 (unsigned long) pid, s->pid_file);
1306 if ((r = service_set_main_pid(s, pid)) < 0)
1309 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1310 /* FIXME: we need to do something here */
1316 static int service_search_main_pid(Service *s) {
1322 /* If we know it anyway, don't ever fallback to unreliable
1324 if (s->main_pid_known)
1327 if (!s->guess_main_pid)
1330 assert(s->main_pid <= 0);
1332 if ((pid = cgroup_bonding_search_main_pid_list(s->meta.cgroup_bondings)) <= 0)
1335 if ((r = service_set_main_pid(s, pid)) < 0)
1338 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1339 /* FIXME: we need to do something here */
1345 static int service_get_sockets(Service *s, Set **_set) {
1354 if (s->socket_fd >= 0)
1357 if (!set_isempty(s->configured_sockets))
1360 /* Collects all Socket objects that belong to this
1361 * service. Note that a service might have multiple sockets
1362 * via multiple names. */
1364 if (!(set = set_new(NULL, NULL)))
1367 SET_FOREACH(t, s->meta.names, i) {
1371 /* Look for all socket objects that go by any of our
1372 * units and collect their fds */
1374 if (!(k = unit_name_change_suffix(t, ".socket"))) {
1379 p = manager_get_unit(s->meta.manager, k);
1385 if ((r = set_put(set, p)) < 0)
1397 static int service_notify_sockets_dead(Service *s) {
1399 Set *set, *free_set = NULL;
1405 /* Notifies all our sockets when we die */
1407 if (s->socket_fd >= 0)
1410 if (!set_isempty(s->configured_sockets))
1411 set = s->configured_sockets;
1413 if ((r = service_get_sockets(s, &free_set)) < 0)
1419 SET_FOREACH(sock, set, i)
1420 socket_notify_service_dead(sock);
1427 static void service_set_state(Service *s, ServiceState state) {
1428 ServiceState old_state;
1431 old_state = s->state;
1434 if (state != SERVICE_START_PRE &&
1435 state != SERVICE_START &&
1436 state != SERVICE_START_POST &&
1437 state != SERVICE_RELOAD &&
1438 state != SERVICE_STOP &&
1439 state != SERVICE_STOP_SIGTERM &&
1440 state != SERVICE_STOP_SIGKILL &&
1441 state != SERVICE_STOP_POST &&
1442 state != SERVICE_FINAL_SIGTERM &&
1443 state != SERVICE_FINAL_SIGKILL &&
1444 state != SERVICE_AUTO_RESTART)
1445 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1447 if (state != SERVICE_START &&
1448 state != SERVICE_START_POST &&
1449 state != SERVICE_RUNNING &&
1450 state != SERVICE_RELOAD &&
1451 state != SERVICE_STOP &&
1452 state != SERVICE_STOP_SIGTERM &&
1453 state != SERVICE_STOP_SIGKILL) {
1454 service_unwatch_main_pid(s);
1455 s->main_command = NULL;
1458 if (state != SERVICE_START_PRE &&
1459 state != SERVICE_START &&
1460 state != SERVICE_START_POST &&
1461 state != SERVICE_RELOAD &&
1462 state != SERVICE_STOP &&
1463 state != SERVICE_STOP_SIGTERM &&
1464 state != SERVICE_STOP_SIGKILL &&
1465 state != SERVICE_STOP_POST &&
1466 state != SERVICE_FINAL_SIGTERM &&
1467 state != SERVICE_FINAL_SIGKILL) {
1468 service_unwatch_control_pid(s);
1469 s->control_command = NULL;
1470 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1473 if (state == SERVICE_DEAD ||
1474 state == SERVICE_STOP ||
1475 state == SERVICE_STOP_SIGTERM ||
1476 state == SERVICE_STOP_SIGKILL ||
1477 state == SERVICE_STOP_POST ||
1478 state == SERVICE_FINAL_SIGTERM ||
1479 state == SERVICE_FINAL_SIGKILL ||
1480 state == SERVICE_FAILED ||
1481 state == SERVICE_AUTO_RESTART)
1482 service_notify_sockets_dead(s);
1484 if (state != SERVICE_START_PRE &&
1485 state != SERVICE_START &&
1486 state != SERVICE_START_POST &&
1487 state != SERVICE_RUNNING &&
1488 state != SERVICE_RELOAD &&
1489 state != SERVICE_STOP &&
1490 state != SERVICE_STOP_SIGTERM &&
1491 state != SERVICE_STOP_SIGKILL &&
1492 state != SERVICE_STOP_POST &&
1493 state != SERVICE_FINAL_SIGTERM &&
1494 state != SERVICE_FINAL_SIGKILL &&
1495 !(state == SERVICE_DEAD && s->meta.job)) {
1496 service_close_socket_fd(s);
1497 service_connection_unref(s);
1500 /* For the inactive states unit_notify() will trim the cgroup,
1501 * but for exit we have to do that ourselves... */
1502 if (state == SERVICE_EXITED && s->meta.manager->n_reloading <= 0)
1503 cgroup_bonding_trim_list(s->meta.cgroup_bondings, true);
1505 if (old_state != state)
1506 log_debug("%s changed %s -> %s", s->meta.id, service_state_to_string(old_state), service_state_to_string(state));
1508 unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state], !s->reload_failure);
1509 s->reload_failure = false;
1512 static int service_coldplug(Unit *u) {
1513 Service *s = SERVICE(u);
1517 assert(s->state == SERVICE_DEAD);
1519 if (s->deserialized_state != s->state) {
1521 if (s->deserialized_state == SERVICE_START_PRE ||
1522 s->deserialized_state == SERVICE_START ||
1523 s->deserialized_state == SERVICE_START_POST ||
1524 s->deserialized_state == SERVICE_RELOAD ||
1525 s->deserialized_state == SERVICE_STOP ||
1526 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1527 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1528 s->deserialized_state == SERVICE_STOP_POST ||
1529 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1530 s->deserialized_state == SERVICE_FINAL_SIGKILL ||
1531 s->deserialized_state == SERVICE_AUTO_RESTART) {
1533 if (s->deserialized_state == SERVICE_AUTO_RESTART || s->timeout_usec > 0) {
1536 k = s->deserialized_state == SERVICE_AUTO_RESTART ? s->restart_usec : s->timeout_usec;
1538 if ((r = unit_watch_timer(UNIT(s), k, &s->timer_watch)) < 0)
1543 if ((s->deserialized_state == SERVICE_START &&
1544 (s->type == SERVICE_FORKING ||
1545 s->type == SERVICE_DBUS ||
1546 s->type == SERVICE_ONESHOT ||
1547 s->type == SERVICE_NOTIFY)) ||
1548 s->deserialized_state == SERVICE_START_POST ||
1549 s->deserialized_state == SERVICE_RUNNING ||
1550 s->deserialized_state == SERVICE_RELOAD ||
1551 s->deserialized_state == SERVICE_STOP ||
1552 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1553 s->deserialized_state == SERVICE_STOP_SIGKILL)
1554 if (s->main_pid > 0)
1555 if ((r = unit_watch_pid(UNIT(s), s->main_pid)) < 0)
1558 if (s->deserialized_state == SERVICE_START_PRE ||
1559 s->deserialized_state == SERVICE_START ||
1560 s->deserialized_state == SERVICE_START_POST ||
1561 s->deserialized_state == SERVICE_RELOAD ||
1562 s->deserialized_state == SERVICE_STOP ||
1563 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1564 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1565 s->deserialized_state == SERVICE_STOP_POST ||
1566 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1567 s->deserialized_state == SERVICE_FINAL_SIGKILL)
1568 if (s->control_pid > 0)
1569 if ((r = unit_watch_pid(UNIT(s), s->control_pid)) < 0)
1572 service_set_state(s, s->deserialized_state);
1578 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
1582 unsigned rn_fds = 0;
1583 Set *set, *free_set = NULL;
1590 if (s->socket_fd >= 0)
1593 if (!set_isempty(s->configured_sockets))
1594 set = s->configured_sockets;
1596 if ((r = service_get_sockets(s, &free_set)) < 0)
1602 SET_FOREACH(sock, set, i) {
1606 if ((r = socket_collect_fds(sock, &cfds, &cn_fds)) < 0)
1618 if (!(t = new(int, rn_fds+cn_fds))) {
1624 memcpy(t, rfds, rn_fds * sizeof(int));
1625 memcpy(t+rn_fds, cfds, cn_fds * sizeof(int));
1630 rn_fds = rn_fds+cn_fds;
1648 static int service_spawn(
1653 bool apply_permissions,
1655 bool apply_tty_stdin,
1656 bool set_notify_socket,
1661 int *fds = NULL, *fdsbuf = NULL;
1662 unsigned n_fds = 0, n_env = 0;
1663 char **argv = NULL, **final_env = NULL, **our_env = NULL;
1670 s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1671 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1672 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
1674 if (s->socket_fd >= 0) {
1675 fds = &s->socket_fd;
1678 if ((r = service_collect_fds(s, &fdsbuf, &n_fds)) < 0)
1685 if (timeout && s->timeout_usec) {
1686 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1689 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1691 if (!(argv = unit_full_printf_strv(UNIT(s), c->argv))) {
1696 if (!(our_env = new0(char*, 4))) {
1701 if (set_notify_socket)
1702 if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=%s", s->meta.manager->notify_socket) < 0) {
1707 if (s->main_pid > 0)
1708 if (asprintf(our_env + n_env++, "MAINPID=%lu", (unsigned long) s->main_pid) < 0) {
1713 if (!(final_env = strv_env_merge(2,
1714 s->meta.manager->environment,
1729 s->meta.manager->confirm_spawn,
1730 s->meta.cgroup_bondings,
1731 s->meta.cgroup_attributes,
1738 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1739 /* FIXME: we need to do something here */
1745 strv_free(final_env);
1755 strv_free(final_env);
1758 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1763 static int main_pid_good(Service *s) {
1766 /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1769 /* If we know the pid file, then lets just check if it is
1771 if (s->main_pid_known) {
1773 /* If it's an alien child let's check if it is still
1775 if (s->main_pid_alien)
1776 return kill(s->main_pid, 0) >= 0 || errno != ESRCH;
1778 /* .. otherwise assume we'll get a SIGCHLD for it,
1779 * which we really should wait for to collect exit
1780 * status and code */
1781 return s->main_pid > 0;
1784 /* We don't know the pid */
1788 static int control_pid_good(Service *s) {
1791 return s->control_pid > 0;
1794 static int cgroup_good(Service *s) {
1799 if ((r = cgroup_bonding_is_empty_list(s->meta.cgroup_bondings)) < 0)
1805 static void service_enter_dead(Service *s, bool success, bool allow_restart) {
1812 if (allow_restart &&
1813 !s->forbid_restart &&
1814 (s->restart == SERVICE_RESTART_ALWAYS ||
1815 (s->restart == SERVICE_RESTART_ON_SUCCESS && !s->failure) ||
1816 (s->restart == SERVICE_RESTART_ON_FAILURE && s->failure) ||
1817 (s->restart == SERVICE_RESTART_ON_ABORT && s->failure &&
1818 (s->main_exec_status.code == CLD_KILLED ||
1819 s->main_exec_status.code == CLD_DUMPED)))) {
1821 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
1824 service_set_state(s, SERVICE_AUTO_RESTART);
1826 service_set_state(s, s->failure ? SERVICE_FAILED : SERVICE_DEAD);
1828 s->forbid_restart = false;
1833 log_warning("%s failed to run install restart timer: %s", s->meta.id, strerror(-r));
1834 service_enter_dead(s, false, false);
1837 static void service_enter_signal(Service *s, ServiceState state, bool success);
1839 static void service_enter_stop_post(Service *s, bool success) {
1846 service_unwatch_control_pid(s);
1848 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST])) {
1849 s->control_command_id = SERVICE_EXEC_STOP_POST;
1851 if ((r = service_spawn(s,
1855 !s->permissions_start_only,
1856 !s->root_directory_start_only,
1859 &s->control_pid)) < 0)
1863 service_set_state(s, SERVICE_STOP_POST);
1865 service_enter_signal(s, SERVICE_FINAL_SIGTERM, true);
1870 log_warning("%s failed to run 'stop-post' task: %s", s->meta.id, strerror(-r));
1871 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1874 static void service_enter_signal(Service *s, ServiceState state, bool success) {
1876 Set *pid_set = NULL;
1877 bool wait_for_exit = false;
1884 if (s->exec_context.kill_mode != KILL_NONE) {
1885 int sig = (state == SERVICE_STOP_SIGTERM || state == SERVICE_FINAL_SIGTERM) ? s->exec_context.kill_signal : SIGKILL;
1887 if (s->main_pid > 0) {
1888 if (kill_and_sigcont(s->main_pid, sig) < 0 && errno != ESRCH)
1889 log_warning("Failed to kill main process %li: %m", (long) s->main_pid);
1891 wait_for_exit = !s->main_pid_alien;
1894 if (s->control_pid > 0) {
1895 if (kill_and_sigcont(s->control_pid, sig) < 0 && errno != ESRCH)
1896 log_warning("Failed to kill control process %li: %m", (long) s->control_pid);
1898 wait_for_exit = true;
1901 if (s->exec_context.kill_mode == KILL_CONTROL_GROUP) {
1903 if (!(pid_set = set_new(trivial_hash_func, trivial_compare_func))) {
1908 /* Exclude the main/control pids from being killed via the cgroup */
1909 if (s->main_pid > 0)
1910 if ((r = set_put(pid_set, LONG_TO_PTR(s->main_pid))) < 0)
1913 if (s->control_pid > 0)
1914 if ((r = set_put(pid_set, LONG_TO_PTR(s->control_pid))) < 0)
1917 if ((r = cgroup_bonding_kill_list(s->meta.cgroup_bondings, sig, true, pid_set)) < 0) {
1918 if (r != -EAGAIN && r != -ESRCH && r != -ENOENT)
1919 log_warning("Failed to kill control group: %s", strerror(-r));
1921 wait_for_exit = true;
1928 if (wait_for_exit) {
1929 if (s->timeout_usec > 0)
1930 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1933 service_set_state(s, state);
1934 } else if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1935 service_enter_stop_post(s, true);
1937 service_enter_dead(s, true, true);
1942 log_warning("%s failed to kill processes: %s", s->meta.id, strerror(-r));
1944 if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1945 service_enter_stop_post(s, false);
1947 service_enter_dead(s, false, true);
1953 static void service_enter_stop(Service *s, bool success) {
1961 service_unwatch_control_pid(s);
1963 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP])) {
1964 s->control_command_id = SERVICE_EXEC_STOP;
1966 if ((r = service_spawn(s,
1970 !s->permissions_start_only,
1971 !s->root_directory_start_only,
1974 &s->control_pid)) < 0)
1977 service_set_state(s, SERVICE_STOP);
1979 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
1984 log_warning("%s failed to run 'stop' task: %s", s->meta.id, strerror(-r));
1985 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1988 static void service_enter_running(Service *s, bool success) {
1989 int main_pid_ok, cgroup_ok;
1995 main_pid_ok = main_pid_good(s);
1996 cgroup_ok = cgroup_good(s);
1998 if ((main_pid_ok > 0 || (main_pid_ok < 0 && cgroup_ok != 0)) &&
1999 (s->bus_name_good || s->type != SERVICE_DBUS))
2000 service_set_state(s, SERVICE_RUNNING);
2001 else if (s->remain_after_exit)
2002 service_set_state(s, SERVICE_EXITED);
2004 service_enter_stop(s, true);
2007 static void service_enter_start_post(Service *s) {
2011 service_unwatch_control_pid(s);
2013 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_POST])) {
2014 s->control_command_id = SERVICE_EXEC_START_POST;
2016 if ((r = service_spawn(s,
2020 !s->permissions_start_only,
2021 !s->root_directory_start_only,
2024 &s->control_pid)) < 0)
2027 service_set_state(s, SERVICE_START_POST);
2029 service_enter_running(s, true);
2034 log_warning("%s failed to run 'start-post' task: %s", s->meta.id, strerror(-r));
2035 service_enter_stop(s, false);
2038 static void service_enter_start(Service *s) {
2045 assert(s->exec_command[SERVICE_EXEC_START]);
2046 assert(!s->exec_command[SERVICE_EXEC_START]->command_next || s->type == SERVICE_ONESHOT);
2048 if (s->type == SERVICE_FORKING)
2049 service_unwatch_control_pid(s);
2051 service_unwatch_main_pid(s);
2053 if (s->type == SERVICE_FORKING) {
2054 s->control_command_id = SERVICE_EXEC_START;
2055 c = s->control_command = s->exec_command[SERVICE_EXEC_START];
2057 s->main_command = NULL;
2059 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2060 s->control_command = NULL;
2062 c = s->main_command = s->exec_command[SERVICE_EXEC_START];
2065 if ((r = service_spawn(s,
2067 s->type == SERVICE_FORKING || s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY,
2072 s->notify_access != NOTIFY_NONE,
2076 if (s->type == SERVICE_SIMPLE) {
2077 /* For simple services we immediately start
2078 * the START_POST binaries. */
2080 service_set_main_pid(s, pid);
2081 service_enter_start_post(s);
2083 } else if (s->type == SERVICE_FORKING) {
2085 /* For forking services we wait until the start
2086 * process exited. */
2088 s->control_pid = pid;
2089 service_set_state(s, SERVICE_START);
2091 } else if (s->type == SERVICE_ONESHOT ||
2092 s->type == SERVICE_DBUS ||
2093 s->type == SERVICE_NOTIFY) {
2095 /* For oneshot services we wait until the start
2096 * process exited, too, but it is our main process. */
2098 /* For D-Bus services we know the main pid right away,
2099 * but wait for the bus name to appear on the
2100 * bus. Notify services are similar. */
2102 service_set_main_pid(s, pid);
2103 service_set_state(s, SERVICE_START);
2105 assert_not_reached("Unknown service type");
2110 log_warning("%s failed to run 'start' task: %s", s->meta.id, strerror(-r));
2111 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2114 static void service_enter_start_pre(Service *s) {
2119 service_unwatch_control_pid(s);
2121 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_PRE])) {
2122 s->control_command_id = SERVICE_EXEC_START_PRE;
2124 if ((r = service_spawn(s,
2128 !s->permissions_start_only,
2129 !s->root_directory_start_only,
2132 &s->control_pid)) < 0)
2135 service_set_state(s, SERVICE_START_PRE);
2137 service_enter_start(s);
2142 log_warning("%s failed to run 'start-pre' task: %s", s->meta.id, strerror(-r));
2143 service_enter_dead(s, false, true);
2146 static void service_enter_restart(Service *s) {
2151 dbus_error_init(&error);
2154 log_info("Job pending for unit, delaying automatic restart.");
2156 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
2160 service_enter_dead(s, true, false);
2162 if ((r = manager_add_job(s->meta.manager, JOB_START, UNIT(s), JOB_FAIL, false, &error, NULL)) < 0)
2165 log_debug("%s scheduled restart job.", s->meta.id);
2169 log_warning("%s failed to schedule restart job: %s", s->meta.id, bus_error(&error, -r));
2170 service_enter_dead(s, false, false);
2172 dbus_error_free(&error);
2175 static void service_enter_reload(Service *s) {
2180 service_unwatch_control_pid(s);
2182 if ((s->control_command = s->exec_command[SERVICE_EXEC_RELOAD])) {
2183 s->control_command_id = SERVICE_EXEC_RELOAD;
2185 if ((r = service_spawn(s,
2189 !s->permissions_start_only,
2190 !s->root_directory_start_only,
2193 &s->control_pid)) < 0)
2196 service_set_state(s, SERVICE_RELOAD);
2198 service_enter_running(s, true);
2203 log_warning("%s failed to run 'reload' task: %s", s->meta.id, strerror(-r));
2204 s->reload_failure = true;
2205 service_enter_running(s, true);
2208 static void service_run_next_control(Service *s, bool success) {
2212 assert(s->control_command);
2213 assert(s->control_command->command_next);
2218 assert(s->control_command_id != SERVICE_EXEC_START);
2220 s->control_command = s->control_command->command_next;
2221 service_unwatch_control_pid(s);
2223 if ((r = service_spawn(s,
2227 !s->permissions_start_only,
2228 !s->root_directory_start_only,
2229 s->control_command_id == SERVICE_EXEC_START_PRE ||
2230 s->control_command_id == SERVICE_EXEC_STOP_POST,
2232 &s->control_pid)) < 0)
2238 log_warning("%s failed to run next control task: %s", s->meta.id, strerror(-r));
2240 if (s->state == SERVICE_START_PRE)
2241 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2242 else if (s->state == SERVICE_STOP)
2243 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
2244 else if (s->state == SERVICE_STOP_POST)
2245 service_enter_dead(s, false, true);
2246 else if (s->state == SERVICE_RELOAD) {
2247 s->reload_failure = true;
2248 service_enter_running(s, true);
2250 service_enter_stop(s, false);
2253 static void service_run_next_main(Service *s, bool success) {
2258 assert(s->main_command);
2259 assert(s->main_command->command_next);
2260 assert(s->type == SERVICE_ONESHOT);
2265 s->main_command = s->main_command->command_next;
2266 service_unwatch_main_pid(s);
2268 if ((r = service_spawn(s,
2275 s->notify_access != NOTIFY_NONE,
2279 service_set_main_pid(s, pid);
2284 log_warning("%s failed to run next main task: %s", s->meta.id, strerror(-r));
2285 service_enter_stop(s, false);
2288 static int service_start(Unit *u) {
2289 Service *s = SERVICE(u);
2293 /* We cannot fulfill this request right now, try again later
2295 if (s->state == SERVICE_STOP ||
2296 s->state == SERVICE_STOP_SIGTERM ||
2297 s->state == SERVICE_STOP_SIGKILL ||
2298 s->state == SERVICE_STOP_POST ||
2299 s->state == SERVICE_FINAL_SIGTERM ||
2300 s->state == SERVICE_FINAL_SIGKILL)
2303 /* Already on it! */
2304 if (s->state == SERVICE_START_PRE ||
2305 s->state == SERVICE_START ||
2306 s->state == SERVICE_START_POST)
2309 assert(s->state == SERVICE_DEAD || s->state == SERVICE_FAILED || s->state == SERVICE_AUTO_RESTART);
2311 /* Make sure we don't enter a busy loop of some kind. */
2312 if (!ratelimit_test(&s->ratelimit)) {
2313 log_warning("%s start request repeated too quickly, refusing to start.", u->meta.id);
2318 s->main_pid_known = false;
2319 s->main_pid_alien = false;
2320 s->forbid_restart = false;
2322 service_enter_start_pre(s);
2326 static int service_stop(Unit *u) {
2327 Service *s = SERVICE(u);
2331 /* This is a user request, so don't do restarts on this
2333 s->forbid_restart = true;
2336 if (s->state == SERVICE_STOP ||
2337 s->state == SERVICE_STOP_SIGTERM ||
2338 s->state == SERVICE_STOP_SIGKILL ||
2339 s->state == SERVICE_STOP_POST ||
2340 s->state == SERVICE_FINAL_SIGTERM ||
2341 s->state == SERVICE_FINAL_SIGKILL)
2344 /* Don't allow a restart */
2345 if (s->state == SERVICE_AUTO_RESTART) {
2346 service_set_state(s, SERVICE_DEAD);
2350 /* If there's already something running we go directly into
2352 if (s->state == SERVICE_START_PRE ||
2353 s->state == SERVICE_START ||
2354 s->state == SERVICE_START_POST ||
2355 s->state == SERVICE_RELOAD) {
2356 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
2360 assert(s->state == SERVICE_RUNNING ||
2361 s->state == SERVICE_EXITED);
2363 service_enter_stop(s, true);
2367 static int service_reload(Unit *u) {
2368 Service *s = SERVICE(u);
2372 assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
2374 service_enter_reload(s);
2378 static bool service_can_reload(Unit *u) {
2379 Service *s = SERVICE(u);
2383 return !!s->exec_command[SERVICE_EXEC_RELOAD];
2386 static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
2387 Service *s = SERVICE(u);
2393 unit_serialize_item(u, f, "state", service_state_to_string(s->state));
2394 unit_serialize_item(u, f, "failure", yes_no(s->failure));
2396 if (s->control_pid > 0)
2397 unit_serialize_item_format(u, f, "control-pid", "%lu", (unsigned long) s->control_pid);
2399 if (s->main_pid_known && s->main_pid > 0)
2400 unit_serialize_item_format(u, f, "main-pid", "%lu", (unsigned long) s->main_pid);
2402 unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
2405 unit_serialize_item(u, f, "status-text", s->status_text);
2407 /* There's a minor uncleanliness here: if there are multiple
2408 * commands attached here, we will start from the first one
2410 if (s->control_command_id >= 0)
2411 unit_serialize_item(u, f, "control-command", service_exec_command_to_string(s->control_command_id));
2413 if (s->socket_fd >= 0) {
2416 if ((copy = fdset_put_dup(fds, s->socket_fd)) < 0)
2419 unit_serialize_item_format(u, f, "socket-fd", "%i", copy);
2422 if (s->main_exec_status.pid > 0) {
2423 unit_serialize_item_format(u, f, "main-exec-status-pid", "%lu", (unsigned long) s->main_exec_status.pid);
2424 dual_timestamp_serialize(f, "main-exec-status-start", &s->main_exec_status.start_timestamp);
2425 dual_timestamp_serialize(f, "main-exec-status-exit", &s->main_exec_status.exit_timestamp);
2427 if (dual_timestamp_is_set(&s->main_exec_status.exit_timestamp)) {
2428 unit_serialize_item_format(u, f, "main-exec-status-code", "%i", s->main_exec_status.code);
2429 unit_serialize_item_format(u, f, "main-exec-status-status", "%i", s->main_exec_status.status);
2436 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
2437 Service *s = SERVICE(u);
2444 if (streq(key, "state")) {
2447 if ((state = service_state_from_string(value)) < 0)
2448 log_debug("Failed to parse state value %s", value);
2450 s->deserialized_state = state;
2451 } else if (streq(key, "failure")) {
2454 if ((b = parse_boolean(value)) < 0)
2455 log_debug("Failed to parse failure value %s", value);
2457 s->failure = b || s->failure;
2458 } else if (streq(key, "control-pid")) {
2461 if (parse_pid(value, &pid) < 0)
2462 log_debug("Failed to parse control-pid value %s", value);
2464 s->control_pid = pid;
2465 } else if (streq(key, "main-pid")) {
2468 if (parse_pid(value, &pid) < 0)
2469 log_debug("Failed to parse main-pid value %s", value);
2471 service_set_main_pid(s, (pid_t) pid);
2472 } else if (streq(key, "main-pid-known")) {
2475 if ((b = parse_boolean(value)) < 0)
2476 log_debug("Failed to parse main-pid-known value %s", value);
2478 s->main_pid_known = b;
2479 } else if (streq(key, "status-text")) {
2482 if ((t = strdup(value))) {
2483 free(s->status_text);
2487 } else if (streq(key, "control-command")) {
2488 ServiceExecCommand id;
2490 if ((id = service_exec_command_from_string(value)) < 0)
2491 log_debug("Failed to parse exec-command value %s", value);
2493 s->control_command_id = id;
2494 s->control_command = s->exec_command[id];
2496 } else if (streq(key, "socket-fd")) {
2499 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2500 log_debug("Failed to parse socket-fd value %s", value);
2503 if (s->socket_fd >= 0)
2504 close_nointr_nofail(s->socket_fd);
2505 s->socket_fd = fdset_remove(fds, fd);
2507 } else if (streq(key, "main-exec-status-pid")) {
2510 if (parse_pid(value, &pid) < 0)
2511 log_debug("Failed to parse main-exec-status-pid value %s", value);
2513 s->main_exec_status.pid = pid;
2514 } else if (streq(key, "main-exec-status-code")) {
2517 if (safe_atoi(value, &i) < 0)
2518 log_debug("Failed to parse main-exec-status-code value %s", value);
2520 s->main_exec_status.code = i;
2521 } else if (streq(key, "main-exec-status-status")) {
2524 if (safe_atoi(value, &i) < 0)
2525 log_debug("Failed to parse main-exec-status-status value %s", value);
2527 s->main_exec_status.status = i;
2528 } else if (streq(key, "main-exec-status-start"))
2529 dual_timestamp_deserialize(value, &s->main_exec_status.start_timestamp);
2530 else if (streq(key, "main-exec-status-exit"))
2531 dual_timestamp_deserialize(value, &s->main_exec_status.exit_timestamp);
2533 log_debug("Unknown serialization key '%s'", key);
2538 static UnitActiveState service_active_state(Unit *u) {
2541 return state_translation_table[SERVICE(u)->state];
2544 static const char *service_sub_state_to_string(Unit *u) {
2547 return service_state_to_string(SERVICE(u)->state);
2550 static bool service_check_gc(Unit *u) {
2551 Service *s = SERVICE(u);
2555 /* Never clean up services that still have a process around,
2556 * even if the service is formally dead. */
2557 if (cgroup_good(s) > 0 ||
2558 main_pid_good(s) > 0 ||
2559 control_pid_good(s) > 0)
2562 #ifdef HAVE_SYSV_COMPAT
2570 static bool service_check_snapshot(Unit *u) {
2571 Service *s = SERVICE(u);
2575 return !s->got_socket_fd;
2578 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2579 Service *s = SERVICE(u);
2585 if (!s->meta.fragment_path)
2586 success = is_clean_exit_lsb(code, status);
2588 success = is_clean_exit(code, status);
2590 if (s->main_pid == pid) {
2593 exec_status_exit(&s->main_exec_status, &s->exec_context, pid, code, status);
2595 /* If this is not a forking service than the main
2596 * process got started and hence we copy the exit
2597 * status so that it is recorded both as main and as
2598 * control process exit status */
2599 if (s->main_command) {
2600 s->main_command->exec_status = s->main_exec_status;
2602 if (s->main_command->ignore)
2606 log_full(success ? LOG_DEBUG : LOG_NOTICE,
2607 "%s: main process exited, code=%s, status=%i", u->meta.id, sigchld_code_to_string(code), status);
2608 s->failure = s->failure || !success;
2610 if (s->main_command &&
2611 s->main_command->command_next &&
2614 /* There is another command to *
2615 * execute, so let's do that. */
2617 log_debug("%s running next main command for state %s", u->meta.id, service_state_to_string(s->state));
2618 service_run_next_main(s, success);
2622 /* The service exited, so the service is officially
2624 s->main_command = NULL;
2628 case SERVICE_START_POST:
2629 case SERVICE_RELOAD:
2631 /* Need to wait until the operation is
2636 if (s->type == SERVICE_ONESHOT) {
2637 /* This was our main goal, so let's go on */
2639 service_enter_start_post(s);
2641 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2644 assert(s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY);
2649 case SERVICE_RUNNING:
2650 service_enter_running(s, success);
2653 case SERVICE_STOP_SIGTERM:
2654 case SERVICE_STOP_SIGKILL:
2656 if (!control_pid_good(s))
2657 service_enter_stop_post(s, success);
2659 /* If there is still a control process, wait for that first */
2663 assert_not_reached("Uh, main process died at wrong time.");
2667 } else if (s->control_pid == pid) {
2671 if (s->control_command) {
2672 exec_status_exit(&s->control_command->exec_status, &s->exec_context, pid, code, status);
2674 if (s->control_command->ignore)
2678 log_full(success ? LOG_DEBUG : LOG_NOTICE,
2679 "%s: control process exited, code=%s status=%i", u->meta.id, sigchld_code_to_string(code), status);
2680 s->failure = s->failure || !success;
2682 if (s->control_command &&
2683 s->control_command->command_next &&
2686 /* There is another command to *
2687 * execute, so let's do that. */
2689 log_debug("%s running next control command for state %s", u->meta.id, service_state_to_string(s->state));
2690 service_run_next_control(s, success);
2693 /* No further commands for this step, so let's
2694 * figure out what to do next */
2696 s->control_command = NULL;
2697 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2699 log_debug("%s got final SIGCHLD for state %s", u->meta.id, service_state_to_string(s->state));
2703 case SERVICE_START_PRE:
2705 service_enter_start(s);
2707 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2711 assert(s->type == SERVICE_FORKING);
2713 /* Let's try to load the pid
2714 * file here if we can. We
2715 * ignore the return value,
2716 * since the PID file might
2717 * actually be created by a
2718 * START_POST script */
2721 service_load_pid_file(s);
2722 service_search_main_pid(s);
2724 service_enter_start_post(s);
2726 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2730 case SERVICE_START_POST:
2732 service_load_pid_file(s);
2733 service_search_main_pid(s);
2736 s->reload_failure = !success;
2737 service_enter_running(s, true);
2740 case SERVICE_RELOAD:
2742 service_load_pid_file(s);
2743 service_search_main_pid(s);
2746 s->reload_failure = !success;
2747 service_enter_running(s, true);
2751 service_enter_signal(s, SERVICE_STOP_SIGTERM, success);
2754 case SERVICE_STOP_SIGTERM:
2755 case SERVICE_STOP_SIGKILL:
2756 if (main_pid_good(s) <= 0)
2757 service_enter_stop_post(s, success);
2759 /* If there is still a service
2760 * process around, wait until
2761 * that one quit, too */
2764 case SERVICE_STOP_POST:
2765 case SERVICE_FINAL_SIGTERM:
2766 case SERVICE_FINAL_SIGKILL:
2767 service_enter_dead(s, success, true);
2771 assert_not_reached("Uh, control process died at wrong time.");
2776 /* Notify clients about changed exit status */
2777 unit_add_to_dbus_queue(u);
2780 static void service_timer_event(Unit *u, uint64_t elapsed, Watch* w) {
2781 Service *s = SERVICE(u);
2784 assert(elapsed == 1);
2786 assert(w == &s->timer_watch);
2790 case SERVICE_START_PRE:
2792 log_warning("%s operation timed out. Terminating.", u->meta.id);
2793 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2796 case SERVICE_START_POST:
2797 log_warning("%s operation timed out. Stopping.", u->meta.id);
2798 service_enter_stop(s, false);
2801 case SERVICE_RELOAD:
2802 log_warning("%s operation timed out. Stopping.", u->meta.id);
2803 s->reload_failure = true;
2804 service_enter_running(s, true);
2808 log_warning("%s stopping timed out. Terminating.", u->meta.id);
2809 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
2812 case SERVICE_STOP_SIGTERM:
2813 if (s->exec_context.send_sigkill) {
2814 log_warning("%s stopping timed out. Killing.", u->meta.id);
2815 service_enter_signal(s, SERVICE_STOP_SIGKILL, false);
2817 log_warning("%s stopping timed out. Skipping SIGKILL.", u->meta.id);
2818 service_enter_stop_post(s, false);
2823 case SERVICE_STOP_SIGKILL:
2824 /* Uh, we sent a SIGKILL and it is still not gone?
2825 * Must be something we cannot kill, so let's just be
2826 * weirded out and continue */
2828 log_warning("%s still around after SIGKILL. Ignoring.", u->meta.id);
2829 service_enter_stop_post(s, false);
2832 case SERVICE_STOP_POST:
2833 log_warning("%s stopping timed out (2). Terminating.", u->meta.id);
2834 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2837 case SERVICE_FINAL_SIGTERM:
2838 if (s->exec_context.send_sigkill) {
2839 log_warning("%s stopping timed out (2). Killing.", u->meta.id);
2840 service_enter_signal(s, SERVICE_FINAL_SIGKILL, false);
2842 log_warning("%s stopping timed out (2). Skipping SIGKILL. Entering failed mode.", u->meta.id);
2843 service_enter_dead(s, false, true);
2848 case SERVICE_FINAL_SIGKILL:
2849 log_warning("%s still around after SIGKILL (2). Entering failed mode.", u->meta.id);
2850 service_enter_dead(s, false, true);
2853 case SERVICE_AUTO_RESTART:
2854 log_info("%s holdoff time over, scheduling restart.", u->meta.id);
2855 service_enter_restart(s);
2859 assert_not_reached("Timeout at wrong time.");
2863 static void service_cgroup_notify_event(Unit *u) {
2864 Service *s = SERVICE(u);
2868 log_debug("%s: cgroup is empty", u->meta.id);
2872 /* Waiting for SIGCHLD is usually more interesting,
2873 * because it includes return codes/signals. Which is
2874 * why we ignore the cgroup events for most cases,
2875 * except when we don't know pid which to expect the
2878 case SERVICE_RUNNING:
2879 service_enter_running(s, true);
2882 case SERVICE_STOP_SIGTERM:
2883 case SERVICE_STOP_SIGKILL:
2885 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2886 service_enter_stop_post(s, true);
2890 case SERVICE_FINAL_SIGTERM:
2891 case SERVICE_FINAL_SIGKILL:
2892 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2893 service_enter_dead(s, true, true);
2902 static void service_notify_message(Unit *u, pid_t pid, char **tags) {
2903 Service *s = SERVICE(u);
2908 if (s->notify_access == NOTIFY_NONE) {
2909 log_warning("%s: Got notification message from PID %lu, but reception is disabled.",
2910 u->meta.id, (unsigned long) pid);
2914 if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
2915 log_warning("%s: Got notification message from PID %lu, but reception only permitted for PID %lu",
2916 u->meta.id, (unsigned long) pid, (unsigned long) s->main_pid);
2920 log_debug("%s: Got message", u->meta.id);
2922 /* Interpret MAINPID= */
2923 if ((e = strv_find_prefix(tags, "MAINPID=")) &&
2924 (s->state == SERVICE_START ||
2925 s->state == SERVICE_START_POST ||
2926 s->state == SERVICE_RUNNING ||
2927 s->state == SERVICE_RELOAD)) {
2929 if (parse_pid(e + 8, &pid) < 0)
2930 log_warning("Failed to parse notification message %s", e);
2932 log_debug("%s: got %s", u->meta.id, e);
2933 service_set_main_pid(s, pid);
2937 /* Interpret READY= */
2938 if (s->type == SERVICE_NOTIFY &&
2939 s->state == SERVICE_START &&
2940 strv_find(tags, "READY=1")) {
2941 log_debug("%s: got READY=1", u->meta.id);
2943 service_enter_start_post(s);
2946 /* Interpret STATUS= */
2947 if ((e = strv_find_prefix(tags, "STATUS="))) {
2951 if (!(t = strdup(e+7))) {
2952 log_error("Failed to allocate string.");
2956 log_debug("%s: got %s", u->meta.id, e);
2958 free(s->status_text);
2961 free(s->status_text);
2962 s->status_text = NULL;
2967 /* Notify clients about changed status or main pid */
2968 unit_add_to_dbus_queue(u);
2971 #ifdef HAVE_SYSV_COMPAT
2974 static void sysv_facility_in_insserv_conf(Manager *mgr) {
2978 if (!(f = fopen("/etc/insserv.conf", "re"))) {
2979 r = errno == ENOENT ? 0 : -errno;
2984 char l[LINE_MAX], *t;
2985 char **parsed = NULL;
2987 if (!fgets(l, sizeof(l), f)) {
2992 log_error("Failed to read configuration file '/etc/insserv.conf': %s", strerror(-r));
2997 if (*t != '$' && *t != '<')
3000 parsed = strv_split(t,WHITESPACE);
3001 /* we ignore <interactive>, not used, equivalent to X-Interactive */
3002 if (parsed && !startswith_no_case (parsed[0], "<interactive>")) {
3005 if (sysv_translate_facility(parsed[0], NULL, &facility) < 0)
3007 if ((u = manager_get_unit(mgr, facility)) && (u->meta.type == UNIT_TARGET)) {
3009 char *dep = NULL, *name, **j;
3011 STRV_FOREACH (j, parsed+1) {
3020 if (sysv_translate_facility(name, NULL, &dep) < 0)
3023 r = unit_add_two_dependencies_by_name(u, UNIT_BEFORE, e, dep, NULL, true);
3038 static int service_enumerate(Manager *m) {
3042 char *path = NULL, *fpath = NULL, *name = NULL;
3043 Set *runlevel_services[ELEMENTSOF(rcnd_table)], *shutdown_services = NULL;
3050 if (m->running_as != MANAGER_SYSTEM)
3053 zero(runlevel_services);
3055 STRV_FOREACH(p, m->lookup_paths.sysvrcnd_path)
3056 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++) {
3060 path = join(*p, "/", rcnd_table[i].path, NULL);
3069 if (!(d = opendir(path))) {
3070 if (errno != ENOENT)
3071 log_warning("opendir() failed on %s: %s", path, strerror(errno));
3076 while ((de = readdir(d))) {
3079 if (ignore_file(de->d_name))
3082 if (de->d_name[0] != 'S' && de->d_name[0] != 'K')
3085 if (strlen(de->d_name) < 4)
3088 a = undecchar(de->d_name[1]);
3089 b = undecchar(de->d_name[2]);
3095 fpath = join(path, "/", de->d_name, NULL);
3101 if (access(fpath, X_OK) < 0) {
3103 if (errno != ENOENT)
3104 log_warning("access() failed on %s: %s", fpath, strerror(errno));
3110 if (!(name = sysv_translate_name(de->d_name + 3))) {
3115 if ((r = manager_load_unit_prepare(m, name, NULL, NULL, &service)) < 0) {
3116 log_warning("Failed to prepare unit %s: %s", name, strerror(-r));
3120 if (de->d_name[0] == 'S') {
3122 if (rcnd_table[i].type == RUNLEVEL_UP || rcnd_table[i].type == RUNLEVEL_SYSINIT) {
3123 SERVICE(service)->sysv_start_priority_from_rcnd =
3124 MAX(a*10 + b, SERVICE(service)->sysv_start_priority_from_rcnd);
3126 SERVICE(service)->sysv_enabled = true;
3129 if ((r = set_ensure_allocated(&runlevel_services[i], trivial_hash_func, trivial_compare_func)) < 0)
3132 if ((r = set_put(runlevel_services[i], service)) < 0)
3135 } else if (de->d_name[0] == 'K' &&
3136 (rcnd_table[i].type == RUNLEVEL_DOWN ||
3137 rcnd_table[i].type == RUNLEVEL_SYSINIT)) {
3139 if ((r = set_ensure_allocated(&shutdown_services, trivial_hash_func, trivial_compare_func)) < 0)
3142 if ((r = set_put(shutdown_services, service)) < 0)
3148 /* Now we loaded all stubs and are aware of the lowest
3149 start-up priority for all services, not let's actually load
3150 the services, this will also tell us which services are
3151 actually native now */
3152 manager_dispatch_load_queue(m);
3154 /* If this is a native service, rely on native ways to pull in
3155 * a service, don't pull it in via sysv rcN.d links. */
3156 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++)
3157 SET_FOREACH(service, runlevel_services[i], j) {
3158 service = unit_follow_merge(service);
3160 if (service->meta.fragment_path)
3163 if ((r = unit_add_two_dependencies_by_name_inverse(service, UNIT_AFTER, UNIT_WANTS, rcnd_table[i].target, NULL, true)) < 0)
3167 /* We honour K links only for halt/reboot. For the normal
3168 * runlevels we assume the stop jobs will be implicitly added
3169 * by the core logic. Also, we don't really distinguish here
3170 * between the runlevels 0 and 6 and just add them to the
3171 * special shutdown target. On SUSE the boot.d/ runlevel is
3172 * also used for shutdown, so we add links for that too to the
3173 * shutdown target.*/
3174 SET_FOREACH(service, shutdown_services, j) {
3175 service = unit_follow_merge(service);
3177 if (service->meta.fragment_path)
3180 if ((r = unit_add_two_dependencies_by_name(service, UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true)) < 0)
3187 sysv_facility_in_insserv_conf (m);
3195 for (i = 0; i < ELEMENTSOF(rcnd_table); i++)
3196 set_free(runlevel_services[i]);
3197 set_free(shutdown_services);
3206 static void service_bus_name_owner_change(
3209 const char *old_owner,
3210 const char *new_owner) {
3212 Service *s = SERVICE(u);
3217 assert(streq(s->bus_name, name));
3218 assert(old_owner || new_owner);
3220 if (old_owner && new_owner)
3221 log_debug("%s's D-Bus name %s changed owner from %s to %s", u->meta.id, name, old_owner, new_owner);
3223 log_debug("%s's D-Bus name %s no longer registered by %s", u->meta.id, name, old_owner);
3225 log_debug("%s's D-Bus name %s now registered by %s", u->meta.id, name, new_owner);
3227 s->bus_name_good = !!new_owner;
3229 if (s->type == SERVICE_DBUS) {
3231 /* service_enter_running() will figure out what to
3233 if (s->state == SERVICE_RUNNING)
3234 service_enter_running(s, true);
3235 else if (s->state == SERVICE_START && new_owner)
3236 service_enter_start_post(s);
3238 } else if (new_owner &&
3240 (s->state == SERVICE_START ||
3241 s->state == SERVICE_START_POST ||
3242 s->state == SERVICE_RUNNING ||
3243 s->state == SERVICE_RELOAD)) {
3245 /* Try to acquire PID from bus service */
3246 log_debug("Trying to acquire PID from D-Bus name...");
3248 bus_query_pid(u->meta.manager, name);
3252 static void service_bus_query_pid_done(
3257 Service *s = SERVICE(u);
3262 log_debug("%s's D-Bus name %s is now owned by process %u", u->meta.id, name, (unsigned) pid);
3264 if (s->main_pid <= 0 &&
3265 (s->state == SERVICE_START ||
3266 s->state == SERVICE_START_POST ||
3267 s->state == SERVICE_RUNNING ||
3268 s->state == SERVICE_RELOAD))
3269 service_set_main_pid(s, pid);
3272 int service_set_socket_fd(Service *s, int fd, Socket *sock) {
3276 /* This is called by the socket code when instantiating a new
3277 * service for a stream socket and the socket needs to be
3280 if (s->meta.load_state != UNIT_LOADED)
3283 if (s->socket_fd >= 0)
3286 if (s->state != SERVICE_DEAD)
3290 s->got_socket_fd = true;
3291 s->accept_socket = sock;
3296 static void service_reset_failed(Unit *u) {
3297 Service *s = SERVICE(u);
3301 if (s->state == SERVICE_FAILED)
3302 service_set_state(s, SERVICE_DEAD);
3307 static bool service_need_daemon_reload(Unit *u) {
3308 Service *s = SERVICE(u);
3312 #ifdef HAVE_SYSV_COMPAT
3317 if (stat(s->sysv_path, &st) < 0)
3318 /* What, cannot access this anymore? */
3321 if (s->sysv_mtime > 0 &&
3322 timespec_load(&st.st_mtim) != s->sysv_mtime)
3330 static int service_kill(Unit *u, KillWho who, KillMode mode, int signo, DBusError *error) {
3331 Service *s = SERVICE(u);
3333 Set *pid_set = NULL;
3337 if (s->main_pid <= 0 && who == KILL_MAIN) {
3338 dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "No main process to kill");
3342 if (s->control_pid <= 0 && who == KILL_CONTROL) {
3343 dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "No control process to kill");
3347 if (who == KILL_CONTROL || who == KILL_ALL)
3348 if (s->control_pid > 0)
3349 if (kill(s->control_pid, signo) < 0)
3352 if (who == KILL_MAIN || who == KILL_ALL)
3353 if (s->main_pid > 0)
3354 if (kill(s->main_pid, signo) < 0)
3357 if (who == KILL_ALL && mode == KILL_CONTROL_GROUP) {
3360 if (!(pid_set = set_new(trivial_hash_func, trivial_compare_func)))
3363 /* Exclude the control/main pid from being killed via the cgroup */
3364 if (s->control_pid > 0)
3365 if ((q = set_put(pid_set, LONG_TO_PTR(s->control_pid))) < 0) {
3370 if (s->main_pid > 0)
3371 if ((q = set_put(pid_set, LONG_TO_PTR(s->main_pid))) < 0) {
3376 if ((q = cgroup_bonding_kill_list(s->meta.cgroup_bondings, signo, false, pid_set)) < 0)
3377 if (q != -EAGAIN && q != -ESRCH && q != -ENOENT)
3388 static const char* const service_state_table[_SERVICE_STATE_MAX] = {
3389 [SERVICE_DEAD] = "dead",
3390 [SERVICE_START_PRE] = "start-pre",
3391 [SERVICE_START] = "start",
3392 [SERVICE_START_POST] = "start-post",
3393 [SERVICE_RUNNING] = "running",
3394 [SERVICE_EXITED] = "exited",
3395 [SERVICE_RELOAD] = "reload",
3396 [SERVICE_STOP] = "stop",
3397 [SERVICE_STOP_SIGTERM] = "stop-sigterm",
3398 [SERVICE_STOP_SIGKILL] = "stop-sigkill",
3399 [SERVICE_STOP_POST] = "stop-post",
3400 [SERVICE_FINAL_SIGTERM] = "final-sigterm",
3401 [SERVICE_FINAL_SIGKILL] = "final-sigkill",
3402 [SERVICE_FAILED] = "failed",
3403 [SERVICE_AUTO_RESTART] = "auto-restart",
3406 DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
3408 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
3409 [SERVICE_RESTART_NO] = "no",
3410 [SERVICE_RESTART_ON_SUCCESS] = "on-success",
3411 [SERVICE_RESTART_ON_FAILURE] = "on-failure",
3412 [SERVICE_RESTART_ON_ABORT] = "on-abort",
3413 [SERVICE_RESTART_ALWAYS] = "always"
3416 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
3418 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
3419 [SERVICE_SIMPLE] = "simple",
3420 [SERVICE_FORKING] = "forking",
3421 [SERVICE_ONESHOT] = "oneshot",
3422 [SERVICE_DBUS] = "dbus",
3423 [SERVICE_NOTIFY] = "notify"
3426 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
3428 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
3429 [SERVICE_EXEC_START_PRE] = "ExecStartPre",
3430 [SERVICE_EXEC_START] = "ExecStart",
3431 [SERVICE_EXEC_START_POST] = "ExecStartPost",
3432 [SERVICE_EXEC_RELOAD] = "ExecReload",
3433 [SERVICE_EXEC_STOP] = "ExecStop",
3434 [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
3437 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
3439 static const char* const notify_access_table[_NOTIFY_ACCESS_MAX] = {
3440 [NOTIFY_NONE] = "none",
3441 [NOTIFY_MAIN] = "main",
3442 [NOTIFY_ALL] = "all"
3445 DEFINE_STRING_TABLE_LOOKUP(notify_access, NotifyAccess);
3447 const UnitVTable service_vtable = {
3448 .suffix = ".service",
3453 .show_status = true,
3455 .init = service_init,
3456 .done = service_done,
3457 .load = service_load,
3459 .coldplug = service_coldplug,
3461 .dump = service_dump,
3463 .start = service_start,
3464 .stop = service_stop,
3465 .reload = service_reload,
3467 .can_reload = service_can_reload,
3469 .kill = service_kill,
3471 .serialize = service_serialize,
3472 .deserialize_item = service_deserialize_item,
3474 .active_state = service_active_state,
3475 .sub_state_to_string = service_sub_state_to_string,
3477 .check_gc = service_check_gc,
3478 .check_snapshot = service_check_snapshot,
3480 .sigchld_event = service_sigchld_event,
3481 .timer_event = service_timer_event,
3483 .reset_failed = service_reset_failed,
3485 .need_daemon_reload = service_need_daemon_reload,
3487 .cgroup_notify_empty = service_cgroup_notify_event,
3488 .notify_message = service_notify_message,
3490 .bus_name_owner_change = service_bus_name_owner_change,
3491 .bus_query_pid_done = service_bus_query_pid_done,
3493 .bus_interface = "org.freedesktop.systemd1.Service",
3494 .bus_message_handler = bus_service_message_handler,
3495 .bus_invalidating_properties = bus_service_invalidating_properties,
3497 #ifdef HAVE_SYSV_COMPAT
3498 .enumerate = service_enumerate