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 },
60 /* SUSE style boot.d */
61 { "boot.d", SPECIAL_SYSINIT_TARGET, RUNLEVEL_SYSINIT },
65 /* Debian style rcS.d */
66 { "rcS.d", SPECIAL_SYSINIT_TARGET, RUNLEVEL_SYSINIT },
69 /* Standard SysV runlevels for shutdown */
70 { "rc0.d", SPECIAL_POWEROFF_TARGET, RUNLEVEL_DOWN },
71 { "rc6.d", SPECIAL_REBOOT_TARGET, RUNLEVEL_DOWN }
73 /* Note that the order here matters, as we read the
74 directories in this order, and we want to make sure that
75 sysv_start_priority is known when we first load the
76 unit. And that value we only know from S links. Hence
77 UP/SYSINIT must be read before DOWN */
80 #define RUNLEVELS_UP "12345"
81 /* #define RUNLEVELS_DOWN "06" */
82 /* #define RUNLEVELS_BOOT "bBsS" */
84 static const UnitActiveState state_translation_table[_SERVICE_STATE_MAX] = {
85 [SERVICE_DEAD] = UNIT_INACTIVE,
86 [SERVICE_START_PRE] = UNIT_ACTIVATING,
87 [SERVICE_START] = UNIT_ACTIVATING,
88 [SERVICE_START_POST] = UNIT_ACTIVATING,
89 [SERVICE_RUNNING] = UNIT_ACTIVE,
90 [SERVICE_EXITED] = UNIT_ACTIVE,
91 [SERVICE_RELOAD] = UNIT_RELOADING,
92 [SERVICE_STOP] = UNIT_DEACTIVATING,
93 [SERVICE_STOP_SIGTERM] = UNIT_DEACTIVATING,
94 [SERVICE_STOP_SIGKILL] = UNIT_DEACTIVATING,
95 [SERVICE_STOP_POST] = UNIT_DEACTIVATING,
96 [SERVICE_FINAL_SIGTERM] = UNIT_DEACTIVATING,
97 [SERVICE_FINAL_SIGKILL] = UNIT_DEACTIVATING,
98 [SERVICE_MAINTENANCE] = UNIT_MAINTENANCE,
99 [SERVICE_AUTO_RESTART] = UNIT_ACTIVATING
102 static void service_init(Unit *u) {
103 Service *s = SERVICE(u);
106 assert(u->meta.load_state == UNIT_STUB);
108 s->timeout_usec = DEFAULT_TIMEOUT_USEC;
109 s->restart_usec = DEFAULT_RESTART_USEC;
110 s->timer_watch.type = WATCH_INVALID;
111 s->sysv_start_priority = -1;
114 exec_context_init(&s->exec_context);
116 RATELIMIT_INIT(s->ratelimit, 10*USEC_PER_SEC, 5);
118 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
121 static void service_unwatch_control_pid(Service *s) {
124 if (s->control_pid <= 0)
127 unit_unwatch_pid(UNIT(s), s->control_pid);
131 static void service_unwatch_main_pid(Service *s) {
134 if (s->main_pid <= 0)
137 unit_unwatch_pid(UNIT(s), s->main_pid);
141 static int service_set_main_pid(Service *s, pid_t pid) {
152 if (get_parent_of_pid(pid, &ppid) >= 0 && ppid != getpid())
153 log_warning("%s: Supervising process %lu which is not our child. We'll most likely not notice when it exits.",
154 s->meta.id, (unsigned long) pid);
157 s->main_pid_known = true;
159 exec_status_start(&s->main_exec_status, pid);
164 static void service_close_socket_fd(Service *s) {
167 if (s->socket_fd < 0)
170 close_nointr_nofail(s->socket_fd);
174 static void service_connection_unref(Service *s) {
180 socket_connection_unref(s->socket);
184 static void service_done(Unit *u) {
185 Service *s = SERVICE(u);
195 free(s->sysv_runlevels);
196 s->sysv_runlevels = NULL;
198 free(s->status_text);
199 s->status_text = NULL;
201 exec_context_done(&s->exec_context);
202 exec_command_free_array(s->exec_command, _SERVICE_EXEC_COMMAND_MAX);
203 s->control_command = NULL;
205 /* This will leak a process, but at least no memory or any of
207 service_unwatch_main_pid(s);
208 service_unwatch_control_pid(s);
211 unit_unwatch_bus_name(UNIT(u), s->bus_name);
216 service_close_socket_fd(s);
217 service_connection_unref(s);
219 unit_unwatch_timer(u, &s->timer_watch);
222 static char *sysv_translate_name(const char *name) {
225 if (!(r = new(char, strlen(name) + sizeof(".service"))))
228 if (startswith(name, "boot."))
229 /* Drop SuSE-style boot. prefix */
230 strcpy(stpcpy(r, name + 5), ".service");
231 else if (endswith(name, ".sh"))
232 /* Drop Debian-style .sh suffix */
233 strcpy(stpcpy(r, name) - 3, ".service");
235 /* Normal init scripts */
236 strcpy(stpcpy(r, name), ".service");
241 static int sysv_translate_facility(const char *name, char **_r) {
243 static const char * const table[] = {
244 /* LSB defined facilities */
245 "$local_fs", SPECIAL_LOCAL_FS_TARGET,
246 "$network", SPECIAL_NETWORK_TARGET,
247 "$named", SPECIAL_NSS_LOOKUP_TARGET,
248 "$portmap", SPECIAL_RPCBIND_TARGET,
249 "$remote_fs", SPECIAL_REMOTE_FS_TARGET,
250 "$syslog", SPECIAL_SYSLOG_TARGET,
251 "$time", SPECIAL_RTC_SET_TARGET,
253 /* Debian extensions */
254 "$mail-transport-agent", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
255 "$mail-transfer-agent", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
256 "$x-display-manager", SPECIAL_DISPLAY_MANAGER_SERVICE
262 for (i = 0; i < ELEMENTSOF(table); i += 2)
263 if (streq(table[i], name)) {
264 if (!(r = strdup(table[i+1])))
273 if (!(r = sysv_translate_name(name)))
284 static int sysv_fix_order(Service *s) {
290 if (s->sysv_start_priority < 0)
293 /* For each pair of services where at least one lacks a LSB
294 * header, we use the start priority value to order things. */
296 LIST_FOREACH(units_per_type, other, s->meta.manager->units_per_type[UNIT_SERVICE]) {
299 bool special_s, special_t;
301 t = (Service*) other;
306 if (t->sysv_start_priority < 0)
309 /* If both units have modern headers we don't care
310 * about the priorities */
311 if ((!s->sysv_path || s->sysv_has_lsb) &&
312 (!t->sysv_path || t->sysv_has_lsb))
315 special_s = s->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, s->sysv_runlevels);
316 special_t = t->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, t->sysv_runlevels);
318 if (special_t && !special_s)
320 else if (special_s && !special_t)
322 else if (t->sysv_start_priority < s->sysv_start_priority)
324 else if (t->sysv_start_priority > s->sysv_start_priority)
329 /* FIXME: Maybe we should compare the name here lexicographically? */
331 if (!(r = unit_add_dependency(UNIT(s), d, UNIT(t), true)) < 0)
338 static ExecCommand *exec_command_new(const char *path, const char *arg1) {
341 if (!(c = new0(ExecCommand, 1)))
344 if (!(c->path = strdup(path))) {
349 if (!(c->argv = strv_new(path, arg1, NULL))) {
358 static int sysv_exec_commands(Service *s) {
362 assert(s->sysv_path);
364 if (!(c = exec_command_new(s->sysv_path, "start")))
366 exec_command_append_list(s->exec_command+SERVICE_EXEC_START, c);
368 if (!(c = exec_command_new(s->sysv_path, "stop")))
370 exec_command_append_list(s->exec_command+SERVICE_EXEC_STOP, c);
372 if (!(c = exec_command_new(s->sysv_path, "reload")))
374 exec_command_append_list(s->exec_command+SERVICE_EXEC_RELOAD, c);
379 static int service_load_sysv_path(Service *s, const char *path) {
396 if (!(f = fopen(path, "re"))) {
397 r = errno == ENOENT ? 0 : -errno;
402 if (!(s->sysv_path = strdup(path))) {
408 char l[LINE_MAX], *t;
410 if (!fgets(l, sizeof(l), f)) {
415 log_error("Failed to read configuration file '%s': %s", path, strerror(-r));
425 if (state == NORMAL && streq(t, "### BEGIN INIT INFO")) {
427 s->sysv_has_lsb = true;
431 if ((state == LSB_DESCRIPTION || state == LSB) && streq(t, "### END INIT INFO")) {
437 t += strspn(t, WHITESPACE);
439 if (state == NORMAL) {
441 /* Try to parse Red Hat style chkconfig headers */
443 if (startswith_no_case(t, "chkconfig:")) {
445 char runlevels[16], *k;
449 if (sscanf(t+10, "%15s %i %*i",
451 &start_priority) != 2) {
453 log_warning("[%s:%u] Failed to parse chkconfig line. Ignoring.", path, line);
457 /* A start priority gathered from the
458 * symlink farms is preferred over the
459 * data from the LSB header. */
460 if (start_priority < 0 || start_priority > 99)
461 log_warning("[%s:%u] Start priority out of range. Ignoring.", path, line);
462 else if (s->sysv_start_priority < 0)
463 s->sysv_start_priority = start_priority;
465 char_array_0(runlevels);
466 k = delete_chars(runlevels, WHITESPACE "-");
471 if (!(d = strdup(k))) {
476 free(s->sysv_runlevels);
477 s->sysv_runlevels = d;
480 } else if (startswith_no_case(t, "description:") &&
481 !u->meta.description) {
483 size_t k = strlen(t);
486 if (t[k-1] == '\\') {
491 if (!(d = strdup(strstrip(t+12)))) {
496 free(u->meta.description);
497 u->meta.description = d;
499 } else if (startswith_no_case(t, "pidfile:")) {
506 if (!path_is_absolute(fn)) {
507 log_warning("[%s:%u] PID file not absolute. Ignoring.", path, line);
511 if (!(fn = strdup(fn))) {
520 } else if (state == DESCRIPTION) {
522 /* Try to parse Red Hat style description
525 size_t k = strlen(t);
533 assert(u->meta.description);
534 if (asprintf(&d, "%s %s", u->meta.description, strstrip(t)) < 0) {
539 free(u->meta.description);
540 u->meta.description = d;
542 } else if (state == LSB || state == LSB_DESCRIPTION) {
544 if (startswith_no_case(t, "Provides:")) {
550 FOREACH_WORD_QUOTED(w, z, t+9, i) {
553 if (!(n = strndup(w, z))) {
558 r = sysv_translate_facility(n, &m);
567 if (unit_name_to_type(m) == UNIT_SERVICE)
568 r = unit_add_name(u, m);
569 else if (s->sysv_start_priority >= 0)
570 r = unit_add_two_dependencies_by_name_inverse(u, UNIT_AFTER, UNIT_WANTS, m, NULL, true);
572 r = unit_add_dependency_by_name_inverse(u, UNIT_AFTER, m, NULL, true);
580 } else if (startswith_no_case(t, "Required-Start:") ||
581 startswith_no_case(t, "Should-Start:") ||
582 startswith_no_case(t, "X-Start-Before:") ||
583 startswith_no_case(t, "X-Start-After:")) {
589 FOREACH_WORD_QUOTED(w, z, strchr(t, ':')+1, i) {
592 if (!(n = strndup(w, z))) {
597 r = sysv_translate_facility(n, &m);
606 r = unit_add_dependency_by_name(u, startswith_no_case(t, "X-Start-Before:") ? UNIT_BEFORE : UNIT_AFTER, m, NULL, true);
612 } else if (startswith_no_case(t, "Default-Start:")) {
617 k = delete_chars(t+14, WHITESPACE "-");
620 if (!(d = strdup(k))) {
625 free(s->sysv_runlevels);
626 s->sysv_runlevels = d;
629 } else if (startswith_no_case(t, "Description:") &&
630 !u->meta.description) {
633 /* We use the long description only if
634 * no short description is set. */
636 state = LSB_DESCRIPTION;
638 if (!(d = strdup(strstrip(t+12)))) {
643 free(u->meta.description);
644 u->meta.description = d;
646 } else if (startswith_no_case(t, "Short-Description:")) {
651 if (!(d = strdup(strstrip(t+18)))) {
656 free(u->meta.description);
657 u->meta.description = d;
659 } else if (startswith_no_case(t, "X-Interactive:")) {
662 if ((b = parse_boolean(strstrip(t+14))) < 0) {
663 log_warning("[%s:%u] Couldn't parse interactive flag. Ignoring.", path, line);
668 s->exec_context.std_input = EXEC_INPUT_TTY;
670 s->exec_context.std_input = EXEC_INPUT_NULL;
672 } else if (state == LSB_DESCRIPTION) {
674 if (startswith(l, "#\t") || startswith(l, "# ")) {
677 assert(u->meta.description);
678 if (asprintf(&d, "%s %s", u->meta.description, t) < 0) {
683 free(u->meta.description);
684 u->meta.description = d;
691 if ((r = sysv_exec_commands(s)) < 0)
694 if (s->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, s->sysv_runlevels)) {
695 /* If there a runlevels configured for this service
696 * but none of the standard ones, then we assume this
697 * is some special kind of service (which might be
698 * needed for early boot) and don't create any links
701 s->meta.default_dependencies = false;
703 /* Don't timeout special services during boot (like fsck) */
707 /* Special setting for all SysV services */
708 s->type = SERVICE_FORKING;
709 s->valid_no_process = true;
710 s->restart = SERVICE_ONCE;
711 s->exec_context.std_output = EXEC_OUTPUT_TTY;
712 s->exec_context.kill_mode = KILL_PROCESS_GROUP;
714 u->meta.load_state = UNIT_LOADED;
725 static int service_load_sysv_name(Service *s, const char *name) {
731 /* For SysV services we strip the boot. or .sh
732 * prefixes/suffixes. */
733 if (startswith(name, "boot.") ||
734 endswith(name, ".sh.service"))
737 STRV_FOREACH(p, s->meta.manager->lookup_paths.sysvinit_path) {
741 if (asprintf(&path, "%s/%s", *p, name) < 0)
744 assert(endswith(path, ".service"));
745 path[strlen(path)-8] = 0;
747 r = service_load_sysv_path(s, path);
749 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
750 /* Try Debian style xxx.sh source'able init scripts */
752 r = service_load_sysv_path(s, path);
757 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
758 /* Try SUSE style boot.xxx init scripts */
760 if (asprintf(&path, "%s/boot.%s", *p, name) < 0)
763 path[strlen(path)-8] = 0;
764 r = service_load_sysv_path(s, path);
771 if ((s->meta.load_state != UNIT_STUB))
778 static int service_load_sysv(Service *s) {
785 /* Load service data from SysV init scripts, preferably with
788 if (strv_isempty(s->meta.manager->lookup_paths.sysvinit_path))
791 if ((t = s->meta.id))
792 if ((r = service_load_sysv_name(s, t)) < 0)
795 if (s->meta.load_state == UNIT_STUB)
796 SET_FOREACH(t, s->meta.names, i) {
800 if ((r == service_load_sysv_name(s, t)) < 0)
803 if (s->meta.load_state != UNIT_STUB)
810 static int service_add_bus_name(Service *s) {
817 if (asprintf(&n, "dbus-%s.service", s->bus_name) < 0)
820 r = unit_merge_by_name(UNIT(s), n);
826 static int service_verify(Service *s) {
829 if (s->meta.load_state != UNIT_LOADED)
832 if (!s->exec_command[SERVICE_EXEC_START]) {
833 log_error("%s lacks ExecStart setting. Refusing.", s->meta.id);
837 if (s->exec_command[SERVICE_EXEC_START]->command_next) {
838 log_error("%s has more than one ExecStart setting. Refusing.", s->meta.id);
842 if (s->type == SERVICE_DBUS && !s->bus_name) {
843 log_error("%s is of type D-Bus but no D-Bus service name has been specified. Refusing.", s->meta.id);
847 if (s->exec_context.pam_name && s->exec_context.kill_mode != KILL_CONTROL_GROUP) {
848 log_error("%s has PAM enabled. Kill mode must be set to 'control-group'. Refusing.", s->meta.id);
855 static int service_add_default_dependencies(Service *s) {
860 /* Add a number of automatic dependencies useful for the
861 * majority of services. */
863 /* First, pull in base system */
864 if (s->meta.manager->running_as == MANAGER_SYSTEM) {
866 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_BASIC_TARGET, NULL, true)) < 0)
869 } else if (s->meta.manager->running_as == MANAGER_SESSION) {
871 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SOCKETS_TARGET, NULL, true)) < 0)
875 /* Second, activate normal shutdown */
876 return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true);
879 static int service_load(Unit *u) {
881 Service *s = SERVICE(u);
885 /* Load a .service file */
886 if ((r = unit_load_fragment(u)) < 0)
889 /* Load a classic init script as a fallback, if we couldn't find anything */
890 if (u->meta.load_state == UNIT_STUB)
891 if ((r = service_load_sysv(s)) < 0)
894 /* Still nothing found? Then let's give up */
895 if (u->meta.load_state == UNIT_STUB)
898 /* We were able to load something, then let's add in the
899 * dropin directories. */
900 if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
903 /* This is a new unit? Then let's add in some extras */
904 if (u->meta.load_state == UNIT_LOADED) {
905 if ((r = unit_add_exec_dependencies(u, &s->exec_context)) < 0)
908 if ((r = unit_add_default_cgroup(u)) < 0)
911 if ((r = sysv_fix_order(s)) < 0)
915 if ((r = service_add_bus_name(s)) < 0)
918 if ((r = unit_watch_bus_name(u, s->bus_name)) < 0)
922 if (s->type == SERVICE_NOTIFY && s->notify_access == NOTIFY_NONE)
923 s->notify_access = NOTIFY_MAIN;
925 if (s->type == SERVICE_DBUS || s->bus_name)
926 if ((r = unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_REQUIRES, SPECIAL_DBUS_TARGET, NULL, true)) < 0)
929 if (s->meta.default_dependencies)
930 if ((r = service_add_default_dependencies(s)) < 0)
934 return service_verify(s);
937 static void service_dump(Unit *u, FILE *f, const char *prefix) {
939 ServiceExecCommand c;
940 Service *s = SERVICE(u);
946 p2 = strappend(prefix, "\t");
947 prefix2 = p2 ? p2 : prefix;
950 "%sService State: %s\n"
951 "%sPermissionsStartOnly: %s\n"
952 "%sRootDirectoryStartOnly: %s\n"
953 "%sValidNoProcess: %s\n"
955 "%sNotifyAccess: %s\n",
956 prefix, service_state_to_string(s->state),
957 prefix, yes_no(s->permissions_start_only),
958 prefix, yes_no(s->root_directory_start_only),
959 prefix, yes_no(s->valid_no_process),
960 prefix, service_type_to_string(s->type),
961 prefix, notify_access_to_string(s->notify_access));
963 if (s->control_pid > 0)
965 "%sControl PID: %lu\n",
966 prefix, (unsigned long) s->control_pid);
971 prefix, (unsigned long) s->main_pid);
976 prefix, s->pid_file);
981 "%sBus Name Good: %s\n",
983 prefix, yes_no(s->bus_name_good));
985 exec_context_dump(&s->exec_context, f, prefix);
987 for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
989 if (!s->exec_command[c])
992 fprintf(f, "%s-> %s:\n",
993 prefix, service_exec_command_to_string(c));
995 exec_command_dump_list(s->exec_command[c], f, prefix2);
1000 "%sSysV Init Script Path: %s\n"
1001 "%sSysV Init Script has LSB Header: %s\n",
1002 prefix, s->sysv_path,
1003 prefix, yes_no(s->sysv_has_lsb));
1005 if (s->sysv_start_priority >= 0)
1007 "%sSysVStartPriority: %i\n",
1008 prefix, s->sysv_start_priority);
1010 if (s->sysv_runlevels)
1011 fprintf(f, "%sSysVRunLevels: %s\n",
1012 prefix, s->sysv_runlevels);
1015 fprintf(f, "%sStatus Text: %s\n",
1016 prefix, s->status_text);
1021 static int service_load_pid_file(Service *s) {
1028 if (s->main_pid_known)
1031 assert(s->main_pid <= 0);
1036 if ((r = read_one_line_file(s->pid_file, &k)) < 0)
1039 r = parse_pid(k, &pid);
1045 if (kill(pid, 0) < 0 && errno != EPERM) {
1046 log_warning("PID %lu read from file %s does not exist. Your service or init script might be broken.",
1047 (unsigned long) pid, s->pid_file);
1051 if ((r = service_set_main_pid(s, pid)) < 0)
1054 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1055 /* FIXME: we need to do something here */
1061 static int service_get_sockets(Service *s, Set **_set) {
1070 if (s->socket_fd >= 0)
1073 /* Collects all Socket objects that belong to this
1074 * service. Note that a service might have multiple sockets
1075 * via multiple names. */
1077 if (!(set = set_new(NULL, NULL)))
1080 SET_FOREACH(t, s->meta.names, i) {
1084 /* Look for all socket objects that go by any of our
1085 * units and collect their fds */
1087 if (!(k = unit_name_change_suffix(t, ".socket"))) {
1092 p = manager_get_unit(s->meta.manager, k);
1098 if ((r = set_put(set, p)) < 0)
1110 static int service_notify_sockets_dead(Service *s) {
1118 if (s->socket_fd >= 0)
1121 /* Notifies all our sockets when we die */
1122 if ((r = service_get_sockets(s, &set)) < 0)
1125 SET_FOREACH(sock, set, i)
1126 socket_notify_service_dead(sock);
1133 static void service_set_state(Service *s, ServiceState state) {
1134 ServiceState old_state;
1137 old_state = s->state;
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 state != SERVICE_AUTO_RESTART)
1151 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1153 if (state != SERVICE_START &&
1154 state != SERVICE_START_POST &&
1155 state != SERVICE_RUNNING &&
1156 state != SERVICE_RELOAD &&
1157 state != SERVICE_STOP &&
1158 state != SERVICE_STOP_SIGTERM &&
1159 state != SERVICE_STOP_SIGKILL)
1160 service_unwatch_main_pid(s);
1162 if (state != SERVICE_START_PRE &&
1163 state != SERVICE_START &&
1164 state != SERVICE_START_POST &&
1165 state != SERVICE_RELOAD &&
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 service_unwatch_control_pid(s);
1173 s->control_command = NULL;
1174 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1177 if (state == SERVICE_DEAD ||
1178 state == SERVICE_STOP ||
1179 state == SERVICE_STOP_SIGTERM ||
1180 state == SERVICE_STOP_SIGKILL ||
1181 state == SERVICE_STOP_POST ||
1182 state == SERVICE_FINAL_SIGTERM ||
1183 state == SERVICE_FINAL_SIGKILL ||
1184 state == SERVICE_MAINTENANCE ||
1185 state == SERVICE_AUTO_RESTART)
1186 service_notify_sockets_dead(s);
1188 if (state != SERVICE_START_PRE &&
1189 state != SERVICE_START &&
1190 state != SERVICE_START_POST &&
1191 state != SERVICE_RUNNING &&
1192 state != SERVICE_RELOAD &&
1193 state != SERVICE_STOP &&
1194 state != SERVICE_STOP_SIGTERM &&
1195 state != SERVICE_STOP_SIGKILL &&
1196 state != SERVICE_STOP_POST &&
1197 state != SERVICE_FINAL_SIGTERM &&
1198 state != SERVICE_FINAL_SIGKILL &&
1199 !(state == SERVICE_DEAD && s->meta.job)) {
1200 service_close_socket_fd(s);
1201 service_connection_unref(s);
1204 /* For the inactive states unit_notify() will trim the cgroup,
1205 * but for exit we have to do that ourselves... */
1206 if (state == SERVICE_EXITED)
1207 cgroup_bonding_trim_list(s->meta.cgroup_bondings, true);
1209 if (old_state != state)
1210 log_debug("%s changed %s -> %s", s->meta.id, service_state_to_string(old_state), service_state_to_string(state));
1212 unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state]);
1215 static int service_coldplug(Unit *u) {
1216 Service *s = SERVICE(u);
1220 assert(s->state == SERVICE_DEAD);
1222 if (s->deserialized_state != s->state) {
1224 if (s->deserialized_state == SERVICE_START_PRE ||
1225 s->deserialized_state == SERVICE_START ||
1226 s->deserialized_state == SERVICE_START_POST ||
1227 s->deserialized_state == SERVICE_RELOAD ||
1228 s->deserialized_state == SERVICE_STOP ||
1229 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1230 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1231 s->deserialized_state == SERVICE_STOP_POST ||
1232 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1233 s->deserialized_state == SERVICE_FINAL_SIGKILL ||
1234 s->deserialized_state == SERVICE_AUTO_RESTART) {
1236 if (s->deserialized_state == SERVICE_AUTO_RESTART || s->timeout_usec > 0) {
1239 k = s->deserialized_state == SERVICE_AUTO_RESTART ? s->restart_usec : s->timeout_usec;
1241 if ((r = unit_watch_timer(UNIT(s), k, &s->timer_watch)) < 0)
1246 if ((s->deserialized_state == SERVICE_START &&
1247 (s->type == SERVICE_FORKING ||
1248 s->type == SERVICE_DBUS ||
1249 s->type == SERVICE_FINISH ||
1250 s->type == SERVICE_NOTIFY)) ||
1251 s->deserialized_state == SERVICE_START_POST ||
1252 s->deserialized_state == SERVICE_RUNNING ||
1253 s->deserialized_state == SERVICE_RELOAD ||
1254 s->deserialized_state == SERVICE_STOP ||
1255 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1256 s->deserialized_state == SERVICE_STOP_SIGKILL)
1257 if (s->main_pid > 0)
1258 if ((r = unit_watch_pid(UNIT(s), s->main_pid)) < 0)
1261 if (s->deserialized_state == SERVICE_START_PRE ||
1262 s->deserialized_state == SERVICE_START ||
1263 s->deserialized_state == SERVICE_START_POST ||
1264 s->deserialized_state == SERVICE_RELOAD ||
1265 s->deserialized_state == SERVICE_STOP ||
1266 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1267 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1268 s->deserialized_state == SERVICE_STOP_POST ||
1269 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1270 s->deserialized_state == SERVICE_FINAL_SIGKILL)
1271 if (s->control_pid > 0)
1272 if ((r = unit_watch_pid(UNIT(s), s->control_pid)) < 0)
1275 service_set_state(s, s->deserialized_state);
1281 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
1285 unsigned rn_fds = 0;
1293 if (s->socket_fd >= 0)
1296 if ((r = service_get_sockets(s, &set)) < 0)
1299 SET_FOREACH(sock, set, i) {
1303 if ((r = socket_collect_fds(sock, &cfds, &cn_fds)) < 0)
1315 if (!(t = new(int, rn_fds+cn_fds))) {
1321 memcpy(t, rfds, rn_fds);
1322 memcpy(t+rn_fds, cfds, cn_fds);
1327 rn_fds = rn_fds+cn_fds;
1345 static int service_spawn(
1350 bool apply_permissions,
1352 bool apply_tty_stdin,
1353 bool set_notify_socket,
1358 int *fds = NULL, *fdsbuf = NULL;
1359 unsigned n_fds = 0, n_env = 0;
1360 char **argv = NULL, **final_env = NULL, **our_env = NULL;
1367 s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1368 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1369 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
1371 if (s->socket_fd >= 0) {
1372 fds = &s->socket_fd;
1375 if ((r = service_collect_fds(s, &fdsbuf, &n_fds)) < 0)
1382 if (timeout && s->timeout_usec) {
1383 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1386 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1388 if (!(argv = unit_full_printf_strv(UNIT(s), c->argv))) {
1393 if (!(our_env = new0(char*, 3))) {
1398 if (set_notify_socket)
1399 if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=@%s", s->meta.manager->notify_socket) < 0) {
1404 if (s->main_pid > 0)
1405 if (asprintf(our_env + n_env++, "MAINPID=%lu", (unsigned long) s->main_pid) < 0) {
1410 if (!(final_env = strv_env_merge(2,
1411 s->meta.manager->environment,
1426 s->meta.manager->confirm_spawn,
1427 s->meta.cgroup_bondings,
1434 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1435 /* FIXME: we need to do something here */
1441 strv_free(final_env);
1451 strv_free(final_env);
1454 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1459 static int main_pid_good(Service *s) {
1462 /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1465 /* If we know the pid file, then lets just check if it is
1467 if (s->main_pid_known)
1468 return s->main_pid > 0;
1470 /* We don't know the pid */
1474 static int control_pid_good(Service *s) {
1477 return s->control_pid > 0;
1480 static int cgroup_good(Service *s) {
1485 if ((r = cgroup_bonding_is_empty_list(s->meta.cgroup_bondings)) < 0)
1491 static void service_enter_dead(Service *s, bool success, bool allow_restart) {
1498 if (allow_restart &&
1500 (s->restart == SERVICE_RESTART_ALWAYS ||
1501 (s->restart == SERVICE_RESTART_ON_SUCCESS && !s->failure))) {
1503 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
1506 service_set_state(s, SERVICE_AUTO_RESTART);
1508 service_set_state(s, s->failure ? SERVICE_MAINTENANCE : SERVICE_DEAD);
1513 log_warning("%s failed to run install restart timer: %s", s->meta.id, strerror(-r));
1514 service_enter_dead(s, false, false);
1517 static void service_enter_signal(Service *s, ServiceState state, bool success);
1519 static void service_enter_stop_post(Service *s, bool success) {
1526 service_unwatch_control_pid(s);
1528 s->control_command_id = SERVICE_EXEC_STOP_POST;
1529 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST])) {
1530 if ((r = service_spawn(s,
1534 !s->permissions_start_only,
1535 !s->root_directory_start_only,
1538 &s->control_pid)) < 0)
1542 service_set_state(s, SERVICE_STOP_POST);
1544 service_enter_signal(s, SERVICE_FINAL_SIGTERM, true);
1549 log_warning("%s failed to run 'stop-post' task: %s", s->meta.id, strerror(-r));
1550 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1553 static void service_enter_signal(Service *s, ServiceState state, bool success) {
1562 if (s->exec_context.kill_mode != KILL_NONE) {
1563 int sig = (state == SERVICE_STOP_SIGTERM || state == SERVICE_FINAL_SIGTERM) ? s->exec_context.kill_signal : SIGKILL;
1565 if (s->exec_context.kill_mode == KILL_CONTROL_GROUP) {
1567 if ((r = cgroup_bonding_kill_list(s->meta.cgroup_bondings, sig)) < 0) {
1568 if (r != -EAGAIN && r != -ESRCH)
1577 if (s->main_pid > 0) {
1578 if (kill(s->exec_context.kill_mode == KILL_PROCESS ? s->main_pid : -s->main_pid, sig) < 0 && errno != ESRCH)
1584 if (s->control_pid > 0) {
1585 if (kill(s->exec_context.kill_mode == KILL_PROCESS ? s->control_pid : -s->control_pid, sig) < 0 && errno != ESRCH)
1596 if (sent && (s->main_pid > 0 || s->control_pid > 0)) {
1597 if (s->timeout_usec > 0)
1598 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1601 service_set_state(s, state);
1602 } else if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1603 service_enter_stop_post(s, true);
1605 service_enter_dead(s, true, true);
1610 log_warning("%s failed to kill processes: %s", s->meta.id, strerror(-r));
1612 if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1613 service_enter_stop_post(s, false);
1615 service_enter_dead(s, false, true);
1618 static void service_enter_stop(Service *s, bool success) {
1626 service_unwatch_control_pid(s);
1628 s->control_command_id = SERVICE_EXEC_STOP;
1629 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP])) {
1630 if ((r = service_spawn(s,
1634 !s->permissions_start_only,
1635 !s->root_directory_start_only,
1638 &s->control_pid)) < 0)
1641 service_set_state(s, SERVICE_STOP);
1643 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
1648 log_warning("%s failed to run 'stop' task: %s", s->meta.id, strerror(-r));
1649 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1652 static void service_enter_running(Service *s, bool success) {
1653 int main_pid_ok, cgroup_ok;
1659 main_pid_ok = main_pid_good(s);
1660 cgroup_ok = cgroup_good(s);
1662 if ((main_pid_ok > 0 || (main_pid_ok < 0 && cgroup_ok != 0)) &&
1663 (s->bus_name_good || s->type != SERVICE_DBUS))
1664 service_set_state(s, SERVICE_RUNNING);
1665 else if (s->valid_no_process)
1666 service_set_state(s, SERVICE_EXITED);
1668 service_enter_stop(s, true);
1671 static void service_enter_start_post(Service *s) {
1675 service_unwatch_control_pid(s);
1677 s->control_command_id = SERVICE_EXEC_START_POST;
1678 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_POST])) {
1679 if ((r = service_spawn(s,
1683 !s->permissions_start_only,
1684 !s->root_directory_start_only,
1687 &s->control_pid)) < 0)
1690 service_set_state(s, SERVICE_START_POST);
1692 service_enter_running(s, true);
1697 log_warning("%s failed to run 'start-post' task: %s", s->meta.id, strerror(-r));
1698 service_enter_stop(s, false);
1701 static void service_enter_start(Service *s) {
1707 assert(s->exec_command[SERVICE_EXEC_START]);
1708 assert(!s->exec_command[SERVICE_EXEC_START]->command_next);
1710 if (s->type == SERVICE_FORKING)
1711 service_unwatch_control_pid(s);
1713 service_unwatch_main_pid(s);
1715 if ((r = service_spawn(s,
1716 s->exec_command[SERVICE_EXEC_START],
1717 s->type == SERVICE_FORKING || s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY,
1722 s->notify_access != NOTIFY_NONE,
1726 if (s->type == SERVICE_SIMPLE) {
1727 /* For simple services we immediately start
1728 * the START_POST binaries. */
1730 service_set_main_pid(s, pid);
1731 service_enter_start_post(s);
1733 } else if (s->type == SERVICE_FORKING) {
1735 /* For forking services we wait until the start
1736 * process exited. */
1738 s->control_command_id = SERVICE_EXEC_START;
1739 s->control_command = s->exec_command[SERVICE_EXEC_START];
1741 s->control_pid = pid;
1742 service_set_state(s, SERVICE_START);
1744 } else if (s->type == SERVICE_FINISH ||
1745 s->type == SERVICE_DBUS ||
1746 s->type == SERVICE_NOTIFY) {
1748 /* For finishing services we wait until the start
1749 * process exited, too, but it is our main process. */
1751 /* For D-Bus services we know the main pid right away,
1752 * but wait for the bus name to appear on the
1753 * bus. Notify services are similar. */
1755 service_set_main_pid(s, pid);
1756 service_set_state(s, SERVICE_START);
1758 assert_not_reached("Unknown service type");
1763 log_warning("%s failed to run 'start' task: %s", s->meta.id, strerror(-r));
1764 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1767 static void service_enter_start_pre(Service *s) {
1772 service_unwatch_control_pid(s);
1774 s->control_command_id = SERVICE_EXEC_START_PRE;
1775 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_PRE])) {
1776 if ((r = service_spawn(s,
1780 !s->permissions_start_only,
1781 !s->root_directory_start_only,
1784 &s->control_pid)) < 0)
1787 service_set_state(s, SERVICE_START_PRE);
1789 service_enter_start(s);
1794 log_warning("%s failed to run 'start-pre' task: %s", s->meta.id, strerror(-r));
1795 service_enter_dead(s, false, true);
1798 static void service_enter_restart(Service *s) {
1803 dbus_error_init(&error);
1805 service_enter_dead(s, true, false);
1807 if ((r = manager_add_job(s->meta.manager, JOB_START, UNIT(s), JOB_FAIL, false, NULL, NULL)) < 0)
1810 log_debug("%s scheduled restart job.", s->meta.id);
1814 log_warning("%s failed to schedule restart job: %s", s->meta.id, bus_error(&error, -r));
1815 service_enter_dead(s, false, false);
1817 dbus_error_free(&error);
1820 static void service_enter_reload(Service *s) {
1825 service_unwatch_control_pid(s);
1827 s->control_command_id = SERVICE_EXEC_RELOAD;
1828 if ((s->control_command = s->exec_command[SERVICE_EXEC_RELOAD])) {
1829 if ((r = service_spawn(s,
1833 !s->permissions_start_only,
1834 !s->root_directory_start_only,
1837 &s->control_pid)) < 0)
1840 service_set_state(s, SERVICE_RELOAD);
1842 service_enter_running(s, true);
1847 log_warning("%s failed to run 'reload' task: %s", s->meta.id, strerror(-r));
1848 service_enter_stop(s, false);
1851 static void service_run_next(Service *s, bool success) {
1855 assert(s->control_command);
1856 assert(s->control_command->command_next);
1861 s->control_command = s->control_command->command_next;
1863 service_unwatch_control_pid(s);
1865 if ((r = service_spawn(s,
1869 !s->permissions_start_only,
1870 !s->root_directory_start_only,
1871 s->control_command_id == SERVICE_EXEC_START_PRE ||
1872 s->control_command_id == SERVICE_EXEC_STOP_POST,
1874 &s->control_pid)) < 0)
1880 log_warning("%s failed to run next task: %s", s->meta.id, strerror(-r));
1882 if (s->state == SERVICE_START_PRE)
1883 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1884 else if (s->state == SERVICE_STOP)
1885 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1886 else if (s->state == SERVICE_STOP_POST)
1887 service_enter_dead(s, false, true);
1889 service_enter_stop(s, false);
1892 static int service_start(Unit *u) {
1893 Service *s = SERVICE(u);
1897 /* We cannot fulfill this request right now, try again later
1899 if (s->state == SERVICE_STOP ||
1900 s->state == SERVICE_STOP_SIGTERM ||
1901 s->state == SERVICE_STOP_SIGKILL ||
1902 s->state == SERVICE_STOP_POST ||
1903 s->state == SERVICE_FINAL_SIGTERM ||
1904 s->state == SERVICE_FINAL_SIGKILL)
1907 /* Already on it! */
1908 if (s->state == SERVICE_START_PRE ||
1909 s->state == SERVICE_START ||
1910 s->state == SERVICE_START_POST)
1913 assert(s->state == SERVICE_DEAD || s->state == SERVICE_MAINTENANCE || s->state == SERVICE_AUTO_RESTART);
1915 /* Make sure we don't enter a busy loop of some kind. */
1916 if (!ratelimit_test(&s->ratelimit)) {
1917 log_warning("%s start request repeated too quickly, refusing to start.", u->meta.id);
1921 if ((s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1922 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1923 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) &&
1925 log_warning("%s can only be started with a per-connection socket.", u->meta.id);
1930 s->main_pid_known = false;
1931 s->allow_restart = true;
1933 service_enter_start_pre(s);
1937 static int service_stop(Unit *u) {
1938 Service *s = SERVICE(u);
1942 /* This is a user request, so don't do restarts on this
1944 s->allow_restart = false;
1947 if (s->state == SERVICE_STOP ||
1948 s->state == SERVICE_STOP_SIGTERM ||
1949 s->state == SERVICE_STOP_SIGKILL ||
1950 s->state == SERVICE_STOP_POST ||
1951 s->state == SERVICE_FINAL_SIGTERM ||
1952 s->state == SERVICE_FINAL_SIGKILL)
1955 /* Don't allow a restart */
1956 if (s->state == SERVICE_AUTO_RESTART) {
1957 service_set_state(s, SERVICE_DEAD);
1961 /* If there's already something running we go directly into
1963 if (s->state == SERVICE_START_PRE ||
1964 s->state == SERVICE_START ||
1965 s->state == SERVICE_START_POST ||
1966 s->state == SERVICE_RELOAD) {
1967 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
1971 assert(s->state == SERVICE_RUNNING ||
1972 s->state == SERVICE_EXITED);
1974 service_enter_stop(s, true);
1978 static int service_reload(Unit *u) {
1979 Service *s = SERVICE(u);
1983 assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
1985 service_enter_reload(s);
1989 static bool service_can_reload(Unit *u) {
1990 Service *s = SERVICE(u);
1994 return !!s->exec_command[SERVICE_EXEC_RELOAD];
1997 static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
1998 Service *s = SERVICE(u);
2004 unit_serialize_item(u, f, "state", service_state_to_string(s->state));
2005 unit_serialize_item(u, f, "failure", yes_no(s->failure));
2007 if (s->control_pid > 0)
2008 unit_serialize_item_format(u, f, "control-pid", "%lu", (unsigned long) s->control_pid);
2010 if (s->main_pid_known && s->main_pid > 0)
2011 unit_serialize_item_format(u, f, "main-pid", "%lu", (unsigned long) s->main_pid);
2013 unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
2016 unit_serialize_item(u, f, "status-text", s->status_text);
2018 /* There's a minor uncleanliness here: if there are multiple
2019 * commands attached here, we will start from the first one
2021 if (s->control_command_id >= 0)
2022 unit_serialize_item(u, f, "control-command", service_exec_command_to_string(s->control_command_id));
2024 if (s->socket_fd >= 0) {
2027 if ((copy = fdset_put_dup(fds, s->socket_fd)) < 0)
2030 unit_serialize_item_format(u, f, "socket-fd", "%i", copy);
2033 if (s->main_exec_status.pid > 0) {
2034 unit_serialize_item_format(u, f, "main-exec-status-pid", "%lu", (unsigned long) s->main_exec_status.pid);
2036 if (s->main_exec_status.start_timestamp.realtime > 0) {
2037 unit_serialize_item_format(u, f, "main-exec-status-start-realtime",
2038 "%llu", (unsigned long long) s->main_exec_status.start_timestamp.realtime);
2040 unit_serialize_item_format(u, f, "main-exec-status-start-monotonic",
2041 "%llu", (unsigned long long) s->main_exec_status.start_timestamp.monotonic);
2044 if (s->main_exec_status.exit_timestamp.realtime > 0) {
2045 unit_serialize_item_format(u, f, "main-exec-status-exit-realtime",
2046 "%llu", (unsigned long long) s->main_exec_status.exit_timestamp.realtime);
2047 unit_serialize_item_format(u, f, "main-exec-status-exit-monotonic",
2048 "%llu", (unsigned long long) s->main_exec_status.exit_timestamp.monotonic);
2050 unit_serialize_item_format(u, f, "main-exec-status-code", "%i", s->main_exec_status.code);
2051 unit_serialize_item_format(u, f, "main-exec-status-status", "%i", s->main_exec_status.status);
2058 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
2059 Service *s = SERVICE(u);
2067 if (streq(key, "state")) {
2070 if ((state = service_state_from_string(value)) < 0)
2071 log_debug("Failed to parse state value %s", value);
2073 s->deserialized_state = state;
2074 } else if (streq(key, "failure")) {
2077 if ((b = parse_boolean(value)) < 0)
2078 log_debug("Failed to parse failure value %s", value);
2080 s->failure = b || s->failure;
2081 } else if (streq(key, "control-pid")) {
2084 if ((r = parse_pid(value, &pid)) < 0)
2085 log_debug("Failed to parse control-pid value %s", value);
2087 s->control_pid = pid;
2088 } else if (streq(key, "main-pid")) {
2091 if ((r = parse_pid(value, &pid)) < 0)
2092 log_debug("Failed to parse main-pid value %s", value);
2094 service_set_main_pid(s, (pid_t) pid);
2095 } else if (streq(key, "main-pid-known")) {
2098 if ((b = parse_boolean(value)) < 0)
2099 log_debug("Failed to parse main-pid-known value %s", value);
2101 s->main_pid_known = b;
2102 } else if (streq(key, "status-text")) {
2105 if ((t = strdup(value))) {
2106 free(s->status_text);
2110 } else if (streq(key, "control-command")) {
2111 ServiceExecCommand id;
2113 if ((id = service_exec_command_from_string(value)) < 0)
2114 log_debug("Failed to parse exec-command value %s", value);
2116 s->control_command_id = id;
2117 s->control_command = s->exec_command[id];
2119 } else if (streq(key, "socket-fd")) {
2122 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2123 log_debug("Failed to parse socket-fd value %s", value);
2126 if (s->socket_fd >= 0)
2127 close_nointr_nofail(s->socket_fd);
2128 s->socket_fd = fdset_remove(fds, fd);
2130 } else if (streq(key, "main-exec-status-pid")) {
2133 if ((r = parse_pid(value, &pid)) < 0)
2134 log_debug("Failed to parse main-exec-status-pid value %s", value);
2136 s->main_exec_status.pid = pid;
2137 } else if (streq(key, "main-exec-status-code")) {
2140 if ((r = safe_atoi(value, &i)) < 0)
2141 log_debug("Failed to parse main-exec-status-code value %s", value);
2143 s->main_exec_status.code = i;
2144 } else if (streq(key, "main-exec-status-status")) {
2147 if ((r = safe_atoi(value, &i)) < 0)
2148 log_debug("Failed to parse main-exec-status-status value %s", value);
2150 s->main_exec_status.status = i;
2151 } else if (streq(key, "main-exec-status-start-realtime")) {
2154 if ((r = safe_atou64(value, &k)) < 0)
2155 log_debug("Failed to parse main-exec-status-start-realtime value %s", value);
2157 s->main_exec_status.start_timestamp.realtime = (usec_t) k;
2158 } else if (streq(key, "main-exec-status-start-monotonic")) {
2161 if ((r = safe_atou64(value, &k)) < 0)
2162 log_debug("Failed to parse main-exec-status-start-monotonic value %s", value);
2164 s->main_exec_status.start_timestamp.monotonic = (usec_t) k;
2165 } else if (streq(key, "main-exec-status-exit-realtime")) {
2168 if ((r = safe_atou64(value, &k)) < 0)
2169 log_debug("Failed to parse main-exec-status-exit-realtime value %s", value);
2171 s->main_exec_status.exit_timestamp.realtime = (usec_t) k;
2172 } else if (streq(key, "main-exec-status-exit-monotonic")) {
2175 if ((r = safe_atou64(value, &k)) < 0)
2176 log_debug("Failed to parse main-exec-status-exit-monotonic value %s", value);
2178 s->main_exec_status.exit_timestamp.monotonic = (usec_t) k;
2180 log_debug("Unknown serialization key '%s'", key);
2185 static UnitActiveState service_active_state(Unit *u) {
2188 return state_translation_table[SERVICE(u)->state];
2191 static const char *service_sub_state_to_string(Unit *u) {
2194 return service_state_to_string(SERVICE(u)->state);
2197 static bool service_check_gc(Unit *u) {
2198 Service *s = SERVICE(u);
2202 return !!s->sysv_path;
2205 static bool service_check_snapshot(Unit *u) {
2206 Service *s = SERVICE(u);
2210 return !s->got_socket_fd;
2213 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2214 Service *s = SERVICE(u);
2220 success = is_clean_exit(code, status);
2222 if (s->main_pid == pid) {
2224 exec_status_exit(&s->main_exec_status, pid, code, status);
2227 if (s->type != SERVICE_FORKING) {
2228 assert(s->exec_command[SERVICE_EXEC_START]);
2229 s->exec_command[SERVICE_EXEC_START]->exec_status = s->main_exec_status;
2231 if (s->exec_command[SERVICE_EXEC_START]->ignore)
2235 log_full(success ? LOG_DEBUG : LOG_NOTICE,
2236 "%s: main process exited, code=%s, status=%i", u->meta.id, sigchld_code_to_string(code), status);
2237 s->failure = s->failure || !success;
2239 /* The service exited, so the service is officially
2244 case SERVICE_START_POST:
2245 case SERVICE_RELOAD:
2247 /* Need to wait until the operation is
2252 if (s->type == SERVICE_FINISH) {
2253 /* This was our main goal, so let's go on */
2255 service_enter_start_post(s);
2257 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2260 assert(s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY);
2265 case SERVICE_RUNNING:
2266 service_enter_running(s, success);
2269 case SERVICE_STOP_SIGTERM:
2270 case SERVICE_STOP_SIGKILL:
2272 if (!control_pid_good(s))
2273 service_enter_stop_post(s, success);
2275 /* If there is still a control process, wait for that first */
2279 assert_not_reached("Uh, main process died at wrong time.");
2282 } else if (s->control_pid == pid) {
2284 if (s->control_command) {
2285 exec_status_exit(&s->control_command->exec_status, pid, code, status);
2287 if (s->control_command->ignore)
2293 log_full(success ? LOG_DEBUG : LOG_NOTICE,
2294 "%s: control process exited, code=%s status=%i", u->meta.id, sigchld_code_to_string(code), status);
2295 s->failure = s->failure || !success;
2297 /* If we are shutting things down anyway we
2298 * don't care about failing commands. */
2300 if (s->control_command && s->control_command->command_next && success) {
2302 /* There is another command to *
2303 * execute, so let's do that. */
2305 log_debug("%s running next command for state %s", u->meta.id, service_state_to_string(s->state));
2306 service_run_next(s, success);
2309 /* No further commands for this step, so let's
2310 * figure out what to do next */
2312 s->control_command = NULL;
2313 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2315 log_debug("%s got final SIGCHLD for state %s", u->meta.id, service_state_to_string(s->state));
2319 case SERVICE_START_PRE:
2321 service_enter_start(s);
2323 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2327 assert(s->type == SERVICE_FORKING);
2329 /* Let's try to load the pid
2330 * file here if we can. We
2331 * ignore the return value,
2332 * since the PID file might
2333 * actually be created by a
2334 * START_POST script */
2338 service_load_pid_file(s);
2340 service_enter_start_post(s);
2342 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2346 case SERVICE_START_POST:
2347 if (success && s->pid_file && !s->main_pid_known) {
2350 /* Hmm, let's see if we can
2351 * load the pid now after the
2352 * start-post scripts got
2355 if ((r = service_load_pid_file(s)) < 0)
2356 log_warning("%s: failed to load PID file %s: %s", s->meta.id, s->pid_file, strerror(-r));
2361 case SERVICE_RELOAD:
2363 service_enter_running(s, true);
2365 service_enter_stop(s, false);
2370 service_enter_signal(s, SERVICE_STOP_SIGTERM, success);
2373 case SERVICE_STOP_SIGTERM:
2374 case SERVICE_STOP_SIGKILL:
2375 if (main_pid_good(s) <= 0)
2376 service_enter_stop_post(s, success);
2378 /* If there is still a service
2379 * process around, wait until
2380 * that one quit, too */
2383 case SERVICE_STOP_POST:
2384 case SERVICE_FINAL_SIGTERM:
2385 case SERVICE_FINAL_SIGKILL:
2386 service_enter_dead(s, success, true);
2390 assert_not_reached("Uh, control process died at wrong time.");
2396 static void service_timer_event(Unit *u, uint64_t elapsed, Watch* w) {
2397 Service *s = SERVICE(u);
2400 assert(elapsed == 1);
2402 assert(w == &s->timer_watch);
2406 case SERVICE_START_PRE:
2408 log_warning("%s operation timed out. Terminating.", u->meta.id);
2409 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2412 case SERVICE_START_POST:
2413 case SERVICE_RELOAD:
2414 log_warning("%s operation timed out. Stopping.", u->meta.id);
2415 service_enter_stop(s, false);
2419 log_warning("%s stopping timed out. Terminating.", u->meta.id);
2420 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
2423 case SERVICE_STOP_SIGTERM:
2424 log_warning("%s stopping timed out. Killing.", u->meta.id);
2425 service_enter_signal(s, SERVICE_STOP_SIGKILL, false);
2428 case SERVICE_STOP_SIGKILL:
2429 /* Uh, wie sent a SIGKILL and it is still not gone?
2430 * Must be something we cannot kill, so let's just be
2431 * weirded out and continue */
2433 log_warning("%s still around after SIGKILL. Ignoring.", u->meta.id);
2434 service_enter_stop_post(s, false);
2437 case SERVICE_STOP_POST:
2438 log_warning("%s stopping timed out (2). Terminating.", u->meta.id);
2439 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2442 case SERVICE_FINAL_SIGTERM:
2443 log_warning("%s stopping timed out (2). Killing.", u->meta.id);
2444 service_enter_signal(s, SERVICE_FINAL_SIGKILL, false);
2447 case SERVICE_FINAL_SIGKILL:
2448 log_warning("%s still around after SIGKILL (2). Entering maintenance mode.", u->meta.id);
2449 service_enter_dead(s, false, true);
2452 case SERVICE_AUTO_RESTART:
2453 log_info("%s holdoff time over, scheduling restart.", u->meta.id);
2454 service_enter_restart(s);
2458 assert_not_reached("Timeout at wrong time.");
2462 static void service_cgroup_notify_event(Unit *u) {
2463 Service *s = SERVICE(u);
2467 log_debug("%s: cgroup is empty", u->meta.id);
2471 /* Waiting for SIGCHLD is usually more interesting,
2472 * because it includes return codes/signals. Which is
2473 * why we ignore the cgroup events for most cases,
2474 * except when we don't know pid which to expect the
2477 case SERVICE_RUNNING:
2478 service_enter_running(s, true);
2486 static void service_notify_message(Unit *u, pid_t pid, char **tags) {
2487 Service *s = SERVICE(u);
2492 if (s->notify_access == NOTIFY_NONE) {
2493 log_warning("%s: Got notification message from PID %lu, but reception is disabled.",
2494 u->meta.id, (unsigned long) pid);
2498 if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
2499 log_warning("%s: Got notification message from PID %lu, but reception only permitted for PID %lu",
2500 u->meta.id, (unsigned long) pid, (unsigned long) s->main_pid);
2504 log_debug("%s: Got message", u->meta.id);
2506 /* Interpret MAINPID= */
2507 if ((e = strv_find_prefix(tags, "MAINPID=")) &&
2508 (s->state == SERVICE_START ||
2509 s->state == SERVICE_START_POST ||
2510 s->state == SERVICE_RUNNING ||
2511 s->state == SERVICE_RELOAD)) {
2513 if (parse_pid(e + 8, &pid) < 0)
2514 log_warning("Failed to parse notification message %s", e);
2516 log_debug("%s: got %s", u->meta.id, e);
2517 service_set_main_pid(s, pid);
2521 /* Interpret READY= */
2522 if (s->type == SERVICE_NOTIFY &&
2523 s->state == SERVICE_START &&
2524 strv_find(tags, "READY=1")) {
2525 log_debug("%s: got READY=1", u->meta.id);
2527 service_enter_start_post(s);
2530 /* Interpret STATUS= */
2531 if ((e = strv_find_prefix(tags, "STATUS="))) {
2535 if (!(t = strdup(e+7))) {
2536 log_error("Failed to allocate string.");
2540 log_debug("%s: got %s", u->meta.id, e);
2542 free(s->status_text);
2545 free(s->status_text);
2546 s->status_text = NULL;
2552 static int service_enumerate(Manager *m) {
2556 char *path = NULL, *fpath = NULL, *name = NULL;
2561 STRV_FOREACH(p, m->lookup_paths.sysvrcnd_path)
2562 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++) {
2567 if (asprintf(&path, "%s/%s", *p, rcnd_table[i].path) < 0) {
2575 if (!(d = opendir(path))) {
2576 if (errno != ENOENT)
2577 log_warning("opendir() failed on %s: %s", path, strerror(errno));
2582 while ((de = readdir(d))) {
2586 if (ignore_file(de->d_name))
2589 if (de->d_name[0] != 'S' && de->d_name[0] != 'K')
2592 if (strlen(de->d_name) < 4)
2595 a = undecchar(de->d_name[1]);
2596 b = undecchar(de->d_name[2]);
2603 if (asprintf(&fpath, "%s/%s/%s", *p, rcnd_table[i].path, de->d_name) < 0) {
2608 if (access(fpath, X_OK) < 0) {
2610 if (errno != ENOENT)
2611 log_warning("access() failed on %s: %s", fpath, strerror(errno));
2617 if (!(name = sysv_translate_name(de->d_name + 3))) {
2622 if ((r = manager_load_unit_prepare(m, name, NULL, NULL, &service)) < 0) {
2623 log_warning("Failed to prepare unit %s: %s", name, strerror(-r));
2627 if (de->d_name[0] == 'S' &&
2628 (rcnd_table[i].type == RUNLEVEL_UP || rcnd_table[i].type == RUNLEVEL_SYSINIT))
2629 SERVICE(service)->sysv_start_priority =
2630 MAX(a*10 + b, SERVICE(service)->sysv_start_priority);
2632 manager_dispatch_load_queue(m);
2633 service = unit_follow_merge(service);
2635 /* If this is a native service, rely
2636 * on native ways to pull in a
2637 * service, don't pull it in via sysv
2639 if (service->meta.fragment_path)
2642 if (de->d_name[0] == 'S') {
2644 if ((r = unit_add_two_dependencies_by_name_inverse(service, UNIT_AFTER, UNIT_WANTS, rcnd_table[i].target, NULL, true)) < 0)
2647 } else if (de->d_name[0] == 'K' &&
2648 (rcnd_table[i].type == RUNLEVEL_DOWN ||
2649 rcnd_table[i].type == RUNLEVEL_SYSINIT)) {
2651 /* We honour K links only for
2652 * halt/reboot. For the normal
2653 * runlevels we assume the
2655 * implicitly added by the
2656 * core logic. Also, we don't
2657 * really distuingish here
2658 * between the runlevels 0 and
2659 * 6 and just add them to the
2660 * special shutdown target. On
2661 * SUSE the boot.d/ runlevel
2662 * is also used for shutdown,
2663 * so we add links for that
2664 * too to the shutdown
2667 if ((r = unit_add_two_dependencies_by_name_inverse(service, UNIT_AFTER, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true)) < 0)
2686 static void service_bus_name_owner_change(
2689 const char *old_owner,
2690 const char *new_owner) {
2692 Service *s = SERVICE(u);
2697 assert(streq(s->bus_name, name));
2698 assert(old_owner || new_owner);
2700 if (old_owner && new_owner)
2701 log_debug("%s's D-Bus name %s changed owner from %s to %s", u->meta.id, name, old_owner, new_owner);
2703 log_debug("%s's D-Bus name %s no longer registered by %s", u->meta.id, name, old_owner);
2705 log_debug("%s's D-Bus name %s now registered by %s", u->meta.id, name, new_owner);
2707 s->bus_name_good = !!new_owner;
2709 if (s->type == SERVICE_DBUS) {
2711 /* service_enter_running() will figure out what to
2713 if (s->state == SERVICE_RUNNING)
2714 service_enter_running(s, true);
2715 else if (s->state == SERVICE_START && new_owner)
2716 service_enter_start_post(s);
2718 } else if (new_owner &&
2720 (s->state == SERVICE_START ||
2721 s->state == SERVICE_START_POST ||
2722 s->state == SERVICE_RUNNING ||
2723 s->state == SERVICE_RELOAD)) {
2725 /* Try to acquire PID from bus service */
2726 log_debug("Trying to acquire PID from D-Bus name...");
2728 bus_query_pid(u->meta.manager, name);
2732 static void service_bus_query_pid_done(
2737 Service *s = SERVICE(u);
2742 log_debug("%s's D-Bus name %s is now owned by process %u", u->meta.id, name, (unsigned) pid);
2744 if (s->main_pid <= 0 &&
2745 (s->state == SERVICE_START ||
2746 s->state == SERVICE_START_POST ||
2747 s->state == SERVICE_RUNNING ||
2748 s->state == SERVICE_RELOAD))
2749 service_set_main_pid(s, pid);
2752 int service_set_socket_fd(Service *s, int fd, Socket *sock) {
2756 /* This is called by the socket code when instantiating a new
2757 * service for a stream socket and the socket needs to be
2760 if (s->meta.load_state != UNIT_LOADED)
2763 if (s->socket_fd >= 0)
2766 if (s->state != SERVICE_DEAD)
2770 s->got_socket_fd = true;
2776 static void service_reset_maintenance(Unit *u) {
2777 Service *s = SERVICE(u);
2781 if (s->state == SERVICE_MAINTENANCE)
2782 service_set_state(s, SERVICE_DEAD);
2787 static const char* const service_state_table[_SERVICE_STATE_MAX] = {
2788 [SERVICE_DEAD] = "dead",
2789 [SERVICE_START_PRE] = "start-pre",
2790 [SERVICE_START] = "start",
2791 [SERVICE_START_POST] = "start-post",
2792 [SERVICE_RUNNING] = "running",
2793 [SERVICE_EXITED] = "exited",
2794 [SERVICE_RELOAD] = "reload",
2795 [SERVICE_STOP] = "stop",
2796 [SERVICE_STOP_SIGTERM] = "stop-sigterm",
2797 [SERVICE_STOP_SIGKILL] = "stop-sigkill",
2798 [SERVICE_STOP_POST] = "stop-post",
2799 [SERVICE_FINAL_SIGTERM] = "final-sigterm",
2800 [SERVICE_FINAL_SIGKILL] = "final-sigkill",
2801 [SERVICE_MAINTENANCE] = "maintenance",
2802 [SERVICE_AUTO_RESTART] = "auto-restart",
2805 DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
2807 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
2808 [SERVICE_ONCE] = "once",
2809 [SERVICE_RESTART_ON_SUCCESS] = "restart-on-success",
2810 [SERVICE_RESTART_ALWAYS] = "restart-always",
2813 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
2815 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
2816 [SERVICE_SIMPLE] = "simple",
2817 [SERVICE_FORKING] = "forking",
2818 [SERVICE_FINISH] = "finish",
2819 [SERVICE_DBUS] = "dbus",
2820 [SERVICE_NOTIFY] = "notify"
2823 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
2825 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
2826 [SERVICE_EXEC_START_PRE] = "ExecStartPre",
2827 [SERVICE_EXEC_START] = "ExecStart",
2828 [SERVICE_EXEC_START_POST] = "ExecStartPost",
2829 [SERVICE_EXEC_RELOAD] = "ExecReload",
2830 [SERVICE_EXEC_STOP] = "ExecStop",
2831 [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
2834 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
2836 static const char* const notify_access_table[_NOTIFY_ACCESS_MAX] = {
2837 [NOTIFY_NONE] = "none",
2838 [NOTIFY_MAIN] = "main",
2839 [NOTIFY_ALL] = "all"
2842 DEFINE_STRING_TABLE_LOOKUP(notify_access, NotifyAccess);
2844 const UnitVTable service_vtable = {
2845 .suffix = ".service",
2846 .show_status = true,
2848 .init = service_init,
2849 .done = service_done,
2850 .load = service_load,
2852 .coldplug = service_coldplug,
2854 .dump = service_dump,
2856 .start = service_start,
2857 .stop = service_stop,
2858 .reload = service_reload,
2860 .can_reload = service_can_reload,
2862 .serialize = service_serialize,
2863 .deserialize_item = service_deserialize_item,
2865 .active_state = service_active_state,
2866 .sub_state_to_string = service_sub_state_to_string,
2868 .check_gc = service_check_gc,
2869 .check_snapshot = service_check_snapshot,
2871 .sigchld_event = service_sigchld_event,
2872 .timer_event = service_timer_event,
2874 .reset_maintenance = service_reset_maintenance,
2876 .cgroup_notify_empty = service_cgroup_notify_event,
2877 .notify_message = service_notify_message,
2879 .bus_name_owner_change = service_bus_name_owner_change,
2880 .bus_query_pid_done = service_bus_query_pid_done,
2882 .bus_message_handler = bus_service_message_handler,
2884 .enumerate = service_enumerate