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"
956 "%sNotifyAccess: %s\n",
957 prefix, service_state_to_string(s->state),
958 prefix, yes_no(s->permissions_start_only),
959 prefix, yes_no(s->root_directory_start_only),
960 prefix, yes_no(s->valid_no_process),
961 prefix, service_type_to_string(s->type),
962 prefix, service_restart_to_string(s->restart),
963 prefix, notify_access_to_string(s->notify_access));
965 if (s->control_pid > 0)
967 "%sControl PID: %lu\n",
968 prefix, (unsigned long) s->control_pid);
973 prefix, (unsigned long) s->main_pid);
978 prefix, s->pid_file);
983 "%sBus Name Good: %s\n",
985 prefix, yes_no(s->bus_name_good));
987 exec_context_dump(&s->exec_context, f, prefix);
989 for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
991 if (!s->exec_command[c])
994 fprintf(f, "%s-> %s:\n",
995 prefix, service_exec_command_to_string(c));
997 exec_command_dump_list(s->exec_command[c], f, prefix2);
1002 "%sSysV Init Script Path: %s\n"
1003 "%sSysV Init Script has LSB Header: %s\n",
1004 prefix, s->sysv_path,
1005 prefix, yes_no(s->sysv_has_lsb));
1007 if (s->sysv_start_priority >= 0)
1009 "%sSysVStartPriority: %i\n",
1010 prefix, s->sysv_start_priority);
1012 if (s->sysv_runlevels)
1013 fprintf(f, "%sSysVRunLevels: %s\n",
1014 prefix, s->sysv_runlevels);
1017 fprintf(f, "%sStatus Text: %s\n",
1018 prefix, s->status_text);
1023 static int service_load_pid_file(Service *s) {
1030 if (s->main_pid_known)
1033 assert(s->main_pid <= 0);
1038 if ((r = read_one_line_file(s->pid_file, &k)) < 0)
1041 r = parse_pid(k, &pid);
1047 if (kill(pid, 0) < 0 && errno != EPERM) {
1048 log_warning("PID %lu read from file %s does not exist. Your service or init script might be broken.",
1049 (unsigned long) pid, s->pid_file);
1053 if ((r = service_set_main_pid(s, pid)) < 0)
1056 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1057 /* FIXME: we need to do something here */
1063 static int service_get_sockets(Service *s, Set **_set) {
1072 if (s->socket_fd >= 0)
1075 /* Collects all Socket objects that belong to this
1076 * service. Note that a service might have multiple sockets
1077 * via multiple names. */
1079 if (!(set = set_new(NULL, NULL)))
1082 SET_FOREACH(t, s->meta.names, i) {
1086 /* Look for all socket objects that go by any of our
1087 * units and collect their fds */
1089 if (!(k = unit_name_change_suffix(t, ".socket"))) {
1094 p = manager_get_unit(s->meta.manager, k);
1100 if ((r = set_put(set, p)) < 0)
1112 static int service_notify_sockets_dead(Service *s) {
1120 if (s->socket_fd >= 0)
1123 /* Notifies all our sockets when we die */
1124 if ((r = service_get_sockets(s, &set)) < 0)
1127 SET_FOREACH(sock, set, i)
1128 socket_notify_service_dead(sock);
1135 static void service_set_state(Service *s, ServiceState state) {
1136 ServiceState old_state;
1139 old_state = s->state;
1142 if (state != SERVICE_START_PRE &&
1143 state != SERVICE_START &&
1144 state != SERVICE_START_POST &&
1145 state != SERVICE_RELOAD &&
1146 state != SERVICE_STOP &&
1147 state != SERVICE_STOP_SIGTERM &&
1148 state != SERVICE_STOP_SIGKILL &&
1149 state != SERVICE_STOP_POST &&
1150 state != SERVICE_FINAL_SIGTERM &&
1151 state != SERVICE_FINAL_SIGKILL &&
1152 state != SERVICE_AUTO_RESTART)
1153 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1155 if (state != SERVICE_START &&
1156 state != SERVICE_START_POST &&
1157 state != SERVICE_RUNNING &&
1158 state != SERVICE_RELOAD &&
1159 state != SERVICE_STOP &&
1160 state != SERVICE_STOP_SIGTERM &&
1161 state != SERVICE_STOP_SIGKILL)
1162 service_unwatch_main_pid(s);
1164 if (state != SERVICE_START_PRE &&
1165 state != SERVICE_START &&
1166 state != SERVICE_START_POST &&
1167 state != SERVICE_RELOAD &&
1168 state != SERVICE_STOP &&
1169 state != SERVICE_STOP_SIGTERM &&
1170 state != SERVICE_STOP_SIGKILL &&
1171 state != SERVICE_STOP_POST &&
1172 state != SERVICE_FINAL_SIGTERM &&
1173 state != SERVICE_FINAL_SIGKILL) {
1174 service_unwatch_control_pid(s);
1175 s->control_command = NULL;
1176 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1179 if (state == SERVICE_DEAD ||
1180 state == SERVICE_STOP ||
1181 state == SERVICE_STOP_SIGTERM ||
1182 state == SERVICE_STOP_SIGKILL ||
1183 state == SERVICE_STOP_POST ||
1184 state == SERVICE_FINAL_SIGTERM ||
1185 state == SERVICE_FINAL_SIGKILL ||
1186 state == SERVICE_MAINTENANCE ||
1187 state == SERVICE_AUTO_RESTART)
1188 service_notify_sockets_dead(s);
1190 if (state != SERVICE_START_PRE &&
1191 state != SERVICE_START &&
1192 state != SERVICE_START_POST &&
1193 state != SERVICE_RUNNING &&
1194 state != SERVICE_RELOAD &&
1195 state != SERVICE_STOP &&
1196 state != SERVICE_STOP_SIGTERM &&
1197 state != SERVICE_STOP_SIGKILL &&
1198 state != SERVICE_STOP_POST &&
1199 state != SERVICE_FINAL_SIGTERM &&
1200 state != SERVICE_FINAL_SIGKILL &&
1201 !(state == SERVICE_DEAD && s->meta.job)) {
1202 service_close_socket_fd(s);
1203 service_connection_unref(s);
1206 /* For the inactive states unit_notify() will trim the cgroup,
1207 * but for exit we have to do that ourselves... */
1208 if (state == SERVICE_EXITED)
1209 cgroup_bonding_trim_list(s->meta.cgroup_bondings, true);
1211 if (old_state != state)
1212 log_debug("%s changed %s -> %s", s->meta.id, service_state_to_string(old_state), service_state_to_string(state));
1214 unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state]);
1217 static int service_coldplug(Unit *u) {
1218 Service *s = SERVICE(u);
1222 assert(s->state == SERVICE_DEAD);
1224 if (s->deserialized_state != s->state) {
1226 if (s->deserialized_state == SERVICE_START_PRE ||
1227 s->deserialized_state == SERVICE_START ||
1228 s->deserialized_state == SERVICE_START_POST ||
1229 s->deserialized_state == SERVICE_RELOAD ||
1230 s->deserialized_state == SERVICE_STOP ||
1231 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1232 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1233 s->deserialized_state == SERVICE_STOP_POST ||
1234 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1235 s->deserialized_state == SERVICE_FINAL_SIGKILL ||
1236 s->deserialized_state == SERVICE_AUTO_RESTART) {
1238 if (s->deserialized_state == SERVICE_AUTO_RESTART || s->timeout_usec > 0) {
1241 k = s->deserialized_state == SERVICE_AUTO_RESTART ? s->restart_usec : s->timeout_usec;
1243 if ((r = unit_watch_timer(UNIT(s), k, &s->timer_watch)) < 0)
1248 if ((s->deserialized_state == SERVICE_START &&
1249 (s->type == SERVICE_FORKING ||
1250 s->type == SERVICE_DBUS ||
1251 s->type == SERVICE_FINISH ||
1252 s->type == SERVICE_NOTIFY)) ||
1253 s->deserialized_state == SERVICE_START_POST ||
1254 s->deserialized_state == SERVICE_RUNNING ||
1255 s->deserialized_state == SERVICE_RELOAD ||
1256 s->deserialized_state == SERVICE_STOP ||
1257 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1258 s->deserialized_state == SERVICE_STOP_SIGKILL)
1259 if (s->main_pid > 0)
1260 if ((r = unit_watch_pid(UNIT(s), s->main_pid)) < 0)
1263 if (s->deserialized_state == SERVICE_START_PRE ||
1264 s->deserialized_state == SERVICE_START ||
1265 s->deserialized_state == SERVICE_START_POST ||
1266 s->deserialized_state == SERVICE_RELOAD ||
1267 s->deserialized_state == SERVICE_STOP ||
1268 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1269 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1270 s->deserialized_state == SERVICE_STOP_POST ||
1271 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1272 s->deserialized_state == SERVICE_FINAL_SIGKILL)
1273 if (s->control_pid > 0)
1274 if ((r = unit_watch_pid(UNIT(s), s->control_pid)) < 0)
1277 service_set_state(s, s->deserialized_state);
1283 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
1287 unsigned rn_fds = 0;
1295 if (s->socket_fd >= 0)
1298 if ((r = service_get_sockets(s, &set)) < 0)
1301 SET_FOREACH(sock, set, i) {
1305 if ((r = socket_collect_fds(sock, &cfds, &cn_fds)) < 0)
1317 if (!(t = new(int, rn_fds+cn_fds))) {
1323 memcpy(t, rfds, rn_fds);
1324 memcpy(t+rn_fds, cfds, cn_fds);
1329 rn_fds = rn_fds+cn_fds;
1347 static int service_spawn(
1352 bool apply_permissions,
1354 bool apply_tty_stdin,
1355 bool set_notify_socket,
1360 int *fds = NULL, *fdsbuf = NULL;
1361 unsigned n_fds = 0, n_env = 0;
1362 char **argv = NULL, **final_env = NULL, **our_env = NULL;
1369 s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1370 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1371 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
1373 if (s->socket_fd >= 0) {
1374 fds = &s->socket_fd;
1377 if ((r = service_collect_fds(s, &fdsbuf, &n_fds)) < 0)
1384 if (timeout && s->timeout_usec) {
1385 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1388 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1390 if (!(argv = unit_full_printf_strv(UNIT(s), c->argv))) {
1395 if (!(our_env = new0(char*, 3))) {
1400 if (set_notify_socket)
1401 if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=@%s", s->meta.manager->notify_socket) < 0) {
1406 if (s->main_pid > 0)
1407 if (asprintf(our_env + n_env++, "MAINPID=%lu", (unsigned long) s->main_pid) < 0) {
1412 if (!(final_env = strv_env_merge(2,
1413 s->meta.manager->environment,
1428 s->meta.manager->confirm_spawn,
1429 s->meta.cgroup_bondings,
1436 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1437 /* FIXME: we need to do something here */
1443 strv_free(final_env);
1453 strv_free(final_env);
1456 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1461 static int main_pid_good(Service *s) {
1464 /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1467 /* If we know the pid file, then lets just check if it is
1469 if (s->main_pid_known)
1470 return s->main_pid > 0;
1472 /* We don't know the pid */
1476 static int control_pid_good(Service *s) {
1479 return s->control_pid > 0;
1482 static int cgroup_good(Service *s) {
1487 if ((r = cgroup_bonding_is_empty_list(s->meta.cgroup_bondings)) < 0)
1493 static void service_enter_dead(Service *s, bool success, bool allow_restart) {
1500 if (allow_restart &&
1502 (s->restart == SERVICE_RESTART_ALWAYS ||
1503 (s->restart == SERVICE_RESTART_ON_SUCCESS && !s->failure))) {
1505 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
1508 service_set_state(s, SERVICE_AUTO_RESTART);
1510 service_set_state(s, s->failure ? SERVICE_MAINTENANCE : SERVICE_DEAD);
1515 log_warning("%s failed to run install restart timer: %s", s->meta.id, strerror(-r));
1516 service_enter_dead(s, false, false);
1519 static void service_enter_signal(Service *s, ServiceState state, bool success);
1521 static void service_enter_stop_post(Service *s, bool success) {
1528 service_unwatch_control_pid(s);
1530 s->control_command_id = SERVICE_EXEC_STOP_POST;
1531 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST])) {
1532 if ((r = service_spawn(s,
1536 !s->permissions_start_only,
1537 !s->root_directory_start_only,
1540 &s->control_pid)) < 0)
1544 service_set_state(s, SERVICE_STOP_POST);
1546 service_enter_signal(s, SERVICE_FINAL_SIGTERM, true);
1551 log_warning("%s failed to run 'stop-post' task: %s", s->meta.id, strerror(-r));
1552 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1555 static void service_enter_signal(Service *s, ServiceState state, bool success) {
1564 if (s->exec_context.kill_mode != KILL_NONE) {
1565 int sig = (state == SERVICE_STOP_SIGTERM || state == SERVICE_FINAL_SIGTERM) ? s->exec_context.kill_signal : SIGKILL;
1567 if (s->exec_context.kill_mode == KILL_CONTROL_GROUP) {
1569 if ((r = cgroup_bonding_kill_list(s->meta.cgroup_bondings, sig)) < 0) {
1570 if (r != -EAGAIN && r != -ESRCH)
1579 if (s->main_pid > 0) {
1580 if (kill(s->exec_context.kill_mode == KILL_PROCESS ? s->main_pid : -s->main_pid, sig) < 0 && errno != ESRCH)
1586 if (s->control_pid > 0) {
1587 if (kill(s->exec_context.kill_mode == KILL_PROCESS ? s->control_pid : -s->control_pid, sig) < 0 && errno != ESRCH)
1598 if (sent && (s->main_pid > 0 || s->control_pid > 0)) {
1599 if (s->timeout_usec > 0)
1600 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1603 service_set_state(s, state);
1604 } else if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1605 service_enter_stop_post(s, true);
1607 service_enter_dead(s, true, true);
1612 log_warning("%s failed to kill processes: %s", s->meta.id, strerror(-r));
1614 if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1615 service_enter_stop_post(s, false);
1617 service_enter_dead(s, false, true);
1620 static void service_enter_stop(Service *s, bool success) {
1628 service_unwatch_control_pid(s);
1630 s->control_command_id = SERVICE_EXEC_STOP;
1631 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP])) {
1632 if ((r = service_spawn(s,
1636 !s->permissions_start_only,
1637 !s->root_directory_start_only,
1640 &s->control_pid)) < 0)
1643 service_set_state(s, SERVICE_STOP);
1645 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
1650 log_warning("%s failed to run 'stop' task: %s", s->meta.id, strerror(-r));
1651 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1654 static void service_enter_running(Service *s, bool success) {
1655 int main_pid_ok, cgroup_ok;
1661 main_pid_ok = main_pid_good(s);
1662 cgroup_ok = cgroup_good(s);
1664 if ((main_pid_ok > 0 || (main_pid_ok < 0 && cgroup_ok != 0)) &&
1665 (s->bus_name_good || s->type != SERVICE_DBUS))
1666 service_set_state(s, SERVICE_RUNNING);
1667 else if (s->valid_no_process)
1668 service_set_state(s, SERVICE_EXITED);
1670 service_enter_stop(s, true);
1673 static void service_enter_start_post(Service *s) {
1677 service_unwatch_control_pid(s);
1679 s->control_command_id = SERVICE_EXEC_START_POST;
1680 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_POST])) {
1681 if ((r = service_spawn(s,
1685 !s->permissions_start_only,
1686 !s->root_directory_start_only,
1689 &s->control_pid)) < 0)
1692 service_set_state(s, SERVICE_START_POST);
1694 service_enter_running(s, true);
1699 log_warning("%s failed to run 'start-post' task: %s", s->meta.id, strerror(-r));
1700 service_enter_stop(s, false);
1703 static void service_enter_start(Service *s) {
1709 assert(s->exec_command[SERVICE_EXEC_START]);
1710 assert(!s->exec_command[SERVICE_EXEC_START]->command_next);
1712 if (s->type == SERVICE_FORKING)
1713 service_unwatch_control_pid(s);
1715 service_unwatch_main_pid(s);
1717 if ((r = service_spawn(s,
1718 s->exec_command[SERVICE_EXEC_START],
1719 s->type == SERVICE_FORKING || s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY,
1724 s->notify_access != NOTIFY_NONE,
1728 if (s->type == SERVICE_SIMPLE) {
1729 /* For simple services we immediately start
1730 * the START_POST binaries. */
1732 service_set_main_pid(s, pid);
1733 service_enter_start_post(s);
1735 } else if (s->type == SERVICE_FORKING) {
1737 /* For forking services we wait until the start
1738 * process exited. */
1740 s->control_command_id = SERVICE_EXEC_START;
1741 s->control_command = s->exec_command[SERVICE_EXEC_START];
1743 s->control_pid = pid;
1744 service_set_state(s, SERVICE_START);
1746 } else if (s->type == SERVICE_FINISH ||
1747 s->type == SERVICE_DBUS ||
1748 s->type == SERVICE_NOTIFY) {
1750 /* For finishing services we wait until the start
1751 * process exited, too, but it is our main process. */
1753 /* For D-Bus services we know the main pid right away,
1754 * but wait for the bus name to appear on the
1755 * bus. Notify services are similar. */
1757 service_set_main_pid(s, pid);
1758 service_set_state(s, SERVICE_START);
1760 assert_not_reached("Unknown service type");
1765 log_warning("%s failed to run 'start' task: %s", s->meta.id, strerror(-r));
1766 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1769 static void service_enter_start_pre(Service *s) {
1774 service_unwatch_control_pid(s);
1776 s->control_command_id = SERVICE_EXEC_START_PRE;
1777 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_PRE])) {
1778 if ((r = service_spawn(s,
1782 !s->permissions_start_only,
1783 !s->root_directory_start_only,
1786 &s->control_pid)) < 0)
1789 service_set_state(s, SERVICE_START_PRE);
1791 service_enter_start(s);
1796 log_warning("%s failed to run 'start-pre' task: %s", s->meta.id, strerror(-r));
1797 service_enter_dead(s, false, true);
1800 static void service_enter_restart(Service *s) {
1805 dbus_error_init(&error);
1807 service_enter_dead(s, true, false);
1809 if ((r = manager_add_job(s->meta.manager, JOB_START, UNIT(s), JOB_FAIL, false, NULL, NULL)) < 0)
1812 log_debug("%s scheduled restart job.", s->meta.id);
1816 log_warning("%s failed to schedule restart job: %s", s->meta.id, bus_error(&error, -r));
1817 service_enter_dead(s, false, false);
1819 dbus_error_free(&error);
1822 static void service_enter_reload(Service *s) {
1827 service_unwatch_control_pid(s);
1829 s->control_command_id = SERVICE_EXEC_RELOAD;
1830 if ((s->control_command = s->exec_command[SERVICE_EXEC_RELOAD])) {
1831 if ((r = service_spawn(s,
1835 !s->permissions_start_only,
1836 !s->root_directory_start_only,
1839 &s->control_pid)) < 0)
1842 service_set_state(s, SERVICE_RELOAD);
1844 service_enter_running(s, true);
1849 log_warning("%s failed to run 'reload' task: %s", s->meta.id, strerror(-r));
1850 service_enter_stop(s, false);
1853 static void service_run_next(Service *s, bool success) {
1857 assert(s->control_command);
1858 assert(s->control_command->command_next);
1863 s->control_command = s->control_command->command_next;
1865 service_unwatch_control_pid(s);
1867 if ((r = service_spawn(s,
1871 !s->permissions_start_only,
1872 !s->root_directory_start_only,
1873 s->control_command_id == SERVICE_EXEC_START_PRE ||
1874 s->control_command_id == SERVICE_EXEC_STOP_POST,
1876 &s->control_pid)) < 0)
1882 log_warning("%s failed to run next task: %s", s->meta.id, strerror(-r));
1884 if (s->state == SERVICE_START_PRE)
1885 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1886 else if (s->state == SERVICE_STOP)
1887 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1888 else if (s->state == SERVICE_STOP_POST)
1889 service_enter_dead(s, false, true);
1891 service_enter_stop(s, false);
1894 static int service_start(Unit *u) {
1895 Service *s = SERVICE(u);
1899 /* We cannot fulfill this request right now, try again later
1901 if (s->state == SERVICE_STOP ||
1902 s->state == SERVICE_STOP_SIGTERM ||
1903 s->state == SERVICE_STOP_SIGKILL ||
1904 s->state == SERVICE_STOP_POST ||
1905 s->state == SERVICE_FINAL_SIGTERM ||
1906 s->state == SERVICE_FINAL_SIGKILL)
1909 /* Already on it! */
1910 if (s->state == SERVICE_START_PRE ||
1911 s->state == SERVICE_START ||
1912 s->state == SERVICE_START_POST)
1915 assert(s->state == SERVICE_DEAD || s->state == SERVICE_MAINTENANCE || s->state == SERVICE_AUTO_RESTART);
1917 /* Make sure we don't enter a busy loop of some kind. */
1918 if (!ratelimit_test(&s->ratelimit)) {
1919 log_warning("%s start request repeated too quickly, refusing to start.", u->meta.id);
1923 if ((s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1924 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1925 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) &&
1927 log_warning("%s can only be started with a per-connection socket.", u->meta.id);
1932 s->main_pid_known = false;
1933 s->allow_restart = true;
1935 service_enter_start_pre(s);
1939 static int service_stop(Unit *u) {
1940 Service *s = SERVICE(u);
1944 /* This is a user request, so don't do restarts on this
1946 s->allow_restart = false;
1949 if (s->state == SERVICE_STOP ||
1950 s->state == SERVICE_STOP_SIGTERM ||
1951 s->state == SERVICE_STOP_SIGKILL ||
1952 s->state == SERVICE_STOP_POST ||
1953 s->state == SERVICE_FINAL_SIGTERM ||
1954 s->state == SERVICE_FINAL_SIGKILL)
1957 /* Don't allow a restart */
1958 if (s->state == SERVICE_AUTO_RESTART) {
1959 service_set_state(s, SERVICE_DEAD);
1963 /* If there's already something running we go directly into
1965 if (s->state == SERVICE_START_PRE ||
1966 s->state == SERVICE_START ||
1967 s->state == SERVICE_START_POST ||
1968 s->state == SERVICE_RELOAD) {
1969 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
1973 assert(s->state == SERVICE_RUNNING ||
1974 s->state == SERVICE_EXITED);
1976 service_enter_stop(s, true);
1980 static int service_reload(Unit *u) {
1981 Service *s = SERVICE(u);
1985 assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
1987 service_enter_reload(s);
1991 static bool service_can_reload(Unit *u) {
1992 Service *s = SERVICE(u);
1996 return !!s->exec_command[SERVICE_EXEC_RELOAD];
1999 static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
2000 Service *s = SERVICE(u);
2006 unit_serialize_item(u, f, "state", service_state_to_string(s->state));
2007 unit_serialize_item(u, f, "failure", yes_no(s->failure));
2009 if (s->control_pid > 0)
2010 unit_serialize_item_format(u, f, "control-pid", "%lu", (unsigned long) s->control_pid);
2012 if (s->main_pid_known && s->main_pid > 0)
2013 unit_serialize_item_format(u, f, "main-pid", "%lu", (unsigned long) s->main_pid);
2015 unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
2018 unit_serialize_item(u, f, "status-text", s->status_text);
2020 /* There's a minor uncleanliness here: if there are multiple
2021 * commands attached here, we will start from the first one
2023 if (s->control_command_id >= 0)
2024 unit_serialize_item(u, f, "control-command", service_exec_command_to_string(s->control_command_id));
2026 if (s->socket_fd >= 0) {
2029 if ((copy = fdset_put_dup(fds, s->socket_fd)) < 0)
2032 unit_serialize_item_format(u, f, "socket-fd", "%i", copy);
2035 if (s->main_exec_status.pid > 0) {
2036 unit_serialize_item_format(u, f, "main-exec-status-pid", "%lu", (unsigned long) s->main_exec_status.pid);
2038 if (s->main_exec_status.start_timestamp.realtime > 0) {
2039 unit_serialize_item_format(u, f, "main-exec-status-start-realtime",
2040 "%llu", (unsigned long long) s->main_exec_status.start_timestamp.realtime);
2042 unit_serialize_item_format(u, f, "main-exec-status-start-monotonic",
2043 "%llu", (unsigned long long) s->main_exec_status.start_timestamp.monotonic);
2046 if (s->main_exec_status.exit_timestamp.realtime > 0) {
2047 unit_serialize_item_format(u, f, "main-exec-status-exit-realtime",
2048 "%llu", (unsigned long long) s->main_exec_status.exit_timestamp.realtime);
2049 unit_serialize_item_format(u, f, "main-exec-status-exit-monotonic",
2050 "%llu", (unsigned long long) s->main_exec_status.exit_timestamp.monotonic);
2052 unit_serialize_item_format(u, f, "main-exec-status-code", "%i", s->main_exec_status.code);
2053 unit_serialize_item_format(u, f, "main-exec-status-status", "%i", s->main_exec_status.status);
2060 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
2061 Service *s = SERVICE(u);
2069 if (streq(key, "state")) {
2072 if ((state = service_state_from_string(value)) < 0)
2073 log_debug("Failed to parse state value %s", value);
2075 s->deserialized_state = state;
2076 } else if (streq(key, "failure")) {
2079 if ((b = parse_boolean(value)) < 0)
2080 log_debug("Failed to parse failure value %s", value);
2082 s->failure = b || s->failure;
2083 } else if (streq(key, "control-pid")) {
2086 if ((r = parse_pid(value, &pid)) < 0)
2087 log_debug("Failed to parse control-pid value %s", value);
2089 s->control_pid = pid;
2090 } else if (streq(key, "main-pid")) {
2093 if ((r = parse_pid(value, &pid)) < 0)
2094 log_debug("Failed to parse main-pid value %s", value);
2096 service_set_main_pid(s, (pid_t) pid);
2097 } else if (streq(key, "main-pid-known")) {
2100 if ((b = parse_boolean(value)) < 0)
2101 log_debug("Failed to parse main-pid-known value %s", value);
2103 s->main_pid_known = b;
2104 } else if (streq(key, "status-text")) {
2107 if ((t = strdup(value))) {
2108 free(s->status_text);
2112 } else if (streq(key, "control-command")) {
2113 ServiceExecCommand id;
2115 if ((id = service_exec_command_from_string(value)) < 0)
2116 log_debug("Failed to parse exec-command value %s", value);
2118 s->control_command_id = id;
2119 s->control_command = s->exec_command[id];
2121 } else if (streq(key, "socket-fd")) {
2124 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2125 log_debug("Failed to parse socket-fd value %s", value);
2128 if (s->socket_fd >= 0)
2129 close_nointr_nofail(s->socket_fd);
2130 s->socket_fd = fdset_remove(fds, fd);
2132 } else if (streq(key, "main-exec-status-pid")) {
2135 if ((r = parse_pid(value, &pid)) < 0)
2136 log_debug("Failed to parse main-exec-status-pid value %s", value);
2138 s->main_exec_status.pid = pid;
2139 } else if (streq(key, "main-exec-status-code")) {
2142 if ((r = safe_atoi(value, &i)) < 0)
2143 log_debug("Failed to parse main-exec-status-code value %s", value);
2145 s->main_exec_status.code = i;
2146 } else if (streq(key, "main-exec-status-status")) {
2149 if ((r = safe_atoi(value, &i)) < 0)
2150 log_debug("Failed to parse main-exec-status-status value %s", value);
2152 s->main_exec_status.status = i;
2153 } else if (streq(key, "main-exec-status-start-realtime")) {
2156 if ((r = safe_atou64(value, &k)) < 0)
2157 log_debug("Failed to parse main-exec-status-start-realtime value %s", value);
2159 s->main_exec_status.start_timestamp.realtime = (usec_t) k;
2160 } else if (streq(key, "main-exec-status-start-monotonic")) {
2163 if ((r = safe_atou64(value, &k)) < 0)
2164 log_debug("Failed to parse main-exec-status-start-monotonic value %s", value);
2166 s->main_exec_status.start_timestamp.monotonic = (usec_t) k;
2167 } else if (streq(key, "main-exec-status-exit-realtime")) {
2170 if ((r = safe_atou64(value, &k)) < 0)
2171 log_debug("Failed to parse main-exec-status-exit-realtime value %s", value);
2173 s->main_exec_status.exit_timestamp.realtime = (usec_t) k;
2174 } else if (streq(key, "main-exec-status-exit-monotonic")) {
2177 if ((r = safe_atou64(value, &k)) < 0)
2178 log_debug("Failed to parse main-exec-status-exit-monotonic value %s", value);
2180 s->main_exec_status.exit_timestamp.monotonic = (usec_t) k;
2182 log_debug("Unknown serialization key '%s'", key);
2187 static UnitActiveState service_active_state(Unit *u) {
2190 return state_translation_table[SERVICE(u)->state];
2193 static const char *service_sub_state_to_string(Unit *u) {
2196 return service_state_to_string(SERVICE(u)->state);
2199 static bool service_check_gc(Unit *u) {
2200 Service *s = SERVICE(u);
2204 return !!s->sysv_path;
2207 static bool service_check_snapshot(Unit *u) {
2208 Service *s = SERVICE(u);
2212 return !s->got_socket_fd;
2215 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2216 Service *s = SERVICE(u);
2222 success = is_clean_exit(code, status);
2224 if (s->main_pid == pid) {
2226 exec_status_exit(&s->main_exec_status, pid, code, status);
2229 if (s->type != SERVICE_FORKING) {
2230 assert(s->exec_command[SERVICE_EXEC_START]);
2231 s->exec_command[SERVICE_EXEC_START]->exec_status = s->main_exec_status;
2233 if (s->exec_command[SERVICE_EXEC_START]->ignore)
2237 log_full(success ? LOG_DEBUG : LOG_NOTICE,
2238 "%s: main process exited, code=%s, status=%i", u->meta.id, sigchld_code_to_string(code), status);
2239 s->failure = s->failure || !success;
2241 /* The service exited, so the service is officially
2246 case SERVICE_START_POST:
2247 case SERVICE_RELOAD:
2249 /* Need to wait until the operation is
2254 if (s->type == SERVICE_FINISH) {
2255 /* This was our main goal, so let's go on */
2257 service_enter_start_post(s);
2259 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2262 assert(s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY);
2267 case SERVICE_RUNNING:
2268 service_enter_running(s, success);
2271 case SERVICE_STOP_SIGTERM:
2272 case SERVICE_STOP_SIGKILL:
2274 if (!control_pid_good(s))
2275 service_enter_stop_post(s, success);
2277 /* If there is still a control process, wait for that first */
2281 assert_not_reached("Uh, main process died at wrong time.");
2284 } else if (s->control_pid == pid) {
2286 if (s->control_command) {
2287 exec_status_exit(&s->control_command->exec_status, pid, code, status);
2289 if (s->control_command->ignore)
2295 log_full(success ? LOG_DEBUG : LOG_NOTICE,
2296 "%s: control process exited, code=%s status=%i", u->meta.id, sigchld_code_to_string(code), status);
2297 s->failure = s->failure || !success;
2299 /* If we are shutting things down anyway we
2300 * don't care about failing commands. */
2302 if (s->control_command && s->control_command->command_next && success) {
2304 /* There is another command to *
2305 * execute, so let's do that. */
2307 log_debug("%s running next command for state %s", u->meta.id, service_state_to_string(s->state));
2308 service_run_next(s, success);
2311 /* No further commands for this step, so let's
2312 * figure out what to do next */
2314 s->control_command = NULL;
2315 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2317 log_debug("%s got final SIGCHLD for state %s", u->meta.id, service_state_to_string(s->state));
2321 case SERVICE_START_PRE:
2323 service_enter_start(s);
2325 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2329 assert(s->type == SERVICE_FORKING);
2331 /* Let's try to load the pid
2332 * file here if we can. We
2333 * ignore the return value,
2334 * since the PID file might
2335 * actually be created by a
2336 * START_POST script */
2340 service_load_pid_file(s);
2342 service_enter_start_post(s);
2344 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2348 case SERVICE_START_POST:
2349 if (success && s->pid_file && !s->main_pid_known) {
2352 /* Hmm, let's see if we can
2353 * load the pid now after the
2354 * start-post scripts got
2357 if ((r = service_load_pid_file(s)) < 0)
2358 log_warning("%s: failed to load PID file %s: %s", s->meta.id, s->pid_file, strerror(-r));
2363 case SERVICE_RELOAD:
2365 service_enter_running(s, true);
2367 service_enter_stop(s, false);
2372 service_enter_signal(s, SERVICE_STOP_SIGTERM, success);
2375 case SERVICE_STOP_SIGTERM:
2376 case SERVICE_STOP_SIGKILL:
2377 if (main_pid_good(s) <= 0)
2378 service_enter_stop_post(s, success);
2380 /* If there is still a service
2381 * process around, wait until
2382 * that one quit, too */
2385 case SERVICE_STOP_POST:
2386 case SERVICE_FINAL_SIGTERM:
2387 case SERVICE_FINAL_SIGKILL:
2388 service_enter_dead(s, success, true);
2392 assert_not_reached("Uh, control process died at wrong time.");
2398 static void service_timer_event(Unit *u, uint64_t elapsed, Watch* w) {
2399 Service *s = SERVICE(u);
2402 assert(elapsed == 1);
2404 assert(w == &s->timer_watch);
2408 case SERVICE_START_PRE:
2410 log_warning("%s operation timed out. Terminating.", u->meta.id);
2411 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2414 case SERVICE_START_POST:
2415 case SERVICE_RELOAD:
2416 log_warning("%s operation timed out. Stopping.", u->meta.id);
2417 service_enter_stop(s, false);
2421 log_warning("%s stopping timed out. Terminating.", u->meta.id);
2422 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
2425 case SERVICE_STOP_SIGTERM:
2426 log_warning("%s stopping timed out. Killing.", u->meta.id);
2427 service_enter_signal(s, SERVICE_STOP_SIGKILL, false);
2430 case SERVICE_STOP_SIGKILL:
2431 /* Uh, wie sent a SIGKILL and it is still not gone?
2432 * Must be something we cannot kill, so let's just be
2433 * weirded out and continue */
2435 log_warning("%s still around after SIGKILL. Ignoring.", u->meta.id);
2436 service_enter_stop_post(s, false);
2439 case SERVICE_STOP_POST:
2440 log_warning("%s stopping timed out (2). Terminating.", u->meta.id);
2441 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2444 case SERVICE_FINAL_SIGTERM:
2445 log_warning("%s stopping timed out (2). Killing.", u->meta.id);
2446 service_enter_signal(s, SERVICE_FINAL_SIGKILL, false);
2449 case SERVICE_FINAL_SIGKILL:
2450 log_warning("%s still around after SIGKILL (2). Entering maintenance mode.", u->meta.id);
2451 service_enter_dead(s, false, true);
2454 case SERVICE_AUTO_RESTART:
2455 log_info("%s holdoff time over, scheduling restart.", u->meta.id);
2456 service_enter_restart(s);
2460 assert_not_reached("Timeout at wrong time.");
2464 static void service_cgroup_notify_event(Unit *u) {
2465 Service *s = SERVICE(u);
2469 log_debug("%s: cgroup is empty", u->meta.id);
2473 /* Waiting for SIGCHLD is usually more interesting,
2474 * because it includes return codes/signals. Which is
2475 * why we ignore the cgroup events for most cases,
2476 * except when we don't know pid which to expect the
2479 case SERVICE_RUNNING:
2480 service_enter_running(s, true);
2488 static void service_notify_message(Unit *u, pid_t pid, char **tags) {
2489 Service *s = SERVICE(u);
2494 if (s->notify_access == NOTIFY_NONE) {
2495 log_warning("%s: Got notification message from PID %lu, but reception is disabled.",
2496 u->meta.id, (unsigned long) pid);
2500 if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
2501 log_warning("%s: Got notification message from PID %lu, but reception only permitted for PID %lu",
2502 u->meta.id, (unsigned long) pid, (unsigned long) s->main_pid);
2506 log_debug("%s: Got message", u->meta.id);
2508 /* Interpret MAINPID= */
2509 if ((e = strv_find_prefix(tags, "MAINPID=")) &&
2510 (s->state == SERVICE_START ||
2511 s->state == SERVICE_START_POST ||
2512 s->state == SERVICE_RUNNING ||
2513 s->state == SERVICE_RELOAD)) {
2515 if (parse_pid(e + 8, &pid) < 0)
2516 log_warning("Failed to parse notification message %s", e);
2518 log_debug("%s: got %s", u->meta.id, e);
2519 service_set_main_pid(s, pid);
2523 /* Interpret READY= */
2524 if (s->type == SERVICE_NOTIFY &&
2525 s->state == SERVICE_START &&
2526 strv_find(tags, "READY=1")) {
2527 log_debug("%s: got READY=1", u->meta.id);
2529 service_enter_start_post(s);
2532 /* Interpret STATUS= */
2533 if ((e = strv_find_prefix(tags, "STATUS="))) {
2537 if (!(t = strdup(e+7))) {
2538 log_error("Failed to allocate string.");
2542 log_debug("%s: got %s", u->meta.id, e);
2544 free(s->status_text);
2547 free(s->status_text);
2548 s->status_text = NULL;
2554 static int service_enumerate(Manager *m) {
2558 char *path = NULL, *fpath = NULL, *name = NULL;
2563 STRV_FOREACH(p, m->lookup_paths.sysvrcnd_path)
2564 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++) {
2569 if (asprintf(&path, "%s/%s", *p, rcnd_table[i].path) < 0) {
2577 if (!(d = opendir(path))) {
2578 if (errno != ENOENT)
2579 log_warning("opendir() failed on %s: %s", path, strerror(errno));
2584 while ((de = readdir(d))) {
2588 if (ignore_file(de->d_name))
2591 if (de->d_name[0] != 'S' && de->d_name[0] != 'K')
2594 if (strlen(de->d_name) < 4)
2597 a = undecchar(de->d_name[1]);
2598 b = undecchar(de->d_name[2]);
2605 if (asprintf(&fpath, "%s/%s/%s", *p, rcnd_table[i].path, de->d_name) < 0) {
2610 if (access(fpath, X_OK) < 0) {
2612 if (errno != ENOENT)
2613 log_warning("access() failed on %s: %s", fpath, strerror(errno));
2619 if (!(name = sysv_translate_name(de->d_name + 3))) {
2624 if ((r = manager_load_unit_prepare(m, name, NULL, NULL, &service)) < 0) {
2625 log_warning("Failed to prepare unit %s: %s", name, strerror(-r));
2629 if (de->d_name[0] == 'S' &&
2630 (rcnd_table[i].type == RUNLEVEL_UP || rcnd_table[i].type == RUNLEVEL_SYSINIT))
2631 SERVICE(service)->sysv_start_priority =
2632 MAX(a*10 + b, SERVICE(service)->sysv_start_priority);
2634 manager_dispatch_load_queue(m);
2635 service = unit_follow_merge(service);
2637 /* If this is a native service, rely
2638 * on native ways to pull in a
2639 * service, don't pull it in via sysv
2641 if (service->meta.fragment_path)
2644 if (de->d_name[0] == 'S') {
2646 if ((r = unit_add_two_dependencies_by_name_inverse(service, UNIT_AFTER, UNIT_WANTS, rcnd_table[i].target, NULL, true)) < 0)
2649 } else if (de->d_name[0] == 'K' &&
2650 (rcnd_table[i].type == RUNLEVEL_DOWN ||
2651 rcnd_table[i].type == RUNLEVEL_SYSINIT)) {
2653 /* We honour K links only for
2654 * halt/reboot. For the normal
2655 * runlevels we assume the
2657 * implicitly added by the
2658 * core logic. Also, we don't
2659 * really distuingish here
2660 * between the runlevels 0 and
2661 * 6 and just add them to the
2662 * special shutdown target. On
2663 * SUSE the boot.d/ runlevel
2664 * is also used for shutdown,
2665 * so we add links for that
2666 * too to the shutdown
2669 if ((r = unit_add_two_dependencies_by_name_inverse(service, UNIT_AFTER, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true)) < 0)
2688 static void service_bus_name_owner_change(
2691 const char *old_owner,
2692 const char *new_owner) {
2694 Service *s = SERVICE(u);
2699 assert(streq(s->bus_name, name));
2700 assert(old_owner || new_owner);
2702 if (old_owner && new_owner)
2703 log_debug("%s's D-Bus name %s changed owner from %s to %s", u->meta.id, name, old_owner, new_owner);
2705 log_debug("%s's D-Bus name %s no longer registered by %s", u->meta.id, name, old_owner);
2707 log_debug("%s's D-Bus name %s now registered by %s", u->meta.id, name, new_owner);
2709 s->bus_name_good = !!new_owner;
2711 if (s->type == SERVICE_DBUS) {
2713 /* service_enter_running() will figure out what to
2715 if (s->state == SERVICE_RUNNING)
2716 service_enter_running(s, true);
2717 else if (s->state == SERVICE_START && new_owner)
2718 service_enter_start_post(s);
2720 } else if (new_owner &&
2722 (s->state == SERVICE_START ||
2723 s->state == SERVICE_START_POST ||
2724 s->state == SERVICE_RUNNING ||
2725 s->state == SERVICE_RELOAD)) {
2727 /* Try to acquire PID from bus service */
2728 log_debug("Trying to acquire PID from D-Bus name...");
2730 bus_query_pid(u->meta.manager, name);
2734 static void service_bus_query_pid_done(
2739 Service *s = SERVICE(u);
2744 log_debug("%s's D-Bus name %s is now owned by process %u", u->meta.id, name, (unsigned) pid);
2746 if (s->main_pid <= 0 &&
2747 (s->state == SERVICE_START ||
2748 s->state == SERVICE_START_POST ||
2749 s->state == SERVICE_RUNNING ||
2750 s->state == SERVICE_RELOAD))
2751 service_set_main_pid(s, pid);
2754 int service_set_socket_fd(Service *s, int fd, Socket *sock) {
2758 /* This is called by the socket code when instantiating a new
2759 * service for a stream socket and the socket needs to be
2762 if (s->meta.load_state != UNIT_LOADED)
2765 if (s->socket_fd >= 0)
2768 if (s->state != SERVICE_DEAD)
2772 s->got_socket_fd = true;
2778 static void service_reset_maintenance(Unit *u) {
2779 Service *s = SERVICE(u);
2783 if (s->state == SERVICE_MAINTENANCE)
2784 service_set_state(s, SERVICE_DEAD);
2789 static const char* const service_state_table[_SERVICE_STATE_MAX] = {
2790 [SERVICE_DEAD] = "dead",
2791 [SERVICE_START_PRE] = "start-pre",
2792 [SERVICE_START] = "start",
2793 [SERVICE_START_POST] = "start-post",
2794 [SERVICE_RUNNING] = "running",
2795 [SERVICE_EXITED] = "exited",
2796 [SERVICE_RELOAD] = "reload",
2797 [SERVICE_STOP] = "stop",
2798 [SERVICE_STOP_SIGTERM] = "stop-sigterm",
2799 [SERVICE_STOP_SIGKILL] = "stop-sigkill",
2800 [SERVICE_STOP_POST] = "stop-post",
2801 [SERVICE_FINAL_SIGTERM] = "final-sigterm",
2802 [SERVICE_FINAL_SIGKILL] = "final-sigkill",
2803 [SERVICE_MAINTENANCE] = "maintenance",
2804 [SERVICE_AUTO_RESTART] = "auto-restart",
2807 DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
2809 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
2810 [SERVICE_ONCE] = "once",
2811 [SERVICE_RESTART_ON_SUCCESS] = "restart-on-success",
2812 [SERVICE_RESTART_ALWAYS] = "restart-always",
2815 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
2817 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
2818 [SERVICE_SIMPLE] = "simple",
2819 [SERVICE_FORKING] = "forking",
2820 [SERVICE_FINISH] = "finish",
2821 [SERVICE_DBUS] = "dbus",
2822 [SERVICE_NOTIFY] = "notify"
2825 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
2827 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
2828 [SERVICE_EXEC_START_PRE] = "ExecStartPre",
2829 [SERVICE_EXEC_START] = "ExecStart",
2830 [SERVICE_EXEC_START_POST] = "ExecStartPost",
2831 [SERVICE_EXEC_RELOAD] = "ExecReload",
2832 [SERVICE_EXEC_STOP] = "ExecStop",
2833 [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
2836 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
2838 static const char* const notify_access_table[_NOTIFY_ACCESS_MAX] = {
2839 [NOTIFY_NONE] = "none",
2840 [NOTIFY_MAIN] = "main",
2841 [NOTIFY_ALL] = "all"
2844 DEFINE_STRING_TABLE_LOOKUP(notify_access, NotifyAccess);
2846 const UnitVTable service_vtable = {
2847 .suffix = ".service",
2848 .show_status = true,
2850 .init = service_init,
2851 .done = service_done,
2852 .load = service_load,
2854 .coldplug = service_coldplug,
2856 .dump = service_dump,
2858 .start = service_start,
2859 .stop = service_stop,
2860 .reload = service_reload,
2862 .can_reload = service_can_reload,
2864 .serialize = service_serialize,
2865 .deserialize_item = service_deserialize_item,
2867 .active_state = service_active_state,
2868 .sub_state_to_string = service_sub_state_to_string,
2870 .check_gc = service_check_gc,
2871 .check_snapshot = service_check_snapshot,
2873 .sigchld_event = service_sigchld_event,
2874 .timer_event = service_timer_event,
2876 .reset_maintenance = service_reset_maintenance,
2878 .cgroup_notify_empty = service_cgroup_notify_event,
2879 .notify_message = service_notify_message,
2881 .bus_name_owner_change = service_bus_name_owner_change,
2882 .bus_query_pid_done = service_bus_query_pid_done,
2884 .bus_message_handler = bus_service_message_handler,
2886 .enumerate = service_enumerate