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_per_type, other, s->meta.manager->units_per_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;
479 if (!(f = fopen(path, "re"))) {
480 r = errno == ENOENT ? 0 : -errno;
485 if (!(s->sysv_path = strdup(path))) {
491 char l[LINE_MAX], *t;
493 if (!fgets(l, sizeof(l), f)) {
498 log_error("Failed to read configuration file '%s': %s", path, strerror(-r));
508 if (state == NORMAL && streq(t, "### BEGIN INIT INFO")) {
510 s->sysv_has_lsb = true;
514 if ((state == LSB_DESCRIPTION || state == LSB) && streq(t, "### END INIT INFO")) {
520 t += strspn(t, WHITESPACE);
522 if (state == NORMAL) {
524 /* Try to parse Red Hat style chkconfig headers */
526 if (startswith_no_case(t, "chkconfig:")) {
528 char runlevels[16], *k;
532 if (sscanf(t+10, "%15s %i %*i",
534 &start_priority) != 2) {
536 log_warning("[%s:%u] Failed to parse chkconfig line. Ignoring.", path, line);
540 /* A start priority gathered from the
541 * symlink farms is preferred over the
542 * data from the LSB header. */
543 if (start_priority < 0 || start_priority > 99)
544 log_warning("[%s:%u] Start priority out of range. Ignoring.", path, line);
546 s->sysv_start_priority = start_priority;
548 char_array_0(runlevels);
549 k = delete_chars(runlevels, WHITESPACE "-");
554 if (!(d = strdup(k))) {
559 free(s->sysv_runlevels);
560 s->sysv_runlevels = d;
563 } else if (startswith_no_case(t, "description:")) {
565 size_t k = strlen(t);
569 if (t[k-1] == '\\') {
574 if ((j = strstrip(t+12)) && *j) {
575 if (!(d = strdup(j))) {
582 free(chkconfig_description);
583 chkconfig_description = d;
585 } else if (startswith_no_case(t, "pidfile:")) {
592 if (!path_is_absolute(fn)) {
593 log_warning("[%s:%u] PID file not absolute. Ignoring.", path, line);
597 if (!(fn = strdup(fn))) {
606 } else if (state == DESCRIPTION) {
608 /* Try to parse Red Hat style description
611 size_t k = strlen(t);
619 if ((j = strstrip(t)) && *j) {
622 if (chkconfig_description)
623 asprintf(&d, "%s %s", chkconfig_description, j);
632 free(chkconfig_description);
633 chkconfig_description = d;
636 } else if (state == LSB || state == LSB_DESCRIPTION) {
638 if (startswith_no_case(t, "Provides:")) {
644 FOREACH_WORD_QUOTED(w, z, t+9, i) {
647 if (!(n = strndup(w, z))) {
652 r = sysv_translate_facility(n, file_name_from_path(path), &m);
661 if (unit_name_to_type(m) == UNIT_SERVICE)
662 r = unit_add_name(u, m);
669 * indication that the
671 * now available. This
674 * targets do NOT pull
677 r = unit_add_two_dependencies_by_name(u, UNIT_BEFORE, UNIT_WANTS, m, NULL, true);
680 log_error("[%s:%u] Failed to add LSB Provides name %s, ignoring: %s", path, line, m, strerror(-r));
685 } else if (startswith_no_case(t, "Required-Start:") ||
686 startswith_no_case(t, "Should-Start:") ||
687 startswith_no_case(t, "X-Start-Before:") ||
688 startswith_no_case(t, "X-Start-After:")) {
694 FOREACH_WORD_QUOTED(w, z, strchr(t, ':')+1, i) {
697 if (!(n = strndup(w, z))) {
702 r = sysv_translate_facility(n, file_name_from_path(path), &m);
705 log_error("[%s:%u] Failed to translate LSB dependency %s, ignoring: %s", path, line, n, strerror(-r));
715 r = unit_add_dependency_by_name(u, startswith_no_case(t, "X-Start-Before:") ? UNIT_BEFORE : UNIT_AFTER, m, NULL, true);
718 log_error("[%s:%u] Failed to add dependency on %s, ignoring: %s", path, line, m, strerror(-r));
722 } else if (startswith_no_case(t, "Default-Start:")) {
727 k = delete_chars(t+14, WHITESPACE "-");
730 if (!(d = strdup(k))) {
735 free(s->sysv_runlevels);
736 s->sysv_runlevels = d;
739 } else if (startswith_no_case(t, "Description:")) {
742 state = LSB_DESCRIPTION;
744 if ((j = strstrip(t+12)) && *j) {
745 if (!(d = strdup(j))) {
752 free(long_description);
753 long_description = d;
755 } else if (startswith_no_case(t, "Short-Description:")) {
760 if ((j = strstrip(t+18)) && *j) {
761 if (!(d = strdup(j))) {
768 free(short_description);
769 short_description = d;
771 } else if (startswith_no_case(t, "X-Interactive:")) {
774 if ((b = parse_boolean(strstrip(t+14))) < 0) {
775 log_warning("[%s:%u] Couldn't parse interactive flag. Ignoring.", path, line);
780 s->exec_context.std_input = EXEC_INPUT_TTY;
782 s->exec_context.std_input = EXEC_INPUT_NULL;
784 } else if (state == LSB_DESCRIPTION) {
786 if (startswith(l, "#\t") || startswith(l, "# ")) {
789 if ((j = strstrip(t)) && *j) {
792 if (long_description)
793 asprintf(&d, "%s %s", long_description, t);
802 free(long_description);
803 long_description = d;
812 if ((r = sysv_exec_commands(s)) < 0)
815 if (s->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, s->sysv_runlevels)) {
816 /* If there a runlevels configured for this service
817 * but none of the standard ones, then we assume this
818 * is some special kind of service (which might be
819 * needed for early boot) and don't create any links
822 s->meta.default_dependencies = false;
824 /* Don't timeout special services during boot (like fsck) */
827 s->timeout_usec = DEFAULT_SYSV_TIMEOUT_USEC;
829 /* Special setting for all SysV services */
830 s->type = SERVICE_FORKING;
831 s->remain_after_exit = true;
832 s->restart = SERVICE_RESTART_NO;
833 s->exec_context.std_output =
834 (s->meta.manager->sysv_console || s->exec_context.std_input == EXEC_INPUT_TTY)
835 ? EXEC_OUTPUT_TTY : s->meta.manager->default_std_output;
836 s->exec_context.kill_mode = KILL_PROCESS;
838 /* We use the long description only if
839 * no short description is set. */
841 if (short_description)
842 description = short_description;
843 else if (chkconfig_description)
844 description = chkconfig_description;
845 else if (long_description)
846 description = long_description;
853 if (!(d = strappend(s->sysv_has_lsb ? "LSB: " : "SYSV: ", description))) {
858 u->meta.description = d;
861 /* The priority that has been set in /etc/rcN.d/ hierarchies
862 * takes precedence over what is stored as default in the LSB
864 if (s->sysv_start_priority_from_rcnd >= 0)
865 s->sysv_start_priority = s->sysv_start_priority_from_rcnd;
867 u->meta.load_state = UNIT_LOADED;
875 free(short_description);
876 free(long_description);
877 free(chkconfig_description);
882 static int service_load_sysv_name(Service *s, const char *name) {
888 /* For SysV services we strip the boot.*, rc.* and *.sh
889 * prefixes/suffixes. */
890 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU) || defined(TARGET_ANGSTROM)
891 if (endswith(name, ".sh.service"))
896 if (startswith(name, "boot."))
900 #ifdef TARGET_FRUGALWARE
901 if (startswith(name, "rc."))
905 STRV_FOREACH(p, s->meta.manager->lookup_paths.sysvinit_path) {
909 if (asprintf(&path, "%s/%s", *p, name) < 0)
912 assert(endswith(path, ".service"));
913 path[strlen(path)-8] = 0;
915 r = service_load_sysv_path(s, path);
917 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU) || defined(TARGET_ANGSTROM)
918 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
919 /* Try Debian style *.sh source'able init scripts */
921 r = service_load_sysv_path(s, path);
927 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
928 /* Try SUSE style boot.* init scripts */
930 if (asprintf(&path, "%s/boot.%s", *p, name) < 0)
933 /* Drop .service suffix */
934 path[strlen(path)-8] = 0;
935 r = service_load_sysv_path(s, path);
940 #ifdef TARGET_FRUGALWARE
941 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
942 /* Try Frugalware style rc.* init scripts */
944 if (asprintf(&path, "%s/rc.%s", *p, name) < 0)
947 /* Drop .service suffix */
948 path[strlen(path)-8] = 0;
949 r = service_load_sysv_path(s, path);
957 if ((s->meta.load_state != UNIT_STUB))
964 static int service_load_sysv(Service *s) {
971 /* Load service data from SysV init scripts, preferably with
974 if (strv_isempty(s->meta.manager->lookup_paths.sysvinit_path))
977 if ((t = s->meta.id))
978 if ((r = service_load_sysv_name(s, t)) < 0)
981 if (s->meta.load_state == UNIT_STUB)
982 SET_FOREACH(t, s->meta.names, i) {
986 if ((r = service_load_sysv_name(s, t)) < 0)
989 if (s->meta.load_state != UNIT_STUB)
997 static int fsck_fix_order(Service *s) {
1003 if (s->fsck_passno <= 0)
1006 /* For each pair of services where both have an fsck priority
1007 * we order things based on it. */
1009 LIST_FOREACH(units_per_type, other, s->meta.manager->units_per_type[UNIT_SERVICE]) {
1013 t = (Service*) other;
1018 if (t->meta.load_state != UNIT_LOADED)
1021 if (t->fsck_passno <= 0)
1024 if (t->fsck_passno < s->fsck_passno)
1026 else if (t->fsck_passno > s->fsck_passno)
1031 if ((r = unit_add_dependency(UNIT(s), d, UNIT(t), true)) < 0)
1038 static int service_verify(Service *s) {
1041 if (s->meta.load_state != UNIT_LOADED)
1044 if (!s->exec_command[SERVICE_EXEC_START]) {
1045 log_error("%s lacks ExecStart setting. Refusing.", s->meta.id);
1049 if (s->type != SERVICE_ONESHOT &&
1050 s->exec_command[SERVICE_EXEC_START]->command_next) {
1051 log_error("%s has more than one ExecStart setting, which is only allowed for Type=oneshot services. Refusing.", s->meta.id);
1055 if (s->type == SERVICE_ONESHOT &&
1056 s->exec_command[SERVICE_EXEC_RELOAD]) {
1057 log_error("%s has an ExecReload setting, which is not allowed for Type=oneshot services. Refusing.", s->meta.id);
1061 if (s->type == SERVICE_DBUS && !s->bus_name) {
1062 log_error("%s is of type D-Bus but no D-Bus service name has been specified. Refusing.", s->meta.id);
1066 if (s->exec_context.pam_name && s->exec_context.kill_mode != KILL_CONTROL_GROUP) {
1067 log_error("%s has PAM enabled. Kill mode must be set to 'control-group'. Refusing.", s->meta.id);
1074 static int service_add_default_dependencies(Service *s) {
1079 /* Add a number of automatic dependencies useful for the
1080 * majority of services. */
1082 /* First, pull in base system */
1083 if (s->meta.manager->running_as == MANAGER_SYSTEM) {
1085 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_BASIC_TARGET, NULL, true)) < 0)
1088 } else if (s->meta.manager->running_as == MANAGER_USER) {
1090 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SOCKETS_TARGET, NULL, true)) < 0)
1094 /* Second, activate normal shutdown */
1095 return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true);
1098 static int service_load(Unit *u) {
1100 Service *s = SERVICE(u);
1104 /* Load a .service file */
1105 if ((r = unit_load_fragment(u)) < 0)
1108 #ifdef HAVE_SYSV_COMPAT
1109 /* Load a classic init script as a fallback, if we couldn't find anything */
1110 if (u->meta.load_state == UNIT_STUB)
1111 if ((r = service_load_sysv(s)) < 0)
1115 /* Still nothing found? Then let's give up */
1116 if (u->meta.load_state == UNIT_STUB)
1119 /* We were able to load something, then let's add in the
1120 * dropin directories. */
1121 if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
1124 /* This is a new unit? Then let's add in some extras */
1125 if (u->meta.load_state == UNIT_LOADED) {
1126 if ((r = unit_add_exec_dependencies(u, &s->exec_context)) < 0)
1129 if ((r = unit_add_default_cgroups(u)) < 0)
1132 #ifdef HAVE_SYSV_COMPAT
1133 if ((r = sysv_fix_order(s)) < 0)
1137 if ((r = fsck_fix_order(s)) < 0)
1141 if ((r = unit_watch_bus_name(u, s->bus_name)) < 0)
1144 if (s->type == SERVICE_NOTIFY && s->notify_access == NOTIFY_NONE)
1145 s->notify_access = NOTIFY_MAIN;
1147 if (s->type == SERVICE_DBUS || s->bus_name)
1148 if ((r = unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_REQUIRES, SPECIAL_DBUS_SOCKET, NULL, true)) < 0)
1151 if (s->meta.default_dependencies)
1152 if ((r = service_add_default_dependencies(s)) < 0)
1156 return service_verify(s);
1159 static void service_dump(Unit *u, FILE *f, const char *prefix) {
1161 ServiceExecCommand c;
1162 Service *s = SERVICE(u);
1163 const char *prefix2;
1168 p2 = strappend(prefix, "\t");
1169 prefix2 = p2 ? p2 : prefix;
1172 "%sService State: %s\n"
1173 "%sPermissionsStartOnly: %s\n"
1174 "%sRootDirectoryStartOnly: %s\n"
1175 "%sRemainAfterExit: %s\n"
1176 "%sGuessMainPID: %s\n"
1179 "%sNotifyAccess: %s\n",
1180 prefix, service_state_to_string(s->state),
1181 prefix, yes_no(s->permissions_start_only),
1182 prefix, yes_no(s->root_directory_start_only),
1183 prefix, yes_no(s->remain_after_exit),
1184 prefix, yes_no(s->guess_main_pid),
1185 prefix, service_type_to_string(s->type),
1186 prefix, service_restart_to_string(s->restart),
1187 prefix, notify_access_to_string(s->notify_access));
1189 if (s->control_pid > 0)
1191 "%sControl PID: %lu\n",
1192 prefix, (unsigned long) s->control_pid);
1194 if (s->main_pid > 0)
1197 "%sMain PID Known: %s\n"
1198 "%sMain PID Alien: %s\n",
1199 prefix, (unsigned long) s->main_pid,
1200 prefix, yes_no(s->main_pid_known),
1201 prefix, yes_no(s->main_pid_alien));
1206 prefix, s->pid_file);
1211 "%sBus Name Good: %s\n",
1212 prefix, s->bus_name,
1213 prefix, yes_no(s->bus_name_good));
1215 exec_context_dump(&s->exec_context, f, prefix);
1217 for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
1219 if (!s->exec_command[c])
1222 fprintf(f, "%s-> %s:\n",
1223 prefix, service_exec_command_to_string(c));
1225 exec_command_dump_list(s->exec_command[c], f, prefix2);
1228 #ifdef HAVE_SYSV_COMPAT
1231 "%sSysV Init Script Path: %s\n"
1232 "%sSysV Init Script has LSB Header: %s\n"
1233 "%sSysVEnabled: %s\n",
1234 prefix, s->sysv_path,
1235 prefix, yes_no(s->sysv_has_lsb),
1236 prefix, yes_no(s->sysv_enabled));
1238 if (s->sysv_start_priority >= 0)
1240 "%sSysVStartPriority: %i\n",
1241 prefix, s->sysv_start_priority);
1243 if (s->sysv_runlevels)
1244 fprintf(f, "%sSysVRunLevels: %s\n",
1245 prefix, s->sysv_runlevels);
1248 if (s->fsck_passno > 0)
1250 "%sFsckPassNo: %i\n",
1251 prefix, s->fsck_passno);
1254 fprintf(f, "%sStatus Text: %s\n",
1255 prefix, s->status_text);
1260 static int service_load_pid_file(Service *s) {
1267 if (s->main_pid_known)
1273 if ((r = read_one_line_file(s->pid_file, &k)) < 0)
1276 r = parse_pid(k, &pid);
1282 if (kill(pid, 0) < 0 && errno != EPERM) {
1283 log_warning("PID %lu read from file %s does not exist. Your service or init script might be broken.",
1284 (unsigned long) pid, s->pid_file);
1288 if ((r = service_set_main_pid(s, pid)) < 0)
1291 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1292 /* FIXME: we need to do something here */
1298 static int service_search_main_pid(Service *s) {
1304 /* If we know it anyway, don't ever fallback to unreliable
1306 if (s->main_pid_known)
1309 if (!s->guess_main_pid)
1312 assert(s->main_pid <= 0);
1314 if ((pid = cgroup_bonding_search_main_pid_list(s->meta.cgroup_bondings)) <= 0)
1317 if ((r = service_set_main_pid(s, pid)) < 0)
1320 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1321 /* FIXME: we need to do something here */
1327 static int service_get_sockets(Service *s, Set **_set) {
1336 if (s->socket_fd >= 0)
1339 if (!set_isempty(s->configured_sockets))
1342 /* Collects all Socket objects that belong to this
1343 * service. Note that a service might have multiple sockets
1344 * via multiple names. */
1346 if (!(set = set_new(NULL, NULL)))
1349 SET_FOREACH(t, s->meta.names, i) {
1353 /* Look for all socket objects that go by any of our
1354 * units and collect their fds */
1356 if (!(k = unit_name_change_suffix(t, ".socket"))) {
1361 p = manager_get_unit(s->meta.manager, k);
1367 if ((r = set_put(set, p)) < 0)
1379 static int service_notify_sockets_dead(Service *s) {
1381 Set *set, *free_set = NULL;
1387 /* Notifies all our sockets when we die */
1389 if (s->socket_fd >= 0)
1392 if (!set_isempty(s->configured_sockets))
1393 set = s->configured_sockets;
1395 if ((r = service_get_sockets(s, &free_set)) < 0)
1401 SET_FOREACH(sock, set, i)
1402 socket_notify_service_dead(sock);
1409 static void service_set_state(Service *s, ServiceState state) {
1410 ServiceState old_state;
1413 old_state = s->state;
1416 if (state != SERVICE_START_PRE &&
1417 state != SERVICE_START &&
1418 state != SERVICE_START_POST &&
1419 state != SERVICE_RELOAD &&
1420 state != SERVICE_STOP &&
1421 state != SERVICE_STOP_SIGTERM &&
1422 state != SERVICE_STOP_SIGKILL &&
1423 state != SERVICE_STOP_POST &&
1424 state != SERVICE_FINAL_SIGTERM &&
1425 state != SERVICE_FINAL_SIGKILL &&
1426 state != SERVICE_AUTO_RESTART)
1427 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1429 if (state != SERVICE_START &&
1430 state != SERVICE_START_POST &&
1431 state != SERVICE_RUNNING &&
1432 state != SERVICE_RELOAD &&
1433 state != SERVICE_STOP &&
1434 state != SERVICE_STOP_SIGTERM &&
1435 state != SERVICE_STOP_SIGKILL) {
1436 service_unwatch_main_pid(s);
1437 s->main_command = NULL;
1440 if (state != SERVICE_START_PRE &&
1441 state != SERVICE_START &&
1442 state != SERVICE_START_POST &&
1443 state != SERVICE_RELOAD &&
1444 state != SERVICE_STOP &&
1445 state != SERVICE_STOP_SIGTERM &&
1446 state != SERVICE_STOP_SIGKILL &&
1447 state != SERVICE_STOP_POST &&
1448 state != SERVICE_FINAL_SIGTERM &&
1449 state != SERVICE_FINAL_SIGKILL) {
1450 service_unwatch_control_pid(s);
1451 s->control_command = NULL;
1452 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1455 if (state == SERVICE_DEAD ||
1456 state == SERVICE_STOP ||
1457 state == SERVICE_STOP_SIGTERM ||
1458 state == SERVICE_STOP_SIGKILL ||
1459 state == SERVICE_STOP_POST ||
1460 state == SERVICE_FINAL_SIGTERM ||
1461 state == SERVICE_FINAL_SIGKILL ||
1462 state == SERVICE_FAILED ||
1463 state == SERVICE_AUTO_RESTART)
1464 service_notify_sockets_dead(s);
1466 if (state != SERVICE_START_PRE &&
1467 state != SERVICE_START &&
1468 state != SERVICE_START_POST &&
1469 state != SERVICE_RUNNING &&
1470 state != SERVICE_RELOAD &&
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_DEAD && s->meta.job)) {
1478 service_close_socket_fd(s);
1479 service_connection_unref(s);
1482 /* For the inactive states unit_notify() will trim the cgroup,
1483 * but for exit we have to do that ourselves... */
1484 if (state == SERVICE_EXITED && s->meta.manager->n_deserializing <= 0)
1485 cgroup_bonding_trim_list(s->meta.cgroup_bondings, true);
1487 if (old_state != state)
1488 log_debug("%s changed %s -> %s", s->meta.id, service_state_to_string(old_state), service_state_to_string(state));
1490 unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state], !s->reload_failure);
1491 s->reload_failure = false;
1494 static int service_coldplug(Unit *u) {
1495 Service *s = SERVICE(u);
1499 assert(s->state == SERVICE_DEAD);
1501 if (s->deserialized_state != s->state) {
1503 if (s->deserialized_state == SERVICE_START_PRE ||
1504 s->deserialized_state == SERVICE_START ||
1505 s->deserialized_state == SERVICE_START_POST ||
1506 s->deserialized_state == SERVICE_RELOAD ||
1507 s->deserialized_state == SERVICE_STOP ||
1508 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1509 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1510 s->deserialized_state == SERVICE_STOP_POST ||
1511 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1512 s->deserialized_state == SERVICE_FINAL_SIGKILL ||
1513 s->deserialized_state == SERVICE_AUTO_RESTART) {
1515 if (s->deserialized_state == SERVICE_AUTO_RESTART || s->timeout_usec > 0) {
1518 k = s->deserialized_state == SERVICE_AUTO_RESTART ? s->restart_usec : s->timeout_usec;
1520 if ((r = unit_watch_timer(UNIT(s), k, &s->timer_watch)) < 0)
1525 if ((s->deserialized_state == SERVICE_START &&
1526 (s->type == SERVICE_FORKING ||
1527 s->type == SERVICE_DBUS ||
1528 s->type == SERVICE_ONESHOT ||
1529 s->type == SERVICE_NOTIFY)) ||
1530 s->deserialized_state == SERVICE_START_POST ||
1531 s->deserialized_state == SERVICE_RUNNING ||
1532 s->deserialized_state == SERVICE_RELOAD ||
1533 s->deserialized_state == SERVICE_STOP ||
1534 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1535 s->deserialized_state == SERVICE_STOP_SIGKILL)
1536 if (s->main_pid > 0)
1537 if ((r = unit_watch_pid(UNIT(s), s->main_pid)) < 0)
1540 if (s->deserialized_state == SERVICE_START_PRE ||
1541 s->deserialized_state == SERVICE_START ||
1542 s->deserialized_state == SERVICE_START_POST ||
1543 s->deserialized_state == SERVICE_RELOAD ||
1544 s->deserialized_state == SERVICE_STOP ||
1545 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1546 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1547 s->deserialized_state == SERVICE_STOP_POST ||
1548 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1549 s->deserialized_state == SERVICE_FINAL_SIGKILL)
1550 if (s->control_pid > 0)
1551 if ((r = unit_watch_pid(UNIT(s), s->control_pid)) < 0)
1554 service_set_state(s, s->deserialized_state);
1560 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
1564 unsigned rn_fds = 0;
1565 Set *set, *free_set = NULL;
1572 if (s->socket_fd >= 0)
1575 if (!set_isempty(s->configured_sockets))
1576 set = s->configured_sockets;
1578 if ((r = service_get_sockets(s, &free_set)) < 0)
1584 SET_FOREACH(sock, set, i) {
1588 if ((r = socket_collect_fds(sock, &cfds, &cn_fds)) < 0)
1600 if (!(t = new(int, rn_fds+cn_fds))) {
1606 memcpy(t, rfds, rn_fds * sizeof(int));
1607 memcpy(t+rn_fds, cfds, cn_fds * sizeof(int));
1612 rn_fds = rn_fds+cn_fds;
1630 static int service_spawn(
1635 bool apply_permissions,
1637 bool apply_tty_stdin,
1638 bool set_notify_socket,
1643 int *fds = NULL, *fdsbuf = NULL;
1644 unsigned n_fds = 0, n_env = 0;
1645 char **argv = NULL, **final_env = NULL, **our_env = NULL;
1652 s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1653 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1654 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
1656 if (s->socket_fd >= 0) {
1657 fds = &s->socket_fd;
1660 if ((r = service_collect_fds(s, &fdsbuf, &n_fds)) < 0)
1667 if (timeout && s->timeout_usec) {
1668 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1671 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1673 if (!(argv = unit_full_printf_strv(UNIT(s), c->argv))) {
1678 if (!(our_env = new0(char*, 4))) {
1683 if (set_notify_socket)
1684 if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=%s", s->meta.manager->notify_socket) < 0) {
1689 if (s->main_pid > 0)
1690 if (asprintf(our_env + n_env++, "MAINPID=%lu", (unsigned long) s->main_pid) < 0) {
1695 if (!(final_env = strv_env_merge(2,
1696 s->meta.manager->environment,
1711 s->meta.manager->confirm_spawn,
1712 s->meta.cgroup_bondings,
1719 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1720 /* FIXME: we need to do something here */
1726 strv_free(final_env);
1736 strv_free(final_env);
1739 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1744 static int main_pid_good(Service *s) {
1747 /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1750 /* If we know the pid file, then lets just check if it is
1752 if (s->main_pid_known) {
1754 /* If it's an alien child let's check if it is still
1756 if (s->main_pid_alien)
1757 return kill(s->main_pid, 0) >= 0 || errno != ESRCH;
1759 /* .. otherwise assume we'll get a SIGCHLD for it,
1760 * which we really should wait for to collect exit
1761 * status and code */
1762 return s->main_pid > 0;
1765 /* We don't know the pid */
1769 static int control_pid_good(Service *s) {
1772 return s->control_pid > 0;
1775 static int cgroup_good(Service *s) {
1780 if ((r = cgroup_bonding_is_empty_list(s->meta.cgroup_bondings)) < 0)
1786 static void service_enter_dead(Service *s, bool success, bool allow_restart) {
1793 if (allow_restart &&
1794 !s->forbid_restart &&
1795 (s->restart == SERVICE_RESTART_ALWAYS ||
1796 (s->restart == SERVICE_RESTART_ON_SUCCESS && !s->failure) ||
1797 (s->restart == SERVICE_RESTART_ON_FAILURE && s->failure) ||
1798 (s->restart == SERVICE_RESTART_ON_ABORT && s->failure &&
1799 (s->main_exec_status.code == CLD_KILLED ||
1800 s->main_exec_status.code == CLD_DUMPED)))) {
1802 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
1805 service_set_state(s, SERVICE_AUTO_RESTART);
1807 service_set_state(s, s->failure ? SERVICE_FAILED : SERVICE_DEAD);
1809 s->forbid_restart = false;
1814 log_warning("%s failed to run install restart timer: %s", s->meta.id, strerror(-r));
1815 service_enter_dead(s, false, false);
1818 static void service_enter_signal(Service *s, ServiceState state, bool success);
1820 static void service_enter_stop_post(Service *s, bool success) {
1827 service_unwatch_control_pid(s);
1829 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST])) {
1830 s->control_command_id = SERVICE_EXEC_STOP_POST;
1832 if ((r = service_spawn(s,
1836 !s->permissions_start_only,
1837 !s->root_directory_start_only,
1840 &s->control_pid)) < 0)
1844 service_set_state(s, SERVICE_STOP_POST);
1846 service_enter_signal(s, SERVICE_FINAL_SIGTERM, true);
1851 log_warning("%s failed to run 'stop-post' task: %s", s->meta.id, strerror(-r));
1852 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1855 static void service_enter_signal(Service *s, ServiceState state, bool success) {
1857 Set *pid_set = NULL;
1858 bool wait_for_exit = false;
1865 if (s->exec_context.kill_mode != KILL_NONE) {
1866 int sig = (state == SERVICE_STOP_SIGTERM || state == SERVICE_FINAL_SIGTERM) ? s->exec_context.kill_signal : SIGKILL;
1868 if (s->main_pid > 0) {
1869 if (kill_and_sigcont(s->main_pid, sig) < 0 && errno != ESRCH)
1870 log_warning("Failed to kill main process %li: %m", (long) s->main_pid);
1872 wait_for_exit = !s->main_pid_alien;
1875 if (s->control_pid > 0) {
1876 if (kill_and_sigcont(s->control_pid, sig) < 0 && errno != ESRCH)
1877 log_warning("Failed to kill control process %li: %m", (long) s->control_pid);
1879 wait_for_exit = true;
1882 if (s->exec_context.kill_mode == KILL_CONTROL_GROUP) {
1884 if (!(pid_set = set_new(trivial_hash_func, trivial_compare_func))) {
1889 /* Exclude the main/control pids from being killed via the cgroup */
1890 if (s->main_pid > 0)
1891 if ((r = set_put(pid_set, LONG_TO_PTR(s->main_pid))) < 0)
1894 if (s->control_pid > 0)
1895 if ((r = set_put(pid_set, LONG_TO_PTR(s->control_pid))) < 0)
1898 if ((r = cgroup_bonding_kill_list(s->meta.cgroup_bondings, sig, true, pid_set)) < 0) {
1899 if (r != -EAGAIN && r != -ESRCH && r != -ENOENT)
1900 log_warning("Failed to kill control group: %s", strerror(-r));
1902 wait_for_exit = true;
1909 if (wait_for_exit) {
1910 if (s->timeout_usec > 0)
1911 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1914 service_set_state(s, state);
1915 } else if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1916 service_enter_stop_post(s, true);
1918 service_enter_dead(s, true, true);
1923 log_warning("%s failed to kill processes: %s", s->meta.id, strerror(-r));
1925 if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1926 service_enter_stop_post(s, false);
1928 service_enter_dead(s, false, true);
1934 static void service_enter_stop(Service *s, bool success) {
1942 service_unwatch_control_pid(s);
1944 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP])) {
1945 s->control_command_id = SERVICE_EXEC_STOP;
1947 if ((r = service_spawn(s,
1951 !s->permissions_start_only,
1952 !s->root_directory_start_only,
1955 &s->control_pid)) < 0)
1958 service_set_state(s, SERVICE_STOP);
1960 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
1965 log_warning("%s failed to run 'stop' task: %s", s->meta.id, strerror(-r));
1966 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1969 static void service_enter_running(Service *s, bool success) {
1970 int main_pid_ok, cgroup_ok;
1976 main_pid_ok = main_pid_good(s);
1977 cgroup_ok = cgroup_good(s);
1979 if ((main_pid_ok > 0 || (main_pid_ok < 0 && cgroup_ok != 0)) &&
1980 (s->bus_name_good || s->type != SERVICE_DBUS))
1981 service_set_state(s, SERVICE_RUNNING);
1982 else if (s->remain_after_exit)
1983 service_set_state(s, SERVICE_EXITED);
1985 service_enter_stop(s, true);
1988 static void service_enter_start_post(Service *s) {
1992 service_unwatch_control_pid(s);
1994 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_POST])) {
1995 s->control_command_id = SERVICE_EXEC_START_POST;
1997 if ((r = service_spawn(s,
2001 !s->permissions_start_only,
2002 !s->root_directory_start_only,
2005 &s->control_pid)) < 0)
2008 service_set_state(s, SERVICE_START_POST);
2010 service_enter_running(s, true);
2015 log_warning("%s failed to run 'start-post' task: %s", s->meta.id, strerror(-r));
2016 service_enter_stop(s, false);
2019 static void service_enter_start(Service *s) {
2026 assert(s->exec_command[SERVICE_EXEC_START]);
2027 assert(!s->exec_command[SERVICE_EXEC_START]->command_next || s->type == SERVICE_ONESHOT);
2029 if (s->type == SERVICE_FORKING)
2030 service_unwatch_control_pid(s);
2032 service_unwatch_main_pid(s);
2034 if (s->type == SERVICE_FORKING) {
2035 s->control_command_id = SERVICE_EXEC_START;
2036 c = s->control_command = s->exec_command[SERVICE_EXEC_START];
2038 s->main_command = NULL;
2040 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2041 s->control_command = NULL;
2043 c = s->main_command = s->exec_command[SERVICE_EXEC_START];
2046 if ((r = service_spawn(s,
2048 s->type == SERVICE_FORKING || s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY,
2053 s->notify_access != NOTIFY_NONE,
2057 if (s->type == SERVICE_SIMPLE) {
2058 /* For simple services we immediately start
2059 * the START_POST binaries. */
2061 service_set_main_pid(s, pid);
2062 service_enter_start_post(s);
2064 } else if (s->type == SERVICE_FORKING) {
2066 /* For forking services we wait until the start
2067 * process exited. */
2069 s->control_pid = pid;
2070 service_set_state(s, SERVICE_START);
2072 } else if (s->type == SERVICE_ONESHOT ||
2073 s->type == SERVICE_DBUS ||
2074 s->type == SERVICE_NOTIFY) {
2076 /* For oneshot services we wait until the start
2077 * process exited, too, but it is our main process. */
2079 /* For D-Bus services we know the main pid right away,
2080 * but wait for the bus name to appear on the
2081 * bus. Notify services are similar. */
2083 service_set_main_pid(s, pid);
2084 service_set_state(s, SERVICE_START);
2086 assert_not_reached("Unknown service type");
2091 log_warning("%s failed to run 'start' task: %s", s->meta.id, strerror(-r));
2092 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2095 static void service_enter_start_pre(Service *s) {
2100 service_unwatch_control_pid(s);
2102 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_PRE])) {
2103 s->control_command_id = SERVICE_EXEC_START_PRE;
2105 if ((r = service_spawn(s,
2109 !s->permissions_start_only,
2110 !s->root_directory_start_only,
2113 &s->control_pid)) < 0)
2116 service_set_state(s, SERVICE_START_PRE);
2118 service_enter_start(s);
2123 log_warning("%s failed to run 'start-pre' task: %s", s->meta.id, strerror(-r));
2124 service_enter_dead(s, false, true);
2127 static void service_enter_restart(Service *s) {
2132 dbus_error_init(&error);
2135 log_info("Job pending for unit, delaying automatic restart.");
2137 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
2141 service_enter_dead(s, true, false);
2143 if ((r = manager_add_job(s->meta.manager, JOB_START, UNIT(s), JOB_FAIL, false, &error, NULL)) < 0)
2146 log_debug("%s scheduled restart job.", s->meta.id);
2150 log_warning("%s failed to schedule restart job: %s", s->meta.id, bus_error(&error, -r));
2151 service_enter_dead(s, false, false);
2153 dbus_error_free(&error);
2156 static void service_enter_reload(Service *s) {
2161 service_unwatch_control_pid(s);
2163 if ((s->control_command = s->exec_command[SERVICE_EXEC_RELOAD])) {
2164 s->control_command_id = SERVICE_EXEC_RELOAD;
2166 if ((r = service_spawn(s,
2170 !s->permissions_start_only,
2171 !s->root_directory_start_only,
2174 &s->control_pid)) < 0)
2177 service_set_state(s, SERVICE_RELOAD);
2179 service_enter_running(s, true);
2184 log_warning("%s failed to run 'reload' task: %s", s->meta.id, strerror(-r));
2185 s->reload_failure = true;
2186 service_enter_running(s, true);
2189 static void service_run_next_control(Service *s, bool success) {
2193 assert(s->control_command);
2194 assert(s->control_command->command_next);
2199 assert(s->control_command_id != SERVICE_EXEC_START);
2201 s->control_command = s->control_command->command_next;
2202 service_unwatch_control_pid(s);
2204 if ((r = service_spawn(s,
2208 !s->permissions_start_only,
2209 !s->root_directory_start_only,
2210 s->control_command_id == SERVICE_EXEC_START_PRE ||
2211 s->control_command_id == SERVICE_EXEC_STOP_POST,
2213 &s->control_pid)) < 0)
2219 log_warning("%s failed to run next control task: %s", s->meta.id, strerror(-r));
2221 if (s->state == SERVICE_START_PRE)
2222 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2223 else if (s->state == SERVICE_STOP)
2224 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
2225 else if (s->state == SERVICE_STOP_POST)
2226 service_enter_dead(s, false, true);
2227 else if (s->state == SERVICE_RELOAD) {
2228 s->reload_failure = true;
2229 service_enter_running(s, true);
2231 service_enter_stop(s, false);
2234 static void service_run_next_main(Service *s, bool success) {
2239 assert(s->main_command);
2240 assert(s->main_command->command_next);
2241 assert(s->type == SERVICE_ONESHOT);
2246 s->main_command = s->main_command->command_next;
2247 service_unwatch_main_pid(s);
2249 if ((r = service_spawn(s,
2256 s->notify_access != NOTIFY_NONE,
2260 service_set_main_pid(s, pid);
2265 log_warning("%s failed to run next main task: %s", s->meta.id, strerror(-r));
2266 service_enter_stop(s, false);
2269 static int service_start(Unit *u) {
2270 Service *s = SERVICE(u);
2274 /* We cannot fulfill this request right now, try again later
2276 if (s->state == SERVICE_STOP ||
2277 s->state == SERVICE_STOP_SIGTERM ||
2278 s->state == SERVICE_STOP_SIGKILL ||
2279 s->state == SERVICE_STOP_POST ||
2280 s->state == SERVICE_FINAL_SIGTERM ||
2281 s->state == SERVICE_FINAL_SIGKILL)
2284 /* Already on it! */
2285 if (s->state == SERVICE_START_PRE ||
2286 s->state == SERVICE_START ||
2287 s->state == SERVICE_START_POST)
2290 assert(s->state == SERVICE_DEAD || s->state == SERVICE_FAILED || s->state == SERVICE_AUTO_RESTART);
2292 /* Make sure we don't enter a busy loop of some kind. */
2293 if (!ratelimit_test(&s->ratelimit)) {
2294 log_warning("%s start request repeated too quickly, refusing to start.", u->meta.id);
2299 s->main_pid_known = false;
2300 s->main_pid_alien = false;
2301 s->forbid_restart = false;
2303 service_enter_start_pre(s);
2307 static int service_stop(Unit *u) {
2308 Service *s = SERVICE(u);
2312 /* This is a user request, so don't do restarts on this
2314 s->forbid_restart = true;
2317 if (s->state == SERVICE_STOP ||
2318 s->state == SERVICE_STOP_SIGTERM ||
2319 s->state == SERVICE_STOP_SIGKILL ||
2320 s->state == SERVICE_STOP_POST ||
2321 s->state == SERVICE_FINAL_SIGTERM ||
2322 s->state == SERVICE_FINAL_SIGKILL)
2325 /* Don't allow a restart */
2326 if (s->state == SERVICE_AUTO_RESTART) {
2327 service_set_state(s, SERVICE_DEAD);
2331 /* If there's already something running we go directly into
2333 if (s->state == SERVICE_START_PRE ||
2334 s->state == SERVICE_START ||
2335 s->state == SERVICE_START_POST ||
2336 s->state == SERVICE_RELOAD) {
2337 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
2341 assert(s->state == SERVICE_RUNNING ||
2342 s->state == SERVICE_EXITED);
2344 service_enter_stop(s, true);
2348 static int service_reload(Unit *u) {
2349 Service *s = SERVICE(u);
2353 assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
2355 service_enter_reload(s);
2359 static bool service_can_reload(Unit *u) {
2360 Service *s = SERVICE(u);
2364 return !!s->exec_command[SERVICE_EXEC_RELOAD];
2367 static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
2368 Service *s = SERVICE(u);
2374 unit_serialize_item(u, f, "state", service_state_to_string(s->state));
2375 unit_serialize_item(u, f, "failure", yes_no(s->failure));
2377 if (s->control_pid > 0)
2378 unit_serialize_item_format(u, f, "control-pid", "%lu", (unsigned long) s->control_pid);
2380 if (s->main_pid_known && s->main_pid > 0)
2381 unit_serialize_item_format(u, f, "main-pid", "%lu", (unsigned long) s->main_pid);
2383 unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
2386 unit_serialize_item(u, f, "status-text", s->status_text);
2388 /* There's a minor uncleanliness here: if there are multiple
2389 * commands attached here, we will start from the first one
2391 if (s->control_command_id >= 0)
2392 unit_serialize_item(u, f, "control-command", service_exec_command_to_string(s->control_command_id));
2394 if (s->socket_fd >= 0) {
2397 if ((copy = fdset_put_dup(fds, s->socket_fd)) < 0)
2400 unit_serialize_item_format(u, f, "socket-fd", "%i", copy);
2403 if (s->main_exec_status.pid > 0) {
2404 unit_serialize_item_format(u, f, "main-exec-status-pid", "%lu", (unsigned long) s->main_exec_status.pid);
2405 dual_timestamp_serialize(f, "main-exec-status-start", &s->main_exec_status.start_timestamp);
2406 dual_timestamp_serialize(f, "main-exec-status-exit", &s->main_exec_status.exit_timestamp);
2408 if (dual_timestamp_is_set(&s->main_exec_status.exit_timestamp)) {
2409 unit_serialize_item_format(u, f, "main-exec-status-code", "%i", s->main_exec_status.code);
2410 unit_serialize_item_format(u, f, "main-exec-status-status", "%i", s->main_exec_status.status);
2417 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
2418 Service *s = SERVICE(u);
2425 if (streq(key, "state")) {
2428 if ((state = service_state_from_string(value)) < 0)
2429 log_debug("Failed to parse state value %s", value);
2431 s->deserialized_state = state;
2432 } else if (streq(key, "failure")) {
2435 if ((b = parse_boolean(value)) < 0)
2436 log_debug("Failed to parse failure value %s", value);
2438 s->failure = b || s->failure;
2439 } else if (streq(key, "control-pid")) {
2442 if (parse_pid(value, &pid) < 0)
2443 log_debug("Failed to parse control-pid value %s", value);
2445 s->control_pid = pid;
2446 } else if (streq(key, "main-pid")) {
2449 if (parse_pid(value, &pid) < 0)
2450 log_debug("Failed to parse main-pid value %s", value);
2452 service_set_main_pid(s, (pid_t) pid);
2453 } else if (streq(key, "main-pid-known")) {
2456 if ((b = parse_boolean(value)) < 0)
2457 log_debug("Failed to parse main-pid-known value %s", value);
2459 s->main_pid_known = b;
2460 } else if (streq(key, "status-text")) {
2463 if ((t = strdup(value))) {
2464 free(s->status_text);
2468 } else if (streq(key, "control-command")) {
2469 ServiceExecCommand id;
2471 if ((id = service_exec_command_from_string(value)) < 0)
2472 log_debug("Failed to parse exec-command value %s", value);
2474 s->control_command_id = id;
2475 s->control_command = s->exec_command[id];
2477 } else if (streq(key, "socket-fd")) {
2480 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2481 log_debug("Failed to parse socket-fd value %s", value);
2484 if (s->socket_fd >= 0)
2485 close_nointr_nofail(s->socket_fd);
2486 s->socket_fd = fdset_remove(fds, fd);
2488 } else if (streq(key, "main-exec-status-pid")) {
2491 if (parse_pid(value, &pid) < 0)
2492 log_debug("Failed to parse main-exec-status-pid value %s", value);
2494 s->main_exec_status.pid = pid;
2495 } else if (streq(key, "main-exec-status-code")) {
2498 if (safe_atoi(value, &i) < 0)
2499 log_debug("Failed to parse main-exec-status-code value %s", value);
2501 s->main_exec_status.code = i;
2502 } else if (streq(key, "main-exec-status-status")) {
2505 if (safe_atoi(value, &i) < 0)
2506 log_debug("Failed to parse main-exec-status-status value %s", value);
2508 s->main_exec_status.status = i;
2509 } else if (streq(key, "main-exec-status-start"))
2510 dual_timestamp_deserialize(value, &s->main_exec_status.start_timestamp);
2511 else if (streq(key, "main-exec-status-exit"))
2512 dual_timestamp_deserialize(value, &s->main_exec_status.exit_timestamp);
2514 log_debug("Unknown serialization key '%s'", key);
2519 static UnitActiveState service_active_state(Unit *u) {
2522 return state_translation_table[SERVICE(u)->state];
2525 static const char *service_sub_state_to_string(Unit *u) {
2528 return service_state_to_string(SERVICE(u)->state);
2531 static bool service_check_gc(Unit *u) {
2532 Service *s = SERVICE(u);
2536 /* Never clean up services that still have a process around,
2537 * even if the service is formally dead. */
2538 if (cgroup_good(s) > 0 ||
2539 main_pid_good(s) > 0 ||
2540 control_pid_good(s) > 0)
2543 #ifdef HAVE_SYSV_COMPAT
2551 static bool service_check_snapshot(Unit *u) {
2552 Service *s = SERVICE(u);
2556 return !s->got_socket_fd;
2559 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2560 Service *s = SERVICE(u);
2566 if (!s->meta.fragment_path)
2567 success = is_clean_exit_lsb(code, status);
2569 success = is_clean_exit(code, status);
2571 if (s->main_pid == pid) {
2574 exec_status_exit(&s->main_exec_status, &s->exec_context, pid, code, status);
2576 /* If this is not a forking service than the main
2577 * process got started and hence we copy the exit
2578 * status so that it is recorded both as main and as
2579 * control process exit status */
2580 if (s->main_command) {
2581 s->main_command->exec_status = s->main_exec_status;
2583 if (s->main_command->ignore)
2587 log_full(success ? LOG_DEBUG : LOG_NOTICE,
2588 "%s: main process exited, code=%s, status=%i", u->meta.id, sigchld_code_to_string(code), status);
2589 s->failure = s->failure || !success;
2591 if (s->main_command &&
2592 s->main_command->command_next &&
2595 /* There is another command to *
2596 * execute, so let's do that. */
2598 log_debug("%s running next main command for state %s", u->meta.id, service_state_to_string(s->state));
2599 service_run_next_main(s, success);
2603 /* The service exited, so the service is officially
2605 s->main_command = NULL;
2609 case SERVICE_START_POST:
2610 case SERVICE_RELOAD:
2612 /* Need to wait until the operation is
2617 if (s->type == SERVICE_ONESHOT) {
2618 /* This was our main goal, so let's go on */
2620 service_enter_start_post(s);
2622 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2625 assert(s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY);
2630 case SERVICE_RUNNING:
2631 service_enter_running(s, success);
2634 case SERVICE_STOP_SIGTERM:
2635 case SERVICE_STOP_SIGKILL:
2637 if (!control_pid_good(s))
2638 service_enter_stop_post(s, success);
2640 /* If there is still a control process, wait for that first */
2644 assert_not_reached("Uh, main process died at wrong time.");
2648 } else if (s->control_pid == pid) {
2652 if (s->control_command) {
2653 exec_status_exit(&s->control_command->exec_status, &s->exec_context, pid, code, status);
2655 if (s->control_command->ignore)
2659 log_full(success ? LOG_DEBUG : LOG_NOTICE,
2660 "%s: control process exited, code=%s status=%i", u->meta.id, sigchld_code_to_string(code), status);
2661 s->failure = s->failure || !success;
2663 if (s->control_command &&
2664 s->control_command->command_next &&
2667 /* There is another command to *
2668 * execute, so let's do that. */
2670 log_debug("%s running next control command for state %s", u->meta.id, service_state_to_string(s->state));
2671 service_run_next_control(s, success);
2674 /* No further commands for this step, so let's
2675 * figure out what to do next */
2677 s->control_command = NULL;
2678 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2680 log_debug("%s got final SIGCHLD for state %s", u->meta.id, service_state_to_string(s->state));
2684 case SERVICE_START_PRE:
2686 service_enter_start(s);
2688 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2692 assert(s->type == SERVICE_FORKING);
2694 /* Let's try to load the pid
2695 * file here if we can. We
2696 * ignore the return value,
2697 * since the PID file might
2698 * actually be created by a
2699 * START_POST script */
2702 service_load_pid_file(s);
2703 service_search_main_pid(s);
2705 service_enter_start_post(s);
2707 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2711 case SERVICE_START_POST:
2713 service_load_pid_file(s);
2714 service_search_main_pid(s);
2717 s->reload_failure = !success;
2718 service_enter_running(s, true);
2721 case SERVICE_RELOAD:
2723 service_load_pid_file(s);
2724 service_search_main_pid(s);
2727 s->reload_failure = !success;
2728 service_enter_running(s, true);
2732 service_enter_signal(s, SERVICE_STOP_SIGTERM, success);
2735 case SERVICE_STOP_SIGTERM:
2736 case SERVICE_STOP_SIGKILL:
2737 if (main_pid_good(s) <= 0)
2738 service_enter_stop_post(s, success);
2740 /* If there is still a service
2741 * process around, wait until
2742 * that one quit, too */
2745 case SERVICE_STOP_POST:
2746 case SERVICE_FINAL_SIGTERM:
2747 case SERVICE_FINAL_SIGKILL:
2748 service_enter_dead(s, success, true);
2752 assert_not_reached("Uh, control process died at wrong time.");
2757 /* Notify clients about changed exit status */
2758 unit_add_to_dbus_queue(u);
2761 static void service_timer_event(Unit *u, uint64_t elapsed, Watch* w) {
2762 Service *s = SERVICE(u);
2765 assert(elapsed == 1);
2767 assert(w == &s->timer_watch);
2771 case SERVICE_START_PRE:
2773 log_warning("%s operation timed out. Terminating.", u->meta.id);
2774 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2777 case SERVICE_START_POST:
2778 log_warning("%s operation timed out. Stopping.", u->meta.id);
2779 service_enter_stop(s, false);
2782 case SERVICE_RELOAD:
2783 log_warning("%s operation timed out. Stopping.", u->meta.id);
2784 s->reload_failure = true;
2785 service_enter_running(s, true);
2789 log_warning("%s stopping timed out. Terminating.", u->meta.id);
2790 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
2793 case SERVICE_STOP_SIGTERM:
2794 if (s->exec_context.send_sigkill) {
2795 log_warning("%s stopping timed out. Killing.", u->meta.id);
2796 service_enter_signal(s, SERVICE_STOP_SIGKILL, false);
2798 log_warning("%s stopping timed out. Skipping SIGKILL.", u->meta.id);
2799 service_enter_stop_post(s, false);
2804 case SERVICE_STOP_SIGKILL:
2805 /* Uh, we sent a SIGKILL and it is still not gone?
2806 * Must be something we cannot kill, so let's just be
2807 * weirded out and continue */
2809 log_warning("%s still around after SIGKILL. Ignoring.", u->meta.id);
2810 service_enter_stop_post(s, false);
2813 case SERVICE_STOP_POST:
2814 log_warning("%s stopping timed out (2). Terminating.", u->meta.id);
2815 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2818 case SERVICE_FINAL_SIGTERM:
2819 if (s->exec_context.send_sigkill) {
2820 log_warning("%s stopping timed out (2). Killing.", u->meta.id);
2821 service_enter_signal(s, SERVICE_FINAL_SIGKILL, false);
2823 log_warning("%s stopping timed out (2). Skipping SIGKILL. Entering failed mode.", u->meta.id);
2824 service_enter_dead(s, false, true);
2829 case SERVICE_FINAL_SIGKILL:
2830 log_warning("%s still around after SIGKILL (2). Entering failed mode.", u->meta.id);
2831 service_enter_dead(s, false, true);
2834 case SERVICE_AUTO_RESTART:
2835 log_info("%s holdoff time over, scheduling restart.", u->meta.id);
2836 service_enter_restart(s);
2840 assert_not_reached("Timeout at wrong time.");
2844 static void service_cgroup_notify_event(Unit *u) {
2845 Service *s = SERVICE(u);
2849 log_debug("%s: cgroup is empty", u->meta.id);
2853 /* Waiting for SIGCHLD is usually more interesting,
2854 * because it includes return codes/signals. Which is
2855 * why we ignore the cgroup events for most cases,
2856 * except when we don't know pid which to expect the
2859 case SERVICE_RUNNING:
2860 service_enter_running(s, true);
2863 case SERVICE_STOP_SIGTERM:
2864 case SERVICE_STOP_SIGKILL:
2866 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2867 service_enter_stop_post(s, true);
2871 case SERVICE_FINAL_SIGTERM:
2872 case SERVICE_FINAL_SIGKILL:
2873 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2874 service_enter_dead(s, true, true);
2883 static void service_notify_message(Unit *u, pid_t pid, char **tags) {
2884 Service *s = SERVICE(u);
2889 if (s->notify_access == NOTIFY_NONE) {
2890 log_warning("%s: Got notification message from PID %lu, but reception is disabled.",
2891 u->meta.id, (unsigned long) pid);
2895 if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
2896 log_warning("%s: Got notification message from PID %lu, but reception only permitted for PID %lu",
2897 u->meta.id, (unsigned long) pid, (unsigned long) s->main_pid);
2901 log_debug("%s: Got message", u->meta.id);
2903 /* Interpret MAINPID= */
2904 if ((e = strv_find_prefix(tags, "MAINPID=")) &&
2905 (s->state == SERVICE_START ||
2906 s->state == SERVICE_START_POST ||
2907 s->state == SERVICE_RUNNING ||
2908 s->state == SERVICE_RELOAD)) {
2910 if (parse_pid(e + 8, &pid) < 0)
2911 log_warning("Failed to parse notification message %s", e);
2913 log_debug("%s: got %s", u->meta.id, e);
2914 service_set_main_pid(s, pid);
2918 /* Interpret READY= */
2919 if (s->type == SERVICE_NOTIFY &&
2920 s->state == SERVICE_START &&
2921 strv_find(tags, "READY=1")) {
2922 log_debug("%s: got READY=1", u->meta.id);
2924 service_enter_start_post(s);
2927 /* Interpret STATUS= */
2928 if ((e = strv_find_prefix(tags, "STATUS="))) {
2932 if (!(t = strdup(e+7))) {
2933 log_error("Failed to allocate string.");
2937 log_debug("%s: got %s", u->meta.id, e);
2939 free(s->status_text);
2942 free(s->status_text);
2943 s->status_text = NULL;
2948 /* Notify clients about changed status or main pid */
2949 unit_add_to_dbus_queue(u);
2952 #ifdef HAVE_SYSV_COMPAT
2953 static int service_enumerate(Manager *m) {
2957 char *path = NULL, *fpath = NULL, *name = NULL;
2958 Set *runlevel_services[ELEMENTSOF(rcnd_table)], *shutdown_services = NULL;
2965 zero(runlevel_services);
2967 STRV_FOREACH(p, m->lookup_paths.sysvrcnd_path)
2968 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++) {
2973 if (asprintf(&path, "%s/%s", *p, rcnd_table[i].path) < 0) {
2981 if (!(d = opendir(path))) {
2982 if (errno != ENOENT)
2983 log_warning("opendir() failed on %s: %s", path, strerror(errno));
2988 while ((de = readdir(d))) {
2991 if (ignore_file(de->d_name))
2994 if (de->d_name[0] != 'S' && de->d_name[0] != 'K')
2997 if (strlen(de->d_name) < 4)
3000 a = undecchar(de->d_name[1]);
3001 b = undecchar(de->d_name[2]);
3008 if (asprintf(&fpath, "%s/%s/%s", *p, rcnd_table[i].path, de->d_name) < 0) {
3013 if (access(fpath, X_OK) < 0) {
3015 if (errno != ENOENT)
3016 log_warning("access() failed on %s: %s", fpath, strerror(errno));
3022 if (!(name = sysv_translate_name(de->d_name + 3))) {
3027 if ((r = manager_load_unit_prepare(m, name, NULL, NULL, &service)) < 0) {
3028 log_warning("Failed to prepare unit %s: %s", name, strerror(-r));
3032 if (de->d_name[0] == 'S') {
3034 if (rcnd_table[i].type == RUNLEVEL_UP || rcnd_table[i].type == RUNLEVEL_SYSINIT) {
3035 SERVICE(service)->sysv_start_priority_from_rcnd =
3036 MAX(a*10 + b, SERVICE(service)->sysv_start_priority_from_rcnd);
3038 SERVICE(service)->sysv_enabled = true;
3041 if ((r = set_ensure_allocated(&runlevel_services[i], trivial_hash_func, trivial_compare_func)) < 0)
3044 if ((r = set_put(runlevel_services[i], service)) < 0)
3047 } else if (de->d_name[0] == 'K' &&
3048 (rcnd_table[i].type == RUNLEVEL_DOWN ||
3049 rcnd_table[i].type == RUNLEVEL_SYSINIT)) {
3051 if ((r = set_ensure_allocated(&shutdown_services, trivial_hash_func, trivial_compare_func)) < 0)
3054 if ((r = set_put(shutdown_services, service)) < 0)
3060 /* Now we loaded all stubs and are aware of the lowest
3061 start-up priority for all services, not let's actually load
3062 the services, this will also tell us which services are
3063 actually native now */
3064 manager_dispatch_load_queue(m);
3066 /* If this is a native service, rely on native ways to pull in
3067 * a service, don't pull it in via sysv rcN.d links. */
3068 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++)
3069 SET_FOREACH(service, runlevel_services[i], j) {
3070 service = unit_follow_merge(service);
3072 if (service->meta.fragment_path)
3075 if ((r = unit_add_two_dependencies_by_name_inverse(service, UNIT_AFTER, UNIT_WANTS, rcnd_table[i].target, NULL, true)) < 0)
3079 /* We honour K links only for halt/reboot. For the normal
3080 * runlevels we assume the stop jobs will be implicitly added
3081 * by the core logic. Also, we don't really distinguish here
3082 * between the runlevels 0 and 6 and just add them to the
3083 * special shutdown target. On SUSE the boot.d/ runlevel is
3084 * also used for shutdown, so we add links for that too to the
3085 * shutdown target.*/
3086 SET_FOREACH(service, shutdown_services, j) {
3087 service = unit_follow_merge(service);
3089 if (service->meta.fragment_path)
3092 if ((r = unit_add_two_dependencies_by_name(service, UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true)) < 0)
3103 for (i = 0; i < ELEMENTSOF(rcnd_table); i++)
3104 set_free(runlevel_services[i]);
3105 set_free(shutdown_services);
3114 static void service_bus_name_owner_change(
3117 const char *old_owner,
3118 const char *new_owner) {
3120 Service *s = SERVICE(u);
3125 assert(streq(s->bus_name, name));
3126 assert(old_owner || new_owner);
3128 if (old_owner && new_owner)
3129 log_debug("%s's D-Bus name %s changed owner from %s to %s", u->meta.id, name, old_owner, new_owner);
3131 log_debug("%s's D-Bus name %s no longer registered by %s", u->meta.id, name, old_owner);
3133 log_debug("%s's D-Bus name %s now registered by %s", u->meta.id, name, new_owner);
3135 s->bus_name_good = !!new_owner;
3137 if (s->type == SERVICE_DBUS) {
3139 /* service_enter_running() will figure out what to
3141 if (s->state == SERVICE_RUNNING)
3142 service_enter_running(s, true);
3143 else if (s->state == SERVICE_START && new_owner)
3144 service_enter_start_post(s);
3146 } else if (new_owner &&
3148 (s->state == SERVICE_START ||
3149 s->state == SERVICE_START_POST ||
3150 s->state == SERVICE_RUNNING ||
3151 s->state == SERVICE_RELOAD)) {
3153 /* Try to acquire PID from bus service */
3154 log_debug("Trying to acquire PID from D-Bus name...");
3156 bus_query_pid(u->meta.manager, name);
3160 static void service_bus_query_pid_done(
3165 Service *s = SERVICE(u);
3170 log_debug("%s's D-Bus name %s is now owned by process %u", u->meta.id, name, (unsigned) pid);
3172 if (s->main_pid <= 0 &&
3173 (s->state == SERVICE_START ||
3174 s->state == SERVICE_START_POST ||
3175 s->state == SERVICE_RUNNING ||
3176 s->state == SERVICE_RELOAD))
3177 service_set_main_pid(s, pid);
3180 int service_set_socket_fd(Service *s, int fd, Socket *sock) {
3184 /* This is called by the socket code when instantiating a new
3185 * service for a stream socket and the socket needs to be
3188 if (s->meta.load_state != UNIT_LOADED)
3191 if (s->socket_fd >= 0)
3194 if (s->state != SERVICE_DEAD)
3198 s->got_socket_fd = true;
3199 s->accept_socket = sock;
3204 static void service_reset_failed(Unit *u) {
3205 Service *s = SERVICE(u);
3209 if (s->state == SERVICE_FAILED)
3210 service_set_state(s, SERVICE_DEAD);
3215 static int service_kill(Unit *u, KillWho who, KillMode mode, int signo, DBusError *error) {
3216 Service *s = SERVICE(u);
3218 Set *pid_set = NULL;
3222 if (s->main_pid <= 0 && who == KILL_MAIN) {
3223 dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "No main process to kill");
3227 if (s->control_pid <= 0 && who == KILL_CONTROL) {
3228 dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "No control process to kill");
3232 if (s->control_pid > 0)
3233 if (kill(s->control_pid, signo) < 0)
3236 if (s->main_pid > 0)
3237 if (kill(s->main_pid, signo) < 0)
3240 if (mode == KILL_CONTROL_GROUP) {
3243 if (!(pid_set = set_new(trivial_hash_func, trivial_compare_func)))
3246 /* Exclude the control/main pid from being killed via the cgroup */
3247 if (s->control_pid > 0)
3248 if ((q = set_put(pid_set, LONG_TO_PTR(s->control_pid))) < 0) {
3253 if (s->main_pid > 0)
3254 if ((q = set_put(pid_set, LONG_TO_PTR(s->main_pid))) < 0) {
3259 if ((q = cgroup_bonding_kill_list(s->meta.cgroup_bondings, signo, false, pid_set)) < 0)
3260 if (r != -EAGAIN && r != -ESRCH && r != -ENOENT)
3271 static const char* const service_state_table[_SERVICE_STATE_MAX] = {
3272 [SERVICE_DEAD] = "dead",
3273 [SERVICE_START_PRE] = "start-pre",
3274 [SERVICE_START] = "start",
3275 [SERVICE_START_POST] = "start-post",
3276 [SERVICE_RUNNING] = "running",
3277 [SERVICE_EXITED] = "exited",
3278 [SERVICE_RELOAD] = "reload",
3279 [SERVICE_STOP] = "stop",
3280 [SERVICE_STOP_SIGTERM] = "stop-sigterm",
3281 [SERVICE_STOP_SIGKILL] = "stop-sigkill",
3282 [SERVICE_STOP_POST] = "stop-post",
3283 [SERVICE_FINAL_SIGTERM] = "final-sigterm",
3284 [SERVICE_FINAL_SIGKILL] = "final-sigkill",
3285 [SERVICE_FAILED] = "failed",
3286 [SERVICE_AUTO_RESTART] = "auto-restart",
3289 DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
3291 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
3292 [SERVICE_RESTART_NO] = "no",
3293 [SERVICE_RESTART_ON_SUCCESS] = "on-success",
3294 [SERVICE_RESTART_ON_FAILURE] = "on-failure",
3295 [SERVICE_RESTART_ON_ABORT] = "on-abort",
3296 [SERVICE_RESTART_ALWAYS] = "always"
3299 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
3301 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
3302 [SERVICE_SIMPLE] = "simple",
3303 [SERVICE_FORKING] = "forking",
3304 [SERVICE_ONESHOT] = "oneshot",
3305 [SERVICE_DBUS] = "dbus",
3306 [SERVICE_NOTIFY] = "notify"
3309 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
3311 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
3312 [SERVICE_EXEC_START_PRE] = "ExecStartPre",
3313 [SERVICE_EXEC_START] = "ExecStart",
3314 [SERVICE_EXEC_START_POST] = "ExecStartPost",
3315 [SERVICE_EXEC_RELOAD] = "ExecReload",
3316 [SERVICE_EXEC_STOP] = "ExecStop",
3317 [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
3320 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
3322 static const char* const notify_access_table[_NOTIFY_ACCESS_MAX] = {
3323 [NOTIFY_NONE] = "none",
3324 [NOTIFY_MAIN] = "main",
3325 [NOTIFY_ALL] = "all"
3328 DEFINE_STRING_TABLE_LOOKUP(notify_access, NotifyAccess);
3330 const UnitVTable service_vtable = {
3331 .suffix = ".service",
3332 .show_status = true,
3334 .init = service_init,
3335 .done = service_done,
3336 .load = service_load,
3338 .coldplug = service_coldplug,
3340 .dump = service_dump,
3342 .start = service_start,
3343 .stop = service_stop,
3344 .reload = service_reload,
3346 .can_reload = service_can_reload,
3348 .kill = service_kill,
3350 .serialize = service_serialize,
3351 .deserialize_item = service_deserialize_item,
3353 .active_state = service_active_state,
3354 .sub_state_to_string = service_sub_state_to_string,
3356 .check_gc = service_check_gc,
3357 .check_snapshot = service_check_snapshot,
3359 .sigchld_event = service_sigchld_event,
3360 .timer_event = service_timer_event,
3362 .reset_failed = service_reset_failed,
3364 .cgroup_notify_empty = service_cgroup_notify_event,
3365 .notify_message = service_notify_message,
3367 .bus_name_owner_change = service_bus_name_owner_change,
3368 .bus_query_pid_done = service_bus_query_pid_done,
3370 .bus_interface = "org.freedesktop.systemd1.Service",
3371 .bus_message_handler = bus_service_message_handler,
3372 .bus_invalidating_properties = bus_service_invalidating_properties,
3374 #ifdef HAVE_SYSV_COMPAT
3375 .enumerate = service_enumerate