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 asprintf(&d, "%s %s", chkconfig_description, j);
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 asprintf(&d, "%s %s", long_description, t);
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 if (asprintf(&path, "%s/%s", *p, name) < 0)
927 assert(endswith(path, ".service"));
928 path[strlen(path)-8] = 0;
930 r = service_load_sysv_path(s, path);
932 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU) || defined(TARGET_ANGSTROM)
933 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
934 /* Try Debian style *.sh source'able init scripts */
936 r = service_load_sysv_path(s, path);
942 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
943 /* Try SUSE style boot.* init scripts */
945 if (asprintf(&path, "%s/boot.%s", *p, name) < 0)
948 /* Drop .service suffix */
949 path[strlen(path)-8] = 0;
950 r = service_load_sysv_path(s, path);
955 #ifdef TARGET_FRUGALWARE
956 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
957 /* Try Frugalware style rc.* init scripts */
959 if (asprintf(&path, "%s/rc.%s", *p, name) < 0)
962 /* Drop .service suffix */
963 path[strlen(path)-8] = 0;
964 r = service_load_sysv_path(s, path);
972 if ((s->meta.load_state != UNIT_STUB))
979 static int service_load_sysv(Service *s) {
986 /* Load service data from SysV init scripts, preferably with
989 if (strv_isempty(s->meta.manager->lookup_paths.sysvinit_path))
992 if ((t = s->meta.id))
993 if ((r = service_load_sysv_name(s, t)) < 0)
996 if (s->meta.load_state == UNIT_STUB)
997 SET_FOREACH(t, s->meta.names, i) {
1001 if ((r = service_load_sysv_name(s, t)) < 0)
1004 if (s->meta.load_state != UNIT_STUB)
1012 static int fsck_fix_order(Service *s) {
1018 if (s->fsck_passno <= 0)
1021 /* For each pair of services where both have an fsck priority
1022 * we order things based on it. */
1024 LIST_FOREACH(units_by_type, other, s->meta.manager->units_by_type[UNIT_SERVICE]) {
1028 t = (Service*) other;
1033 if (t->meta.load_state != UNIT_LOADED)
1036 if (t->fsck_passno <= 0)
1039 if (t->fsck_passno < s->fsck_passno)
1041 else if (t->fsck_passno > s->fsck_passno)
1046 if ((r = unit_add_dependency(UNIT(s), d, UNIT(t), true)) < 0)
1053 static int service_verify(Service *s) {
1056 if (s->meta.load_state != UNIT_LOADED)
1059 if (!s->exec_command[SERVICE_EXEC_START]) {
1060 log_error("%s lacks ExecStart setting. Refusing.", s->meta.id);
1064 if (s->type != SERVICE_ONESHOT &&
1065 s->exec_command[SERVICE_EXEC_START]->command_next) {
1066 log_error("%s has more than one ExecStart setting, which is only allowed for Type=oneshot services. Refusing.", s->meta.id);
1070 if (s->type == SERVICE_ONESHOT &&
1071 s->exec_command[SERVICE_EXEC_RELOAD]) {
1072 log_error("%s has an ExecReload setting, which is not allowed for Type=oneshot services. Refusing.", s->meta.id);
1076 if (s->type == SERVICE_DBUS && !s->bus_name) {
1077 log_error("%s is of type D-Bus but no D-Bus service name has been specified. Refusing.", s->meta.id);
1081 if (s->exec_context.pam_name && s->exec_context.kill_mode != KILL_CONTROL_GROUP) {
1082 log_error("%s has PAM enabled. Kill mode must be set to 'control-group'. Refusing.", s->meta.id);
1089 static int service_add_default_dependencies(Service *s) {
1094 /* Add a number of automatic dependencies useful for the
1095 * majority of services. */
1097 /* First, pull in base system */
1098 if (s->meta.manager->running_as == MANAGER_SYSTEM) {
1100 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_BASIC_TARGET, NULL, true)) < 0)
1103 } else if (s->meta.manager->running_as == MANAGER_USER) {
1105 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SOCKETS_TARGET, NULL, true)) < 0)
1109 /* Second, activate normal shutdown */
1110 return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true);
1113 static int service_load(Unit *u) {
1115 Service *s = SERVICE(u);
1119 /* Load a .service file */
1120 if ((r = unit_load_fragment(u)) < 0)
1123 #ifdef HAVE_SYSV_COMPAT
1124 /* Load a classic init script as a fallback, if we couldn't find anything */
1125 if (u->meta.load_state == UNIT_STUB)
1126 if ((r = service_load_sysv(s)) < 0)
1130 /* Still nothing found? Then let's give up */
1131 if (u->meta.load_state == UNIT_STUB)
1134 /* We were able to load something, then let's add in the
1135 * dropin directories. */
1136 if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
1139 /* This is a new unit? Then let's add in some extras */
1140 if (u->meta.load_state == UNIT_LOADED) {
1141 if ((r = unit_add_exec_dependencies(u, &s->exec_context)) < 0)
1144 if ((r = unit_add_default_cgroups(u)) < 0)
1147 #ifdef HAVE_SYSV_COMPAT
1148 if ((r = sysv_fix_order(s)) < 0)
1152 if ((r = fsck_fix_order(s)) < 0)
1156 if ((r = unit_watch_bus_name(u, s->bus_name)) < 0)
1159 if (s->type == SERVICE_NOTIFY && s->notify_access == NOTIFY_NONE)
1160 s->notify_access = NOTIFY_MAIN;
1162 if (s->type == SERVICE_DBUS || s->bus_name)
1163 if ((r = unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_REQUIRES, SPECIAL_DBUS_SOCKET, NULL, true)) < 0)
1166 if (s->meta.default_dependencies)
1167 if ((r = service_add_default_dependencies(s)) < 0)
1171 return service_verify(s);
1174 static void service_dump(Unit *u, FILE *f, const char *prefix) {
1176 ServiceExecCommand c;
1177 Service *s = SERVICE(u);
1178 const char *prefix2;
1183 p2 = strappend(prefix, "\t");
1184 prefix2 = p2 ? p2 : prefix;
1187 "%sService State: %s\n"
1188 "%sPermissionsStartOnly: %s\n"
1189 "%sRootDirectoryStartOnly: %s\n"
1190 "%sRemainAfterExit: %s\n"
1191 "%sGuessMainPID: %s\n"
1194 "%sNotifyAccess: %s\n",
1195 prefix, service_state_to_string(s->state),
1196 prefix, yes_no(s->permissions_start_only),
1197 prefix, yes_no(s->root_directory_start_only),
1198 prefix, yes_no(s->remain_after_exit),
1199 prefix, yes_no(s->guess_main_pid),
1200 prefix, service_type_to_string(s->type),
1201 prefix, service_restart_to_string(s->restart),
1202 prefix, notify_access_to_string(s->notify_access));
1204 if (s->control_pid > 0)
1206 "%sControl PID: %lu\n",
1207 prefix, (unsigned long) s->control_pid);
1209 if (s->main_pid > 0)
1212 "%sMain PID Known: %s\n"
1213 "%sMain PID Alien: %s\n",
1214 prefix, (unsigned long) s->main_pid,
1215 prefix, yes_no(s->main_pid_known),
1216 prefix, yes_no(s->main_pid_alien));
1221 prefix, s->pid_file);
1226 "%sBus Name Good: %s\n",
1227 prefix, s->bus_name,
1228 prefix, yes_no(s->bus_name_good));
1230 exec_context_dump(&s->exec_context, f, prefix);
1232 for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
1234 if (!s->exec_command[c])
1237 fprintf(f, "%s-> %s:\n",
1238 prefix, service_exec_command_to_string(c));
1240 exec_command_dump_list(s->exec_command[c], f, prefix2);
1243 #ifdef HAVE_SYSV_COMPAT
1246 "%sSysV Init Script Path: %s\n"
1247 "%sSysV Init Script has LSB Header: %s\n"
1248 "%sSysVEnabled: %s\n",
1249 prefix, s->sysv_path,
1250 prefix, yes_no(s->sysv_has_lsb),
1251 prefix, yes_no(s->sysv_enabled));
1253 if (s->sysv_start_priority >= 0)
1255 "%sSysVStartPriority: %i\n",
1256 prefix, s->sysv_start_priority);
1258 if (s->sysv_runlevels)
1259 fprintf(f, "%sSysVRunLevels: %s\n",
1260 prefix, s->sysv_runlevels);
1263 if (s->fsck_passno > 0)
1265 "%sFsckPassNo: %i\n",
1266 prefix, s->fsck_passno);
1269 fprintf(f, "%sStatus Text: %s\n",
1270 prefix, s->status_text);
1275 static int service_load_pid_file(Service *s) {
1282 if (s->main_pid_known)
1288 if ((r = read_one_line_file(s->pid_file, &k)) < 0)
1291 r = parse_pid(k, &pid);
1297 if (kill(pid, 0) < 0 && errno != EPERM) {
1298 log_warning("PID %lu read from file %s does not exist. Your service or init script might be broken.",
1299 (unsigned long) pid, s->pid_file);
1303 if ((r = service_set_main_pid(s, pid)) < 0)
1306 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1307 /* FIXME: we need to do something here */
1313 static int service_search_main_pid(Service *s) {
1319 /* If we know it anyway, don't ever fallback to unreliable
1321 if (s->main_pid_known)
1324 if (!s->guess_main_pid)
1327 assert(s->main_pid <= 0);
1329 if ((pid = cgroup_bonding_search_main_pid_list(s->meta.cgroup_bondings)) <= 0)
1332 if ((r = service_set_main_pid(s, pid)) < 0)
1335 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1336 /* FIXME: we need to do something here */
1342 static int service_get_sockets(Service *s, Set **_set) {
1351 if (s->socket_fd >= 0)
1354 if (!set_isempty(s->configured_sockets))
1357 /* Collects all Socket objects that belong to this
1358 * service. Note that a service might have multiple sockets
1359 * via multiple names. */
1361 if (!(set = set_new(NULL, NULL)))
1364 SET_FOREACH(t, s->meta.names, i) {
1368 /* Look for all socket objects that go by any of our
1369 * units and collect their fds */
1371 if (!(k = unit_name_change_suffix(t, ".socket"))) {
1376 p = manager_get_unit(s->meta.manager, k);
1382 if ((r = set_put(set, p)) < 0)
1394 static int service_notify_sockets_dead(Service *s) {
1396 Set *set, *free_set = NULL;
1402 /* Notifies all our sockets when we die */
1404 if (s->socket_fd >= 0)
1407 if (!set_isempty(s->configured_sockets))
1408 set = s->configured_sockets;
1410 if ((r = service_get_sockets(s, &free_set)) < 0)
1416 SET_FOREACH(sock, set, i)
1417 socket_notify_service_dead(sock);
1424 static void service_set_state(Service *s, ServiceState state) {
1425 ServiceState old_state;
1428 old_state = s->state;
1431 if (state != SERVICE_START_PRE &&
1432 state != SERVICE_START &&
1433 state != SERVICE_START_POST &&
1434 state != SERVICE_RELOAD &&
1435 state != SERVICE_STOP &&
1436 state != SERVICE_STOP_SIGTERM &&
1437 state != SERVICE_STOP_SIGKILL &&
1438 state != SERVICE_STOP_POST &&
1439 state != SERVICE_FINAL_SIGTERM &&
1440 state != SERVICE_FINAL_SIGKILL &&
1441 state != SERVICE_AUTO_RESTART)
1442 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1444 if (state != SERVICE_START &&
1445 state != SERVICE_START_POST &&
1446 state != SERVICE_RUNNING &&
1447 state != SERVICE_RELOAD &&
1448 state != SERVICE_STOP &&
1449 state != SERVICE_STOP_SIGTERM &&
1450 state != SERVICE_STOP_SIGKILL) {
1451 service_unwatch_main_pid(s);
1452 s->main_command = NULL;
1455 if (state != SERVICE_START_PRE &&
1456 state != SERVICE_START &&
1457 state != SERVICE_START_POST &&
1458 state != SERVICE_RELOAD &&
1459 state != SERVICE_STOP &&
1460 state != SERVICE_STOP_SIGTERM &&
1461 state != SERVICE_STOP_SIGKILL &&
1462 state != SERVICE_STOP_POST &&
1463 state != SERVICE_FINAL_SIGTERM &&
1464 state != SERVICE_FINAL_SIGKILL) {
1465 service_unwatch_control_pid(s);
1466 s->control_command = NULL;
1467 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1470 if (state == SERVICE_DEAD ||
1471 state == SERVICE_STOP ||
1472 state == SERVICE_STOP_SIGTERM ||
1473 state == SERVICE_STOP_SIGKILL ||
1474 state == SERVICE_STOP_POST ||
1475 state == SERVICE_FINAL_SIGTERM ||
1476 state == SERVICE_FINAL_SIGKILL ||
1477 state == SERVICE_FAILED ||
1478 state == SERVICE_AUTO_RESTART)
1479 service_notify_sockets_dead(s);
1481 if (state != SERVICE_START_PRE &&
1482 state != SERVICE_START &&
1483 state != SERVICE_START_POST &&
1484 state != SERVICE_RUNNING &&
1485 state != SERVICE_RELOAD &&
1486 state != SERVICE_STOP &&
1487 state != SERVICE_STOP_SIGTERM &&
1488 state != SERVICE_STOP_SIGKILL &&
1489 state != SERVICE_STOP_POST &&
1490 state != SERVICE_FINAL_SIGTERM &&
1491 state != SERVICE_FINAL_SIGKILL &&
1492 !(state == SERVICE_DEAD && s->meta.job)) {
1493 service_close_socket_fd(s);
1494 service_connection_unref(s);
1497 /* For the inactive states unit_notify() will trim the cgroup,
1498 * but for exit we have to do that ourselves... */
1499 if (state == SERVICE_EXITED && s->meta.manager->n_reloading <= 0)
1500 cgroup_bonding_trim_list(s->meta.cgroup_bondings, true);
1502 if (old_state != state)
1503 log_debug("%s changed %s -> %s", s->meta.id, service_state_to_string(old_state), service_state_to_string(state));
1505 unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state], !s->reload_failure);
1506 s->reload_failure = false;
1509 static int service_coldplug(Unit *u) {
1510 Service *s = SERVICE(u);
1514 assert(s->state == SERVICE_DEAD);
1516 if (s->deserialized_state != s->state) {
1518 if (s->deserialized_state == SERVICE_START_PRE ||
1519 s->deserialized_state == SERVICE_START ||
1520 s->deserialized_state == SERVICE_START_POST ||
1521 s->deserialized_state == SERVICE_RELOAD ||
1522 s->deserialized_state == SERVICE_STOP ||
1523 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1524 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1525 s->deserialized_state == SERVICE_STOP_POST ||
1526 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1527 s->deserialized_state == SERVICE_FINAL_SIGKILL ||
1528 s->deserialized_state == SERVICE_AUTO_RESTART) {
1530 if (s->deserialized_state == SERVICE_AUTO_RESTART || s->timeout_usec > 0) {
1533 k = s->deserialized_state == SERVICE_AUTO_RESTART ? s->restart_usec : s->timeout_usec;
1535 if ((r = unit_watch_timer(UNIT(s), k, &s->timer_watch)) < 0)
1540 if ((s->deserialized_state == SERVICE_START &&
1541 (s->type == SERVICE_FORKING ||
1542 s->type == SERVICE_DBUS ||
1543 s->type == SERVICE_ONESHOT ||
1544 s->type == SERVICE_NOTIFY)) ||
1545 s->deserialized_state == SERVICE_START_POST ||
1546 s->deserialized_state == SERVICE_RUNNING ||
1547 s->deserialized_state == SERVICE_RELOAD ||
1548 s->deserialized_state == SERVICE_STOP ||
1549 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1550 s->deserialized_state == SERVICE_STOP_SIGKILL)
1551 if (s->main_pid > 0)
1552 if ((r = unit_watch_pid(UNIT(s), s->main_pid)) < 0)
1555 if (s->deserialized_state == SERVICE_START_PRE ||
1556 s->deserialized_state == SERVICE_START ||
1557 s->deserialized_state == SERVICE_START_POST ||
1558 s->deserialized_state == SERVICE_RELOAD ||
1559 s->deserialized_state == SERVICE_STOP ||
1560 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1561 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1562 s->deserialized_state == SERVICE_STOP_POST ||
1563 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1564 s->deserialized_state == SERVICE_FINAL_SIGKILL)
1565 if (s->control_pid > 0)
1566 if ((r = unit_watch_pid(UNIT(s), s->control_pid)) < 0)
1569 service_set_state(s, s->deserialized_state);
1575 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
1579 unsigned rn_fds = 0;
1580 Set *set, *free_set = NULL;
1587 if (s->socket_fd >= 0)
1590 if (!set_isempty(s->configured_sockets))
1591 set = s->configured_sockets;
1593 if ((r = service_get_sockets(s, &free_set)) < 0)
1599 SET_FOREACH(sock, set, i) {
1603 if ((r = socket_collect_fds(sock, &cfds, &cn_fds)) < 0)
1615 if (!(t = new(int, rn_fds+cn_fds))) {
1621 memcpy(t, rfds, rn_fds * sizeof(int));
1622 memcpy(t+rn_fds, cfds, cn_fds * sizeof(int));
1627 rn_fds = rn_fds+cn_fds;
1645 static int service_spawn(
1650 bool apply_permissions,
1652 bool apply_tty_stdin,
1653 bool set_notify_socket,
1658 int *fds = NULL, *fdsbuf = NULL;
1659 unsigned n_fds = 0, n_env = 0;
1660 char **argv = NULL, **final_env = NULL, **our_env = NULL;
1667 s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1668 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1669 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
1671 if (s->socket_fd >= 0) {
1672 fds = &s->socket_fd;
1675 if ((r = service_collect_fds(s, &fdsbuf, &n_fds)) < 0)
1682 if (timeout && s->timeout_usec) {
1683 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1686 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1688 if (!(argv = unit_full_printf_strv(UNIT(s), c->argv))) {
1693 if (!(our_env = new0(char*, 4))) {
1698 if (set_notify_socket)
1699 if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=%s", s->meta.manager->notify_socket) < 0) {
1704 if (s->main_pid > 0)
1705 if (asprintf(our_env + n_env++, "MAINPID=%lu", (unsigned long) s->main_pid) < 0) {
1710 if (!(final_env = strv_env_merge(2,
1711 s->meta.manager->environment,
1726 s->meta.manager->confirm_spawn,
1727 s->meta.cgroup_bondings,
1734 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1735 /* FIXME: we need to do something here */
1741 strv_free(final_env);
1751 strv_free(final_env);
1754 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1759 static int main_pid_good(Service *s) {
1762 /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1765 /* If we know the pid file, then lets just check if it is
1767 if (s->main_pid_known) {
1769 /* If it's an alien child let's check if it is still
1771 if (s->main_pid_alien)
1772 return kill(s->main_pid, 0) >= 0 || errno != ESRCH;
1774 /* .. otherwise assume we'll get a SIGCHLD for it,
1775 * which we really should wait for to collect exit
1776 * status and code */
1777 return s->main_pid > 0;
1780 /* We don't know the pid */
1784 static int control_pid_good(Service *s) {
1787 return s->control_pid > 0;
1790 static int cgroup_good(Service *s) {
1795 if ((r = cgroup_bonding_is_empty_list(s->meta.cgroup_bondings)) < 0)
1801 static void service_enter_dead(Service *s, bool success, bool allow_restart) {
1808 if (allow_restart &&
1809 !s->forbid_restart &&
1810 (s->restart == SERVICE_RESTART_ALWAYS ||
1811 (s->restart == SERVICE_RESTART_ON_SUCCESS && !s->failure) ||
1812 (s->restart == SERVICE_RESTART_ON_FAILURE && s->failure) ||
1813 (s->restart == SERVICE_RESTART_ON_ABORT && s->failure &&
1814 (s->main_exec_status.code == CLD_KILLED ||
1815 s->main_exec_status.code == CLD_DUMPED)))) {
1817 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
1820 service_set_state(s, SERVICE_AUTO_RESTART);
1822 service_set_state(s, s->failure ? SERVICE_FAILED : SERVICE_DEAD);
1824 s->forbid_restart = false;
1829 log_warning("%s failed to run install restart timer: %s", s->meta.id, strerror(-r));
1830 service_enter_dead(s, false, false);
1833 static void service_enter_signal(Service *s, ServiceState state, bool success);
1835 static void service_enter_stop_post(Service *s, bool success) {
1842 service_unwatch_control_pid(s);
1844 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST])) {
1845 s->control_command_id = SERVICE_EXEC_STOP_POST;
1847 if ((r = service_spawn(s,
1851 !s->permissions_start_only,
1852 !s->root_directory_start_only,
1855 &s->control_pid)) < 0)
1859 service_set_state(s, SERVICE_STOP_POST);
1861 service_enter_signal(s, SERVICE_FINAL_SIGTERM, true);
1866 log_warning("%s failed to run 'stop-post' task: %s", s->meta.id, strerror(-r));
1867 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1870 static void service_enter_signal(Service *s, ServiceState state, bool success) {
1872 Set *pid_set = NULL;
1873 bool wait_for_exit = false;
1880 if (s->exec_context.kill_mode != KILL_NONE) {
1881 int sig = (state == SERVICE_STOP_SIGTERM || state == SERVICE_FINAL_SIGTERM) ? s->exec_context.kill_signal : SIGKILL;
1883 if (s->main_pid > 0) {
1884 if (kill_and_sigcont(s->main_pid, sig) < 0 && errno != ESRCH)
1885 log_warning("Failed to kill main process %li: %m", (long) s->main_pid);
1887 wait_for_exit = !s->main_pid_alien;
1890 if (s->control_pid > 0) {
1891 if (kill_and_sigcont(s->control_pid, sig) < 0 && errno != ESRCH)
1892 log_warning("Failed to kill control process %li: %m", (long) s->control_pid);
1894 wait_for_exit = true;
1897 if (s->exec_context.kill_mode == KILL_CONTROL_GROUP) {
1899 if (!(pid_set = set_new(trivial_hash_func, trivial_compare_func))) {
1904 /* Exclude the main/control pids from being killed via the cgroup */
1905 if (s->main_pid > 0)
1906 if ((r = set_put(pid_set, LONG_TO_PTR(s->main_pid))) < 0)
1909 if (s->control_pid > 0)
1910 if ((r = set_put(pid_set, LONG_TO_PTR(s->control_pid))) < 0)
1913 if ((r = cgroup_bonding_kill_list(s->meta.cgroup_bondings, sig, true, pid_set)) < 0) {
1914 if (r != -EAGAIN && r != -ESRCH && r != -ENOENT)
1915 log_warning("Failed to kill control group: %s", strerror(-r));
1917 wait_for_exit = true;
1924 if (wait_for_exit) {
1925 if (s->timeout_usec > 0)
1926 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1929 service_set_state(s, state);
1930 } else if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1931 service_enter_stop_post(s, true);
1933 service_enter_dead(s, true, true);
1938 log_warning("%s failed to kill processes: %s", s->meta.id, strerror(-r));
1940 if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1941 service_enter_stop_post(s, false);
1943 service_enter_dead(s, false, true);
1949 static void service_enter_stop(Service *s, bool success) {
1957 service_unwatch_control_pid(s);
1959 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP])) {
1960 s->control_command_id = SERVICE_EXEC_STOP;
1962 if ((r = service_spawn(s,
1966 !s->permissions_start_only,
1967 !s->root_directory_start_only,
1970 &s->control_pid)) < 0)
1973 service_set_state(s, SERVICE_STOP);
1975 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
1980 log_warning("%s failed to run 'stop' task: %s", s->meta.id, strerror(-r));
1981 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1984 static void service_enter_running(Service *s, bool success) {
1985 int main_pid_ok, cgroup_ok;
1991 main_pid_ok = main_pid_good(s);
1992 cgroup_ok = cgroup_good(s);
1994 if ((main_pid_ok > 0 || (main_pid_ok < 0 && cgroup_ok != 0)) &&
1995 (s->bus_name_good || s->type != SERVICE_DBUS))
1996 service_set_state(s, SERVICE_RUNNING);
1997 else if (s->remain_after_exit)
1998 service_set_state(s, SERVICE_EXITED);
2000 service_enter_stop(s, true);
2003 static void service_enter_start_post(Service *s) {
2007 service_unwatch_control_pid(s);
2009 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_POST])) {
2010 s->control_command_id = SERVICE_EXEC_START_POST;
2012 if ((r = service_spawn(s,
2016 !s->permissions_start_only,
2017 !s->root_directory_start_only,
2020 &s->control_pid)) < 0)
2023 service_set_state(s, SERVICE_START_POST);
2025 service_enter_running(s, true);
2030 log_warning("%s failed to run 'start-post' task: %s", s->meta.id, strerror(-r));
2031 service_enter_stop(s, false);
2034 static void service_enter_start(Service *s) {
2041 assert(s->exec_command[SERVICE_EXEC_START]);
2042 assert(!s->exec_command[SERVICE_EXEC_START]->command_next || s->type == SERVICE_ONESHOT);
2044 if (s->type == SERVICE_FORKING)
2045 service_unwatch_control_pid(s);
2047 service_unwatch_main_pid(s);
2049 if (s->type == SERVICE_FORKING) {
2050 s->control_command_id = SERVICE_EXEC_START;
2051 c = s->control_command = s->exec_command[SERVICE_EXEC_START];
2053 s->main_command = NULL;
2055 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2056 s->control_command = NULL;
2058 c = s->main_command = s->exec_command[SERVICE_EXEC_START];
2061 if ((r = service_spawn(s,
2063 s->type == SERVICE_FORKING || s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY,
2068 s->notify_access != NOTIFY_NONE,
2072 if (s->type == SERVICE_SIMPLE) {
2073 /* For simple services we immediately start
2074 * the START_POST binaries. */
2076 service_set_main_pid(s, pid);
2077 service_enter_start_post(s);
2079 } else if (s->type == SERVICE_FORKING) {
2081 /* For forking services we wait until the start
2082 * process exited. */
2084 s->control_pid = pid;
2085 service_set_state(s, SERVICE_START);
2087 } else if (s->type == SERVICE_ONESHOT ||
2088 s->type == SERVICE_DBUS ||
2089 s->type == SERVICE_NOTIFY) {
2091 /* For oneshot services we wait until the start
2092 * process exited, too, but it is our main process. */
2094 /* For D-Bus services we know the main pid right away,
2095 * but wait for the bus name to appear on the
2096 * bus. Notify services are similar. */
2098 service_set_main_pid(s, pid);
2099 service_set_state(s, SERVICE_START);
2101 assert_not_reached("Unknown service type");
2106 log_warning("%s failed to run 'start' task: %s", s->meta.id, strerror(-r));
2107 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2110 static void service_enter_start_pre(Service *s) {
2115 service_unwatch_control_pid(s);
2117 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_PRE])) {
2118 s->control_command_id = SERVICE_EXEC_START_PRE;
2120 if ((r = service_spawn(s,
2124 !s->permissions_start_only,
2125 !s->root_directory_start_only,
2128 &s->control_pid)) < 0)
2131 service_set_state(s, SERVICE_START_PRE);
2133 service_enter_start(s);
2138 log_warning("%s failed to run 'start-pre' task: %s", s->meta.id, strerror(-r));
2139 service_enter_dead(s, false, true);
2142 static void service_enter_restart(Service *s) {
2147 dbus_error_init(&error);
2150 log_info("Job pending for unit, delaying automatic restart.");
2152 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
2156 service_enter_dead(s, true, false);
2158 if ((r = manager_add_job(s->meta.manager, JOB_START, UNIT(s), JOB_FAIL, false, &error, NULL)) < 0)
2161 log_debug("%s scheduled restart job.", s->meta.id);
2165 log_warning("%s failed to schedule restart job: %s", s->meta.id, bus_error(&error, -r));
2166 service_enter_dead(s, false, false);
2168 dbus_error_free(&error);
2171 static void service_enter_reload(Service *s) {
2176 service_unwatch_control_pid(s);
2178 if ((s->control_command = s->exec_command[SERVICE_EXEC_RELOAD])) {
2179 s->control_command_id = SERVICE_EXEC_RELOAD;
2181 if ((r = service_spawn(s,
2185 !s->permissions_start_only,
2186 !s->root_directory_start_only,
2189 &s->control_pid)) < 0)
2192 service_set_state(s, SERVICE_RELOAD);
2194 service_enter_running(s, true);
2199 log_warning("%s failed to run 'reload' task: %s", s->meta.id, strerror(-r));
2200 s->reload_failure = true;
2201 service_enter_running(s, true);
2204 static void service_run_next_control(Service *s, bool success) {
2208 assert(s->control_command);
2209 assert(s->control_command->command_next);
2214 assert(s->control_command_id != SERVICE_EXEC_START);
2216 s->control_command = s->control_command->command_next;
2217 service_unwatch_control_pid(s);
2219 if ((r = service_spawn(s,
2223 !s->permissions_start_only,
2224 !s->root_directory_start_only,
2225 s->control_command_id == SERVICE_EXEC_START_PRE ||
2226 s->control_command_id == SERVICE_EXEC_STOP_POST,
2228 &s->control_pid)) < 0)
2234 log_warning("%s failed to run next control task: %s", s->meta.id, strerror(-r));
2236 if (s->state == SERVICE_START_PRE)
2237 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2238 else if (s->state == SERVICE_STOP)
2239 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
2240 else if (s->state == SERVICE_STOP_POST)
2241 service_enter_dead(s, false, true);
2242 else if (s->state == SERVICE_RELOAD) {
2243 s->reload_failure = true;
2244 service_enter_running(s, true);
2246 service_enter_stop(s, false);
2249 static void service_run_next_main(Service *s, bool success) {
2254 assert(s->main_command);
2255 assert(s->main_command->command_next);
2256 assert(s->type == SERVICE_ONESHOT);
2261 s->main_command = s->main_command->command_next;
2262 service_unwatch_main_pid(s);
2264 if ((r = service_spawn(s,
2271 s->notify_access != NOTIFY_NONE,
2275 service_set_main_pid(s, pid);
2280 log_warning("%s failed to run next main task: %s", s->meta.id, strerror(-r));
2281 service_enter_stop(s, false);
2284 static int service_start(Unit *u) {
2285 Service *s = SERVICE(u);
2289 /* We cannot fulfill this request right now, try again later
2291 if (s->state == SERVICE_STOP ||
2292 s->state == SERVICE_STOP_SIGTERM ||
2293 s->state == SERVICE_STOP_SIGKILL ||
2294 s->state == SERVICE_STOP_POST ||
2295 s->state == SERVICE_FINAL_SIGTERM ||
2296 s->state == SERVICE_FINAL_SIGKILL)
2299 /* Already on it! */
2300 if (s->state == SERVICE_START_PRE ||
2301 s->state == SERVICE_START ||
2302 s->state == SERVICE_START_POST)
2305 assert(s->state == SERVICE_DEAD || s->state == SERVICE_FAILED || s->state == SERVICE_AUTO_RESTART);
2307 /* Make sure we don't enter a busy loop of some kind. */
2308 if (!ratelimit_test(&s->ratelimit)) {
2309 log_warning("%s start request repeated too quickly, refusing to start.", u->meta.id);
2314 s->main_pid_known = false;
2315 s->main_pid_alien = false;
2316 s->forbid_restart = false;
2318 service_enter_start_pre(s);
2322 static int service_stop(Unit *u) {
2323 Service *s = SERVICE(u);
2327 /* This is a user request, so don't do restarts on this
2329 s->forbid_restart = true;
2332 if (s->state == SERVICE_STOP ||
2333 s->state == SERVICE_STOP_SIGTERM ||
2334 s->state == SERVICE_STOP_SIGKILL ||
2335 s->state == SERVICE_STOP_POST ||
2336 s->state == SERVICE_FINAL_SIGTERM ||
2337 s->state == SERVICE_FINAL_SIGKILL)
2340 /* Don't allow a restart */
2341 if (s->state == SERVICE_AUTO_RESTART) {
2342 service_set_state(s, SERVICE_DEAD);
2346 /* If there's already something running we go directly into
2348 if (s->state == SERVICE_START_PRE ||
2349 s->state == SERVICE_START ||
2350 s->state == SERVICE_START_POST ||
2351 s->state == SERVICE_RELOAD) {
2352 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
2356 assert(s->state == SERVICE_RUNNING ||
2357 s->state == SERVICE_EXITED);
2359 service_enter_stop(s, true);
2363 static int service_reload(Unit *u) {
2364 Service *s = SERVICE(u);
2368 assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
2370 service_enter_reload(s);
2374 static bool service_can_reload(Unit *u) {
2375 Service *s = SERVICE(u);
2379 return !!s->exec_command[SERVICE_EXEC_RELOAD];
2382 static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
2383 Service *s = SERVICE(u);
2389 unit_serialize_item(u, f, "state", service_state_to_string(s->state));
2390 unit_serialize_item(u, f, "failure", yes_no(s->failure));
2392 if (s->control_pid > 0)
2393 unit_serialize_item_format(u, f, "control-pid", "%lu", (unsigned long) s->control_pid);
2395 if (s->main_pid_known && s->main_pid > 0)
2396 unit_serialize_item_format(u, f, "main-pid", "%lu", (unsigned long) s->main_pid);
2398 unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
2401 unit_serialize_item(u, f, "status-text", s->status_text);
2403 /* There's a minor uncleanliness here: if there are multiple
2404 * commands attached here, we will start from the first one
2406 if (s->control_command_id >= 0)
2407 unit_serialize_item(u, f, "control-command", service_exec_command_to_string(s->control_command_id));
2409 if (s->socket_fd >= 0) {
2412 if ((copy = fdset_put_dup(fds, s->socket_fd)) < 0)
2415 unit_serialize_item_format(u, f, "socket-fd", "%i", copy);
2418 if (s->main_exec_status.pid > 0) {
2419 unit_serialize_item_format(u, f, "main-exec-status-pid", "%lu", (unsigned long) s->main_exec_status.pid);
2420 dual_timestamp_serialize(f, "main-exec-status-start", &s->main_exec_status.start_timestamp);
2421 dual_timestamp_serialize(f, "main-exec-status-exit", &s->main_exec_status.exit_timestamp);
2423 if (dual_timestamp_is_set(&s->main_exec_status.exit_timestamp)) {
2424 unit_serialize_item_format(u, f, "main-exec-status-code", "%i", s->main_exec_status.code);
2425 unit_serialize_item_format(u, f, "main-exec-status-status", "%i", s->main_exec_status.status);
2432 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
2433 Service *s = SERVICE(u);
2440 if (streq(key, "state")) {
2443 if ((state = service_state_from_string(value)) < 0)
2444 log_debug("Failed to parse state value %s", value);
2446 s->deserialized_state = state;
2447 } else if (streq(key, "failure")) {
2450 if ((b = parse_boolean(value)) < 0)
2451 log_debug("Failed to parse failure value %s", value);
2453 s->failure = b || s->failure;
2454 } else if (streq(key, "control-pid")) {
2457 if (parse_pid(value, &pid) < 0)
2458 log_debug("Failed to parse control-pid value %s", value);
2460 s->control_pid = pid;
2461 } else if (streq(key, "main-pid")) {
2464 if (parse_pid(value, &pid) < 0)
2465 log_debug("Failed to parse main-pid value %s", value);
2467 service_set_main_pid(s, (pid_t) pid);
2468 } else if (streq(key, "main-pid-known")) {
2471 if ((b = parse_boolean(value)) < 0)
2472 log_debug("Failed to parse main-pid-known value %s", value);
2474 s->main_pid_known = b;
2475 } else if (streq(key, "status-text")) {
2478 if ((t = strdup(value))) {
2479 free(s->status_text);
2483 } else if (streq(key, "control-command")) {
2484 ServiceExecCommand id;
2486 if ((id = service_exec_command_from_string(value)) < 0)
2487 log_debug("Failed to parse exec-command value %s", value);
2489 s->control_command_id = id;
2490 s->control_command = s->exec_command[id];
2492 } else if (streq(key, "socket-fd")) {
2495 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2496 log_debug("Failed to parse socket-fd value %s", value);
2499 if (s->socket_fd >= 0)
2500 close_nointr_nofail(s->socket_fd);
2501 s->socket_fd = fdset_remove(fds, fd);
2503 } else if (streq(key, "main-exec-status-pid")) {
2506 if (parse_pid(value, &pid) < 0)
2507 log_debug("Failed to parse main-exec-status-pid value %s", value);
2509 s->main_exec_status.pid = pid;
2510 } else if (streq(key, "main-exec-status-code")) {
2513 if (safe_atoi(value, &i) < 0)
2514 log_debug("Failed to parse main-exec-status-code value %s", value);
2516 s->main_exec_status.code = i;
2517 } else if (streq(key, "main-exec-status-status")) {
2520 if (safe_atoi(value, &i) < 0)
2521 log_debug("Failed to parse main-exec-status-status value %s", value);
2523 s->main_exec_status.status = i;
2524 } else if (streq(key, "main-exec-status-start"))
2525 dual_timestamp_deserialize(value, &s->main_exec_status.start_timestamp);
2526 else if (streq(key, "main-exec-status-exit"))
2527 dual_timestamp_deserialize(value, &s->main_exec_status.exit_timestamp);
2529 log_debug("Unknown serialization key '%s'", key);
2534 static UnitActiveState service_active_state(Unit *u) {
2537 return state_translation_table[SERVICE(u)->state];
2540 static const char *service_sub_state_to_string(Unit *u) {
2543 return service_state_to_string(SERVICE(u)->state);
2546 static bool service_check_gc(Unit *u) {
2547 Service *s = SERVICE(u);
2551 /* Never clean up services that still have a process around,
2552 * even if the service is formally dead. */
2553 if (cgroup_good(s) > 0 ||
2554 main_pid_good(s) > 0 ||
2555 control_pid_good(s) > 0)
2558 #ifdef HAVE_SYSV_COMPAT
2566 static bool service_check_snapshot(Unit *u) {
2567 Service *s = SERVICE(u);
2571 return !s->got_socket_fd;
2574 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2575 Service *s = SERVICE(u);
2581 if (!s->meta.fragment_path)
2582 success = is_clean_exit_lsb(code, status);
2584 success = is_clean_exit(code, status);
2586 if (s->main_pid == pid) {
2589 exec_status_exit(&s->main_exec_status, &s->exec_context, pid, code, status);
2591 /* If this is not a forking service than the main
2592 * process got started and hence we copy the exit
2593 * status so that it is recorded both as main and as
2594 * control process exit status */
2595 if (s->main_command) {
2596 s->main_command->exec_status = s->main_exec_status;
2598 if (s->main_command->ignore)
2602 log_full(success ? LOG_DEBUG : LOG_NOTICE,
2603 "%s: main process exited, code=%s, status=%i", u->meta.id, sigchld_code_to_string(code), status);
2604 s->failure = s->failure || !success;
2606 if (s->main_command &&
2607 s->main_command->command_next &&
2610 /* There is another command to *
2611 * execute, so let's do that. */
2613 log_debug("%s running next main command for state %s", u->meta.id, service_state_to_string(s->state));
2614 service_run_next_main(s, success);
2618 /* The service exited, so the service is officially
2620 s->main_command = NULL;
2624 case SERVICE_START_POST:
2625 case SERVICE_RELOAD:
2627 /* Need to wait until the operation is
2632 if (s->type == SERVICE_ONESHOT) {
2633 /* This was our main goal, so let's go on */
2635 service_enter_start_post(s);
2637 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2640 assert(s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY);
2645 case SERVICE_RUNNING:
2646 service_enter_running(s, success);
2649 case SERVICE_STOP_SIGTERM:
2650 case SERVICE_STOP_SIGKILL:
2652 if (!control_pid_good(s))
2653 service_enter_stop_post(s, success);
2655 /* If there is still a control process, wait for that first */
2659 assert_not_reached("Uh, main process died at wrong time.");
2663 } else if (s->control_pid == pid) {
2667 if (s->control_command) {
2668 exec_status_exit(&s->control_command->exec_status, &s->exec_context, pid, code, status);
2670 if (s->control_command->ignore)
2674 log_full(success ? LOG_DEBUG : LOG_NOTICE,
2675 "%s: control process exited, code=%s status=%i", u->meta.id, sigchld_code_to_string(code), status);
2676 s->failure = s->failure || !success;
2678 if (s->control_command &&
2679 s->control_command->command_next &&
2682 /* There is another command to *
2683 * execute, so let's do that. */
2685 log_debug("%s running next control command for state %s", u->meta.id, service_state_to_string(s->state));
2686 service_run_next_control(s, success);
2689 /* No further commands for this step, so let's
2690 * figure out what to do next */
2692 s->control_command = NULL;
2693 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2695 log_debug("%s got final SIGCHLD for state %s", u->meta.id, service_state_to_string(s->state));
2699 case SERVICE_START_PRE:
2701 service_enter_start(s);
2703 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2707 assert(s->type == SERVICE_FORKING);
2709 /* Let's try to load the pid
2710 * file here if we can. We
2711 * ignore the return value,
2712 * since the PID file might
2713 * actually be created by a
2714 * START_POST script */
2717 service_load_pid_file(s);
2718 service_search_main_pid(s);
2720 service_enter_start_post(s);
2722 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2726 case SERVICE_START_POST:
2728 service_load_pid_file(s);
2729 service_search_main_pid(s);
2732 s->reload_failure = !success;
2733 service_enter_running(s, true);
2736 case SERVICE_RELOAD:
2738 service_load_pid_file(s);
2739 service_search_main_pid(s);
2742 s->reload_failure = !success;
2743 service_enter_running(s, true);
2747 service_enter_signal(s, SERVICE_STOP_SIGTERM, success);
2750 case SERVICE_STOP_SIGTERM:
2751 case SERVICE_STOP_SIGKILL:
2752 if (main_pid_good(s) <= 0)
2753 service_enter_stop_post(s, success);
2755 /* If there is still a service
2756 * process around, wait until
2757 * that one quit, too */
2760 case SERVICE_STOP_POST:
2761 case SERVICE_FINAL_SIGTERM:
2762 case SERVICE_FINAL_SIGKILL:
2763 service_enter_dead(s, success, true);
2767 assert_not_reached("Uh, control process died at wrong time.");
2772 /* Notify clients about changed exit status */
2773 unit_add_to_dbus_queue(u);
2776 static void service_timer_event(Unit *u, uint64_t elapsed, Watch* w) {
2777 Service *s = SERVICE(u);
2780 assert(elapsed == 1);
2782 assert(w == &s->timer_watch);
2786 case SERVICE_START_PRE:
2788 log_warning("%s operation timed out. Terminating.", u->meta.id);
2789 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2792 case SERVICE_START_POST:
2793 log_warning("%s operation timed out. Stopping.", u->meta.id);
2794 service_enter_stop(s, false);
2797 case SERVICE_RELOAD:
2798 log_warning("%s operation timed out. Stopping.", u->meta.id);
2799 s->reload_failure = true;
2800 service_enter_running(s, true);
2804 log_warning("%s stopping timed out. Terminating.", u->meta.id);
2805 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
2808 case SERVICE_STOP_SIGTERM:
2809 if (s->exec_context.send_sigkill) {
2810 log_warning("%s stopping timed out. Killing.", u->meta.id);
2811 service_enter_signal(s, SERVICE_STOP_SIGKILL, false);
2813 log_warning("%s stopping timed out. Skipping SIGKILL.", u->meta.id);
2814 service_enter_stop_post(s, false);
2819 case SERVICE_STOP_SIGKILL:
2820 /* Uh, we sent a SIGKILL and it is still not gone?
2821 * Must be something we cannot kill, so let's just be
2822 * weirded out and continue */
2824 log_warning("%s still around after SIGKILL. Ignoring.", u->meta.id);
2825 service_enter_stop_post(s, false);
2828 case SERVICE_STOP_POST:
2829 log_warning("%s stopping timed out (2). Terminating.", u->meta.id);
2830 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2833 case SERVICE_FINAL_SIGTERM:
2834 if (s->exec_context.send_sigkill) {
2835 log_warning("%s stopping timed out (2). Killing.", u->meta.id);
2836 service_enter_signal(s, SERVICE_FINAL_SIGKILL, false);
2838 log_warning("%s stopping timed out (2). Skipping SIGKILL. Entering failed mode.", u->meta.id);
2839 service_enter_dead(s, false, true);
2844 case SERVICE_FINAL_SIGKILL:
2845 log_warning("%s still around after SIGKILL (2). Entering failed mode.", u->meta.id);
2846 service_enter_dead(s, false, true);
2849 case SERVICE_AUTO_RESTART:
2850 log_info("%s holdoff time over, scheduling restart.", u->meta.id);
2851 service_enter_restart(s);
2855 assert_not_reached("Timeout at wrong time.");
2859 static void service_cgroup_notify_event(Unit *u) {
2860 Service *s = SERVICE(u);
2864 log_debug("%s: cgroup is empty", u->meta.id);
2868 /* Waiting for SIGCHLD is usually more interesting,
2869 * because it includes return codes/signals. Which is
2870 * why we ignore the cgroup events for most cases,
2871 * except when we don't know pid which to expect the
2874 case SERVICE_RUNNING:
2875 service_enter_running(s, true);
2878 case SERVICE_STOP_SIGTERM:
2879 case SERVICE_STOP_SIGKILL:
2881 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2882 service_enter_stop_post(s, true);
2886 case SERVICE_FINAL_SIGTERM:
2887 case SERVICE_FINAL_SIGKILL:
2888 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2889 service_enter_dead(s, true, true);
2898 static void service_notify_message(Unit *u, pid_t pid, char **tags) {
2899 Service *s = SERVICE(u);
2904 if (s->notify_access == NOTIFY_NONE) {
2905 log_warning("%s: Got notification message from PID %lu, but reception is disabled.",
2906 u->meta.id, (unsigned long) pid);
2910 if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
2911 log_warning("%s: Got notification message from PID %lu, but reception only permitted for PID %lu",
2912 u->meta.id, (unsigned long) pid, (unsigned long) s->main_pid);
2916 log_debug("%s: Got message", u->meta.id);
2918 /* Interpret MAINPID= */
2919 if ((e = strv_find_prefix(tags, "MAINPID=")) &&
2920 (s->state == SERVICE_START ||
2921 s->state == SERVICE_START_POST ||
2922 s->state == SERVICE_RUNNING ||
2923 s->state == SERVICE_RELOAD)) {
2925 if (parse_pid(e + 8, &pid) < 0)
2926 log_warning("Failed to parse notification message %s", e);
2928 log_debug("%s: got %s", u->meta.id, e);
2929 service_set_main_pid(s, pid);
2933 /* Interpret READY= */
2934 if (s->type == SERVICE_NOTIFY &&
2935 s->state == SERVICE_START &&
2936 strv_find(tags, "READY=1")) {
2937 log_debug("%s: got READY=1", u->meta.id);
2939 service_enter_start_post(s);
2942 /* Interpret STATUS= */
2943 if ((e = strv_find_prefix(tags, "STATUS="))) {
2947 if (!(t = strdup(e+7))) {
2948 log_error("Failed to allocate string.");
2952 log_debug("%s: got %s", u->meta.id, e);
2954 free(s->status_text);
2957 free(s->status_text);
2958 s->status_text = NULL;
2963 /* Notify clients about changed status or main pid */
2964 unit_add_to_dbus_queue(u);
2967 #ifdef HAVE_SYSV_COMPAT
2968 static int service_enumerate(Manager *m) {
2972 char *path = NULL, *fpath = NULL, *name = NULL;
2973 Set *runlevel_services[ELEMENTSOF(rcnd_table)], *shutdown_services = NULL;
2980 if (m->running_as != MANAGER_SYSTEM)
2983 zero(runlevel_services);
2985 STRV_FOREACH(p, m->lookup_paths.sysvrcnd_path)
2986 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++) {
2991 if (asprintf(&path, "%s/%s", *p, rcnd_table[i].path) < 0) {
2999 if (!(d = opendir(path))) {
3000 if (errno != ENOENT)
3001 log_warning("opendir() failed on %s: %s", path, strerror(errno));
3006 while ((de = readdir(d))) {
3009 if (ignore_file(de->d_name))
3012 if (de->d_name[0] != 'S' && de->d_name[0] != 'K')
3015 if (strlen(de->d_name) < 4)
3018 a = undecchar(de->d_name[1]);
3019 b = undecchar(de->d_name[2]);
3026 if (asprintf(&fpath, "%s/%s/%s", *p, rcnd_table[i].path, de->d_name) < 0) {
3031 if (access(fpath, X_OK) < 0) {
3033 if (errno != ENOENT)
3034 log_warning("access() failed on %s: %s", fpath, strerror(errno));
3040 if (!(name = sysv_translate_name(de->d_name + 3))) {
3045 if ((r = manager_load_unit_prepare(m, name, NULL, NULL, &service)) < 0) {
3046 log_warning("Failed to prepare unit %s: %s", name, strerror(-r));
3050 if (de->d_name[0] == 'S') {
3052 if (rcnd_table[i].type == RUNLEVEL_UP || rcnd_table[i].type == RUNLEVEL_SYSINIT) {
3053 SERVICE(service)->sysv_start_priority_from_rcnd =
3054 MAX(a*10 + b, SERVICE(service)->sysv_start_priority_from_rcnd);
3056 SERVICE(service)->sysv_enabled = true;
3059 if ((r = set_ensure_allocated(&runlevel_services[i], trivial_hash_func, trivial_compare_func)) < 0)
3062 if ((r = set_put(runlevel_services[i], service)) < 0)
3065 } else if (de->d_name[0] == 'K' &&
3066 (rcnd_table[i].type == RUNLEVEL_DOWN ||
3067 rcnd_table[i].type == RUNLEVEL_SYSINIT)) {
3069 if ((r = set_ensure_allocated(&shutdown_services, trivial_hash_func, trivial_compare_func)) < 0)
3072 if ((r = set_put(shutdown_services, service)) < 0)
3078 /* Now we loaded all stubs and are aware of the lowest
3079 start-up priority for all services, not let's actually load
3080 the services, this will also tell us which services are
3081 actually native now */
3082 manager_dispatch_load_queue(m);
3084 /* If this is a native service, rely on native ways to pull in
3085 * a service, don't pull it in via sysv rcN.d links. */
3086 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++)
3087 SET_FOREACH(service, runlevel_services[i], j) {
3088 service = unit_follow_merge(service);
3090 if (service->meta.fragment_path)
3093 if ((r = unit_add_two_dependencies_by_name_inverse(service, UNIT_AFTER, UNIT_WANTS, rcnd_table[i].target, NULL, true)) < 0)
3097 /* We honour K links only for halt/reboot. For the normal
3098 * runlevels we assume the stop jobs will be implicitly added
3099 * by the core logic. Also, we don't really distinguish here
3100 * between the runlevels 0 and 6 and just add them to the
3101 * special shutdown target. On SUSE the boot.d/ runlevel is
3102 * also used for shutdown, so we add links for that too to the
3103 * shutdown target.*/
3104 SET_FOREACH(service, shutdown_services, j) {
3105 service = unit_follow_merge(service);
3107 if (service->meta.fragment_path)
3110 if ((r = unit_add_two_dependencies_by_name(service, UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true)) < 0)
3121 for (i = 0; i < ELEMENTSOF(rcnd_table); i++)
3122 set_free(runlevel_services[i]);
3123 set_free(shutdown_services);
3132 static void service_bus_name_owner_change(
3135 const char *old_owner,
3136 const char *new_owner) {
3138 Service *s = SERVICE(u);
3143 assert(streq(s->bus_name, name));
3144 assert(old_owner || new_owner);
3146 if (old_owner && new_owner)
3147 log_debug("%s's D-Bus name %s changed owner from %s to %s", u->meta.id, name, old_owner, new_owner);
3149 log_debug("%s's D-Bus name %s no longer registered by %s", u->meta.id, name, old_owner);
3151 log_debug("%s's D-Bus name %s now registered by %s", u->meta.id, name, new_owner);
3153 s->bus_name_good = !!new_owner;
3155 if (s->type == SERVICE_DBUS) {
3157 /* service_enter_running() will figure out what to
3159 if (s->state == SERVICE_RUNNING)
3160 service_enter_running(s, true);
3161 else if (s->state == SERVICE_START && new_owner)
3162 service_enter_start_post(s);
3164 } else if (new_owner &&
3166 (s->state == SERVICE_START ||
3167 s->state == SERVICE_START_POST ||
3168 s->state == SERVICE_RUNNING ||
3169 s->state == SERVICE_RELOAD)) {
3171 /* Try to acquire PID from bus service */
3172 log_debug("Trying to acquire PID from D-Bus name...");
3174 bus_query_pid(u->meta.manager, name);
3178 static void service_bus_query_pid_done(
3183 Service *s = SERVICE(u);
3188 log_debug("%s's D-Bus name %s is now owned by process %u", u->meta.id, name, (unsigned) pid);
3190 if (s->main_pid <= 0 &&
3191 (s->state == SERVICE_START ||
3192 s->state == SERVICE_START_POST ||
3193 s->state == SERVICE_RUNNING ||
3194 s->state == SERVICE_RELOAD))
3195 service_set_main_pid(s, pid);
3198 int service_set_socket_fd(Service *s, int fd, Socket *sock) {
3202 /* This is called by the socket code when instantiating a new
3203 * service for a stream socket and the socket needs to be
3206 if (s->meta.load_state != UNIT_LOADED)
3209 if (s->socket_fd >= 0)
3212 if (s->state != SERVICE_DEAD)
3216 s->got_socket_fd = true;
3217 s->accept_socket = sock;
3222 static void service_reset_failed(Unit *u) {
3223 Service *s = SERVICE(u);
3227 if (s->state == SERVICE_FAILED)
3228 service_set_state(s, SERVICE_DEAD);
3233 static bool service_need_daemon_reload(Unit *u) {
3234 Service *s = SERVICE(u);
3238 #ifdef HAVE_SYSV_COMPAT
3243 if (stat(s->sysv_path, &st) < 0)
3244 /* What, cannot access this anymore? */
3247 if (s->sysv_mtime > 0 &&
3248 timespec_load(&st.st_mtim) != s->sysv_mtime)
3256 static int service_kill(Unit *u, KillWho who, KillMode mode, int signo, DBusError *error) {
3257 Service *s = SERVICE(u);
3259 Set *pid_set = NULL;
3263 if (s->main_pid <= 0 && who == KILL_MAIN) {
3264 dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "No main process to kill");
3268 if (s->control_pid <= 0 && who == KILL_CONTROL) {
3269 dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "No control process to kill");
3273 if (who == KILL_CONTROL || who == KILL_ALL)
3274 if (s->control_pid > 0)
3275 if (kill(s->control_pid, signo) < 0)
3278 if (who == KILL_MAIN || who == KILL_ALL)
3279 if (s->main_pid > 0)
3280 if (kill(s->main_pid, signo) < 0)
3283 if (who == KILL_ALL && mode == KILL_CONTROL_GROUP) {
3286 if (!(pid_set = set_new(trivial_hash_func, trivial_compare_func)))
3289 /* Exclude the control/main pid from being killed via the cgroup */
3290 if (s->control_pid > 0)
3291 if ((q = set_put(pid_set, LONG_TO_PTR(s->control_pid))) < 0) {
3296 if (s->main_pid > 0)
3297 if ((q = set_put(pid_set, LONG_TO_PTR(s->main_pid))) < 0) {
3302 if ((q = cgroup_bonding_kill_list(s->meta.cgroup_bondings, signo, false, pid_set)) < 0)
3303 if (q != -EAGAIN && q != -ESRCH && q != -ENOENT)
3314 static const char* const service_state_table[_SERVICE_STATE_MAX] = {
3315 [SERVICE_DEAD] = "dead",
3316 [SERVICE_START_PRE] = "start-pre",
3317 [SERVICE_START] = "start",
3318 [SERVICE_START_POST] = "start-post",
3319 [SERVICE_RUNNING] = "running",
3320 [SERVICE_EXITED] = "exited",
3321 [SERVICE_RELOAD] = "reload",
3322 [SERVICE_STOP] = "stop",
3323 [SERVICE_STOP_SIGTERM] = "stop-sigterm",
3324 [SERVICE_STOP_SIGKILL] = "stop-sigkill",
3325 [SERVICE_STOP_POST] = "stop-post",
3326 [SERVICE_FINAL_SIGTERM] = "final-sigterm",
3327 [SERVICE_FINAL_SIGKILL] = "final-sigkill",
3328 [SERVICE_FAILED] = "failed",
3329 [SERVICE_AUTO_RESTART] = "auto-restart",
3332 DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
3334 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
3335 [SERVICE_RESTART_NO] = "no",
3336 [SERVICE_RESTART_ON_SUCCESS] = "on-success",
3337 [SERVICE_RESTART_ON_FAILURE] = "on-failure",
3338 [SERVICE_RESTART_ON_ABORT] = "on-abort",
3339 [SERVICE_RESTART_ALWAYS] = "always"
3342 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
3344 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
3345 [SERVICE_SIMPLE] = "simple",
3346 [SERVICE_FORKING] = "forking",
3347 [SERVICE_ONESHOT] = "oneshot",
3348 [SERVICE_DBUS] = "dbus",
3349 [SERVICE_NOTIFY] = "notify"
3352 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
3354 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
3355 [SERVICE_EXEC_START_PRE] = "ExecStartPre",
3356 [SERVICE_EXEC_START] = "ExecStart",
3357 [SERVICE_EXEC_START_POST] = "ExecStartPost",
3358 [SERVICE_EXEC_RELOAD] = "ExecReload",
3359 [SERVICE_EXEC_STOP] = "ExecStop",
3360 [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
3363 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
3365 static const char* const notify_access_table[_NOTIFY_ACCESS_MAX] = {
3366 [NOTIFY_NONE] = "none",
3367 [NOTIFY_MAIN] = "main",
3368 [NOTIFY_ALL] = "all"
3371 DEFINE_STRING_TABLE_LOOKUP(notify_access, NotifyAccess);
3373 const UnitVTable service_vtable = {
3374 .suffix = ".service",
3375 .show_status = true,
3377 .init = service_init,
3378 .done = service_done,
3379 .load = service_load,
3381 .coldplug = service_coldplug,
3383 .dump = service_dump,
3385 .start = service_start,
3386 .stop = service_stop,
3387 .reload = service_reload,
3389 .can_reload = service_can_reload,
3391 .kill = service_kill,
3393 .serialize = service_serialize,
3394 .deserialize_item = service_deserialize_item,
3396 .active_state = service_active_state,
3397 .sub_state_to_string = service_sub_state_to_string,
3399 .check_gc = service_check_gc,
3400 .check_snapshot = service_check_snapshot,
3402 .sigchld_event = service_sigchld_event,
3403 .timer_event = service_timer_event,
3405 .reset_failed = service_reset_failed,
3407 .need_daemon_reload = service_need_daemon_reload,
3409 .cgroup_notify_empty = service_cgroup_notify_event,
3410 .notify_message = service_notify_message,
3412 .bus_name_owner_change = service_bus_name_owner_change,
3413 .bus_query_pid_done = service_bus_query_pid_done,
3415 .bus_interface = "org.freedesktop.systemd1.Service",
3416 .bus_message_handler = bus_service_message_handler,
3417 .bus_invalidating_properties = bus_service_invalidating_properties,
3419 #ifdef HAVE_SYSV_COMPAT
3420 .enumerate = service_enumerate