1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
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 = strappend("LSB: ", 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 = strappend("LSB: ", 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 = strappend("LSB: ", 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->remain_after_exit = 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->type != SERVICE_ONESHOT &&
838 s->exec_command[SERVICE_EXEC_START]->command_next) {
839 log_error("%s has more than one ExecStart setting, which is only allowed for Type=oneshot services. Refusing.", s->meta.id);
843 if (s->type == SERVICE_DBUS && !s->bus_name) {
844 log_error("%s is of type D-Bus but no D-Bus service name has been specified. Refusing.", s->meta.id);
848 if (s->exec_context.pam_name && s->exec_context.kill_mode != KILL_CONTROL_GROUP) {
849 log_error("%s has PAM enabled. Kill mode must be set to 'control-group'. Refusing.", s->meta.id);
856 static int service_add_default_dependencies(Service *s) {
861 /* Add a number of automatic dependencies useful for the
862 * majority of services. */
864 /* First, pull in base system */
865 if (s->meta.manager->running_as == MANAGER_SYSTEM) {
867 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_BASIC_TARGET, NULL, true)) < 0)
870 } else if (s->meta.manager->running_as == MANAGER_SESSION) {
872 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SOCKETS_TARGET, NULL, true)) < 0)
876 /* Second, activate normal shutdown */
877 return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTED_BY, SPECIAL_SHUTDOWN_TARGET, NULL, true);
880 static int service_load(Unit *u) {
882 Service *s = SERVICE(u);
886 /* Load a .service file */
887 if ((r = unit_load_fragment(u)) < 0)
890 /* Load a classic init script as a fallback, if we couldn't find anything */
891 if (u->meta.load_state == UNIT_STUB)
892 if ((r = service_load_sysv(s)) < 0)
895 /* Still nothing found? Then let's give up */
896 if (u->meta.load_state == UNIT_STUB)
899 /* We were able to load something, then let's add in the
900 * dropin directories. */
901 if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
904 /* This is a new unit? Then let's add in some extras */
905 if (u->meta.load_state == UNIT_LOADED) {
906 if ((r = unit_add_exec_dependencies(u, &s->exec_context)) < 0)
909 if ((r = unit_add_default_cgroup(u)) < 0)
912 if ((r = sysv_fix_order(s)) < 0)
916 if ((r = service_add_bus_name(s)) < 0)
919 if ((r = unit_watch_bus_name(u, s->bus_name)) < 0)
923 if (s->type == SERVICE_NOTIFY && s->notify_access == NOTIFY_NONE)
924 s->notify_access = NOTIFY_MAIN;
926 if (s->type == SERVICE_DBUS || s->bus_name)
927 if ((r = unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_REQUIRES, SPECIAL_DBUS_TARGET, NULL, true)) < 0)
930 if (s->meta.default_dependencies)
931 if ((r = service_add_default_dependencies(s)) < 0)
935 return service_verify(s);
938 static void service_dump(Unit *u, FILE *f, const char *prefix) {
940 ServiceExecCommand c;
941 Service *s = SERVICE(u);
947 p2 = strappend(prefix, "\t");
948 prefix2 = p2 ? p2 : prefix;
951 "%sService State: %s\n"
952 "%sPermissionsStartOnly: %s\n"
953 "%sRootDirectoryStartOnly: %s\n"
954 "%sRemainAfterExit: %s\n"
957 "%sNotifyAccess: %s\n",
958 prefix, service_state_to_string(s->state),
959 prefix, yes_no(s->permissions_start_only),
960 prefix, yes_no(s->root_directory_start_only),
961 prefix, yes_no(s->remain_after_exit),
962 prefix, service_type_to_string(s->type),
963 prefix, service_restart_to_string(s->restart),
964 prefix, notify_access_to_string(s->notify_access));
966 if (s->control_pid > 0)
968 "%sControl PID: %lu\n",
969 prefix, (unsigned long) s->control_pid);
974 prefix, (unsigned long) s->main_pid);
979 prefix, s->pid_file);
984 "%sBus Name Good: %s\n",
986 prefix, yes_no(s->bus_name_good));
988 exec_context_dump(&s->exec_context, f, prefix);
990 for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
992 if (!s->exec_command[c])
995 fprintf(f, "%s-> %s:\n",
996 prefix, service_exec_command_to_string(c));
998 exec_command_dump_list(s->exec_command[c], f, prefix2);
1003 "%sSysV Init Script Path: %s\n"
1004 "%sSysV Init Script has LSB Header: %s\n",
1005 prefix, s->sysv_path,
1006 prefix, yes_no(s->sysv_has_lsb));
1008 if (s->sysv_start_priority >= 0)
1010 "%sSysVStartPriority: %i\n"
1011 "%sSysVEnabled: %s\n",
1012 prefix, s->sysv_start_priority,
1013 prefix, yes_no(s->sysv_enabled));
1015 if (s->sysv_runlevels)
1016 fprintf(f, "%sSysVRunLevels: %s\n",
1017 prefix, s->sysv_runlevels);
1020 fprintf(f, "%sStatus Text: %s\n",
1021 prefix, s->status_text);
1026 static int service_load_pid_file(Service *s) {
1033 if (s->main_pid_known)
1036 assert(s->main_pid <= 0);
1041 if ((r = read_one_line_file(s->pid_file, &k)) < 0)
1044 r = parse_pid(k, &pid);
1050 if (kill(pid, 0) < 0 && errno != EPERM) {
1051 log_warning("PID %lu read from file %s does not exist. Your service or init script might be broken.",
1052 (unsigned long) pid, s->pid_file);
1056 if ((r = service_set_main_pid(s, pid)) < 0)
1059 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1060 /* FIXME: we need to do something here */
1066 static int service_get_sockets(Service *s, Set **_set) {
1075 if (s->socket_fd >= 0)
1078 /* Collects all Socket objects that belong to this
1079 * service. Note that a service might have multiple sockets
1080 * via multiple names. */
1082 if (!(set = set_new(NULL, NULL)))
1085 SET_FOREACH(t, s->meta.names, i) {
1089 /* Look for all socket objects that go by any of our
1090 * units and collect their fds */
1092 if (!(k = unit_name_change_suffix(t, ".socket"))) {
1097 p = manager_get_unit(s->meta.manager, k);
1103 if ((r = set_put(set, p)) < 0)
1115 static int service_notify_sockets_dead(Service *s) {
1123 if (s->socket_fd >= 0)
1126 /* Notifies all our sockets when we die */
1127 if ((r = service_get_sockets(s, &set)) < 0)
1130 SET_FOREACH(sock, set, i)
1131 socket_notify_service_dead(sock);
1138 static void service_set_state(Service *s, ServiceState state) {
1139 ServiceState old_state;
1142 old_state = s->state;
1145 if (state != SERVICE_START_PRE &&
1146 state != SERVICE_START &&
1147 state != SERVICE_START_POST &&
1148 state != SERVICE_RELOAD &&
1149 state != SERVICE_STOP &&
1150 state != SERVICE_STOP_SIGTERM &&
1151 state != SERVICE_STOP_SIGKILL &&
1152 state != SERVICE_STOP_POST &&
1153 state != SERVICE_FINAL_SIGTERM &&
1154 state != SERVICE_FINAL_SIGKILL &&
1155 state != SERVICE_AUTO_RESTART)
1156 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1158 if (state != SERVICE_START &&
1159 state != SERVICE_START_POST &&
1160 state != SERVICE_RUNNING &&
1161 state != SERVICE_RELOAD &&
1162 state != SERVICE_STOP &&
1163 state != SERVICE_STOP_SIGTERM &&
1164 state != SERVICE_STOP_SIGKILL)
1165 service_unwatch_main_pid(s);
1167 if (state != SERVICE_START_PRE &&
1168 state != SERVICE_START &&
1169 state != SERVICE_START_POST &&
1170 state != SERVICE_RELOAD &&
1171 state != SERVICE_STOP &&
1172 state != SERVICE_STOP_SIGTERM &&
1173 state != SERVICE_STOP_SIGKILL &&
1174 state != SERVICE_STOP_POST &&
1175 state != SERVICE_FINAL_SIGTERM &&
1176 state != SERVICE_FINAL_SIGKILL) {
1177 service_unwatch_control_pid(s);
1178 s->control_command = NULL;
1179 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1182 if (state == SERVICE_DEAD ||
1183 state == SERVICE_STOP ||
1184 state == SERVICE_STOP_SIGTERM ||
1185 state == SERVICE_STOP_SIGKILL ||
1186 state == SERVICE_STOP_POST ||
1187 state == SERVICE_FINAL_SIGTERM ||
1188 state == SERVICE_FINAL_SIGKILL ||
1189 state == SERVICE_MAINTENANCE ||
1190 state == SERVICE_AUTO_RESTART)
1191 service_notify_sockets_dead(s);
1193 if (state != SERVICE_START_PRE &&
1194 state != SERVICE_START &&
1195 state != SERVICE_START_POST &&
1196 state != SERVICE_RUNNING &&
1197 state != SERVICE_RELOAD &&
1198 state != SERVICE_STOP &&
1199 state != SERVICE_STOP_SIGTERM &&
1200 state != SERVICE_STOP_SIGKILL &&
1201 state != SERVICE_STOP_POST &&
1202 state != SERVICE_FINAL_SIGTERM &&
1203 state != SERVICE_FINAL_SIGKILL &&
1204 !(state == SERVICE_DEAD && s->meta.job)) {
1205 service_close_socket_fd(s);
1206 service_connection_unref(s);
1209 /* For the inactive states unit_notify() will trim the cgroup,
1210 * but for exit we have to do that ourselves... */
1211 if (state == SERVICE_EXITED)
1212 cgroup_bonding_trim_list(s->meta.cgroup_bondings, true);
1214 if (old_state != state)
1215 log_debug("%s changed %s -> %s", s->meta.id, service_state_to_string(old_state), service_state_to_string(state));
1217 unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state]);
1220 static int service_coldplug(Unit *u) {
1221 Service *s = SERVICE(u);
1225 assert(s->state == SERVICE_DEAD);
1227 if (s->deserialized_state != s->state) {
1229 if (s->deserialized_state == SERVICE_START_PRE ||
1230 s->deserialized_state == SERVICE_START ||
1231 s->deserialized_state == SERVICE_START_POST ||
1232 s->deserialized_state == SERVICE_RELOAD ||
1233 s->deserialized_state == SERVICE_STOP ||
1234 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1235 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1236 s->deserialized_state == SERVICE_STOP_POST ||
1237 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1238 s->deserialized_state == SERVICE_FINAL_SIGKILL ||
1239 s->deserialized_state == SERVICE_AUTO_RESTART) {
1241 if (s->deserialized_state == SERVICE_AUTO_RESTART || s->timeout_usec > 0) {
1244 k = s->deserialized_state == SERVICE_AUTO_RESTART ? s->restart_usec : s->timeout_usec;
1246 if ((r = unit_watch_timer(UNIT(s), k, &s->timer_watch)) < 0)
1251 if ((s->deserialized_state == SERVICE_START &&
1252 (s->type == SERVICE_FORKING ||
1253 s->type == SERVICE_DBUS ||
1254 s->type == SERVICE_ONESHOT ||
1255 s->type == SERVICE_NOTIFY)) ||
1256 s->deserialized_state == SERVICE_START_POST ||
1257 s->deserialized_state == SERVICE_RUNNING ||
1258 s->deserialized_state == SERVICE_RELOAD ||
1259 s->deserialized_state == SERVICE_STOP ||
1260 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1261 s->deserialized_state == SERVICE_STOP_SIGKILL)
1262 if (s->main_pid > 0)
1263 if ((r = unit_watch_pid(UNIT(s), s->main_pid)) < 0)
1266 if (s->deserialized_state == SERVICE_START_PRE ||
1267 s->deserialized_state == SERVICE_START ||
1268 s->deserialized_state == SERVICE_START_POST ||
1269 s->deserialized_state == SERVICE_RELOAD ||
1270 s->deserialized_state == SERVICE_STOP ||
1271 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1272 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1273 s->deserialized_state == SERVICE_STOP_POST ||
1274 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1275 s->deserialized_state == SERVICE_FINAL_SIGKILL)
1276 if (s->control_pid > 0)
1277 if ((r = unit_watch_pid(UNIT(s), s->control_pid)) < 0)
1280 service_set_state(s, s->deserialized_state);
1286 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
1290 unsigned rn_fds = 0;
1298 if (s->socket_fd >= 0)
1301 if ((r = service_get_sockets(s, &set)) < 0)
1304 SET_FOREACH(sock, set, i) {
1308 if ((r = socket_collect_fds(sock, &cfds, &cn_fds)) < 0)
1320 if (!(t = new(int, rn_fds+cn_fds))) {
1326 memcpy(t, rfds, rn_fds);
1327 memcpy(t+rn_fds, cfds, cn_fds);
1332 rn_fds = rn_fds+cn_fds;
1350 static int service_spawn(
1355 bool apply_permissions,
1357 bool apply_tty_stdin,
1358 bool set_notify_socket,
1363 int *fds = NULL, *fdsbuf = NULL;
1364 unsigned n_fds = 0, n_env = 0;
1365 char **argv = NULL, **final_env = NULL, **our_env = NULL;
1372 s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1373 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1374 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
1376 if (s->socket_fd >= 0) {
1377 fds = &s->socket_fd;
1380 if ((r = service_collect_fds(s, &fdsbuf, &n_fds)) < 0)
1387 if (timeout && s->timeout_usec) {
1388 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1391 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1393 if (!(argv = unit_full_printf_strv(UNIT(s), c->argv))) {
1398 if (!(our_env = new0(char*, 3))) {
1403 if (set_notify_socket)
1404 if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=@%s", s->meta.manager->notify_socket) < 0) {
1409 if (s->main_pid > 0)
1410 if (asprintf(our_env + n_env++, "MAINPID=%lu", (unsigned long) s->main_pid) < 0) {
1415 if (!(final_env = strv_env_merge(2,
1416 s->meta.manager->environment,
1431 s->meta.manager->confirm_spawn,
1432 s->meta.cgroup_bondings,
1439 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1440 /* FIXME: we need to do something here */
1446 strv_free(final_env);
1456 strv_free(final_env);
1459 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1464 static int main_pid_good(Service *s) {
1467 /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1470 /* If we know the pid file, then lets just check if it is
1472 if (s->main_pid_known)
1473 return s->main_pid > 0;
1475 /* We don't know the pid */
1479 static int control_pid_good(Service *s) {
1482 return s->control_pid > 0;
1485 static int cgroup_good(Service *s) {
1490 if ((r = cgroup_bonding_is_empty_list(s->meta.cgroup_bondings)) < 0)
1496 static void service_enter_dead(Service *s, bool success, bool allow_restart) {
1503 if (allow_restart &&
1504 !s->forbid_restart &&
1505 (s->restart == SERVICE_RESTART_ALWAYS ||
1506 (s->restart == SERVICE_RESTART_ON_SUCCESS && !s->failure))) {
1508 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
1511 service_set_state(s, SERVICE_AUTO_RESTART);
1513 service_set_state(s, s->failure ? SERVICE_MAINTENANCE : SERVICE_DEAD);
1515 s->forbid_restart = false;
1520 log_warning("%s failed to run install restart timer: %s", s->meta.id, strerror(-r));
1521 service_enter_dead(s, false, false);
1524 static void service_enter_signal(Service *s, ServiceState state, bool success);
1526 static void service_enter_stop_post(Service *s, bool success) {
1533 service_unwatch_control_pid(s);
1535 s->control_command_id = SERVICE_EXEC_STOP_POST;
1536 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST])) {
1537 if ((r = service_spawn(s,
1541 !s->permissions_start_only,
1542 !s->root_directory_start_only,
1545 &s->control_pid)) < 0)
1549 service_set_state(s, SERVICE_STOP_POST);
1551 service_enter_signal(s, SERVICE_FINAL_SIGTERM, true);
1556 log_warning("%s failed to run 'stop-post' task: %s", s->meta.id, strerror(-r));
1557 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1560 static void service_enter_signal(Service *s, ServiceState state, bool success) {
1569 if (s->exec_context.kill_mode != KILL_NONE) {
1570 int sig = (state == SERVICE_STOP_SIGTERM || state == SERVICE_FINAL_SIGTERM) ? s->exec_context.kill_signal : SIGKILL;
1572 if (s->exec_context.kill_mode == KILL_CONTROL_GROUP) {
1574 if ((r = cgroup_bonding_kill_list(s->meta.cgroup_bondings, sig)) < 0) {
1575 if (r != -EAGAIN && r != -ESRCH)
1584 if (s->main_pid > 0) {
1585 if (kill(s->exec_context.kill_mode == KILL_PROCESS ? s->main_pid : -s->main_pid, sig) < 0 && errno != ESRCH)
1591 if (s->control_pid > 0) {
1592 if (kill(s->exec_context.kill_mode == KILL_PROCESS ? s->control_pid : -s->control_pid, sig) < 0 && errno != ESRCH)
1603 if (sent && (s->main_pid > 0 || s->control_pid > 0)) {
1604 if (s->timeout_usec > 0)
1605 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1608 service_set_state(s, state);
1609 } else if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1610 service_enter_stop_post(s, true);
1612 service_enter_dead(s, true, true);
1617 log_warning("%s failed to kill processes: %s", s->meta.id, strerror(-r));
1619 if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1620 service_enter_stop_post(s, false);
1622 service_enter_dead(s, false, true);
1625 static void service_enter_stop(Service *s, bool success) {
1633 service_unwatch_control_pid(s);
1635 s->control_command_id = SERVICE_EXEC_STOP;
1636 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP])) {
1637 if ((r = service_spawn(s,
1641 !s->permissions_start_only,
1642 !s->root_directory_start_only,
1645 &s->control_pid)) < 0)
1648 service_set_state(s, SERVICE_STOP);
1650 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
1655 log_warning("%s failed to run 'stop' task: %s", s->meta.id, strerror(-r));
1656 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1659 static void service_enter_running(Service *s, bool success) {
1660 int main_pid_ok, cgroup_ok;
1666 main_pid_ok = main_pid_good(s);
1667 cgroup_ok = cgroup_good(s);
1669 if ((main_pid_ok > 0 || (main_pid_ok < 0 && cgroup_ok != 0)) &&
1670 (s->bus_name_good || s->type != SERVICE_DBUS))
1671 service_set_state(s, SERVICE_RUNNING);
1672 else if (s->remain_after_exit)
1673 service_set_state(s, SERVICE_EXITED);
1675 service_enter_stop(s, true);
1678 static void service_enter_start_post(Service *s) {
1682 service_unwatch_control_pid(s);
1684 s->control_command_id = SERVICE_EXEC_START_POST;
1685 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_POST])) {
1686 if ((r = service_spawn(s,
1690 !s->permissions_start_only,
1691 !s->root_directory_start_only,
1694 &s->control_pid)) < 0)
1697 service_set_state(s, SERVICE_START_POST);
1699 service_enter_running(s, true);
1704 log_warning("%s failed to run 'start-post' task: %s", s->meta.id, strerror(-r));
1705 service_enter_stop(s, false);
1708 static void service_enter_start(Service *s) {
1714 assert(s->exec_command[SERVICE_EXEC_START]);
1715 assert(!s->exec_command[SERVICE_EXEC_START]->command_next || s->type == SERVICE_ONESHOT);
1717 if (s->type == SERVICE_FORKING)
1718 service_unwatch_control_pid(s);
1720 service_unwatch_main_pid(s);
1722 s->control_command_id = SERVICE_EXEC_START;
1723 s->control_command = s->exec_command[SERVICE_EXEC_START];
1725 if ((r = service_spawn(s,
1727 s->type == SERVICE_FORKING || s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY,
1732 s->notify_access != NOTIFY_NONE,
1736 if (s->type == SERVICE_SIMPLE) {
1737 /* For simple services we immediately start
1738 * the START_POST binaries. */
1740 service_set_main_pid(s, pid);
1741 service_enter_start_post(s);
1743 } else if (s->type == SERVICE_FORKING) {
1745 /* For forking services we wait until the start
1746 * process exited. */
1748 s->control_pid = pid;
1749 service_set_state(s, SERVICE_START);
1751 } else if (s->type == SERVICE_ONESHOT ||
1752 s->type == SERVICE_DBUS ||
1753 s->type == SERVICE_NOTIFY) {
1755 /* For oneshot services we wait until the start
1756 * process exited, too, but it is our main process. */
1758 /* For D-Bus services we know the main pid right away,
1759 * but wait for the bus name to appear on the
1760 * bus. Notify services are similar. */
1762 service_set_main_pid(s, pid);
1763 service_set_state(s, SERVICE_START);
1765 assert_not_reached("Unknown service type");
1770 log_warning("%s failed to run 'start' task: %s", s->meta.id, strerror(-r));
1771 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1774 static void service_enter_start_pre(Service *s) {
1779 service_unwatch_control_pid(s);
1781 s->control_command_id = SERVICE_EXEC_START_PRE;
1782 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_PRE])) {
1783 if ((r = service_spawn(s,
1787 !s->permissions_start_only,
1788 !s->root_directory_start_only,
1791 &s->control_pid)) < 0)
1794 service_set_state(s, SERVICE_START_PRE);
1796 service_enter_start(s);
1801 log_warning("%s failed to run 'start-pre' task: %s", s->meta.id, strerror(-r));
1802 service_enter_dead(s, false, true);
1805 static void service_enter_restart(Service *s) {
1810 dbus_error_init(&error);
1812 service_enter_dead(s, true, false);
1814 if ((r = manager_add_job(s->meta.manager, JOB_START, UNIT(s), JOB_FAIL, false, NULL, NULL)) < 0)
1817 log_debug("%s scheduled restart job.", s->meta.id);
1821 log_warning("%s failed to schedule restart job: %s", s->meta.id, bus_error(&error, -r));
1822 service_enter_dead(s, false, false);
1824 dbus_error_free(&error);
1827 static void service_enter_reload(Service *s) {
1832 service_unwatch_control_pid(s);
1834 s->control_command_id = SERVICE_EXEC_RELOAD;
1835 if ((s->control_command = s->exec_command[SERVICE_EXEC_RELOAD])) {
1836 if ((r = service_spawn(s,
1840 !s->permissions_start_only,
1841 !s->root_directory_start_only,
1844 &s->control_pid)) < 0)
1847 service_set_state(s, SERVICE_RELOAD);
1849 service_enter_running(s, true);
1854 log_warning("%s failed to run 'reload' task: %s", s->meta.id, strerror(-r));
1855 service_enter_stop(s, false);
1858 static void service_run_next_control(Service *s, bool success) {
1862 assert(s->control_command);
1863 assert(s->control_command->command_next);
1868 assert(s->control_command_id != SERVICE_EXEC_START);
1870 s->control_command = s->control_command->command_next;
1871 service_unwatch_control_pid(s);
1873 if ((r = service_spawn(s,
1877 !s->permissions_start_only,
1878 !s->root_directory_start_only,
1879 s->control_command_id == SERVICE_EXEC_START_PRE ||
1880 s->control_command_id == SERVICE_EXEC_STOP_POST,
1882 &s->control_pid)) < 0)
1888 log_warning("%s failed to run next control task: %s", s->meta.id, strerror(-r));
1890 if (s->state == SERVICE_START_PRE)
1891 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1892 else if (s->state == SERVICE_STOP)
1893 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1894 else if (s->state == SERVICE_STOP_POST)
1895 service_enter_dead(s, false, true);
1897 service_enter_stop(s, false);
1900 static void service_run_next_main(Service *s, bool success) {
1905 assert(s->control_command);
1906 assert(s->control_command->command_next);
1911 assert(s->control_command_id == SERVICE_EXEC_START);
1912 assert(s->type == SERVICE_ONESHOT);
1914 s->control_command = s->control_command->command_next;
1915 service_unwatch_main_pid(s);
1917 if ((r = service_spawn(s,
1924 s->notify_access != NOTIFY_NONE,
1928 service_set_main_pid(s, pid);
1933 log_warning("%s failed to run next main task: %s", s->meta.id, strerror(-r));
1934 service_enter_stop(s, false);
1937 static int service_start(Unit *u) {
1938 Service *s = SERVICE(u);
1942 /* We cannot fulfill this request right now, try again later
1944 if (s->state == SERVICE_STOP ||
1945 s->state == SERVICE_STOP_SIGTERM ||
1946 s->state == SERVICE_STOP_SIGKILL ||
1947 s->state == SERVICE_STOP_POST ||
1948 s->state == SERVICE_FINAL_SIGTERM ||
1949 s->state == SERVICE_FINAL_SIGKILL)
1952 /* Already on it! */
1953 if (s->state == SERVICE_START_PRE ||
1954 s->state == SERVICE_START ||
1955 s->state == SERVICE_START_POST)
1958 assert(s->state == SERVICE_DEAD || s->state == SERVICE_MAINTENANCE || s->state == SERVICE_AUTO_RESTART);
1960 /* Make sure we don't enter a busy loop of some kind. */
1961 if (!ratelimit_test(&s->ratelimit)) {
1962 log_warning("%s start request repeated too quickly, refusing to start.", u->meta.id);
1966 if ((s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1967 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1968 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) &&
1970 log_warning("%s can only be started with a per-connection socket.", u->meta.id);
1975 s->main_pid_known = false;
1976 s->forbid_restart = false;
1978 service_enter_start_pre(s);
1982 static int service_stop(Unit *u) {
1983 Service *s = SERVICE(u);
1987 /* This is a user request, so don't do restarts on this
1989 s->forbid_restart = true;
1992 if (s->state == SERVICE_STOP ||
1993 s->state == SERVICE_STOP_SIGTERM ||
1994 s->state == SERVICE_STOP_SIGKILL ||
1995 s->state == SERVICE_STOP_POST ||
1996 s->state == SERVICE_FINAL_SIGTERM ||
1997 s->state == SERVICE_FINAL_SIGKILL)
2000 /* Don't allow a restart */
2001 if (s->state == SERVICE_AUTO_RESTART) {
2002 service_set_state(s, SERVICE_DEAD);
2006 /* If there's already something running we go directly into
2008 if (s->state == SERVICE_START_PRE ||
2009 s->state == SERVICE_START ||
2010 s->state == SERVICE_START_POST ||
2011 s->state == SERVICE_RELOAD) {
2012 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
2016 assert(s->state == SERVICE_RUNNING ||
2017 s->state == SERVICE_EXITED);
2019 service_enter_stop(s, true);
2023 static int service_reload(Unit *u) {
2024 Service *s = SERVICE(u);
2028 assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
2030 service_enter_reload(s);
2034 static bool service_can_reload(Unit *u) {
2035 Service *s = SERVICE(u);
2039 return !!s->exec_command[SERVICE_EXEC_RELOAD];
2042 static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
2043 Service *s = SERVICE(u);
2049 unit_serialize_item(u, f, "state", service_state_to_string(s->state));
2050 unit_serialize_item(u, f, "failure", yes_no(s->failure));
2052 if (s->control_pid > 0)
2053 unit_serialize_item_format(u, f, "control-pid", "%lu", (unsigned long) s->control_pid);
2055 if (s->main_pid_known && s->main_pid > 0)
2056 unit_serialize_item_format(u, f, "main-pid", "%lu", (unsigned long) s->main_pid);
2058 unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
2061 unit_serialize_item(u, f, "status-text", s->status_text);
2063 /* There's a minor uncleanliness here: if there are multiple
2064 * commands attached here, we will start from the first one
2066 if (s->control_command_id >= 0)
2067 unit_serialize_item(u, f, "control-command", service_exec_command_to_string(s->control_command_id));
2069 if (s->socket_fd >= 0) {
2072 if ((copy = fdset_put_dup(fds, s->socket_fd)) < 0)
2075 unit_serialize_item_format(u, f, "socket-fd", "%i", copy);
2078 if (s->main_exec_status.pid > 0) {
2079 unit_serialize_item_format(u, f, "main-exec-status-pid", "%lu", (unsigned long) s->main_exec_status.pid);
2081 if (s->main_exec_status.start_timestamp.realtime > 0) {
2082 unit_serialize_item_format(u, f, "main-exec-status-start-realtime",
2083 "%llu", (unsigned long long) s->main_exec_status.start_timestamp.realtime);
2085 unit_serialize_item_format(u, f, "main-exec-status-start-monotonic",
2086 "%llu", (unsigned long long) s->main_exec_status.start_timestamp.monotonic);
2089 if (s->main_exec_status.exit_timestamp.realtime > 0) {
2090 unit_serialize_item_format(u, f, "main-exec-status-exit-realtime",
2091 "%llu", (unsigned long long) s->main_exec_status.exit_timestamp.realtime);
2092 unit_serialize_item_format(u, f, "main-exec-status-exit-monotonic",
2093 "%llu", (unsigned long long) s->main_exec_status.exit_timestamp.monotonic);
2095 unit_serialize_item_format(u, f, "main-exec-status-code", "%i", s->main_exec_status.code);
2096 unit_serialize_item_format(u, f, "main-exec-status-status", "%i", s->main_exec_status.status);
2103 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
2104 Service *s = SERVICE(u);
2111 if (streq(key, "state")) {
2114 if ((state = service_state_from_string(value)) < 0)
2115 log_debug("Failed to parse state value %s", value);
2117 s->deserialized_state = state;
2118 } else if (streq(key, "failure")) {
2121 if ((b = parse_boolean(value)) < 0)
2122 log_debug("Failed to parse failure value %s", value);
2124 s->failure = b || s->failure;
2125 } else if (streq(key, "control-pid")) {
2128 if (parse_pid(value, &pid) < 0)
2129 log_debug("Failed to parse control-pid value %s", value);
2131 s->control_pid = pid;
2132 } else if (streq(key, "main-pid")) {
2135 if (parse_pid(value, &pid) < 0)
2136 log_debug("Failed to parse main-pid value %s", value);
2138 service_set_main_pid(s, (pid_t) pid);
2139 } else if (streq(key, "main-pid-known")) {
2142 if ((b = parse_boolean(value)) < 0)
2143 log_debug("Failed to parse main-pid-known value %s", value);
2145 s->main_pid_known = b;
2146 } else if (streq(key, "status-text")) {
2149 if ((t = strdup(value))) {
2150 free(s->status_text);
2154 } else if (streq(key, "control-command")) {
2155 ServiceExecCommand id;
2157 if ((id = service_exec_command_from_string(value)) < 0)
2158 log_debug("Failed to parse exec-command value %s", value);
2160 s->control_command_id = id;
2161 s->control_command = s->exec_command[id];
2163 } else if (streq(key, "socket-fd")) {
2166 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2167 log_debug("Failed to parse socket-fd value %s", value);
2170 if (s->socket_fd >= 0)
2171 close_nointr_nofail(s->socket_fd);
2172 s->socket_fd = fdset_remove(fds, fd);
2174 } else if (streq(key, "main-exec-status-pid")) {
2177 if (parse_pid(value, &pid) < 0)
2178 log_debug("Failed to parse main-exec-status-pid value %s", value);
2180 s->main_exec_status.pid = pid;
2181 } else if (streq(key, "main-exec-status-code")) {
2184 if (safe_atoi(value, &i) < 0)
2185 log_debug("Failed to parse main-exec-status-code value %s", value);
2187 s->main_exec_status.code = i;
2188 } else if (streq(key, "main-exec-status-status")) {
2191 if (safe_atoi(value, &i) < 0)
2192 log_debug("Failed to parse main-exec-status-status value %s", value);
2194 s->main_exec_status.status = i;
2195 } else if (streq(key, "main-exec-status-start-realtime")) {
2198 if (safe_atou64(value, &k) < 0)
2199 log_debug("Failed to parse main-exec-status-start-realtime value %s", value);
2201 s->main_exec_status.start_timestamp.realtime = (usec_t) k;
2202 } else if (streq(key, "main-exec-status-start-monotonic")) {
2205 if (safe_atou64(value, &k) < 0)
2206 log_debug("Failed to parse main-exec-status-start-monotonic value %s", value);
2208 s->main_exec_status.start_timestamp.monotonic = (usec_t) k;
2209 } else if (streq(key, "main-exec-status-exit-realtime")) {
2212 if (safe_atou64(value, &k) < 0)
2213 log_debug("Failed to parse main-exec-status-exit-realtime value %s", value);
2215 s->main_exec_status.exit_timestamp.realtime = (usec_t) k;
2216 } else if (streq(key, "main-exec-status-exit-monotonic")) {
2219 if (safe_atou64(value, &k) < 0)
2220 log_debug("Failed to parse main-exec-status-exit-monotonic value %s", value);
2222 s->main_exec_status.exit_timestamp.monotonic = (usec_t) k;
2224 log_debug("Unknown serialization key '%s'", key);
2229 static UnitActiveState service_active_state(Unit *u) {
2232 return state_translation_table[SERVICE(u)->state];
2235 static const char *service_sub_state_to_string(Unit *u) {
2238 return service_state_to_string(SERVICE(u)->state);
2241 static bool service_check_gc(Unit *u) {
2242 Service *s = SERVICE(u);
2246 return !!s->sysv_path;
2249 static bool service_check_snapshot(Unit *u) {
2250 Service *s = SERVICE(u);
2254 return !s->got_socket_fd;
2257 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2258 Service *s = SERVICE(u);
2264 success = is_clean_exit(code, status);
2266 if (s->main_pid == pid) {
2269 exec_status_exit(&s->main_exec_status, pid, code, status);
2271 if (s->type != SERVICE_FORKING && s->control_command) {
2272 s->control_command->exec_status = s->main_exec_status;
2274 if (s->control_command->ignore)
2278 log_full(success ? LOG_DEBUG : LOG_NOTICE,
2279 "%s: main process exited, code=%s, status=%i", u->meta.id, sigchld_code_to_string(code), status);
2280 s->failure = s->failure || !success;
2282 if (s->control_command &&
2283 s->control_command->command_next &&
2286 /* There is another command to *
2287 * execute, so let's do that. */
2289 log_debug("%s running next main command for state %s", u->meta.id, service_state_to_string(s->state));
2290 service_run_next_main(s, success);
2294 /* The service exited, so the service is officially
2297 s->control_command = NULL;
2298 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2302 case SERVICE_START_POST:
2303 case SERVICE_RELOAD:
2305 /* Need to wait until the operation is
2310 if (s->type == SERVICE_ONESHOT) {
2311 /* This was our main goal, so let's go on */
2313 service_enter_start_post(s);
2315 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2318 assert(s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY);
2323 case SERVICE_RUNNING:
2324 service_enter_running(s, success);
2327 case SERVICE_STOP_SIGTERM:
2328 case SERVICE_STOP_SIGKILL:
2330 if (!control_pid_good(s))
2331 service_enter_stop_post(s, success);
2333 /* If there is still a control process, wait for that first */
2337 assert_not_reached("Uh, main process died at wrong time.");
2341 } else if (s->control_pid == pid) {
2345 if (s->control_command) {
2346 exec_status_exit(&s->control_command->exec_status, pid, code, status);
2348 if (s->control_command->ignore)
2352 log_full(success ? LOG_DEBUG : LOG_NOTICE,
2353 "%s: control process exited, code=%s status=%i", u->meta.id, sigchld_code_to_string(code), status);
2354 s->failure = s->failure || !success;
2356 if (s->control_command &&
2357 s->control_command->command_next &&
2360 /* There is another command to *
2361 * execute, so let's do that. */
2363 log_debug("%s running next control command for state %s", u->meta.id, service_state_to_string(s->state));
2364 service_run_next_control(s, success);
2367 /* No further commands for this step, so let's
2368 * figure out what to do next */
2370 s->control_command = NULL;
2371 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2373 log_debug("%s got final SIGCHLD for state %s", u->meta.id, service_state_to_string(s->state));
2377 case SERVICE_START_PRE:
2379 service_enter_start(s);
2381 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2385 assert(s->type == SERVICE_FORKING);
2387 /* Let's try to load the pid
2388 * file here if we can. We
2389 * ignore the return value,
2390 * since the PID file might
2391 * actually be created by a
2392 * START_POST script */
2396 service_load_pid_file(s);
2398 service_enter_start_post(s);
2400 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2404 case SERVICE_START_POST:
2405 if (success && s->pid_file && !s->main_pid_known) {
2408 /* Hmm, let's see if we can
2409 * load the pid now after the
2410 * start-post scripts got
2413 if ((r = service_load_pid_file(s)) < 0)
2414 log_warning("%s: failed to load PID file %s: %s", s->meta.id, s->pid_file, strerror(-r));
2419 case SERVICE_RELOAD:
2421 service_enter_running(s, true);
2423 service_enter_stop(s, false);
2428 service_enter_signal(s, SERVICE_STOP_SIGTERM, success);
2431 case SERVICE_STOP_SIGTERM:
2432 case SERVICE_STOP_SIGKILL:
2433 if (main_pid_good(s) <= 0)
2434 service_enter_stop_post(s, success);
2436 /* If there is still a service
2437 * process around, wait until
2438 * that one quit, too */
2441 case SERVICE_STOP_POST:
2442 case SERVICE_FINAL_SIGTERM:
2443 case SERVICE_FINAL_SIGKILL:
2444 service_enter_dead(s, success, true);
2448 assert_not_reached("Uh, control process died at wrong time.");
2454 static void service_timer_event(Unit *u, uint64_t elapsed, Watch* w) {
2455 Service *s = SERVICE(u);
2458 assert(elapsed == 1);
2460 assert(w == &s->timer_watch);
2464 case SERVICE_START_PRE:
2466 log_warning("%s operation timed out. Terminating.", u->meta.id);
2467 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2470 case SERVICE_START_POST:
2471 case SERVICE_RELOAD:
2472 log_warning("%s operation timed out. Stopping.", u->meta.id);
2473 service_enter_stop(s, false);
2477 log_warning("%s stopping timed out. Terminating.", u->meta.id);
2478 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
2481 case SERVICE_STOP_SIGTERM:
2482 log_warning("%s stopping timed out. Killing.", u->meta.id);
2483 service_enter_signal(s, SERVICE_STOP_SIGKILL, false);
2486 case SERVICE_STOP_SIGKILL:
2487 /* Uh, wie sent a SIGKILL and it is still not gone?
2488 * Must be something we cannot kill, so let's just be
2489 * weirded out and continue */
2491 log_warning("%s still around after SIGKILL. Ignoring.", u->meta.id);
2492 service_enter_stop_post(s, false);
2495 case SERVICE_STOP_POST:
2496 log_warning("%s stopping timed out (2). Terminating.", u->meta.id);
2497 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2500 case SERVICE_FINAL_SIGTERM:
2501 log_warning("%s stopping timed out (2). Killing.", u->meta.id);
2502 service_enter_signal(s, SERVICE_FINAL_SIGKILL, false);
2505 case SERVICE_FINAL_SIGKILL:
2506 log_warning("%s still around after SIGKILL (2). Entering maintenance mode.", u->meta.id);
2507 service_enter_dead(s, false, true);
2510 case SERVICE_AUTO_RESTART:
2511 log_info("%s holdoff time over, scheduling restart.", u->meta.id);
2512 service_enter_restart(s);
2516 assert_not_reached("Timeout at wrong time.");
2520 static void service_cgroup_notify_event(Unit *u) {
2521 Service *s = SERVICE(u);
2525 log_debug("%s: cgroup is empty", u->meta.id);
2529 /* Waiting for SIGCHLD is usually more interesting,
2530 * because it includes return codes/signals. Which is
2531 * why we ignore the cgroup events for most cases,
2532 * except when we don't know pid which to expect the
2535 case SERVICE_RUNNING:
2536 service_enter_running(s, true);
2544 static void service_notify_message(Unit *u, pid_t pid, char **tags) {
2545 Service *s = SERVICE(u);
2550 if (s->notify_access == NOTIFY_NONE) {
2551 log_warning("%s: Got notification message from PID %lu, but reception is disabled.",
2552 u->meta.id, (unsigned long) pid);
2556 if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
2557 log_warning("%s: Got notification message from PID %lu, but reception only permitted for PID %lu",
2558 u->meta.id, (unsigned long) pid, (unsigned long) s->main_pid);
2562 log_debug("%s: Got message", u->meta.id);
2564 /* Interpret MAINPID= */
2565 if ((e = strv_find_prefix(tags, "MAINPID=")) &&
2566 (s->state == SERVICE_START ||
2567 s->state == SERVICE_START_POST ||
2568 s->state == SERVICE_RUNNING ||
2569 s->state == SERVICE_RELOAD)) {
2571 if (parse_pid(e + 8, &pid) < 0)
2572 log_warning("Failed to parse notification message %s", e);
2574 log_debug("%s: got %s", u->meta.id, e);
2575 service_set_main_pid(s, pid);
2579 /* Interpret READY= */
2580 if (s->type == SERVICE_NOTIFY &&
2581 s->state == SERVICE_START &&
2582 strv_find(tags, "READY=1")) {
2583 log_debug("%s: got READY=1", u->meta.id);
2585 service_enter_start_post(s);
2588 /* Interpret STATUS= */
2589 if ((e = strv_find_prefix(tags, "STATUS="))) {
2593 if (!(t = strdup(e+7))) {
2594 log_error("Failed to allocate string.");
2598 log_debug("%s: got %s", u->meta.id, e);
2600 free(s->status_text);
2603 free(s->status_text);
2604 s->status_text = NULL;
2610 static int service_enumerate(Manager *m) {
2614 char *path = NULL, *fpath = NULL, *name = NULL;
2619 STRV_FOREACH(p, m->lookup_paths.sysvrcnd_path)
2620 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++) {
2625 if (asprintf(&path, "%s/%s", *p, rcnd_table[i].path) < 0) {
2633 if (!(d = opendir(path))) {
2634 if (errno != ENOENT)
2635 log_warning("opendir() failed on %s: %s", path, strerror(errno));
2640 while ((de = readdir(d))) {
2644 if (ignore_file(de->d_name))
2647 if (de->d_name[0] != 'S' && de->d_name[0] != 'K')
2650 if (strlen(de->d_name) < 4)
2653 a = undecchar(de->d_name[1]);
2654 b = undecchar(de->d_name[2]);
2661 if (asprintf(&fpath, "%s/%s/%s", *p, rcnd_table[i].path, de->d_name) < 0) {
2666 if (access(fpath, X_OK) < 0) {
2668 if (errno != ENOENT)
2669 log_warning("access() failed on %s: %s", fpath, strerror(errno));
2675 if (!(name = sysv_translate_name(de->d_name + 3))) {
2680 if ((r = manager_load_unit_prepare(m, name, NULL, NULL, &service)) < 0) {
2681 log_warning("Failed to prepare unit %s: %s", name, strerror(-r));
2685 if (de->d_name[0] == 'S' &&
2686 (rcnd_table[i].type == RUNLEVEL_UP || rcnd_table[i].type == RUNLEVEL_SYSINIT)) {
2687 SERVICE(service)->sysv_start_priority =
2688 MAX(a*10 + b, SERVICE(service)->sysv_start_priority);
2689 SERVICE(service)->sysv_enabled = true;
2692 manager_dispatch_load_queue(m);
2693 service = unit_follow_merge(service);
2695 /* If this is a native service, rely
2696 * on native ways to pull in a
2697 * service, don't pull it in via sysv
2699 if (service->meta.fragment_path)
2702 if (de->d_name[0] == 'S') {
2704 if ((r = unit_add_two_dependencies_by_name_inverse(service, UNIT_AFTER, UNIT_WANTS, rcnd_table[i].target, NULL, true)) < 0)
2707 } else if (de->d_name[0] == 'K' &&
2708 (rcnd_table[i].type == RUNLEVEL_DOWN ||
2709 rcnd_table[i].type == RUNLEVEL_SYSINIT)) {
2711 /* We honour K links only for
2712 * halt/reboot. For the normal
2713 * runlevels we assume the
2715 * implicitly added by the
2716 * core logic. Also, we don't
2717 * really distuingish here
2718 * between the runlevels 0 and
2719 * 6 and just add them to the
2720 * special shutdown target. On
2721 * SUSE the boot.d/ runlevel
2722 * is also used for shutdown,
2723 * so we add links for that
2724 * too to the shutdown
2727 if ((r = unit_add_two_dependencies_by_name_inverse(service, UNIT_AFTER, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true)) < 0)
2746 static void service_bus_name_owner_change(
2749 const char *old_owner,
2750 const char *new_owner) {
2752 Service *s = SERVICE(u);
2757 assert(streq(s->bus_name, name));
2758 assert(old_owner || new_owner);
2760 if (old_owner && new_owner)
2761 log_debug("%s's D-Bus name %s changed owner from %s to %s", u->meta.id, name, old_owner, new_owner);
2763 log_debug("%s's D-Bus name %s no longer registered by %s", u->meta.id, name, old_owner);
2765 log_debug("%s's D-Bus name %s now registered by %s", u->meta.id, name, new_owner);
2767 s->bus_name_good = !!new_owner;
2769 if (s->type == SERVICE_DBUS) {
2771 /* service_enter_running() will figure out what to
2773 if (s->state == SERVICE_RUNNING)
2774 service_enter_running(s, true);
2775 else if (s->state == SERVICE_START && new_owner)
2776 service_enter_start_post(s);
2778 } else if (new_owner &&
2780 (s->state == SERVICE_START ||
2781 s->state == SERVICE_START_POST ||
2782 s->state == SERVICE_RUNNING ||
2783 s->state == SERVICE_RELOAD)) {
2785 /* Try to acquire PID from bus service */
2786 log_debug("Trying to acquire PID from D-Bus name...");
2788 bus_query_pid(u->meta.manager, name);
2792 static void service_bus_query_pid_done(
2797 Service *s = SERVICE(u);
2802 log_debug("%s's D-Bus name %s is now owned by process %u", u->meta.id, name, (unsigned) pid);
2804 if (s->main_pid <= 0 &&
2805 (s->state == SERVICE_START ||
2806 s->state == SERVICE_START_POST ||
2807 s->state == SERVICE_RUNNING ||
2808 s->state == SERVICE_RELOAD))
2809 service_set_main_pid(s, pid);
2812 int service_set_socket_fd(Service *s, int fd, Socket *sock) {
2816 /* This is called by the socket code when instantiating a new
2817 * service for a stream socket and the socket needs to be
2820 if (s->meta.load_state != UNIT_LOADED)
2823 if (s->socket_fd >= 0)
2826 if (s->state != SERVICE_DEAD)
2830 s->got_socket_fd = true;
2836 static void service_reset_maintenance(Unit *u) {
2837 Service *s = SERVICE(u);
2841 if (s->state == SERVICE_MAINTENANCE)
2842 service_set_state(s, SERVICE_DEAD);
2847 static const char* const service_state_table[_SERVICE_STATE_MAX] = {
2848 [SERVICE_DEAD] = "dead",
2849 [SERVICE_START_PRE] = "start-pre",
2850 [SERVICE_START] = "start",
2851 [SERVICE_START_POST] = "start-post",
2852 [SERVICE_RUNNING] = "running",
2853 [SERVICE_EXITED] = "exited",
2854 [SERVICE_RELOAD] = "reload",
2855 [SERVICE_STOP] = "stop",
2856 [SERVICE_STOP_SIGTERM] = "stop-sigterm",
2857 [SERVICE_STOP_SIGKILL] = "stop-sigkill",
2858 [SERVICE_STOP_POST] = "stop-post",
2859 [SERVICE_FINAL_SIGTERM] = "final-sigterm",
2860 [SERVICE_FINAL_SIGKILL] = "final-sigkill",
2861 [SERVICE_MAINTENANCE] = "maintenance",
2862 [SERVICE_AUTO_RESTART] = "auto-restart",
2865 DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
2867 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
2868 [SERVICE_ONCE] = "once",
2869 [SERVICE_RESTART_ON_SUCCESS] = "restart-on-success",
2870 [SERVICE_RESTART_ALWAYS] = "restart-always",
2873 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
2875 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
2876 [SERVICE_SIMPLE] = "simple",
2877 [SERVICE_FORKING] = "forking",
2878 [SERVICE_ONESHOT] = "oneshot",
2879 [SERVICE_DBUS] = "dbus",
2880 [SERVICE_NOTIFY] = "notify"
2883 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
2885 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
2886 [SERVICE_EXEC_START_PRE] = "ExecStartPre",
2887 [SERVICE_EXEC_START] = "ExecStart",
2888 [SERVICE_EXEC_START_POST] = "ExecStartPost",
2889 [SERVICE_EXEC_RELOAD] = "ExecReload",
2890 [SERVICE_EXEC_STOP] = "ExecStop",
2891 [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
2894 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
2896 static const char* const notify_access_table[_NOTIFY_ACCESS_MAX] = {
2897 [NOTIFY_NONE] = "none",
2898 [NOTIFY_MAIN] = "main",
2899 [NOTIFY_ALL] = "all"
2902 DEFINE_STRING_TABLE_LOOKUP(notify_access, NotifyAccess);
2904 const UnitVTable service_vtable = {
2905 .suffix = ".service",
2906 .show_status = true,
2908 .init = service_init,
2909 .done = service_done,
2910 .load = service_load,
2912 .coldplug = service_coldplug,
2914 .dump = service_dump,
2916 .start = service_start,
2917 .stop = service_stop,
2918 .reload = service_reload,
2920 .can_reload = service_can_reload,
2922 .serialize = service_serialize,
2923 .deserialize_item = service_deserialize_item,
2925 .active_state = service_active_state,
2926 .sub_state_to_string = service_sub_state_to_string,
2928 .check_gc = service_check_gc,
2929 .check_snapshot = service_check_snapshot,
2931 .sigchld_event = service_sigchld_event,
2932 .timer_event = service_timer_event,
2934 .reset_maintenance = service_reset_maintenance,
2936 .cgroup_notify_empty = service_cgroup_notify_event,
2937 .notify_message = service_notify_message,
2939 .bus_name_owner_change = service_bus_name_owner_change,
2940 .bus_query_pid_done = service_bus_query_pid_done,
2942 .bus_message_handler = bus_service_message_handler,
2944 .enumerate = service_enumerate