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"
39 #define COMMENTS "#;\n"
40 #define NEWLINES "\n\r"
42 #ifdef HAVE_SYSV_COMPAT
44 #define DEFAULT_SYSV_TIMEOUT_USEC (3*USEC_PER_MINUTE)
46 typedef enum RunlevelType {
55 const RunlevelType type;
57 /* Standard SysV runlevels for start-up */
58 { "rc1.d", SPECIAL_RESCUE_TARGET, RUNLEVEL_UP },
59 { "rc2.d", SPECIAL_RUNLEVEL2_TARGET, RUNLEVEL_UP },
60 { "rc3.d", SPECIAL_RUNLEVEL3_TARGET, RUNLEVEL_UP },
61 { "rc4.d", SPECIAL_RUNLEVEL4_TARGET, RUNLEVEL_UP },
62 { "rc5.d", SPECIAL_RUNLEVEL5_TARGET, RUNLEVEL_UP },
65 /* SUSE style boot.d */
66 { "boot.d", SPECIAL_SYSINIT_TARGET, RUNLEVEL_SYSINIT },
69 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU) || defined(TARGET_FRUGALWARE)
70 /* Debian style rcS.d */
71 { "rcS.d", SPECIAL_SYSINIT_TARGET, RUNLEVEL_SYSINIT },
74 /* Standard SysV runlevels for shutdown */
75 { "rc0.d", SPECIAL_POWEROFF_TARGET, RUNLEVEL_DOWN },
76 { "rc6.d", SPECIAL_REBOOT_TARGET, RUNLEVEL_DOWN }
78 /* Note that the order here matters, as we read the
79 directories in this order, and we want to make sure that
80 sysv_start_priority is known when we first load the
81 unit. And that value we only know from S links. Hence
82 UP/SYSINIT must be read before DOWN */
85 #define RUNLEVELS_UP "12345"
86 /* #define RUNLEVELS_DOWN "06" */
87 /* #define RUNLEVELS_BOOT "bBsS" */
90 static const UnitActiveState state_translation_table[_SERVICE_STATE_MAX] = {
91 [SERVICE_DEAD] = UNIT_INACTIVE,
92 [SERVICE_START_PRE] = UNIT_ACTIVATING,
93 [SERVICE_START] = UNIT_ACTIVATING,
94 [SERVICE_START_POST] = UNIT_ACTIVATING,
95 [SERVICE_RUNNING] = UNIT_ACTIVE,
96 [SERVICE_EXITED] = UNIT_ACTIVE,
97 [SERVICE_RELOAD] = UNIT_RELOADING,
98 [SERVICE_STOP] = UNIT_DEACTIVATING,
99 [SERVICE_STOP_SIGTERM] = UNIT_DEACTIVATING,
100 [SERVICE_STOP_SIGKILL] = UNIT_DEACTIVATING,
101 [SERVICE_STOP_POST] = UNIT_DEACTIVATING,
102 [SERVICE_FINAL_SIGTERM] = UNIT_DEACTIVATING,
103 [SERVICE_FINAL_SIGKILL] = UNIT_DEACTIVATING,
104 [SERVICE_FAILED] = UNIT_FAILED,
105 [SERVICE_AUTO_RESTART] = UNIT_ACTIVATING
108 static void service_init(Unit *u) {
109 Service *s = SERVICE(u);
112 assert(u->meta.load_state == UNIT_STUB);
114 s->timeout_usec = DEFAULT_TIMEOUT_USEC;
115 s->restart_usec = DEFAULT_RESTART_USEC;
116 s->timer_watch.type = WATCH_INVALID;
117 #ifdef HAVE_SYSV_COMPAT
118 s->sysv_start_priority = -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) {
163 if (get_parent_of_pid(pid, &ppid) >= 0 && ppid != getpid())
164 log_warning("%s: Supervising process %lu which is not our child. We'll most likely not notice when it exits.",
165 s->meta.id, (unsigned long) pid);
168 s->main_pid_known = true;
170 exec_status_start(&s->main_exec_status, pid);
175 static void service_close_socket_fd(Service *s) {
178 if (s->socket_fd < 0)
181 close_nointr_nofail(s->socket_fd);
185 static void service_connection_unref(Service *s) {
188 if (!s->accept_socket)
191 socket_connection_unref(s->accept_socket);
192 s->accept_socket = NULL;
195 static void service_done(Unit *u) {
196 Service *s = SERVICE(u);
203 #ifdef HAVE_SYSV_COMPAT
207 free(s->sysv_runlevels);
208 s->sysv_runlevels = NULL;
211 free(s->status_text);
212 s->status_text = NULL;
214 exec_context_done(&s->exec_context);
215 exec_command_free_array(s->exec_command, _SERVICE_EXEC_COMMAND_MAX);
216 s->control_command = NULL;
217 s->main_command = NULL;
219 /* This will leak a process, but at least no memory or any of
221 service_unwatch_main_pid(s);
222 service_unwatch_control_pid(s);
225 unit_unwatch_bus_name(UNIT(u), s->bus_name);
230 service_close_socket_fd(s);
231 service_connection_unref(s);
233 set_free(s->configured_sockets);
235 unit_unwatch_timer(u, &s->timer_watch);
238 #ifdef HAVE_SYSV_COMPAT
239 static char *sysv_translate_name(const char *name) {
242 if (!(r = new(char, strlen(name) + sizeof(".service"))))
245 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU)
246 if (endswith(name, ".sh"))
247 /* Drop Debian-style .sh suffix */
248 strcpy(stpcpy(r, name) - 3, ".service");
251 if (startswith(name, "boot."))
252 /* Drop SuSE-style boot. prefix */
253 strcpy(stpcpy(r, name + 5), ".service");
255 #ifdef TARGET_FRUGALWARE
256 if (startswith(name, "rc."))
257 /* Drop Frugalware-style rc. prefix */
258 strcpy(stpcpy(r, name + 3), ".service");
261 /* Normal init scripts */
262 strcpy(stpcpy(r, name), ".service");
267 static int sysv_translate_facility(const char *name, const char *filename, char **_r) {
269 /* We silently ignore the $ prefix here. According to the LSB
270 * spec it simply indicates whether something is a
271 * standardized name or a distribution-specific one. Since we
272 * just follow what already exists and do not introduce new
273 * uses or names we don't care who introduced a new name. */
275 static const char * const table[] = {
276 /* LSB defined facilities */
277 "local_fs", SPECIAL_LOCAL_FS_TARGET,
278 #ifndef TARGET_MANDRIVA
279 /* Due to unfortunate name selection in Mandriva,
280 * $network is provided by network-up which is ordered
281 * after network which actually starts interfaces.
282 * To break the loop, just ignore it */
283 "network", SPECIAL_NETWORK_TARGET,
285 "named", SPECIAL_NSS_LOOKUP_TARGET,
286 "portmap", SPECIAL_RPCBIND_TARGET,
287 "remote_fs", SPECIAL_REMOTE_FS_TARGET,
288 "syslog", SPECIAL_SYSLOG_TARGET,
289 "time", SPECIAL_RTC_SET_TARGET,
291 /* common extensions */
292 "mail-transfer-agent", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
293 "x-display-manager", SPECIAL_DISPLAY_MANAGER_SERVICE,
296 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU)
297 "mail-transport-agent", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
301 "MTA", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
302 "smtpdaemon", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
303 "httpd", SPECIAL_HTTP_DAEMON_TARGET,
307 "smtp", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
318 n = *name == '$' ? name + 1 : name;
320 for (i = 0; i < ELEMENTSOF(table); i += 2) {
322 if (!streq(table[i], n))
328 if (!(r = strdup(table[i+1])))
334 /* If we don't know this name, fallback heuristics to figure
335 * out whether something is a target or a service alias. */
338 if (!unit_prefix_is_valid(n))
341 /* Facilities starting with $ are most likely targets */
342 r = unit_name_build(n, NULL, ".target");
343 } else if (filename && streq(name, filename))
344 /* Names equaling the file name of the services are redundant */
347 /* Everything else we assume to be normal service names */
348 r = sysv_translate_name(n);
359 static int sysv_fix_order(Service *s) {
365 if (s->sysv_start_priority < 0)
368 /* For each pair of services where at least one lacks a LSB
369 * header, we use the start priority value to order things. */
371 LIST_FOREACH(units_per_type, other, s->meta.manager->units_per_type[UNIT_SERVICE]) {
374 bool special_s, special_t;
376 t = (Service*) other;
381 if (t->meta.load_state != UNIT_LOADED)
384 if (t->sysv_start_priority < 0)
387 /* If both units have modern headers we don't care
388 * about the priorities */
389 if ((s->meta.fragment_path || s->sysv_has_lsb) &&
390 (t->meta.fragment_path || t->sysv_has_lsb))
393 special_s = s->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, s->sysv_runlevels);
394 special_t = t->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, t->sysv_runlevels);
396 if (special_t && !special_s)
398 else if (special_s && !special_t)
400 else if (t->sysv_start_priority < s->sysv_start_priority)
402 else if (t->sysv_start_priority > s->sysv_start_priority)
407 /* FIXME: Maybe we should compare the name here lexicographically? */
409 if (!(r = unit_add_dependency(UNIT(s), d, UNIT(t), true)) < 0)
416 static ExecCommand *exec_command_new(const char *path, const char *arg1) {
419 if (!(c = new0(ExecCommand, 1)))
422 if (!(c->path = strdup(path))) {
427 if (!(c->argv = strv_new(path, arg1, NULL))) {
436 static int sysv_exec_commands(Service *s) {
440 assert(s->sysv_path);
442 if (!(c = exec_command_new(s->sysv_path, "start")))
444 exec_command_append_list(s->exec_command+SERVICE_EXEC_START, c);
446 if (!(c = exec_command_new(s->sysv_path, "stop")))
448 exec_command_append_list(s->exec_command+SERVICE_EXEC_STOP, c);
450 if (!(c = exec_command_new(s->sysv_path, "reload")))
452 exec_command_append_list(s->exec_command+SERVICE_EXEC_RELOAD, c);
457 static int service_load_sysv_path(Service *s, const char *path) {
468 char *short_description = NULL, *long_description = NULL, *chkconfig_description = NULL, *description;
475 if (!(f = fopen(path, "re"))) {
476 r = errno == ENOENT ? 0 : -errno;
481 if (!(s->sysv_path = strdup(path))) {
487 char l[LINE_MAX], *t;
489 if (!fgets(l, sizeof(l), f)) {
494 log_error("Failed to read configuration file '%s': %s", path, strerror(-r));
504 if (state == NORMAL && streq(t, "### BEGIN INIT INFO")) {
506 s->sysv_has_lsb = true;
510 if ((state == LSB_DESCRIPTION || state == LSB) && streq(t, "### END INIT INFO")) {
516 t += strspn(t, WHITESPACE);
518 if (state == NORMAL) {
520 /* Try to parse Red Hat style chkconfig headers */
522 if (startswith_no_case(t, "chkconfig:")) {
524 char runlevels[16], *k;
528 if (sscanf(t+10, "%15s %i %*i",
530 &start_priority) != 2) {
532 log_warning("[%s:%u] Failed to parse chkconfig line. Ignoring.", path, line);
536 /* A start priority gathered from the
537 * symlink farms is preferred over the
538 * data from the LSB header. */
539 if (start_priority < 0 || start_priority > 99)
540 log_warning("[%s:%u] Start priority out of range. Ignoring.", path, line);
541 else if (s->sysv_start_priority < 0)
542 s->sysv_start_priority = start_priority;
544 char_array_0(runlevels);
545 k = delete_chars(runlevels, WHITESPACE "-");
550 if (!(d = strdup(k))) {
555 free(s->sysv_runlevels);
556 s->sysv_runlevels = d;
559 } else if (startswith_no_case(t, "description:")) {
561 size_t k = strlen(t);
565 if (t[k-1] == '\\') {
570 if ((j = strstrip(t+12)) && *j) {
571 if (!(d = strdup(j))) {
578 free(chkconfig_description);
579 chkconfig_description = d;
581 } else if (startswith_no_case(t, "pidfile:")) {
588 if (!path_is_absolute(fn)) {
589 log_warning("[%s:%u] PID file not absolute. Ignoring.", path, line);
593 if (!(fn = strdup(fn))) {
602 } else if (state == DESCRIPTION) {
604 /* Try to parse Red Hat style description
607 size_t k = strlen(t);
615 if ((j = strstrip(t)) && *j) {
618 if (chkconfig_description)
619 asprintf(&d, "%s %s", chkconfig_description, j);
628 free(chkconfig_description);
629 chkconfig_description = d;
632 } else if (state == LSB || state == LSB_DESCRIPTION) {
634 if (startswith_no_case(t, "Provides:")) {
640 FOREACH_WORD_QUOTED(w, z, t+9, i) {
643 if (!(n = strndup(w, z))) {
648 r = sysv_translate_facility(n, file_name_from_path(path), &m);
657 if (unit_name_to_type(m) == UNIT_SERVICE)
658 r = unit_add_name(u, m);
660 r = unit_add_dependency_by_name(u, UNIT_BEFORE, m, NULL, true);
662 if (s->sysv_enabled) {
665 if ((k = unit_add_dependency_by_name_inverse(u, UNIT_WANTS, m, NULL, true)) < 0)
671 log_error("[%s:%u] Failed to add LSB Provides name %s, ignoring: %s", path, line, m, strerror(-r));
676 } else if (startswith_no_case(t, "Required-Start:") ||
677 startswith_no_case(t, "Should-Start:") ||
678 startswith_no_case(t, "X-Start-Before:") ||
679 startswith_no_case(t, "X-Start-After:")) {
685 FOREACH_WORD_QUOTED(w, z, strchr(t, ':')+1, i) {
688 if (!(n = strndup(w, z))) {
693 r = sysv_translate_facility(n, file_name_from_path(path), &m);
696 log_error("[%s:%u] Failed to translate LSB dependency %s, ignoring: %s", path, line, n, strerror(-r));
706 r = unit_add_dependency_by_name(u, startswith_no_case(t, "X-Start-Before:") ? UNIT_BEFORE : UNIT_AFTER, m, NULL, true);
709 log_error("[%s:%u] Failed to add dependency on %s, ignoring: %s", path, line, m, strerror(-r));
713 } else if (startswith_no_case(t, "Default-Start:")) {
718 k = delete_chars(t+14, WHITESPACE "-");
721 if (!(d = strdup(k))) {
726 free(s->sysv_runlevels);
727 s->sysv_runlevels = d;
730 } else if (startswith_no_case(t, "Description:")) {
733 state = LSB_DESCRIPTION;
735 if ((j = strstrip(t+12)) && *j) {
736 if (!(d = strdup(j))) {
743 free(long_description);
744 long_description = d;
746 } else if (startswith_no_case(t, "Short-Description:")) {
751 if ((j = strstrip(t+18)) && *j) {
752 if (!(d = strdup(j))) {
759 free(short_description);
760 short_description = d;
762 } else if (startswith_no_case(t, "X-Interactive:")) {
765 if ((b = parse_boolean(strstrip(t+14))) < 0) {
766 log_warning("[%s:%u] Couldn't parse interactive flag. Ignoring.", path, line);
771 s->exec_context.std_input = EXEC_INPUT_TTY;
773 s->exec_context.std_input = EXEC_INPUT_NULL;
775 } else if (state == LSB_DESCRIPTION) {
777 if (startswith(l, "#\t") || startswith(l, "# ")) {
780 if ((j = strstrip(t)) && *j) {
783 if (long_description)
784 asprintf(&d, "%s %s", long_description, t);
793 free(long_description);
794 long_description = d;
803 if ((r = sysv_exec_commands(s)) < 0)
806 if (s->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, s->sysv_runlevels)) {
807 /* If there a runlevels configured for this service
808 * but none of the standard ones, then we assume this
809 * is some special kind of service (which might be
810 * needed for early boot) and don't create any links
813 s->meta.default_dependencies = false;
815 /* Don't timeout special services during boot (like fsck) */
818 s->timeout_usec = DEFAULT_SYSV_TIMEOUT_USEC;
820 /* Special setting for all SysV services */
821 s->type = SERVICE_FORKING;
822 s->remain_after_exit = true;
823 s->restart = SERVICE_RESTART_NO;
824 s->exec_context.std_output =
825 (s->meta.manager->sysv_console || s->exec_context.std_input == EXEC_INPUT_TTY)
826 ? EXEC_OUTPUT_TTY : s->meta.manager->default_std_output;
827 s->exec_context.kill_mode = KILL_PROCESS_GROUP;
829 /* We use the long description only if
830 * no short description is set. */
832 if (short_description)
833 description = short_description;
834 else if (chkconfig_description)
835 description = chkconfig_description;
836 else if (long_description)
837 description = long_description;
844 if (!(d = strappend(s->sysv_has_lsb ? "LSB: " : "SYSV: ", description))) {
849 u->meta.description = d;
852 u->meta.load_state = UNIT_LOADED;
860 free(short_description);
861 free(long_description);
862 free(chkconfig_description);
867 static int service_load_sysv_name(Service *s, const char *name) {
873 /* For SysV services we strip the boot.*, rc.* and *.sh
874 * prefixes/suffixes. */
875 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU)
876 if (endswith(name, ".sh.service"))
881 if (startswith(name, "boot."))
885 #ifdef TARGET_FRUGALWARE
886 if (startswith(name, "rc."))
890 STRV_FOREACH(p, s->meta.manager->lookup_paths.sysvinit_path) {
894 if (asprintf(&path, "%s/%s", *p, name) < 0)
897 assert(endswith(path, ".service"));
898 path[strlen(path)-8] = 0;
900 r = service_load_sysv_path(s, path);
902 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU)
903 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
904 /* Try Debian style *.sh source'able init scripts */
906 r = service_load_sysv_path(s, path);
912 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
913 /* Try SUSE style boot.* init scripts */
915 if (asprintf(&path, "%s/boot.%s", *p, name) < 0)
918 /* Drop .service suffix */
919 path[strlen(path)-8] = 0;
920 r = service_load_sysv_path(s, path);
925 #ifdef TARGET_FRUGALWARE
926 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
927 /* Try Frugalware style rc.* init scripts */
929 if (asprintf(&path, "%s/rc.%s", *p, name) < 0)
932 /* Drop .service suffix */
933 path[strlen(path)-8] = 0;
934 r = service_load_sysv_path(s, path);
942 if ((s->meta.load_state != UNIT_STUB))
949 static int service_load_sysv(Service *s) {
956 /* Load service data from SysV init scripts, preferably with
959 if (strv_isempty(s->meta.manager->lookup_paths.sysvinit_path))
962 if ((t = s->meta.id))
963 if ((r = service_load_sysv_name(s, t)) < 0)
966 if (s->meta.load_state == UNIT_STUB)
967 SET_FOREACH(t, s->meta.names, i) {
971 if ((r = service_load_sysv_name(s, t)) < 0)
974 if (s->meta.load_state != UNIT_STUB)
982 static int fsck_fix_order(Service *s) {
988 if (s->fsck_passno <= 0)
991 /* For each pair of services where both have an fsck priority
992 * we order things based on it. */
994 LIST_FOREACH(units_per_type, other, s->meta.manager->units_per_type[UNIT_SERVICE]) {
998 t = (Service*) other;
1003 if (t->meta.load_state != UNIT_LOADED)
1006 if (t->fsck_passno <= 0)
1009 if (t->fsck_passno < s->fsck_passno)
1011 else if (t->fsck_passno > s->fsck_passno)
1016 if (!(r = unit_add_dependency(UNIT(s), d, UNIT(t), true)) < 0)
1023 static int service_verify(Service *s) {
1026 if (s->meta.load_state != UNIT_LOADED)
1029 if (!s->exec_command[SERVICE_EXEC_START]) {
1030 log_error("%s lacks ExecStart setting. Refusing.", s->meta.id);
1034 if (s->type != SERVICE_ONESHOT &&
1035 s->exec_command[SERVICE_EXEC_START]->command_next) {
1036 log_error("%s has more than one ExecStart setting, which is only allowed for Type=oneshot services. Refusing.", s->meta.id);
1040 if (s->type == SERVICE_ONESHOT &&
1041 s->exec_command[SERVICE_EXEC_RELOAD]) {
1042 log_error("%s has an ExecReload setting, which is not allowed for Type=oneshot services. Refusing.", s->meta.id);
1046 if (s->type == SERVICE_DBUS && !s->bus_name) {
1047 log_error("%s is of type D-Bus but no D-Bus service name has been specified. Refusing.", s->meta.id);
1051 if (s->exec_context.pam_name && s->exec_context.kill_mode != KILL_CONTROL_GROUP) {
1052 log_error("%s has PAM enabled. Kill mode must be set to 'control-group'. Refusing.", s->meta.id);
1059 static int service_add_default_dependencies(Service *s) {
1064 /* Add a number of automatic dependencies useful for the
1065 * majority of services. */
1067 /* First, pull in base system */
1068 if (s->meta.manager->running_as == MANAGER_SYSTEM) {
1070 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_BASIC_TARGET, NULL, true)) < 0)
1073 } else if (s->meta.manager->running_as == MANAGER_USER) {
1075 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SOCKETS_TARGET, NULL, true)) < 0)
1079 /* Second, activate normal shutdown */
1080 return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true);
1083 static int service_load(Unit *u) {
1085 Service *s = SERVICE(u);
1089 /* Load a .service file */
1090 if ((r = unit_load_fragment(u)) < 0)
1093 #ifdef HAVE_SYSV_COMPAT
1094 /* Load a classic init script as a fallback, if we couldn't find anything */
1095 if (u->meta.load_state == UNIT_STUB)
1096 if ((r = service_load_sysv(s)) < 0)
1100 /* Still nothing found? Then let's give up */
1101 if (u->meta.load_state == UNIT_STUB)
1104 /* We were able to load something, then let's add in the
1105 * dropin directories. */
1106 if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
1109 /* This is a new unit? Then let's add in some extras */
1110 if (u->meta.load_state == UNIT_LOADED) {
1111 if ((r = unit_add_exec_dependencies(u, &s->exec_context)) < 0)
1114 if ((r = unit_add_default_cgroups(u)) < 0)
1117 #ifdef HAVE_SYSV_COMPAT
1118 if ((r = sysv_fix_order(s)) < 0)
1122 if ((r = fsck_fix_order(s)) < 0)
1126 if ((r = unit_watch_bus_name(u, s->bus_name)) < 0)
1129 if (s->type == SERVICE_NOTIFY && s->notify_access == NOTIFY_NONE)
1130 s->notify_access = NOTIFY_MAIN;
1132 if (s->type == SERVICE_DBUS || s->bus_name)
1133 if ((r = unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_REQUIRES, SPECIAL_DBUS_TARGET, NULL, true)) < 0)
1136 if (s->meta.default_dependencies)
1137 if ((r = service_add_default_dependencies(s)) < 0)
1141 return service_verify(s);
1144 static void service_dump(Unit *u, FILE *f, const char *prefix) {
1146 ServiceExecCommand c;
1147 Service *s = SERVICE(u);
1148 const char *prefix2;
1153 p2 = strappend(prefix, "\t");
1154 prefix2 = p2 ? p2 : prefix;
1157 "%sService State: %s\n"
1158 "%sPermissionsStartOnly: %s\n"
1159 "%sRootDirectoryStartOnly: %s\n"
1160 "%sRemainAfterExit: %s\n"
1161 "%sGuessMainPID: %s\n"
1164 "%sNotifyAccess: %s\n",
1165 prefix, service_state_to_string(s->state),
1166 prefix, yes_no(s->permissions_start_only),
1167 prefix, yes_no(s->root_directory_start_only),
1168 prefix, yes_no(s->remain_after_exit),
1169 prefix, yes_no(s->guess_main_pid),
1170 prefix, service_type_to_string(s->type),
1171 prefix, service_restart_to_string(s->restart),
1172 prefix, notify_access_to_string(s->notify_access));
1174 if (s->control_pid > 0)
1176 "%sControl PID: %lu\n",
1177 prefix, (unsigned long) s->control_pid);
1179 if (s->main_pid > 0)
1181 "%sMain PID: %lu\n",
1182 prefix, (unsigned long) s->main_pid);
1187 prefix, s->pid_file);
1192 "%sBus Name Good: %s\n",
1193 prefix, s->bus_name,
1194 prefix, yes_no(s->bus_name_good));
1196 exec_context_dump(&s->exec_context, f, prefix);
1198 for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
1200 if (!s->exec_command[c])
1203 fprintf(f, "%s-> %s:\n",
1204 prefix, service_exec_command_to_string(c));
1206 exec_command_dump_list(s->exec_command[c], f, prefix2);
1209 #ifdef HAVE_SYSV_COMPAT
1212 "%sSysV Init Script Path: %s\n"
1213 "%sSysV Init Script has LSB Header: %s\n"
1214 "%sSysVEnabled: %s\n",
1215 prefix, s->sysv_path,
1216 prefix, yes_no(s->sysv_has_lsb),
1217 prefix, yes_no(s->sysv_enabled));
1219 if (s->sysv_start_priority >= 0)
1221 "%sSysVStartPriority: %i\n",
1222 prefix, s->sysv_start_priority);
1224 if (s->sysv_runlevels)
1225 fprintf(f, "%sSysVRunLevels: %s\n",
1226 prefix, s->sysv_runlevels);
1229 if (s->fsck_passno > 0)
1231 "%sFsckPassNo: %i\n",
1232 prefix, s->fsck_passno);
1235 fprintf(f, "%sStatus Text: %s\n",
1236 prefix, s->status_text);
1241 static int service_load_pid_file(Service *s) {
1251 if ((r = read_one_line_file(s->pid_file, &k)) < 0)
1254 r = parse_pid(k, &pid);
1260 if (kill(pid, 0) < 0 && errno != EPERM) {
1261 log_warning("PID %lu read from file %s does not exist. Your service or init script might be broken.",
1262 (unsigned long) pid, s->pid_file);
1266 if ((r = service_set_main_pid(s, pid)) < 0)
1269 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1270 /* FIXME: we need to do something here */
1276 static int service_search_main_pid(Service *s) {
1282 /* If we know it anyway, don't ever fallback to unreliable
1284 if (s->main_pid_known)
1287 if (!s->guess_main_pid)
1290 assert(s->main_pid <= 0);
1292 if ((pid = cgroup_bonding_search_main_pid_list(s->meta.cgroup_bondings)) <= 0)
1295 if ((r = service_set_main_pid(s, pid)) < 0)
1298 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1299 /* FIXME: we need to do something here */
1305 static int service_get_sockets(Service *s, Set **_set) {
1314 if (s->socket_fd >= 0)
1317 if (!set_isempty(s->configured_sockets))
1320 /* Collects all Socket objects that belong to this
1321 * service. Note that a service might have multiple sockets
1322 * via multiple names. */
1324 if (!(set = set_new(NULL, NULL)))
1327 SET_FOREACH(t, s->meta.names, i) {
1331 /* Look for all socket objects that go by any of our
1332 * units and collect their fds */
1334 if (!(k = unit_name_change_suffix(t, ".socket"))) {
1339 p = manager_get_unit(s->meta.manager, k);
1345 if ((r = set_put(set, p)) < 0)
1357 static int service_notify_sockets_dead(Service *s) {
1359 Set *set, *free_set = NULL;
1365 /* Notifies all our sockets when we die */
1367 if (s->socket_fd >= 0)
1370 if (!set_isempty(s->configured_sockets))
1371 set = s->configured_sockets;
1373 if ((r = service_get_sockets(s, &free_set)) < 0)
1379 SET_FOREACH(sock, set, i)
1380 socket_notify_service_dead(sock);
1387 static void service_set_state(Service *s, ServiceState state) {
1388 ServiceState old_state;
1391 old_state = s->state;
1394 if (state != SERVICE_START_PRE &&
1395 state != SERVICE_START &&
1396 state != SERVICE_START_POST &&
1397 state != SERVICE_RELOAD &&
1398 state != SERVICE_STOP &&
1399 state != SERVICE_STOP_SIGTERM &&
1400 state != SERVICE_STOP_SIGKILL &&
1401 state != SERVICE_STOP_POST &&
1402 state != SERVICE_FINAL_SIGTERM &&
1403 state != SERVICE_FINAL_SIGKILL &&
1404 state != SERVICE_AUTO_RESTART)
1405 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1407 if (state != SERVICE_START &&
1408 state != SERVICE_START_POST &&
1409 state != SERVICE_RUNNING &&
1410 state != SERVICE_RELOAD &&
1411 state != SERVICE_STOP &&
1412 state != SERVICE_STOP_SIGTERM &&
1413 state != SERVICE_STOP_SIGKILL) {
1414 service_unwatch_main_pid(s);
1415 s->main_command = NULL;
1418 if (state != SERVICE_START_PRE &&
1419 state != SERVICE_START &&
1420 state != SERVICE_START_POST &&
1421 state != SERVICE_RELOAD &&
1422 state != SERVICE_STOP &&
1423 state != SERVICE_STOP_SIGTERM &&
1424 state != SERVICE_STOP_SIGKILL &&
1425 state != SERVICE_STOP_POST &&
1426 state != SERVICE_FINAL_SIGTERM &&
1427 state != SERVICE_FINAL_SIGKILL) {
1428 service_unwatch_control_pid(s);
1429 s->control_command = NULL;
1430 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1433 if (state == SERVICE_DEAD ||
1434 state == SERVICE_STOP ||
1435 state == SERVICE_STOP_SIGTERM ||
1436 state == SERVICE_STOP_SIGKILL ||
1437 state == SERVICE_STOP_POST ||
1438 state == SERVICE_FINAL_SIGTERM ||
1439 state == SERVICE_FINAL_SIGKILL ||
1440 state == SERVICE_FAILED ||
1441 state == SERVICE_AUTO_RESTART)
1442 service_notify_sockets_dead(s);
1444 if (state != SERVICE_START_PRE &&
1445 state != SERVICE_START &&
1446 state != SERVICE_START_POST &&
1447 state != SERVICE_RUNNING &&
1448 state != SERVICE_RELOAD &&
1449 state != SERVICE_STOP &&
1450 state != SERVICE_STOP_SIGTERM &&
1451 state != SERVICE_STOP_SIGKILL &&
1452 state != SERVICE_STOP_POST &&
1453 state != SERVICE_FINAL_SIGTERM &&
1454 state != SERVICE_FINAL_SIGKILL &&
1455 !(state == SERVICE_DEAD && s->meta.job)) {
1456 service_close_socket_fd(s);
1457 service_connection_unref(s);
1460 /* For the inactive states unit_notify() will trim the cgroup,
1461 * but for exit we have to do that ourselves... */
1462 if (state == SERVICE_EXITED)
1463 cgroup_bonding_trim_list(s->meta.cgroup_bondings, true);
1465 if (old_state != state)
1466 log_debug("%s changed %s -> %s", s->meta.id, service_state_to_string(old_state), service_state_to_string(state));
1468 unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state], !s->reload_failure);
1469 s->reload_failure = false;
1472 static int service_coldplug(Unit *u) {
1473 Service *s = SERVICE(u);
1477 assert(s->state == SERVICE_DEAD);
1479 if (s->deserialized_state != s->state) {
1481 if (s->deserialized_state == SERVICE_START_PRE ||
1482 s->deserialized_state == SERVICE_START ||
1483 s->deserialized_state == SERVICE_START_POST ||
1484 s->deserialized_state == SERVICE_RELOAD ||
1485 s->deserialized_state == SERVICE_STOP ||
1486 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1487 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1488 s->deserialized_state == SERVICE_STOP_POST ||
1489 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1490 s->deserialized_state == SERVICE_FINAL_SIGKILL ||
1491 s->deserialized_state == SERVICE_AUTO_RESTART) {
1493 if (s->deserialized_state == SERVICE_AUTO_RESTART || s->timeout_usec > 0) {
1496 k = s->deserialized_state == SERVICE_AUTO_RESTART ? s->restart_usec : s->timeout_usec;
1498 if ((r = unit_watch_timer(UNIT(s), k, &s->timer_watch)) < 0)
1503 if ((s->deserialized_state == SERVICE_START &&
1504 (s->type == SERVICE_FORKING ||
1505 s->type == SERVICE_DBUS ||
1506 s->type == SERVICE_ONESHOT ||
1507 s->type == SERVICE_NOTIFY)) ||
1508 s->deserialized_state == SERVICE_START_POST ||
1509 s->deserialized_state == SERVICE_RUNNING ||
1510 s->deserialized_state == SERVICE_RELOAD ||
1511 s->deserialized_state == SERVICE_STOP ||
1512 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1513 s->deserialized_state == SERVICE_STOP_SIGKILL)
1514 if (s->main_pid > 0)
1515 if ((r = unit_watch_pid(UNIT(s), s->main_pid)) < 0)
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 if (s->control_pid > 0)
1529 if ((r = unit_watch_pid(UNIT(s), s->control_pid)) < 0)
1532 service_set_state(s, s->deserialized_state);
1538 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
1542 unsigned rn_fds = 0;
1543 Set *set, *free_set = NULL;
1550 if (s->socket_fd >= 0)
1553 if (!set_isempty(s->configured_sockets))
1554 set = s->configured_sockets;
1556 if ((r = service_get_sockets(s, &free_set)) < 0)
1562 SET_FOREACH(sock, set, i) {
1566 if ((r = socket_collect_fds(sock, &cfds, &cn_fds)) < 0)
1578 if (!(t = new(int, rn_fds+cn_fds))) {
1584 memcpy(t, rfds, rn_fds);
1585 memcpy(t+rn_fds, cfds, cn_fds);
1590 rn_fds = rn_fds+cn_fds;
1608 static int service_spawn(
1613 bool apply_permissions,
1615 bool apply_tty_stdin,
1616 bool set_notify_socket,
1621 int *fds = NULL, *fdsbuf = NULL;
1622 unsigned n_fds = 0, n_env = 0;
1623 char **argv = NULL, **final_env = NULL, **our_env = NULL;
1630 s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1631 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1632 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
1634 if (s->socket_fd >= 0) {
1635 fds = &s->socket_fd;
1638 if ((r = service_collect_fds(s, &fdsbuf, &n_fds)) < 0)
1645 if (timeout && s->timeout_usec) {
1646 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1649 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1651 if (!(argv = unit_full_printf_strv(UNIT(s), c->argv))) {
1656 if (!(our_env = new0(char*, 4))) {
1661 if (set_notify_socket)
1662 if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=%s", s->meta.manager->notify_socket) < 0) {
1667 if (s->main_pid > 0)
1668 if (asprintf(our_env + n_env++, "MAINPID=%lu", (unsigned long) s->main_pid) < 0) {
1673 if (!(final_env = strv_env_merge(2,
1674 s->meta.manager->environment,
1689 s->meta.manager->confirm_spawn,
1690 s->meta.cgroup_bondings,
1697 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1698 /* FIXME: we need to do something here */
1704 strv_free(final_env);
1714 strv_free(final_env);
1717 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1722 static int main_pid_good(Service *s) {
1725 /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1728 /* If we know the pid file, then lets just check if it is
1730 if (s->main_pid_known)
1731 return s->main_pid > 0;
1733 /* We don't know the pid */
1737 static int control_pid_good(Service *s) {
1740 return s->control_pid > 0;
1743 static int cgroup_good(Service *s) {
1748 if ((r = cgroup_bonding_is_empty_list(s->meta.cgroup_bondings)) < 0)
1754 static void service_enter_dead(Service *s, bool success, bool allow_restart) {
1761 if (allow_restart &&
1762 !s->forbid_restart &&
1763 (s->restart == SERVICE_RESTART_ALWAYS ||
1764 (s->restart == SERVICE_RESTART_ON_SUCCESS && !s->failure) ||
1765 (s->restart == SERVICE_RESTART_ON_FAILURE && s->failure) ||
1766 (s->restart == SERVICE_RESTART_ON_ABORT && s->failure &&
1767 (s->main_exec_status.code == CLD_KILLED ||
1768 s->main_exec_status.code == CLD_DUMPED)))) {
1770 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
1773 service_set_state(s, SERVICE_AUTO_RESTART);
1775 service_set_state(s, s->failure ? SERVICE_FAILED : SERVICE_DEAD);
1777 s->forbid_restart = false;
1782 log_warning("%s failed to run install restart timer: %s", s->meta.id, strerror(-r));
1783 service_enter_dead(s, false, false);
1786 static void service_enter_signal(Service *s, ServiceState state, bool success);
1788 static void service_enter_stop_post(Service *s, bool success) {
1795 service_unwatch_control_pid(s);
1797 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST])) {
1798 s->control_command_id = SERVICE_EXEC_STOP_POST;
1800 if ((r = service_spawn(s,
1804 !s->permissions_start_only,
1805 !s->root_directory_start_only,
1808 &s->control_pid)) < 0)
1812 service_set_state(s, SERVICE_STOP_POST);
1814 service_enter_signal(s, SERVICE_FINAL_SIGTERM, true);
1819 log_warning("%s failed to run 'stop-post' task: %s", s->meta.id, strerror(-r));
1820 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1823 static void service_enter_signal(Service *s, ServiceState state, bool success) {
1825 Set *pid_set = NULL;
1826 bool wait_for_exit = false;
1833 if (s->exec_context.kill_mode != KILL_NONE) {
1834 int sig = (state == SERVICE_STOP_SIGTERM || state == SERVICE_FINAL_SIGTERM) ? s->exec_context.kill_signal : SIGKILL;
1836 if (s->main_pid > 0) {
1837 if (kill_and_sigcont(s->exec_context.kill_mode == KILL_PROCESS_GROUP ?
1839 s->main_pid, sig) < 0 && errno != ESRCH)
1841 log_warning("Failed to kill main process %li: %m", (long) s->main_pid);
1843 wait_for_exit = true;
1846 if (s->control_pid > 0) {
1847 if (kill_and_sigcont(s->exec_context.kill_mode == KILL_PROCESS_GROUP ?
1849 s->control_pid, sig) < 0 && errno != ESRCH)
1851 log_warning("Failed to kill control process %li: %m", (long) s->control_pid);
1853 wait_for_exit = true;
1856 if (s->exec_context.kill_mode == KILL_CONTROL_GROUP) {
1858 if (!(pid_set = set_new(trivial_hash_func, trivial_compare_func))) {
1863 /* Exclude the main/control pids from being killed via the cgroup */
1864 if (s->main_pid > 0)
1865 if ((r = set_put(pid_set, LONG_TO_PTR(s->main_pid))) < 0)
1868 if (s->control_pid > 0)
1869 if ((r = set_put(pid_set, LONG_TO_PTR(s->control_pid))) < 0)
1872 if ((r = cgroup_bonding_kill_list(s->meta.cgroup_bondings, sig, true, pid_set)) < 0) {
1873 if (r != -EAGAIN && r != -ESRCH && r != -ENOENT)
1874 log_warning("Failed to kill control group: %s", strerror(-r));
1876 wait_for_exit = true;
1882 if (wait_for_exit) {
1883 if (s->timeout_usec > 0)
1884 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1887 service_set_state(s, state);
1888 } else if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1889 service_enter_stop_post(s, true);
1891 service_enter_dead(s, true, true);
1896 log_warning("%s failed to kill processes: %s", s->meta.id, strerror(-r));
1898 if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1899 service_enter_stop_post(s, false);
1901 service_enter_dead(s, false, true);
1907 static void service_enter_stop(Service *s, bool success) {
1915 service_unwatch_control_pid(s);
1917 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP])) {
1918 s->control_command_id = SERVICE_EXEC_STOP;
1920 if ((r = service_spawn(s,
1924 !s->permissions_start_only,
1925 !s->root_directory_start_only,
1928 &s->control_pid)) < 0)
1931 service_set_state(s, SERVICE_STOP);
1933 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
1938 log_warning("%s failed to run 'stop' task: %s", s->meta.id, strerror(-r));
1939 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1942 static void service_enter_running(Service *s, bool success) {
1943 int main_pid_ok, cgroup_ok;
1949 main_pid_ok = main_pid_good(s);
1950 cgroup_ok = cgroup_good(s);
1952 if ((main_pid_ok > 0 || (main_pid_ok < 0 && cgroup_ok != 0)) &&
1953 (s->bus_name_good || s->type != SERVICE_DBUS))
1954 service_set_state(s, SERVICE_RUNNING);
1955 else if (s->remain_after_exit)
1956 service_set_state(s, SERVICE_EXITED);
1958 service_enter_stop(s, true);
1961 static void service_enter_start_post(Service *s) {
1965 service_unwatch_control_pid(s);
1967 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_POST])) {
1968 s->control_command_id = SERVICE_EXEC_START_POST;
1970 if ((r = service_spawn(s,
1974 !s->permissions_start_only,
1975 !s->root_directory_start_only,
1978 &s->control_pid)) < 0)
1981 service_set_state(s, SERVICE_START_POST);
1983 service_enter_running(s, true);
1988 log_warning("%s failed to run 'start-post' task: %s", s->meta.id, strerror(-r));
1989 service_enter_stop(s, false);
1992 static void service_enter_start(Service *s) {
1999 assert(s->exec_command[SERVICE_EXEC_START]);
2000 assert(!s->exec_command[SERVICE_EXEC_START]->command_next || s->type == SERVICE_ONESHOT);
2002 if (s->type == SERVICE_FORKING)
2003 service_unwatch_control_pid(s);
2005 service_unwatch_main_pid(s);
2007 if (s->type == SERVICE_FORKING) {
2008 s->control_command_id = SERVICE_EXEC_START;
2009 c = s->control_command = s->exec_command[SERVICE_EXEC_START];
2011 s->main_command = NULL;
2013 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2014 s->control_command = NULL;
2016 c = s->main_command = s->exec_command[SERVICE_EXEC_START];
2019 if ((r = service_spawn(s,
2021 s->type == SERVICE_FORKING || s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY,
2026 s->notify_access != NOTIFY_NONE,
2030 if (s->type == SERVICE_SIMPLE) {
2031 /* For simple services we immediately start
2032 * the START_POST binaries. */
2034 service_set_main_pid(s, pid);
2035 service_enter_start_post(s);
2037 } else if (s->type == SERVICE_FORKING) {
2039 /* For forking services we wait until the start
2040 * process exited. */
2042 s->control_pid = pid;
2043 service_set_state(s, SERVICE_START);
2045 } else if (s->type == SERVICE_ONESHOT ||
2046 s->type == SERVICE_DBUS ||
2047 s->type == SERVICE_NOTIFY) {
2049 /* For oneshot services we wait until the start
2050 * process exited, too, but it is our main process. */
2052 /* For D-Bus services we know the main pid right away,
2053 * but wait for the bus name to appear on the
2054 * bus. Notify services are similar. */
2056 service_set_main_pid(s, pid);
2057 service_set_state(s, SERVICE_START);
2059 assert_not_reached("Unknown service type");
2064 log_warning("%s failed to run 'start' task: %s", s->meta.id, strerror(-r));
2065 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2068 static void service_enter_start_pre(Service *s) {
2073 service_unwatch_control_pid(s);
2075 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_PRE])) {
2076 s->control_command_id = SERVICE_EXEC_START_PRE;
2078 if ((r = service_spawn(s,
2082 !s->permissions_start_only,
2083 !s->root_directory_start_only,
2086 &s->control_pid)) < 0)
2089 service_set_state(s, SERVICE_START_PRE);
2091 service_enter_start(s);
2096 log_warning("%s failed to run 'start-pre' task: %s", s->meta.id, strerror(-r));
2097 service_enter_dead(s, false, true);
2100 static void service_enter_restart(Service *s) {
2105 dbus_error_init(&error);
2108 log_info("Job pending for unit, delaying automatic restart.");
2110 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
2114 service_enter_dead(s, true, false);
2116 if ((r = manager_add_job(s->meta.manager, JOB_START, UNIT(s), JOB_FAIL, false, &error, NULL)) < 0)
2119 log_debug("%s scheduled restart job.", s->meta.id);
2123 log_warning("%s failed to schedule restart job: %s", s->meta.id, bus_error(&error, -r));
2124 service_enter_dead(s, false, false);
2126 dbus_error_free(&error);
2129 static void service_enter_reload(Service *s) {
2134 service_unwatch_control_pid(s);
2136 if ((s->control_command = s->exec_command[SERVICE_EXEC_RELOAD])) {
2137 s->control_command_id = SERVICE_EXEC_RELOAD;
2139 if ((r = service_spawn(s,
2143 !s->permissions_start_only,
2144 !s->root_directory_start_only,
2147 &s->control_pid)) < 0)
2150 service_set_state(s, SERVICE_RELOAD);
2152 service_enter_running(s, true);
2157 log_warning("%s failed to run 'reload' task: %s", s->meta.id, strerror(-r));
2158 s->reload_failure = true;
2159 service_enter_running(s, true);
2162 static void service_run_next_control(Service *s, bool success) {
2166 assert(s->control_command);
2167 assert(s->control_command->command_next);
2172 assert(s->control_command_id != SERVICE_EXEC_START);
2174 s->control_command = s->control_command->command_next;
2175 service_unwatch_control_pid(s);
2177 if ((r = service_spawn(s,
2181 !s->permissions_start_only,
2182 !s->root_directory_start_only,
2183 s->control_command_id == SERVICE_EXEC_START_PRE ||
2184 s->control_command_id == SERVICE_EXEC_STOP_POST,
2186 &s->control_pid)) < 0)
2192 log_warning("%s failed to run next control task: %s", s->meta.id, strerror(-r));
2194 if (s->state == SERVICE_START_PRE)
2195 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2196 else if (s->state == SERVICE_STOP)
2197 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
2198 else if (s->state == SERVICE_STOP_POST)
2199 service_enter_dead(s, false, true);
2200 else if (s->state == SERVICE_RELOAD) {
2201 s->reload_failure = true;
2202 service_enter_running(s, true);
2204 service_enter_stop(s, false);
2207 static void service_run_next_main(Service *s, bool success) {
2212 assert(s->main_command);
2213 assert(s->main_command->command_next);
2214 assert(s->type == SERVICE_ONESHOT);
2219 s->main_command = s->main_command->command_next;
2220 service_unwatch_main_pid(s);
2222 if ((r = service_spawn(s,
2229 s->notify_access != NOTIFY_NONE,
2233 service_set_main_pid(s, pid);
2238 log_warning("%s failed to run next main task: %s", s->meta.id, strerror(-r));
2239 service_enter_stop(s, false);
2242 static int service_start(Unit *u) {
2243 Service *s = SERVICE(u);
2247 /* We cannot fulfill this request right now, try again later
2249 if (s->state == SERVICE_STOP ||
2250 s->state == SERVICE_STOP_SIGTERM ||
2251 s->state == SERVICE_STOP_SIGKILL ||
2252 s->state == SERVICE_STOP_POST ||
2253 s->state == SERVICE_FINAL_SIGTERM ||
2254 s->state == SERVICE_FINAL_SIGKILL)
2257 /* Already on it! */
2258 if (s->state == SERVICE_START_PRE ||
2259 s->state == SERVICE_START ||
2260 s->state == SERVICE_START_POST)
2263 assert(s->state == SERVICE_DEAD || s->state == SERVICE_FAILED || s->state == SERVICE_AUTO_RESTART);
2265 /* Make sure we don't enter a busy loop of some kind. */
2266 if (!ratelimit_test(&s->ratelimit)) {
2267 log_warning("%s start request repeated too quickly, refusing to start.", u->meta.id);
2272 s->main_pid_known = false;
2273 s->forbid_restart = false;
2275 service_enter_start_pre(s);
2279 static int service_stop(Unit *u) {
2280 Service *s = SERVICE(u);
2284 /* This is a user request, so don't do restarts on this
2286 s->forbid_restart = true;
2289 if (s->state == SERVICE_STOP ||
2290 s->state == SERVICE_STOP_SIGTERM ||
2291 s->state == SERVICE_STOP_SIGKILL ||
2292 s->state == SERVICE_STOP_POST ||
2293 s->state == SERVICE_FINAL_SIGTERM ||
2294 s->state == SERVICE_FINAL_SIGKILL)
2297 /* Don't allow a restart */
2298 if (s->state == SERVICE_AUTO_RESTART) {
2299 service_set_state(s, SERVICE_DEAD);
2303 /* If there's already something running we go directly into
2305 if (s->state == SERVICE_START_PRE ||
2306 s->state == SERVICE_START ||
2307 s->state == SERVICE_START_POST ||
2308 s->state == SERVICE_RELOAD) {
2309 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
2313 assert(s->state == SERVICE_RUNNING ||
2314 s->state == SERVICE_EXITED);
2316 service_enter_stop(s, true);
2320 static int service_reload(Unit *u) {
2321 Service *s = SERVICE(u);
2325 assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
2327 service_enter_reload(s);
2331 static bool service_can_reload(Unit *u) {
2332 Service *s = SERVICE(u);
2336 return !!s->exec_command[SERVICE_EXEC_RELOAD];
2339 static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
2340 Service *s = SERVICE(u);
2346 unit_serialize_item(u, f, "state", service_state_to_string(s->state));
2347 unit_serialize_item(u, f, "failure", yes_no(s->failure));
2349 if (s->control_pid > 0)
2350 unit_serialize_item_format(u, f, "control-pid", "%lu", (unsigned long) s->control_pid);
2352 if (s->main_pid_known && s->main_pid > 0)
2353 unit_serialize_item_format(u, f, "main-pid", "%lu", (unsigned long) s->main_pid);
2355 unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
2358 unit_serialize_item(u, f, "status-text", s->status_text);
2360 /* There's a minor uncleanliness here: if there are multiple
2361 * commands attached here, we will start from the first one
2363 if (s->control_command_id >= 0)
2364 unit_serialize_item(u, f, "control-command", service_exec_command_to_string(s->control_command_id));
2366 if (s->socket_fd >= 0) {
2369 if ((copy = fdset_put_dup(fds, s->socket_fd)) < 0)
2372 unit_serialize_item_format(u, f, "socket-fd", "%i", copy);
2375 if (s->main_exec_status.pid > 0) {
2376 unit_serialize_item_format(u, f, "main-exec-status-pid", "%lu", (unsigned long) s->main_exec_status.pid);
2377 dual_timestamp_serialize(f, "main-exec-status-start", &s->main_exec_status.start_timestamp);
2378 dual_timestamp_serialize(f, "main-exec-status-exit", &s->main_exec_status.exit_timestamp);
2380 if (dual_timestamp_is_set(&s->main_exec_status.exit_timestamp)) {
2381 unit_serialize_item_format(u, f, "main-exec-status-code", "%i", s->main_exec_status.code);
2382 unit_serialize_item_format(u, f, "main-exec-status-status", "%i", s->main_exec_status.status);
2389 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
2390 Service *s = SERVICE(u);
2397 if (streq(key, "state")) {
2400 if ((state = service_state_from_string(value)) < 0)
2401 log_debug("Failed to parse state value %s", value);
2403 s->deserialized_state = state;
2404 } else if (streq(key, "failure")) {
2407 if ((b = parse_boolean(value)) < 0)
2408 log_debug("Failed to parse failure value %s", value);
2410 s->failure = b || s->failure;
2411 } else if (streq(key, "control-pid")) {
2414 if (parse_pid(value, &pid) < 0)
2415 log_debug("Failed to parse control-pid value %s", value);
2417 s->control_pid = pid;
2418 } else if (streq(key, "main-pid")) {
2421 if (parse_pid(value, &pid) < 0)
2422 log_debug("Failed to parse main-pid value %s", value);
2424 service_set_main_pid(s, (pid_t) pid);
2425 } else if (streq(key, "main-pid-known")) {
2428 if ((b = parse_boolean(value)) < 0)
2429 log_debug("Failed to parse main-pid-known value %s", value);
2431 s->main_pid_known = b;
2432 } else if (streq(key, "status-text")) {
2435 if ((t = strdup(value))) {
2436 free(s->status_text);
2440 } else if (streq(key, "control-command")) {
2441 ServiceExecCommand id;
2443 if ((id = service_exec_command_from_string(value)) < 0)
2444 log_debug("Failed to parse exec-command value %s", value);
2446 s->control_command_id = id;
2447 s->control_command = s->exec_command[id];
2449 } else if (streq(key, "socket-fd")) {
2452 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2453 log_debug("Failed to parse socket-fd value %s", value);
2456 if (s->socket_fd >= 0)
2457 close_nointr_nofail(s->socket_fd);
2458 s->socket_fd = fdset_remove(fds, fd);
2460 } else if (streq(key, "main-exec-status-pid")) {
2463 if (parse_pid(value, &pid) < 0)
2464 log_debug("Failed to parse main-exec-status-pid value %s", value);
2466 s->main_exec_status.pid = pid;
2467 } else if (streq(key, "main-exec-status-code")) {
2470 if (safe_atoi(value, &i) < 0)
2471 log_debug("Failed to parse main-exec-status-code value %s", value);
2473 s->main_exec_status.code = i;
2474 } else if (streq(key, "main-exec-status-status")) {
2477 if (safe_atoi(value, &i) < 0)
2478 log_debug("Failed to parse main-exec-status-status value %s", value);
2480 s->main_exec_status.status = i;
2481 } else if (streq(key, "main-exec-status-start"))
2482 dual_timestamp_deserialize(value, &s->main_exec_status.start_timestamp);
2483 else if (streq(key, "main-exec-status-exit"))
2484 dual_timestamp_deserialize(value, &s->main_exec_status.exit_timestamp);
2486 log_debug("Unknown serialization key '%s'", key);
2491 static UnitActiveState service_active_state(Unit *u) {
2494 return state_translation_table[SERVICE(u)->state];
2497 static const char *service_sub_state_to_string(Unit *u) {
2500 return service_state_to_string(SERVICE(u)->state);
2503 static bool service_check_gc(Unit *u) {
2504 Service *s = SERVICE(u);
2508 /* Never clean up services that still have a process around,
2509 * even if the service is formally dead. */
2510 if (cgroup_good(s) > 0 ||
2511 main_pid_good(s) > 0 ||
2512 control_pid_good(s) > 0)
2515 #ifdef HAVE_SYSV_COMPAT
2523 static bool service_check_snapshot(Unit *u) {
2524 Service *s = SERVICE(u);
2528 return !s->got_socket_fd;
2531 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2532 Service *s = SERVICE(u);
2538 if (!s->meta.fragment_path)
2539 success = is_clean_exit_lsb(code, status);
2541 success = is_clean_exit(code, status);
2543 if (s->main_pid == pid) {
2546 exec_status_exit(&s->main_exec_status, pid, code, status, s->exec_context.utmp_id);
2548 /* If this is not a forking service than the main
2549 * process got started and hence we copy the exit
2550 * status so that it is recorded both as main and as
2551 * control process exit status */
2552 if (s->main_command) {
2553 s->main_command->exec_status = s->main_exec_status;
2555 if (s->main_command->ignore)
2559 log_full(success ? LOG_DEBUG : LOG_NOTICE,
2560 "%s: main process exited, code=%s, status=%i", u->meta.id, sigchld_code_to_string(code), status);
2561 s->failure = s->failure || !success;
2563 if (s->main_command &&
2564 s->main_command->command_next &&
2567 /* There is another command to *
2568 * execute, so let's do that. */
2570 log_debug("%s running next main command for state %s", u->meta.id, service_state_to_string(s->state));
2571 service_run_next_main(s, success);
2575 /* The service exited, so the service is officially
2577 s->main_command = NULL;
2581 case SERVICE_START_POST:
2582 case SERVICE_RELOAD:
2584 /* Need to wait until the operation is
2589 if (s->type == SERVICE_ONESHOT) {
2590 /* This was our main goal, so let's go on */
2592 service_enter_start_post(s);
2594 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2597 assert(s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY);
2602 case SERVICE_RUNNING:
2603 service_enter_running(s, success);
2606 case SERVICE_STOP_SIGTERM:
2607 case SERVICE_STOP_SIGKILL:
2609 if (!control_pid_good(s))
2610 service_enter_stop_post(s, success);
2612 /* If there is still a control process, wait for that first */
2616 assert_not_reached("Uh, main process died at wrong time.");
2620 } else if (s->control_pid == pid) {
2624 if (s->control_command) {
2625 exec_status_exit(&s->control_command->exec_status, pid, code, status, s->exec_context.utmp_id);
2627 if (s->control_command->ignore)
2631 log_full(success ? LOG_DEBUG : LOG_NOTICE,
2632 "%s: control process exited, code=%s status=%i", u->meta.id, sigchld_code_to_string(code), status);
2633 s->failure = s->failure || !success;
2635 if (s->control_command &&
2636 s->control_command->command_next &&
2639 /* There is another command to *
2640 * execute, so let's do that. */
2642 log_debug("%s running next control command for state %s", u->meta.id, service_state_to_string(s->state));
2643 service_run_next_control(s, success);
2646 /* No further commands for this step, so let's
2647 * figure out what to do next */
2649 s->control_command = NULL;
2650 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2652 log_debug("%s got final SIGCHLD for state %s", u->meta.id, service_state_to_string(s->state));
2656 case SERVICE_START_PRE:
2658 service_enter_start(s);
2660 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2664 assert(s->type == SERVICE_FORKING);
2666 /* Let's try to load the pid
2667 * file here if we can. We
2668 * ignore the return value,
2669 * since the PID file might
2670 * actually be created by a
2671 * START_POST script */
2674 service_load_pid_file(s);
2675 service_search_main_pid(s);
2677 service_enter_start_post(s);
2679 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2683 case SERVICE_START_POST:
2684 if (success && s->pid_file && !s->main_pid_known) {
2687 /* Hmm, let's see if we can
2688 * load the pid now after the
2689 * start-post scripts got
2692 if ((r = service_load_pid_file(s)) < 0)
2693 log_warning("%s: failed to load PID file %s: %s", s->meta.id, s->pid_file, strerror(-r));
2696 s->reload_failure = !success;
2697 service_enter_running(s, true);
2700 case SERVICE_RELOAD:
2702 service_load_pid_file(s);
2703 service_search_main_pid(s);
2706 s->reload_failure = !success;
2707 service_enter_running(s, true);
2711 service_enter_signal(s, SERVICE_STOP_SIGTERM, success);
2714 case SERVICE_STOP_SIGTERM:
2715 case SERVICE_STOP_SIGKILL:
2716 if (main_pid_good(s) <= 0)
2717 service_enter_stop_post(s, success);
2719 /* If there is still a service
2720 * process around, wait until
2721 * that one quit, too */
2724 case SERVICE_STOP_POST:
2725 case SERVICE_FINAL_SIGTERM:
2726 case SERVICE_FINAL_SIGKILL:
2727 service_enter_dead(s, success, true);
2731 assert_not_reached("Uh, control process died at wrong time.");
2736 /* Notify clients about changed exit status */
2737 unit_add_to_dbus_queue(u);
2740 static void service_timer_event(Unit *u, uint64_t elapsed, Watch* w) {
2741 Service *s = SERVICE(u);
2744 assert(elapsed == 1);
2746 assert(w == &s->timer_watch);
2750 case SERVICE_START_PRE:
2752 log_warning("%s operation timed out. Terminating.", u->meta.id);
2753 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2756 case SERVICE_START_POST:
2757 log_warning("%s operation timed out. Stopping.", u->meta.id);
2758 service_enter_stop(s, false);
2761 case SERVICE_RELOAD:
2762 log_warning("%s operation timed out. Stopping.", u->meta.id);
2763 s->reload_failure = true;
2764 service_enter_running(s, true);
2768 log_warning("%s stopping timed out. Terminating.", u->meta.id);
2769 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
2772 case SERVICE_STOP_SIGTERM:
2773 if (s->exec_context.send_sigkill) {
2774 log_warning("%s stopping timed out. Killing.", u->meta.id);
2775 service_enter_signal(s, SERVICE_STOP_SIGKILL, false);
2777 log_warning("%s stopping timed out. Skipping SIGKILL.", u->meta.id);
2778 service_enter_stop_post(s, false);
2783 case SERVICE_STOP_SIGKILL:
2784 /* Uh, we sent a SIGKILL and it is still not gone?
2785 * Must be something we cannot kill, so let's just be
2786 * weirded out and continue */
2788 log_warning("%s still around after SIGKILL. Ignoring.", u->meta.id);
2789 service_enter_stop_post(s, false);
2792 case SERVICE_STOP_POST:
2793 log_warning("%s stopping timed out (2). Terminating.", u->meta.id);
2794 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2797 case SERVICE_FINAL_SIGTERM:
2798 if (s->exec_context.send_sigkill) {
2799 log_warning("%s stopping timed out (2). Killing.", u->meta.id);
2800 service_enter_signal(s, SERVICE_FINAL_SIGKILL, false);
2802 log_warning("%s stopping timed out (2). Skipping SIGKILL. Entering failed mode.", u->meta.id);
2803 service_enter_dead(s, false, true);
2808 case SERVICE_FINAL_SIGKILL:
2809 log_warning("%s still around after SIGKILL (2). Entering failed mode.", u->meta.id);
2810 service_enter_dead(s, false, true);
2813 case SERVICE_AUTO_RESTART:
2814 log_info("%s holdoff time over, scheduling restart.", u->meta.id);
2815 service_enter_restart(s);
2819 assert_not_reached("Timeout at wrong time.");
2823 static void service_cgroup_notify_event(Unit *u) {
2824 Service *s = SERVICE(u);
2828 log_debug("%s: cgroup is empty", u->meta.id);
2832 /* Waiting for SIGCHLD is usually more interesting,
2833 * because it includes return codes/signals. Which is
2834 * why we ignore the cgroup events for most cases,
2835 * except when we don't know pid which to expect the
2838 case SERVICE_RUNNING:
2839 service_enter_running(s, true);
2842 case SERVICE_STOP_SIGTERM:
2843 case SERVICE_STOP_SIGKILL:
2844 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2845 service_enter_stop_post(s, true);
2849 case SERVICE_FINAL_SIGTERM:
2850 case SERVICE_FINAL_SIGKILL:
2851 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2852 service_enter_dead(s, true, true);
2861 static void service_notify_message(Unit *u, pid_t pid, char **tags) {
2862 Service *s = SERVICE(u);
2867 if (s->notify_access == NOTIFY_NONE) {
2868 log_warning("%s: Got notification message from PID %lu, but reception is disabled.",
2869 u->meta.id, (unsigned long) pid);
2873 if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
2874 log_warning("%s: Got notification message from PID %lu, but reception only permitted for PID %lu",
2875 u->meta.id, (unsigned long) pid, (unsigned long) s->main_pid);
2879 log_debug("%s: Got message", u->meta.id);
2881 /* Interpret MAINPID= */
2882 if ((e = strv_find_prefix(tags, "MAINPID=")) &&
2883 (s->state == SERVICE_START ||
2884 s->state == SERVICE_START_POST ||
2885 s->state == SERVICE_RUNNING ||
2886 s->state == SERVICE_RELOAD)) {
2888 if (parse_pid(e + 8, &pid) < 0)
2889 log_warning("Failed to parse notification message %s", e);
2891 log_debug("%s: got %s", u->meta.id, e);
2892 service_set_main_pid(s, pid);
2896 /* Interpret READY= */
2897 if (s->type == SERVICE_NOTIFY &&
2898 s->state == SERVICE_START &&
2899 strv_find(tags, "READY=1")) {
2900 log_debug("%s: got READY=1", u->meta.id);
2902 service_enter_start_post(s);
2905 /* Interpret STATUS= */
2906 if ((e = strv_find_prefix(tags, "STATUS="))) {
2910 if (!(t = strdup(e+7))) {
2911 log_error("Failed to allocate string.");
2915 log_debug("%s: got %s", u->meta.id, e);
2917 free(s->status_text);
2920 free(s->status_text);
2921 s->status_text = NULL;
2926 /* Notify clients about changed status or main pid */
2927 unit_add_to_dbus_queue(u);
2930 #ifdef HAVE_SYSV_COMPAT
2931 static int service_enumerate(Manager *m) {
2935 char *path = NULL, *fpath = NULL, *name = NULL;
2936 Set *runlevel_services[ELEMENTSOF(rcnd_table)], *shutdown_services = NULL;
2943 zero(runlevel_services);
2945 STRV_FOREACH(p, m->lookup_paths.sysvrcnd_path)
2946 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++) {
2951 if (asprintf(&path, "%s/%s", *p, rcnd_table[i].path) < 0) {
2959 if (!(d = opendir(path))) {
2960 if (errno != ENOENT)
2961 log_warning("opendir() failed on %s: %s", path, strerror(errno));
2966 while ((de = readdir(d))) {
2969 if (ignore_file(de->d_name))
2972 if (de->d_name[0] != 'S' && de->d_name[0] != 'K')
2975 if (strlen(de->d_name) < 4)
2978 a = undecchar(de->d_name[1]);
2979 b = undecchar(de->d_name[2]);
2986 if (asprintf(&fpath, "%s/%s/%s", *p, rcnd_table[i].path, de->d_name) < 0) {
2991 if (access(fpath, X_OK) < 0) {
2993 if (errno != ENOENT)
2994 log_warning("access() failed on %s: %s", fpath, strerror(errno));
3000 if (!(name = sysv_translate_name(de->d_name + 3))) {
3005 if ((r = manager_load_unit_prepare(m, name, NULL, NULL, &service)) < 0) {
3006 log_warning("Failed to prepare unit %s: %s", name, strerror(-r));
3010 if (de->d_name[0] == 'S') {
3012 if (rcnd_table[i].type == RUNLEVEL_UP || rcnd_table[i].type == RUNLEVEL_SYSINIT) {
3013 SERVICE(service)->sysv_start_priority =
3014 MAX(a*10 + b, SERVICE(service)->sysv_start_priority);
3016 SERVICE(service)->sysv_enabled = true;
3019 if ((r = set_ensure_allocated(&runlevel_services[i], trivial_hash_func, trivial_compare_func)) < 0)
3022 if ((r = set_put(runlevel_services[i], service)) < 0)
3025 } else if (de->d_name[0] == 'K' &&
3026 (rcnd_table[i].type == RUNLEVEL_DOWN ||
3027 rcnd_table[i].type == RUNLEVEL_SYSINIT)) {
3029 if ((r = set_ensure_allocated(&shutdown_services, trivial_hash_func, trivial_compare_func)) < 0)
3032 if ((r = set_put(shutdown_services, service)) < 0)
3038 /* Now we loaded all stubs and are aware of the lowest
3039 start-up priority for all services, not let's actually load
3040 the services, this will also tell us which services are
3041 actually native now */
3042 manager_dispatch_load_queue(m);
3044 /* If this is a native service, rely on native ways to pull in
3045 * a service, don't pull it in via sysv rcN.d links. */
3046 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++)
3047 SET_FOREACH(service, runlevel_services[i], j) {
3048 service = unit_follow_merge(service);
3050 if (service->meta.fragment_path)
3053 if ((r = unit_add_two_dependencies_by_name_inverse(service, UNIT_AFTER, UNIT_WANTS, rcnd_table[i].target, NULL, true)) < 0)
3057 /* We honour K links only for halt/reboot. For the normal
3058 * runlevels we assume the stop jobs will be implicitly added
3059 * by the core logic. Also, we don't really distinguish here
3060 * between the runlevels 0 and 6 and just add them to the
3061 * special shutdown target. On SUSE the boot.d/ runlevel is
3062 * also used for shutdown, so we add links for that too to the
3063 * shutdown target.*/
3064 SET_FOREACH(service, shutdown_services, j) {
3065 service = unit_follow_merge(service);
3067 if (service->meta.fragment_path)
3070 if ((r = unit_add_two_dependencies_by_name(service, UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true)) < 0)
3081 for (i = 0; i < ELEMENTSOF(rcnd_table); i++)
3082 set_free(runlevel_services[i]);
3083 set_free(shutdown_services);
3092 static void service_bus_name_owner_change(
3095 const char *old_owner,
3096 const char *new_owner) {
3098 Service *s = SERVICE(u);
3103 assert(streq(s->bus_name, name));
3104 assert(old_owner || new_owner);
3106 if (old_owner && new_owner)
3107 log_debug("%s's D-Bus name %s changed owner from %s to %s", u->meta.id, name, old_owner, new_owner);
3109 log_debug("%s's D-Bus name %s no longer registered by %s", u->meta.id, name, old_owner);
3111 log_debug("%s's D-Bus name %s now registered by %s", u->meta.id, name, new_owner);
3113 s->bus_name_good = !!new_owner;
3115 if (s->type == SERVICE_DBUS) {
3117 /* service_enter_running() will figure out what to
3119 if (s->state == SERVICE_RUNNING)
3120 service_enter_running(s, true);
3121 else if (s->state == SERVICE_START && new_owner)
3122 service_enter_start_post(s);
3124 } else if (new_owner &&
3126 (s->state == SERVICE_START ||
3127 s->state == SERVICE_START_POST ||
3128 s->state == SERVICE_RUNNING ||
3129 s->state == SERVICE_RELOAD)) {
3131 /* Try to acquire PID from bus service */
3132 log_debug("Trying to acquire PID from D-Bus name...");
3134 bus_query_pid(u->meta.manager, name);
3138 static void service_bus_query_pid_done(
3143 Service *s = SERVICE(u);
3148 log_debug("%s's D-Bus name %s is now owned by process %u", u->meta.id, name, (unsigned) pid);
3150 if (s->main_pid <= 0 &&
3151 (s->state == SERVICE_START ||
3152 s->state == SERVICE_START_POST ||
3153 s->state == SERVICE_RUNNING ||
3154 s->state == SERVICE_RELOAD))
3155 service_set_main_pid(s, pid);
3158 int service_set_socket_fd(Service *s, int fd, Socket *sock) {
3162 /* This is called by the socket code when instantiating a new
3163 * service for a stream socket and the socket needs to be
3166 if (s->meta.load_state != UNIT_LOADED)
3169 if (s->socket_fd >= 0)
3172 if (s->state != SERVICE_DEAD)
3176 s->got_socket_fd = true;
3177 s->accept_socket = sock;
3182 static void service_reset_failed(Unit *u) {
3183 Service *s = SERVICE(u);
3187 if (s->state == SERVICE_FAILED)
3188 service_set_state(s, SERVICE_DEAD);
3193 static int service_kill(Unit *u, KillWho who, KillMode mode, int signo, DBusError *error) {
3194 Service *s = SERVICE(u);
3196 Set *pid_set = NULL;
3200 if (s->main_pid <= 0 && who == KILL_MAIN) {
3201 dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "No main process to kill");
3205 if (s->control_pid <= 0 && who == KILL_CONTROL) {
3206 dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "No control process to kill");
3210 if (s->control_pid > 0)
3211 if (kill(mode == KILL_PROCESS_GROUP ? -s->control_pid : s->control_pid, signo) < 0)
3214 if (s->main_pid > 0)
3215 if (kill(mode == KILL_PROCESS_GROUP ? -s->main_pid : s->main_pid, signo) < 0)
3218 if (mode == KILL_CONTROL_GROUP) {
3221 if (!(pid_set = set_new(trivial_hash_func, trivial_compare_func)))
3224 /* Exclude the control/main pid from being killed via the cgroup */
3225 if (s->control_pid > 0)
3226 if ((q = set_put(pid_set, LONG_TO_PTR(s->control_pid))) < 0) {
3231 if (s->main_pid > 0)
3232 if ((q = set_put(pid_set, LONG_TO_PTR(s->main_pid))) < 0) {
3237 if ((q = cgroup_bonding_kill_list(s->meta.cgroup_bondings, signo, false, pid_set)) < 0)
3238 if (r != -EAGAIN && r != -ESRCH && r != -ENOENT)
3249 static const char* const service_state_table[_SERVICE_STATE_MAX] = {
3250 [SERVICE_DEAD] = "dead",
3251 [SERVICE_START_PRE] = "start-pre",
3252 [SERVICE_START] = "start",
3253 [SERVICE_START_POST] = "start-post",
3254 [SERVICE_RUNNING] = "running",
3255 [SERVICE_EXITED] = "exited",
3256 [SERVICE_RELOAD] = "reload",
3257 [SERVICE_STOP] = "stop",
3258 [SERVICE_STOP_SIGTERM] = "stop-sigterm",
3259 [SERVICE_STOP_SIGKILL] = "stop-sigkill",
3260 [SERVICE_STOP_POST] = "stop-post",
3261 [SERVICE_FINAL_SIGTERM] = "final-sigterm",
3262 [SERVICE_FINAL_SIGKILL] = "final-sigkill",
3263 [SERVICE_FAILED] = "failed",
3264 [SERVICE_AUTO_RESTART] = "auto-restart",
3267 DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
3269 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
3270 [SERVICE_RESTART_NO] = "no",
3271 [SERVICE_RESTART_ON_SUCCESS] = "on-success",
3272 [SERVICE_RESTART_ON_FAILURE] = "on-failure",
3273 [SERVICE_RESTART_ON_ABORT] = "on-abort",
3274 [SERVICE_RESTART_ALWAYS] = "always"
3277 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
3279 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
3280 [SERVICE_SIMPLE] = "simple",
3281 [SERVICE_FORKING] = "forking",
3282 [SERVICE_ONESHOT] = "oneshot",
3283 [SERVICE_DBUS] = "dbus",
3284 [SERVICE_NOTIFY] = "notify"
3287 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
3289 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
3290 [SERVICE_EXEC_START_PRE] = "ExecStartPre",
3291 [SERVICE_EXEC_START] = "ExecStart",
3292 [SERVICE_EXEC_START_POST] = "ExecStartPost",
3293 [SERVICE_EXEC_RELOAD] = "ExecReload",
3294 [SERVICE_EXEC_STOP] = "ExecStop",
3295 [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
3298 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
3300 static const char* const notify_access_table[_NOTIFY_ACCESS_MAX] = {
3301 [NOTIFY_NONE] = "none",
3302 [NOTIFY_MAIN] = "main",
3303 [NOTIFY_ALL] = "all"
3306 DEFINE_STRING_TABLE_LOOKUP(notify_access, NotifyAccess);
3308 const UnitVTable service_vtable = {
3309 .suffix = ".service",
3310 .show_status = true,
3312 .init = service_init,
3313 .done = service_done,
3314 .load = service_load,
3316 .coldplug = service_coldplug,
3318 .dump = service_dump,
3320 .start = service_start,
3321 .stop = service_stop,
3322 .reload = service_reload,
3324 .can_reload = service_can_reload,
3326 .kill = service_kill,
3328 .serialize = service_serialize,
3329 .deserialize_item = service_deserialize_item,
3331 .active_state = service_active_state,
3332 .sub_state_to_string = service_sub_state_to_string,
3334 .check_gc = service_check_gc,
3335 .check_snapshot = service_check_snapshot,
3337 .sigchld_event = service_sigchld_event,
3338 .timer_event = service_timer_event,
3340 .reset_failed = service_reset_failed,
3342 .cgroup_notify_empty = service_cgroup_notify_event,
3343 .notify_message = service_notify_message,
3345 .bus_name_owner_change = service_bus_name_owner_change,
3346 .bus_query_pid_done = service_bus_query_pid_done,
3348 .bus_interface = "org.freedesktop.systemd1.Service",
3349 .bus_message_handler = bus_service_message_handler,
3350 .bus_invalidating_properties = bus_service_invalidating_properties,
3352 #ifdef HAVE_SYSV_COMPAT
3353 .enumerate = service_enumerate