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 */
53 { "rc0.d", SPECIAL_POWEROFF_TARGET, RUNLEVEL_DOWN },
54 { "rc1.d", SPECIAL_RESCUE_TARGET, RUNLEVEL_UP },
55 { "rc2.d", SPECIAL_RUNLEVEL2_TARGET, RUNLEVEL_UP },
56 { "rc3.d", SPECIAL_RUNLEVEL3_TARGET, RUNLEVEL_UP },
57 { "rc4.d", SPECIAL_RUNLEVEL4_TARGET, RUNLEVEL_UP },
58 { "rc5.d", SPECIAL_RUNLEVEL5_TARGET, RUNLEVEL_UP },
59 { "rc6.d", SPECIAL_REBOOT_TARGET, RUNLEVEL_DOWN },
61 /* SUSE style boot.d */
62 { "boot.d", SPECIAL_SYSINIT_TARGET, RUNLEVEL_SYSINIT },
64 /* Debian style rcS.d */
65 { "rcS.d", SPECIAL_SYSINIT_TARGET, RUNLEVEL_SYSINIT },
68 #define RUNLEVELS_UP "12345"
69 /* #define RUNLEVELS_DOWN "06" */
70 /* #define RUNLEVELS_BOOT "bBsS" */
72 static const UnitActiveState state_translation_table[_SERVICE_STATE_MAX] = {
73 [SERVICE_DEAD] = UNIT_INACTIVE,
74 [SERVICE_START_PRE] = UNIT_ACTIVATING,
75 [SERVICE_START] = UNIT_ACTIVATING,
76 [SERVICE_START_POST] = UNIT_ACTIVATING,
77 [SERVICE_RUNNING] = UNIT_ACTIVE,
78 [SERVICE_EXITED] = UNIT_ACTIVE,
79 [SERVICE_RELOAD] = UNIT_RELOADING,
80 [SERVICE_STOP] = UNIT_DEACTIVATING,
81 [SERVICE_STOP_SIGTERM] = UNIT_DEACTIVATING,
82 [SERVICE_STOP_SIGKILL] = UNIT_DEACTIVATING,
83 [SERVICE_STOP_POST] = UNIT_DEACTIVATING,
84 [SERVICE_FINAL_SIGTERM] = UNIT_DEACTIVATING,
85 [SERVICE_FINAL_SIGKILL] = UNIT_DEACTIVATING,
86 [SERVICE_MAINTENANCE] = UNIT_MAINTENANCE,
87 [SERVICE_AUTO_RESTART] = UNIT_ACTIVATING
90 static void service_init(Unit *u) {
91 Service *s = SERVICE(u);
94 assert(u->meta.load_state == UNIT_STUB);
96 s->timeout_usec = DEFAULT_TIMEOUT_USEC;
97 s->restart_usec = DEFAULT_RESTART_USEC;
98 s->timer_watch.type = WATCH_INVALID;
99 s->sysv_start_priority = -1;
102 exec_context_init(&s->exec_context);
104 RATELIMIT_INIT(s->ratelimit, 10*USEC_PER_SEC, 5);
106 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
109 static void service_unwatch_control_pid(Service *s) {
112 if (s->control_pid <= 0)
115 unit_unwatch_pid(UNIT(s), s->control_pid);
119 static void service_unwatch_main_pid(Service *s) {
122 if (s->main_pid <= 0)
125 unit_unwatch_pid(UNIT(s), s->main_pid);
129 static int service_set_main_pid(Service *s, pid_t pid) {
140 if (get_parent_of_pid(pid, &ppid) >= 0 && ppid != getpid())
141 log_warning("%s: Supervising process %lu which is not our child. We'll most likely not notice when it exits.",
142 s->meta.id, (unsigned long) pid);
145 s->main_pid_known = true;
147 exec_status_start(&s->main_exec_status, pid);
152 static void service_close_socket_fd(Service *s) {
155 if (s->socket_fd < 0)
158 close_nointr_nofail(s->socket_fd);
162 static void service_connection_unref(Service *s) {
168 socket_connection_unref(s->socket);
172 static void service_done(Unit *u) {
173 Service *s = SERVICE(u);
183 free(s->sysv_runlevels);
184 s->sysv_runlevels = NULL;
186 free(s->status_text);
187 s->status_text = NULL;
189 exec_context_done(&s->exec_context);
190 exec_command_free_array(s->exec_command, _SERVICE_EXEC_COMMAND_MAX);
191 s->control_command = NULL;
193 /* This will leak a process, but at least no memory or any of
195 service_unwatch_main_pid(s);
196 service_unwatch_control_pid(s);
199 unit_unwatch_bus_name(UNIT(u), s->bus_name);
204 service_close_socket_fd(s);
205 service_connection_unref(s);
207 unit_unwatch_timer(u, &s->timer_watch);
210 static char *sysv_translate_name(const char *name) {
213 if (!(r = new(char, strlen(name) + sizeof(".service"))))
216 if (startswith(name, "boot."))
217 /* Drop SuSE-style boot. prefix */
218 strcpy(stpcpy(r, name + 5), ".service");
219 else if (endswith(name, ".sh"))
220 /* Drop Debian-style .sh suffix */
221 strcpy(stpcpy(r, name) - 3, ".service");
223 /* Normal init scripts */
224 strcpy(stpcpy(r, name), ".service");
229 static int sysv_translate_facility(const char *name, char **_r) {
231 static const char * const table[] = {
232 /* LSB defined facilities */
233 "$local_fs", SPECIAL_LOCAL_FS_TARGET,
234 "$network", SPECIAL_NETWORK_TARGET,
235 "$named", SPECIAL_NSS_LOOKUP_TARGET,
236 "$portmap", SPECIAL_RPCBIND_TARGET,
237 "$remote_fs", SPECIAL_REMOTE_FS_TARGET,
238 "$syslog", SPECIAL_SYSLOG_TARGET,
239 "$time", SPECIAL_RTC_SET_TARGET,
241 /* Debian extensions */
242 "$mail-transport-agent", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
243 "$mail-transfer-agent", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
244 "$x-display-manager", SPECIAL_DISPLAY_MANAGER_SERVICE
250 for (i = 0; i < ELEMENTSOF(table); i += 2)
251 if (streq(table[i], name)) {
252 if (!(r = strdup(table[i+1])))
261 if (!(r = sysv_translate_name(name)))
272 static int sysv_fix_order(Service *s) {
278 if (s->sysv_start_priority < 0)
281 /* For each pair of services where at least one lacks a LSB
282 * header, we use the start priority value to order things. */
284 LIST_FOREACH(units_per_type, other, s->meta.manager->units_per_type[UNIT_SERVICE]) {
288 t = (Service*) other;
293 if (t->sysv_start_priority < 0)
296 /* If both units have modern headers we don't care
297 * about the priorities */
298 if ((!s->sysv_path || s->sysv_has_lsb) &&
299 (!t->sysv_path || t->sysv_has_lsb))
302 if (t->sysv_start_priority < s->sysv_start_priority)
304 else if (t->sysv_start_priority > s->sysv_start_priority)
309 /* FIXME: Maybe we should compare the name here lexicographically? */
311 if (!(r = unit_add_dependency(UNIT(s), d, UNIT(t), true)) < 0)
318 static ExecCommand *exec_command_new(const char *path, const char *arg1) {
321 if (!(c = new0(ExecCommand, 1)))
324 if (!(c->path = strdup(path))) {
329 if (!(c->argv = strv_new(path, arg1, NULL))) {
338 static int sysv_exec_commands(Service *s) {
342 assert(s->sysv_path);
344 if (!(c = exec_command_new(s->sysv_path, "start")))
346 exec_command_append_list(s->exec_command+SERVICE_EXEC_START, c);
348 if (!(c = exec_command_new(s->sysv_path, "stop")))
350 exec_command_append_list(s->exec_command+SERVICE_EXEC_STOP, c);
352 if (!(c = exec_command_new(s->sysv_path, "reload")))
354 exec_command_append_list(s->exec_command+SERVICE_EXEC_RELOAD, c);
359 static int service_load_sysv_path(Service *s, const char *path) {
376 if (!(f = fopen(path, "re"))) {
377 r = errno == ENOENT ? 0 : -errno;
382 if (!(s->sysv_path = strdup(path))) {
388 char l[LINE_MAX], *t;
390 if (!fgets(l, sizeof(l), f)) {
395 log_error("Failed to read configuration file '%s': %s", path, strerror(-r));
405 if (state == NORMAL && streq(t, "### BEGIN INIT INFO")) {
407 s->sysv_has_lsb = true;
411 if ((state == LSB_DESCRIPTION || state == LSB) && streq(t, "### END INIT INFO")) {
417 t += strspn(t, WHITESPACE);
419 if (state == NORMAL) {
421 /* Try to parse Red Hat style chkconfig headers */
423 if (startswith_no_case(t, "chkconfig:")) {
425 char runlevels[16], *k;
429 if (sscanf(t+10, "%15s %i %*i",
431 &start_priority) != 2) {
433 log_warning("[%s:%u] Failed to parse chkconfig line. Ignoring.", path, line);
437 /* A start priority gathered from the
438 * symlink farms is preferred over the
439 * data from the LSB header. */
440 if (start_priority < 0 || start_priority > 99)
441 log_warning("[%s:%u] Start priority out of range. Ignoring.", path, line);
442 else if (s->sysv_start_priority < 0)
443 s->sysv_start_priority = start_priority;
445 char_array_0(runlevels);
446 k = delete_chars(runlevels, WHITESPACE "-");
451 if (!(d = strdup(k))) {
456 free(s->sysv_runlevels);
457 s->sysv_runlevels = d;
460 } else if (startswith_no_case(t, "description:") &&
461 !u->meta.description) {
463 size_t k = strlen(t);
466 if (t[k-1] == '\\') {
471 if (!(d = strdup(strstrip(t+12)))) {
476 free(u->meta.description);
477 u->meta.description = d;
479 } else if (startswith_no_case(t, "pidfile:")) {
486 if (!path_is_absolute(fn)) {
487 log_warning("[%s:%u] PID file not absolute. Ignoring.", path, line);
491 if (!(fn = strdup(fn))) {
500 } else if (state == DESCRIPTION) {
502 /* Try to parse Red Hat style description
505 size_t k = strlen(t);
513 assert(u->meta.description);
514 if (asprintf(&d, "%s %s", u->meta.description, strstrip(t)) < 0) {
519 free(u->meta.description);
520 u->meta.description = d;
522 } else if (state == LSB || state == LSB_DESCRIPTION) {
524 if (startswith_no_case(t, "Provides:")) {
530 FOREACH_WORD_QUOTED(w, z, t+9, i) {
533 if (!(n = strndup(w, z))) {
538 r = sysv_translate_facility(n, &m);
547 if (unit_name_to_type(m) == UNIT_SERVICE)
548 r = unit_add_name(u, m);
550 r = unit_add_two_dependencies_by_name_inverse(u, UNIT_AFTER, UNIT_REQUIRES, m, NULL, true);
558 } else if (startswith_no_case(t, "Required-Start:") ||
559 startswith_no_case(t, "Should-Start:") ||
560 startswith_no_case(t, "X-Start-Before:") ||
561 startswith_no_case(t, "X-Start-After:")) {
567 FOREACH_WORD_QUOTED(w, z, strchr(t, ':')+1, i) {
570 if (!(n = strndup(w, z))) {
575 r = sysv_translate_facility(n, &m);
584 r = unit_add_dependency_by_name(u, startswith_no_case(t, "X-Start-Before:") ? UNIT_BEFORE : UNIT_AFTER, m, NULL, true);
590 } else if (startswith_no_case(t, "Default-Start:")) {
595 k = delete_chars(t+14, WHITESPACE "-");
598 if (!(d = strdup(k))) {
603 free(s->sysv_runlevels);
604 s->sysv_runlevels = d;
607 } else if (startswith_no_case(t, "Description:") &&
608 !u->meta.description) {
611 /* We use the long description only if
612 * no short description is set. */
614 state = LSB_DESCRIPTION;
616 if (!(d = strdup(strstrip(t+12)))) {
621 free(u->meta.description);
622 u->meta.description = d;
624 } else if (startswith_no_case(t, "Short-Description:")) {
629 if (!(d = strdup(strstrip(t+18)))) {
634 free(u->meta.description);
635 u->meta.description = d;
637 } else if (startswith_no_case(t, "X-Interactive:")) {
640 if ((b = parse_boolean(strstrip(t+14))) < 0) {
641 log_warning("[%s:%u] Couldn't parse interactive flag. Ignoring.", path, line);
646 s->exec_context.std_input = EXEC_INPUT_TTY;
648 s->exec_context.std_input = EXEC_INPUT_NULL;
650 } else if (state == LSB_DESCRIPTION) {
652 if (startswith(l, "#\t") || startswith(l, "# ")) {
655 assert(u->meta.description);
656 if (asprintf(&d, "%s %s", u->meta.description, t) < 0) {
661 free(u->meta.description);
662 u->meta.description = d;
669 if ((r = sysv_exec_commands(s)) < 0)
672 if (s->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, s->sysv_runlevels)) {
673 /* If there a runlevels configured for this service
674 * but none of the standard ones, then we assume this
675 * is some special kind of service (which might be
676 * needed for early boot) and don't create any links
679 s->meta.default_dependencies = false;
681 /* Don't timeout special services during boot (like fsck) */
685 /* Special setting for all SysV services */
686 s->type = SERVICE_FORKING;
687 s->valid_no_process = true;
688 s->restart = SERVICE_ONCE;
689 s->exec_context.std_output = EXEC_OUTPUT_TTY;
690 s->exec_context.kill_mode = KILL_PROCESS_GROUP;
692 u->meta.load_state = UNIT_LOADED;
703 static int service_load_sysv_name(Service *s, const char *name) {
709 /* For SysV services we strip the boot. or .sh
710 * prefixes/suffixes. */
711 if (startswith(name, "boot.") ||
712 endswith(name, ".sh.service"))
715 STRV_FOREACH(p, s->meta.manager->lookup_paths.sysvinit_path) {
719 if (asprintf(&path, "%s/%s", *p, name) < 0)
722 assert(endswith(path, ".service"));
723 path[strlen(path)-8] = 0;
725 r = service_load_sysv_path(s, path);
727 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
728 /* Try Debian style xxx.sh source'able init scripts */
730 r = service_load_sysv_path(s, path);
735 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
736 /* Try SUSE style boot.xxx init scripts */
738 if (asprintf(&path, "%s/boot.%s", *p, name) < 0)
741 path[strlen(path)-8] = 0;
742 r = service_load_sysv_path(s, path);
749 if ((s->meta.load_state != UNIT_STUB))
756 static int service_load_sysv(Service *s) {
763 /* Load service data from SysV init scripts, preferably with
766 if (strv_isempty(s->meta.manager->lookup_paths.sysvinit_path))
769 if ((t = s->meta.id))
770 if ((r = service_load_sysv_name(s, t)) < 0)
773 if (s->meta.load_state == UNIT_STUB)
774 SET_FOREACH(t, s->meta.names, i) {
778 if ((r == service_load_sysv_name(s, t)) < 0)
781 if (s->meta.load_state != UNIT_STUB)
788 static int service_add_bus_name(Service *s) {
795 if (asprintf(&n, "dbus-%s.service", s->bus_name) < 0)
798 r = unit_merge_by_name(UNIT(s), n);
804 static int service_verify(Service *s) {
807 if (s->meta.load_state != UNIT_LOADED)
810 if (!s->exec_command[SERVICE_EXEC_START]) {
811 log_error("%s lacks ExecStart setting. Refusing.", s->meta.id);
815 if (s->exec_command[SERVICE_EXEC_START]->command_next) {
816 log_error("%s has more than one ExecStart setting. Refusing.", s->meta.id);
820 if (s->type == SERVICE_DBUS && !s->bus_name) {
821 log_error("%s is of type D-Bus but no D-Bus service name has been specified. Refusing.", s->meta.id);
825 if (s->exec_context.pam_name && s->exec_context.kill_mode != KILL_CONTROL_GROUP) {
826 log_error("%s has PAM enabled. Kill mode must be set to 'control-group'. Refusing.", s->meta.id);
833 static int service_add_default_dependencies(Service *s) {
838 /* Add a number of automatic dependencies useful for the
839 * majority of services. */
841 /* First, pull in base system */
842 if (s->meta.manager->running_as == MANAGER_SYSTEM) {
844 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_BASIC_TARGET, NULL, true)) < 0)
847 } else if (s->meta.manager->running_as == MANAGER_SESSION) {
849 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SOCKETS_TARGET, NULL, true)) < 0)
853 /* Second, activate normal shutdown */
854 return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true);
857 static int service_load(Unit *u) {
859 Service *s = SERVICE(u);
863 /* Load a .service file */
864 if ((r = unit_load_fragment(u)) < 0)
867 /* Load a classic init script as a fallback, if we couldn't find anything */
868 if (u->meta.load_state == UNIT_STUB)
869 if ((r = service_load_sysv(s)) < 0)
872 /* Still nothing found? Then let's give up */
873 if (u->meta.load_state == UNIT_STUB)
876 /* We were able to load something, then let's add in the
877 * dropin directories. */
878 if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
881 /* This is a new unit? Then let's add in some extras */
882 if (u->meta.load_state == UNIT_LOADED) {
883 if ((r = unit_add_exec_dependencies(u, &s->exec_context)) < 0)
886 if ((r = unit_add_default_cgroup(u)) < 0)
889 if ((r = sysv_fix_order(s)) < 0)
893 if ((r = service_add_bus_name(s)) < 0)
896 if ((r = unit_watch_bus_name(u, s->bus_name)) < 0)
900 if (s->type == SERVICE_NOTIFY && s->notify_access == NOTIFY_NONE)
901 s->notify_access = NOTIFY_MAIN;
903 if (s->type == SERVICE_DBUS || s->bus_name)
904 if ((r = unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_REQUIRES, SPECIAL_DBUS_TARGET, NULL, true)) < 0)
907 if (s->meta.default_dependencies)
908 if ((r = service_add_default_dependencies(s)) < 0)
912 return service_verify(s);
915 static void service_dump(Unit *u, FILE *f, const char *prefix) {
917 ServiceExecCommand c;
918 Service *s = SERVICE(u);
924 p2 = strappend(prefix, "\t");
925 prefix2 = p2 ? p2 : prefix;
928 "%sService State: %s\n"
929 "%sPermissionsStartOnly: %s\n"
930 "%sRootDirectoryStartOnly: %s\n"
931 "%sValidNoProcess: %s\n"
933 "%sNotifyAccess: %s\n",
934 prefix, service_state_to_string(s->state),
935 prefix, yes_no(s->permissions_start_only),
936 prefix, yes_no(s->root_directory_start_only),
937 prefix, yes_no(s->valid_no_process),
938 prefix, service_type_to_string(s->type),
939 prefix, notify_access_to_string(s->notify_access));
941 if (s->control_pid > 0)
943 "%sControl PID: %lu\n",
944 prefix, (unsigned long) s->control_pid);
949 prefix, (unsigned long) s->main_pid);
954 prefix, s->pid_file);
959 "%sBus Name Good: %s\n",
961 prefix, yes_no(s->bus_name_good));
963 exec_context_dump(&s->exec_context, f, prefix);
965 for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
967 if (!s->exec_command[c])
970 fprintf(f, "%s-> %s:\n",
971 prefix, service_exec_command_to_string(c));
973 exec_command_dump_list(s->exec_command[c], f, prefix2);
978 "%sSysV Init Script Path: %s\n"
979 "%sSysV Init Script has LSB Header: %s\n",
980 prefix, s->sysv_path,
981 prefix, yes_no(s->sysv_has_lsb));
983 if (s->sysv_start_priority >= 0)
985 "%sSysVStartPriority: %i\n",
986 prefix, s->sysv_start_priority);
988 if (s->sysv_runlevels)
989 fprintf(f, "%sSysVRunLevels: %s\n",
990 prefix, s->sysv_runlevels);
993 fprintf(f, "%sStatus Text: %s\n",
994 prefix, s->status_text);
999 static int service_load_pid_file(Service *s) {
1006 if (s->main_pid_known)
1009 assert(s->main_pid <= 0);
1014 if ((r = read_one_line_file(s->pid_file, &k)) < 0)
1017 r = parse_pid(k, &pid);
1023 if (kill(pid, 0) < 0 && errno != EPERM) {
1024 log_warning("PID %lu read from file %s does not exist. Your service or init script might be broken.",
1025 (unsigned long) pid, s->pid_file);
1029 if ((r = service_set_main_pid(s, pid)) < 0)
1032 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1033 /* FIXME: we need to do something here */
1039 static int service_get_sockets(Service *s, Set **_set) {
1048 if (s->socket_fd >= 0)
1051 /* Collects all Socket objects that belong to this
1052 * service. Note that a service might have multiple sockets
1053 * via multiple names. */
1055 if (!(set = set_new(NULL, NULL)))
1058 SET_FOREACH(t, s->meta.names, i) {
1062 /* Look for all socket objects that go by any of our
1063 * units and collect their fds */
1065 if (!(k = unit_name_change_suffix(t, ".socket"))) {
1070 p = manager_get_unit(s->meta.manager, k);
1076 if ((r = set_put(set, p)) < 0)
1088 static int service_notify_sockets_dead(Service *s) {
1096 if (s->socket_fd >= 0)
1099 /* Notifies all our sockets when we die */
1100 if ((r = service_get_sockets(s, &set)) < 0)
1103 SET_FOREACH(sock, set, i)
1104 socket_notify_service_dead(sock);
1111 static void service_set_state(Service *s, ServiceState state) {
1112 ServiceState old_state;
1115 old_state = s->state;
1118 if (state != SERVICE_START_PRE &&
1119 state != SERVICE_START &&
1120 state != SERVICE_START_POST &&
1121 state != SERVICE_RELOAD &&
1122 state != SERVICE_STOP &&
1123 state != SERVICE_STOP_SIGTERM &&
1124 state != SERVICE_STOP_SIGKILL &&
1125 state != SERVICE_STOP_POST &&
1126 state != SERVICE_FINAL_SIGTERM &&
1127 state != SERVICE_FINAL_SIGKILL &&
1128 state != SERVICE_AUTO_RESTART)
1129 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1131 if (state != SERVICE_START &&
1132 state != SERVICE_START_POST &&
1133 state != SERVICE_RUNNING &&
1134 state != SERVICE_RELOAD &&
1135 state != SERVICE_STOP &&
1136 state != SERVICE_STOP_SIGTERM &&
1137 state != SERVICE_STOP_SIGKILL)
1138 service_unwatch_main_pid(s);
1140 if (state != SERVICE_START_PRE &&
1141 state != SERVICE_START &&
1142 state != SERVICE_START_POST &&
1143 state != SERVICE_RELOAD &&
1144 state != SERVICE_STOP &&
1145 state != SERVICE_STOP_SIGTERM &&
1146 state != SERVICE_STOP_SIGKILL &&
1147 state != SERVICE_STOP_POST &&
1148 state != SERVICE_FINAL_SIGTERM &&
1149 state != SERVICE_FINAL_SIGKILL) {
1150 service_unwatch_control_pid(s);
1151 s->control_command = NULL;
1152 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1155 if (state == SERVICE_DEAD ||
1156 state == SERVICE_STOP ||
1157 state == SERVICE_STOP_SIGTERM ||
1158 state == SERVICE_STOP_SIGKILL ||
1159 state == SERVICE_STOP_POST ||
1160 state == SERVICE_FINAL_SIGTERM ||
1161 state == SERVICE_FINAL_SIGKILL ||
1162 state == SERVICE_MAINTENANCE ||
1163 state == SERVICE_AUTO_RESTART)
1164 service_notify_sockets_dead(s);
1166 if (state != SERVICE_START_PRE &&
1167 state != SERVICE_START &&
1168 state != SERVICE_START_POST &&
1169 state != SERVICE_RUNNING &&
1170 state != SERVICE_RELOAD &&
1171 state != SERVICE_STOP &&
1172 state != SERVICE_STOP_SIGTERM &&
1173 state != SERVICE_STOP_SIGKILL &&
1174 state != SERVICE_STOP_POST &&
1175 state != SERVICE_FINAL_SIGTERM &&
1176 state != SERVICE_FINAL_SIGKILL &&
1177 !(state == SERVICE_DEAD && s->meta.job)) {
1178 service_close_socket_fd(s);
1179 service_connection_unref(s);
1182 /* For the inactive states unit_notify() will trim the cgroup,
1183 * but for exit we have to do that ourselves... */
1184 if (state == SERVICE_EXITED)
1185 cgroup_bonding_trim_list(s->meta.cgroup_bondings, true);
1187 if (old_state != state)
1188 log_debug("%s changed %s -> %s", s->meta.id, service_state_to_string(old_state), service_state_to_string(state));
1190 unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state]);
1193 static int service_coldplug(Unit *u) {
1194 Service *s = SERVICE(u);
1198 assert(s->state == SERVICE_DEAD);
1200 if (s->deserialized_state != s->state) {
1202 if (s->deserialized_state == SERVICE_START_PRE ||
1203 s->deserialized_state == SERVICE_START ||
1204 s->deserialized_state == SERVICE_START_POST ||
1205 s->deserialized_state == SERVICE_RELOAD ||
1206 s->deserialized_state == SERVICE_STOP ||
1207 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1208 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1209 s->deserialized_state == SERVICE_STOP_POST ||
1210 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1211 s->deserialized_state == SERVICE_FINAL_SIGKILL ||
1212 s->deserialized_state == SERVICE_AUTO_RESTART) {
1214 if (s->deserialized_state == SERVICE_AUTO_RESTART || s->timeout_usec > 0) {
1217 k = s->deserialized_state == SERVICE_AUTO_RESTART ? s->restart_usec : s->timeout_usec;
1219 if ((r = unit_watch_timer(UNIT(s), k, &s->timer_watch)) < 0)
1224 if ((s->deserialized_state == SERVICE_START &&
1225 (s->type == SERVICE_FORKING ||
1226 s->type == SERVICE_DBUS ||
1227 s->type == SERVICE_FINISH ||
1228 s->type == SERVICE_NOTIFY)) ||
1229 s->deserialized_state == SERVICE_START_POST ||
1230 s->deserialized_state == SERVICE_RUNNING ||
1231 s->deserialized_state == SERVICE_RELOAD ||
1232 s->deserialized_state == SERVICE_STOP ||
1233 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1234 s->deserialized_state == SERVICE_STOP_SIGKILL)
1235 if (s->main_pid > 0)
1236 if ((r = unit_watch_pid(UNIT(s), s->main_pid)) < 0)
1239 if (s->deserialized_state == SERVICE_START_PRE ||
1240 s->deserialized_state == SERVICE_START ||
1241 s->deserialized_state == SERVICE_START_POST ||
1242 s->deserialized_state == SERVICE_RELOAD ||
1243 s->deserialized_state == SERVICE_STOP ||
1244 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1245 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1246 s->deserialized_state == SERVICE_STOP_POST ||
1247 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1248 s->deserialized_state == SERVICE_FINAL_SIGKILL)
1249 if (s->control_pid > 0)
1250 if ((r = unit_watch_pid(UNIT(s), s->control_pid)) < 0)
1253 service_set_state(s, s->deserialized_state);
1259 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
1263 unsigned rn_fds = 0;
1271 if (s->socket_fd >= 0)
1274 if ((r = service_get_sockets(s, &set)) < 0)
1277 SET_FOREACH(sock, set, i) {
1281 if ((r = socket_collect_fds(sock, &cfds, &cn_fds)) < 0)
1293 if (!(t = new(int, rn_fds+cn_fds))) {
1299 memcpy(t, rfds, rn_fds);
1300 memcpy(t+rn_fds, cfds, cn_fds);
1305 rn_fds = rn_fds+cn_fds;
1323 static int service_spawn(
1328 bool apply_permissions,
1330 bool apply_tty_stdin,
1331 bool set_notify_socket,
1336 int *fds = NULL, *fdsbuf = NULL;
1337 unsigned n_fds = 0, n_env = 0;
1338 char **argv = NULL, **final_env = NULL, **our_env = NULL;
1345 s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1346 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1347 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
1349 if (s->socket_fd >= 0) {
1350 fds = &s->socket_fd;
1353 if ((r = service_collect_fds(s, &fdsbuf, &n_fds)) < 0)
1360 if (timeout && s->timeout_usec) {
1361 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1364 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1366 if (!(argv = unit_full_printf_strv(UNIT(s), c->argv))) {
1371 if (!(our_env = new0(char*, 3))) {
1376 if (set_notify_socket)
1377 if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=@%s", s->meta.manager->notify_socket) < 0) {
1382 if (s->main_pid > 0)
1383 if (asprintf(our_env + n_env++, "MAINPID=%lu", (unsigned long) s->main_pid) < 0) {
1388 if (!(final_env = strv_env_merge(2,
1389 s->meta.manager->environment,
1404 s->meta.manager->confirm_spawn,
1405 s->meta.cgroup_bondings,
1412 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1413 /* FIXME: we need to do something here */
1419 strv_free(final_env);
1429 strv_free(final_env);
1432 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1437 static int main_pid_good(Service *s) {
1440 /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1443 /* If we know the pid file, then lets just check if it is
1445 if (s->main_pid_known)
1446 return s->main_pid > 0;
1448 /* We don't know the pid */
1452 static int control_pid_good(Service *s) {
1455 return s->control_pid > 0;
1458 static int cgroup_good(Service *s) {
1463 if ((r = cgroup_bonding_is_empty_list(s->meta.cgroup_bondings)) < 0)
1469 static void service_enter_dead(Service *s, bool success, bool allow_restart) {
1476 if (allow_restart &&
1478 (s->restart == SERVICE_RESTART_ALWAYS ||
1479 (s->restart == SERVICE_RESTART_ON_SUCCESS && !s->failure))) {
1481 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
1484 service_set_state(s, SERVICE_AUTO_RESTART);
1486 service_set_state(s, s->failure ? SERVICE_MAINTENANCE : SERVICE_DEAD);
1491 log_warning("%s failed to run install restart timer: %s", s->meta.id, strerror(-r));
1492 service_enter_dead(s, false, false);
1495 static void service_enter_signal(Service *s, ServiceState state, bool success);
1497 static void service_enter_stop_post(Service *s, bool success) {
1504 service_unwatch_control_pid(s);
1506 s->control_command_id = SERVICE_EXEC_STOP_POST;
1507 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST])) {
1508 if ((r = service_spawn(s,
1512 !s->permissions_start_only,
1513 !s->root_directory_start_only,
1516 &s->control_pid)) < 0)
1520 service_set_state(s, SERVICE_STOP_POST);
1522 service_enter_signal(s, SERVICE_FINAL_SIGTERM, true);
1527 log_warning("%s failed to run 'stop-post' task: %s", s->meta.id, strerror(-r));
1528 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1531 static void service_enter_signal(Service *s, ServiceState state, bool success) {
1540 if (s->exec_context.kill_mode != KILL_NONE) {
1541 int sig = (state == SERVICE_STOP_SIGTERM || state == SERVICE_FINAL_SIGTERM) ? s->exec_context.kill_signal : SIGKILL;
1543 if (s->exec_context.kill_mode == KILL_CONTROL_GROUP) {
1545 if ((r = cgroup_bonding_kill_list(s->meta.cgroup_bondings, sig)) < 0) {
1546 if (r != -EAGAIN && r != -ESRCH)
1555 if (s->main_pid > 0) {
1556 if (kill(s->exec_context.kill_mode == KILL_PROCESS ? s->main_pid : -s->main_pid, sig) < 0 && errno != ESRCH)
1562 if (s->control_pid > 0) {
1563 if (kill(s->exec_context.kill_mode == KILL_PROCESS ? s->control_pid : -s->control_pid, sig) < 0 && errno != ESRCH)
1574 if (sent && (s->main_pid > 0 || s->control_pid > 0)) {
1575 if (s->timeout_usec > 0)
1576 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1579 service_set_state(s, state);
1580 } else if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1581 service_enter_stop_post(s, true);
1583 service_enter_dead(s, true, true);
1588 log_warning("%s failed to kill processes: %s", s->meta.id, strerror(-r));
1590 if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1591 service_enter_stop_post(s, false);
1593 service_enter_dead(s, false, true);
1596 static void service_enter_stop(Service *s, bool success) {
1604 service_unwatch_control_pid(s);
1606 s->control_command_id = SERVICE_EXEC_STOP;
1607 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP])) {
1608 if ((r = service_spawn(s,
1612 !s->permissions_start_only,
1613 !s->root_directory_start_only,
1616 &s->control_pid)) < 0)
1619 service_set_state(s, SERVICE_STOP);
1621 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
1626 log_warning("%s failed to run 'stop' task: %s", s->meta.id, strerror(-r));
1627 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1630 static void service_enter_running(Service *s, bool success) {
1631 int main_pid_ok, cgroup_ok;
1637 main_pid_ok = main_pid_good(s);
1638 cgroup_ok = cgroup_good(s);
1640 if ((main_pid_ok > 0 || (main_pid_ok < 0 && cgroup_ok != 0)) &&
1641 (s->bus_name_good || s->type != SERVICE_DBUS))
1642 service_set_state(s, SERVICE_RUNNING);
1643 else if (s->valid_no_process)
1644 service_set_state(s, SERVICE_EXITED);
1646 service_enter_stop(s, true);
1649 static void service_enter_start_post(Service *s) {
1653 service_unwatch_control_pid(s);
1655 s->control_command_id = SERVICE_EXEC_START_POST;
1656 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_POST])) {
1657 if ((r = service_spawn(s,
1661 !s->permissions_start_only,
1662 !s->root_directory_start_only,
1665 &s->control_pid)) < 0)
1668 service_set_state(s, SERVICE_START_POST);
1670 service_enter_running(s, true);
1675 log_warning("%s failed to run 'start-post' task: %s", s->meta.id, strerror(-r));
1676 service_enter_stop(s, false);
1679 static void service_enter_start(Service *s) {
1685 assert(s->exec_command[SERVICE_EXEC_START]);
1686 assert(!s->exec_command[SERVICE_EXEC_START]->command_next);
1688 if (s->type == SERVICE_FORKING)
1689 service_unwatch_control_pid(s);
1691 service_unwatch_main_pid(s);
1693 if ((r = service_spawn(s,
1694 s->exec_command[SERVICE_EXEC_START],
1695 s->type == SERVICE_FORKING || s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY,
1700 s->notify_access != NOTIFY_NONE,
1704 if (s->type == SERVICE_SIMPLE) {
1705 /* For simple services we immediately start
1706 * the START_POST binaries. */
1708 service_set_main_pid(s, pid);
1709 service_enter_start_post(s);
1711 } else if (s->type == SERVICE_FORKING) {
1713 /* For forking services we wait until the start
1714 * process exited. */
1716 s->control_command_id = SERVICE_EXEC_START;
1717 s->control_command = s->exec_command[SERVICE_EXEC_START];
1719 s->control_pid = pid;
1720 service_set_state(s, SERVICE_START);
1722 } else if (s->type == SERVICE_FINISH ||
1723 s->type == SERVICE_DBUS ||
1724 s->type == SERVICE_NOTIFY) {
1726 /* For finishing services we wait until the start
1727 * process exited, too, but it is our main process. */
1729 /* For D-Bus services we know the main pid right away,
1730 * but wait for the bus name to appear on the
1731 * bus. Notify services are similar. */
1733 service_set_main_pid(s, pid);
1734 service_set_state(s, SERVICE_START);
1736 assert_not_reached("Unknown service type");
1741 log_warning("%s failed to run 'start' task: %s", s->meta.id, strerror(-r));
1742 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1745 static void service_enter_start_pre(Service *s) {
1750 service_unwatch_control_pid(s);
1752 s->control_command_id = SERVICE_EXEC_START_PRE;
1753 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_PRE])) {
1754 if ((r = service_spawn(s,
1758 !s->permissions_start_only,
1759 !s->root_directory_start_only,
1762 &s->control_pid)) < 0)
1765 service_set_state(s, SERVICE_START_PRE);
1767 service_enter_start(s);
1772 log_warning("%s failed to run 'start-pre' task: %s", s->meta.id, strerror(-r));
1773 service_enter_dead(s, false, true);
1776 static void service_enter_restart(Service *s) {
1781 dbus_error_init(&error);
1783 service_enter_dead(s, true, false);
1785 if ((r = manager_add_job(s->meta.manager, JOB_START, UNIT(s), JOB_FAIL, false, NULL, NULL)) < 0)
1788 log_debug("%s scheduled restart job.", s->meta.id);
1792 log_warning("%s failed to schedule restart job: %s", s->meta.id, bus_error(&error, -r));
1793 service_enter_dead(s, false, false);
1795 dbus_error_free(&error);
1798 static void service_enter_reload(Service *s) {
1803 service_unwatch_control_pid(s);
1805 s->control_command_id = SERVICE_EXEC_RELOAD;
1806 if ((s->control_command = s->exec_command[SERVICE_EXEC_RELOAD])) {
1807 if ((r = service_spawn(s,
1811 !s->permissions_start_only,
1812 !s->root_directory_start_only,
1815 &s->control_pid)) < 0)
1818 service_set_state(s, SERVICE_RELOAD);
1820 service_enter_running(s, true);
1825 log_warning("%s failed to run 'reload' task: %s", s->meta.id, strerror(-r));
1826 service_enter_stop(s, false);
1829 static void service_run_next(Service *s, bool success) {
1833 assert(s->control_command);
1834 assert(s->control_command->command_next);
1839 s->control_command = s->control_command->command_next;
1841 service_unwatch_control_pid(s);
1843 if ((r = service_spawn(s,
1847 !s->permissions_start_only,
1848 !s->root_directory_start_only,
1849 s->control_command_id == SERVICE_EXEC_START_PRE ||
1850 s->control_command_id == SERVICE_EXEC_STOP_POST,
1852 &s->control_pid)) < 0)
1858 log_warning("%s failed to run next task: %s", s->meta.id, strerror(-r));
1860 if (s->state == SERVICE_START_PRE)
1861 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1862 else if (s->state == SERVICE_STOP)
1863 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1864 else if (s->state == SERVICE_STOP_POST)
1865 service_enter_dead(s, false, true);
1867 service_enter_stop(s, false);
1870 static int service_start(Unit *u) {
1871 Service *s = SERVICE(u);
1875 /* We cannot fulfill this request right now, try again later
1877 if (s->state == SERVICE_STOP ||
1878 s->state == SERVICE_STOP_SIGTERM ||
1879 s->state == SERVICE_STOP_SIGKILL ||
1880 s->state == SERVICE_STOP_POST ||
1881 s->state == SERVICE_FINAL_SIGTERM ||
1882 s->state == SERVICE_FINAL_SIGKILL)
1885 /* Already on it! */
1886 if (s->state == SERVICE_START_PRE ||
1887 s->state == SERVICE_START ||
1888 s->state == SERVICE_START_POST)
1891 assert(s->state == SERVICE_DEAD || s->state == SERVICE_MAINTENANCE || s->state == SERVICE_AUTO_RESTART);
1893 /* Make sure we don't enter a busy loop of some kind. */
1894 if (!ratelimit_test(&s->ratelimit)) {
1895 log_warning("%s start request repeated too quickly, refusing to start.", u->meta.id);
1900 s->main_pid_known = false;
1901 s->allow_restart = true;
1903 service_enter_start_pre(s);
1907 static int service_stop(Unit *u) {
1908 Service *s = SERVICE(u);
1912 /* This is a user request, so don't do restarts on this
1914 s->allow_restart = false;
1917 if (s->state == SERVICE_STOP ||
1918 s->state == SERVICE_STOP_SIGTERM ||
1919 s->state == SERVICE_STOP_SIGKILL ||
1920 s->state == SERVICE_STOP_POST ||
1921 s->state == SERVICE_FINAL_SIGTERM ||
1922 s->state == SERVICE_FINAL_SIGKILL)
1925 /* Don't allow a restart */
1926 if (s->state == SERVICE_AUTO_RESTART) {
1927 service_set_state(s, SERVICE_DEAD);
1931 /* If there's already something running we go directly into
1933 if (s->state == SERVICE_START_PRE ||
1934 s->state == SERVICE_START ||
1935 s->state == SERVICE_START_POST ||
1936 s->state == SERVICE_RELOAD) {
1937 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
1941 assert(s->state == SERVICE_RUNNING ||
1942 s->state == SERVICE_EXITED);
1944 service_enter_stop(s, true);
1948 static int service_reload(Unit *u) {
1949 Service *s = SERVICE(u);
1953 assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
1955 service_enter_reload(s);
1959 static bool service_can_reload(Unit *u) {
1960 Service *s = SERVICE(u);
1964 return !!s->exec_command[SERVICE_EXEC_RELOAD];
1967 static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
1968 Service *s = SERVICE(u);
1974 unit_serialize_item(u, f, "state", service_state_to_string(s->state));
1975 unit_serialize_item(u, f, "failure", yes_no(s->failure));
1977 if (s->control_pid > 0)
1978 unit_serialize_item_format(u, f, "control-pid", "%lu", (unsigned long) s->control_pid);
1980 if (s->main_pid_known && s->main_pid > 0)
1981 unit_serialize_item_format(u, f, "main-pid", "%lu", (unsigned long) s->main_pid);
1983 unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
1985 /* There's a minor uncleanliness here: if there are multiple
1986 * commands attached here, we will start from the first one
1988 if (s->control_command_id >= 0)
1989 unit_serialize_item(u, f, "control-command", service_exec_command_to_string(s->control_command_id));
1991 if (s->socket_fd >= 0) {
1994 if ((copy = fdset_put_dup(fds, s->socket_fd)) < 0)
1997 unit_serialize_item_format(u, f, "socket-fd", "%i", copy);
2000 if (s->main_exec_status.pid > 0) {
2001 unit_serialize_item_format(u, f, "main-exec-status-pid", "%lu", (unsigned long) s->main_exec_status.pid);
2003 if (s->main_exec_status.start_timestamp.realtime > 0) {
2004 unit_serialize_item_format(u, f, "main-exec-status-start-realtime",
2005 "%llu", (unsigned long long) s->main_exec_status.start_timestamp.realtime);
2007 unit_serialize_item_format(u, f, "main-exec-status-start-monotonic",
2008 "%llu", (unsigned long long) s->main_exec_status.start_timestamp.monotonic);
2011 if (s->main_exec_status.exit_timestamp.realtime > 0) {
2012 unit_serialize_item_format(u, f, "main-exec-status-exit-realtime",
2013 "%llu", (unsigned long long) s->main_exec_status.exit_timestamp.realtime);
2014 unit_serialize_item_format(u, f, "main-exec-status-exit-monotonic",
2015 "%llu", (unsigned long long) s->main_exec_status.exit_timestamp.monotonic);
2017 unit_serialize_item_format(u, f, "main-exec-status-code", "%i", s->main_exec_status.code);
2018 unit_serialize_item_format(u, f, "main-exec-status-status", "%i", s->main_exec_status.status);
2025 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
2026 Service *s = SERVICE(u);
2034 if (streq(key, "state")) {
2037 if ((state = service_state_from_string(value)) < 0)
2038 log_debug("Failed to parse state value %s", value);
2040 s->deserialized_state = state;
2041 } else if (streq(key, "failure")) {
2044 if ((b = parse_boolean(value)) < 0)
2045 log_debug("Failed to parse failure value %s", value);
2047 s->failure = b || s->failure;
2048 } else if (streq(key, "control-pid")) {
2051 if ((r = parse_pid(value, &pid)) < 0)
2052 log_debug("Failed to parse control-pid value %s", value);
2054 s->control_pid = pid;
2055 } else if (streq(key, "main-pid")) {
2058 if ((r = parse_pid(value, &pid)) < 0)
2059 log_debug("Failed to parse main-pid value %s", value);
2061 service_set_main_pid(s, (pid_t) pid);
2062 } else if (streq(key, "main-pid-known")) {
2065 if ((b = parse_boolean(value)) < 0)
2066 log_debug("Failed to parse main-pid-known value %s", value);
2068 s->main_pid_known = b;
2069 } else if (streq(key, "control-command")) {
2070 ServiceExecCommand id;
2072 if ((id = service_exec_command_from_string(value)) < 0)
2073 log_debug("Failed to parse exec-command value %s", value);
2075 s->control_command_id = id;
2076 s->control_command = s->exec_command[id];
2078 } else if (streq(key, "socket-fd")) {
2081 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2082 log_debug("Failed to parse socket-fd value %s", value);
2085 if (s->socket_fd >= 0)
2086 close_nointr_nofail(s->socket_fd);
2087 s->socket_fd = fdset_remove(fds, fd);
2089 } else if (streq(key, "main-exec-status-pid")) {
2092 if ((r = parse_pid(value, &pid)) < 0)
2093 log_debug("Failed to parse main-exec-status-pid value %s", value);
2095 s->main_exec_status.pid = pid;
2096 } else if (streq(key, "main-exec-status-code")) {
2099 if ((r = safe_atoi(value, &i)) < 0)
2100 log_debug("Failed to parse main-exec-status-code value %s", value);
2102 s->main_exec_status.code = i;
2103 } else if (streq(key, "main-exec-status-status")) {
2106 if ((r = safe_atoi(value, &i)) < 0)
2107 log_debug("Failed to parse main-exec-status-status value %s", value);
2109 s->main_exec_status.status = i;
2110 } else if (streq(key, "main-exec-status-start-realtime")) {
2113 if ((r = safe_atou64(value, &k)) < 0)
2114 log_debug("Failed to parse main-exec-status-start-realtime value %s", value);
2116 s->main_exec_status.start_timestamp.realtime = (usec_t) k;
2117 } else if (streq(key, "main-exec-status-start-monotonic")) {
2120 if ((r = safe_atou64(value, &k)) < 0)
2121 log_debug("Failed to parse main-exec-status-start-monotonic value %s", value);
2123 s->main_exec_status.start_timestamp.monotonic = (usec_t) k;
2124 } else if (streq(key, "main-exec-status-exit-realtime")) {
2127 if ((r = safe_atou64(value, &k)) < 0)
2128 log_debug("Failed to parse main-exec-status-exit-realtime value %s", value);
2130 s->main_exec_status.exit_timestamp.realtime = (usec_t) k;
2131 } else if (streq(key, "main-exec-status-exit-monotonic")) {
2134 if ((r = safe_atou64(value, &k)) < 0)
2135 log_debug("Failed to parse main-exec-status-exit-monotonic value %s", value);
2137 s->main_exec_status.exit_timestamp.monotonic = (usec_t) k;
2139 log_debug("Unknown serialization key '%s'", key);
2144 static UnitActiveState service_active_state(Unit *u) {
2147 return state_translation_table[SERVICE(u)->state];
2150 static const char *service_sub_state_to_string(Unit *u) {
2153 return service_state_to_string(SERVICE(u)->state);
2156 static bool service_check_gc(Unit *u) {
2157 Service *s = SERVICE(u);
2161 return !!s->sysv_path;
2164 static bool service_check_snapshot(Unit *u) {
2165 Service *s = SERVICE(u);
2169 return !s->got_socket_fd;
2172 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2173 Service *s = SERVICE(u);
2179 success = is_clean_exit(code, status);
2181 if (s->main_pid == pid) {
2183 exec_status_exit(&s->main_exec_status, pid, code, status);
2186 if (s->type != SERVICE_FORKING) {
2187 assert(s->exec_command[SERVICE_EXEC_START]);
2188 s->exec_command[SERVICE_EXEC_START]->exec_status = s->main_exec_status;
2190 if (s->exec_command[SERVICE_EXEC_START]->ignore)
2194 log_debug("%s: main process exited, code=%s, status=%i", u->meta.id, sigchld_code_to_string(code), status);
2195 s->failure = s->failure || !success;
2197 /* The service exited, so the service is officially
2202 case SERVICE_START_POST:
2203 case SERVICE_RELOAD:
2205 /* Need to wait until the operation is
2210 if (s->type == SERVICE_FINISH) {
2211 /* This was our main goal, so let's go on */
2213 service_enter_start_post(s);
2215 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2218 assert(s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY);
2223 case SERVICE_RUNNING:
2224 service_enter_running(s, success);
2227 case SERVICE_STOP_SIGTERM:
2228 case SERVICE_STOP_SIGKILL:
2230 if (!control_pid_good(s))
2231 service_enter_stop_post(s, success);
2233 /* If there is still a control process, wait for that first */
2237 assert_not_reached("Uh, main process died at wrong time.");
2240 } else if (s->control_pid == pid) {
2242 if (s->control_command) {
2243 exec_status_exit(&s->control_command->exec_status, pid, code, status);
2245 if (s->control_command->ignore)
2251 log_debug("%s: control process exited, code=%s status=%i", u->meta.id, sigchld_code_to_string(code), status);
2252 s->failure = s->failure || !success;
2254 /* If we are shutting things down anyway we
2255 * don't care about failing commands. */
2257 if (s->control_command && s->control_command->command_next && success) {
2259 /* There is another command to *
2260 * execute, so let's do that. */
2262 log_debug("%s running next command for state %s", u->meta.id, service_state_to_string(s->state));
2263 service_run_next(s, success);
2266 /* No further commands for this step, so let's
2267 * figure out what to do next */
2269 s->control_command = NULL;
2270 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2272 log_debug("%s got final SIGCHLD for state %s", u->meta.id, service_state_to_string(s->state));
2276 case SERVICE_START_PRE:
2278 service_enter_start(s);
2280 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2284 assert(s->type == SERVICE_FORKING);
2286 /* Let's try to load the pid
2287 * file here if we can. We
2288 * ignore the return value,
2289 * since the PID file might
2290 * actually be created by a
2291 * START_POST script */
2295 service_load_pid_file(s);
2297 service_enter_start_post(s);
2299 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2303 case SERVICE_START_POST:
2304 if (success && s->pid_file && !s->main_pid_known) {
2307 /* Hmm, let's see if we can
2308 * load the pid now after the
2309 * start-post scripts got
2312 if ((r = service_load_pid_file(s)) < 0)
2313 log_warning("%s: failed to load PID file %s: %s", s->meta.id, s->pid_file, strerror(-r));
2318 case SERVICE_RELOAD:
2320 service_enter_running(s, true);
2322 service_enter_stop(s, false);
2327 service_enter_signal(s, SERVICE_STOP_SIGTERM, success);
2330 case SERVICE_STOP_SIGTERM:
2331 case SERVICE_STOP_SIGKILL:
2332 if (main_pid_good(s) <= 0)
2333 service_enter_stop_post(s, success);
2335 /* If there is still a service
2336 * process around, wait until
2337 * that one quit, too */
2340 case SERVICE_STOP_POST:
2341 case SERVICE_FINAL_SIGTERM:
2342 case SERVICE_FINAL_SIGKILL:
2343 service_enter_dead(s, success, true);
2347 assert_not_reached("Uh, control process died at wrong time.");
2353 static void service_timer_event(Unit *u, uint64_t elapsed, Watch* w) {
2354 Service *s = SERVICE(u);
2357 assert(elapsed == 1);
2359 assert(w == &s->timer_watch);
2363 case SERVICE_START_PRE:
2365 log_warning("%s operation timed out. Terminating.", u->meta.id);
2366 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2369 case SERVICE_START_POST:
2370 case SERVICE_RELOAD:
2371 log_warning("%s operation timed out. Stopping.", u->meta.id);
2372 service_enter_stop(s, false);
2376 log_warning("%s stopping timed out. Terminating.", u->meta.id);
2377 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
2380 case SERVICE_STOP_SIGTERM:
2381 log_warning("%s stopping timed out. Killing.", u->meta.id);
2382 service_enter_signal(s, SERVICE_STOP_SIGKILL, false);
2385 case SERVICE_STOP_SIGKILL:
2386 /* Uh, wie sent a SIGKILL and it is still not gone?
2387 * Must be something we cannot kill, so let's just be
2388 * weirded out and continue */
2390 log_warning("%s still around after SIGKILL. Ignoring.", u->meta.id);
2391 service_enter_stop_post(s, false);
2394 case SERVICE_STOP_POST:
2395 log_warning("%s stopping timed out (2). Terminating.", u->meta.id);
2396 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2399 case SERVICE_FINAL_SIGTERM:
2400 log_warning("%s stopping timed out (2). Killing.", u->meta.id);
2401 service_enter_signal(s, SERVICE_FINAL_SIGKILL, false);
2404 case SERVICE_FINAL_SIGKILL:
2405 log_warning("%s still around after SIGKILL (2). Entering maintenance mode.", u->meta.id);
2406 service_enter_dead(s, false, true);
2409 case SERVICE_AUTO_RESTART:
2410 log_info("%s holdoff time over, scheduling restart.", u->meta.id);
2411 service_enter_restart(s);
2415 assert_not_reached("Timeout at wrong time.");
2419 static void service_cgroup_notify_event(Unit *u) {
2420 Service *s = SERVICE(u);
2424 log_debug("%s: cgroup is empty", u->meta.id);
2428 /* Waiting for SIGCHLD is usually more interesting,
2429 * because it includes return codes/signals. Which is
2430 * why we ignore the cgroup events for most cases,
2431 * except when we don't know pid which to expect the
2434 case SERVICE_RUNNING:
2435 service_enter_running(s, true);
2443 static void service_notify_message(Unit *u, pid_t pid, char **tags) {
2444 Service *s = SERVICE(u);
2449 if (s->notify_access == NOTIFY_NONE) {
2450 log_warning("%s: Got notification message from PID %lu, but reception is disabled.",
2451 u->meta.id, (unsigned long) pid);
2455 if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
2456 log_warning("%s: Got notification message from PID %lu, but reception only permitted for PID %lu",
2457 u->meta.id, (unsigned long) pid, (unsigned long) s->main_pid);
2461 log_debug("%s: Got message", u->meta.id);
2463 /* Interpret MAINPID= */
2464 if ((e = strv_find_prefix(tags, "MAINPID=")) &&
2465 (s->state == SERVICE_START ||
2466 s->state == SERVICE_START_POST ||
2467 s->state == SERVICE_RUNNING ||
2468 s->state == SERVICE_RELOAD)) {
2470 if (parse_pid(e + 8, &pid) < 0)
2471 log_warning("Failed to parse %s", e);
2473 log_debug("%s: got %s", u->meta.id, e);
2474 service_set_main_pid(s, pid);
2478 /* Interpret READY= */
2479 if (s->type == SERVICE_NOTIFY &&
2480 s->state == SERVICE_START &&
2481 strv_find(tags, "READY=1")) {
2482 log_debug("%s: got READY=1", u->meta.id);
2484 service_enter_start_post(s);
2487 /* Interpret STATUS= */
2488 if ((e = strv_find_prefix(tags, "STATUS="))) {
2491 if (!(t = strdup(e+7))) {
2492 log_error("Failed to allocate string.");
2496 log_debug("%s: got %s", u->meta.id, e);
2498 free(s->status_text);
2503 static int service_enumerate(Manager *m) {
2507 char *path = NULL, *fpath = NULL, *name = NULL;
2512 STRV_FOREACH(p, m->lookup_paths.sysvrcnd_path)
2513 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++) {
2518 if (asprintf(&path, "%s/%s", *p, rcnd_table[i].path) < 0) {
2526 if (!(d = opendir(path))) {
2527 if (errno != ENOENT)
2528 log_warning("opendir() failed on %s: %s", path, strerror(errno));
2533 while ((de = readdir(d))) {
2537 if (ignore_file(de->d_name))
2540 if (de->d_name[0] != 'S' && de->d_name[0] != 'K')
2543 if (strlen(de->d_name) < 4)
2546 a = undecchar(de->d_name[1]);
2547 b = undecchar(de->d_name[2]);
2554 if (asprintf(&fpath, "%s/%s/%s", *p, rcnd_table[i].path, de->d_name) < 0) {
2559 if (access(fpath, X_OK) < 0) {
2561 if (errno != ENOENT)
2562 log_warning("access() failed on %s: %s", fpath, strerror(errno));
2568 if (!(name = sysv_translate_name(de->d_name + 3))) {
2573 if ((r = manager_load_unit_prepare(m, name, NULL, NULL, &service)) < 0) {
2574 log_warning("Failed to prepare unit %s: %s", name, strerror(-r));
2578 if (de->d_name[0] == 'S' &&
2579 (rcnd_table[i].type == RUNLEVEL_UP || rcnd_table[i].type == RUNLEVEL_SYSINIT))
2580 SERVICE(service)->sysv_start_priority =
2581 MAX(a*10 + b, SERVICE(service)->sysv_start_priority);
2583 manager_dispatch_load_queue(m);
2584 service = unit_follow_merge(service);
2586 /* If this is a native service, rely
2587 * on native ways to pull in a
2588 * service, don't pull it in via sysv
2590 if (service->meta.fragment_path)
2593 if (de->d_name[0] == 'S') {
2595 if ((r = unit_add_two_dependencies_by_name_inverse(service, UNIT_AFTER, UNIT_WANTS, rcnd_table[i].target, NULL, true)) < 0)
2598 } else if (de->d_name[0] == 'K' &&
2599 (rcnd_table[i].type == RUNLEVEL_DOWN ||
2600 rcnd_table[i].type == RUNLEVEL_SYSINIT)) {
2602 /* We honour K links only for
2603 * halt/reboot. For the normal
2604 * runlevels we assume the
2606 * implicitly added by the
2607 * core logic. Also, we don't
2608 * really distuingish here
2609 * between the runlevels 0 and
2610 * 6 and just add them to the
2611 * special shutdown target. On
2612 * SUSE the boot.d/ runlevel
2613 * is also used for shutdown,
2614 * so we add links for that
2615 * too to the shutdown
2618 if ((r = unit_add_two_dependencies_by_name_inverse(service, UNIT_AFTER, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true)) < 0)
2637 static void service_bus_name_owner_change(
2640 const char *old_owner,
2641 const char *new_owner) {
2643 Service *s = SERVICE(u);
2648 assert(streq(s->bus_name, name));
2649 assert(old_owner || new_owner);
2651 if (old_owner && new_owner)
2652 log_debug("%s's D-Bus name %s changed owner from %s to %s", u->meta.id, name, old_owner, new_owner);
2654 log_debug("%s's D-Bus name %s no longer registered by %s", u->meta.id, name, old_owner);
2656 log_debug("%s's D-Bus name %s now registered by %s", u->meta.id, name, new_owner);
2658 s->bus_name_good = !!new_owner;
2660 if (s->type == SERVICE_DBUS) {
2662 /* service_enter_running() will figure out what to
2664 if (s->state == SERVICE_RUNNING)
2665 service_enter_running(s, true);
2666 else if (s->state == SERVICE_START && new_owner)
2667 service_enter_start_post(s);
2669 } else if (new_owner &&
2671 (s->state == SERVICE_START ||
2672 s->state == SERVICE_START_POST ||
2673 s->state == SERVICE_RUNNING ||
2674 s->state == SERVICE_RELOAD)) {
2676 /* Try to acquire PID from bus service */
2677 log_debug("Trying to acquire PID from D-Bus name...");
2679 bus_query_pid(u->meta.manager, name);
2683 static void service_bus_query_pid_done(
2688 Service *s = SERVICE(u);
2693 log_debug("%s's D-Bus name %s is now owned by process %u", u->meta.id, name, (unsigned) pid);
2695 if (s->main_pid <= 0 &&
2696 (s->state == SERVICE_START ||
2697 s->state == SERVICE_START_POST ||
2698 s->state == SERVICE_RUNNING ||
2699 s->state == SERVICE_RELOAD))
2700 service_set_main_pid(s, pid);
2703 int service_set_socket_fd(Service *s, int fd, Socket *sock) {
2707 /* This is called by the socket code when instantiating a new
2708 * service for a stream socket and the socket needs to be
2711 if (s->meta.load_state != UNIT_LOADED)
2714 if (s->socket_fd >= 0)
2717 if (s->state != SERVICE_DEAD)
2721 s->got_socket_fd = true;
2727 static const char* const service_state_table[_SERVICE_STATE_MAX] = {
2728 [SERVICE_DEAD] = "dead",
2729 [SERVICE_START_PRE] = "start-pre",
2730 [SERVICE_START] = "start",
2731 [SERVICE_START_POST] = "start-post",
2732 [SERVICE_RUNNING] = "running",
2733 [SERVICE_EXITED] = "exited",
2734 [SERVICE_RELOAD] = "reload",
2735 [SERVICE_STOP] = "stop",
2736 [SERVICE_STOP_SIGTERM] = "stop-sigterm",
2737 [SERVICE_STOP_SIGKILL] = "stop-sigkill",
2738 [SERVICE_STOP_POST] = "stop-post",
2739 [SERVICE_FINAL_SIGTERM] = "final-sigterm",
2740 [SERVICE_FINAL_SIGKILL] = "final-sigkill",
2741 [SERVICE_MAINTENANCE] = "maintenance",
2742 [SERVICE_AUTO_RESTART] = "auto-restart",
2745 DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
2747 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
2748 [SERVICE_ONCE] = "once",
2749 [SERVICE_RESTART_ON_SUCCESS] = "restart-on-success",
2750 [SERVICE_RESTART_ALWAYS] = "restart-always",
2753 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
2755 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
2756 [SERVICE_SIMPLE] = "simple",
2757 [SERVICE_FORKING] = "forking",
2758 [SERVICE_FINISH] = "finish",
2759 [SERVICE_DBUS] = "dbus",
2760 [SERVICE_NOTIFY] = "notify"
2763 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
2765 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
2766 [SERVICE_EXEC_START_PRE] = "ExecStartPre",
2767 [SERVICE_EXEC_START] = "ExecStart",
2768 [SERVICE_EXEC_START_POST] = "ExecStartPost",
2769 [SERVICE_EXEC_RELOAD] = "ExecReload",
2770 [SERVICE_EXEC_STOP] = "ExecStop",
2771 [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
2774 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
2776 static const char* const notify_access_table[_NOTIFY_ACCESS_MAX] = {
2777 [NOTIFY_NONE] = "none",
2778 [NOTIFY_MAIN] = "main",
2779 [NOTIFY_ALL] = "all"
2782 DEFINE_STRING_TABLE_LOOKUP(notify_access, NotifyAccess);
2784 const UnitVTable service_vtable = {
2785 .suffix = ".service",
2786 .show_status = true,
2788 .init = service_init,
2789 .done = service_done,
2790 .load = service_load,
2792 .coldplug = service_coldplug,
2794 .dump = service_dump,
2796 .start = service_start,
2797 .stop = service_stop,
2798 .reload = service_reload,
2800 .can_reload = service_can_reload,
2802 .serialize = service_serialize,
2803 .deserialize_item = service_deserialize_item,
2805 .active_state = service_active_state,
2806 .sub_state_to_string = service_sub_state_to_string,
2808 .check_gc = service_check_gc,
2809 .check_snapshot = service_check_snapshot,
2811 .sigchld_event = service_sigchld_event,
2812 .timer_event = service_timer_event,
2814 .cgroup_notify_empty = service_cgroup_notify_event,
2815 .notify_message = service_notify_message,
2817 .bus_name_owner_change = service_bus_name_owner_change,
2818 .bus_query_pid_done = service_bus_query_pid_done,
2820 .bus_message_handler = bus_service_message_handler,
2822 .enumerate = service_enumerate