1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
29 #include "load-fragment.h"
30 #include "load-dropin.h"
33 #include "unit-name.h"
34 #include "dbus-service.h"
36 #include "bus-errors.h"
38 #define COMMENTS "#;\n"
39 #define NEWLINES "\n\r"
41 typedef enum RunlevelType {
50 const RunlevelType type;
52 /* Standard SysV runlevels for start-up */
53 { "rc1.d", SPECIAL_RESCUE_TARGET, RUNLEVEL_UP },
54 { "rc2.d", SPECIAL_RUNLEVEL2_TARGET, RUNLEVEL_UP },
55 { "rc3.d", SPECIAL_RUNLEVEL3_TARGET, RUNLEVEL_UP },
56 { "rc4.d", SPECIAL_RUNLEVEL4_TARGET, RUNLEVEL_UP },
57 { "rc5.d", SPECIAL_RUNLEVEL5_TARGET, RUNLEVEL_UP },
59 /* SUSE style boot.d */
60 { "boot.d", SPECIAL_SYSINIT_TARGET, RUNLEVEL_SYSINIT },
62 /* Debian style rcS.d */
63 { "rcS.d", SPECIAL_SYSINIT_TARGET, RUNLEVEL_SYSINIT },
65 /* Standard SysV runlevels for shutdown */
66 { "rc0.d", SPECIAL_POWEROFF_TARGET, RUNLEVEL_DOWN },
67 { "rc6.d", SPECIAL_REBOOT_TARGET, RUNLEVEL_DOWN }
69 /* Note that the order here matters, as we read the
70 directories in this order, and we want to make sure that
71 sysv_start_priority is known when we first load the
72 unit. And that value we only know from S links. Hence
73 UP/SYSINIT must be read before DOWN */
76 #define RUNLEVELS_UP "12345"
77 /* #define RUNLEVELS_DOWN "06" */
78 /* #define RUNLEVELS_BOOT "bBsS" */
80 static const UnitActiveState state_translation_table[_SERVICE_STATE_MAX] = {
81 [SERVICE_DEAD] = UNIT_INACTIVE,
82 [SERVICE_START_PRE] = UNIT_ACTIVATING,
83 [SERVICE_START] = UNIT_ACTIVATING,
84 [SERVICE_START_POST] = UNIT_ACTIVATING,
85 [SERVICE_RUNNING] = UNIT_ACTIVE,
86 [SERVICE_EXITED] = UNIT_ACTIVE,
87 [SERVICE_RELOAD] = UNIT_RELOADING,
88 [SERVICE_STOP] = UNIT_DEACTIVATING,
89 [SERVICE_STOP_SIGTERM] = UNIT_DEACTIVATING,
90 [SERVICE_STOP_SIGKILL] = UNIT_DEACTIVATING,
91 [SERVICE_STOP_POST] = UNIT_DEACTIVATING,
92 [SERVICE_FINAL_SIGTERM] = UNIT_DEACTIVATING,
93 [SERVICE_FINAL_SIGKILL] = UNIT_DEACTIVATING,
94 [SERVICE_MAINTENANCE] = UNIT_MAINTENANCE,
95 [SERVICE_AUTO_RESTART] = UNIT_ACTIVATING
98 static void service_init(Unit *u) {
99 Service *s = SERVICE(u);
102 assert(u->meta.load_state == UNIT_STUB);
104 s->timeout_usec = DEFAULT_TIMEOUT_USEC;
105 s->restart_usec = DEFAULT_RESTART_USEC;
106 s->timer_watch.type = WATCH_INVALID;
107 s->sysv_start_priority = -1;
110 exec_context_init(&s->exec_context);
112 RATELIMIT_INIT(s->ratelimit, 10*USEC_PER_SEC, 5);
114 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
117 static void service_unwatch_control_pid(Service *s) {
120 if (s->control_pid <= 0)
123 unit_unwatch_pid(UNIT(s), s->control_pid);
127 static void service_unwatch_main_pid(Service *s) {
130 if (s->main_pid <= 0)
133 unit_unwatch_pid(UNIT(s), s->main_pid);
137 static int service_set_main_pid(Service *s, pid_t pid) {
148 if (get_parent_of_pid(pid, &ppid) >= 0 && ppid != getpid())
149 log_warning("%s: Supervising process %lu which is not our child. We'll most likely not notice when it exits.",
150 s->meta.id, (unsigned long) pid);
153 s->main_pid_known = true;
155 exec_status_start(&s->main_exec_status, pid);
160 static void service_close_socket_fd(Service *s) {
163 if (s->socket_fd < 0)
166 close_nointr_nofail(s->socket_fd);
170 static void service_connection_unref(Service *s) {
176 socket_connection_unref(s->socket);
180 static void service_done(Unit *u) {
181 Service *s = SERVICE(u);
191 free(s->sysv_runlevels);
192 s->sysv_runlevels = NULL;
194 free(s->status_text);
195 s->status_text = NULL;
197 exec_context_done(&s->exec_context);
198 exec_command_free_array(s->exec_command, _SERVICE_EXEC_COMMAND_MAX);
199 s->control_command = NULL;
201 /* This will leak a process, but at least no memory or any of
203 service_unwatch_main_pid(s);
204 service_unwatch_control_pid(s);
207 unit_unwatch_bus_name(UNIT(u), s->bus_name);
212 service_close_socket_fd(s);
213 service_connection_unref(s);
215 unit_unwatch_timer(u, &s->timer_watch);
218 static char *sysv_translate_name(const char *name) {
221 if (!(r = new(char, strlen(name) + sizeof(".service"))))
224 if (startswith(name, "boot."))
225 /* Drop SuSE-style boot. prefix */
226 strcpy(stpcpy(r, name + 5), ".service");
227 else if (endswith(name, ".sh"))
228 /* Drop Debian-style .sh suffix */
229 strcpy(stpcpy(r, name) - 3, ".service");
231 /* Normal init scripts */
232 strcpy(stpcpy(r, name), ".service");
237 static int sysv_translate_facility(const char *name, char **_r) {
239 static const char * const table[] = {
240 /* LSB defined facilities */
241 "$local_fs", SPECIAL_LOCAL_FS_TARGET,
242 "$network", SPECIAL_NETWORK_TARGET,
243 "$named", SPECIAL_NSS_LOOKUP_TARGET,
244 "$portmap", SPECIAL_RPCBIND_TARGET,
245 "$remote_fs", SPECIAL_REMOTE_FS_TARGET,
246 "$syslog", SPECIAL_SYSLOG_TARGET,
247 "$time", SPECIAL_RTC_SET_TARGET,
249 /* Debian extensions */
250 "$mail-transport-agent", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
251 "$mail-transfer-agent", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
252 "$x-display-manager", SPECIAL_DISPLAY_MANAGER_SERVICE
258 for (i = 0; i < ELEMENTSOF(table); i += 2)
259 if (streq(table[i], name)) {
260 if (!(r = strdup(table[i+1])))
269 if (!(r = sysv_translate_name(name)))
280 static int sysv_fix_order(Service *s) {
286 if (s->sysv_start_priority < 0)
289 /* For each pair of services where at least one lacks a LSB
290 * header, we use the start priority value to order things. */
292 LIST_FOREACH(units_per_type, other, s->meta.manager->units_per_type[UNIT_SERVICE]) {
295 bool special_s, special_t;
297 t = (Service*) other;
302 if (t->sysv_start_priority < 0)
305 /* If both units have modern headers we don't care
306 * about the priorities */
307 if ((!s->sysv_path || s->sysv_has_lsb) &&
308 (!t->sysv_path || t->sysv_has_lsb))
311 special_s = s->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, s->sysv_runlevels);
312 special_t = t->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, t->sysv_runlevels);
314 if (special_t && !special_s)
316 else if (special_s && !special_t)
318 else if (t->sysv_start_priority < s->sysv_start_priority)
320 else if (t->sysv_start_priority > s->sysv_start_priority)
325 /* FIXME: Maybe we should compare the name here lexicographically? */
327 if (!(r = unit_add_dependency(UNIT(s), d, UNIT(t), true)) < 0)
334 static ExecCommand *exec_command_new(const char *path, const char *arg1) {
337 if (!(c = new0(ExecCommand, 1)))
340 if (!(c->path = strdup(path))) {
345 if (!(c->argv = strv_new(path, arg1, NULL))) {
354 static int sysv_exec_commands(Service *s) {
358 assert(s->sysv_path);
360 if (!(c = exec_command_new(s->sysv_path, "start")))
362 exec_command_append_list(s->exec_command+SERVICE_EXEC_START, c);
364 if (!(c = exec_command_new(s->sysv_path, "stop")))
366 exec_command_append_list(s->exec_command+SERVICE_EXEC_STOP, c);
368 if (!(c = exec_command_new(s->sysv_path, "reload")))
370 exec_command_append_list(s->exec_command+SERVICE_EXEC_RELOAD, c);
375 static int service_load_sysv_path(Service *s, const char *path) {
392 if (!(f = fopen(path, "re"))) {
393 r = errno == ENOENT ? 0 : -errno;
398 if (!(s->sysv_path = strdup(path))) {
404 char l[LINE_MAX], *t;
406 if (!fgets(l, sizeof(l), f)) {
411 log_error("Failed to read configuration file '%s': %s", path, strerror(-r));
421 if (state == NORMAL && streq(t, "### BEGIN INIT INFO")) {
423 s->sysv_has_lsb = true;
427 if ((state == LSB_DESCRIPTION || state == LSB) && streq(t, "### END INIT INFO")) {
433 t += strspn(t, WHITESPACE);
435 if (state == NORMAL) {
437 /* Try to parse Red Hat style chkconfig headers */
439 if (startswith_no_case(t, "chkconfig:")) {
441 char runlevels[16], *k;
445 if (sscanf(t+10, "%15s %i %*i",
447 &start_priority) != 2) {
449 log_warning("[%s:%u] Failed to parse chkconfig line. Ignoring.", path, line);
453 /* A start priority gathered from the
454 * symlink farms is preferred over the
455 * data from the LSB header. */
456 if (start_priority < 0 || start_priority > 99)
457 log_warning("[%s:%u] Start priority out of range. Ignoring.", path, line);
458 else if (s->sysv_start_priority < 0)
459 s->sysv_start_priority = start_priority;
461 char_array_0(runlevels);
462 k = delete_chars(runlevels, WHITESPACE "-");
467 if (!(d = strdup(k))) {
472 free(s->sysv_runlevels);
473 s->sysv_runlevels = d;
476 } else if (startswith_no_case(t, "description:") &&
477 !u->meta.description) {
479 size_t k = strlen(t);
482 if (t[k-1] == '\\') {
487 if (!(d = strdup(strstrip(t+12)))) {
492 free(u->meta.description);
493 u->meta.description = d;
495 } else if (startswith_no_case(t, "pidfile:")) {
502 if (!path_is_absolute(fn)) {
503 log_warning("[%s:%u] PID file not absolute. Ignoring.", path, line);
507 if (!(fn = strdup(fn))) {
516 } else if (state == DESCRIPTION) {
518 /* Try to parse Red Hat style description
521 size_t k = strlen(t);
529 assert(u->meta.description);
530 if (asprintf(&d, "%s %s", u->meta.description, strstrip(t)) < 0) {
535 free(u->meta.description);
536 u->meta.description = d;
538 } else if (state == LSB || state == LSB_DESCRIPTION) {
540 if (startswith_no_case(t, "Provides:")) {
546 FOREACH_WORD_QUOTED(w, z, t+9, i) {
549 if (!(n = strndup(w, z))) {
554 r = sysv_translate_facility(n, &m);
563 if (unit_name_to_type(m) == UNIT_SERVICE)
564 r = unit_add_name(u, m);
565 else if (s->sysv_start_priority >= 0)
566 r = unit_add_two_dependencies_by_name_inverse(u, UNIT_AFTER, UNIT_WANTS, m, NULL, true);
568 r = unit_add_dependency_by_name_inverse(u, UNIT_AFTER, m, NULL, true);
576 } else if (startswith_no_case(t, "Required-Start:") ||
577 startswith_no_case(t, "Should-Start:") ||
578 startswith_no_case(t, "X-Start-Before:") ||
579 startswith_no_case(t, "X-Start-After:")) {
585 FOREACH_WORD_QUOTED(w, z, strchr(t, ':')+1, i) {
588 if (!(n = strndup(w, z))) {
593 r = sysv_translate_facility(n, &m);
602 r = unit_add_dependency_by_name(u, startswith_no_case(t, "X-Start-Before:") ? UNIT_BEFORE : UNIT_AFTER, m, NULL, true);
608 } else if (startswith_no_case(t, "Default-Start:")) {
613 k = delete_chars(t+14, WHITESPACE "-");
616 if (!(d = strdup(k))) {
621 free(s->sysv_runlevels);
622 s->sysv_runlevels = d;
625 } else if (startswith_no_case(t, "Description:") &&
626 !u->meta.description) {
629 /* We use the long description only if
630 * no short description is set. */
632 state = LSB_DESCRIPTION;
634 if (!(d = strdup(strstrip(t+12)))) {
639 free(u->meta.description);
640 u->meta.description = d;
642 } else if (startswith_no_case(t, "Short-Description:")) {
647 if (!(d = strdup(strstrip(t+18)))) {
652 free(u->meta.description);
653 u->meta.description = d;
655 } else if (startswith_no_case(t, "X-Interactive:")) {
658 if ((b = parse_boolean(strstrip(t+14))) < 0) {
659 log_warning("[%s:%u] Couldn't parse interactive flag. Ignoring.", path, line);
664 s->exec_context.std_input = EXEC_INPUT_TTY;
666 s->exec_context.std_input = EXEC_INPUT_NULL;
668 } else if (state == LSB_DESCRIPTION) {
670 if (startswith(l, "#\t") || startswith(l, "# ")) {
673 assert(u->meta.description);
674 if (asprintf(&d, "%s %s", u->meta.description, t) < 0) {
679 free(u->meta.description);
680 u->meta.description = d;
687 if ((r = sysv_exec_commands(s)) < 0)
690 if (s->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, s->sysv_runlevels)) {
691 /* If there a runlevels configured for this service
692 * but none of the standard ones, then we assume this
693 * is some special kind of service (which might be
694 * needed for early boot) and don't create any links
697 s->meta.default_dependencies = false;
699 /* Don't timeout special services during boot (like fsck) */
703 /* Special setting for all SysV services */
704 s->type = SERVICE_FORKING;
705 s->valid_no_process = true;
706 s->restart = SERVICE_ONCE;
707 s->exec_context.std_output = EXEC_OUTPUT_TTY;
708 s->exec_context.kill_mode = KILL_PROCESS_GROUP;
710 u->meta.load_state = UNIT_LOADED;
721 static int service_load_sysv_name(Service *s, const char *name) {
727 /* For SysV services we strip the boot. or .sh
728 * prefixes/suffixes. */
729 if (startswith(name, "boot.") ||
730 endswith(name, ".sh.service"))
733 STRV_FOREACH(p, s->meta.manager->lookup_paths.sysvinit_path) {
737 if (asprintf(&path, "%s/%s", *p, name) < 0)
740 assert(endswith(path, ".service"));
741 path[strlen(path)-8] = 0;
743 r = service_load_sysv_path(s, path);
745 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
746 /* Try Debian style xxx.sh source'able init scripts */
748 r = service_load_sysv_path(s, path);
753 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
754 /* Try SUSE style boot.xxx init scripts */
756 if (asprintf(&path, "%s/boot.%s", *p, name) < 0)
759 path[strlen(path)-8] = 0;
760 r = service_load_sysv_path(s, path);
767 if ((s->meta.load_state != UNIT_STUB))
774 static int service_load_sysv(Service *s) {
781 /* Load service data from SysV init scripts, preferably with
784 if (strv_isempty(s->meta.manager->lookup_paths.sysvinit_path))
787 if ((t = s->meta.id))
788 if ((r = service_load_sysv_name(s, t)) < 0)
791 if (s->meta.load_state == UNIT_STUB)
792 SET_FOREACH(t, s->meta.names, i) {
796 if ((r == service_load_sysv_name(s, t)) < 0)
799 if (s->meta.load_state != UNIT_STUB)
806 static int service_add_bus_name(Service *s) {
813 if (asprintf(&n, "dbus-%s.service", s->bus_name) < 0)
816 r = unit_merge_by_name(UNIT(s), n);
822 static int service_verify(Service *s) {
825 if (s->meta.load_state != UNIT_LOADED)
828 if (!s->exec_command[SERVICE_EXEC_START]) {
829 log_error("%s lacks ExecStart setting. Refusing.", s->meta.id);
833 if (s->exec_command[SERVICE_EXEC_START]->command_next) {
834 log_error("%s has more than one ExecStart setting. Refusing.", s->meta.id);
838 if (s->type == SERVICE_DBUS && !s->bus_name) {
839 log_error("%s is of type D-Bus but no D-Bus service name has been specified. Refusing.", s->meta.id);
843 if (s->exec_context.pam_name && s->exec_context.kill_mode != KILL_CONTROL_GROUP) {
844 log_error("%s has PAM enabled. Kill mode must be set to 'control-group'. Refusing.", s->meta.id);
851 static int service_add_default_dependencies(Service *s) {
856 /* Add a number of automatic dependencies useful for the
857 * majority of services. */
859 /* First, pull in base system */
860 if (s->meta.manager->running_as == MANAGER_SYSTEM) {
862 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_BASIC_TARGET, NULL, true)) < 0)
865 } else if (s->meta.manager->running_as == MANAGER_SESSION) {
867 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SOCKETS_TARGET, NULL, true)) < 0)
871 /* Second, activate normal shutdown */
872 return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true);
875 static int service_load(Unit *u) {
877 Service *s = SERVICE(u);
881 /* Load a .service file */
882 if ((r = unit_load_fragment(u)) < 0)
885 /* Load a classic init script as a fallback, if we couldn't find anything */
886 if (u->meta.load_state == UNIT_STUB)
887 if ((r = service_load_sysv(s)) < 0)
890 /* Still nothing found? Then let's give up */
891 if (u->meta.load_state == UNIT_STUB)
894 /* We were able to load something, then let's add in the
895 * dropin directories. */
896 if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
899 /* This is a new unit? Then let's add in some extras */
900 if (u->meta.load_state == UNIT_LOADED) {
901 if ((r = unit_add_exec_dependencies(u, &s->exec_context)) < 0)
904 if ((r = unit_add_default_cgroup(u)) < 0)
907 if ((r = sysv_fix_order(s)) < 0)
911 if ((r = service_add_bus_name(s)) < 0)
914 if ((r = unit_watch_bus_name(u, s->bus_name)) < 0)
918 if (s->type == SERVICE_NOTIFY && s->notify_access == NOTIFY_NONE)
919 s->notify_access = NOTIFY_MAIN;
921 if (s->type == SERVICE_DBUS || s->bus_name)
922 if ((r = unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_REQUIRES, SPECIAL_DBUS_TARGET, NULL, true)) < 0)
925 if (s->meta.default_dependencies)
926 if ((r = service_add_default_dependencies(s)) < 0)
930 return service_verify(s);
933 static void service_dump(Unit *u, FILE *f, const char *prefix) {
935 ServiceExecCommand c;
936 Service *s = SERVICE(u);
942 p2 = strappend(prefix, "\t");
943 prefix2 = p2 ? p2 : prefix;
946 "%sService State: %s\n"
947 "%sPermissionsStartOnly: %s\n"
948 "%sRootDirectoryStartOnly: %s\n"
949 "%sValidNoProcess: %s\n"
951 "%sNotifyAccess: %s\n",
952 prefix, service_state_to_string(s->state),
953 prefix, yes_no(s->permissions_start_only),
954 prefix, yes_no(s->root_directory_start_only),
955 prefix, yes_no(s->valid_no_process),
956 prefix, service_type_to_string(s->type),
957 prefix, notify_access_to_string(s->notify_access));
959 if (s->control_pid > 0)
961 "%sControl PID: %lu\n",
962 prefix, (unsigned long) s->control_pid);
967 prefix, (unsigned long) s->main_pid);
972 prefix, s->pid_file);
977 "%sBus Name Good: %s\n",
979 prefix, yes_no(s->bus_name_good));
981 exec_context_dump(&s->exec_context, f, prefix);
983 for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
985 if (!s->exec_command[c])
988 fprintf(f, "%s-> %s:\n",
989 prefix, service_exec_command_to_string(c));
991 exec_command_dump_list(s->exec_command[c], f, prefix2);
996 "%sSysV Init Script Path: %s\n"
997 "%sSysV Init Script has LSB Header: %s\n",
998 prefix, s->sysv_path,
999 prefix, yes_no(s->sysv_has_lsb));
1001 if (s->sysv_start_priority >= 0)
1003 "%sSysVStartPriority: %i\n",
1004 prefix, s->sysv_start_priority);
1006 if (s->sysv_runlevels)
1007 fprintf(f, "%sSysVRunLevels: %s\n",
1008 prefix, s->sysv_runlevels);
1011 fprintf(f, "%sStatus Text: %s\n",
1012 prefix, s->status_text);
1017 static int service_load_pid_file(Service *s) {
1024 if (s->main_pid_known)
1027 assert(s->main_pid <= 0);
1032 if ((r = read_one_line_file(s->pid_file, &k)) < 0)
1035 r = parse_pid(k, &pid);
1041 if (kill(pid, 0) < 0 && errno != EPERM) {
1042 log_warning("PID %lu read from file %s does not exist. Your service or init script might be broken.",
1043 (unsigned long) pid, s->pid_file);
1047 if ((r = service_set_main_pid(s, pid)) < 0)
1050 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1051 /* FIXME: we need to do something here */
1057 static int service_get_sockets(Service *s, Set **_set) {
1066 if (s->socket_fd >= 0)
1069 /* Collects all Socket objects that belong to this
1070 * service. Note that a service might have multiple sockets
1071 * via multiple names. */
1073 if (!(set = set_new(NULL, NULL)))
1076 SET_FOREACH(t, s->meta.names, i) {
1080 /* Look for all socket objects that go by any of our
1081 * units and collect their fds */
1083 if (!(k = unit_name_change_suffix(t, ".socket"))) {
1088 p = manager_get_unit(s->meta.manager, k);
1094 if ((r = set_put(set, p)) < 0)
1106 static int service_notify_sockets_dead(Service *s) {
1114 if (s->socket_fd >= 0)
1117 /* Notifies all our sockets when we die */
1118 if ((r = service_get_sockets(s, &set)) < 0)
1121 SET_FOREACH(sock, set, i)
1122 socket_notify_service_dead(sock);
1129 static void service_set_state(Service *s, ServiceState state) {
1130 ServiceState old_state;
1133 old_state = s->state;
1136 if (state != SERVICE_START_PRE &&
1137 state != SERVICE_START &&
1138 state != SERVICE_START_POST &&
1139 state != SERVICE_RELOAD &&
1140 state != SERVICE_STOP &&
1141 state != SERVICE_STOP_SIGTERM &&
1142 state != SERVICE_STOP_SIGKILL &&
1143 state != SERVICE_STOP_POST &&
1144 state != SERVICE_FINAL_SIGTERM &&
1145 state != SERVICE_FINAL_SIGKILL &&
1146 state != SERVICE_AUTO_RESTART)
1147 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1149 if (state != SERVICE_START &&
1150 state != SERVICE_START_POST &&
1151 state != SERVICE_RUNNING &&
1152 state != SERVICE_RELOAD &&
1153 state != SERVICE_STOP &&
1154 state != SERVICE_STOP_SIGTERM &&
1155 state != SERVICE_STOP_SIGKILL)
1156 service_unwatch_main_pid(s);
1158 if (state != SERVICE_START_PRE &&
1159 state != SERVICE_START &&
1160 state != SERVICE_START_POST &&
1161 state != SERVICE_RELOAD &&
1162 state != SERVICE_STOP &&
1163 state != SERVICE_STOP_SIGTERM &&
1164 state != SERVICE_STOP_SIGKILL &&
1165 state != SERVICE_STOP_POST &&
1166 state != SERVICE_FINAL_SIGTERM &&
1167 state != SERVICE_FINAL_SIGKILL) {
1168 service_unwatch_control_pid(s);
1169 s->control_command = NULL;
1170 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1173 if (state == SERVICE_DEAD ||
1174 state == SERVICE_STOP ||
1175 state == SERVICE_STOP_SIGTERM ||
1176 state == SERVICE_STOP_SIGKILL ||
1177 state == SERVICE_STOP_POST ||
1178 state == SERVICE_FINAL_SIGTERM ||
1179 state == SERVICE_FINAL_SIGKILL ||
1180 state == SERVICE_MAINTENANCE ||
1181 state == SERVICE_AUTO_RESTART)
1182 service_notify_sockets_dead(s);
1184 if (state != SERVICE_START_PRE &&
1185 state != SERVICE_START &&
1186 state != SERVICE_START_POST &&
1187 state != SERVICE_RUNNING &&
1188 state != SERVICE_RELOAD &&
1189 state != SERVICE_STOP &&
1190 state != SERVICE_STOP_SIGTERM &&
1191 state != SERVICE_STOP_SIGKILL &&
1192 state != SERVICE_STOP_POST &&
1193 state != SERVICE_FINAL_SIGTERM &&
1194 state != SERVICE_FINAL_SIGKILL &&
1195 !(state == SERVICE_DEAD && s->meta.job)) {
1196 service_close_socket_fd(s);
1197 service_connection_unref(s);
1200 /* For the inactive states unit_notify() will trim the cgroup,
1201 * but for exit we have to do that ourselves... */
1202 if (state == SERVICE_EXITED)
1203 cgroup_bonding_trim_list(s->meta.cgroup_bondings, true);
1205 if (old_state != state)
1206 log_debug("%s changed %s -> %s", s->meta.id, service_state_to_string(old_state), service_state_to_string(state));
1208 unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state]);
1211 static int service_coldplug(Unit *u) {
1212 Service *s = SERVICE(u);
1216 assert(s->state == SERVICE_DEAD);
1218 if (s->deserialized_state != s->state) {
1220 if (s->deserialized_state == SERVICE_START_PRE ||
1221 s->deserialized_state == SERVICE_START ||
1222 s->deserialized_state == SERVICE_START_POST ||
1223 s->deserialized_state == SERVICE_RELOAD ||
1224 s->deserialized_state == SERVICE_STOP ||
1225 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1226 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1227 s->deserialized_state == SERVICE_STOP_POST ||
1228 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1229 s->deserialized_state == SERVICE_FINAL_SIGKILL ||
1230 s->deserialized_state == SERVICE_AUTO_RESTART) {
1232 if (s->deserialized_state == SERVICE_AUTO_RESTART || s->timeout_usec > 0) {
1235 k = s->deserialized_state == SERVICE_AUTO_RESTART ? s->restart_usec : s->timeout_usec;
1237 if ((r = unit_watch_timer(UNIT(s), k, &s->timer_watch)) < 0)
1242 if ((s->deserialized_state == SERVICE_START &&
1243 (s->type == SERVICE_FORKING ||
1244 s->type == SERVICE_DBUS ||
1245 s->type == SERVICE_FINISH ||
1246 s->type == SERVICE_NOTIFY)) ||
1247 s->deserialized_state == SERVICE_START_POST ||
1248 s->deserialized_state == SERVICE_RUNNING ||
1249 s->deserialized_state == SERVICE_RELOAD ||
1250 s->deserialized_state == SERVICE_STOP ||
1251 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1252 s->deserialized_state == SERVICE_STOP_SIGKILL)
1253 if (s->main_pid > 0)
1254 if ((r = unit_watch_pid(UNIT(s), s->main_pid)) < 0)
1257 if (s->deserialized_state == SERVICE_START_PRE ||
1258 s->deserialized_state == SERVICE_START ||
1259 s->deserialized_state == SERVICE_START_POST ||
1260 s->deserialized_state == SERVICE_RELOAD ||
1261 s->deserialized_state == SERVICE_STOP ||
1262 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1263 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1264 s->deserialized_state == SERVICE_STOP_POST ||
1265 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1266 s->deserialized_state == SERVICE_FINAL_SIGKILL)
1267 if (s->control_pid > 0)
1268 if ((r = unit_watch_pid(UNIT(s), s->control_pid)) < 0)
1271 service_set_state(s, s->deserialized_state);
1277 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
1281 unsigned rn_fds = 0;
1289 if (s->socket_fd >= 0)
1292 if ((r = service_get_sockets(s, &set)) < 0)
1295 SET_FOREACH(sock, set, i) {
1299 if ((r = socket_collect_fds(sock, &cfds, &cn_fds)) < 0)
1311 if (!(t = new(int, rn_fds+cn_fds))) {
1317 memcpy(t, rfds, rn_fds);
1318 memcpy(t+rn_fds, cfds, cn_fds);
1323 rn_fds = rn_fds+cn_fds;
1341 static int service_spawn(
1346 bool apply_permissions,
1348 bool apply_tty_stdin,
1349 bool set_notify_socket,
1354 int *fds = NULL, *fdsbuf = NULL;
1355 unsigned n_fds = 0, n_env = 0;
1356 char **argv = NULL, **final_env = NULL, **our_env = NULL;
1363 s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1364 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1365 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
1367 if (s->socket_fd >= 0) {
1368 fds = &s->socket_fd;
1371 if ((r = service_collect_fds(s, &fdsbuf, &n_fds)) < 0)
1378 if (timeout && s->timeout_usec) {
1379 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1382 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1384 if (!(argv = unit_full_printf_strv(UNIT(s), c->argv))) {
1389 if (!(our_env = new0(char*, 3))) {
1394 if (set_notify_socket)
1395 if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=@%s", s->meta.manager->notify_socket) < 0) {
1400 if (s->main_pid > 0)
1401 if (asprintf(our_env + n_env++, "MAINPID=%lu", (unsigned long) s->main_pid) < 0) {
1406 if (!(final_env = strv_env_merge(2,
1407 s->meta.manager->environment,
1422 s->meta.manager->confirm_spawn,
1423 s->meta.cgroup_bondings,
1430 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1431 /* FIXME: we need to do something here */
1437 strv_free(final_env);
1447 strv_free(final_env);
1450 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1455 static int main_pid_good(Service *s) {
1458 /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1461 /* If we know the pid file, then lets just check if it is
1463 if (s->main_pid_known)
1464 return s->main_pid > 0;
1466 /* We don't know the pid */
1470 static int control_pid_good(Service *s) {
1473 return s->control_pid > 0;
1476 static int cgroup_good(Service *s) {
1481 if ((r = cgroup_bonding_is_empty_list(s->meta.cgroup_bondings)) < 0)
1487 static void service_enter_dead(Service *s, bool success, bool allow_restart) {
1494 if (allow_restart &&
1496 (s->restart == SERVICE_RESTART_ALWAYS ||
1497 (s->restart == SERVICE_RESTART_ON_SUCCESS && !s->failure))) {
1499 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
1502 service_set_state(s, SERVICE_AUTO_RESTART);
1504 service_set_state(s, s->failure ? SERVICE_MAINTENANCE : SERVICE_DEAD);
1509 log_warning("%s failed to run install restart timer: %s", s->meta.id, strerror(-r));
1510 service_enter_dead(s, false, false);
1513 static void service_enter_signal(Service *s, ServiceState state, bool success);
1515 static void service_enter_stop_post(Service *s, bool success) {
1522 service_unwatch_control_pid(s);
1524 s->control_command_id = SERVICE_EXEC_STOP_POST;
1525 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST])) {
1526 if ((r = service_spawn(s,
1530 !s->permissions_start_only,
1531 !s->root_directory_start_only,
1534 &s->control_pid)) < 0)
1538 service_set_state(s, SERVICE_STOP_POST);
1540 service_enter_signal(s, SERVICE_FINAL_SIGTERM, true);
1545 log_warning("%s failed to run 'stop-post' task: %s", s->meta.id, strerror(-r));
1546 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1549 static void service_enter_signal(Service *s, ServiceState state, bool success) {
1558 if (s->exec_context.kill_mode != KILL_NONE) {
1559 int sig = (state == SERVICE_STOP_SIGTERM || state == SERVICE_FINAL_SIGTERM) ? s->exec_context.kill_signal : SIGKILL;
1561 if (s->exec_context.kill_mode == KILL_CONTROL_GROUP) {
1563 if ((r = cgroup_bonding_kill_list(s->meta.cgroup_bondings, sig)) < 0) {
1564 if (r != -EAGAIN && r != -ESRCH)
1573 if (s->main_pid > 0) {
1574 if (kill(s->exec_context.kill_mode == KILL_PROCESS ? s->main_pid : -s->main_pid, sig) < 0 && errno != ESRCH)
1580 if (s->control_pid > 0) {
1581 if (kill(s->exec_context.kill_mode == KILL_PROCESS ? s->control_pid : -s->control_pid, sig) < 0 && errno != ESRCH)
1592 if (sent && (s->main_pid > 0 || s->control_pid > 0)) {
1593 if (s->timeout_usec > 0)
1594 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1597 service_set_state(s, state);
1598 } else if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1599 service_enter_stop_post(s, true);
1601 service_enter_dead(s, true, true);
1606 log_warning("%s failed to kill processes: %s", s->meta.id, strerror(-r));
1608 if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1609 service_enter_stop_post(s, false);
1611 service_enter_dead(s, false, true);
1614 static void service_enter_stop(Service *s, bool success) {
1622 service_unwatch_control_pid(s);
1624 s->control_command_id = SERVICE_EXEC_STOP;
1625 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP])) {
1626 if ((r = service_spawn(s,
1630 !s->permissions_start_only,
1631 !s->root_directory_start_only,
1634 &s->control_pid)) < 0)
1637 service_set_state(s, SERVICE_STOP);
1639 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
1644 log_warning("%s failed to run 'stop' task: %s", s->meta.id, strerror(-r));
1645 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1648 static void service_enter_running(Service *s, bool success) {
1649 int main_pid_ok, cgroup_ok;
1655 main_pid_ok = main_pid_good(s);
1656 cgroup_ok = cgroup_good(s);
1658 if ((main_pid_ok > 0 || (main_pid_ok < 0 && cgroup_ok != 0)) &&
1659 (s->bus_name_good || s->type != SERVICE_DBUS))
1660 service_set_state(s, SERVICE_RUNNING);
1661 else if (s->valid_no_process)
1662 service_set_state(s, SERVICE_EXITED);
1664 service_enter_stop(s, true);
1667 static void service_enter_start_post(Service *s) {
1671 service_unwatch_control_pid(s);
1673 s->control_command_id = SERVICE_EXEC_START_POST;
1674 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_POST])) {
1675 if ((r = service_spawn(s,
1679 !s->permissions_start_only,
1680 !s->root_directory_start_only,
1683 &s->control_pid)) < 0)
1686 service_set_state(s, SERVICE_START_POST);
1688 service_enter_running(s, true);
1693 log_warning("%s failed to run 'start-post' task: %s", s->meta.id, strerror(-r));
1694 service_enter_stop(s, false);
1697 static void service_enter_start(Service *s) {
1703 assert(s->exec_command[SERVICE_EXEC_START]);
1704 assert(!s->exec_command[SERVICE_EXEC_START]->command_next);
1706 if (s->type == SERVICE_FORKING)
1707 service_unwatch_control_pid(s);
1709 service_unwatch_main_pid(s);
1711 if ((r = service_spawn(s,
1712 s->exec_command[SERVICE_EXEC_START],
1713 s->type == SERVICE_FORKING || s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY,
1718 s->notify_access != NOTIFY_NONE,
1722 if (s->type == SERVICE_SIMPLE) {
1723 /* For simple services we immediately start
1724 * the START_POST binaries. */
1726 service_set_main_pid(s, pid);
1727 service_enter_start_post(s);
1729 } else if (s->type == SERVICE_FORKING) {
1731 /* For forking services we wait until the start
1732 * process exited. */
1734 s->control_command_id = SERVICE_EXEC_START;
1735 s->control_command = s->exec_command[SERVICE_EXEC_START];
1737 s->control_pid = pid;
1738 service_set_state(s, SERVICE_START);
1740 } else if (s->type == SERVICE_FINISH ||
1741 s->type == SERVICE_DBUS ||
1742 s->type == SERVICE_NOTIFY) {
1744 /* For finishing services we wait until the start
1745 * process exited, too, but it is our main process. */
1747 /* For D-Bus services we know the main pid right away,
1748 * but wait for the bus name to appear on the
1749 * bus. Notify services are similar. */
1751 service_set_main_pid(s, pid);
1752 service_set_state(s, SERVICE_START);
1754 assert_not_reached("Unknown service type");
1759 log_warning("%s failed to run 'start' task: %s", s->meta.id, strerror(-r));
1760 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1763 static void service_enter_start_pre(Service *s) {
1768 service_unwatch_control_pid(s);
1770 s->control_command_id = SERVICE_EXEC_START_PRE;
1771 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_PRE])) {
1772 if ((r = service_spawn(s,
1776 !s->permissions_start_only,
1777 !s->root_directory_start_only,
1780 &s->control_pid)) < 0)
1783 service_set_state(s, SERVICE_START_PRE);
1785 service_enter_start(s);
1790 log_warning("%s failed to run 'start-pre' task: %s", s->meta.id, strerror(-r));
1791 service_enter_dead(s, false, true);
1794 static void service_enter_restart(Service *s) {
1799 dbus_error_init(&error);
1801 service_enter_dead(s, true, false);
1803 if ((r = manager_add_job(s->meta.manager, JOB_START, UNIT(s), JOB_FAIL, false, NULL, NULL)) < 0)
1806 log_debug("%s scheduled restart job.", s->meta.id);
1810 log_warning("%s failed to schedule restart job: %s", s->meta.id, bus_error(&error, -r));
1811 service_enter_dead(s, false, false);
1813 dbus_error_free(&error);
1816 static void service_enter_reload(Service *s) {
1821 service_unwatch_control_pid(s);
1823 s->control_command_id = SERVICE_EXEC_RELOAD;
1824 if ((s->control_command = s->exec_command[SERVICE_EXEC_RELOAD])) {
1825 if ((r = service_spawn(s,
1829 !s->permissions_start_only,
1830 !s->root_directory_start_only,
1833 &s->control_pid)) < 0)
1836 service_set_state(s, SERVICE_RELOAD);
1838 service_enter_running(s, true);
1843 log_warning("%s failed to run 'reload' task: %s", s->meta.id, strerror(-r));
1844 service_enter_stop(s, false);
1847 static void service_run_next(Service *s, bool success) {
1851 assert(s->control_command);
1852 assert(s->control_command->command_next);
1857 s->control_command = s->control_command->command_next;
1859 service_unwatch_control_pid(s);
1861 if ((r = service_spawn(s,
1865 !s->permissions_start_only,
1866 !s->root_directory_start_only,
1867 s->control_command_id == SERVICE_EXEC_START_PRE ||
1868 s->control_command_id == SERVICE_EXEC_STOP_POST,
1870 &s->control_pid)) < 0)
1876 log_warning("%s failed to run next task: %s", s->meta.id, strerror(-r));
1878 if (s->state == SERVICE_START_PRE)
1879 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1880 else if (s->state == SERVICE_STOP)
1881 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1882 else if (s->state == SERVICE_STOP_POST)
1883 service_enter_dead(s, false, true);
1885 service_enter_stop(s, false);
1888 static int service_start(Unit *u) {
1889 Service *s = SERVICE(u);
1893 /* We cannot fulfill this request right now, try again later
1895 if (s->state == SERVICE_STOP ||
1896 s->state == SERVICE_STOP_SIGTERM ||
1897 s->state == SERVICE_STOP_SIGKILL ||
1898 s->state == SERVICE_STOP_POST ||
1899 s->state == SERVICE_FINAL_SIGTERM ||
1900 s->state == SERVICE_FINAL_SIGKILL)
1903 /* Already on it! */
1904 if (s->state == SERVICE_START_PRE ||
1905 s->state == SERVICE_START ||
1906 s->state == SERVICE_START_POST)
1909 assert(s->state == SERVICE_DEAD || s->state == SERVICE_MAINTENANCE || s->state == SERVICE_AUTO_RESTART);
1911 /* Make sure we don't enter a busy loop of some kind. */
1912 if (!ratelimit_test(&s->ratelimit)) {
1913 log_warning("%s start request repeated too quickly, refusing to start.", u->meta.id);
1917 if ((s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1918 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1919 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) &&
1921 log_warning("%s can only be started with a per-connection socket.", u->meta.id);
1926 s->main_pid_known = false;
1927 s->allow_restart = true;
1929 service_enter_start_pre(s);
1933 static int service_stop(Unit *u) {
1934 Service *s = SERVICE(u);
1938 /* This is a user request, so don't do restarts on this
1940 s->allow_restart = false;
1943 if (s->state == SERVICE_STOP ||
1944 s->state == SERVICE_STOP_SIGTERM ||
1945 s->state == SERVICE_STOP_SIGKILL ||
1946 s->state == SERVICE_STOP_POST ||
1947 s->state == SERVICE_FINAL_SIGTERM ||
1948 s->state == SERVICE_FINAL_SIGKILL)
1951 /* Don't allow a restart */
1952 if (s->state == SERVICE_AUTO_RESTART) {
1953 service_set_state(s, SERVICE_DEAD);
1957 /* If there's already something running we go directly into
1959 if (s->state == SERVICE_START_PRE ||
1960 s->state == SERVICE_START ||
1961 s->state == SERVICE_START_POST ||
1962 s->state == SERVICE_RELOAD) {
1963 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
1967 assert(s->state == SERVICE_RUNNING ||
1968 s->state == SERVICE_EXITED);
1970 service_enter_stop(s, true);
1974 static int service_reload(Unit *u) {
1975 Service *s = SERVICE(u);
1979 assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
1981 service_enter_reload(s);
1985 static bool service_can_reload(Unit *u) {
1986 Service *s = SERVICE(u);
1990 return !!s->exec_command[SERVICE_EXEC_RELOAD];
1993 static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
1994 Service *s = SERVICE(u);
2000 unit_serialize_item(u, f, "state", service_state_to_string(s->state));
2001 unit_serialize_item(u, f, "failure", yes_no(s->failure));
2003 if (s->control_pid > 0)
2004 unit_serialize_item_format(u, f, "control-pid", "%lu", (unsigned long) s->control_pid);
2006 if (s->main_pid_known && s->main_pid > 0)
2007 unit_serialize_item_format(u, f, "main-pid", "%lu", (unsigned long) s->main_pid);
2009 unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
2012 unit_serialize_item(u, f, "status-text", s->status_text);
2014 /* There's a minor uncleanliness here: if there are multiple
2015 * commands attached here, we will start from the first one
2017 if (s->control_command_id >= 0)
2018 unit_serialize_item(u, f, "control-command", service_exec_command_to_string(s->control_command_id));
2020 if (s->socket_fd >= 0) {
2023 if ((copy = fdset_put_dup(fds, s->socket_fd)) < 0)
2026 unit_serialize_item_format(u, f, "socket-fd", "%i", copy);
2029 if (s->main_exec_status.pid > 0) {
2030 unit_serialize_item_format(u, f, "main-exec-status-pid", "%lu", (unsigned long) s->main_exec_status.pid);
2032 if (s->main_exec_status.start_timestamp.realtime > 0) {
2033 unit_serialize_item_format(u, f, "main-exec-status-start-realtime",
2034 "%llu", (unsigned long long) s->main_exec_status.start_timestamp.realtime);
2036 unit_serialize_item_format(u, f, "main-exec-status-start-monotonic",
2037 "%llu", (unsigned long long) s->main_exec_status.start_timestamp.monotonic);
2040 if (s->main_exec_status.exit_timestamp.realtime > 0) {
2041 unit_serialize_item_format(u, f, "main-exec-status-exit-realtime",
2042 "%llu", (unsigned long long) s->main_exec_status.exit_timestamp.realtime);
2043 unit_serialize_item_format(u, f, "main-exec-status-exit-monotonic",
2044 "%llu", (unsigned long long) s->main_exec_status.exit_timestamp.monotonic);
2046 unit_serialize_item_format(u, f, "main-exec-status-code", "%i", s->main_exec_status.code);
2047 unit_serialize_item_format(u, f, "main-exec-status-status", "%i", s->main_exec_status.status);
2054 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
2055 Service *s = SERVICE(u);
2063 if (streq(key, "state")) {
2066 if ((state = service_state_from_string(value)) < 0)
2067 log_debug("Failed to parse state value %s", value);
2069 s->deserialized_state = state;
2070 } else if (streq(key, "failure")) {
2073 if ((b = parse_boolean(value)) < 0)
2074 log_debug("Failed to parse failure value %s", value);
2076 s->failure = b || s->failure;
2077 } else if (streq(key, "control-pid")) {
2080 if ((r = parse_pid(value, &pid)) < 0)
2081 log_debug("Failed to parse control-pid value %s", value);
2083 s->control_pid = pid;
2084 } else if (streq(key, "main-pid")) {
2087 if ((r = parse_pid(value, &pid)) < 0)
2088 log_debug("Failed to parse main-pid value %s", value);
2090 service_set_main_pid(s, (pid_t) pid);
2091 } else if (streq(key, "main-pid-known")) {
2094 if ((b = parse_boolean(value)) < 0)
2095 log_debug("Failed to parse main-pid-known value %s", value);
2097 s->main_pid_known = b;
2098 } else if (streq(key, "status-text")) {
2101 if ((t = strdup(value))) {
2102 free(s->status_text);
2106 } else if (streq(key, "control-command")) {
2107 ServiceExecCommand id;
2109 if ((id = service_exec_command_from_string(value)) < 0)
2110 log_debug("Failed to parse exec-command value %s", value);
2112 s->control_command_id = id;
2113 s->control_command = s->exec_command[id];
2115 } else if (streq(key, "socket-fd")) {
2118 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2119 log_debug("Failed to parse socket-fd value %s", value);
2122 if (s->socket_fd >= 0)
2123 close_nointr_nofail(s->socket_fd);
2124 s->socket_fd = fdset_remove(fds, fd);
2126 } else if (streq(key, "main-exec-status-pid")) {
2129 if ((r = parse_pid(value, &pid)) < 0)
2130 log_debug("Failed to parse main-exec-status-pid value %s", value);
2132 s->main_exec_status.pid = pid;
2133 } else if (streq(key, "main-exec-status-code")) {
2136 if ((r = safe_atoi(value, &i)) < 0)
2137 log_debug("Failed to parse main-exec-status-code value %s", value);
2139 s->main_exec_status.code = i;
2140 } else if (streq(key, "main-exec-status-status")) {
2143 if ((r = safe_atoi(value, &i)) < 0)
2144 log_debug("Failed to parse main-exec-status-status value %s", value);
2146 s->main_exec_status.status = i;
2147 } else if (streq(key, "main-exec-status-start-realtime")) {
2150 if ((r = safe_atou64(value, &k)) < 0)
2151 log_debug("Failed to parse main-exec-status-start-realtime value %s", value);
2153 s->main_exec_status.start_timestamp.realtime = (usec_t) k;
2154 } else if (streq(key, "main-exec-status-start-monotonic")) {
2157 if ((r = safe_atou64(value, &k)) < 0)
2158 log_debug("Failed to parse main-exec-status-start-monotonic value %s", value);
2160 s->main_exec_status.start_timestamp.monotonic = (usec_t) k;
2161 } else if (streq(key, "main-exec-status-exit-realtime")) {
2164 if ((r = safe_atou64(value, &k)) < 0)
2165 log_debug("Failed to parse main-exec-status-exit-realtime value %s", value);
2167 s->main_exec_status.exit_timestamp.realtime = (usec_t) k;
2168 } else if (streq(key, "main-exec-status-exit-monotonic")) {
2171 if ((r = safe_atou64(value, &k)) < 0)
2172 log_debug("Failed to parse main-exec-status-exit-monotonic value %s", value);
2174 s->main_exec_status.exit_timestamp.monotonic = (usec_t) k;
2176 log_debug("Unknown serialization key '%s'", key);
2181 static UnitActiveState service_active_state(Unit *u) {
2184 return state_translation_table[SERVICE(u)->state];
2187 static const char *service_sub_state_to_string(Unit *u) {
2190 return service_state_to_string(SERVICE(u)->state);
2193 static bool service_check_gc(Unit *u) {
2194 Service *s = SERVICE(u);
2198 return !!s->sysv_path;
2201 static bool service_check_snapshot(Unit *u) {
2202 Service *s = SERVICE(u);
2206 return !s->got_socket_fd;
2209 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2210 Service *s = SERVICE(u);
2216 success = is_clean_exit(code, status);
2218 if (s->main_pid == pid) {
2220 exec_status_exit(&s->main_exec_status, pid, code, status);
2223 if (s->type != SERVICE_FORKING) {
2224 assert(s->exec_command[SERVICE_EXEC_START]);
2225 s->exec_command[SERVICE_EXEC_START]->exec_status = s->main_exec_status;
2227 if (s->exec_command[SERVICE_EXEC_START]->ignore)
2231 log_full(success ? LOG_DEBUG : LOG_NOTICE,
2232 "%s: main process exited, code=%s, status=%i", u->meta.id, sigchld_code_to_string(code), status);
2233 s->failure = s->failure || !success;
2235 /* The service exited, so the service is officially
2240 case SERVICE_START_POST:
2241 case SERVICE_RELOAD:
2243 /* Need to wait until the operation is
2248 if (s->type == SERVICE_FINISH) {
2249 /* This was our main goal, so let's go on */
2251 service_enter_start_post(s);
2253 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2256 assert(s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY);
2261 case SERVICE_RUNNING:
2262 service_enter_running(s, success);
2265 case SERVICE_STOP_SIGTERM:
2266 case SERVICE_STOP_SIGKILL:
2268 if (!control_pid_good(s))
2269 service_enter_stop_post(s, success);
2271 /* If there is still a control process, wait for that first */
2275 assert_not_reached("Uh, main process died at wrong time.");
2278 } else if (s->control_pid == pid) {
2280 if (s->control_command) {
2281 exec_status_exit(&s->control_command->exec_status, pid, code, status);
2283 if (s->control_command->ignore)
2289 log_full(success ? LOG_DEBUG : LOG_NOTICE,
2290 "%s: control process exited, code=%s status=%i", u->meta.id, sigchld_code_to_string(code), status);
2291 s->failure = s->failure || !success;
2293 /* If we are shutting things down anyway we
2294 * don't care about failing commands. */
2296 if (s->control_command && s->control_command->command_next && success) {
2298 /* There is another command to *
2299 * execute, so let's do that. */
2301 log_debug("%s running next command for state %s", u->meta.id, service_state_to_string(s->state));
2302 service_run_next(s, success);
2305 /* No further commands for this step, so let's
2306 * figure out what to do next */
2308 s->control_command = NULL;
2309 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2311 log_debug("%s got final SIGCHLD for state %s", u->meta.id, service_state_to_string(s->state));
2315 case SERVICE_START_PRE:
2317 service_enter_start(s);
2319 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2323 assert(s->type == SERVICE_FORKING);
2325 /* Let's try to load the pid
2326 * file here if we can. We
2327 * ignore the return value,
2328 * since the PID file might
2329 * actually be created by a
2330 * START_POST script */
2334 service_load_pid_file(s);
2336 service_enter_start_post(s);
2338 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2342 case SERVICE_START_POST:
2343 if (success && s->pid_file && !s->main_pid_known) {
2346 /* Hmm, let's see if we can
2347 * load the pid now after the
2348 * start-post scripts got
2351 if ((r = service_load_pid_file(s)) < 0)
2352 log_warning("%s: failed to load PID file %s: %s", s->meta.id, s->pid_file, strerror(-r));
2357 case SERVICE_RELOAD:
2359 service_enter_running(s, true);
2361 service_enter_stop(s, false);
2366 service_enter_signal(s, SERVICE_STOP_SIGTERM, success);
2369 case SERVICE_STOP_SIGTERM:
2370 case SERVICE_STOP_SIGKILL:
2371 if (main_pid_good(s) <= 0)
2372 service_enter_stop_post(s, success);
2374 /* If there is still a service
2375 * process around, wait until
2376 * that one quit, too */
2379 case SERVICE_STOP_POST:
2380 case SERVICE_FINAL_SIGTERM:
2381 case SERVICE_FINAL_SIGKILL:
2382 service_enter_dead(s, success, true);
2386 assert_not_reached("Uh, control process died at wrong time.");
2392 static void service_timer_event(Unit *u, uint64_t elapsed, Watch* w) {
2393 Service *s = SERVICE(u);
2396 assert(elapsed == 1);
2398 assert(w == &s->timer_watch);
2402 case SERVICE_START_PRE:
2404 log_warning("%s operation timed out. Terminating.", u->meta.id);
2405 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2408 case SERVICE_START_POST:
2409 case SERVICE_RELOAD:
2410 log_warning("%s operation timed out. Stopping.", u->meta.id);
2411 service_enter_stop(s, false);
2415 log_warning("%s stopping timed out. Terminating.", u->meta.id);
2416 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
2419 case SERVICE_STOP_SIGTERM:
2420 log_warning("%s stopping timed out. Killing.", u->meta.id);
2421 service_enter_signal(s, SERVICE_STOP_SIGKILL, false);
2424 case SERVICE_STOP_SIGKILL:
2425 /* Uh, wie sent a SIGKILL and it is still not gone?
2426 * Must be something we cannot kill, so let's just be
2427 * weirded out and continue */
2429 log_warning("%s still around after SIGKILL. Ignoring.", u->meta.id);
2430 service_enter_stop_post(s, false);
2433 case SERVICE_STOP_POST:
2434 log_warning("%s stopping timed out (2). Terminating.", u->meta.id);
2435 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2438 case SERVICE_FINAL_SIGTERM:
2439 log_warning("%s stopping timed out (2). Killing.", u->meta.id);
2440 service_enter_signal(s, SERVICE_FINAL_SIGKILL, false);
2443 case SERVICE_FINAL_SIGKILL:
2444 log_warning("%s still around after SIGKILL (2). Entering maintenance mode.", u->meta.id);
2445 service_enter_dead(s, false, true);
2448 case SERVICE_AUTO_RESTART:
2449 log_info("%s holdoff time over, scheduling restart.", u->meta.id);
2450 service_enter_restart(s);
2454 assert_not_reached("Timeout at wrong time.");
2458 static void service_cgroup_notify_event(Unit *u) {
2459 Service *s = SERVICE(u);
2463 log_debug("%s: cgroup is empty", u->meta.id);
2467 /* Waiting for SIGCHLD is usually more interesting,
2468 * because it includes return codes/signals. Which is
2469 * why we ignore the cgroup events for most cases,
2470 * except when we don't know pid which to expect the
2473 case SERVICE_RUNNING:
2474 service_enter_running(s, true);
2482 static void service_notify_message(Unit *u, pid_t pid, char **tags) {
2483 Service *s = SERVICE(u);
2488 if (s->notify_access == NOTIFY_NONE) {
2489 log_warning("%s: Got notification message from PID %lu, but reception is disabled.",
2490 u->meta.id, (unsigned long) pid);
2494 if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
2495 log_warning("%s: Got notification message from PID %lu, but reception only permitted for PID %lu",
2496 u->meta.id, (unsigned long) pid, (unsigned long) s->main_pid);
2500 log_debug("%s: Got message", u->meta.id);
2502 /* Interpret MAINPID= */
2503 if ((e = strv_find_prefix(tags, "MAINPID=")) &&
2504 (s->state == SERVICE_START ||
2505 s->state == SERVICE_START_POST ||
2506 s->state == SERVICE_RUNNING ||
2507 s->state == SERVICE_RELOAD)) {
2509 if (parse_pid(e + 8, &pid) < 0)
2510 log_warning("Failed to parse notification message %s", e);
2512 log_debug("%s: got %s", u->meta.id, e);
2513 service_set_main_pid(s, pid);
2517 /* Interpret READY= */
2518 if (s->type == SERVICE_NOTIFY &&
2519 s->state == SERVICE_START &&
2520 strv_find(tags, "READY=1")) {
2521 log_debug("%s: got READY=1", u->meta.id);
2523 service_enter_start_post(s);
2526 /* Interpret STATUS= */
2527 if ((e = strv_find_prefix(tags, "STATUS="))) {
2531 if (!(t = strdup(e+7))) {
2532 log_error("Failed to allocate string.");
2536 log_debug("%s: got %s", u->meta.id, e);
2538 free(s->status_text);
2541 free(s->status_text);
2542 s->status_text = NULL;
2548 static int service_enumerate(Manager *m) {
2552 char *path = NULL, *fpath = NULL, *name = NULL;
2557 STRV_FOREACH(p, m->lookup_paths.sysvrcnd_path)
2558 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++) {
2563 if (asprintf(&path, "%s/%s", *p, rcnd_table[i].path) < 0) {
2571 if (!(d = opendir(path))) {
2572 if (errno != ENOENT)
2573 log_warning("opendir() failed on %s: %s", path, strerror(errno));
2578 while ((de = readdir(d))) {
2582 if (ignore_file(de->d_name))
2585 if (de->d_name[0] != 'S' && de->d_name[0] != 'K')
2588 if (strlen(de->d_name) < 4)
2591 a = undecchar(de->d_name[1]);
2592 b = undecchar(de->d_name[2]);
2599 if (asprintf(&fpath, "%s/%s/%s", *p, rcnd_table[i].path, de->d_name) < 0) {
2604 if (access(fpath, X_OK) < 0) {
2606 if (errno != ENOENT)
2607 log_warning("access() failed on %s: %s", fpath, strerror(errno));
2613 if (!(name = sysv_translate_name(de->d_name + 3))) {
2618 if ((r = manager_load_unit_prepare(m, name, NULL, NULL, &service)) < 0) {
2619 log_warning("Failed to prepare unit %s: %s", name, strerror(-r));
2623 if (de->d_name[0] == 'S' &&
2624 (rcnd_table[i].type == RUNLEVEL_UP || rcnd_table[i].type == RUNLEVEL_SYSINIT))
2625 SERVICE(service)->sysv_start_priority =
2626 MAX(a*10 + b, SERVICE(service)->sysv_start_priority);
2628 manager_dispatch_load_queue(m);
2629 service = unit_follow_merge(service);
2631 /* If this is a native service, rely
2632 * on native ways to pull in a
2633 * service, don't pull it in via sysv
2635 if (service->meta.fragment_path)
2638 if (de->d_name[0] == 'S') {
2640 if ((r = unit_add_two_dependencies_by_name_inverse(service, UNIT_AFTER, UNIT_WANTS, rcnd_table[i].target, NULL, true)) < 0)
2643 } else if (de->d_name[0] == 'K' &&
2644 (rcnd_table[i].type == RUNLEVEL_DOWN ||
2645 rcnd_table[i].type == RUNLEVEL_SYSINIT)) {
2647 /* We honour K links only for
2648 * halt/reboot. For the normal
2649 * runlevels we assume the
2651 * implicitly added by the
2652 * core logic. Also, we don't
2653 * really distuingish here
2654 * between the runlevels 0 and
2655 * 6 and just add them to the
2656 * special shutdown target. On
2657 * SUSE the boot.d/ runlevel
2658 * is also used for shutdown,
2659 * so we add links for that
2660 * too to the shutdown
2663 if ((r = unit_add_two_dependencies_by_name_inverse(service, UNIT_AFTER, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true)) < 0)
2682 static void service_bus_name_owner_change(
2685 const char *old_owner,
2686 const char *new_owner) {
2688 Service *s = SERVICE(u);
2693 assert(streq(s->bus_name, name));
2694 assert(old_owner || new_owner);
2696 if (old_owner && new_owner)
2697 log_debug("%s's D-Bus name %s changed owner from %s to %s", u->meta.id, name, old_owner, new_owner);
2699 log_debug("%s's D-Bus name %s no longer registered by %s", u->meta.id, name, old_owner);
2701 log_debug("%s's D-Bus name %s now registered by %s", u->meta.id, name, new_owner);
2703 s->bus_name_good = !!new_owner;
2705 if (s->type == SERVICE_DBUS) {
2707 /* service_enter_running() will figure out what to
2709 if (s->state == SERVICE_RUNNING)
2710 service_enter_running(s, true);
2711 else if (s->state == SERVICE_START && new_owner)
2712 service_enter_start_post(s);
2714 } else if (new_owner &&
2716 (s->state == SERVICE_START ||
2717 s->state == SERVICE_START_POST ||
2718 s->state == SERVICE_RUNNING ||
2719 s->state == SERVICE_RELOAD)) {
2721 /* Try to acquire PID from bus service */
2722 log_debug("Trying to acquire PID from D-Bus name...");
2724 bus_query_pid(u->meta.manager, name);
2728 static void service_bus_query_pid_done(
2733 Service *s = SERVICE(u);
2738 log_debug("%s's D-Bus name %s is now owned by process %u", u->meta.id, name, (unsigned) pid);
2740 if (s->main_pid <= 0 &&
2741 (s->state == SERVICE_START ||
2742 s->state == SERVICE_START_POST ||
2743 s->state == SERVICE_RUNNING ||
2744 s->state == SERVICE_RELOAD))
2745 service_set_main_pid(s, pid);
2748 int service_set_socket_fd(Service *s, int fd, Socket *sock) {
2752 /* This is called by the socket code when instantiating a new
2753 * service for a stream socket and the socket needs to be
2756 if (s->meta.load_state != UNIT_LOADED)
2759 if (s->socket_fd >= 0)
2762 if (s->state != SERVICE_DEAD)
2766 s->got_socket_fd = true;
2772 static void service_reset_maintenance(Unit *u) {
2773 Service *s = SERVICE(u);
2777 if (s->state == SERVICE_MAINTENANCE)
2778 service_set_state(s, SERVICE_DEAD);
2783 static const char* const service_state_table[_SERVICE_STATE_MAX] = {
2784 [SERVICE_DEAD] = "dead",
2785 [SERVICE_START_PRE] = "start-pre",
2786 [SERVICE_START] = "start",
2787 [SERVICE_START_POST] = "start-post",
2788 [SERVICE_RUNNING] = "running",
2789 [SERVICE_EXITED] = "exited",
2790 [SERVICE_RELOAD] = "reload",
2791 [SERVICE_STOP] = "stop",
2792 [SERVICE_STOP_SIGTERM] = "stop-sigterm",
2793 [SERVICE_STOP_SIGKILL] = "stop-sigkill",
2794 [SERVICE_STOP_POST] = "stop-post",
2795 [SERVICE_FINAL_SIGTERM] = "final-sigterm",
2796 [SERVICE_FINAL_SIGKILL] = "final-sigkill",
2797 [SERVICE_MAINTENANCE] = "maintenance",
2798 [SERVICE_AUTO_RESTART] = "auto-restart",
2801 DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
2803 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
2804 [SERVICE_ONCE] = "once",
2805 [SERVICE_RESTART_ON_SUCCESS] = "restart-on-success",
2806 [SERVICE_RESTART_ALWAYS] = "restart-always",
2809 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
2811 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
2812 [SERVICE_SIMPLE] = "simple",
2813 [SERVICE_FORKING] = "forking",
2814 [SERVICE_FINISH] = "finish",
2815 [SERVICE_DBUS] = "dbus",
2816 [SERVICE_NOTIFY] = "notify"
2819 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
2821 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
2822 [SERVICE_EXEC_START_PRE] = "ExecStartPre",
2823 [SERVICE_EXEC_START] = "ExecStart",
2824 [SERVICE_EXEC_START_POST] = "ExecStartPost",
2825 [SERVICE_EXEC_RELOAD] = "ExecReload",
2826 [SERVICE_EXEC_STOP] = "ExecStop",
2827 [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
2830 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
2832 static const char* const notify_access_table[_NOTIFY_ACCESS_MAX] = {
2833 [NOTIFY_NONE] = "none",
2834 [NOTIFY_MAIN] = "main",
2835 [NOTIFY_ALL] = "all"
2838 DEFINE_STRING_TABLE_LOOKUP(notify_access, NotifyAccess);
2840 const UnitVTable service_vtable = {
2841 .suffix = ".service",
2842 .show_status = true,
2844 .init = service_init,
2845 .done = service_done,
2846 .load = service_load,
2848 .coldplug = service_coldplug,
2850 .dump = service_dump,
2852 .start = service_start,
2853 .stop = service_stop,
2854 .reload = service_reload,
2856 .can_reload = service_can_reload,
2858 .serialize = service_serialize,
2859 .deserialize_item = service_deserialize_item,
2861 .active_state = service_active_state,
2862 .sub_state_to_string = service_sub_state_to_string,
2864 .check_gc = service_check_gc,
2865 .check_snapshot = service_check_snapshot,
2867 .sigchld_event = service_sigchld_event,
2868 .timer_event = service_timer_event,
2870 .reset_maintenance = service_reset_maintenance,
2872 .cgroup_notify_empty = service_cgroup_notify_event,
2873 .notify_message = service_notify_message,
2875 .bus_name_owner_change = service_bus_name_owner_change,
2876 .bus_query_pid_done = service_bus_query_pid_done,
2878 .bus_message_handler = bus_service_message_handler,
2880 .enumerate = service_enumerate