1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
29 #include "load-fragment.h"
30 #include "load-dropin.h"
33 #include "unit-name.h"
34 #include "dbus-service.h"
36 #include "bus-errors.h"
38 #define COMMENTS "#;\n"
39 #define NEWLINES "\n\r"
41 typedef enum RunlevelType {
50 const RunlevelType type;
52 /* Standard SysV runlevels */
53 { "rc0.d", SPECIAL_POWEROFF_TARGET, RUNLEVEL_DOWN },
54 { "rc1.d", SPECIAL_RESCUE_TARGET, RUNLEVEL_UP },
55 { "rc2.d", SPECIAL_RUNLEVEL2_TARGET, RUNLEVEL_UP },
56 { "rc3.d", SPECIAL_RUNLEVEL3_TARGET, RUNLEVEL_UP },
57 { "rc4.d", SPECIAL_RUNLEVEL4_TARGET, RUNLEVEL_UP },
58 { "rc5.d", SPECIAL_RUNLEVEL5_TARGET, RUNLEVEL_UP },
59 { "rc6.d", SPECIAL_REBOOT_TARGET, RUNLEVEL_DOWN },
61 /* SUSE style boot.d */
62 { "boot.d", SPECIAL_SYSINIT_TARGET, RUNLEVEL_SYSINIT },
64 /* Debian style rcS.d */
65 { "rcS.d", SPECIAL_SYSINIT_TARGET, RUNLEVEL_SYSINIT },
68 #define RUNLEVELS_UP "12345"
69 /* #define RUNLEVELS_DOWN "06" */
70 /* #define RUNLEVELS_BOOT "bBsS" */
72 static const UnitActiveState state_translation_table[_SERVICE_STATE_MAX] = {
73 [SERVICE_DEAD] = UNIT_INACTIVE,
74 [SERVICE_START_PRE] = UNIT_ACTIVATING,
75 [SERVICE_START] = UNIT_ACTIVATING,
76 [SERVICE_START_POST] = UNIT_ACTIVATING,
77 [SERVICE_RUNNING] = UNIT_ACTIVE,
78 [SERVICE_EXITED] = UNIT_ACTIVE,
79 [SERVICE_RELOAD] = UNIT_RELOADING,
80 [SERVICE_STOP] = UNIT_DEACTIVATING,
81 [SERVICE_STOP_SIGTERM] = UNIT_DEACTIVATING,
82 [SERVICE_STOP_SIGKILL] = UNIT_DEACTIVATING,
83 [SERVICE_STOP_POST] = UNIT_DEACTIVATING,
84 [SERVICE_FINAL_SIGTERM] = UNIT_DEACTIVATING,
85 [SERVICE_FINAL_SIGKILL] = UNIT_DEACTIVATING,
86 [SERVICE_MAINTENANCE] = UNIT_MAINTENANCE,
87 [SERVICE_AUTO_RESTART] = UNIT_ACTIVATING
90 static void service_init(Unit *u) {
91 Service *s = SERVICE(u);
94 assert(u->meta.load_state == UNIT_STUB);
96 s->timeout_usec = DEFAULT_TIMEOUT_USEC;
97 s->restart_usec = DEFAULT_RESTART_USEC;
98 s->timer_watch.type = WATCH_INVALID;
99 s->sysv_start_priority = -1;
102 exec_context_init(&s->exec_context);
104 RATELIMIT_INIT(s->ratelimit, 10*USEC_PER_SEC, 5);
106 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
109 static void service_unwatch_control_pid(Service *s) {
112 if (s->control_pid <= 0)
115 unit_unwatch_pid(UNIT(s), s->control_pid);
119 static void service_unwatch_main_pid(Service *s) {
122 if (s->main_pid <= 0)
125 unit_unwatch_pid(UNIT(s), s->main_pid);
129 static int service_set_main_pid(Service *s, pid_t pid) {
140 if (get_parent_of_pid(pid, &ppid) >= 0 && ppid != getpid())
141 log_warning("%s: Supervising process %lu which is not our child. We'll most likely not notice when it exits.",
142 s->meta.id, (unsigned long) pid);
145 s->main_pid_known = true;
147 exec_status_start(&s->main_exec_status, pid);
152 static void service_close_socket_fd(Service *s) {
155 if (s->socket_fd < 0)
158 close_nointr_nofail(s->socket_fd);
162 static void service_connection_unref(Service *s) {
168 socket_connection_unref(s->socket);
172 static void service_done(Unit *u) {
173 Service *s = SERVICE(u);
183 free(s->sysv_runlevels);
184 s->sysv_runlevels = NULL;
186 free(s->status_text);
187 s->status_text = NULL;
189 exec_context_done(&s->exec_context);
190 exec_command_free_array(s->exec_command, _SERVICE_EXEC_COMMAND_MAX);
191 s->control_command = NULL;
193 /* This will leak a process, but at least no memory or any of
195 service_unwatch_main_pid(s);
196 service_unwatch_control_pid(s);
199 unit_unwatch_bus_name(UNIT(u), s->bus_name);
204 service_close_socket_fd(s);
205 service_connection_unref(s);
207 unit_unwatch_timer(u, &s->timer_watch);
210 static char *sysv_translate_name(const char *name) {
213 if (!(r = new(char, strlen(name) + sizeof(".service"))))
216 if (startswith(name, "boot."))
217 /* Drop SuSE-style boot. prefix */
218 strcpy(stpcpy(r, name + 5), ".service");
219 else if (endswith(name, ".sh"))
220 /* Drop Debian-style .sh suffix */
221 strcpy(stpcpy(r, name) - 3, ".service");
223 /* Normal init scripts */
224 strcpy(stpcpy(r, name), ".service");
229 static int sysv_translate_facility(const char *name, char **_r) {
231 static const char * const table[] = {
232 /* LSB defined facilities */
233 "$local_fs", SPECIAL_LOCAL_FS_TARGET,
234 "$network", SPECIAL_NETWORK_TARGET,
235 "$named", SPECIAL_NSS_LOOKUP_TARGET,
236 "$portmap", SPECIAL_RPCBIND_TARGET,
237 "$remote_fs", SPECIAL_REMOTE_FS_TARGET,
238 "$syslog", SPECIAL_SYSLOG_TARGET,
239 "$time", SPECIAL_RTC_SET_TARGET,
241 /* Debian extensions */
242 "$mail-transport-agent", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
243 "$mail-transfer-agent", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
244 "$x-display-manager", SPECIAL_DISPLAY_MANAGER_SERVICE
250 for (i = 0; i < ELEMENTSOF(table); i += 2)
251 if (streq(table[i], name)) {
252 if (!(r = strdup(table[i+1])))
261 if (!(r = sysv_translate_name(name)))
272 static int sysv_fix_order(Service *s) {
278 if (s->sysv_start_priority < 0)
281 /* For each pair of services where at least one lacks a LSB
282 * header, we use the start priority value to order things. */
284 LIST_FOREACH(units_per_type, other, s->meta.manager->units_per_type[UNIT_SERVICE]) {
288 t = (Service*) other;
293 if (t->sysv_start_priority < 0)
296 /* If both units have modern headers we don't care
297 * about the priorities */
298 if ((!s->sysv_path || s->sysv_has_lsb) &&
299 (!t->sysv_path || t->sysv_has_lsb))
302 if (t->sysv_start_priority < s->sysv_start_priority)
304 else if (t->sysv_start_priority > s->sysv_start_priority)
309 /* FIXME: Maybe we should compare the name here lexicographically? */
311 if (!(r = unit_add_dependency(UNIT(s), d, UNIT(t), true)) < 0)
318 static ExecCommand *exec_command_new(const char *path, const char *arg1) {
321 if (!(c = new0(ExecCommand, 1)))
324 if (!(c->path = strdup(path))) {
329 if (!(c->argv = strv_new(path, arg1, NULL))) {
338 static int sysv_exec_commands(Service *s) {
342 assert(s->sysv_path);
344 if (!(c = exec_command_new(s->sysv_path, "start")))
346 exec_command_append_list(s->exec_command+SERVICE_EXEC_START, c);
348 if (!(c = exec_command_new(s->sysv_path, "stop")))
350 exec_command_append_list(s->exec_command+SERVICE_EXEC_STOP, c);
352 if (!(c = exec_command_new(s->sysv_path, "reload")))
354 exec_command_append_list(s->exec_command+SERVICE_EXEC_RELOAD, c);
359 static int service_load_sysv_path(Service *s, const char *path) {
376 if (!(f = fopen(path, "re"))) {
377 r = errno == ENOENT ? 0 : -errno;
382 if (!(s->sysv_path = strdup(path))) {
388 char l[LINE_MAX], *t;
390 if (!fgets(l, sizeof(l), f)) {
395 log_error("Failed to read configuration file '%s': %s", path, strerror(-r));
405 if (state == NORMAL && streq(t, "### BEGIN INIT INFO")) {
407 s->sysv_has_lsb = true;
411 if ((state == LSB_DESCRIPTION || state == LSB) && streq(t, "### END INIT INFO")) {
417 t += strspn(t, WHITESPACE);
419 if (state == NORMAL) {
421 /* Try to parse Red Hat style chkconfig headers */
423 if (startswith_no_case(t, "chkconfig:")) {
425 char runlevels[16], *k;
429 if (sscanf(t+10, "%15s %i %*i",
431 &start_priority) != 2) {
433 log_warning("[%s:%u] Failed to parse chkconfig line. Ignoring.", path, line);
437 /* A start priority gathered from the
438 * symlink farms is preferred over the
439 * data from the LSB header. */
440 if (start_priority < 0 || start_priority > 99)
441 log_warning("[%s:%u] Start priority out of range. Ignoring.", path, line);
442 else if (s->sysv_start_priority < 0)
443 s->sysv_start_priority = start_priority;
445 char_array_0(runlevels);
446 k = delete_chars(runlevels, WHITESPACE "-");
451 if (!(d = strdup(k))) {
456 free(s->sysv_runlevels);
457 s->sysv_runlevels = d;
460 } else if (startswith_no_case(t, "description:") &&
461 !u->meta.description) {
463 size_t k = strlen(t);
466 if (t[k-1] == '\\') {
471 if (!(d = strdup(strstrip(t+12)))) {
476 free(u->meta.description);
477 u->meta.description = d;
479 } else if (startswith_no_case(t, "pidfile:")) {
486 if (!path_is_absolute(fn)) {
487 log_warning("[%s:%u] PID file not absolute. Ignoring.", path, line);
491 if (!(fn = strdup(fn))) {
500 } else if (state == DESCRIPTION) {
502 /* Try to parse Red Hat style description
505 size_t k = strlen(t);
513 assert(u->meta.description);
514 if (asprintf(&d, "%s %s", u->meta.description, strstrip(t)) < 0) {
519 free(u->meta.description);
520 u->meta.description = d;
522 } else if (state == LSB || state == LSB_DESCRIPTION) {
524 if (startswith_no_case(t, "Provides:")) {
530 FOREACH_WORD_QUOTED(w, z, t+9, i) {
533 if (!(n = strndup(w, z))) {
538 r = sysv_translate_facility(n, &m);
547 if (unit_name_to_type(m) == UNIT_SERVICE)
548 r = unit_add_name(u, m);
550 r = unit_add_two_dependencies_by_name_inverse(u, UNIT_AFTER, UNIT_REQUIRES, m, NULL, true);
558 } else if (startswith_no_case(t, "Required-Start:") ||
559 startswith_no_case(t, "Should-Start:") ||
560 startswith_no_case(t, "X-Start-Before:") ||
561 startswith_no_case(t, "X-Start-After:")) {
567 FOREACH_WORD_QUOTED(w, z, strchr(t, ':')+1, i) {
570 if (!(n = strndup(w, z))) {
575 r = sysv_translate_facility(n, &m);
584 r = unit_add_dependency_by_name(u, startswith_no_case(t, "X-Start-Before:") ? UNIT_BEFORE : UNIT_AFTER, m, NULL, true);
590 } else if (startswith_no_case(t, "Default-Start:")) {
595 k = delete_chars(t+14, WHITESPACE "-");
598 if (!(d = strdup(k))) {
603 free(s->sysv_runlevels);
604 s->sysv_runlevels = d;
607 } else if (startswith_no_case(t, "Description:") &&
608 !u->meta.description) {
611 /* We use the long description only if
612 * no short description is set. */
614 state = LSB_DESCRIPTION;
616 if (!(d = strdup(strstrip(t+12)))) {
621 free(u->meta.description);
622 u->meta.description = d;
624 } else if (startswith_no_case(t, "Short-Description:")) {
629 if (!(d = strdup(strstrip(t+18)))) {
634 u->meta.description = d;
636 } else if (startswith_no_case(t, "X-Interactive:")) {
639 if ((b = parse_boolean(strstrip(t+14))) < 0) {
640 log_warning("[%s:%u] Couldn't parse interactive flag. Ignoring.", path, line);
645 s->exec_context.std_input = EXEC_INPUT_TTY;
647 s->exec_context.std_input = EXEC_INPUT_NULL;
649 } else if (state == LSB_DESCRIPTION) {
651 if (startswith(l, "#\t") || startswith(l, "# ")) {
654 assert(u->meta.description);
655 if (asprintf(&d, "%s %s", u->meta.description, t) < 0) {
660 free(u->meta.description);
661 u->meta.description = d;
668 if ((r = sysv_exec_commands(s)) < 0)
671 if (s->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, s->sysv_runlevels)) {
672 /* If there a runlevels configured for this service
673 * but none of the standard ones, then we assume this
674 * is some special kind of service (which might be
675 * needed for early boot) and don't create any links
678 s->meta.default_dependencies = false;
680 /* Don't timeout special services during boot (like fsck) */
684 /* Special setting for all SysV services */
685 s->type = SERVICE_FORKING;
686 s->valid_no_process = true;
687 s->kill_mode = KILL_PROCESS_GROUP;
688 s->restart = SERVICE_ONCE;
689 s->exec_context.std_output = EXEC_OUTPUT_TTY;
691 u->meta.load_state = UNIT_LOADED;
702 static int service_load_sysv_name(Service *s, const char *name) {
708 /* For SysV services we strip the boot. or .sh
709 * prefixes/suffixes. */
710 if (startswith(name, "boot.") ||
711 endswith(name, ".sh.service"))
714 STRV_FOREACH(p, s->meta.manager->lookup_paths.sysvinit_path) {
718 if (asprintf(&path, "%s/%s", *p, name) < 0)
721 assert(endswith(path, ".service"));
722 path[strlen(path)-8] = 0;
724 r = service_load_sysv_path(s, path);
726 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
727 /* Try Debian style xxx.sh source'able init scripts */
729 r = service_load_sysv_path(s, path);
734 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
735 /* Try SUSE style boot.xxx init scripts */
737 if (asprintf(&path, "%s/boot.%s", *p, name) < 0)
740 path[strlen(path)-8] = 0;
741 r = service_load_sysv_path(s, path);
748 if ((s->meta.load_state != UNIT_STUB))
755 static int service_load_sysv(Service *s) {
762 /* Load service data from SysV init scripts, preferably with
765 if (strv_isempty(s->meta.manager->lookup_paths.sysvinit_path))
768 if ((t = s->meta.id))
769 if ((r = service_load_sysv_name(s, t)) < 0)
772 if (s->meta.load_state == UNIT_STUB)
773 SET_FOREACH(t, s->meta.names, i) {
777 if ((r == service_load_sysv_name(s, t)) < 0)
780 if (s->meta.load_state != UNIT_STUB)
787 static int service_add_bus_name(Service *s) {
794 if (asprintf(&n, "dbus-%s.service", s->bus_name) < 0)
797 r = unit_merge_by_name(UNIT(s), n);
803 static int service_verify(Service *s) {
806 if (s->meta.load_state != UNIT_LOADED)
809 if (!s->exec_command[SERVICE_EXEC_START]) {
810 log_error("%s lacks ExecStart setting. Refusing.", s->meta.id);
814 if (s->exec_command[SERVICE_EXEC_START]->command_next) {
815 log_error("%s has more than one ExecStart setting. Refusing.", s->meta.id);
819 if (s->type == SERVICE_DBUS && !s->bus_name) {
820 log_error("%s is of type D-Bus but no D-Bus service name has been specified. Refusing.", s->meta.id);
824 if (s->exec_context.pam_name && s->kill_mode != KILL_CONTROL_GROUP) {
825 log_error("%s has PAM enabled. Kill mode must be set to 'control-group'. Refusing.", s->meta.id);
832 static int service_add_default_dependencies(Service *s) {
837 /* Add a number of automatic dependencies useful for the
838 * majority of services. */
840 /* First, pull in base system */
841 if (s->meta.manager->running_as == MANAGER_SYSTEM) {
843 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_BASIC_TARGET, NULL, true)) < 0)
846 } else if (s->meta.manager->running_as == MANAGER_SESSION) {
848 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SOCKETS_TARGET, NULL, true)) < 0)
852 /* Second, activate normal shutdown */
853 return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true);
856 static int service_load(Unit *u) {
858 Service *s = SERVICE(u);
862 /* Load a .service file */
863 if ((r = unit_load_fragment(u)) < 0)
866 /* Load a classic init script as a fallback, if we couldn't find anything */
867 if (u->meta.load_state == UNIT_STUB)
868 if ((r = service_load_sysv(s)) < 0)
871 /* Still nothing found? Then let's give up */
872 if (u->meta.load_state == UNIT_STUB)
875 /* We were able to load something, then let's add in the
876 * dropin directories. */
877 if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
880 /* This is a new unit? Then let's add in some extras */
881 if (u->meta.load_state == UNIT_LOADED) {
882 if ((r = unit_add_exec_dependencies(u, &s->exec_context)) < 0)
885 if ((r = unit_add_default_cgroup(u)) < 0)
888 if ((r = sysv_fix_order(s)) < 0)
892 if ((r = service_add_bus_name(s)) < 0)
895 if ((r = unit_watch_bus_name(u, s->bus_name)) < 0)
899 if (s->type == SERVICE_NOTIFY && s->notify_access == NOTIFY_NONE)
900 s->notify_access = NOTIFY_MAIN;
902 if (s->type == SERVICE_DBUS || s->bus_name)
903 if ((r = unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_REQUIRES, SPECIAL_DBUS_TARGET, NULL, true)) < 0)
906 if (s->meta.default_dependencies)
907 if ((r = service_add_default_dependencies(s)) < 0)
911 return service_verify(s);
914 static void service_dump(Unit *u, FILE *f, const char *prefix) {
916 ServiceExecCommand c;
917 Service *s = SERVICE(u);
923 p2 = strappend(prefix, "\t");
924 prefix2 = p2 ? p2 : prefix;
927 "%sService State: %s\n"
928 "%sPermissionsStartOnly: %s\n"
929 "%sRootDirectoryStartOnly: %s\n"
930 "%sValidNoProcess: %s\n"
933 "%sNotifyAccess: %s\n",
934 prefix, service_state_to_string(s->state),
935 prefix, yes_no(s->permissions_start_only),
936 prefix, yes_no(s->root_directory_start_only),
937 prefix, yes_no(s->valid_no_process),
938 prefix, kill_mode_to_string(s->kill_mode),
939 prefix, service_type_to_string(s->type),
940 prefix, notify_access_to_string(s->notify_access));
942 if (s->control_pid > 0)
944 "%sControl PID: %lu\n",
945 prefix, (unsigned long) s->control_pid);
950 prefix, (unsigned long) s->main_pid);
955 prefix, s->pid_file);
960 "%sBus Name Good: %s\n",
962 prefix, yes_no(s->bus_name_good));
964 exec_context_dump(&s->exec_context, f, prefix);
966 for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
968 if (!s->exec_command[c])
971 fprintf(f, "%s-> %s:\n",
972 prefix, service_exec_command_to_string(c));
974 exec_command_dump_list(s->exec_command[c], f, prefix2);
979 "%sSysV Init Script Path: %s\n"
980 "%sSysV Init Script has LSB Header: %s\n",
981 prefix, s->sysv_path,
982 prefix, yes_no(s->sysv_has_lsb));
984 if (s->sysv_start_priority >= 0)
986 "%sSysVStartPriority: %i\n",
987 prefix, s->sysv_start_priority);
989 if (s->sysv_runlevels)
990 fprintf(f, "%sSysVRunLevels: %s\n",
991 prefix, s->sysv_runlevels);
994 fprintf(f, "%sStatus Text: %s\n",
995 prefix, s->status_text);
1000 static int service_load_pid_file(Service *s) {
1007 if (s->main_pid_known)
1010 assert(s->main_pid <= 0);
1015 if ((r = read_one_line_file(s->pid_file, &k)) < 0)
1018 r = parse_pid(k, &pid);
1024 if (kill(pid, 0) < 0 && errno != EPERM) {
1025 log_warning("PID %lu read from file %s does not exist. Your service or init script might be broken.",
1026 (unsigned long) pid, s->pid_file);
1030 if ((r = service_set_main_pid(s, pid)) < 0)
1033 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1034 /* FIXME: we need to do something here */
1040 static int service_get_sockets(Service *s, Set **_set) {
1049 if (s->socket_fd >= 0)
1052 /* Collects all Socket objects that belong to this
1053 * service. Note that a service might have multiple sockets
1054 * via multiple names. */
1056 if (!(set = set_new(NULL, NULL)))
1059 SET_FOREACH(t, s->meta.names, i) {
1063 /* Look for all socket objects that go by any of our
1064 * units and collect their fds */
1066 if (!(k = unit_name_change_suffix(t, ".socket"))) {
1071 p = manager_get_unit(s->meta.manager, k);
1077 if ((r = set_put(set, p)) < 0)
1089 static int service_notify_sockets_dead(Service *s) {
1097 if (s->socket_fd >= 0)
1100 /* Notifies all our sockets when we die */
1101 if ((r = service_get_sockets(s, &set)) < 0)
1104 SET_FOREACH(sock, set, i)
1105 socket_notify_service_dead(sock);
1112 static void service_set_state(Service *s, ServiceState state) {
1113 ServiceState old_state;
1116 old_state = s->state;
1119 if (state != SERVICE_START_PRE &&
1120 state != SERVICE_START &&
1121 state != SERVICE_START_POST &&
1122 state != SERVICE_RELOAD &&
1123 state != SERVICE_STOP &&
1124 state != SERVICE_STOP_SIGTERM &&
1125 state != SERVICE_STOP_SIGKILL &&
1126 state != SERVICE_STOP_POST &&
1127 state != SERVICE_FINAL_SIGTERM &&
1128 state != SERVICE_FINAL_SIGKILL &&
1129 state != SERVICE_AUTO_RESTART)
1130 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1132 if (state != SERVICE_START &&
1133 state != SERVICE_START_POST &&
1134 state != SERVICE_RUNNING &&
1135 state != SERVICE_RELOAD &&
1136 state != SERVICE_STOP &&
1137 state != SERVICE_STOP_SIGTERM &&
1138 state != SERVICE_STOP_SIGKILL)
1139 service_unwatch_main_pid(s);
1141 if (state != SERVICE_START_PRE &&
1142 state != SERVICE_START &&
1143 state != SERVICE_START_POST &&
1144 state != SERVICE_RELOAD &&
1145 state != SERVICE_STOP &&
1146 state != SERVICE_STOP_SIGTERM &&
1147 state != SERVICE_STOP_SIGKILL &&
1148 state != SERVICE_STOP_POST &&
1149 state != SERVICE_FINAL_SIGTERM &&
1150 state != SERVICE_FINAL_SIGKILL) {
1151 service_unwatch_control_pid(s);
1152 s->control_command = NULL;
1153 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1156 if (state == SERVICE_DEAD ||
1157 state == SERVICE_STOP ||
1158 state == SERVICE_STOP_SIGTERM ||
1159 state == SERVICE_STOP_SIGKILL ||
1160 state == SERVICE_STOP_POST ||
1161 state == SERVICE_FINAL_SIGTERM ||
1162 state == SERVICE_FINAL_SIGKILL ||
1163 state == SERVICE_MAINTENANCE ||
1164 state == SERVICE_AUTO_RESTART)
1165 service_notify_sockets_dead(s);
1167 if (state != SERVICE_START_PRE &&
1168 state != SERVICE_START &&
1169 state != SERVICE_START_POST &&
1170 state != SERVICE_RUNNING &&
1171 state != SERVICE_RELOAD &&
1172 state != SERVICE_STOP &&
1173 state != SERVICE_STOP_SIGTERM &&
1174 state != SERVICE_STOP_SIGKILL &&
1175 state != SERVICE_STOP_POST &&
1176 state != SERVICE_FINAL_SIGTERM &&
1177 state != SERVICE_FINAL_SIGKILL &&
1178 !(state == SERVICE_DEAD && s->meta.job)) {
1179 service_close_socket_fd(s);
1180 service_connection_unref(s);
1183 if (old_state != state)
1184 log_debug("%s changed %s -> %s", s->meta.id, service_state_to_string(old_state), service_state_to_string(state));
1186 unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state]);
1189 static int service_coldplug(Unit *u) {
1190 Service *s = SERVICE(u);
1194 assert(s->state == SERVICE_DEAD);
1196 if (s->deserialized_state != s->state) {
1198 if (s->deserialized_state == SERVICE_START_PRE ||
1199 s->deserialized_state == SERVICE_START ||
1200 s->deserialized_state == SERVICE_START_POST ||
1201 s->deserialized_state == SERVICE_RELOAD ||
1202 s->deserialized_state == SERVICE_STOP ||
1203 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1204 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1205 s->deserialized_state == SERVICE_STOP_POST ||
1206 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1207 s->deserialized_state == SERVICE_FINAL_SIGKILL ||
1208 s->deserialized_state == SERVICE_AUTO_RESTART) {
1210 if (s->deserialized_state == SERVICE_AUTO_RESTART || s->timeout_usec > 0) {
1213 k = s->deserialized_state == SERVICE_AUTO_RESTART ? s->restart_usec : s->timeout_usec;
1215 if ((r = unit_watch_timer(UNIT(s), k, &s->timer_watch)) < 0)
1220 if ((s->deserialized_state == SERVICE_START &&
1221 (s->type == SERVICE_FORKING ||
1222 s->type == SERVICE_DBUS ||
1223 s->type == SERVICE_FINISH ||
1224 s->type == SERVICE_NOTIFY)) ||
1225 s->deserialized_state == SERVICE_START_POST ||
1226 s->deserialized_state == SERVICE_RUNNING ||
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 if (s->main_pid > 0)
1232 if ((r = unit_watch_pid(UNIT(s), s->main_pid)) < 0)
1235 if (s->deserialized_state == SERVICE_START_PRE ||
1236 s->deserialized_state == SERVICE_START ||
1237 s->deserialized_state == SERVICE_START_POST ||
1238 s->deserialized_state == SERVICE_RELOAD ||
1239 s->deserialized_state == SERVICE_STOP ||
1240 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1241 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1242 s->deserialized_state == SERVICE_STOP_POST ||
1243 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1244 s->deserialized_state == SERVICE_FINAL_SIGKILL)
1245 if (s->control_pid > 0)
1246 if ((r = unit_watch_pid(UNIT(s), s->control_pid)) < 0)
1249 service_set_state(s, s->deserialized_state);
1255 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
1259 unsigned rn_fds = 0;
1267 if (s->socket_fd >= 0)
1270 if ((r = service_get_sockets(s, &set)) < 0)
1273 SET_FOREACH(sock, set, i) {
1277 if ((r = socket_collect_fds(sock, &cfds, &cn_fds)) < 0)
1289 if (!(t = new(int, rn_fds+cn_fds))) {
1295 memcpy(t, rfds, rn_fds);
1296 memcpy(t+rn_fds, cfds, cn_fds);
1301 rn_fds = rn_fds+cn_fds;
1319 static int service_spawn(
1324 bool apply_permissions,
1326 bool apply_tty_stdin,
1327 bool set_notify_socket,
1332 int *fds = NULL, *fdsbuf = NULL;
1333 unsigned n_fds = 0, n_env = 0;
1334 char **argv = NULL, **final_env = NULL, **our_env = NULL;
1341 s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1342 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1343 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
1345 if (s->socket_fd >= 0) {
1346 fds = &s->socket_fd;
1349 if ((r = service_collect_fds(s, &fdsbuf, &n_fds)) < 0)
1356 if (timeout && s->timeout_usec) {
1357 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1360 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1362 if (!(argv = unit_full_printf_strv(UNIT(s), c->argv))) {
1367 if (!(our_env = new0(char*, 3))) {
1372 if (set_notify_socket)
1373 if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=@%s", s->meta.manager->notify_socket) < 0) {
1378 if (s->main_pid > 0)
1379 if (asprintf(our_env + n_env++, "MAINPID=%lu", (unsigned long) s->main_pid) < 0) {
1384 if (!(final_env = strv_env_merge(2,
1385 s->meta.manager->environment,
1400 s->meta.manager->confirm_spawn,
1401 s->meta.cgroup_bondings,
1408 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1409 /* FIXME: we need to do something here */
1415 strv_free(final_env);
1425 strv_free(final_env);
1428 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1433 static int main_pid_good(Service *s) {
1436 /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1439 /* If we know the pid file, then lets just check if it is
1441 if (s->main_pid_known)
1442 return s->main_pid > 0;
1444 /* We don't know the pid */
1448 static int control_pid_good(Service *s) {
1451 return s->control_pid > 0;
1454 static int cgroup_good(Service *s) {
1459 if ((r = cgroup_bonding_is_empty_list(s->meta.cgroup_bondings)) < 0)
1465 static void service_enter_dead(Service *s, bool success, bool allow_restart) {
1472 if (allow_restart &&
1474 (s->restart == SERVICE_RESTART_ALWAYS ||
1475 (s->restart == SERVICE_RESTART_ON_SUCCESS && !s->failure))) {
1477 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
1480 service_set_state(s, SERVICE_AUTO_RESTART);
1482 service_set_state(s, s->failure ? SERVICE_MAINTENANCE : SERVICE_DEAD);
1487 log_warning("%s failed to run install restart timer: %s", s->meta.id, strerror(-r));
1488 service_enter_dead(s, false, false);
1491 static void service_enter_signal(Service *s, ServiceState state, bool success);
1493 static void service_enter_stop_post(Service *s, bool success) {
1500 service_unwatch_control_pid(s);
1502 s->control_command_id = SERVICE_EXEC_STOP_POST;
1503 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST])) {
1504 if ((r = service_spawn(s,
1508 !s->permissions_start_only,
1509 !s->root_directory_start_only,
1512 &s->control_pid)) < 0)
1516 service_set_state(s, SERVICE_STOP_POST);
1518 service_enter_signal(s, SERVICE_FINAL_SIGTERM, true);
1523 log_warning("%s failed to run 'stop-post' task: %s", s->meta.id, strerror(-r));
1524 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1527 static void service_enter_signal(Service *s, ServiceState state, bool success) {
1536 if (s->kill_mode != KILL_NONE) {
1537 int sig = (state == SERVICE_STOP_SIGTERM || state == SERVICE_FINAL_SIGTERM) ? SIGTERM : SIGKILL;
1539 if (s->kill_mode == KILL_CONTROL_GROUP) {
1541 if ((r = cgroup_bonding_kill_list(s->meta.cgroup_bondings, sig)) < 0) {
1542 if (r != -EAGAIN && r != -ESRCH)
1551 if (s->main_pid > 0) {
1552 if (kill(s->kill_mode == KILL_PROCESS ? s->main_pid : -s->main_pid, sig) < 0 && errno != ESRCH)
1558 if (s->control_pid > 0) {
1559 if (kill(s->kill_mode == KILL_PROCESS ? s->control_pid : -s->control_pid, sig) < 0 && errno != ESRCH)
1570 if (sent && (s->main_pid > 0 || s->control_pid > 0)) {
1571 if (s->timeout_usec > 0)
1572 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1575 service_set_state(s, state);
1576 } else if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1577 service_enter_stop_post(s, true);
1579 service_enter_dead(s, true, true);
1584 log_warning("%s failed to kill processes: %s", s->meta.id, strerror(-r));
1586 if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1587 service_enter_stop_post(s, false);
1589 service_enter_dead(s, false, true);
1592 static void service_enter_stop(Service *s, bool success) {
1600 service_unwatch_control_pid(s);
1602 s->control_command_id = SERVICE_EXEC_STOP;
1603 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP])) {
1604 if ((r = service_spawn(s,
1608 !s->permissions_start_only,
1609 !s->root_directory_start_only,
1612 &s->control_pid)) < 0)
1615 service_set_state(s, SERVICE_STOP);
1617 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
1622 log_warning("%s failed to run 'stop' task: %s", s->meta.id, strerror(-r));
1623 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1626 static void service_enter_running(Service *s, bool success) {
1627 int main_pid_ok, cgroup_ok;
1633 main_pid_ok = main_pid_good(s);
1634 cgroup_ok = cgroup_good(s);
1636 if ((main_pid_ok > 0 || (main_pid_ok < 0 && cgroup_ok != 0)) &&
1637 (s->bus_name_good || s->type != SERVICE_DBUS))
1638 service_set_state(s, SERVICE_RUNNING);
1639 else if (s->valid_no_process)
1640 service_set_state(s, SERVICE_EXITED);
1642 service_enter_stop(s, true);
1645 static void service_enter_start_post(Service *s) {
1649 service_unwatch_control_pid(s);
1651 s->control_command_id = SERVICE_EXEC_START_POST;
1652 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_POST])) {
1653 if ((r = service_spawn(s,
1657 !s->permissions_start_only,
1658 !s->root_directory_start_only,
1661 &s->control_pid)) < 0)
1664 service_set_state(s, SERVICE_START_POST);
1666 service_enter_running(s, true);
1671 log_warning("%s failed to run 'start-post' task: %s", s->meta.id, strerror(-r));
1672 service_enter_stop(s, false);
1675 static void service_enter_start(Service *s) {
1681 assert(s->exec_command[SERVICE_EXEC_START]);
1682 assert(!s->exec_command[SERVICE_EXEC_START]->command_next);
1684 if (s->type == SERVICE_FORKING)
1685 service_unwatch_control_pid(s);
1687 service_unwatch_main_pid(s);
1689 if ((r = service_spawn(s,
1690 s->exec_command[SERVICE_EXEC_START],
1691 s->type == SERVICE_FORKING || s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY,
1696 s->notify_access != NOTIFY_NONE,
1700 if (s->type == SERVICE_SIMPLE) {
1701 /* For simple services we immediately start
1702 * the START_POST binaries. */
1704 service_set_main_pid(s, pid);
1705 service_enter_start_post(s);
1707 } else if (s->type == SERVICE_FORKING) {
1709 /* For forking services we wait until the start
1710 * process exited. */
1712 s->control_command_id = SERVICE_EXEC_START;
1713 s->control_command = s->exec_command[SERVICE_EXEC_START];
1715 s->control_pid = pid;
1716 service_set_state(s, SERVICE_START);
1718 } else if (s->type == SERVICE_FINISH ||
1719 s->type == SERVICE_DBUS ||
1720 s->type == SERVICE_NOTIFY) {
1722 /* For finishing services we wait until the start
1723 * process exited, too, but it is our main process. */
1725 /* For D-Bus services we know the main pid right away,
1726 * but wait for the bus name to appear on the
1727 * bus. Notify services are similar. */
1729 service_set_main_pid(s, pid);
1730 service_set_state(s, SERVICE_START);
1732 assert_not_reached("Unknown service type");
1737 log_warning("%s failed to run 'start' task: %s", s->meta.id, strerror(-r));
1738 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1741 static void service_enter_start_pre(Service *s) {
1746 service_unwatch_control_pid(s);
1748 s->control_command_id = SERVICE_EXEC_START_PRE;
1749 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_PRE])) {
1750 if ((r = service_spawn(s,
1754 !s->permissions_start_only,
1755 !s->root_directory_start_only,
1758 &s->control_pid)) < 0)
1761 service_set_state(s, SERVICE_START_PRE);
1763 service_enter_start(s);
1768 log_warning("%s failed to run 'start-pre' task: %s", s->meta.id, strerror(-r));
1769 service_enter_dead(s, false, true);
1772 static void service_enter_restart(Service *s) {
1777 dbus_error_init(&error);
1779 service_enter_dead(s, true, false);
1781 if ((r = manager_add_job(s->meta.manager, JOB_START, UNIT(s), JOB_FAIL, false, NULL, NULL)) < 0)
1784 log_debug("%s scheduled restart job.", s->meta.id);
1788 log_warning("%s failed to schedule restart job: %s", s->meta.id, bus_error(&error, -r));
1789 service_enter_dead(s, false, false);
1791 dbus_error_free(&error);
1794 static void service_enter_reload(Service *s) {
1799 service_unwatch_control_pid(s);
1801 s->control_command_id = SERVICE_EXEC_RELOAD;
1802 if ((s->control_command = s->exec_command[SERVICE_EXEC_RELOAD])) {
1803 if ((r = service_spawn(s,
1807 !s->permissions_start_only,
1808 !s->root_directory_start_only,
1811 &s->control_pid)) < 0)
1814 service_set_state(s, SERVICE_RELOAD);
1816 service_enter_running(s, true);
1821 log_warning("%s failed to run 'reload' task: %s", s->meta.id, strerror(-r));
1822 service_enter_stop(s, false);
1825 static void service_run_next(Service *s, bool success) {
1829 assert(s->control_command);
1830 assert(s->control_command->command_next);
1835 s->control_command = s->control_command->command_next;
1837 service_unwatch_control_pid(s);
1839 if ((r = service_spawn(s,
1843 !s->permissions_start_only,
1844 !s->root_directory_start_only,
1847 &s->control_pid)) < 0)
1853 log_warning("%s failed to run next task: %s", s->meta.id, strerror(-r));
1855 if (s->state == SERVICE_START_PRE)
1856 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1857 else if (s->state == SERVICE_STOP)
1858 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1859 else if (s->state == SERVICE_STOP_POST)
1860 service_enter_dead(s, false, true);
1862 service_enter_stop(s, false);
1865 static int service_start(Unit *u) {
1866 Service *s = SERVICE(u);
1870 /* We cannot fulfill this request right now, try again later
1872 if (s->state == SERVICE_STOP ||
1873 s->state == SERVICE_STOP_SIGTERM ||
1874 s->state == SERVICE_STOP_SIGKILL ||
1875 s->state == SERVICE_STOP_POST ||
1876 s->state == SERVICE_FINAL_SIGTERM ||
1877 s->state == SERVICE_FINAL_SIGKILL)
1880 /* Already on it! */
1881 if (s->state == SERVICE_START_PRE ||
1882 s->state == SERVICE_START ||
1883 s->state == SERVICE_START_POST)
1886 assert(s->state == SERVICE_DEAD || s->state == SERVICE_MAINTENANCE || s->state == SERVICE_AUTO_RESTART);
1888 /* Make sure we don't enter a busy loop of some kind. */
1889 if (!ratelimit_test(&s->ratelimit)) {
1890 log_warning("%s start request repeated too quickly, refusing to start.", u->meta.id);
1895 s->main_pid_known = false;
1896 s->allow_restart = true;
1898 service_enter_start_pre(s);
1902 static int service_stop(Unit *u) {
1903 Service *s = SERVICE(u);
1907 /* Cannot do this now */
1908 if (s->state == SERVICE_START_PRE ||
1909 s->state == SERVICE_START ||
1910 s->state == SERVICE_START_POST ||
1911 s->state == SERVICE_RELOAD)
1915 if (s->state == SERVICE_STOP ||
1916 s->state == SERVICE_STOP_SIGTERM ||
1917 s->state == SERVICE_STOP_SIGKILL ||
1918 s->state == SERVICE_STOP_POST ||
1919 s->state == SERVICE_FINAL_SIGTERM ||
1920 s->state == SERVICE_FINAL_SIGKILL)
1923 if (s->state == SERVICE_AUTO_RESTART) {
1924 service_set_state(s, SERVICE_DEAD);
1928 assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
1930 /* This is a user request, so don't do restarts on this
1932 s->allow_restart = false;
1934 service_enter_stop(s, true);
1938 static int service_reload(Unit *u) {
1939 Service *s = SERVICE(u);
1943 assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
1945 service_enter_reload(s);
1949 static bool service_can_reload(Unit *u) {
1950 Service *s = SERVICE(u);
1954 return !!s->exec_command[SERVICE_EXEC_RELOAD];
1957 static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
1958 Service *s = SERVICE(u);
1964 unit_serialize_item(u, f, "state", service_state_to_string(s->state));
1965 unit_serialize_item(u, f, "failure", yes_no(s->failure));
1967 if (s->control_pid > 0)
1968 unit_serialize_item_format(u, f, "control-pid", "%lu", (unsigned long) s->control_pid);
1970 if (s->main_pid_known && s->main_pid > 0)
1971 unit_serialize_item_format(u, f, "main-pid", "%lu", (unsigned long) s->main_pid);
1973 unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
1975 /* There's a minor uncleanliness here: if there are multiple
1976 * commands attached here, we will start from the first one
1978 if (s->control_command_id >= 0)
1979 unit_serialize_item(u, f, "control-command", service_exec_command_to_string(s->control_command_id));
1981 if (s->socket_fd >= 0) {
1984 if ((copy = fdset_put_dup(fds, s->socket_fd)) < 0)
1987 unit_serialize_item_format(u, f, "socket-fd", "%i", copy);
1990 if (s->main_exec_status.pid > 0) {
1991 unit_serialize_item_format(u, f, "main-exec-status-pid", "%lu", (unsigned long) s->main_exec_status.pid);
1993 if (s->main_exec_status.start_timestamp.realtime > 0) {
1994 unit_serialize_item_format(u, f, "main-exec-status-start-realtime",
1995 "%llu", (unsigned long long) s->main_exec_status.start_timestamp.realtime);
1997 unit_serialize_item_format(u, f, "main-exec-status-start-monotonic",
1998 "%llu", (unsigned long long) s->main_exec_status.start_timestamp.monotonic);
2001 if (s->main_exec_status.exit_timestamp.realtime > 0) {
2002 unit_serialize_item_format(u, f, "main-exec-status-exit-realtime",
2003 "%llu", (unsigned long long) s->main_exec_status.exit_timestamp.realtime);
2004 unit_serialize_item_format(u, f, "main-exec-status-exit-monotonic",
2005 "%llu", (unsigned long long) s->main_exec_status.exit_timestamp.monotonic);
2007 unit_serialize_item_format(u, f, "main-exec-status-code", "%i", s->main_exec_status.code);
2008 unit_serialize_item_format(u, f, "main-exec-status-status", "%i", s->main_exec_status.status);
2015 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
2016 Service *s = SERVICE(u);
2024 if (streq(key, "state")) {
2027 if ((state = service_state_from_string(value)) < 0)
2028 log_debug("Failed to parse state value %s", value);
2030 s->deserialized_state = state;
2031 } else if (streq(key, "failure")) {
2034 if ((b = parse_boolean(value)) < 0)
2035 log_debug("Failed to parse failure value %s", value);
2037 s->failure = b || s->failure;
2038 } else if (streq(key, "control-pid")) {
2041 if ((r = parse_pid(value, &pid)) < 0)
2042 log_debug("Failed to parse control-pid value %s", value);
2044 s->control_pid = pid;
2045 } else if (streq(key, "main-pid")) {
2048 if ((r = parse_pid(value, &pid)) < 0)
2049 log_debug("Failed to parse main-pid value %s", value);
2051 service_set_main_pid(s, (pid_t) pid);
2052 } else if (streq(key, "main-pid-known")) {
2055 if ((b = parse_boolean(value)) < 0)
2056 log_debug("Failed to parse main-pid-known value %s", value);
2058 s->main_pid_known = b;
2059 } else if (streq(key, "control-command")) {
2060 ServiceExecCommand id;
2062 if ((id = service_exec_command_from_string(value)) < 0)
2063 log_debug("Failed to parse exec-command value %s", value);
2065 s->control_command_id = id;
2066 s->control_command = s->exec_command[id];
2068 } else if (streq(key, "socket-fd")) {
2071 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2072 log_debug("Failed to parse socket-fd value %s", value);
2075 if (s->socket_fd >= 0)
2076 close_nointr_nofail(s->socket_fd);
2077 s->socket_fd = fdset_remove(fds, fd);
2079 } else if (streq(key, "main-exec-status-pid")) {
2082 if ((r = parse_pid(value, &pid)) < 0)
2083 log_debug("Failed to parse main-exec-status-pid value %s", value);
2085 s->main_exec_status.pid = pid;
2086 } else if (streq(key, "main-exec-status-code")) {
2089 if ((r = safe_atoi(value, &i)) < 0)
2090 log_debug("Failed to parse main-exec-status-code value %s", value);
2092 s->main_exec_status.code = i;
2093 } else if (streq(key, "main-exec-status-status")) {
2096 if ((r = safe_atoi(value, &i)) < 0)
2097 log_debug("Failed to parse main-exec-status-status value %s", value);
2099 s->main_exec_status.status = i;
2100 } else if (streq(key, "main-exec-status-start-realtime")) {
2103 if ((r = safe_atou64(value, &k)) < 0)
2104 log_debug("Failed to parse main-exec-status-start-realtime value %s", value);
2106 s->main_exec_status.start_timestamp.realtime = (usec_t) k;
2107 } else if (streq(key, "main-exec-status-start-monotonic")) {
2110 if ((r = safe_atou64(value, &k)) < 0)
2111 log_debug("Failed to parse main-exec-status-start-monotonic value %s", value);
2113 s->main_exec_status.start_timestamp.monotonic = (usec_t) k;
2114 } else if (streq(key, "main-exec-status-exit-realtime")) {
2117 if ((r = safe_atou64(value, &k)) < 0)
2118 log_debug("Failed to parse main-exec-status-exit-realtime value %s", value);
2120 s->main_exec_status.exit_timestamp.realtime = (usec_t) k;
2121 } else if (streq(key, "main-exec-status-exit-monotonic")) {
2124 if ((r = safe_atou64(value, &k)) < 0)
2125 log_debug("Failed to parse main-exec-status-exit-monotonic value %s", value);
2127 s->main_exec_status.exit_timestamp.monotonic = (usec_t) k;
2129 log_debug("Unknown serialization key '%s'", key);
2134 static UnitActiveState service_active_state(Unit *u) {
2137 return state_translation_table[SERVICE(u)->state];
2140 static const char *service_sub_state_to_string(Unit *u) {
2143 return service_state_to_string(SERVICE(u)->state);
2146 static bool service_check_gc(Unit *u) {
2147 Service *s = SERVICE(u);
2151 return !!s->sysv_path;
2154 static bool service_check_snapshot(Unit *u) {
2155 Service *s = SERVICE(u);
2159 return !s->got_socket_fd;
2162 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2163 Service *s = SERVICE(u);
2169 success = is_clean_exit(code, status);
2170 s->failure = s->failure || !success;
2172 if (s->main_pid == pid) {
2174 exec_status_exit(&s->main_exec_status, pid, code, status);
2177 if (s->type != SERVICE_FORKING) {
2178 assert(s->exec_command[SERVICE_EXEC_START]);
2179 s->exec_command[SERVICE_EXEC_START]->exec_status = s->main_exec_status;
2182 log_debug("%s: main process exited, code=%s, status=%i", u->meta.id, sigchld_code_to_string(code), status);
2184 /* The service exited, so the service is officially
2189 case SERVICE_START_POST:
2190 case SERVICE_RELOAD:
2192 /* Need to wait until the operation is
2197 if (s->type == SERVICE_FINISH) {
2198 /* This was our main goal, so let's go on */
2200 service_enter_start_post(s);
2202 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2205 assert(s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY);
2210 case SERVICE_RUNNING:
2211 service_enter_running(s, success);
2214 case SERVICE_STOP_SIGTERM:
2215 case SERVICE_STOP_SIGKILL:
2217 if (!control_pid_good(s))
2218 service_enter_stop_post(s, success);
2220 /* If there is still a control process, wait for that first */
2224 assert_not_reached("Uh, main process died at wrong time.");
2227 } else if (s->control_pid == pid) {
2229 if (s->control_command)
2230 exec_status_exit(&s->control_command->exec_status, pid, code, status);
2234 log_debug("%s: control process exited, code=%s status=%i", u->meta.id, sigchld_code_to_string(code), status);
2236 /* If we are shutting things down anyway we
2237 * don't care about failing commands. */
2239 if (s->control_command && s->control_command->command_next && success) {
2241 /* There is another command to *
2242 * execute, so let's do that. */
2244 log_debug("%s running next command for state %s", u->meta.id, service_state_to_string(s->state));
2245 service_run_next(s, success);
2248 /* No further commands for this step, so let's
2249 * figure out what to do next */
2251 s->control_command = NULL;
2252 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2254 log_debug("%s got final SIGCHLD for state %s", u->meta.id, service_state_to_string(s->state));
2258 case SERVICE_START_PRE:
2260 service_enter_start(s);
2262 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2266 assert(s->type == SERVICE_FORKING);
2268 /* Let's try to load the pid
2269 * file here if we can. We
2270 * ignore the return value,
2271 * since the PID file might
2272 * actually be created by a
2273 * START_POST script */
2277 service_load_pid_file(s);
2279 service_enter_start_post(s);
2281 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2285 case SERVICE_START_POST:
2286 if (success && s->pid_file && !s->main_pid_known) {
2289 /* Hmm, let's see if we can
2290 * load the pid now after the
2291 * start-post scripts got
2294 if ((r = service_load_pid_file(s)) < 0)
2295 log_warning("%s: failed to load PID file %s: %s", s->meta.id, s->pid_file, strerror(-r));
2300 case SERVICE_RELOAD:
2302 service_enter_running(s, true);
2304 service_enter_stop(s, false);
2309 service_enter_signal(s, SERVICE_STOP_SIGTERM, success);
2312 case SERVICE_STOP_SIGTERM:
2313 case SERVICE_STOP_SIGKILL:
2314 if (main_pid_good(s) <= 0)
2315 service_enter_stop_post(s, success);
2317 /* If there is still a service
2318 * process around, wait until
2319 * that one quit, too */
2322 case SERVICE_STOP_POST:
2323 case SERVICE_FINAL_SIGTERM:
2324 case SERVICE_FINAL_SIGKILL:
2325 service_enter_dead(s, success, true);
2329 assert_not_reached("Uh, control process died at wrong time.");
2335 static void service_timer_event(Unit *u, uint64_t elapsed, Watch* w) {
2336 Service *s = SERVICE(u);
2339 assert(elapsed == 1);
2341 assert(w == &s->timer_watch);
2345 case SERVICE_START_PRE:
2347 log_warning("%s operation timed out. Terminating.", u->meta.id);
2348 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2351 case SERVICE_START_POST:
2352 case SERVICE_RELOAD:
2353 log_warning("%s operation timed out. Stopping.", u->meta.id);
2354 service_enter_stop(s, false);
2358 log_warning("%s stopping timed out. Terminating.", u->meta.id);
2359 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
2362 case SERVICE_STOP_SIGTERM:
2363 log_warning("%s stopping timed out. Killing.", u->meta.id);
2364 service_enter_signal(s, SERVICE_STOP_SIGKILL, false);
2367 case SERVICE_STOP_SIGKILL:
2368 /* Uh, wie sent a SIGKILL and it is still not gone?
2369 * Must be something we cannot kill, so let's just be
2370 * weirded out and continue */
2372 log_warning("%s still around after SIGKILL. Ignoring.", u->meta.id);
2373 service_enter_stop_post(s, false);
2376 case SERVICE_STOP_POST:
2377 log_warning("%s stopping timed out (2). Terminating.", u->meta.id);
2378 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2381 case SERVICE_FINAL_SIGTERM:
2382 log_warning("%s stopping timed out (2). Killing.", u->meta.id);
2383 service_enter_signal(s, SERVICE_FINAL_SIGKILL, false);
2386 case SERVICE_FINAL_SIGKILL:
2387 log_warning("%s still around after SIGKILL (2). Entering maintenance mode.", u->meta.id);
2388 service_enter_dead(s, false, true);
2391 case SERVICE_AUTO_RESTART:
2392 log_info("%s holdoff time over, scheduling restart.", u->meta.id);
2393 service_enter_restart(s);
2397 assert_not_reached("Timeout at wrong time.");
2401 static void service_cgroup_notify_event(Unit *u) {
2402 Service *s = SERVICE(u);
2406 log_debug("%s: cgroup is empty", u->meta.id);
2410 /* Waiting for SIGCHLD is usually more interesting,
2411 * because it includes return codes/signals. Which is
2412 * why we ignore the cgroup events for most cases,
2413 * except when we don't know pid which to expect the
2416 case SERVICE_RUNNING:
2417 service_enter_running(s, true);
2425 static void service_notify_message(Unit *u, pid_t pid, char **tags) {
2426 Service *s = SERVICE(u);
2431 if (s->notify_access == NOTIFY_NONE) {
2432 log_warning("%s: Got notification message from PID %lu, but reception is disabled.",
2433 u->meta.id, (unsigned long) pid);
2437 if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
2438 log_warning("%s: Got notification message from PID %lu, but reception only permitted for PID %lu",
2439 u->meta.id, (unsigned long) pid, (unsigned long) s->main_pid);
2443 log_debug("%s: Got message", u->meta.id);
2445 /* Interpret MAINPID= */
2446 if ((e = strv_find_prefix(tags, "MAINPID=")) &&
2447 (s->state == SERVICE_START ||
2448 s->state == SERVICE_START_POST ||
2449 s->state == SERVICE_RUNNING ||
2450 s->state == SERVICE_RELOAD)) {
2452 if (parse_pid(e + 8, &pid) < 0)
2453 log_warning("Failed to parse %s", e);
2455 log_debug("%s: got %s", u->meta.id, e);
2456 service_set_main_pid(s, pid);
2460 /* Interpret READY= */
2461 if (s->type == SERVICE_NOTIFY &&
2462 s->state == SERVICE_START &&
2463 strv_find(tags, "READY=1")) {
2464 log_debug("%s: got READY=1", u->meta.id);
2466 service_enter_start_post(s);
2469 /* Interpret STATUS= */
2470 if ((e = strv_find_prefix(tags, "STATUS="))) {
2473 if (!(t = strdup(e+7))) {
2474 log_error("Failed to allocate string.");
2478 log_debug("%s: got %s", u->meta.id, e);
2480 free(s->status_text);
2485 static int service_enumerate(Manager *m) {
2489 char *path = NULL, *fpath = NULL, *name = NULL;
2494 STRV_FOREACH(p, m->lookup_paths.sysvrcnd_path)
2495 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++) {
2500 if (asprintf(&path, "%s/%s", *p, rcnd_table[i].path) < 0) {
2508 if (!(d = opendir(path))) {
2509 if (errno != ENOENT)
2510 log_warning("opendir() failed on %s: %s", path, strerror(errno));
2515 while ((de = readdir(d))) {
2519 if (ignore_file(de->d_name))
2522 if (de->d_name[0] != 'S' && de->d_name[0] != 'K')
2525 if (strlen(de->d_name) < 4)
2528 a = undecchar(de->d_name[1]);
2529 b = undecchar(de->d_name[2]);
2536 if (asprintf(&fpath, "%s/%s/%s", *p, rcnd_table[i].path, de->d_name) < 0) {
2541 if (access(fpath, X_OK) < 0) {
2543 if (errno != ENOENT)
2544 log_warning("access() failed on %s: %s", fpath, strerror(errno));
2550 if (!(name = sysv_translate_name(de->d_name + 3))) {
2555 if ((r = manager_load_unit_prepare(m, name, NULL, NULL, &service)) < 0) {
2556 log_warning("Failed to prepare unit %s: %s", name, strerror(-r));
2560 if (de->d_name[0] == 'S' &&
2561 (rcnd_table[i].type == RUNLEVEL_UP || rcnd_table[i].type == RUNLEVEL_SYSINIT))
2562 SERVICE(service)->sysv_start_priority =
2563 MAX(a*10 + b, SERVICE(service)->sysv_start_priority);
2565 manager_dispatch_load_queue(m);
2566 service = unit_follow_merge(service);
2568 /* If this is a native service, rely
2569 * on native ways to pull in a
2570 * service, don't pull it in via sysv
2572 if (service->meta.fragment_path)
2575 if (de->d_name[0] == 'S') {
2577 if ((r = unit_add_two_dependencies_by_name_inverse(service, UNIT_AFTER, UNIT_WANTS, rcnd_table[i].target, NULL, true)) < 0)
2580 } else if (de->d_name[0] == 'K' &&
2581 (rcnd_table[i].type == RUNLEVEL_DOWN ||
2582 rcnd_table[i].type == RUNLEVEL_SYSINIT)) {
2584 /* We honour K links only for
2585 * halt/reboot. For the normal
2586 * runlevels we assume the
2588 * implicitly added by the
2589 * core logic. Also, we don't
2590 * really distuingish here
2591 * between the runlevels 0 and
2592 * 6 and just add them to the
2593 * special shutdown target. On
2594 * SUSE the boot.d/ runlevel
2595 * is also used for shutdown,
2596 * so we add links for that
2597 * too to the shutdown
2600 if ((r = unit_add_two_dependencies_by_name_inverse(service, UNIT_AFTER, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true)) < 0)
2619 static void service_bus_name_owner_change(
2622 const char *old_owner,
2623 const char *new_owner) {
2625 Service *s = SERVICE(u);
2630 assert(streq(s->bus_name, name));
2631 assert(old_owner || new_owner);
2633 if (old_owner && new_owner)
2634 log_debug("%s's D-Bus name %s changed owner from %s to %s", u->meta.id, name, old_owner, new_owner);
2636 log_debug("%s's D-Bus name %s no longer registered by %s", u->meta.id, name, old_owner);
2638 log_debug("%s's D-Bus name %s now registered by %s", u->meta.id, name, new_owner);
2640 s->bus_name_good = !!new_owner;
2642 if (s->type == SERVICE_DBUS) {
2644 /* service_enter_running() will figure out what to
2646 if (s->state == SERVICE_RUNNING)
2647 service_enter_running(s, true);
2648 else if (s->state == SERVICE_START && new_owner)
2649 service_enter_start_post(s);
2651 } else if (new_owner &&
2653 (s->state == SERVICE_START ||
2654 s->state == SERVICE_START_POST ||
2655 s->state == SERVICE_RUNNING ||
2656 s->state == SERVICE_RELOAD)) {
2658 /* Try to acquire PID from bus service */
2659 log_debug("Trying to acquire PID from D-Bus name...");
2661 bus_query_pid(u->meta.manager, name);
2665 static void service_bus_query_pid_done(
2670 Service *s = SERVICE(u);
2675 log_debug("%s's D-Bus name %s is now owned by process %u", u->meta.id, name, (unsigned) pid);
2677 if (s->main_pid <= 0 &&
2678 (s->state == SERVICE_START ||
2679 s->state == SERVICE_START_POST ||
2680 s->state == SERVICE_RUNNING ||
2681 s->state == SERVICE_RELOAD))
2682 service_set_main_pid(s, pid);
2685 int service_set_socket_fd(Service *s, int fd, Socket *sock) {
2689 /* This is called by the socket code when instantiating a new
2690 * service for a stream socket and the socket needs to be
2693 if (s->meta.load_state != UNIT_LOADED)
2696 if (s->socket_fd >= 0)
2699 if (s->state != SERVICE_DEAD)
2703 s->got_socket_fd = true;
2709 static const char* const service_state_table[_SERVICE_STATE_MAX] = {
2710 [SERVICE_DEAD] = "dead",
2711 [SERVICE_START_PRE] = "start-pre",
2712 [SERVICE_START] = "start",
2713 [SERVICE_START_POST] = "start-post",
2714 [SERVICE_RUNNING] = "running",
2715 [SERVICE_EXITED] = "exited",
2716 [SERVICE_RELOAD] = "reload",
2717 [SERVICE_STOP] = "stop",
2718 [SERVICE_STOP_SIGTERM] = "stop-sigterm",
2719 [SERVICE_STOP_SIGKILL] = "stop-sigkill",
2720 [SERVICE_STOP_POST] = "stop-post",
2721 [SERVICE_FINAL_SIGTERM] = "final-sigterm",
2722 [SERVICE_FINAL_SIGKILL] = "final-sigkill",
2723 [SERVICE_MAINTENANCE] = "maintenance",
2724 [SERVICE_AUTO_RESTART] = "auto-restart",
2727 DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
2729 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
2730 [SERVICE_ONCE] = "once",
2731 [SERVICE_RESTART_ON_SUCCESS] = "restart-on-success",
2732 [SERVICE_RESTART_ALWAYS] = "restart-always",
2735 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
2737 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
2738 [SERVICE_SIMPLE] = "simple",
2739 [SERVICE_FORKING] = "forking",
2740 [SERVICE_FINISH] = "finish",
2741 [SERVICE_DBUS] = "dbus",
2742 [SERVICE_NOTIFY] = "notify"
2745 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
2747 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
2748 [SERVICE_EXEC_START_PRE] = "ExecStartPre",
2749 [SERVICE_EXEC_START] = "ExecStart",
2750 [SERVICE_EXEC_START_POST] = "ExecStartPost",
2751 [SERVICE_EXEC_RELOAD] = "ExecReload",
2752 [SERVICE_EXEC_STOP] = "ExecStop",
2753 [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
2756 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
2758 static const char* const notify_access_table[_NOTIFY_ACCESS_MAX] = {
2759 [NOTIFY_NONE] = "none",
2760 [NOTIFY_MAIN] = "main",
2761 [NOTIFY_ALL] = "all"
2764 DEFINE_STRING_TABLE_LOOKUP(notify_access, NotifyAccess);
2766 const UnitVTable service_vtable = {
2767 .suffix = ".service",
2768 .show_status = true,
2770 .init = service_init,
2771 .done = service_done,
2772 .load = service_load,
2774 .coldplug = service_coldplug,
2776 .dump = service_dump,
2778 .start = service_start,
2779 .stop = service_stop,
2780 .reload = service_reload,
2782 .can_reload = service_can_reload,
2784 .serialize = service_serialize,
2785 .deserialize_item = service_deserialize_item,
2787 .active_state = service_active_state,
2788 .sub_state_to_string = service_sub_state_to_string,
2790 .check_gc = service_check_gc,
2791 .check_snapshot = service_check_snapshot,
2793 .sigchld_event = service_sigchld_event,
2794 .timer_event = service_timer_event,
2796 .cgroup_notify_empty = service_cgroup_notify_event,
2797 .notify_message = service_notify_message,
2799 .bus_name_owner_change = service_bus_name_owner_change,
2800 .bus_query_pid_done = service_bus_query_pid_done,
2802 .bus_message_handler = bus_service_message_handler,
2804 .enumerate = service_enumerate