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]) {
296 t = (Service*) other;
301 if (t->sysv_start_priority < 0)
304 /* If both units have modern headers we don't care
305 * about the priorities */
306 if ((!s->sysv_path || s->sysv_has_lsb) &&
307 (!t->sysv_path || t->sysv_has_lsb))
310 if (t->sysv_start_priority < s->sysv_start_priority)
312 else if (t->sysv_start_priority > s->sysv_start_priority)
317 /* FIXME: Maybe we should compare the name here lexicographically? */
319 if (!(r = unit_add_dependency(UNIT(s), d, UNIT(t), true)) < 0)
326 static ExecCommand *exec_command_new(const char *path, const char *arg1) {
329 if (!(c = new0(ExecCommand, 1)))
332 if (!(c->path = strdup(path))) {
337 if (!(c->argv = strv_new(path, arg1, NULL))) {
346 static int sysv_exec_commands(Service *s) {
350 assert(s->sysv_path);
352 if (!(c = exec_command_new(s->sysv_path, "start")))
354 exec_command_append_list(s->exec_command+SERVICE_EXEC_START, c);
356 if (!(c = exec_command_new(s->sysv_path, "stop")))
358 exec_command_append_list(s->exec_command+SERVICE_EXEC_STOP, c);
360 if (!(c = exec_command_new(s->sysv_path, "reload")))
362 exec_command_append_list(s->exec_command+SERVICE_EXEC_RELOAD, c);
367 static int service_load_sysv_path(Service *s, const char *path) {
384 if (!(f = fopen(path, "re"))) {
385 r = errno == ENOENT ? 0 : -errno;
390 if (!(s->sysv_path = strdup(path))) {
396 char l[LINE_MAX], *t;
398 if (!fgets(l, sizeof(l), f)) {
403 log_error("Failed to read configuration file '%s': %s", path, strerror(-r));
413 if (state == NORMAL && streq(t, "### BEGIN INIT INFO")) {
415 s->sysv_has_lsb = true;
419 if ((state == LSB_DESCRIPTION || state == LSB) && streq(t, "### END INIT INFO")) {
425 t += strspn(t, WHITESPACE);
427 if (state == NORMAL) {
429 /* Try to parse Red Hat style chkconfig headers */
431 if (startswith_no_case(t, "chkconfig:")) {
433 char runlevels[16], *k;
437 if (sscanf(t+10, "%15s %i %*i",
439 &start_priority) != 2) {
441 log_warning("[%s:%u] Failed to parse chkconfig line. Ignoring.", path, line);
445 /* A start priority gathered from the
446 * symlink farms is preferred over the
447 * data from the LSB header. */
448 if (start_priority < 0 || start_priority > 99)
449 log_warning("[%s:%u] Start priority out of range. Ignoring.", path, line);
450 else if (s->sysv_start_priority < 0)
451 s->sysv_start_priority = start_priority;
453 char_array_0(runlevels);
454 k = delete_chars(runlevels, WHITESPACE "-");
459 if (!(d = strdup(k))) {
464 free(s->sysv_runlevels);
465 s->sysv_runlevels = d;
468 } else if (startswith_no_case(t, "description:") &&
469 !u->meta.description) {
471 size_t k = strlen(t);
474 if (t[k-1] == '\\') {
479 if (!(d = strdup(strstrip(t+12)))) {
484 free(u->meta.description);
485 u->meta.description = d;
487 } else if (startswith_no_case(t, "pidfile:")) {
494 if (!path_is_absolute(fn)) {
495 log_warning("[%s:%u] PID file not absolute. Ignoring.", path, line);
499 if (!(fn = strdup(fn))) {
508 } else if (state == DESCRIPTION) {
510 /* Try to parse Red Hat style description
513 size_t k = strlen(t);
521 assert(u->meta.description);
522 if (asprintf(&d, "%s %s", u->meta.description, strstrip(t)) < 0) {
527 free(u->meta.description);
528 u->meta.description = d;
530 } else if (state == LSB || state == LSB_DESCRIPTION) {
532 if (startswith_no_case(t, "Provides:")) {
538 FOREACH_WORD_QUOTED(w, z, t+9, i) {
541 if (!(n = strndup(w, z))) {
546 r = sysv_translate_facility(n, &m);
555 if (unit_name_to_type(m) == UNIT_SERVICE)
556 r = unit_add_name(u, m);
557 else if (s->sysv_start_priority >= 0)
558 r = unit_add_two_dependencies_by_name_inverse(u, UNIT_AFTER, UNIT_WANTS, m, NULL, true);
560 r = unit_add_dependency_by_name_inverse(u, UNIT_AFTER, m, NULL, true);
568 } else if (startswith_no_case(t, "Required-Start:") ||
569 startswith_no_case(t, "Should-Start:") ||
570 startswith_no_case(t, "X-Start-Before:") ||
571 startswith_no_case(t, "X-Start-After:")) {
577 FOREACH_WORD_QUOTED(w, z, strchr(t, ':')+1, i) {
580 if (!(n = strndup(w, z))) {
585 r = sysv_translate_facility(n, &m);
594 r = unit_add_dependency_by_name(u, startswith_no_case(t, "X-Start-Before:") ? UNIT_BEFORE : UNIT_AFTER, m, NULL, true);
600 } else if (startswith_no_case(t, "Default-Start:")) {
605 k = delete_chars(t+14, WHITESPACE "-");
608 if (!(d = strdup(k))) {
613 free(s->sysv_runlevels);
614 s->sysv_runlevels = d;
617 } else if (startswith_no_case(t, "Description:") &&
618 !u->meta.description) {
621 /* We use the long description only if
622 * no short description is set. */
624 state = LSB_DESCRIPTION;
626 if (!(d = strdup(strstrip(t+12)))) {
631 free(u->meta.description);
632 u->meta.description = d;
634 } else if (startswith_no_case(t, "Short-Description:")) {
639 if (!(d = strdup(strstrip(t+18)))) {
644 free(u->meta.description);
645 u->meta.description = d;
647 } else if (startswith_no_case(t, "X-Interactive:")) {
650 if ((b = parse_boolean(strstrip(t+14))) < 0) {
651 log_warning("[%s:%u] Couldn't parse interactive flag. Ignoring.", path, line);
656 s->exec_context.std_input = EXEC_INPUT_TTY;
658 s->exec_context.std_input = EXEC_INPUT_NULL;
660 } else if (state == LSB_DESCRIPTION) {
662 if (startswith(l, "#\t") || startswith(l, "# ")) {
665 assert(u->meta.description);
666 if (asprintf(&d, "%s %s", u->meta.description, t) < 0) {
671 free(u->meta.description);
672 u->meta.description = d;
679 if ((r = sysv_exec_commands(s)) < 0)
682 if (s->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, s->sysv_runlevels)) {
683 /* If there a runlevels configured for this service
684 * but none of the standard ones, then we assume this
685 * is some special kind of service (which might be
686 * needed for early boot) and don't create any links
689 s->meta.default_dependencies = false;
691 /* Don't timeout special services during boot (like fsck) */
695 /* Special setting for all SysV services */
696 s->type = SERVICE_FORKING;
697 s->valid_no_process = true;
698 s->restart = SERVICE_ONCE;
699 s->exec_context.std_output = EXEC_OUTPUT_TTY;
700 s->exec_context.kill_mode = KILL_PROCESS_GROUP;
702 u->meta.load_state = UNIT_LOADED;
713 static int service_load_sysv_name(Service *s, const char *name) {
719 /* For SysV services we strip the boot. or .sh
720 * prefixes/suffixes. */
721 if (startswith(name, "boot.") ||
722 endswith(name, ".sh.service"))
725 STRV_FOREACH(p, s->meta.manager->lookup_paths.sysvinit_path) {
729 if (asprintf(&path, "%s/%s", *p, name) < 0)
732 assert(endswith(path, ".service"));
733 path[strlen(path)-8] = 0;
735 r = service_load_sysv_path(s, path);
737 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
738 /* Try Debian style xxx.sh source'able init scripts */
740 r = service_load_sysv_path(s, path);
745 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
746 /* Try SUSE style boot.xxx init scripts */
748 if (asprintf(&path, "%s/boot.%s", *p, name) < 0)
751 path[strlen(path)-8] = 0;
752 r = service_load_sysv_path(s, path);
759 if ((s->meta.load_state != UNIT_STUB))
766 static int service_load_sysv(Service *s) {
773 /* Load service data from SysV init scripts, preferably with
776 if (strv_isempty(s->meta.manager->lookup_paths.sysvinit_path))
779 if ((t = s->meta.id))
780 if ((r = service_load_sysv_name(s, t)) < 0)
783 if (s->meta.load_state == UNIT_STUB)
784 SET_FOREACH(t, s->meta.names, i) {
788 if ((r == service_load_sysv_name(s, t)) < 0)
791 if (s->meta.load_state != UNIT_STUB)
798 static int service_add_bus_name(Service *s) {
805 if (asprintf(&n, "dbus-%s.service", s->bus_name) < 0)
808 r = unit_merge_by_name(UNIT(s), n);
814 static int service_verify(Service *s) {
817 if (s->meta.load_state != UNIT_LOADED)
820 if (!s->exec_command[SERVICE_EXEC_START]) {
821 log_error("%s lacks ExecStart setting. Refusing.", s->meta.id);
825 if (s->exec_command[SERVICE_EXEC_START]->command_next) {
826 log_error("%s has more than one ExecStart setting. Refusing.", s->meta.id);
830 if (s->type == SERVICE_DBUS && !s->bus_name) {
831 log_error("%s is of type D-Bus but no D-Bus service name has been specified. Refusing.", s->meta.id);
835 if (s->exec_context.pam_name && s->exec_context.kill_mode != KILL_CONTROL_GROUP) {
836 log_error("%s has PAM enabled. Kill mode must be set to 'control-group'. Refusing.", s->meta.id);
843 static int service_add_default_dependencies(Service *s) {
848 /* Add a number of automatic dependencies useful for the
849 * majority of services. */
851 /* First, pull in base system */
852 if (s->meta.manager->running_as == MANAGER_SYSTEM) {
854 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_BASIC_TARGET, NULL, true)) < 0)
857 } else if (s->meta.manager->running_as == MANAGER_SESSION) {
859 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SOCKETS_TARGET, NULL, true)) < 0)
863 /* Second, activate normal shutdown */
864 return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true);
867 static int service_load(Unit *u) {
869 Service *s = SERVICE(u);
873 /* Load a .service file */
874 if ((r = unit_load_fragment(u)) < 0)
877 /* Load a classic init script as a fallback, if we couldn't find anything */
878 if (u->meta.load_state == UNIT_STUB)
879 if ((r = service_load_sysv(s)) < 0)
882 /* Still nothing found? Then let's give up */
883 if (u->meta.load_state == UNIT_STUB)
886 /* We were able to load something, then let's add in the
887 * dropin directories. */
888 if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
891 /* This is a new unit? Then let's add in some extras */
892 if (u->meta.load_state == UNIT_LOADED) {
893 if ((r = unit_add_exec_dependencies(u, &s->exec_context)) < 0)
896 if ((r = unit_add_default_cgroup(u)) < 0)
899 if ((r = sysv_fix_order(s)) < 0)
903 if ((r = service_add_bus_name(s)) < 0)
906 if ((r = unit_watch_bus_name(u, s->bus_name)) < 0)
910 if (s->type == SERVICE_NOTIFY && s->notify_access == NOTIFY_NONE)
911 s->notify_access = NOTIFY_MAIN;
913 if (s->type == SERVICE_DBUS || s->bus_name)
914 if ((r = unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_REQUIRES, SPECIAL_DBUS_TARGET, NULL, true)) < 0)
917 if (s->meta.default_dependencies)
918 if ((r = service_add_default_dependencies(s)) < 0)
922 return service_verify(s);
925 static void service_dump(Unit *u, FILE *f, const char *prefix) {
927 ServiceExecCommand c;
928 Service *s = SERVICE(u);
934 p2 = strappend(prefix, "\t");
935 prefix2 = p2 ? p2 : prefix;
938 "%sService State: %s\n"
939 "%sPermissionsStartOnly: %s\n"
940 "%sRootDirectoryStartOnly: %s\n"
941 "%sValidNoProcess: %s\n"
943 "%sNotifyAccess: %s\n",
944 prefix, service_state_to_string(s->state),
945 prefix, yes_no(s->permissions_start_only),
946 prefix, yes_no(s->root_directory_start_only),
947 prefix, yes_no(s->valid_no_process),
948 prefix, service_type_to_string(s->type),
949 prefix, notify_access_to_string(s->notify_access));
951 if (s->control_pid > 0)
953 "%sControl PID: %lu\n",
954 prefix, (unsigned long) s->control_pid);
959 prefix, (unsigned long) s->main_pid);
964 prefix, s->pid_file);
969 "%sBus Name Good: %s\n",
971 prefix, yes_no(s->bus_name_good));
973 exec_context_dump(&s->exec_context, f, prefix);
975 for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
977 if (!s->exec_command[c])
980 fprintf(f, "%s-> %s:\n",
981 prefix, service_exec_command_to_string(c));
983 exec_command_dump_list(s->exec_command[c], f, prefix2);
988 "%sSysV Init Script Path: %s\n"
989 "%sSysV Init Script has LSB Header: %s\n",
990 prefix, s->sysv_path,
991 prefix, yes_no(s->sysv_has_lsb));
993 if (s->sysv_start_priority >= 0)
995 "%sSysVStartPriority: %i\n",
996 prefix, s->sysv_start_priority);
998 if (s->sysv_runlevels)
999 fprintf(f, "%sSysVRunLevels: %s\n",
1000 prefix, s->sysv_runlevels);
1003 fprintf(f, "%sStatus Text: %s\n",
1004 prefix, s->status_text);
1009 static int service_load_pid_file(Service *s) {
1016 if (s->main_pid_known)
1019 assert(s->main_pid <= 0);
1024 if ((r = read_one_line_file(s->pid_file, &k)) < 0)
1027 r = parse_pid(k, &pid);
1033 if (kill(pid, 0) < 0 && errno != EPERM) {
1034 log_warning("PID %lu read from file %s does not exist. Your service or init script might be broken.",
1035 (unsigned long) pid, s->pid_file);
1039 if ((r = service_set_main_pid(s, pid)) < 0)
1042 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1043 /* FIXME: we need to do something here */
1049 static int service_get_sockets(Service *s, Set **_set) {
1058 if (s->socket_fd >= 0)
1061 /* Collects all Socket objects that belong to this
1062 * service. Note that a service might have multiple sockets
1063 * via multiple names. */
1065 if (!(set = set_new(NULL, NULL)))
1068 SET_FOREACH(t, s->meta.names, i) {
1072 /* Look for all socket objects that go by any of our
1073 * units and collect their fds */
1075 if (!(k = unit_name_change_suffix(t, ".socket"))) {
1080 p = manager_get_unit(s->meta.manager, k);
1086 if ((r = set_put(set, p)) < 0)
1098 static int service_notify_sockets_dead(Service *s) {
1106 if (s->socket_fd >= 0)
1109 /* Notifies all our sockets when we die */
1110 if ((r = service_get_sockets(s, &set)) < 0)
1113 SET_FOREACH(sock, set, i)
1114 socket_notify_service_dead(sock);
1121 static void service_set_state(Service *s, ServiceState state) {
1122 ServiceState old_state;
1125 old_state = s->state;
1128 if (state != SERVICE_START_PRE &&
1129 state != SERVICE_START &&
1130 state != SERVICE_START_POST &&
1131 state != SERVICE_RELOAD &&
1132 state != SERVICE_STOP &&
1133 state != SERVICE_STOP_SIGTERM &&
1134 state != SERVICE_STOP_SIGKILL &&
1135 state != SERVICE_STOP_POST &&
1136 state != SERVICE_FINAL_SIGTERM &&
1137 state != SERVICE_FINAL_SIGKILL &&
1138 state != SERVICE_AUTO_RESTART)
1139 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1141 if (state != SERVICE_START &&
1142 state != SERVICE_START_POST &&
1143 state != SERVICE_RUNNING &&
1144 state != SERVICE_RELOAD &&
1145 state != SERVICE_STOP &&
1146 state != SERVICE_STOP_SIGTERM &&
1147 state != SERVICE_STOP_SIGKILL)
1148 service_unwatch_main_pid(s);
1150 if (state != SERVICE_START_PRE &&
1151 state != SERVICE_START &&
1152 state != SERVICE_START_POST &&
1153 state != SERVICE_RELOAD &&
1154 state != SERVICE_STOP &&
1155 state != SERVICE_STOP_SIGTERM &&
1156 state != SERVICE_STOP_SIGKILL &&
1157 state != SERVICE_STOP_POST &&
1158 state != SERVICE_FINAL_SIGTERM &&
1159 state != SERVICE_FINAL_SIGKILL) {
1160 service_unwatch_control_pid(s);
1161 s->control_command = NULL;
1162 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1165 if (state == SERVICE_DEAD ||
1166 state == SERVICE_STOP ||
1167 state == SERVICE_STOP_SIGTERM ||
1168 state == SERVICE_STOP_SIGKILL ||
1169 state == SERVICE_STOP_POST ||
1170 state == SERVICE_FINAL_SIGTERM ||
1171 state == SERVICE_FINAL_SIGKILL ||
1172 state == SERVICE_MAINTENANCE ||
1173 state == SERVICE_AUTO_RESTART)
1174 service_notify_sockets_dead(s);
1176 if (state != SERVICE_START_PRE &&
1177 state != SERVICE_START &&
1178 state != SERVICE_START_POST &&
1179 state != SERVICE_RUNNING &&
1180 state != SERVICE_RELOAD &&
1181 state != SERVICE_STOP &&
1182 state != SERVICE_STOP_SIGTERM &&
1183 state != SERVICE_STOP_SIGKILL &&
1184 state != SERVICE_STOP_POST &&
1185 state != SERVICE_FINAL_SIGTERM &&
1186 state != SERVICE_FINAL_SIGKILL &&
1187 !(state == SERVICE_DEAD && s->meta.job)) {
1188 service_close_socket_fd(s);
1189 service_connection_unref(s);
1192 /* For the inactive states unit_notify() will trim the cgroup,
1193 * but for exit we have to do that ourselves... */
1194 if (state == SERVICE_EXITED)
1195 cgroup_bonding_trim_list(s->meta.cgroup_bondings, true);
1197 if (old_state != state)
1198 log_debug("%s changed %s -> %s", s->meta.id, service_state_to_string(old_state), service_state_to_string(state));
1200 unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state]);
1203 static int service_coldplug(Unit *u) {
1204 Service *s = SERVICE(u);
1208 assert(s->state == SERVICE_DEAD);
1210 if (s->deserialized_state != s->state) {
1212 if (s->deserialized_state == SERVICE_START_PRE ||
1213 s->deserialized_state == SERVICE_START ||
1214 s->deserialized_state == SERVICE_START_POST ||
1215 s->deserialized_state == SERVICE_RELOAD ||
1216 s->deserialized_state == SERVICE_STOP ||
1217 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1218 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1219 s->deserialized_state == SERVICE_STOP_POST ||
1220 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1221 s->deserialized_state == SERVICE_FINAL_SIGKILL ||
1222 s->deserialized_state == SERVICE_AUTO_RESTART) {
1224 if (s->deserialized_state == SERVICE_AUTO_RESTART || s->timeout_usec > 0) {
1227 k = s->deserialized_state == SERVICE_AUTO_RESTART ? s->restart_usec : s->timeout_usec;
1229 if ((r = unit_watch_timer(UNIT(s), k, &s->timer_watch)) < 0)
1234 if ((s->deserialized_state == SERVICE_START &&
1235 (s->type == SERVICE_FORKING ||
1236 s->type == SERVICE_DBUS ||
1237 s->type == SERVICE_FINISH ||
1238 s->type == SERVICE_NOTIFY)) ||
1239 s->deserialized_state == SERVICE_START_POST ||
1240 s->deserialized_state == SERVICE_RUNNING ||
1241 s->deserialized_state == SERVICE_RELOAD ||
1242 s->deserialized_state == SERVICE_STOP ||
1243 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1244 s->deserialized_state == SERVICE_STOP_SIGKILL)
1245 if (s->main_pid > 0)
1246 if ((r = unit_watch_pid(UNIT(s), s->main_pid)) < 0)
1249 if (s->deserialized_state == SERVICE_START_PRE ||
1250 s->deserialized_state == SERVICE_START ||
1251 s->deserialized_state == SERVICE_START_POST ||
1252 s->deserialized_state == SERVICE_RELOAD ||
1253 s->deserialized_state == SERVICE_STOP ||
1254 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1255 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1256 s->deserialized_state == SERVICE_STOP_POST ||
1257 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1258 s->deserialized_state == SERVICE_FINAL_SIGKILL)
1259 if (s->control_pid > 0)
1260 if ((r = unit_watch_pid(UNIT(s), s->control_pid)) < 0)
1263 service_set_state(s, s->deserialized_state);
1269 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
1273 unsigned rn_fds = 0;
1281 if (s->socket_fd >= 0)
1284 if ((r = service_get_sockets(s, &set)) < 0)
1287 SET_FOREACH(sock, set, i) {
1291 if ((r = socket_collect_fds(sock, &cfds, &cn_fds)) < 0)
1303 if (!(t = new(int, rn_fds+cn_fds))) {
1309 memcpy(t, rfds, rn_fds);
1310 memcpy(t+rn_fds, cfds, cn_fds);
1315 rn_fds = rn_fds+cn_fds;
1333 static int service_spawn(
1338 bool apply_permissions,
1340 bool apply_tty_stdin,
1341 bool set_notify_socket,
1346 int *fds = NULL, *fdsbuf = NULL;
1347 unsigned n_fds = 0, n_env = 0;
1348 char **argv = NULL, **final_env = NULL, **our_env = NULL;
1355 s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1356 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1357 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
1359 if (s->socket_fd >= 0) {
1360 fds = &s->socket_fd;
1363 if ((r = service_collect_fds(s, &fdsbuf, &n_fds)) < 0)
1370 if (timeout && s->timeout_usec) {
1371 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1374 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1376 if (!(argv = unit_full_printf_strv(UNIT(s), c->argv))) {
1381 if (!(our_env = new0(char*, 3))) {
1386 if (set_notify_socket)
1387 if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=@%s", s->meta.manager->notify_socket) < 0) {
1392 if (s->main_pid > 0)
1393 if (asprintf(our_env + n_env++, "MAINPID=%lu", (unsigned long) s->main_pid) < 0) {
1398 if (!(final_env = strv_env_merge(2,
1399 s->meta.manager->environment,
1414 s->meta.manager->confirm_spawn,
1415 s->meta.cgroup_bondings,
1422 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1423 /* FIXME: we need to do something here */
1429 strv_free(final_env);
1439 strv_free(final_env);
1442 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1447 static int main_pid_good(Service *s) {
1450 /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1453 /* If we know the pid file, then lets just check if it is
1455 if (s->main_pid_known)
1456 return s->main_pid > 0;
1458 /* We don't know the pid */
1462 static int control_pid_good(Service *s) {
1465 return s->control_pid > 0;
1468 static int cgroup_good(Service *s) {
1473 if ((r = cgroup_bonding_is_empty_list(s->meta.cgroup_bondings)) < 0)
1479 static void service_enter_dead(Service *s, bool success, bool allow_restart) {
1486 if (allow_restart &&
1488 (s->restart == SERVICE_RESTART_ALWAYS ||
1489 (s->restart == SERVICE_RESTART_ON_SUCCESS && !s->failure))) {
1491 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
1494 service_set_state(s, SERVICE_AUTO_RESTART);
1496 service_set_state(s, s->failure ? SERVICE_MAINTENANCE : SERVICE_DEAD);
1501 log_warning("%s failed to run install restart timer: %s", s->meta.id, strerror(-r));
1502 service_enter_dead(s, false, false);
1505 static void service_enter_signal(Service *s, ServiceState state, bool success);
1507 static void service_enter_stop_post(Service *s, bool success) {
1514 service_unwatch_control_pid(s);
1516 s->control_command_id = SERVICE_EXEC_STOP_POST;
1517 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST])) {
1518 if ((r = service_spawn(s,
1522 !s->permissions_start_only,
1523 !s->root_directory_start_only,
1526 &s->control_pid)) < 0)
1530 service_set_state(s, SERVICE_STOP_POST);
1532 service_enter_signal(s, SERVICE_FINAL_SIGTERM, true);
1537 log_warning("%s failed to run 'stop-post' task: %s", s->meta.id, strerror(-r));
1538 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1541 static void service_enter_signal(Service *s, ServiceState state, bool success) {
1550 if (s->exec_context.kill_mode != KILL_NONE) {
1551 int sig = (state == SERVICE_STOP_SIGTERM || state == SERVICE_FINAL_SIGTERM) ? s->exec_context.kill_signal : SIGKILL;
1553 if (s->exec_context.kill_mode == KILL_CONTROL_GROUP) {
1555 if ((r = cgroup_bonding_kill_list(s->meta.cgroup_bondings, sig)) < 0) {
1556 if (r != -EAGAIN && r != -ESRCH)
1565 if (s->main_pid > 0) {
1566 if (kill(s->exec_context.kill_mode == KILL_PROCESS ? s->main_pid : -s->main_pid, sig) < 0 && errno != ESRCH)
1572 if (s->control_pid > 0) {
1573 if (kill(s->exec_context.kill_mode == KILL_PROCESS ? s->control_pid : -s->control_pid, sig) < 0 && errno != ESRCH)
1584 if (sent && (s->main_pid > 0 || s->control_pid > 0)) {
1585 if (s->timeout_usec > 0)
1586 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1589 service_set_state(s, state);
1590 } else if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1591 service_enter_stop_post(s, true);
1593 service_enter_dead(s, true, true);
1598 log_warning("%s failed to kill processes: %s", s->meta.id, strerror(-r));
1600 if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1601 service_enter_stop_post(s, false);
1603 service_enter_dead(s, false, true);
1606 static void service_enter_stop(Service *s, bool success) {
1614 service_unwatch_control_pid(s);
1616 s->control_command_id = SERVICE_EXEC_STOP;
1617 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP])) {
1618 if ((r = service_spawn(s,
1622 !s->permissions_start_only,
1623 !s->root_directory_start_only,
1626 &s->control_pid)) < 0)
1629 service_set_state(s, SERVICE_STOP);
1631 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
1636 log_warning("%s failed to run 'stop' task: %s", s->meta.id, strerror(-r));
1637 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1640 static void service_enter_running(Service *s, bool success) {
1641 int main_pid_ok, cgroup_ok;
1647 main_pid_ok = main_pid_good(s);
1648 cgroup_ok = cgroup_good(s);
1650 if ((main_pid_ok > 0 || (main_pid_ok < 0 && cgroup_ok != 0)) &&
1651 (s->bus_name_good || s->type != SERVICE_DBUS))
1652 service_set_state(s, SERVICE_RUNNING);
1653 else if (s->valid_no_process)
1654 service_set_state(s, SERVICE_EXITED);
1656 service_enter_stop(s, true);
1659 static void service_enter_start_post(Service *s) {
1663 service_unwatch_control_pid(s);
1665 s->control_command_id = SERVICE_EXEC_START_POST;
1666 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_POST])) {
1667 if ((r = service_spawn(s,
1671 !s->permissions_start_only,
1672 !s->root_directory_start_only,
1675 &s->control_pid)) < 0)
1678 service_set_state(s, SERVICE_START_POST);
1680 service_enter_running(s, true);
1685 log_warning("%s failed to run 'start-post' task: %s", s->meta.id, strerror(-r));
1686 service_enter_stop(s, false);
1689 static void service_enter_start(Service *s) {
1695 assert(s->exec_command[SERVICE_EXEC_START]);
1696 assert(!s->exec_command[SERVICE_EXEC_START]->command_next);
1698 if (s->type == SERVICE_FORKING)
1699 service_unwatch_control_pid(s);
1701 service_unwatch_main_pid(s);
1703 if ((r = service_spawn(s,
1704 s->exec_command[SERVICE_EXEC_START],
1705 s->type == SERVICE_FORKING || s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY,
1710 s->notify_access != NOTIFY_NONE,
1714 if (s->type == SERVICE_SIMPLE) {
1715 /* For simple services we immediately start
1716 * the START_POST binaries. */
1718 service_set_main_pid(s, pid);
1719 service_enter_start_post(s);
1721 } else if (s->type == SERVICE_FORKING) {
1723 /* For forking services we wait until the start
1724 * process exited. */
1726 s->control_command_id = SERVICE_EXEC_START;
1727 s->control_command = s->exec_command[SERVICE_EXEC_START];
1729 s->control_pid = pid;
1730 service_set_state(s, SERVICE_START);
1732 } else if (s->type == SERVICE_FINISH ||
1733 s->type == SERVICE_DBUS ||
1734 s->type == SERVICE_NOTIFY) {
1736 /* For finishing services we wait until the start
1737 * process exited, too, but it is our main process. */
1739 /* For D-Bus services we know the main pid right away,
1740 * but wait for the bus name to appear on the
1741 * bus. Notify services are similar. */
1743 service_set_main_pid(s, pid);
1744 service_set_state(s, SERVICE_START);
1746 assert_not_reached("Unknown service type");
1751 log_warning("%s failed to run 'start' task: %s", s->meta.id, strerror(-r));
1752 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1755 static void service_enter_start_pre(Service *s) {
1760 service_unwatch_control_pid(s);
1762 s->control_command_id = SERVICE_EXEC_START_PRE;
1763 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_PRE])) {
1764 if ((r = service_spawn(s,
1768 !s->permissions_start_only,
1769 !s->root_directory_start_only,
1772 &s->control_pid)) < 0)
1775 service_set_state(s, SERVICE_START_PRE);
1777 service_enter_start(s);
1782 log_warning("%s failed to run 'start-pre' task: %s", s->meta.id, strerror(-r));
1783 service_enter_dead(s, false, true);
1786 static void service_enter_restart(Service *s) {
1791 dbus_error_init(&error);
1793 service_enter_dead(s, true, false);
1795 if ((r = manager_add_job(s->meta.manager, JOB_START, UNIT(s), JOB_FAIL, false, NULL, NULL)) < 0)
1798 log_debug("%s scheduled restart job.", s->meta.id);
1802 log_warning("%s failed to schedule restart job: %s", s->meta.id, bus_error(&error, -r));
1803 service_enter_dead(s, false, false);
1805 dbus_error_free(&error);
1808 static void service_enter_reload(Service *s) {
1813 service_unwatch_control_pid(s);
1815 s->control_command_id = SERVICE_EXEC_RELOAD;
1816 if ((s->control_command = s->exec_command[SERVICE_EXEC_RELOAD])) {
1817 if ((r = service_spawn(s,
1821 !s->permissions_start_only,
1822 !s->root_directory_start_only,
1825 &s->control_pid)) < 0)
1828 service_set_state(s, SERVICE_RELOAD);
1830 service_enter_running(s, true);
1835 log_warning("%s failed to run 'reload' task: %s", s->meta.id, strerror(-r));
1836 service_enter_stop(s, false);
1839 static void service_run_next(Service *s, bool success) {
1843 assert(s->control_command);
1844 assert(s->control_command->command_next);
1849 s->control_command = s->control_command->command_next;
1851 service_unwatch_control_pid(s);
1853 if ((r = service_spawn(s,
1857 !s->permissions_start_only,
1858 !s->root_directory_start_only,
1859 s->control_command_id == SERVICE_EXEC_START_PRE ||
1860 s->control_command_id == SERVICE_EXEC_STOP_POST,
1862 &s->control_pid)) < 0)
1868 log_warning("%s failed to run next task: %s", s->meta.id, strerror(-r));
1870 if (s->state == SERVICE_START_PRE)
1871 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1872 else if (s->state == SERVICE_STOP)
1873 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1874 else if (s->state == SERVICE_STOP_POST)
1875 service_enter_dead(s, false, true);
1877 service_enter_stop(s, false);
1880 static int service_start(Unit *u) {
1881 Service *s = SERVICE(u);
1885 /* We cannot fulfill this request right now, try again later
1887 if (s->state == SERVICE_STOP ||
1888 s->state == SERVICE_STOP_SIGTERM ||
1889 s->state == SERVICE_STOP_SIGKILL ||
1890 s->state == SERVICE_STOP_POST ||
1891 s->state == SERVICE_FINAL_SIGTERM ||
1892 s->state == SERVICE_FINAL_SIGKILL)
1895 /* Already on it! */
1896 if (s->state == SERVICE_START_PRE ||
1897 s->state == SERVICE_START ||
1898 s->state == SERVICE_START_POST)
1901 assert(s->state == SERVICE_DEAD || s->state == SERVICE_MAINTENANCE || s->state == SERVICE_AUTO_RESTART);
1903 /* Make sure we don't enter a busy loop of some kind. */
1904 if (!ratelimit_test(&s->ratelimit)) {
1905 log_warning("%s start request repeated too quickly, refusing to start.", u->meta.id);
1909 if ((s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1910 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1911 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) &&
1913 log_warning("%s can only be started with a per-connection socket.", u->meta.id);
1918 s->main_pid_known = false;
1919 s->allow_restart = true;
1921 service_enter_start_pre(s);
1925 static int service_stop(Unit *u) {
1926 Service *s = SERVICE(u);
1930 /* This is a user request, so don't do restarts on this
1932 s->allow_restart = false;
1935 if (s->state == SERVICE_STOP ||
1936 s->state == SERVICE_STOP_SIGTERM ||
1937 s->state == SERVICE_STOP_SIGKILL ||
1938 s->state == SERVICE_STOP_POST ||
1939 s->state == SERVICE_FINAL_SIGTERM ||
1940 s->state == SERVICE_FINAL_SIGKILL)
1943 /* Don't allow a restart */
1944 if (s->state == SERVICE_AUTO_RESTART) {
1945 service_set_state(s, SERVICE_DEAD);
1949 /* If there's already something running we go directly into
1951 if (s->state == SERVICE_START_PRE ||
1952 s->state == SERVICE_START ||
1953 s->state == SERVICE_START_POST ||
1954 s->state == SERVICE_RELOAD) {
1955 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
1959 assert(s->state == SERVICE_RUNNING ||
1960 s->state == SERVICE_EXITED);
1962 service_enter_stop(s, true);
1966 static int service_reload(Unit *u) {
1967 Service *s = SERVICE(u);
1971 assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
1973 service_enter_reload(s);
1977 static bool service_can_reload(Unit *u) {
1978 Service *s = SERVICE(u);
1982 return !!s->exec_command[SERVICE_EXEC_RELOAD];
1985 static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
1986 Service *s = SERVICE(u);
1992 unit_serialize_item(u, f, "state", service_state_to_string(s->state));
1993 unit_serialize_item(u, f, "failure", yes_no(s->failure));
1995 if (s->control_pid > 0)
1996 unit_serialize_item_format(u, f, "control-pid", "%lu", (unsigned long) s->control_pid);
1998 if (s->main_pid_known && s->main_pid > 0)
1999 unit_serialize_item_format(u, f, "main-pid", "%lu", (unsigned long) s->main_pid);
2001 unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
2003 /* There's a minor uncleanliness here: if there are multiple
2004 * commands attached here, we will start from the first one
2006 if (s->control_command_id >= 0)
2007 unit_serialize_item(u, f, "control-command", service_exec_command_to_string(s->control_command_id));
2009 if (s->socket_fd >= 0) {
2012 if ((copy = fdset_put_dup(fds, s->socket_fd)) < 0)
2015 unit_serialize_item_format(u, f, "socket-fd", "%i", copy);
2018 if (s->main_exec_status.pid > 0) {
2019 unit_serialize_item_format(u, f, "main-exec-status-pid", "%lu", (unsigned long) s->main_exec_status.pid);
2021 if (s->main_exec_status.start_timestamp.realtime > 0) {
2022 unit_serialize_item_format(u, f, "main-exec-status-start-realtime",
2023 "%llu", (unsigned long long) s->main_exec_status.start_timestamp.realtime);
2025 unit_serialize_item_format(u, f, "main-exec-status-start-monotonic",
2026 "%llu", (unsigned long long) s->main_exec_status.start_timestamp.monotonic);
2029 if (s->main_exec_status.exit_timestamp.realtime > 0) {
2030 unit_serialize_item_format(u, f, "main-exec-status-exit-realtime",
2031 "%llu", (unsigned long long) s->main_exec_status.exit_timestamp.realtime);
2032 unit_serialize_item_format(u, f, "main-exec-status-exit-monotonic",
2033 "%llu", (unsigned long long) s->main_exec_status.exit_timestamp.monotonic);
2035 unit_serialize_item_format(u, f, "main-exec-status-code", "%i", s->main_exec_status.code);
2036 unit_serialize_item_format(u, f, "main-exec-status-status", "%i", s->main_exec_status.status);
2043 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
2044 Service *s = SERVICE(u);
2052 if (streq(key, "state")) {
2055 if ((state = service_state_from_string(value)) < 0)
2056 log_debug("Failed to parse state value %s", value);
2058 s->deserialized_state = state;
2059 } else if (streq(key, "failure")) {
2062 if ((b = parse_boolean(value)) < 0)
2063 log_debug("Failed to parse failure value %s", value);
2065 s->failure = b || s->failure;
2066 } else if (streq(key, "control-pid")) {
2069 if ((r = parse_pid(value, &pid)) < 0)
2070 log_debug("Failed to parse control-pid value %s", value);
2072 s->control_pid = pid;
2073 } else if (streq(key, "main-pid")) {
2076 if ((r = parse_pid(value, &pid)) < 0)
2077 log_debug("Failed to parse main-pid value %s", value);
2079 service_set_main_pid(s, (pid_t) pid);
2080 } else if (streq(key, "main-pid-known")) {
2083 if ((b = parse_boolean(value)) < 0)
2084 log_debug("Failed to parse main-pid-known value %s", value);
2086 s->main_pid_known = b;
2087 } else if (streq(key, "control-command")) {
2088 ServiceExecCommand id;
2090 if ((id = service_exec_command_from_string(value)) < 0)
2091 log_debug("Failed to parse exec-command value %s", value);
2093 s->control_command_id = id;
2094 s->control_command = s->exec_command[id];
2096 } else if (streq(key, "socket-fd")) {
2099 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2100 log_debug("Failed to parse socket-fd value %s", value);
2103 if (s->socket_fd >= 0)
2104 close_nointr_nofail(s->socket_fd);
2105 s->socket_fd = fdset_remove(fds, fd);
2107 } else if (streq(key, "main-exec-status-pid")) {
2110 if ((r = parse_pid(value, &pid)) < 0)
2111 log_debug("Failed to parse main-exec-status-pid value %s", value);
2113 s->main_exec_status.pid = pid;
2114 } else if (streq(key, "main-exec-status-code")) {
2117 if ((r = safe_atoi(value, &i)) < 0)
2118 log_debug("Failed to parse main-exec-status-code value %s", value);
2120 s->main_exec_status.code = i;
2121 } else if (streq(key, "main-exec-status-status")) {
2124 if ((r = safe_atoi(value, &i)) < 0)
2125 log_debug("Failed to parse main-exec-status-status value %s", value);
2127 s->main_exec_status.status = i;
2128 } else if (streq(key, "main-exec-status-start-realtime")) {
2131 if ((r = safe_atou64(value, &k)) < 0)
2132 log_debug("Failed to parse main-exec-status-start-realtime value %s", value);
2134 s->main_exec_status.start_timestamp.realtime = (usec_t) k;
2135 } else if (streq(key, "main-exec-status-start-monotonic")) {
2138 if ((r = safe_atou64(value, &k)) < 0)
2139 log_debug("Failed to parse main-exec-status-start-monotonic value %s", value);
2141 s->main_exec_status.start_timestamp.monotonic = (usec_t) k;
2142 } else if (streq(key, "main-exec-status-exit-realtime")) {
2145 if ((r = safe_atou64(value, &k)) < 0)
2146 log_debug("Failed to parse main-exec-status-exit-realtime value %s", value);
2148 s->main_exec_status.exit_timestamp.realtime = (usec_t) k;
2149 } else if (streq(key, "main-exec-status-exit-monotonic")) {
2152 if ((r = safe_atou64(value, &k)) < 0)
2153 log_debug("Failed to parse main-exec-status-exit-monotonic value %s", value);
2155 s->main_exec_status.exit_timestamp.monotonic = (usec_t) k;
2157 log_debug("Unknown serialization key '%s'", key);
2162 static UnitActiveState service_active_state(Unit *u) {
2165 return state_translation_table[SERVICE(u)->state];
2168 static const char *service_sub_state_to_string(Unit *u) {
2171 return service_state_to_string(SERVICE(u)->state);
2174 static bool service_check_gc(Unit *u) {
2175 Service *s = SERVICE(u);
2179 return !!s->sysv_path;
2182 static bool service_check_snapshot(Unit *u) {
2183 Service *s = SERVICE(u);
2187 return !s->got_socket_fd;
2190 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2191 Service *s = SERVICE(u);
2197 success = is_clean_exit(code, status);
2199 if (s->main_pid == pid) {
2201 exec_status_exit(&s->main_exec_status, pid, code, status);
2204 if (s->type != SERVICE_FORKING) {
2205 assert(s->exec_command[SERVICE_EXEC_START]);
2206 s->exec_command[SERVICE_EXEC_START]->exec_status = s->main_exec_status;
2208 if (s->exec_command[SERVICE_EXEC_START]->ignore)
2212 log_full(success ? LOG_DEBUG : LOG_NOTICE,
2213 "%s: main process exited, code=%s, status=%i", u->meta.id, sigchld_code_to_string(code), status);
2214 s->failure = s->failure || !success;
2216 /* The service exited, so the service is officially
2221 case SERVICE_START_POST:
2222 case SERVICE_RELOAD:
2224 /* Need to wait until the operation is
2229 if (s->type == SERVICE_FINISH) {
2230 /* This was our main goal, so let's go on */
2232 service_enter_start_post(s);
2234 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2237 assert(s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY);
2242 case SERVICE_RUNNING:
2243 service_enter_running(s, success);
2246 case SERVICE_STOP_SIGTERM:
2247 case SERVICE_STOP_SIGKILL:
2249 if (!control_pid_good(s))
2250 service_enter_stop_post(s, success);
2252 /* If there is still a control process, wait for that first */
2256 assert_not_reached("Uh, main process died at wrong time.");
2259 } else if (s->control_pid == pid) {
2261 if (s->control_command) {
2262 exec_status_exit(&s->control_command->exec_status, pid, code, status);
2264 if (s->control_command->ignore)
2270 log_full(success ? LOG_DEBUG : LOG_NOTICE,
2271 "%s: control process exited, code=%s status=%i", u->meta.id, sigchld_code_to_string(code), status);
2272 s->failure = s->failure || !success;
2274 /* If we are shutting things down anyway we
2275 * don't care about failing commands. */
2277 if (s->control_command && s->control_command->command_next && success) {
2279 /* There is another command to *
2280 * execute, so let's do that. */
2282 log_debug("%s running next command for state %s", u->meta.id, service_state_to_string(s->state));
2283 service_run_next(s, success);
2286 /* No further commands for this step, so let's
2287 * figure out what to do next */
2289 s->control_command = NULL;
2290 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2292 log_debug("%s got final SIGCHLD for state %s", u->meta.id, service_state_to_string(s->state));
2296 case SERVICE_START_PRE:
2298 service_enter_start(s);
2300 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2304 assert(s->type == SERVICE_FORKING);
2306 /* Let's try to load the pid
2307 * file here if we can. We
2308 * ignore the return value,
2309 * since the PID file might
2310 * actually be created by a
2311 * START_POST script */
2315 service_load_pid_file(s);
2317 service_enter_start_post(s);
2319 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2323 case SERVICE_START_POST:
2324 if (success && s->pid_file && !s->main_pid_known) {
2327 /* Hmm, let's see if we can
2328 * load the pid now after the
2329 * start-post scripts got
2332 if ((r = service_load_pid_file(s)) < 0)
2333 log_warning("%s: failed to load PID file %s: %s", s->meta.id, s->pid_file, strerror(-r));
2338 case SERVICE_RELOAD:
2340 service_enter_running(s, true);
2342 service_enter_stop(s, false);
2347 service_enter_signal(s, SERVICE_STOP_SIGTERM, success);
2350 case SERVICE_STOP_SIGTERM:
2351 case SERVICE_STOP_SIGKILL:
2352 if (main_pid_good(s) <= 0)
2353 service_enter_stop_post(s, success);
2355 /* If there is still a service
2356 * process around, wait until
2357 * that one quit, too */
2360 case SERVICE_STOP_POST:
2361 case SERVICE_FINAL_SIGTERM:
2362 case SERVICE_FINAL_SIGKILL:
2363 service_enter_dead(s, success, true);
2367 assert_not_reached("Uh, control process died at wrong time.");
2373 static void service_timer_event(Unit *u, uint64_t elapsed, Watch* w) {
2374 Service *s = SERVICE(u);
2377 assert(elapsed == 1);
2379 assert(w == &s->timer_watch);
2383 case SERVICE_START_PRE:
2385 log_warning("%s operation timed out. Terminating.", u->meta.id);
2386 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2389 case SERVICE_START_POST:
2390 case SERVICE_RELOAD:
2391 log_warning("%s operation timed out. Stopping.", u->meta.id);
2392 service_enter_stop(s, false);
2396 log_warning("%s stopping timed out. Terminating.", u->meta.id);
2397 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
2400 case SERVICE_STOP_SIGTERM:
2401 log_warning("%s stopping timed out. Killing.", u->meta.id);
2402 service_enter_signal(s, SERVICE_STOP_SIGKILL, false);
2405 case SERVICE_STOP_SIGKILL:
2406 /* Uh, wie sent a SIGKILL and it is still not gone?
2407 * Must be something we cannot kill, so let's just be
2408 * weirded out and continue */
2410 log_warning("%s still around after SIGKILL. Ignoring.", u->meta.id);
2411 service_enter_stop_post(s, false);
2414 case SERVICE_STOP_POST:
2415 log_warning("%s stopping timed out (2). Terminating.", u->meta.id);
2416 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2419 case SERVICE_FINAL_SIGTERM:
2420 log_warning("%s stopping timed out (2). Killing.", u->meta.id);
2421 service_enter_signal(s, SERVICE_FINAL_SIGKILL, false);
2424 case SERVICE_FINAL_SIGKILL:
2425 log_warning("%s still around after SIGKILL (2). Entering maintenance mode.", u->meta.id);
2426 service_enter_dead(s, false, true);
2429 case SERVICE_AUTO_RESTART:
2430 log_info("%s holdoff time over, scheduling restart.", u->meta.id);
2431 service_enter_restart(s);
2435 assert_not_reached("Timeout at wrong time.");
2439 static void service_cgroup_notify_event(Unit *u) {
2440 Service *s = SERVICE(u);
2444 log_debug("%s: cgroup is empty", u->meta.id);
2448 /* Waiting for SIGCHLD is usually more interesting,
2449 * because it includes return codes/signals. Which is
2450 * why we ignore the cgroup events for most cases,
2451 * except when we don't know pid which to expect the
2454 case SERVICE_RUNNING:
2455 service_enter_running(s, true);
2463 static void service_notify_message(Unit *u, pid_t pid, char **tags) {
2464 Service *s = SERVICE(u);
2469 if (s->notify_access == NOTIFY_NONE) {
2470 log_warning("%s: Got notification message from PID %lu, but reception is disabled.",
2471 u->meta.id, (unsigned long) pid);
2475 if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
2476 log_warning("%s: Got notification message from PID %lu, but reception only permitted for PID %lu",
2477 u->meta.id, (unsigned long) pid, (unsigned long) s->main_pid);
2481 log_debug("%s: Got message", u->meta.id);
2483 /* Interpret MAINPID= */
2484 if ((e = strv_find_prefix(tags, "MAINPID=")) &&
2485 (s->state == SERVICE_START ||
2486 s->state == SERVICE_START_POST ||
2487 s->state == SERVICE_RUNNING ||
2488 s->state == SERVICE_RELOAD)) {
2490 if (parse_pid(e + 8, &pid) < 0)
2491 log_warning("Failed to parse notification message %s", e);
2493 log_debug("%s: got %s", u->meta.id, e);
2494 service_set_main_pid(s, pid);
2498 /* Interpret READY= */
2499 if (s->type == SERVICE_NOTIFY &&
2500 s->state == SERVICE_START &&
2501 strv_find(tags, "READY=1")) {
2502 log_debug("%s: got READY=1", u->meta.id);
2504 service_enter_start_post(s);
2507 /* Interpret STATUS= */
2508 if ((e = strv_find_prefix(tags, "STATUS="))) {
2511 if (!(t = strdup(e+7))) {
2512 log_error("Failed to allocate string.");
2516 log_debug("%s: got %s", u->meta.id, e);
2518 free(s->status_text);
2523 static int service_enumerate(Manager *m) {
2527 char *path = NULL, *fpath = NULL, *name = NULL;
2532 STRV_FOREACH(p, m->lookup_paths.sysvrcnd_path)
2533 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++) {
2538 if (asprintf(&path, "%s/%s", *p, rcnd_table[i].path) < 0) {
2546 if (!(d = opendir(path))) {
2547 if (errno != ENOENT)
2548 log_warning("opendir() failed on %s: %s", path, strerror(errno));
2553 while ((de = readdir(d))) {
2557 if (ignore_file(de->d_name))
2560 if (de->d_name[0] != 'S' && de->d_name[0] != 'K')
2563 if (strlen(de->d_name) < 4)
2566 a = undecchar(de->d_name[1]);
2567 b = undecchar(de->d_name[2]);
2574 if (asprintf(&fpath, "%s/%s/%s", *p, rcnd_table[i].path, de->d_name) < 0) {
2579 if (access(fpath, X_OK) < 0) {
2581 if (errno != ENOENT)
2582 log_warning("access() failed on %s: %s", fpath, strerror(errno));
2588 if (!(name = sysv_translate_name(de->d_name + 3))) {
2593 if ((r = manager_load_unit_prepare(m, name, NULL, NULL, &service)) < 0) {
2594 log_warning("Failed to prepare unit %s: %s", name, strerror(-r));
2598 if (de->d_name[0] == 'S' &&
2599 (rcnd_table[i].type == RUNLEVEL_UP || rcnd_table[i].type == RUNLEVEL_SYSINIT))
2600 SERVICE(service)->sysv_start_priority =
2601 MAX(a*10 + b, SERVICE(service)->sysv_start_priority);
2603 manager_dispatch_load_queue(m);
2604 service = unit_follow_merge(service);
2606 /* If this is a native service, rely
2607 * on native ways to pull in a
2608 * service, don't pull it in via sysv
2610 if (service->meta.fragment_path)
2613 if (de->d_name[0] == 'S') {
2615 if ((r = unit_add_two_dependencies_by_name_inverse(service, UNIT_AFTER, UNIT_WANTS, rcnd_table[i].target, NULL, true)) < 0)
2618 } else if (de->d_name[0] == 'K' &&
2619 (rcnd_table[i].type == RUNLEVEL_DOWN ||
2620 rcnd_table[i].type == RUNLEVEL_SYSINIT)) {
2622 /* We honour K links only for
2623 * halt/reboot. For the normal
2624 * runlevels we assume the
2626 * implicitly added by the
2627 * core logic. Also, we don't
2628 * really distuingish here
2629 * between the runlevels 0 and
2630 * 6 and just add them to the
2631 * special shutdown target. On
2632 * SUSE the boot.d/ runlevel
2633 * is also used for shutdown,
2634 * so we add links for that
2635 * too to the shutdown
2638 if ((r = unit_add_two_dependencies_by_name_inverse(service, UNIT_AFTER, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true)) < 0)
2657 static void service_bus_name_owner_change(
2660 const char *old_owner,
2661 const char *new_owner) {
2663 Service *s = SERVICE(u);
2668 assert(streq(s->bus_name, name));
2669 assert(old_owner || new_owner);
2671 if (old_owner && new_owner)
2672 log_debug("%s's D-Bus name %s changed owner from %s to %s", u->meta.id, name, old_owner, new_owner);
2674 log_debug("%s's D-Bus name %s no longer registered by %s", u->meta.id, name, old_owner);
2676 log_debug("%s's D-Bus name %s now registered by %s", u->meta.id, name, new_owner);
2678 s->bus_name_good = !!new_owner;
2680 if (s->type == SERVICE_DBUS) {
2682 /* service_enter_running() will figure out what to
2684 if (s->state == SERVICE_RUNNING)
2685 service_enter_running(s, true);
2686 else if (s->state == SERVICE_START && new_owner)
2687 service_enter_start_post(s);
2689 } else if (new_owner &&
2691 (s->state == SERVICE_START ||
2692 s->state == SERVICE_START_POST ||
2693 s->state == SERVICE_RUNNING ||
2694 s->state == SERVICE_RELOAD)) {
2696 /* Try to acquire PID from bus service */
2697 log_debug("Trying to acquire PID from D-Bus name...");
2699 bus_query_pid(u->meta.manager, name);
2703 static void service_bus_query_pid_done(
2708 Service *s = SERVICE(u);
2713 log_debug("%s's D-Bus name %s is now owned by process %u", u->meta.id, name, (unsigned) pid);
2715 if (s->main_pid <= 0 &&
2716 (s->state == SERVICE_START ||
2717 s->state == SERVICE_START_POST ||
2718 s->state == SERVICE_RUNNING ||
2719 s->state == SERVICE_RELOAD))
2720 service_set_main_pid(s, pid);
2723 int service_set_socket_fd(Service *s, int fd, Socket *sock) {
2727 /* This is called by the socket code when instantiating a new
2728 * service for a stream socket and the socket needs to be
2731 if (s->meta.load_state != UNIT_LOADED)
2734 if (s->socket_fd >= 0)
2737 if (s->state != SERVICE_DEAD)
2741 s->got_socket_fd = true;
2747 static void service_reset_maintenance(Unit *u) {
2748 Service *s = SERVICE(u);
2752 if (s->state == SERVICE_MAINTENANCE)
2753 service_set_state(s, SERVICE_DEAD);
2758 static const char* const service_state_table[_SERVICE_STATE_MAX] = {
2759 [SERVICE_DEAD] = "dead",
2760 [SERVICE_START_PRE] = "start-pre",
2761 [SERVICE_START] = "start",
2762 [SERVICE_START_POST] = "start-post",
2763 [SERVICE_RUNNING] = "running",
2764 [SERVICE_EXITED] = "exited",
2765 [SERVICE_RELOAD] = "reload",
2766 [SERVICE_STOP] = "stop",
2767 [SERVICE_STOP_SIGTERM] = "stop-sigterm",
2768 [SERVICE_STOP_SIGKILL] = "stop-sigkill",
2769 [SERVICE_STOP_POST] = "stop-post",
2770 [SERVICE_FINAL_SIGTERM] = "final-sigterm",
2771 [SERVICE_FINAL_SIGKILL] = "final-sigkill",
2772 [SERVICE_MAINTENANCE] = "maintenance",
2773 [SERVICE_AUTO_RESTART] = "auto-restart",
2776 DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
2778 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
2779 [SERVICE_ONCE] = "once",
2780 [SERVICE_RESTART_ON_SUCCESS] = "restart-on-success",
2781 [SERVICE_RESTART_ALWAYS] = "restart-always",
2784 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
2786 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
2787 [SERVICE_SIMPLE] = "simple",
2788 [SERVICE_FORKING] = "forking",
2789 [SERVICE_FINISH] = "finish",
2790 [SERVICE_DBUS] = "dbus",
2791 [SERVICE_NOTIFY] = "notify"
2794 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
2796 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
2797 [SERVICE_EXEC_START_PRE] = "ExecStartPre",
2798 [SERVICE_EXEC_START] = "ExecStart",
2799 [SERVICE_EXEC_START_POST] = "ExecStartPost",
2800 [SERVICE_EXEC_RELOAD] = "ExecReload",
2801 [SERVICE_EXEC_STOP] = "ExecStop",
2802 [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
2805 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
2807 static const char* const notify_access_table[_NOTIFY_ACCESS_MAX] = {
2808 [NOTIFY_NONE] = "none",
2809 [NOTIFY_MAIN] = "main",
2810 [NOTIFY_ALL] = "all"
2813 DEFINE_STRING_TABLE_LOOKUP(notify_access, NotifyAccess);
2815 const UnitVTable service_vtable = {
2816 .suffix = ".service",
2817 .show_status = true,
2819 .init = service_init,
2820 .done = service_done,
2821 .load = service_load,
2823 .coldplug = service_coldplug,
2825 .dump = service_dump,
2827 .start = service_start,
2828 .stop = service_stop,
2829 .reload = service_reload,
2831 .can_reload = service_can_reload,
2833 .serialize = service_serialize,
2834 .deserialize_item = service_deserialize_item,
2836 .active_state = service_active_state,
2837 .sub_state_to_string = service_sub_state_to_string,
2839 .check_gc = service_check_gc,
2840 .check_snapshot = service_check_snapshot,
2842 .sigchld_event = service_sigchld_event,
2843 .timer_event = service_timer_event,
2845 .reset_maintenance = service_reset_maintenance,
2847 .cgroup_notify_empty = service_cgroup_notify_event,
2848 .notify_message = service_notify_message,
2850 .bus_name_owner_change = service_bus_name_owner_change,
2851 .bus_query_pid_done = service_bus_query_pid_done,
2853 .bus_message_handler = bus_service_message_handler,
2855 .enumerate = service_enumerate