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 =
712 (s->meta.manager->sysv_console || s->exec_context.std_input == EXEC_INPUT_TTY)
713 ? EXEC_OUTPUT_TTY : EXEC_OUTPUT_NULL;
714 s->exec_context.kill_mode = KILL_PROCESS_GROUP;
716 u->meta.load_state = UNIT_LOADED;
727 static int service_load_sysv_name(Service *s, const char *name) {
733 /* For SysV services we strip the boot. or .sh
734 * prefixes/suffixes. */
735 if (startswith(name, "boot.") ||
736 endswith(name, ".sh.service"))
739 STRV_FOREACH(p, s->meta.manager->lookup_paths.sysvinit_path) {
743 if (asprintf(&path, "%s/%s", *p, name) < 0)
746 assert(endswith(path, ".service"));
747 path[strlen(path)-8] = 0;
749 r = service_load_sysv_path(s, path);
751 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
752 /* Try Debian style xxx.sh source'able init scripts */
754 r = service_load_sysv_path(s, path);
759 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
760 /* Try SUSE style boot.xxx init scripts */
762 if (asprintf(&path, "%s/boot.%s", *p, name) < 0)
765 path[strlen(path)-8] = 0;
766 r = service_load_sysv_path(s, path);
773 if ((s->meta.load_state != UNIT_STUB))
780 static int service_load_sysv(Service *s) {
787 /* Load service data from SysV init scripts, preferably with
790 if (strv_isempty(s->meta.manager->lookup_paths.sysvinit_path))
793 if ((t = s->meta.id))
794 if ((r = service_load_sysv_name(s, t)) < 0)
797 if (s->meta.load_state == UNIT_STUB)
798 SET_FOREACH(t, s->meta.names, i) {
802 if ((r = service_load_sysv_name(s, t)) < 0)
805 if (s->meta.load_state != UNIT_STUB)
812 static int service_add_bus_name(Service *s) {
819 if (asprintf(&n, "dbus-%s.service", s->bus_name) < 0)
822 r = unit_merge_by_name(UNIT(s), n);
828 static int service_verify(Service *s) {
831 if (s->meta.load_state != UNIT_LOADED)
834 if (!s->exec_command[SERVICE_EXEC_START]) {
835 log_error("%s lacks ExecStart setting. Refusing.", s->meta.id);
839 if (s->type != SERVICE_ONESHOT &&
840 s->exec_command[SERVICE_EXEC_START]->command_next) {
841 log_error("%s has more than one ExecStart setting, which is only allowed for Type=oneshot services. Refusing.", s->meta.id);
845 if (s->type == SERVICE_DBUS && !s->bus_name) {
846 log_error("%s is of type D-Bus but no D-Bus service name has been specified. Refusing.", s->meta.id);
850 if (s->exec_context.pam_name && s->exec_context.kill_mode != KILL_CONTROL_GROUP) {
851 log_error("%s has PAM enabled. Kill mode must be set to 'control-group'. Refusing.", s->meta.id);
858 static int service_add_default_dependencies(Service *s) {
863 /* Add a number of automatic dependencies useful for the
864 * majority of services. */
866 /* First, pull in base system */
867 if (s->meta.manager->running_as == MANAGER_SYSTEM) {
869 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_BASIC_TARGET, NULL, true)) < 0)
872 } else if (s->meta.manager->running_as == MANAGER_SESSION) {
874 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SOCKETS_TARGET, NULL, true)) < 0)
878 /* Second, activate normal shutdown */
879 return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTED_BY, SPECIAL_SHUTDOWN_TARGET, NULL, true);
882 static int service_load(Unit *u) {
884 Service *s = SERVICE(u);
888 /* Load a .service file */
889 if ((r = unit_load_fragment(u)) < 0)
892 /* Load a classic init script as a fallback, if we couldn't find anything */
893 if (u->meta.load_state == UNIT_STUB)
894 if ((r = service_load_sysv(s)) < 0)
897 /* Still nothing found? Then let's give up */
898 if (u->meta.load_state == UNIT_STUB)
901 /* We were able to load something, then let's add in the
902 * dropin directories. */
903 if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
906 /* This is a new unit? Then let's add in some extras */
907 if (u->meta.load_state == UNIT_LOADED) {
908 if ((r = unit_add_exec_dependencies(u, &s->exec_context)) < 0)
911 if ((r = unit_add_default_cgroup(u)) < 0)
914 if ((r = sysv_fix_order(s)) < 0)
918 if ((r = service_add_bus_name(s)) < 0)
921 if ((r = unit_watch_bus_name(u, s->bus_name)) < 0)
925 if (s->type == SERVICE_NOTIFY && s->notify_access == NOTIFY_NONE)
926 s->notify_access = NOTIFY_MAIN;
928 if (s->type == SERVICE_DBUS || s->bus_name)
929 if ((r = unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_REQUIRES, SPECIAL_DBUS_TARGET, NULL, true)) < 0)
932 if (s->meta.default_dependencies)
933 if ((r = service_add_default_dependencies(s)) < 0)
937 return service_verify(s);
940 static void service_dump(Unit *u, FILE *f, const char *prefix) {
942 ServiceExecCommand c;
943 Service *s = SERVICE(u);
949 p2 = strappend(prefix, "\t");
950 prefix2 = p2 ? p2 : prefix;
953 "%sService State: %s\n"
954 "%sPermissionsStartOnly: %s\n"
955 "%sRootDirectoryStartOnly: %s\n"
956 "%sRemainAfterExit: %s\n"
959 "%sNotifyAccess: %s\n",
960 prefix, service_state_to_string(s->state),
961 prefix, yes_no(s->permissions_start_only),
962 prefix, yes_no(s->root_directory_start_only),
963 prefix, yes_no(s->remain_after_exit),
964 prefix, service_type_to_string(s->type),
965 prefix, service_restart_to_string(s->restart),
966 prefix, notify_access_to_string(s->notify_access));
968 if (s->control_pid > 0)
970 "%sControl PID: %lu\n",
971 prefix, (unsigned long) s->control_pid);
976 prefix, (unsigned long) s->main_pid);
981 prefix, s->pid_file);
986 "%sBus Name Good: %s\n",
988 prefix, yes_no(s->bus_name_good));
990 exec_context_dump(&s->exec_context, f, prefix);
992 for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
994 if (!s->exec_command[c])
997 fprintf(f, "%s-> %s:\n",
998 prefix, service_exec_command_to_string(c));
1000 exec_command_dump_list(s->exec_command[c], f, prefix2);
1005 "%sSysV Init Script Path: %s\n"
1006 "%sSysV Init Script has LSB Header: %s\n",
1007 prefix, s->sysv_path,
1008 prefix, yes_no(s->sysv_has_lsb));
1010 if (s->sysv_start_priority >= 0)
1012 "%sSysVStartPriority: %i\n"
1013 "%sSysVEnabled: %s\n",
1014 prefix, s->sysv_start_priority,
1015 prefix, yes_no(s->sysv_enabled));
1017 if (s->sysv_runlevels)
1018 fprintf(f, "%sSysVRunLevels: %s\n",
1019 prefix, s->sysv_runlevels);
1022 fprintf(f, "%sStatus Text: %s\n",
1023 prefix, s->status_text);
1028 static int service_load_pid_file(Service *s) {
1035 if (s->main_pid_known)
1038 assert(s->main_pid <= 0);
1043 if ((r = read_one_line_file(s->pid_file, &k)) < 0)
1046 r = parse_pid(k, &pid);
1052 if (kill(pid, 0) < 0 && errno != EPERM) {
1053 log_warning("PID %lu read from file %s does not exist. Your service or init script might be broken.",
1054 (unsigned long) pid, s->pid_file);
1058 if ((r = service_set_main_pid(s, pid)) < 0)
1061 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1062 /* FIXME: we need to do something here */
1068 static int service_get_sockets(Service *s, Set **_set) {
1077 if (s->socket_fd >= 0)
1080 /* Collects all Socket objects that belong to this
1081 * service. Note that a service might have multiple sockets
1082 * via multiple names. */
1084 if (!(set = set_new(NULL, NULL)))
1087 SET_FOREACH(t, s->meta.names, i) {
1091 /* Look for all socket objects that go by any of our
1092 * units and collect their fds */
1094 if (!(k = unit_name_change_suffix(t, ".socket"))) {
1099 p = manager_get_unit(s->meta.manager, k);
1105 if ((r = set_put(set, p)) < 0)
1117 static int service_notify_sockets_dead(Service *s) {
1125 if (s->socket_fd >= 0)
1128 /* Notifies all our sockets when we die */
1129 if ((r = service_get_sockets(s, &set)) < 0)
1132 SET_FOREACH(sock, set, i)
1133 socket_notify_service_dead(sock);
1140 static void service_set_state(Service *s, ServiceState state) {
1141 ServiceState old_state;
1144 old_state = s->state;
1147 if (state != SERVICE_START_PRE &&
1148 state != SERVICE_START &&
1149 state != SERVICE_START_POST &&
1150 state != SERVICE_RELOAD &&
1151 state != SERVICE_STOP &&
1152 state != SERVICE_STOP_SIGTERM &&
1153 state != SERVICE_STOP_SIGKILL &&
1154 state != SERVICE_STOP_POST &&
1155 state != SERVICE_FINAL_SIGTERM &&
1156 state != SERVICE_FINAL_SIGKILL &&
1157 state != SERVICE_AUTO_RESTART)
1158 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1160 if (state != SERVICE_START &&
1161 state != SERVICE_START_POST &&
1162 state != SERVICE_RUNNING &&
1163 state != SERVICE_RELOAD &&
1164 state != SERVICE_STOP &&
1165 state != SERVICE_STOP_SIGTERM &&
1166 state != SERVICE_STOP_SIGKILL)
1167 service_unwatch_main_pid(s);
1169 if (state != SERVICE_START_PRE &&
1170 state != SERVICE_START &&
1171 state != SERVICE_START_POST &&
1172 state != SERVICE_RELOAD &&
1173 state != SERVICE_STOP &&
1174 state != SERVICE_STOP_SIGTERM &&
1175 state != SERVICE_STOP_SIGKILL &&
1176 state != SERVICE_STOP_POST &&
1177 state != SERVICE_FINAL_SIGTERM &&
1178 state != SERVICE_FINAL_SIGKILL) {
1179 service_unwatch_control_pid(s);
1180 s->control_command = NULL;
1181 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1184 if (state == SERVICE_DEAD ||
1185 state == SERVICE_STOP ||
1186 state == SERVICE_STOP_SIGTERM ||
1187 state == SERVICE_STOP_SIGKILL ||
1188 state == SERVICE_STOP_POST ||
1189 state == SERVICE_FINAL_SIGTERM ||
1190 state == SERVICE_FINAL_SIGKILL ||
1191 state == SERVICE_MAINTENANCE ||
1192 state == SERVICE_AUTO_RESTART)
1193 service_notify_sockets_dead(s);
1195 if (state != SERVICE_START_PRE &&
1196 state != SERVICE_START &&
1197 state != SERVICE_START_POST &&
1198 state != SERVICE_RUNNING &&
1199 state != SERVICE_RELOAD &&
1200 state != SERVICE_STOP &&
1201 state != SERVICE_STOP_SIGTERM &&
1202 state != SERVICE_STOP_SIGKILL &&
1203 state != SERVICE_STOP_POST &&
1204 state != SERVICE_FINAL_SIGTERM &&
1205 state != SERVICE_FINAL_SIGKILL &&
1206 !(state == SERVICE_DEAD && s->meta.job)) {
1207 service_close_socket_fd(s);
1208 service_connection_unref(s);
1211 /* For the inactive states unit_notify() will trim the cgroup,
1212 * but for exit we have to do that ourselves... */
1213 if (state == SERVICE_EXITED)
1214 cgroup_bonding_trim_list(s->meta.cgroup_bondings, true);
1216 if (old_state != state)
1217 log_debug("%s changed %s -> %s", s->meta.id, service_state_to_string(old_state), service_state_to_string(state));
1219 unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state]);
1222 static int service_coldplug(Unit *u) {
1223 Service *s = SERVICE(u);
1227 assert(s->state == SERVICE_DEAD);
1229 if (s->deserialized_state != s->state) {
1231 if (s->deserialized_state == SERVICE_START_PRE ||
1232 s->deserialized_state == SERVICE_START ||
1233 s->deserialized_state == SERVICE_START_POST ||
1234 s->deserialized_state == SERVICE_RELOAD ||
1235 s->deserialized_state == SERVICE_STOP ||
1236 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1237 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1238 s->deserialized_state == SERVICE_STOP_POST ||
1239 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1240 s->deserialized_state == SERVICE_FINAL_SIGKILL ||
1241 s->deserialized_state == SERVICE_AUTO_RESTART) {
1243 if (s->deserialized_state == SERVICE_AUTO_RESTART || s->timeout_usec > 0) {
1246 k = s->deserialized_state == SERVICE_AUTO_RESTART ? s->restart_usec : s->timeout_usec;
1248 if ((r = unit_watch_timer(UNIT(s), k, &s->timer_watch)) < 0)
1253 if ((s->deserialized_state == SERVICE_START &&
1254 (s->type == SERVICE_FORKING ||
1255 s->type == SERVICE_DBUS ||
1256 s->type == SERVICE_ONESHOT ||
1257 s->type == SERVICE_NOTIFY)) ||
1258 s->deserialized_state == SERVICE_START_POST ||
1259 s->deserialized_state == SERVICE_RUNNING ||
1260 s->deserialized_state == SERVICE_RELOAD ||
1261 s->deserialized_state == SERVICE_STOP ||
1262 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1263 s->deserialized_state == SERVICE_STOP_SIGKILL)
1264 if (s->main_pid > 0)
1265 if ((r = unit_watch_pid(UNIT(s), s->main_pid)) < 0)
1268 if (s->deserialized_state == SERVICE_START_PRE ||
1269 s->deserialized_state == SERVICE_START ||
1270 s->deserialized_state == SERVICE_START_POST ||
1271 s->deserialized_state == SERVICE_RELOAD ||
1272 s->deserialized_state == SERVICE_STOP ||
1273 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1274 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1275 s->deserialized_state == SERVICE_STOP_POST ||
1276 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1277 s->deserialized_state == SERVICE_FINAL_SIGKILL)
1278 if (s->control_pid > 0)
1279 if ((r = unit_watch_pid(UNIT(s), s->control_pid)) < 0)
1282 service_set_state(s, s->deserialized_state);
1288 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
1292 unsigned rn_fds = 0;
1300 if (s->socket_fd >= 0)
1303 if ((r = service_get_sockets(s, &set)) < 0)
1306 SET_FOREACH(sock, set, i) {
1310 if ((r = socket_collect_fds(sock, &cfds, &cn_fds)) < 0)
1322 if (!(t = new(int, rn_fds+cn_fds))) {
1328 memcpy(t, rfds, rn_fds);
1329 memcpy(t+rn_fds, cfds, cn_fds);
1334 rn_fds = rn_fds+cn_fds;
1352 static int service_spawn(
1357 bool apply_permissions,
1359 bool apply_tty_stdin,
1360 bool set_notify_socket,
1365 int *fds = NULL, *fdsbuf = NULL;
1366 unsigned n_fds = 0, n_env = 0;
1367 char **argv = NULL, **final_env = NULL, **our_env = NULL;
1374 s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1375 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1376 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
1378 if (s->socket_fd >= 0) {
1379 fds = &s->socket_fd;
1382 if ((r = service_collect_fds(s, &fdsbuf, &n_fds)) < 0)
1389 if (timeout && s->timeout_usec) {
1390 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1393 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1395 if (!(argv = unit_full_printf_strv(UNIT(s), c->argv))) {
1400 if (!(our_env = new0(char*, 3))) {
1405 if (set_notify_socket)
1406 if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=@%s", s->meta.manager->notify_socket) < 0) {
1411 if (s->main_pid > 0)
1412 if (asprintf(our_env + n_env++, "MAINPID=%lu", (unsigned long) s->main_pid) < 0) {
1417 if (!(final_env = strv_env_merge(2,
1418 s->meta.manager->environment,
1433 s->meta.manager->confirm_spawn,
1434 s->meta.cgroup_bondings,
1441 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1442 /* FIXME: we need to do something here */
1448 strv_free(final_env);
1458 strv_free(final_env);
1461 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1466 static int main_pid_good(Service *s) {
1469 /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1472 /* If we know the pid file, then lets just check if it is
1474 if (s->main_pid_known)
1475 return s->main_pid > 0;
1477 /* We don't know the pid */
1481 static int control_pid_good(Service *s) {
1484 return s->control_pid > 0;
1487 static int cgroup_good(Service *s) {
1492 if ((r = cgroup_bonding_is_empty_list(s->meta.cgroup_bondings)) < 0)
1498 static void service_enter_dead(Service *s, bool success, bool allow_restart) {
1505 if (allow_restart &&
1506 !s->forbid_restart &&
1507 (s->restart == SERVICE_RESTART_ALWAYS ||
1508 (s->restart == SERVICE_RESTART_ON_SUCCESS && !s->failure))) {
1510 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
1513 service_set_state(s, SERVICE_AUTO_RESTART);
1515 service_set_state(s, s->failure ? SERVICE_MAINTENANCE : SERVICE_DEAD);
1517 s->forbid_restart = false;
1522 log_warning("%s failed to run install restart timer: %s", s->meta.id, strerror(-r));
1523 service_enter_dead(s, false, false);
1526 static void service_enter_signal(Service *s, ServiceState state, bool success);
1528 static void service_enter_stop_post(Service *s, bool success) {
1535 service_unwatch_control_pid(s);
1537 s->control_command_id = SERVICE_EXEC_STOP_POST;
1538 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST])) {
1539 if ((r = service_spawn(s,
1543 !s->permissions_start_only,
1544 !s->root_directory_start_only,
1547 &s->control_pid)) < 0)
1551 service_set_state(s, SERVICE_STOP_POST);
1553 service_enter_signal(s, SERVICE_FINAL_SIGTERM, true);
1558 log_warning("%s failed to run 'stop-post' task: %s", s->meta.id, strerror(-r));
1559 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1562 static void service_enter_signal(Service *s, ServiceState state, bool success) {
1571 if (s->exec_context.kill_mode != KILL_NONE) {
1572 int sig = (state == SERVICE_STOP_SIGTERM || state == SERVICE_FINAL_SIGTERM) ? s->exec_context.kill_signal : SIGKILL;
1574 if (s->exec_context.kill_mode == KILL_CONTROL_GROUP) {
1576 if ((r = cgroup_bonding_kill_list(s->meta.cgroup_bondings, sig)) < 0) {
1577 if (r != -EAGAIN && r != -ESRCH)
1586 if (s->main_pid > 0) {
1587 if (kill(s->exec_context.kill_mode == KILL_PROCESS ? s->main_pid : -s->main_pid, sig) < 0 && errno != ESRCH)
1593 if (s->control_pid > 0) {
1594 if (kill(s->exec_context.kill_mode == KILL_PROCESS ? s->control_pid : -s->control_pid, sig) < 0 && errno != ESRCH)
1605 if (sent && (s->main_pid > 0 || s->control_pid > 0)) {
1606 if (s->timeout_usec > 0)
1607 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1610 service_set_state(s, state);
1611 } else if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1612 service_enter_stop_post(s, true);
1614 service_enter_dead(s, true, true);
1619 log_warning("%s failed to kill processes: %s", s->meta.id, strerror(-r));
1621 if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1622 service_enter_stop_post(s, false);
1624 service_enter_dead(s, false, true);
1627 static void service_enter_stop(Service *s, bool success) {
1635 service_unwatch_control_pid(s);
1637 s->control_command_id = SERVICE_EXEC_STOP;
1638 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP])) {
1639 if ((r = service_spawn(s,
1643 !s->permissions_start_only,
1644 !s->root_directory_start_only,
1647 &s->control_pid)) < 0)
1650 service_set_state(s, SERVICE_STOP);
1652 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
1657 log_warning("%s failed to run 'stop' task: %s", s->meta.id, strerror(-r));
1658 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1661 static void service_enter_running(Service *s, bool success) {
1662 int main_pid_ok, cgroup_ok;
1668 main_pid_ok = main_pid_good(s);
1669 cgroup_ok = cgroup_good(s);
1671 if ((main_pid_ok > 0 || (main_pid_ok < 0 && cgroup_ok != 0)) &&
1672 (s->bus_name_good || s->type != SERVICE_DBUS))
1673 service_set_state(s, SERVICE_RUNNING);
1674 else if (s->remain_after_exit)
1675 service_set_state(s, SERVICE_EXITED);
1677 service_enter_stop(s, true);
1680 static void service_enter_start_post(Service *s) {
1684 service_unwatch_control_pid(s);
1686 s->control_command_id = SERVICE_EXEC_START_POST;
1687 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_POST])) {
1688 if ((r = service_spawn(s,
1692 !s->permissions_start_only,
1693 !s->root_directory_start_only,
1696 &s->control_pid)) < 0)
1699 service_set_state(s, SERVICE_START_POST);
1701 service_enter_running(s, true);
1706 log_warning("%s failed to run 'start-post' task: %s", s->meta.id, strerror(-r));
1707 service_enter_stop(s, false);
1710 static void service_enter_start(Service *s) {
1716 assert(s->exec_command[SERVICE_EXEC_START]);
1717 assert(!s->exec_command[SERVICE_EXEC_START]->command_next || s->type == SERVICE_ONESHOT);
1719 if (s->type == SERVICE_FORKING)
1720 service_unwatch_control_pid(s);
1722 service_unwatch_main_pid(s);
1724 s->control_command_id = SERVICE_EXEC_START;
1725 s->control_command = s->exec_command[SERVICE_EXEC_START];
1727 if ((r = service_spawn(s,
1729 s->type == SERVICE_FORKING || s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY,
1734 s->notify_access != NOTIFY_NONE,
1738 if (s->type == SERVICE_SIMPLE) {
1739 /* For simple services we immediately start
1740 * the START_POST binaries. */
1742 service_set_main_pid(s, pid);
1743 service_enter_start_post(s);
1745 } else if (s->type == SERVICE_FORKING) {
1747 /* For forking services we wait until the start
1748 * process exited. */
1750 s->control_pid = pid;
1751 service_set_state(s, SERVICE_START);
1753 } else if (s->type == SERVICE_ONESHOT ||
1754 s->type == SERVICE_DBUS ||
1755 s->type == SERVICE_NOTIFY) {
1757 /* For oneshot services we wait until the start
1758 * process exited, too, but it is our main process. */
1760 /* For D-Bus services we know the main pid right away,
1761 * but wait for the bus name to appear on the
1762 * bus. Notify services are similar. */
1764 service_set_main_pid(s, pid);
1765 service_set_state(s, SERVICE_START);
1767 assert_not_reached("Unknown service type");
1772 log_warning("%s failed to run 'start' task: %s", s->meta.id, strerror(-r));
1773 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1776 static void service_enter_start_pre(Service *s) {
1781 service_unwatch_control_pid(s);
1783 s->control_command_id = SERVICE_EXEC_START_PRE;
1784 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_PRE])) {
1785 if ((r = service_spawn(s,
1789 !s->permissions_start_only,
1790 !s->root_directory_start_only,
1793 &s->control_pid)) < 0)
1796 service_set_state(s, SERVICE_START_PRE);
1798 service_enter_start(s);
1803 log_warning("%s failed to run 'start-pre' task: %s", s->meta.id, strerror(-r));
1804 service_enter_dead(s, false, true);
1807 static void service_enter_restart(Service *s) {
1812 dbus_error_init(&error);
1814 service_enter_dead(s, true, false);
1816 if ((r = manager_add_job(s->meta.manager, JOB_START, UNIT(s), JOB_FAIL, false, NULL, NULL)) < 0)
1819 log_debug("%s scheduled restart job.", s->meta.id);
1823 log_warning("%s failed to schedule restart job: %s", s->meta.id, bus_error(&error, -r));
1824 service_enter_dead(s, false, false);
1826 dbus_error_free(&error);
1829 static void service_enter_reload(Service *s) {
1834 service_unwatch_control_pid(s);
1836 s->control_command_id = SERVICE_EXEC_RELOAD;
1837 if ((s->control_command = s->exec_command[SERVICE_EXEC_RELOAD])) {
1838 if ((r = service_spawn(s,
1842 !s->permissions_start_only,
1843 !s->root_directory_start_only,
1846 &s->control_pid)) < 0)
1849 service_set_state(s, SERVICE_RELOAD);
1851 service_enter_running(s, true);
1856 log_warning("%s failed to run 'reload' task: %s", s->meta.id, strerror(-r));
1857 service_enter_stop(s, false);
1860 static void service_run_next_control(Service *s, bool success) {
1864 assert(s->control_command);
1865 assert(s->control_command->command_next);
1870 assert(s->control_command_id != SERVICE_EXEC_START);
1872 s->control_command = s->control_command->command_next;
1873 service_unwatch_control_pid(s);
1875 if ((r = service_spawn(s,
1879 !s->permissions_start_only,
1880 !s->root_directory_start_only,
1881 s->control_command_id == SERVICE_EXEC_START_PRE ||
1882 s->control_command_id == SERVICE_EXEC_STOP_POST,
1884 &s->control_pid)) < 0)
1890 log_warning("%s failed to run next control task: %s", s->meta.id, strerror(-r));
1892 if (s->state == SERVICE_START_PRE)
1893 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1894 else if (s->state == SERVICE_STOP)
1895 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1896 else if (s->state == SERVICE_STOP_POST)
1897 service_enter_dead(s, false, true);
1899 service_enter_stop(s, false);
1902 static void service_run_next_main(Service *s, bool success) {
1907 assert(s->control_command);
1908 assert(s->control_command->command_next);
1913 assert(s->control_command_id == SERVICE_EXEC_START);
1914 assert(s->type == SERVICE_ONESHOT);
1916 s->control_command = s->control_command->command_next;
1917 service_unwatch_main_pid(s);
1919 if ((r = service_spawn(s,
1926 s->notify_access != NOTIFY_NONE,
1930 service_set_main_pid(s, pid);
1935 log_warning("%s failed to run next main task: %s", s->meta.id, strerror(-r));
1936 service_enter_stop(s, false);
1939 static int service_start(Unit *u) {
1940 Service *s = SERVICE(u);
1944 /* We cannot fulfill this request right now, try again later
1946 if (s->state == SERVICE_STOP ||
1947 s->state == SERVICE_STOP_SIGTERM ||
1948 s->state == SERVICE_STOP_SIGKILL ||
1949 s->state == SERVICE_STOP_POST ||
1950 s->state == SERVICE_FINAL_SIGTERM ||
1951 s->state == SERVICE_FINAL_SIGKILL)
1954 /* Already on it! */
1955 if (s->state == SERVICE_START_PRE ||
1956 s->state == SERVICE_START ||
1957 s->state == SERVICE_START_POST)
1960 assert(s->state == SERVICE_DEAD || s->state == SERVICE_MAINTENANCE || s->state == SERVICE_AUTO_RESTART);
1962 /* Make sure we don't enter a busy loop of some kind. */
1963 if (!ratelimit_test(&s->ratelimit)) {
1964 log_warning("%s start request repeated too quickly, refusing to start.", u->meta.id);
1968 if ((s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1969 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1970 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) &&
1972 log_warning("%s can only be started with a per-connection socket.", u->meta.id);
1977 s->main_pid_known = false;
1978 s->forbid_restart = false;
1980 service_enter_start_pre(s);
1984 static int service_stop(Unit *u) {
1985 Service *s = SERVICE(u);
1989 /* This is a user request, so don't do restarts on this
1991 s->forbid_restart = true;
1994 if (s->state == SERVICE_STOP ||
1995 s->state == SERVICE_STOP_SIGTERM ||
1996 s->state == SERVICE_STOP_SIGKILL ||
1997 s->state == SERVICE_STOP_POST ||
1998 s->state == SERVICE_FINAL_SIGTERM ||
1999 s->state == SERVICE_FINAL_SIGKILL)
2002 /* Don't allow a restart */
2003 if (s->state == SERVICE_AUTO_RESTART) {
2004 service_set_state(s, SERVICE_DEAD);
2008 /* If there's already something running we go directly into
2010 if (s->state == SERVICE_START_PRE ||
2011 s->state == SERVICE_START ||
2012 s->state == SERVICE_START_POST ||
2013 s->state == SERVICE_RELOAD) {
2014 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
2018 assert(s->state == SERVICE_RUNNING ||
2019 s->state == SERVICE_EXITED);
2021 service_enter_stop(s, true);
2025 static int service_reload(Unit *u) {
2026 Service *s = SERVICE(u);
2030 assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
2032 service_enter_reload(s);
2036 static bool service_can_reload(Unit *u) {
2037 Service *s = SERVICE(u);
2041 return !!s->exec_command[SERVICE_EXEC_RELOAD];
2044 static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
2045 Service *s = SERVICE(u);
2051 unit_serialize_item(u, f, "state", service_state_to_string(s->state));
2052 unit_serialize_item(u, f, "failure", yes_no(s->failure));
2054 if (s->control_pid > 0)
2055 unit_serialize_item_format(u, f, "control-pid", "%lu", (unsigned long) s->control_pid);
2057 if (s->main_pid_known && s->main_pid > 0)
2058 unit_serialize_item_format(u, f, "main-pid", "%lu", (unsigned long) s->main_pid);
2060 unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
2063 unit_serialize_item(u, f, "status-text", s->status_text);
2065 /* There's a minor uncleanliness here: if there are multiple
2066 * commands attached here, we will start from the first one
2068 if (s->control_command_id >= 0)
2069 unit_serialize_item(u, f, "control-command", service_exec_command_to_string(s->control_command_id));
2071 if (s->socket_fd >= 0) {
2074 if ((copy = fdset_put_dup(fds, s->socket_fd)) < 0)
2077 unit_serialize_item_format(u, f, "socket-fd", "%i", copy);
2080 if (s->main_exec_status.pid > 0) {
2081 unit_serialize_item_format(u, f, "main-exec-status-pid", "%lu", (unsigned long) s->main_exec_status.pid);
2083 if (s->main_exec_status.start_timestamp.realtime > 0) {
2084 unit_serialize_item_format(u, f, "main-exec-status-start-realtime",
2085 "%llu", (unsigned long long) s->main_exec_status.start_timestamp.realtime);
2087 unit_serialize_item_format(u, f, "main-exec-status-start-monotonic",
2088 "%llu", (unsigned long long) s->main_exec_status.start_timestamp.monotonic);
2091 if (s->main_exec_status.exit_timestamp.realtime > 0) {
2092 unit_serialize_item_format(u, f, "main-exec-status-exit-realtime",
2093 "%llu", (unsigned long long) s->main_exec_status.exit_timestamp.realtime);
2094 unit_serialize_item_format(u, f, "main-exec-status-exit-monotonic",
2095 "%llu", (unsigned long long) s->main_exec_status.exit_timestamp.monotonic);
2097 unit_serialize_item_format(u, f, "main-exec-status-code", "%i", s->main_exec_status.code);
2098 unit_serialize_item_format(u, f, "main-exec-status-status", "%i", s->main_exec_status.status);
2105 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
2106 Service *s = SERVICE(u);
2113 if (streq(key, "state")) {
2116 if ((state = service_state_from_string(value)) < 0)
2117 log_debug("Failed to parse state value %s", value);
2119 s->deserialized_state = state;
2120 } else if (streq(key, "failure")) {
2123 if ((b = parse_boolean(value)) < 0)
2124 log_debug("Failed to parse failure value %s", value);
2126 s->failure = b || s->failure;
2127 } else if (streq(key, "control-pid")) {
2130 if (parse_pid(value, &pid) < 0)
2131 log_debug("Failed to parse control-pid value %s", value);
2133 s->control_pid = pid;
2134 } else if (streq(key, "main-pid")) {
2137 if (parse_pid(value, &pid) < 0)
2138 log_debug("Failed to parse main-pid value %s", value);
2140 service_set_main_pid(s, (pid_t) pid);
2141 } else if (streq(key, "main-pid-known")) {
2144 if ((b = parse_boolean(value)) < 0)
2145 log_debug("Failed to parse main-pid-known value %s", value);
2147 s->main_pid_known = b;
2148 } else if (streq(key, "status-text")) {
2151 if ((t = strdup(value))) {
2152 free(s->status_text);
2156 } else if (streq(key, "control-command")) {
2157 ServiceExecCommand id;
2159 if ((id = service_exec_command_from_string(value)) < 0)
2160 log_debug("Failed to parse exec-command value %s", value);
2162 s->control_command_id = id;
2163 s->control_command = s->exec_command[id];
2165 } else if (streq(key, "socket-fd")) {
2168 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2169 log_debug("Failed to parse socket-fd value %s", value);
2172 if (s->socket_fd >= 0)
2173 close_nointr_nofail(s->socket_fd);
2174 s->socket_fd = fdset_remove(fds, fd);
2176 } else if (streq(key, "main-exec-status-pid")) {
2179 if (parse_pid(value, &pid) < 0)
2180 log_debug("Failed to parse main-exec-status-pid value %s", value);
2182 s->main_exec_status.pid = pid;
2183 } else if (streq(key, "main-exec-status-code")) {
2186 if (safe_atoi(value, &i) < 0)
2187 log_debug("Failed to parse main-exec-status-code value %s", value);
2189 s->main_exec_status.code = i;
2190 } else if (streq(key, "main-exec-status-status")) {
2193 if (safe_atoi(value, &i) < 0)
2194 log_debug("Failed to parse main-exec-status-status value %s", value);
2196 s->main_exec_status.status = i;
2197 } else if (streq(key, "main-exec-status-start-realtime")) {
2200 if (safe_atou64(value, &k) < 0)
2201 log_debug("Failed to parse main-exec-status-start-realtime value %s", value);
2203 s->main_exec_status.start_timestamp.realtime = (usec_t) k;
2204 } else if (streq(key, "main-exec-status-start-monotonic")) {
2207 if (safe_atou64(value, &k) < 0)
2208 log_debug("Failed to parse main-exec-status-start-monotonic value %s", value);
2210 s->main_exec_status.start_timestamp.monotonic = (usec_t) k;
2211 } else if (streq(key, "main-exec-status-exit-realtime")) {
2214 if (safe_atou64(value, &k) < 0)
2215 log_debug("Failed to parse main-exec-status-exit-realtime value %s", value);
2217 s->main_exec_status.exit_timestamp.realtime = (usec_t) k;
2218 } else if (streq(key, "main-exec-status-exit-monotonic")) {
2221 if (safe_atou64(value, &k) < 0)
2222 log_debug("Failed to parse main-exec-status-exit-monotonic value %s", value);
2224 s->main_exec_status.exit_timestamp.monotonic = (usec_t) k;
2226 log_debug("Unknown serialization key '%s'", key);
2231 static UnitActiveState service_active_state(Unit *u) {
2234 return state_translation_table[SERVICE(u)->state];
2237 static const char *service_sub_state_to_string(Unit *u) {
2240 return service_state_to_string(SERVICE(u)->state);
2243 static bool service_check_gc(Unit *u) {
2244 Service *s = SERVICE(u);
2248 return !!s->sysv_path;
2251 static bool service_check_snapshot(Unit *u) {
2252 Service *s = SERVICE(u);
2256 return !s->got_socket_fd;
2259 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2260 Service *s = SERVICE(u);
2267 success = is_clean_exit_lsb(code, status);
2269 success = is_clean_exit(code, status);
2271 if (s->main_pid == pid) {
2274 exec_status_exit(&s->main_exec_status, pid, code, status);
2276 if (s->type != SERVICE_FORKING && s->control_command) {
2277 s->control_command->exec_status = s->main_exec_status;
2279 if (s->control_command->ignore)
2283 log_full(success ? LOG_DEBUG : LOG_NOTICE,
2284 "%s: main process exited, code=%s, status=%i", u->meta.id, sigchld_code_to_string(code), status);
2285 s->failure = s->failure || !success;
2287 if (s->control_command &&
2288 s->control_command->command_next &&
2291 /* There is another command to *
2292 * execute, so let's do that. */
2294 log_debug("%s running next main command for state %s", u->meta.id, service_state_to_string(s->state));
2295 service_run_next_main(s, success);
2299 /* The service exited, so the service is officially
2302 s->control_command = NULL;
2303 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2307 case SERVICE_START_POST:
2308 case SERVICE_RELOAD:
2310 /* Need to wait until the operation is
2315 if (s->type == SERVICE_ONESHOT) {
2316 /* This was our main goal, so let's go on */
2318 service_enter_start_post(s);
2320 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2323 assert(s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY);
2328 case SERVICE_RUNNING:
2329 service_enter_running(s, success);
2332 case SERVICE_STOP_SIGTERM:
2333 case SERVICE_STOP_SIGKILL:
2335 if (!control_pid_good(s))
2336 service_enter_stop_post(s, success);
2338 /* If there is still a control process, wait for that first */
2342 assert_not_reached("Uh, main process died at wrong time.");
2346 } else if (s->control_pid == pid) {
2350 if (s->control_command) {
2351 exec_status_exit(&s->control_command->exec_status, pid, code, status);
2353 if (s->control_command->ignore)
2357 log_full(success ? LOG_DEBUG : LOG_NOTICE,
2358 "%s: control process exited, code=%s status=%i", u->meta.id, sigchld_code_to_string(code), status);
2359 s->failure = s->failure || !success;
2361 if (s->control_command &&
2362 s->control_command->command_next &&
2365 /* There is another command to *
2366 * execute, so let's do that. */
2368 log_debug("%s running next control command for state %s", u->meta.id, service_state_to_string(s->state));
2369 service_run_next_control(s, success);
2372 /* No further commands for this step, so let's
2373 * figure out what to do next */
2375 s->control_command = NULL;
2376 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2378 log_debug("%s got final SIGCHLD for state %s", u->meta.id, service_state_to_string(s->state));
2382 case SERVICE_START_PRE:
2384 service_enter_start(s);
2386 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2390 assert(s->type == SERVICE_FORKING);
2392 /* Let's try to load the pid
2393 * file here if we can. We
2394 * ignore the return value,
2395 * since the PID file might
2396 * actually be created by a
2397 * START_POST script */
2401 service_load_pid_file(s);
2403 service_enter_start_post(s);
2405 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2409 case SERVICE_START_POST:
2410 if (success && s->pid_file && !s->main_pid_known) {
2413 /* Hmm, let's see if we can
2414 * load the pid now after the
2415 * start-post scripts got
2418 if ((r = service_load_pid_file(s)) < 0)
2419 log_warning("%s: failed to load PID file %s: %s", s->meta.id, s->pid_file, strerror(-r));
2424 case SERVICE_RELOAD:
2426 service_enter_running(s, true);
2428 service_enter_stop(s, false);
2433 service_enter_signal(s, SERVICE_STOP_SIGTERM, success);
2436 case SERVICE_STOP_SIGTERM:
2437 case SERVICE_STOP_SIGKILL:
2438 if (main_pid_good(s) <= 0)
2439 service_enter_stop_post(s, success);
2441 /* If there is still a service
2442 * process around, wait until
2443 * that one quit, too */
2446 case SERVICE_STOP_POST:
2447 case SERVICE_FINAL_SIGTERM:
2448 case SERVICE_FINAL_SIGKILL:
2449 service_enter_dead(s, success, true);
2453 assert_not_reached("Uh, control process died at wrong time.");
2458 /* Notify clients about changed exit status */
2459 unit_add_to_dbus_queue(u);
2462 static void service_timer_event(Unit *u, uint64_t elapsed, Watch* w) {
2463 Service *s = SERVICE(u);
2466 assert(elapsed == 1);
2468 assert(w == &s->timer_watch);
2472 case SERVICE_START_PRE:
2474 log_warning("%s operation timed out. Terminating.", u->meta.id);
2475 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2478 case SERVICE_START_POST:
2479 case SERVICE_RELOAD:
2480 log_warning("%s operation timed out. Stopping.", u->meta.id);
2481 service_enter_stop(s, false);
2485 log_warning("%s stopping timed out. Terminating.", u->meta.id);
2486 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
2489 case SERVICE_STOP_SIGTERM:
2490 log_warning("%s stopping timed out. Killing.", u->meta.id);
2491 service_enter_signal(s, SERVICE_STOP_SIGKILL, false);
2494 case SERVICE_STOP_SIGKILL:
2495 /* Uh, wie sent a SIGKILL and it is still not gone?
2496 * Must be something we cannot kill, so let's just be
2497 * weirded out and continue */
2499 log_warning("%s still around after SIGKILL. Ignoring.", u->meta.id);
2500 service_enter_stop_post(s, false);
2503 case SERVICE_STOP_POST:
2504 log_warning("%s stopping timed out (2). Terminating.", u->meta.id);
2505 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2508 case SERVICE_FINAL_SIGTERM:
2509 log_warning("%s stopping timed out (2). Killing.", u->meta.id);
2510 service_enter_signal(s, SERVICE_FINAL_SIGKILL, false);
2513 case SERVICE_FINAL_SIGKILL:
2514 log_warning("%s still around after SIGKILL (2). Entering maintenance mode.", u->meta.id);
2515 service_enter_dead(s, false, true);
2518 case SERVICE_AUTO_RESTART:
2519 log_info("%s holdoff time over, scheduling restart.", u->meta.id);
2520 service_enter_restart(s);
2524 assert_not_reached("Timeout at wrong time.");
2528 static void service_cgroup_notify_event(Unit *u) {
2529 Service *s = SERVICE(u);
2533 log_debug("%s: cgroup is empty", u->meta.id);
2537 /* Waiting for SIGCHLD is usually more interesting,
2538 * because it includes return codes/signals. Which is
2539 * why we ignore the cgroup events for most cases,
2540 * except when we don't know pid which to expect the
2543 case SERVICE_RUNNING:
2544 service_enter_running(s, true);
2552 static void service_notify_message(Unit *u, pid_t pid, char **tags) {
2553 Service *s = SERVICE(u);
2558 if (s->notify_access == NOTIFY_NONE) {
2559 log_warning("%s: Got notification message from PID %lu, but reception is disabled.",
2560 u->meta.id, (unsigned long) pid);
2564 if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
2565 log_warning("%s: Got notification message from PID %lu, but reception only permitted for PID %lu",
2566 u->meta.id, (unsigned long) pid, (unsigned long) s->main_pid);
2570 log_debug("%s: Got message", u->meta.id);
2572 /* Interpret MAINPID= */
2573 if ((e = strv_find_prefix(tags, "MAINPID=")) &&
2574 (s->state == SERVICE_START ||
2575 s->state == SERVICE_START_POST ||
2576 s->state == SERVICE_RUNNING ||
2577 s->state == SERVICE_RELOAD)) {
2579 if (parse_pid(e + 8, &pid) < 0)
2580 log_warning("Failed to parse notification message %s", e);
2582 log_debug("%s: got %s", u->meta.id, e);
2583 service_set_main_pid(s, pid);
2587 /* Interpret READY= */
2588 if (s->type == SERVICE_NOTIFY &&
2589 s->state == SERVICE_START &&
2590 strv_find(tags, "READY=1")) {
2591 log_debug("%s: got READY=1", u->meta.id);
2593 service_enter_start_post(s);
2596 /* Interpret STATUS= */
2597 if ((e = strv_find_prefix(tags, "STATUS="))) {
2601 if (!(t = strdup(e+7))) {
2602 log_error("Failed to allocate string.");
2606 log_debug("%s: got %s", u->meta.id, e);
2608 free(s->status_text);
2611 free(s->status_text);
2612 s->status_text = NULL;
2617 /* Notify clients about changed status or main pid */
2618 unit_add_to_dbus_queue(u);
2621 static int service_enumerate(Manager *m) {
2625 char *path = NULL, *fpath = NULL, *name = NULL;
2630 STRV_FOREACH(p, m->lookup_paths.sysvrcnd_path)
2631 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++) {
2636 if (asprintf(&path, "%s/%s", *p, rcnd_table[i].path) < 0) {
2644 if (!(d = opendir(path))) {
2645 if (errno != ENOENT)
2646 log_warning("opendir() failed on %s: %s", path, strerror(errno));
2651 while ((de = readdir(d))) {
2655 if (ignore_file(de->d_name))
2658 if (de->d_name[0] != 'S' && de->d_name[0] != 'K')
2661 if (strlen(de->d_name) < 4)
2664 a = undecchar(de->d_name[1]);
2665 b = undecchar(de->d_name[2]);
2672 if (asprintf(&fpath, "%s/%s/%s", *p, rcnd_table[i].path, de->d_name) < 0) {
2677 if (access(fpath, X_OK) < 0) {
2679 if (errno != ENOENT)
2680 log_warning("access() failed on %s: %s", fpath, strerror(errno));
2686 if (!(name = sysv_translate_name(de->d_name + 3))) {
2691 if ((r = manager_load_unit_prepare(m, name, NULL, NULL, &service)) < 0) {
2692 log_warning("Failed to prepare unit %s: %s", name, strerror(-r));
2696 if (de->d_name[0] == 'S' &&
2697 (rcnd_table[i].type == RUNLEVEL_UP || rcnd_table[i].type == RUNLEVEL_SYSINIT)) {
2698 SERVICE(service)->sysv_start_priority =
2699 MAX(a*10 + b, SERVICE(service)->sysv_start_priority);
2700 SERVICE(service)->sysv_enabled = true;
2703 manager_dispatch_load_queue(m);
2704 service = unit_follow_merge(service);
2706 /* If this is a native service, rely
2707 * on native ways to pull in a
2708 * service, don't pull it in via sysv
2710 if (service->meta.fragment_path)
2713 if (de->d_name[0] == 'S') {
2715 if ((r = unit_add_two_dependencies_by_name_inverse(service, UNIT_AFTER, UNIT_WANTS, rcnd_table[i].target, NULL, true)) < 0)
2718 } else if (de->d_name[0] == 'K' &&
2719 (rcnd_table[i].type == RUNLEVEL_DOWN ||
2720 rcnd_table[i].type == RUNLEVEL_SYSINIT)) {
2722 /* We honour K links only for
2723 * halt/reboot. For the normal
2724 * runlevels we assume the
2726 * implicitly added by the
2727 * core logic. Also, we don't
2728 * really distuingish here
2729 * between the runlevels 0 and
2730 * 6 and just add them to the
2731 * special shutdown target. On
2732 * SUSE the boot.d/ runlevel
2733 * is also used for shutdown,
2734 * so we add links for that
2735 * too to the shutdown
2738 if ((r = unit_add_two_dependencies_by_name_inverse(service, UNIT_AFTER, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true)) < 0)
2757 static void service_bus_name_owner_change(
2760 const char *old_owner,
2761 const char *new_owner) {
2763 Service *s = SERVICE(u);
2768 assert(streq(s->bus_name, name));
2769 assert(old_owner || new_owner);
2771 if (old_owner && new_owner)
2772 log_debug("%s's D-Bus name %s changed owner from %s to %s", u->meta.id, name, old_owner, new_owner);
2774 log_debug("%s's D-Bus name %s no longer registered by %s", u->meta.id, name, old_owner);
2776 log_debug("%s's D-Bus name %s now registered by %s", u->meta.id, name, new_owner);
2778 s->bus_name_good = !!new_owner;
2780 if (s->type == SERVICE_DBUS) {
2782 /* service_enter_running() will figure out what to
2784 if (s->state == SERVICE_RUNNING)
2785 service_enter_running(s, true);
2786 else if (s->state == SERVICE_START && new_owner)
2787 service_enter_start_post(s);
2789 } else if (new_owner &&
2791 (s->state == SERVICE_START ||
2792 s->state == SERVICE_START_POST ||
2793 s->state == SERVICE_RUNNING ||
2794 s->state == SERVICE_RELOAD)) {
2796 /* Try to acquire PID from bus service */
2797 log_debug("Trying to acquire PID from D-Bus name...");
2799 bus_query_pid(u->meta.manager, name);
2803 static void service_bus_query_pid_done(
2808 Service *s = SERVICE(u);
2813 log_debug("%s's D-Bus name %s is now owned by process %u", u->meta.id, name, (unsigned) pid);
2815 if (s->main_pid <= 0 &&
2816 (s->state == SERVICE_START ||
2817 s->state == SERVICE_START_POST ||
2818 s->state == SERVICE_RUNNING ||
2819 s->state == SERVICE_RELOAD))
2820 service_set_main_pid(s, pid);
2823 int service_set_socket_fd(Service *s, int fd, Socket *sock) {
2827 /* This is called by the socket code when instantiating a new
2828 * service for a stream socket and the socket needs to be
2831 if (s->meta.load_state != UNIT_LOADED)
2834 if (s->socket_fd >= 0)
2837 if (s->state != SERVICE_DEAD)
2841 s->got_socket_fd = true;
2847 static void service_reset_maintenance(Unit *u) {
2848 Service *s = SERVICE(u);
2852 if (s->state == SERVICE_MAINTENANCE)
2853 service_set_state(s, SERVICE_DEAD);
2858 static const char* const service_state_table[_SERVICE_STATE_MAX] = {
2859 [SERVICE_DEAD] = "dead",
2860 [SERVICE_START_PRE] = "start-pre",
2861 [SERVICE_START] = "start",
2862 [SERVICE_START_POST] = "start-post",
2863 [SERVICE_RUNNING] = "running",
2864 [SERVICE_EXITED] = "exited",
2865 [SERVICE_RELOAD] = "reload",
2866 [SERVICE_STOP] = "stop",
2867 [SERVICE_STOP_SIGTERM] = "stop-sigterm",
2868 [SERVICE_STOP_SIGKILL] = "stop-sigkill",
2869 [SERVICE_STOP_POST] = "stop-post",
2870 [SERVICE_FINAL_SIGTERM] = "final-sigterm",
2871 [SERVICE_FINAL_SIGKILL] = "final-sigkill",
2872 [SERVICE_MAINTENANCE] = "maintenance",
2873 [SERVICE_AUTO_RESTART] = "auto-restart",
2876 DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
2878 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
2879 [SERVICE_ONCE] = "once",
2880 [SERVICE_RESTART_ON_SUCCESS] = "restart-on-success",
2881 [SERVICE_RESTART_ALWAYS] = "restart-always",
2884 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
2886 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
2887 [SERVICE_SIMPLE] = "simple",
2888 [SERVICE_FORKING] = "forking",
2889 [SERVICE_ONESHOT] = "oneshot",
2890 [SERVICE_DBUS] = "dbus",
2891 [SERVICE_NOTIFY] = "notify"
2894 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
2896 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
2897 [SERVICE_EXEC_START_PRE] = "ExecStartPre",
2898 [SERVICE_EXEC_START] = "ExecStart",
2899 [SERVICE_EXEC_START_POST] = "ExecStartPost",
2900 [SERVICE_EXEC_RELOAD] = "ExecReload",
2901 [SERVICE_EXEC_STOP] = "ExecStop",
2902 [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
2905 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
2907 static const char* const notify_access_table[_NOTIFY_ACCESS_MAX] = {
2908 [NOTIFY_NONE] = "none",
2909 [NOTIFY_MAIN] = "main",
2910 [NOTIFY_ALL] = "all"
2913 DEFINE_STRING_TABLE_LOOKUP(notify_access, NotifyAccess);
2915 const UnitVTable service_vtable = {
2916 .suffix = ".service",
2917 .show_status = true,
2919 .init = service_init,
2920 .done = service_done,
2921 .load = service_load,
2923 .coldplug = service_coldplug,
2925 .dump = service_dump,
2927 .start = service_start,
2928 .stop = service_stop,
2929 .reload = service_reload,
2931 .can_reload = service_can_reload,
2933 .serialize = service_serialize,
2934 .deserialize_item = service_deserialize_item,
2936 .active_state = service_active_state,
2937 .sub_state_to_string = service_sub_state_to_string,
2939 .check_gc = service_check_gc,
2940 .check_snapshot = service_check_snapshot,
2942 .sigchld_event = service_sigchld_event,
2943 .timer_event = service_timer_event,
2945 .reset_maintenance = service_reset_maintenance,
2947 .cgroup_notify_empty = service_cgroup_notify_event,
2948 .notify_message = service_notify_message,
2950 .bus_name_owner_change = service_bus_name_owner_change,
2951 .bus_query_pid_done = service_bus_query_pid_done,
2953 .bus_interface = "org.freedesktop.systemd1.Service",
2954 .bus_message_handler = bus_service_message_handler,
2955 .bus_invalidating_properties = bus_service_invalidating_properties,
2957 .enumerate = service_enumerate