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_enabled)
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 = s->meta.manager->sysv_console ? EXEC_OUTPUT_TTY : EXEC_OUTPUT_NULL;
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_CONFLICTED_BY, 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 "%sSysVEnabled: %s\n",
1011 prefix, s->sysv_start_priority,
1012 prefix, yes_no(s->sysv_enabled));
1014 if (s->sysv_runlevels)
1015 fprintf(f, "%sSysVRunLevels: %s\n",
1016 prefix, s->sysv_runlevels);
1019 fprintf(f, "%sStatus Text: %s\n",
1020 prefix, s->status_text);
1025 static int service_load_pid_file(Service *s) {
1032 if (s->main_pid_known)
1035 assert(s->main_pid <= 0);
1040 if ((r = read_one_line_file(s->pid_file, &k)) < 0)
1043 r = parse_pid(k, &pid);
1049 if (kill(pid, 0) < 0 && errno != EPERM) {
1050 log_warning("PID %lu read from file %s does not exist. Your service or init script might be broken.",
1051 (unsigned long) pid, s->pid_file);
1055 if ((r = service_set_main_pid(s, pid)) < 0)
1058 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1059 /* FIXME: we need to do something here */
1065 static int service_get_sockets(Service *s, Set **_set) {
1074 if (s->socket_fd >= 0)
1077 /* Collects all Socket objects that belong to this
1078 * service. Note that a service might have multiple sockets
1079 * via multiple names. */
1081 if (!(set = set_new(NULL, NULL)))
1084 SET_FOREACH(t, s->meta.names, i) {
1088 /* Look for all socket objects that go by any of our
1089 * units and collect their fds */
1091 if (!(k = unit_name_change_suffix(t, ".socket"))) {
1096 p = manager_get_unit(s->meta.manager, k);
1102 if ((r = set_put(set, p)) < 0)
1114 static int service_notify_sockets_dead(Service *s) {
1122 if (s->socket_fd >= 0)
1125 /* Notifies all our sockets when we die */
1126 if ((r = service_get_sockets(s, &set)) < 0)
1129 SET_FOREACH(sock, set, i)
1130 socket_notify_service_dead(sock);
1137 static void service_set_state(Service *s, ServiceState state) {
1138 ServiceState old_state;
1141 old_state = s->state;
1144 if (state != SERVICE_START_PRE &&
1145 state != SERVICE_START &&
1146 state != SERVICE_START_POST &&
1147 state != SERVICE_RELOAD &&
1148 state != SERVICE_STOP &&
1149 state != SERVICE_STOP_SIGTERM &&
1150 state != SERVICE_STOP_SIGKILL &&
1151 state != SERVICE_STOP_POST &&
1152 state != SERVICE_FINAL_SIGTERM &&
1153 state != SERVICE_FINAL_SIGKILL &&
1154 state != SERVICE_AUTO_RESTART)
1155 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1157 if (state != SERVICE_START &&
1158 state != SERVICE_START_POST &&
1159 state != SERVICE_RUNNING &&
1160 state != SERVICE_RELOAD &&
1161 state != SERVICE_STOP &&
1162 state != SERVICE_STOP_SIGTERM &&
1163 state != SERVICE_STOP_SIGKILL)
1164 service_unwatch_main_pid(s);
1166 if (state != SERVICE_START_PRE &&
1167 state != SERVICE_START &&
1168 state != SERVICE_START_POST &&
1169 state != SERVICE_RELOAD &&
1170 state != SERVICE_STOP &&
1171 state != SERVICE_STOP_SIGTERM &&
1172 state != SERVICE_STOP_SIGKILL &&
1173 state != SERVICE_STOP_POST &&
1174 state != SERVICE_FINAL_SIGTERM &&
1175 state != SERVICE_FINAL_SIGKILL) {
1176 service_unwatch_control_pid(s);
1177 s->control_command = NULL;
1178 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1181 if (state == SERVICE_DEAD ||
1182 state == SERVICE_STOP ||
1183 state == SERVICE_STOP_SIGTERM ||
1184 state == SERVICE_STOP_SIGKILL ||
1185 state == SERVICE_STOP_POST ||
1186 state == SERVICE_FINAL_SIGTERM ||
1187 state == SERVICE_FINAL_SIGKILL ||
1188 state == SERVICE_MAINTENANCE ||
1189 state == SERVICE_AUTO_RESTART)
1190 service_notify_sockets_dead(s);
1192 if (state != SERVICE_START_PRE &&
1193 state != SERVICE_START &&
1194 state != SERVICE_START_POST &&
1195 state != SERVICE_RUNNING &&
1196 state != SERVICE_RELOAD &&
1197 state != SERVICE_STOP &&
1198 state != SERVICE_STOP_SIGTERM &&
1199 state != SERVICE_STOP_SIGKILL &&
1200 state != SERVICE_STOP_POST &&
1201 state != SERVICE_FINAL_SIGTERM &&
1202 state != SERVICE_FINAL_SIGKILL &&
1203 !(state == SERVICE_DEAD && s->meta.job)) {
1204 service_close_socket_fd(s);
1205 service_connection_unref(s);
1208 /* For the inactive states unit_notify() will trim the cgroup,
1209 * but for exit we have to do that ourselves... */
1210 if (state == SERVICE_EXITED)
1211 cgroup_bonding_trim_list(s->meta.cgroup_bondings, true);
1213 if (old_state != state)
1214 log_debug("%s changed %s -> %s", s->meta.id, service_state_to_string(old_state), service_state_to_string(state));
1216 unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state]);
1219 static int service_coldplug(Unit *u) {
1220 Service *s = SERVICE(u);
1224 assert(s->state == SERVICE_DEAD);
1226 if (s->deserialized_state != s->state) {
1228 if (s->deserialized_state == SERVICE_START_PRE ||
1229 s->deserialized_state == SERVICE_START ||
1230 s->deserialized_state == SERVICE_START_POST ||
1231 s->deserialized_state == SERVICE_RELOAD ||
1232 s->deserialized_state == SERVICE_STOP ||
1233 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1234 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1235 s->deserialized_state == SERVICE_STOP_POST ||
1236 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1237 s->deserialized_state == SERVICE_FINAL_SIGKILL ||
1238 s->deserialized_state == SERVICE_AUTO_RESTART) {
1240 if (s->deserialized_state == SERVICE_AUTO_RESTART || s->timeout_usec > 0) {
1243 k = s->deserialized_state == SERVICE_AUTO_RESTART ? s->restart_usec : s->timeout_usec;
1245 if ((r = unit_watch_timer(UNIT(s), k, &s->timer_watch)) < 0)
1250 if ((s->deserialized_state == SERVICE_START &&
1251 (s->type == SERVICE_FORKING ||
1252 s->type == SERVICE_DBUS ||
1253 s->type == SERVICE_FINISH ||
1254 s->type == SERVICE_NOTIFY)) ||
1255 s->deserialized_state == SERVICE_START_POST ||
1256 s->deserialized_state == SERVICE_RUNNING ||
1257 s->deserialized_state == SERVICE_RELOAD ||
1258 s->deserialized_state == SERVICE_STOP ||
1259 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1260 s->deserialized_state == SERVICE_STOP_SIGKILL)
1261 if (s->main_pid > 0)
1262 if ((r = unit_watch_pid(UNIT(s), s->main_pid)) < 0)
1265 if (s->deserialized_state == SERVICE_START_PRE ||
1266 s->deserialized_state == SERVICE_START ||
1267 s->deserialized_state == SERVICE_START_POST ||
1268 s->deserialized_state == SERVICE_RELOAD ||
1269 s->deserialized_state == SERVICE_STOP ||
1270 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1271 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1272 s->deserialized_state == SERVICE_STOP_POST ||
1273 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1274 s->deserialized_state == SERVICE_FINAL_SIGKILL)
1275 if (s->control_pid > 0)
1276 if ((r = unit_watch_pid(UNIT(s), s->control_pid)) < 0)
1279 service_set_state(s, s->deserialized_state);
1285 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
1289 unsigned rn_fds = 0;
1297 if (s->socket_fd >= 0)
1300 if ((r = service_get_sockets(s, &set)) < 0)
1303 SET_FOREACH(sock, set, i) {
1307 if ((r = socket_collect_fds(sock, &cfds, &cn_fds)) < 0)
1319 if (!(t = new(int, rn_fds+cn_fds))) {
1325 memcpy(t, rfds, rn_fds);
1326 memcpy(t+rn_fds, cfds, cn_fds);
1331 rn_fds = rn_fds+cn_fds;
1349 static int service_spawn(
1354 bool apply_permissions,
1356 bool apply_tty_stdin,
1357 bool set_notify_socket,
1362 int *fds = NULL, *fdsbuf = NULL;
1363 unsigned n_fds = 0, n_env = 0;
1364 char **argv = NULL, **final_env = NULL, **our_env = NULL;
1371 s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1372 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1373 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
1375 if (s->socket_fd >= 0) {
1376 fds = &s->socket_fd;
1379 if ((r = service_collect_fds(s, &fdsbuf, &n_fds)) < 0)
1386 if (timeout && s->timeout_usec) {
1387 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1390 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1392 if (!(argv = unit_full_printf_strv(UNIT(s), c->argv))) {
1397 if (!(our_env = new0(char*, 3))) {
1402 if (set_notify_socket)
1403 if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=@%s", s->meta.manager->notify_socket) < 0) {
1408 if (s->main_pid > 0)
1409 if (asprintf(our_env + n_env++, "MAINPID=%lu", (unsigned long) s->main_pid) < 0) {
1414 if (!(final_env = strv_env_merge(2,
1415 s->meta.manager->environment,
1430 s->meta.manager->confirm_spawn,
1431 s->meta.cgroup_bondings,
1438 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1439 /* FIXME: we need to do something here */
1445 strv_free(final_env);
1455 strv_free(final_env);
1458 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1463 static int main_pid_good(Service *s) {
1466 /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1469 /* If we know the pid file, then lets just check if it is
1471 if (s->main_pid_known)
1472 return s->main_pid > 0;
1474 /* We don't know the pid */
1478 static int control_pid_good(Service *s) {
1481 return s->control_pid > 0;
1484 static int cgroup_good(Service *s) {
1489 if ((r = cgroup_bonding_is_empty_list(s->meta.cgroup_bondings)) < 0)
1495 static void service_enter_dead(Service *s, bool success, bool allow_restart) {
1502 if (allow_restart &&
1503 !s->forbid_restart &&
1504 (s->restart == SERVICE_RESTART_ALWAYS ||
1505 (s->restart == SERVICE_RESTART_ON_SUCCESS && !s->failure))) {
1507 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
1510 service_set_state(s, SERVICE_AUTO_RESTART);
1512 service_set_state(s, s->failure ? SERVICE_MAINTENANCE : SERVICE_DEAD);
1514 s->forbid_restart = false;
1519 log_warning("%s failed to run install restart timer: %s", s->meta.id, strerror(-r));
1520 service_enter_dead(s, false, false);
1523 static void service_enter_signal(Service *s, ServiceState state, bool success);
1525 static void service_enter_stop_post(Service *s, bool success) {
1532 service_unwatch_control_pid(s);
1534 s->control_command_id = SERVICE_EXEC_STOP_POST;
1535 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST])) {
1536 if ((r = service_spawn(s,
1540 !s->permissions_start_only,
1541 !s->root_directory_start_only,
1544 &s->control_pid)) < 0)
1548 service_set_state(s, SERVICE_STOP_POST);
1550 service_enter_signal(s, SERVICE_FINAL_SIGTERM, true);
1555 log_warning("%s failed to run 'stop-post' task: %s", s->meta.id, strerror(-r));
1556 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1559 static void service_enter_signal(Service *s, ServiceState state, bool success) {
1568 if (s->exec_context.kill_mode != KILL_NONE) {
1569 int sig = (state == SERVICE_STOP_SIGTERM || state == SERVICE_FINAL_SIGTERM) ? s->exec_context.kill_signal : SIGKILL;
1571 if (s->exec_context.kill_mode == KILL_CONTROL_GROUP) {
1573 if ((r = cgroup_bonding_kill_list(s->meta.cgroup_bondings, sig)) < 0) {
1574 if (r != -EAGAIN && r != -ESRCH)
1583 if (s->main_pid > 0) {
1584 if (kill(s->exec_context.kill_mode == KILL_PROCESS ? s->main_pid : -s->main_pid, sig) < 0 && errno != ESRCH)
1590 if (s->control_pid > 0) {
1591 if (kill(s->exec_context.kill_mode == KILL_PROCESS ? s->control_pid : -s->control_pid, sig) < 0 && errno != ESRCH)
1602 if (sent && (s->main_pid > 0 || s->control_pid > 0)) {
1603 if (s->timeout_usec > 0)
1604 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1607 service_set_state(s, state);
1608 } else if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1609 service_enter_stop_post(s, true);
1611 service_enter_dead(s, true, true);
1616 log_warning("%s failed to kill processes: %s", s->meta.id, strerror(-r));
1618 if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1619 service_enter_stop_post(s, false);
1621 service_enter_dead(s, false, true);
1624 static void service_enter_stop(Service *s, bool success) {
1632 service_unwatch_control_pid(s);
1634 s->control_command_id = SERVICE_EXEC_STOP;
1635 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP])) {
1636 if ((r = service_spawn(s,
1640 !s->permissions_start_only,
1641 !s->root_directory_start_only,
1644 &s->control_pid)) < 0)
1647 service_set_state(s, SERVICE_STOP);
1649 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
1654 log_warning("%s failed to run 'stop' task: %s", s->meta.id, strerror(-r));
1655 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1658 static void service_enter_running(Service *s, bool success) {
1659 int main_pid_ok, cgroup_ok;
1665 main_pid_ok = main_pid_good(s);
1666 cgroup_ok = cgroup_good(s);
1668 if ((main_pid_ok > 0 || (main_pid_ok < 0 && cgroup_ok != 0)) &&
1669 (s->bus_name_good || s->type != SERVICE_DBUS))
1670 service_set_state(s, SERVICE_RUNNING);
1671 else if (s->valid_no_process)
1672 service_set_state(s, SERVICE_EXITED);
1674 service_enter_stop(s, true);
1677 static void service_enter_start_post(Service *s) {
1681 service_unwatch_control_pid(s);
1683 s->control_command_id = SERVICE_EXEC_START_POST;
1684 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_POST])) {
1685 if ((r = service_spawn(s,
1689 !s->permissions_start_only,
1690 !s->root_directory_start_only,
1693 &s->control_pid)) < 0)
1696 service_set_state(s, SERVICE_START_POST);
1698 service_enter_running(s, true);
1703 log_warning("%s failed to run 'start-post' task: %s", s->meta.id, strerror(-r));
1704 service_enter_stop(s, false);
1707 static void service_enter_start(Service *s) {
1713 assert(s->exec_command[SERVICE_EXEC_START]);
1714 assert(!s->exec_command[SERVICE_EXEC_START]->command_next);
1716 if (s->type == SERVICE_FORKING)
1717 service_unwatch_control_pid(s);
1719 service_unwatch_main_pid(s);
1721 if ((r = service_spawn(s,
1722 s->exec_command[SERVICE_EXEC_START],
1723 s->type == SERVICE_FORKING || s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY,
1728 s->notify_access != NOTIFY_NONE,
1732 if (s->type == SERVICE_SIMPLE) {
1733 /* For simple services we immediately start
1734 * the START_POST binaries. */
1736 service_set_main_pid(s, pid);
1737 service_enter_start_post(s);
1739 } else if (s->type == SERVICE_FORKING) {
1741 /* For forking services we wait until the start
1742 * process exited. */
1744 s->control_command_id = SERVICE_EXEC_START;
1745 s->control_command = s->exec_command[SERVICE_EXEC_START];
1747 s->control_pid = pid;
1748 service_set_state(s, SERVICE_START);
1750 } else if (s->type == SERVICE_FINISH ||
1751 s->type == SERVICE_DBUS ||
1752 s->type == SERVICE_NOTIFY) {
1754 /* For finishing services we wait until the start
1755 * process exited, too, but it is our main process. */
1757 /* For D-Bus services we know the main pid right away,
1758 * but wait for the bus name to appear on the
1759 * bus. Notify services are similar. */
1761 service_set_main_pid(s, pid);
1762 service_set_state(s, SERVICE_START);
1764 assert_not_reached("Unknown service type");
1769 log_warning("%s failed to run 'start' task: %s", s->meta.id, strerror(-r));
1770 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1773 static void service_enter_start_pre(Service *s) {
1778 service_unwatch_control_pid(s);
1780 s->control_command_id = SERVICE_EXEC_START_PRE;
1781 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_PRE])) {
1782 if ((r = service_spawn(s,
1786 !s->permissions_start_only,
1787 !s->root_directory_start_only,
1790 &s->control_pid)) < 0)
1793 service_set_state(s, SERVICE_START_PRE);
1795 service_enter_start(s);
1800 log_warning("%s failed to run 'start-pre' task: %s", s->meta.id, strerror(-r));
1801 service_enter_dead(s, false, true);
1804 static void service_enter_restart(Service *s) {
1809 dbus_error_init(&error);
1811 service_enter_dead(s, true, false);
1813 if ((r = manager_add_job(s->meta.manager, JOB_START, UNIT(s), JOB_FAIL, false, NULL, NULL)) < 0)
1816 log_debug("%s scheduled restart job.", s->meta.id);
1820 log_warning("%s failed to schedule restart job: %s", s->meta.id, bus_error(&error, -r));
1821 service_enter_dead(s, false, false);
1823 dbus_error_free(&error);
1826 static void service_enter_reload(Service *s) {
1831 service_unwatch_control_pid(s);
1833 s->control_command_id = SERVICE_EXEC_RELOAD;
1834 if ((s->control_command = s->exec_command[SERVICE_EXEC_RELOAD])) {
1835 if ((r = service_spawn(s,
1839 !s->permissions_start_only,
1840 !s->root_directory_start_only,
1843 &s->control_pid)) < 0)
1846 service_set_state(s, SERVICE_RELOAD);
1848 service_enter_running(s, true);
1853 log_warning("%s failed to run 'reload' task: %s", s->meta.id, strerror(-r));
1854 service_enter_stop(s, false);
1857 static void service_run_next(Service *s, bool success) {
1861 assert(s->control_command);
1862 assert(s->control_command->command_next);
1867 s->control_command = s->control_command->command_next;
1869 service_unwatch_control_pid(s);
1871 if ((r = service_spawn(s,
1875 !s->permissions_start_only,
1876 !s->root_directory_start_only,
1877 s->control_command_id == SERVICE_EXEC_START_PRE ||
1878 s->control_command_id == SERVICE_EXEC_STOP_POST,
1880 &s->control_pid)) < 0)
1886 log_warning("%s failed to run next task: %s", s->meta.id, strerror(-r));
1888 if (s->state == SERVICE_START_PRE)
1889 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1890 else if (s->state == SERVICE_STOP)
1891 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1892 else if (s->state == SERVICE_STOP_POST)
1893 service_enter_dead(s, false, true);
1895 service_enter_stop(s, false);
1898 static int service_start(Unit *u) {
1899 Service *s = SERVICE(u);
1903 /* We cannot fulfill this request right now, try again later
1905 if (s->state == SERVICE_STOP ||
1906 s->state == SERVICE_STOP_SIGTERM ||
1907 s->state == SERVICE_STOP_SIGKILL ||
1908 s->state == SERVICE_STOP_POST ||
1909 s->state == SERVICE_FINAL_SIGTERM ||
1910 s->state == SERVICE_FINAL_SIGKILL)
1913 /* Already on it! */
1914 if (s->state == SERVICE_START_PRE ||
1915 s->state == SERVICE_START ||
1916 s->state == SERVICE_START_POST)
1919 assert(s->state == SERVICE_DEAD || s->state == SERVICE_MAINTENANCE || s->state == SERVICE_AUTO_RESTART);
1921 /* Make sure we don't enter a busy loop of some kind. */
1922 if (!ratelimit_test(&s->ratelimit)) {
1923 log_warning("%s start request repeated too quickly, refusing to start.", u->meta.id);
1927 if ((s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1928 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1929 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) &&
1931 log_warning("%s can only be started with a per-connection socket.", u->meta.id);
1936 s->main_pid_known = false;
1937 s->forbid_restart = false;
1939 service_enter_start_pre(s);
1943 static int service_stop(Unit *u) {
1944 Service *s = SERVICE(u);
1948 /* This is a user request, so don't do restarts on this
1950 s->forbid_restart = true;
1953 if (s->state == SERVICE_STOP ||
1954 s->state == SERVICE_STOP_SIGTERM ||
1955 s->state == SERVICE_STOP_SIGKILL ||
1956 s->state == SERVICE_STOP_POST ||
1957 s->state == SERVICE_FINAL_SIGTERM ||
1958 s->state == SERVICE_FINAL_SIGKILL)
1961 /* Don't allow a restart */
1962 if (s->state == SERVICE_AUTO_RESTART) {
1963 service_set_state(s, SERVICE_DEAD);
1967 /* If there's already something running we go directly into
1969 if (s->state == SERVICE_START_PRE ||
1970 s->state == SERVICE_START ||
1971 s->state == SERVICE_START_POST ||
1972 s->state == SERVICE_RELOAD) {
1973 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
1977 assert(s->state == SERVICE_RUNNING ||
1978 s->state == SERVICE_EXITED);
1980 service_enter_stop(s, true);
1984 static int service_reload(Unit *u) {
1985 Service *s = SERVICE(u);
1989 assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
1991 service_enter_reload(s);
1995 static bool service_can_reload(Unit *u) {
1996 Service *s = SERVICE(u);
2000 return !!s->exec_command[SERVICE_EXEC_RELOAD];
2003 static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
2004 Service *s = SERVICE(u);
2010 unit_serialize_item(u, f, "state", service_state_to_string(s->state));
2011 unit_serialize_item(u, f, "failure", yes_no(s->failure));
2013 if (s->control_pid > 0)
2014 unit_serialize_item_format(u, f, "control-pid", "%lu", (unsigned long) s->control_pid);
2016 if (s->main_pid_known && s->main_pid > 0)
2017 unit_serialize_item_format(u, f, "main-pid", "%lu", (unsigned long) s->main_pid);
2019 unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
2022 unit_serialize_item(u, f, "status-text", s->status_text);
2024 /* There's a minor uncleanliness here: if there are multiple
2025 * commands attached here, we will start from the first one
2027 if (s->control_command_id >= 0)
2028 unit_serialize_item(u, f, "control-command", service_exec_command_to_string(s->control_command_id));
2030 if (s->socket_fd >= 0) {
2033 if ((copy = fdset_put_dup(fds, s->socket_fd)) < 0)
2036 unit_serialize_item_format(u, f, "socket-fd", "%i", copy);
2039 if (s->main_exec_status.pid > 0) {
2040 unit_serialize_item_format(u, f, "main-exec-status-pid", "%lu", (unsigned long) s->main_exec_status.pid);
2042 if (s->main_exec_status.start_timestamp.realtime > 0) {
2043 unit_serialize_item_format(u, f, "main-exec-status-start-realtime",
2044 "%llu", (unsigned long long) s->main_exec_status.start_timestamp.realtime);
2046 unit_serialize_item_format(u, f, "main-exec-status-start-monotonic",
2047 "%llu", (unsigned long long) s->main_exec_status.start_timestamp.monotonic);
2050 if (s->main_exec_status.exit_timestamp.realtime > 0) {
2051 unit_serialize_item_format(u, f, "main-exec-status-exit-realtime",
2052 "%llu", (unsigned long long) s->main_exec_status.exit_timestamp.realtime);
2053 unit_serialize_item_format(u, f, "main-exec-status-exit-monotonic",
2054 "%llu", (unsigned long long) s->main_exec_status.exit_timestamp.monotonic);
2056 unit_serialize_item_format(u, f, "main-exec-status-code", "%i", s->main_exec_status.code);
2057 unit_serialize_item_format(u, f, "main-exec-status-status", "%i", s->main_exec_status.status);
2064 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
2065 Service *s = SERVICE(u);
2072 if (streq(key, "state")) {
2075 if ((state = service_state_from_string(value)) < 0)
2076 log_debug("Failed to parse state value %s", value);
2078 s->deserialized_state = state;
2079 } else if (streq(key, "failure")) {
2082 if ((b = parse_boolean(value)) < 0)
2083 log_debug("Failed to parse failure value %s", value);
2085 s->failure = b || s->failure;
2086 } else if (streq(key, "control-pid")) {
2089 if (parse_pid(value, &pid) < 0)
2090 log_debug("Failed to parse control-pid value %s", value);
2092 s->control_pid = pid;
2093 } else if (streq(key, "main-pid")) {
2096 if (parse_pid(value, &pid) < 0)
2097 log_debug("Failed to parse main-pid value %s", value);
2099 service_set_main_pid(s, (pid_t) pid);
2100 } else if (streq(key, "main-pid-known")) {
2103 if ((b = parse_boolean(value)) < 0)
2104 log_debug("Failed to parse main-pid-known value %s", value);
2106 s->main_pid_known = b;
2107 } else if (streq(key, "status-text")) {
2110 if ((t = strdup(value))) {
2111 free(s->status_text);
2115 } else if (streq(key, "control-command")) {
2116 ServiceExecCommand id;
2118 if ((id = service_exec_command_from_string(value)) < 0)
2119 log_debug("Failed to parse exec-command value %s", value);
2121 s->control_command_id = id;
2122 s->control_command = s->exec_command[id];
2124 } else if (streq(key, "socket-fd")) {
2127 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2128 log_debug("Failed to parse socket-fd value %s", value);
2131 if (s->socket_fd >= 0)
2132 close_nointr_nofail(s->socket_fd);
2133 s->socket_fd = fdset_remove(fds, fd);
2135 } else if (streq(key, "main-exec-status-pid")) {
2138 if (parse_pid(value, &pid) < 0)
2139 log_debug("Failed to parse main-exec-status-pid value %s", value);
2141 s->main_exec_status.pid = pid;
2142 } else if (streq(key, "main-exec-status-code")) {
2145 if (safe_atoi(value, &i) < 0)
2146 log_debug("Failed to parse main-exec-status-code value %s", value);
2148 s->main_exec_status.code = i;
2149 } else if (streq(key, "main-exec-status-status")) {
2152 if (safe_atoi(value, &i) < 0)
2153 log_debug("Failed to parse main-exec-status-status value %s", value);
2155 s->main_exec_status.status = i;
2156 } else if (streq(key, "main-exec-status-start-realtime")) {
2159 if (safe_atou64(value, &k) < 0)
2160 log_debug("Failed to parse main-exec-status-start-realtime value %s", value);
2162 s->main_exec_status.start_timestamp.realtime = (usec_t) k;
2163 } else if (streq(key, "main-exec-status-start-monotonic")) {
2166 if (safe_atou64(value, &k) < 0)
2167 log_debug("Failed to parse main-exec-status-start-monotonic value %s", value);
2169 s->main_exec_status.start_timestamp.monotonic = (usec_t) k;
2170 } else if (streq(key, "main-exec-status-exit-realtime")) {
2173 if (safe_atou64(value, &k) < 0)
2174 log_debug("Failed to parse main-exec-status-exit-realtime value %s", value);
2176 s->main_exec_status.exit_timestamp.realtime = (usec_t) k;
2177 } else if (streq(key, "main-exec-status-exit-monotonic")) {
2180 if (safe_atou64(value, &k) < 0)
2181 log_debug("Failed to parse main-exec-status-exit-monotonic value %s", value);
2183 s->main_exec_status.exit_timestamp.monotonic = (usec_t) k;
2185 log_debug("Unknown serialization key '%s'", key);
2190 static UnitActiveState service_active_state(Unit *u) {
2193 return state_translation_table[SERVICE(u)->state];
2196 static const char *service_sub_state_to_string(Unit *u) {
2199 return service_state_to_string(SERVICE(u)->state);
2202 static bool service_check_gc(Unit *u) {
2203 Service *s = SERVICE(u);
2207 return !!s->sysv_path;
2210 static bool service_check_snapshot(Unit *u) {
2211 Service *s = SERVICE(u);
2215 return !s->got_socket_fd;
2218 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2219 Service *s = SERVICE(u);
2225 success = is_clean_exit(code, status);
2227 if (s->main_pid == pid) {
2229 exec_status_exit(&s->main_exec_status, pid, code, status);
2232 if (s->type != SERVICE_FORKING) {
2233 assert(s->exec_command[SERVICE_EXEC_START]);
2234 s->exec_command[SERVICE_EXEC_START]->exec_status = s->main_exec_status;
2236 if (s->exec_command[SERVICE_EXEC_START]->ignore)
2240 log_full(success ? LOG_DEBUG : LOG_NOTICE,
2241 "%s: main process exited, code=%s, status=%i", u->meta.id, sigchld_code_to_string(code), status);
2242 s->failure = s->failure || !success;
2244 /* The service exited, so the service is officially
2249 case SERVICE_START_POST:
2250 case SERVICE_RELOAD:
2252 /* Need to wait until the operation is
2257 if (s->type == SERVICE_FINISH) {
2258 /* This was our main goal, so let's go on */
2260 service_enter_start_post(s);
2262 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2265 assert(s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY);
2270 case SERVICE_RUNNING:
2271 service_enter_running(s, success);
2274 case SERVICE_STOP_SIGTERM:
2275 case SERVICE_STOP_SIGKILL:
2277 if (!control_pid_good(s))
2278 service_enter_stop_post(s, success);
2280 /* If there is still a control process, wait for that first */
2284 assert_not_reached("Uh, main process died at wrong time.");
2287 } else if (s->control_pid == pid) {
2289 if (s->control_command) {
2290 exec_status_exit(&s->control_command->exec_status, pid, code, status);
2292 if (s->control_command->ignore)
2298 log_full(success ? LOG_DEBUG : LOG_NOTICE,
2299 "%s: control process exited, code=%s status=%i", u->meta.id, sigchld_code_to_string(code), status);
2300 s->failure = s->failure || !success;
2302 /* If we are shutting things down anyway we
2303 * don't care about failing commands. */
2305 if (s->control_command && s->control_command->command_next && success) {
2307 /* There is another command to *
2308 * execute, so let's do that. */
2310 log_debug("%s running next command for state %s", u->meta.id, service_state_to_string(s->state));
2311 service_run_next(s, success);
2314 /* No further commands for this step, so let's
2315 * figure out what to do next */
2317 s->control_command = NULL;
2318 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2320 log_debug("%s got final SIGCHLD for state %s", u->meta.id, service_state_to_string(s->state));
2324 case SERVICE_START_PRE:
2326 service_enter_start(s);
2328 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2332 assert(s->type == SERVICE_FORKING);
2334 /* Let's try to load the pid
2335 * file here if we can. We
2336 * ignore the return value,
2337 * since the PID file might
2338 * actually be created by a
2339 * START_POST script */
2343 service_load_pid_file(s);
2345 service_enter_start_post(s);
2347 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2351 case SERVICE_START_POST:
2352 if (success && s->pid_file && !s->main_pid_known) {
2355 /* Hmm, let's see if we can
2356 * load the pid now after the
2357 * start-post scripts got
2360 if ((r = service_load_pid_file(s)) < 0)
2361 log_warning("%s: failed to load PID file %s: %s", s->meta.id, s->pid_file, strerror(-r));
2366 case SERVICE_RELOAD:
2368 service_enter_running(s, true);
2370 service_enter_stop(s, false);
2375 service_enter_signal(s, SERVICE_STOP_SIGTERM, success);
2378 case SERVICE_STOP_SIGTERM:
2379 case SERVICE_STOP_SIGKILL:
2380 if (main_pid_good(s) <= 0)
2381 service_enter_stop_post(s, success);
2383 /* If there is still a service
2384 * process around, wait until
2385 * that one quit, too */
2388 case SERVICE_STOP_POST:
2389 case SERVICE_FINAL_SIGTERM:
2390 case SERVICE_FINAL_SIGKILL:
2391 service_enter_dead(s, success, true);
2395 assert_not_reached("Uh, control process died at wrong time.");
2401 static void service_timer_event(Unit *u, uint64_t elapsed, Watch* w) {
2402 Service *s = SERVICE(u);
2405 assert(elapsed == 1);
2407 assert(w == &s->timer_watch);
2411 case SERVICE_START_PRE:
2413 log_warning("%s operation timed out. Terminating.", u->meta.id);
2414 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2417 case SERVICE_START_POST:
2418 case SERVICE_RELOAD:
2419 log_warning("%s operation timed out. Stopping.", u->meta.id);
2420 service_enter_stop(s, false);
2424 log_warning("%s stopping timed out. Terminating.", u->meta.id);
2425 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
2428 case SERVICE_STOP_SIGTERM:
2429 log_warning("%s stopping timed out. Killing.", u->meta.id);
2430 service_enter_signal(s, SERVICE_STOP_SIGKILL, false);
2433 case SERVICE_STOP_SIGKILL:
2434 /* Uh, wie sent a SIGKILL and it is still not gone?
2435 * Must be something we cannot kill, so let's just be
2436 * weirded out and continue */
2438 log_warning("%s still around after SIGKILL. Ignoring.", u->meta.id);
2439 service_enter_stop_post(s, false);
2442 case SERVICE_STOP_POST:
2443 log_warning("%s stopping timed out (2). Terminating.", u->meta.id);
2444 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2447 case SERVICE_FINAL_SIGTERM:
2448 log_warning("%s stopping timed out (2). Killing.", u->meta.id);
2449 service_enter_signal(s, SERVICE_FINAL_SIGKILL, false);
2452 case SERVICE_FINAL_SIGKILL:
2453 log_warning("%s still around after SIGKILL (2). Entering maintenance mode.", u->meta.id);
2454 service_enter_dead(s, false, true);
2457 case SERVICE_AUTO_RESTART:
2458 log_info("%s holdoff time over, scheduling restart.", u->meta.id);
2459 service_enter_restart(s);
2463 assert_not_reached("Timeout at wrong time.");
2467 static void service_cgroup_notify_event(Unit *u) {
2468 Service *s = SERVICE(u);
2472 log_debug("%s: cgroup is empty", u->meta.id);
2476 /* Waiting for SIGCHLD is usually more interesting,
2477 * because it includes return codes/signals. Which is
2478 * why we ignore the cgroup events for most cases,
2479 * except when we don't know pid which to expect the
2482 case SERVICE_RUNNING:
2483 service_enter_running(s, true);
2491 static void service_notify_message(Unit *u, pid_t pid, char **tags) {
2492 Service *s = SERVICE(u);
2497 if (s->notify_access == NOTIFY_NONE) {
2498 log_warning("%s: Got notification message from PID %lu, but reception is disabled.",
2499 u->meta.id, (unsigned long) pid);
2503 if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
2504 log_warning("%s: Got notification message from PID %lu, but reception only permitted for PID %lu",
2505 u->meta.id, (unsigned long) pid, (unsigned long) s->main_pid);
2509 log_debug("%s: Got message", u->meta.id);
2511 /* Interpret MAINPID= */
2512 if ((e = strv_find_prefix(tags, "MAINPID=")) &&
2513 (s->state == SERVICE_START ||
2514 s->state == SERVICE_START_POST ||
2515 s->state == SERVICE_RUNNING ||
2516 s->state == SERVICE_RELOAD)) {
2518 if (parse_pid(e + 8, &pid) < 0)
2519 log_warning("Failed to parse notification message %s", e);
2521 log_debug("%s: got %s", u->meta.id, e);
2522 service_set_main_pid(s, pid);
2526 /* Interpret READY= */
2527 if (s->type == SERVICE_NOTIFY &&
2528 s->state == SERVICE_START &&
2529 strv_find(tags, "READY=1")) {
2530 log_debug("%s: got READY=1", u->meta.id);
2532 service_enter_start_post(s);
2535 /* Interpret STATUS= */
2536 if ((e = strv_find_prefix(tags, "STATUS="))) {
2540 if (!(t = strdup(e+7))) {
2541 log_error("Failed to allocate string.");
2545 log_debug("%s: got %s", u->meta.id, e);
2547 free(s->status_text);
2550 free(s->status_text);
2551 s->status_text = NULL;
2557 static int service_enumerate(Manager *m) {
2561 char *path = NULL, *fpath = NULL, *name = NULL;
2566 STRV_FOREACH(p, m->lookup_paths.sysvrcnd_path)
2567 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++) {
2572 if (asprintf(&path, "%s/%s", *p, rcnd_table[i].path) < 0) {
2580 if (!(d = opendir(path))) {
2581 if (errno != ENOENT)
2582 log_warning("opendir() failed on %s: %s", path, strerror(errno));
2587 while ((de = readdir(d))) {
2591 if (ignore_file(de->d_name))
2594 if (de->d_name[0] != 'S' && de->d_name[0] != 'K')
2597 if (strlen(de->d_name) < 4)
2600 a = undecchar(de->d_name[1]);
2601 b = undecchar(de->d_name[2]);
2608 if (asprintf(&fpath, "%s/%s/%s", *p, rcnd_table[i].path, de->d_name) < 0) {
2613 if (access(fpath, X_OK) < 0) {
2615 if (errno != ENOENT)
2616 log_warning("access() failed on %s: %s", fpath, strerror(errno));
2622 if (!(name = sysv_translate_name(de->d_name + 3))) {
2627 if ((r = manager_load_unit_prepare(m, name, NULL, NULL, &service)) < 0) {
2628 log_warning("Failed to prepare unit %s: %s", name, strerror(-r));
2632 if (de->d_name[0] == 'S' &&
2633 (rcnd_table[i].type == RUNLEVEL_UP || rcnd_table[i].type == RUNLEVEL_SYSINIT)) {
2634 SERVICE(service)->sysv_start_priority =
2635 MAX(a*10 + b, SERVICE(service)->sysv_start_priority);
2636 SERVICE(service)->sysv_enabled = true;
2639 manager_dispatch_load_queue(m);
2640 service = unit_follow_merge(service);
2642 /* If this is a native service, rely
2643 * on native ways to pull in a
2644 * service, don't pull it in via sysv
2646 if (service->meta.fragment_path)
2649 if (de->d_name[0] == 'S') {
2651 if ((r = unit_add_two_dependencies_by_name_inverse(service, UNIT_AFTER, UNIT_WANTS, rcnd_table[i].target, NULL, true)) < 0)
2654 } else if (de->d_name[0] == 'K' &&
2655 (rcnd_table[i].type == RUNLEVEL_DOWN ||
2656 rcnd_table[i].type == RUNLEVEL_SYSINIT)) {
2658 /* We honour K links only for
2659 * halt/reboot. For the normal
2660 * runlevels we assume the
2662 * implicitly added by the
2663 * core logic. Also, we don't
2664 * really distuingish here
2665 * between the runlevels 0 and
2666 * 6 and just add them to the
2667 * special shutdown target. On
2668 * SUSE the boot.d/ runlevel
2669 * is also used for shutdown,
2670 * so we add links for that
2671 * too to the shutdown
2674 if ((r = unit_add_two_dependencies_by_name_inverse(service, UNIT_AFTER, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true)) < 0)
2693 static void service_bus_name_owner_change(
2696 const char *old_owner,
2697 const char *new_owner) {
2699 Service *s = SERVICE(u);
2704 assert(streq(s->bus_name, name));
2705 assert(old_owner || new_owner);
2707 if (old_owner && new_owner)
2708 log_debug("%s's D-Bus name %s changed owner from %s to %s", u->meta.id, name, old_owner, new_owner);
2710 log_debug("%s's D-Bus name %s no longer registered by %s", u->meta.id, name, old_owner);
2712 log_debug("%s's D-Bus name %s now registered by %s", u->meta.id, name, new_owner);
2714 s->bus_name_good = !!new_owner;
2716 if (s->type == SERVICE_DBUS) {
2718 /* service_enter_running() will figure out what to
2720 if (s->state == SERVICE_RUNNING)
2721 service_enter_running(s, true);
2722 else if (s->state == SERVICE_START && new_owner)
2723 service_enter_start_post(s);
2725 } else if (new_owner &&
2727 (s->state == SERVICE_START ||
2728 s->state == SERVICE_START_POST ||
2729 s->state == SERVICE_RUNNING ||
2730 s->state == SERVICE_RELOAD)) {
2732 /* Try to acquire PID from bus service */
2733 log_debug("Trying to acquire PID from D-Bus name...");
2735 bus_query_pid(u->meta.manager, name);
2739 static void service_bus_query_pid_done(
2744 Service *s = SERVICE(u);
2749 log_debug("%s's D-Bus name %s is now owned by process %u", u->meta.id, name, (unsigned) pid);
2751 if (s->main_pid <= 0 &&
2752 (s->state == SERVICE_START ||
2753 s->state == SERVICE_START_POST ||
2754 s->state == SERVICE_RUNNING ||
2755 s->state == SERVICE_RELOAD))
2756 service_set_main_pid(s, pid);
2759 int service_set_socket_fd(Service *s, int fd, Socket *sock) {
2763 /* This is called by the socket code when instantiating a new
2764 * service for a stream socket and the socket needs to be
2767 if (s->meta.load_state != UNIT_LOADED)
2770 if (s->socket_fd >= 0)
2773 if (s->state != SERVICE_DEAD)
2777 s->got_socket_fd = true;
2783 static void service_reset_maintenance(Unit *u) {
2784 Service *s = SERVICE(u);
2788 if (s->state == SERVICE_MAINTENANCE)
2789 service_set_state(s, SERVICE_DEAD);
2794 static const char* const service_state_table[_SERVICE_STATE_MAX] = {
2795 [SERVICE_DEAD] = "dead",
2796 [SERVICE_START_PRE] = "start-pre",
2797 [SERVICE_START] = "start",
2798 [SERVICE_START_POST] = "start-post",
2799 [SERVICE_RUNNING] = "running",
2800 [SERVICE_EXITED] = "exited",
2801 [SERVICE_RELOAD] = "reload",
2802 [SERVICE_STOP] = "stop",
2803 [SERVICE_STOP_SIGTERM] = "stop-sigterm",
2804 [SERVICE_STOP_SIGKILL] = "stop-sigkill",
2805 [SERVICE_STOP_POST] = "stop-post",
2806 [SERVICE_FINAL_SIGTERM] = "final-sigterm",
2807 [SERVICE_FINAL_SIGKILL] = "final-sigkill",
2808 [SERVICE_MAINTENANCE] = "maintenance",
2809 [SERVICE_AUTO_RESTART] = "auto-restart",
2812 DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
2814 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
2815 [SERVICE_ONCE] = "once",
2816 [SERVICE_RESTART_ON_SUCCESS] = "restart-on-success",
2817 [SERVICE_RESTART_ALWAYS] = "restart-always",
2820 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
2822 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
2823 [SERVICE_SIMPLE] = "simple",
2824 [SERVICE_FORKING] = "forking",
2825 [SERVICE_FINISH] = "finish",
2826 [SERVICE_DBUS] = "dbus",
2827 [SERVICE_NOTIFY] = "notify"
2830 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
2832 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
2833 [SERVICE_EXEC_START_PRE] = "ExecStartPre",
2834 [SERVICE_EXEC_START] = "ExecStart",
2835 [SERVICE_EXEC_START_POST] = "ExecStartPost",
2836 [SERVICE_EXEC_RELOAD] = "ExecReload",
2837 [SERVICE_EXEC_STOP] = "ExecStop",
2838 [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
2841 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
2843 static const char* const notify_access_table[_NOTIFY_ACCESS_MAX] = {
2844 [NOTIFY_NONE] = "none",
2845 [NOTIFY_MAIN] = "main",
2846 [NOTIFY_ALL] = "all"
2849 DEFINE_STRING_TABLE_LOOKUP(notify_access, NotifyAccess);
2851 const UnitVTable service_vtable = {
2852 .suffix = ".service",
2853 .show_status = true,
2855 .init = service_init,
2856 .done = service_done,
2857 .load = service_load,
2859 .coldplug = service_coldplug,
2861 .dump = service_dump,
2863 .start = service_start,
2864 .stop = service_stop,
2865 .reload = service_reload,
2867 .can_reload = service_can_reload,
2869 .serialize = service_serialize,
2870 .deserialize_item = service_deserialize_item,
2872 .active_state = service_active_state,
2873 .sub_state_to_string = service_sub_state_to_string,
2875 .check_gc = service_check_gc,
2876 .check_snapshot = service_check_snapshot,
2878 .sigchld_event = service_sigchld_event,
2879 .timer_event = service_timer_event,
2881 .reset_maintenance = service_reset_maintenance,
2883 .cgroup_notify_empty = service_cgroup_notify_event,
2884 .notify_message = service_notify_message,
2886 .bus_name_owner_change = service_bus_name_owner_change,
2887 .bus_query_pid_done = service_bus_query_pid_done,
2889 .bus_message_handler = bus_service_message_handler,
2891 .enumerate = service_enumerate