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 Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
31 #include "load-fragment.h"
32 #include "load-dropin.h"
35 #include "unit-name.h"
36 #include "unit-printf.h"
37 #include "dbus-service.h"
39 #include "exit-status.h"
41 #include "path-util.h"
46 #include "bus-error.h"
48 #include "bus-kernel.h"
50 static const UnitActiveState state_translation_table[_SERVICE_STATE_MAX] = {
51 [SERVICE_DEAD] = UNIT_INACTIVE,
52 [SERVICE_START_PRE] = UNIT_ACTIVATING,
53 [SERVICE_START] = UNIT_ACTIVATING,
54 [SERVICE_START_POST] = UNIT_ACTIVATING,
55 [SERVICE_RUNNING] = UNIT_ACTIVE,
56 [SERVICE_EXITED] = UNIT_ACTIVE,
57 [SERVICE_RELOAD] = UNIT_RELOADING,
58 [SERVICE_STOP] = UNIT_DEACTIVATING,
59 [SERVICE_STOP_SIGABRT] = UNIT_DEACTIVATING,
60 [SERVICE_STOP_SIGTERM] = UNIT_DEACTIVATING,
61 [SERVICE_STOP_SIGKILL] = UNIT_DEACTIVATING,
62 [SERVICE_STOP_POST] = UNIT_DEACTIVATING,
63 [SERVICE_FINAL_SIGTERM] = UNIT_DEACTIVATING,
64 [SERVICE_FINAL_SIGKILL] = UNIT_DEACTIVATING,
65 [SERVICE_FAILED] = UNIT_FAILED,
66 [SERVICE_AUTO_RESTART] = UNIT_ACTIVATING
69 /* For Type=idle we never want to delay any other jobs, hence we
70 * consider idle jobs active as soon as we start working on them */
71 static const UnitActiveState state_translation_table_idle[_SERVICE_STATE_MAX] = {
72 [SERVICE_DEAD] = UNIT_INACTIVE,
73 [SERVICE_START_PRE] = UNIT_ACTIVE,
74 [SERVICE_START] = UNIT_ACTIVE,
75 [SERVICE_START_POST] = UNIT_ACTIVE,
76 [SERVICE_RUNNING] = UNIT_ACTIVE,
77 [SERVICE_EXITED] = UNIT_ACTIVE,
78 [SERVICE_RELOAD] = UNIT_RELOADING,
79 [SERVICE_STOP] = UNIT_DEACTIVATING,
80 [SERVICE_STOP_SIGABRT] = UNIT_DEACTIVATING,
81 [SERVICE_STOP_SIGTERM] = UNIT_DEACTIVATING,
82 [SERVICE_STOP_SIGKILL] = UNIT_DEACTIVATING,
83 [SERVICE_STOP_POST] = UNIT_DEACTIVATING,
84 [SERVICE_FINAL_SIGTERM] = UNIT_DEACTIVATING,
85 [SERVICE_FINAL_SIGKILL] = UNIT_DEACTIVATING,
86 [SERVICE_FAILED] = UNIT_FAILED,
87 [SERVICE_AUTO_RESTART] = UNIT_ACTIVATING
90 static int service_dispatch_io(sd_event_source *source, int fd, uint32_t events, void *userdata);
91 static int service_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata);
92 static int service_dispatch_watchdog(sd_event_source *source, usec_t usec, void *userdata);
94 static void service_enter_signal(Service *s, ServiceState state, ServiceResult f);
95 static void service_enter_reload_by_notify(Service *s);
97 static void service_init(Unit *u) {
98 Service *s = SERVICE(u);
101 assert(u->load_state == UNIT_STUB);
103 s->timeout_start_usec = u->manager->default_timeout_start_usec;
104 s->timeout_stop_usec = u->manager->default_timeout_stop_usec;
105 s->restart_usec = u->manager->default_restart_usec;
106 s->type = _SERVICE_TYPE_INVALID;
108 s->bus_endpoint_fd = -1;
109 s->guess_main_pid = true;
111 RATELIMIT_INIT(s->start_limit, u->manager->default_start_limit_interval, u->manager->default_start_limit_burst);
113 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
116 static void service_unwatch_control_pid(Service *s) {
119 if (s->control_pid <= 0)
122 unit_unwatch_pid(UNIT(s), s->control_pid);
126 static void service_unwatch_main_pid(Service *s) {
129 if (s->main_pid <= 0)
132 unit_unwatch_pid(UNIT(s), s->main_pid);
136 static void service_unwatch_pid_file(Service *s) {
137 if (!s->pid_file_pathspec)
140 log_debug_unit(UNIT(s)->id, "Stopping watch for %s's PID file %s", UNIT(s)->id, s->pid_file_pathspec->path);
141 path_spec_unwatch(s->pid_file_pathspec);
142 path_spec_done(s->pid_file_pathspec);
143 free(s->pid_file_pathspec);
144 s->pid_file_pathspec = NULL;
147 static int service_set_main_pid(Service *s, pid_t pid) {
158 if (s->main_pid == pid && s->main_pid_known)
161 if (s->main_pid != pid) {
162 service_unwatch_main_pid(s);
163 exec_status_start(&s->main_exec_status, pid);
167 s->main_pid_known = true;
169 if (get_parent_of_pid(pid, &ppid) >= 0 && ppid != getpid()) {
170 log_warning_unit(UNIT(s)->id, "%s: Supervising process "PID_FMT" which is not our child. We'll most likely not notice when it exits.", UNIT(s)->id, pid);
171 s->main_pid_alien = true;
173 s->main_pid_alien = false;
178 static void service_close_socket_fd(Service *s) {
181 s->socket_fd = asynchronous_close(s->socket_fd);
184 static void service_connection_unref(Service *s) {
187 if (!UNIT_ISSET(s->accept_socket))
190 socket_connection_unref(SOCKET(UNIT_DEREF(s->accept_socket)));
191 unit_ref_unset(&s->accept_socket);
194 static void service_stop_watchdog(Service *s) {
197 s->watchdog_event_source = sd_event_source_unref(s->watchdog_event_source);
198 s->watchdog_timestamp = DUAL_TIMESTAMP_NULL;
201 static void service_start_watchdog(Service *s) {
206 if (s->watchdog_usec <= 0)
209 if (s->watchdog_event_source) {
210 r = sd_event_source_set_time(s->watchdog_event_source, s->watchdog_timestamp.monotonic + s->watchdog_usec);
212 log_warning_unit(UNIT(s)->id, "%s failed to reset watchdog timer: %s", UNIT(s)->id, strerror(-r));
216 r = sd_event_source_set_enabled(s->watchdog_event_source, SD_EVENT_ONESHOT);
218 r = sd_event_add_time(
219 UNIT(s)->manager->event,
220 &s->watchdog_event_source,
222 s->watchdog_timestamp.monotonic + s->watchdog_usec, 0,
223 service_dispatch_watchdog, s);
225 log_warning_unit(UNIT(s)->id, "%s failed to add watchdog timer: %s", UNIT(s)->id, strerror(-r));
229 /* Let's process everything else which might be a sign
230 * of living before we consider a service died. */
231 r = sd_event_source_set_priority(s->watchdog_event_source, SD_EVENT_PRIORITY_IDLE);
235 log_warning_unit(UNIT(s)->id, "%s failed to install watchdog timer: %s", UNIT(s)->id, strerror(-r));
238 static void service_reset_watchdog(Service *s) {
241 dual_timestamp_get(&s->watchdog_timestamp);
242 service_start_watchdog(s);
245 static void service_done(Unit *u) {
246 Service *s = SERVICE(u);
253 free(s->status_text);
254 s->status_text = NULL;
257 s->reboot_arg = NULL;
259 s->exec_runtime = exec_runtime_unref(s->exec_runtime);
260 exec_command_free_array(s->exec_command, _SERVICE_EXEC_COMMAND_MAX);
261 s->control_command = NULL;
262 s->main_command = NULL;
264 exit_status_set_free(&s->restart_prevent_status);
265 exit_status_set_free(&s->restart_force_status);
266 exit_status_set_free(&s->success_status);
268 /* This will leak a process, but at least no memory or any of
270 service_unwatch_main_pid(s);
271 service_unwatch_control_pid(s);
272 service_unwatch_pid_file(s);
275 unit_unwatch_bus_name(u, s->bus_name);
280 s->bus_endpoint_fd = safe_close(s->bus_endpoint_fd);
281 service_close_socket_fd(s);
282 service_connection_unref(s);
284 unit_ref_unset(&s->accept_socket);
286 service_stop_watchdog(s);
288 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
291 static int service_arm_timer(Service *s, usec_t usec) {
296 if (s->timer_event_source) {
297 r = sd_event_source_set_time(s->timer_event_source, now(CLOCK_MONOTONIC) + usec);
301 return sd_event_source_set_enabled(s->timer_event_source, SD_EVENT_ONESHOT);
304 return sd_event_add_time(
305 UNIT(s)->manager->event,
306 &s->timer_event_source,
308 now(CLOCK_MONOTONIC) + usec, 0,
309 service_dispatch_timer, s);
312 static int service_verify(Service *s) {
315 if (UNIT(s)->load_state != UNIT_LOADED)
318 if (!s->exec_command[SERVICE_EXEC_START] && !s->exec_command[SERVICE_EXEC_STOP]) {
319 log_error_unit(UNIT(s)->id, "%s lacks both ExecStart= and ExecStop= setting. Refusing.", UNIT(s)->id);
323 if (s->type != SERVICE_ONESHOT && !s->exec_command[SERVICE_EXEC_START]) {
324 log_error_unit(UNIT(s)->id, "%s has no ExecStart= setting, which is only allowed for Type=oneshot services. Refusing.", UNIT(s)->id);
328 if (!s->remain_after_exit && !s->exec_command[SERVICE_EXEC_START]) {
329 log_error_unit(UNIT(s)->id, "%s has no ExecStart= setting, which is only allowed for RemainAfterExit=yes services. Refusing.", UNIT(s)->id);
333 if (s->type != SERVICE_ONESHOT && s->exec_command[SERVICE_EXEC_START]->command_next) {
334 log_error_unit(UNIT(s)->id, "%s has more than one ExecStart= setting, which is only allowed for Type=oneshot services. Refusing.", UNIT(s)->id);
338 if (s->type == SERVICE_ONESHOT && s->restart != SERVICE_RESTART_NO) {
339 log_error_unit(UNIT(s)->id, "%s has Restart= setting other than no, which isn't allowed for Type=oneshot services. Refusing.", UNIT(s)->id);
343 if (s->type == SERVICE_ONESHOT && !exit_status_set_is_empty(&s->restart_force_status)) {
344 log_error_unit(UNIT(s)->id, "%s has RestartForceStatus= set, which isn't allowed for Type=oneshot services. Refusing.", UNIT(s)->id);
348 if (s->type == SERVICE_DBUS && !s->bus_name) {
349 log_error_unit(UNIT(s)->id, "%s is of type D-Bus but no D-Bus service name has been specified. Refusing.", UNIT(s)->id);
353 if (s->bus_name && s->type != SERVICE_DBUS)
354 log_warning_unit(UNIT(s)->id, "%s has a D-Bus service name specified, but is not of type dbus. Ignoring.", UNIT(s)->id);
356 if (s->exec_context.pam_name && !(s->kill_context.kill_mode == KILL_CONTROL_GROUP || s->kill_context.kill_mode == KILL_MIXED)) {
357 log_error_unit(UNIT(s)->id, "%s has PAM enabled. Kill mode must be set to 'control-group' or 'mixed'. Refusing.", UNIT(s)->id);
364 static int service_add_default_dependencies(Service *s) {
369 /* Add a number of automatic dependencies useful for the
370 * majority of services. */
372 /* First, pull in base system */
373 r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_BASIC_TARGET, NULL, true);
377 /* Second, activate normal shutdown */
378 r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true);
382 static void service_fix_output(Service *s) {
385 /* If nothing has been explicitly configured, patch default
386 * output in. If input is socket/tty we avoid this however,
387 * since in that case we want output to default to the same
388 * place as we read input from. */
390 if (s->exec_context.std_error == EXEC_OUTPUT_INHERIT &&
391 s->exec_context.std_output == EXEC_OUTPUT_INHERIT &&
392 s->exec_context.std_input == EXEC_INPUT_NULL)
393 s->exec_context.std_error = UNIT(s)->manager->default_std_error;
395 if (s->exec_context.std_output == EXEC_OUTPUT_INHERIT &&
396 s->exec_context.std_input == EXEC_INPUT_NULL)
397 s->exec_context.std_output = UNIT(s)->manager->default_std_output;
400 static int service_load(Unit *u) {
401 Service *s = SERVICE(u);
406 /* Load a .service file */
407 r = unit_load_fragment(u);
411 /* Still nothing found? Then let's give up */
412 if (u->load_state == UNIT_STUB)
415 /* This is a new unit? Then let's add in some extras */
416 if (u->load_state == UNIT_LOADED) {
418 /* We were able to load something, then let's add in
419 * the dropin directories. */
420 r = unit_load_dropin(u);
424 if (s->type == _SERVICE_TYPE_INVALID) {
425 /* Figure out a type automatically */
427 s->type = SERVICE_DBUS;
428 else if (s->exec_command[SERVICE_EXEC_START])
429 s->type = SERVICE_SIMPLE;
431 s->type = SERVICE_ONESHOT;
434 /* Oneshot services have disabled start timeout by default */
435 if (s->type == SERVICE_ONESHOT && !s->start_timeout_defined)
436 s->timeout_start_usec = 0;
438 service_fix_output(s);
440 r = unit_patch_contexts(u);
444 r = unit_add_exec_dependencies(u, &s->exec_context);
448 r = unit_add_default_slice(u, &s->cgroup_context);
452 if (s->type == SERVICE_NOTIFY && s->notify_access == NOTIFY_NONE)
453 s->notify_access = NOTIFY_MAIN;
455 if (s->watchdog_usec > 0 && s->notify_access == NOTIFY_NONE)
456 s->notify_access = NOTIFY_MAIN;
459 r = unit_watch_bus_name(u, s->bus_name);
464 if (u->default_dependencies) {
465 r = service_add_default_dependencies(s);
472 return service_verify(s);
475 static void service_dump(Unit *u, FILE *f, const char *prefix) {
476 ServiceExecCommand c;
477 Service *s = SERVICE(u);
482 prefix = strempty(prefix);
483 prefix2 = strappenda(prefix, "\t");
486 "%sService State: %s\n"
488 "%sReload Result: %s\n"
489 "%sPermissionsStartOnly: %s\n"
490 "%sRootDirectoryStartOnly: %s\n"
491 "%sRemainAfterExit: %s\n"
492 "%sGuessMainPID: %s\n"
495 "%sNotifyAccess: %s\n"
496 "%sNotifyState: %s\n",
497 prefix, service_state_to_string(s->state),
498 prefix, service_result_to_string(s->result),
499 prefix, service_result_to_string(s->reload_result),
500 prefix, yes_no(s->permissions_start_only),
501 prefix, yes_no(s->root_directory_start_only),
502 prefix, yes_no(s->remain_after_exit),
503 prefix, yes_no(s->guess_main_pid),
504 prefix, service_type_to_string(s->type),
505 prefix, service_restart_to_string(s->restart),
506 prefix, notify_access_to_string(s->notify_access),
507 prefix, notify_state_to_string(s->notify_state));
509 if (s->control_pid > 0)
511 "%sControl PID: "PID_FMT"\n",
512 prefix, s->control_pid);
516 "%sMain PID: "PID_FMT"\n"
517 "%sMain PID Known: %s\n"
518 "%sMain PID Alien: %s\n",
520 prefix, yes_no(s->main_pid_known),
521 prefix, yes_no(s->main_pid_alien));
526 prefix, s->pid_file);
531 "%sBus Name Good: %s\n",
533 prefix, yes_no(s->bus_name_good));
535 kill_context_dump(&s->kill_context, f, prefix);
536 exec_context_dump(&s->exec_context, f, prefix);
538 for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
540 if (!s->exec_command[c])
543 fprintf(f, "%s-> %s:\n",
544 prefix, service_exec_command_to_string(c));
546 exec_command_dump_list(s->exec_command[c], f, prefix2);
549 #ifdef HAVE_SYSV_COMPAT
550 if (s->sysv_start_priority >= 0)
552 "%sSysVStartPriority: %i\n",
553 prefix, s->sysv_start_priority);
557 fprintf(f, "%sStatus Text: %s\n",
558 prefix, s->status_text);
561 static int service_load_pid_file(Service *s, bool may_warn) {
562 _cleanup_free_ char *k = NULL;
571 r = read_one_line_file(s->pid_file, &k);
574 log_info_unit(UNIT(s)->id, "PID file %s not readable (yet?) after %s.", s->pid_file, service_state_to_string(s->state));
578 r = parse_pid(k, &pid);
581 log_info_unit(UNIT(s)->id, "Failed to read PID from file %s: %s", s->pid_file, strerror(-r));
585 if (!pid_is_alive(pid)) {
587 log_info_unit(UNIT(s)->id, "PID "PID_FMT" read from file %s does not exist or is a zombie.", pid, s->pid_file);
591 if (s->main_pid_known) {
592 if (pid == s->main_pid)
595 log_debug_unit(UNIT(s)->id, "Main PID changing: "PID_FMT" -> "PID_FMT, s->main_pid, pid);
597 service_unwatch_main_pid(s);
598 s->main_pid_known = false;
600 log_debug_unit(UNIT(s)->id, "Main PID loaded: "PID_FMT, pid);
602 r = service_set_main_pid(s, pid);
606 r = unit_watch_pid(UNIT(s), pid);
608 /* FIXME: we need to do something here */
609 log_warning_unit(UNIT(s)->id, "Failed to watch PID "PID_FMT" from service %s", pid, UNIT(s)->id);
616 static int service_search_main_pid(Service *s) {
622 /* If we know it anyway, don't ever fallback to unreliable
624 if (s->main_pid_known)
627 if (!s->guess_main_pid)
630 assert(s->main_pid <= 0);
632 pid = unit_search_main_pid(UNIT(s));
636 log_debug_unit(UNIT(s)->id, "Main PID guessed: "PID_FMT, pid);
637 r = service_set_main_pid(s, pid);
641 r = unit_watch_pid(UNIT(s), pid);
643 /* FIXME: we need to do something here */
644 log_warning_unit(UNIT(s)->id, "Failed to watch PID "PID_FMT" from service %s", pid, UNIT(s)->id);
651 static void service_set_state(Service *s, ServiceState state) {
652 ServiceState old_state;
653 const UnitActiveState *table;
657 table = s->type == SERVICE_IDLE ? state_translation_table_idle : state_translation_table;
659 old_state = s->state;
662 service_unwatch_pid_file(s);
665 SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
667 SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL,
668 SERVICE_STOP_SIGABRT, SERVICE_STOP_POST,
669 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL,
670 SERVICE_AUTO_RESTART))
671 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
674 SERVICE_START, SERVICE_START_POST,
675 SERVICE_RUNNING, SERVICE_RELOAD,
676 SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL,
677 SERVICE_STOP_SIGABRT, SERVICE_STOP_POST,
678 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL)) {
679 service_unwatch_main_pid(s);
680 s->main_command = NULL;
684 SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
686 SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL,
687 SERVICE_STOP_SIGABRT, SERVICE_STOP_POST,
688 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL)) {
689 service_unwatch_control_pid(s);
690 s->control_command = NULL;
691 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
694 if (IN_SET(state, SERVICE_DEAD, SERVICE_FAILED, SERVICE_AUTO_RESTART))
695 unit_unwatch_all_pids(UNIT(s));
698 SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
699 SERVICE_RUNNING, SERVICE_RELOAD,
700 SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
701 SERVICE_STOP_SIGABRT, SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL) &&
702 !(state == SERVICE_DEAD && UNIT(s)->job)) {
703 service_close_socket_fd(s);
704 service_connection_unref(s);
707 if (!IN_SET(state, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD))
708 service_stop_watchdog(s);
710 /* For the inactive states unit_notify() will trim the cgroup,
711 * but for exit we have to do that ourselves... */
712 if (state == SERVICE_EXITED && UNIT(s)->manager->n_reloading <= 0)
713 unit_destroy_cgroup(UNIT(s));
715 /* For remain_after_exit services, let's see if we can "release" the
716 * hold on the console, since unit_notify() only does that in case of
718 if (state == SERVICE_EXITED &&
719 s->remain_after_exit &&
720 UNIT(s)->manager->n_on_console > 0) {
724 ec = unit_get_exec_context(UNIT(s));
725 if (ec && exec_context_may_touch_console(ec)) {
726 Manager *m = UNIT(s)->manager;
729 if (m->n_on_console == 0)
730 /* unset no_console_output flag, since the console is free */
731 m->no_console_output = false;
735 if (old_state != state)
736 log_debug_unit(UNIT(s)->id, "%s changed %s -> %s", UNIT(s)->id, service_state_to_string(old_state), service_state_to_string(state));
738 unit_notify(UNIT(s), table[old_state], table[state], s->reload_result == SERVICE_SUCCESS);
739 s->reload_result = SERVICE_SUCCESS;
742 static int service_coldplug(Unit *u) {
743 Service *s = SERVICE(u);
747 assert(s->state == SERVICE_DEAD);
749 if (s->deserialized_state != s->state) {
751 if (IN_SET(s->deserialized_state,
752 SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
754 SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL,
755 SERVICE_STOP_SIGABRT, SERVICE_STOP_POST,
756 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL)) {
760 k = IN_SET(s->deserialized_state, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST, SERVICE_RELOAD) ? s->timeout_start_usec : s->timeout_stop_usec;
762 /* For the start/stop timeouts 0 means off */
764 r = service_arm_timer(s, k);
770 if (s->deserialized_state == SERVICE_AUTO_RESTART) {
772 /* The restart timeouts 0 means immediately */
773 r = service_arm_timer(s, s->restart_usec);
778 if (pid_is_unwaited(s->main_pid) &&
779 ((s->deserialized_state == SERVICE_START && IN_SET(s->type, SERVICE_FORKING, SERVICE_DBUS, SERVICE_ONESHOT, SERVICE_NOTIFY)) ||
780 IN_SET(s->deserialized_state,
781 SERVICE_START, SERVICE_START_POST,
782 SERVICE_RUNNING, SERVICE_RELOAD,
783 SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL,
784 SERVICE_STOP_SIGABRT, SERVICE_STOP_POST,
785 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL))) {
786 r = unit_watch_pid(UNIT(s), s->main_pid);
791 if (pid_is_unwaited(s->control_pid) &&
792 IN_SET(s->deserialized_state,
793 SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
795 SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL,
796 SERVICE_STOP_SIGABRT, SERVICE_STOP_POST,
797 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL)) {
798 r = unit_watch_pid(UNIT(s), s->control_pid);
803 if (!IN_SET(s->deserialized_state, SERVICE_DEAD, SERVICE_FAILED, SERVICE_AUTO_RESTART))
804 unit_watch_all_pids(UNIT(s));
806 if (IN_SET(s->deserialized_state, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD))
807 service_start_watchdog(s);
809 service_set_state(s, s->deserialized_state);
815 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
826 if (s->socket_fd >= 0)
829 SET_FOREACH(u, UNIT(s)->dependencies[UNIT_TRIGGERED_BY], i) {
834 if (u->type != UNIT_SOCKET)
839 r = socket_collect_fds(sock, &cfds, &cn_fds);
852 t = new(int, rn_fds+cn_fds);
859 memcpy(t, rfds, rn_fds * sizeof(int));
860 memcpy(t+rn_fds, cfds, cn_fds * sizeof(int));
865 rn_fds = rn_fds+cn_fds;
880 static int service_spawn(
885 bool apply_permissions,
887 bool apply_tty_stdin,
894 _cleanup_free_ int *fdsbuf = NULL;
895 unsigned n_fds = 0, n_env = 0;
896 _cleanup_free_ char *bus_endpoint_path = NULL;
897 _cleanup_strv_free_ char
898 **argv = NULL, **final_env = NULL, **our_env = NULL;
900 ExecParameters exec_params = {
901 .apply_permissions = apply_permissions,
902 .apply_chroot = apply_chroot,
903 .apply_tty_stdin = apply_tty_stdin,
904 .bus_endpoint_fd = -1,
905 .selinux_context_net = s->socket_fd_selinux_context_net
912 unit_realize_cgroup(UNIT(s));
914 r = unit_setup_exec_runtime(UNIT(s));
919 s->exec_context.std_input == EXEC_INPUT_SOCKET ||
920 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
921 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
923 if (s->socket_fd >= 0) {
927 r = service_collect_fds(s, &fdsbuf, &n_fds);
936 r = service_arm_timer(s, timeout);
940 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
942 r = unit_full_printf_strv(UNIT(s), c->argv, &argv);
946 our_env = new0(char*, 4);
952 if (is_control ? s->notify_access == NOTIFY_ALL : s->notify_access != NOTIFY_NONE)
953 if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=%s", UNIT(s)->manager->notify_socket) < 0) {
959 if (asprintf(our_env + n_env++, "MAINPID="PID_FMT, s->main_pid) < 0) {
964 if (UNIT(s)->manager->running_as != SYSTEMD_SYSTEM)
965 if (asprintf(our_env + n_env++, "MANAGERPID="PID_FMT, getpid()) < 0) {
970 final_env = strv_env_merge(2, UNIT(s)->manager->environment, our_env, NULL);
976 if (is_control && UNIT(s)->cgroup_path) {
977 path = strappenda(UNIT(s)->cgroup_path, "/control");
978 cg_create(SYSTEMD_CGROUP_CONTROLLER, path);
980 path = UNIT(s)->cgroup_path;
983 if (s->exec_context.bus_endpoint) {
984 r = bus_kernel_create_endpoint(UNIT(s)->manager->running_as == SYSTEMD_SYSTEM ? "system" : "user",
985 UNIT(s)->id, &bus_endpoint_path);
989 /* Pass the fd to the exec_params so that the child process can upload the policy.
990 * Keep a reference to the fd in the service, so the endpoint is kept alive as long
991 * as the service is running. */
992 exec_params.bus_endpoint_fd = s->bus_endpoint_fd = r;
996 exec_params.argv = argv;
997 exec_params.fds = fds;
998 exec_params.n_fds = n_fds;
999 exec_params.environment = final_env;
1000 exec_params.confirm_spawn = UNIT(s)->manager->confirm_spawn;
1001 exec_params.cgroup_supported = UNIT(s)->manager->cgroup_supported;
1002 exec_params.cgroup_path = path;
1003 exec_params.cgroup_delegate = s->cgroup_context.delegate;
1004 exec_params.runtime_prefix = manager_get_runtime_prefix(UNIT(s)->manager);
1005 exec_params.unit_id = UNIT(s)->id;
1006 exec_params.watchdog_usec = s->watchdog_usec;
1007 exec_params.bus_endpoint_path = bus_endpoint_path;
1008 if (s->type == SERVICE_IDLE)
1009 exec_params.idle_pipe = UNIT(s)->manager->idle_pipe;
1019 r = unit_watch_pid(UNIT(s), pid);
1021 /* FIXME: we need to do something here */
1030 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
1035 static int main_pid_good(Service *s) {
1038 /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1041 /* If we know the pid file, then lets just check if it is
1043 if (s->main_pid_known) {
1045 /* If it's an alien child let's check if it is still
1047 if (s->main_pid_alien && s->main_pid > 0)
1048 return pid_is_alive(s->main_pid);
1050 /* .. otherwise assume we'll get a SIGCHLD for it,
1051 * which we really should wait for to collect exit
1052 * status and code */
1053 return s->main_pid > 0;
1056 /* We don't know the pid */
1060 _pure_ static int control_pid_good(Service *s) {
1063 return s->control_pid > 0;
1066 static int cgroup_good(Service *s) {
1071 if (!UNIT(s)->cgroup_path)
1074 r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, UNIT(s)->cgroup_path, true);
1081 static void service_enter_dead(Service *s, ServiceResult f, bool allow_restart) {
1085 if (f != SERVICE_SUCCESS)
1088 service_set_state(s, s->result != SERVICE_SUCCESS ? SERVICE_FAILED : SERVICE_DEAD);
1090 if (s->result != SERVICE_SUCCESS) {
1091 log_warning_unit(UNIT(s)->id, "%s failed.", UNIT(s)->id);
1092 failure_action(UNIT(s)->manager, s->failure_action, s->reboot_arg);
1095 if (allow_restart &&
1096 !s->forbid_restart &&
1097 (s->restart == SERVICE_RESTART_ALWAYS ||
1098 (s->restart == SERVICE_RESTART_ON_SUCCESS && s->result == SERVICE_SUCCESS) ||
1099 (s->restart == SERVICE_RESTART_ON_FAILURE && s->result != SERVICE_SUCCESS) ||
1100 (s->restart == SERVICE_RESTART_ON_ABNORMAL && !IN_SET(s->result, SERVICE_SUCCESS, SERVICE_FAILURE_EXIT_CODE)) ||
1101 (s->restart == SERVICE_RESTART_ON_WATCHDOG && s->result == SERVICE_FAILURE_WATCHDOG) ||
1102 (s->restart == SERVICE_RESTART_ON_ABORT && IN_SET(s->result, SERVICE_FAILURE_SIGNAL, SERVICE_FAILURE_CORE_DUMP)) ||
1103 (s->main_exec_status.code == CLD_EXITED && set_contains(s->restart_force_status.status, INT_TO_PTR(s->main_exec_status.status))) ||
1104 (IN_SET(s->main_exec_status.code, CLD_KILLED, CLD_DUMPED) && set_contains(s->restart_force_status.signal, INT_TO_PTR(s->main_exec_status.status)))) &&
1105 (s->main_exec_status.code != CLD_EXITED || !set_contains(s->restart_prevent_status.status, INT_TO_PTR(s->main_exec_status.status))) &&
1106 (!IN_SET(s->main_exec_status.code, CLD_KILLED, CLD_DUMPED) || !set_contains(s->restart_prevent_status.signal, INT_TO_PTR(s->main_exec_status.status)))) {
1108 r = service_arm_timer(s, s->restart_usec);
1112 service_set_state(s, SERVICE_AUTO_RESTART);
1115 s->forbid_restart = false;
1117 /* We want fresh tmpdirs in case service is started again immediately */
1118 exec_runtime_destroy(s->exec_runtime);
1119 s->exec_runtime = exec_runtime_unref(s->exec_runtime);
1121 /* Also, remove the runtime directory in */
1122 exec_context_destroy_runtime_directory(&s->exec_context, manager_get_runtime_prefix(UNIT(s)->manager));
1124 /* Try to delete the pid file. At this point it will be
1125 * out-of-date, and some software might be confused by it, so
1126 * let's remove it. */
1128 unlink_noerrno(s->pid_file);
1133 log_warning_unit(UNIT(s)->id, "%s failed to run install restart timer: %s", UNIT(s)->id, strerror(-r));
1134 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, false);
1137 static void service_enter_stop_post(Service *s, ServiceResult f) {
1141 if (f != SERVICE_SUCCESS)
1144 service_unwatch_control_pid(s);
1145 unit_watch_all_pids(UNIT(s));
1147 s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST];
1148 if (s->control_command) {
1149 s->control_command_id = SERVICE_EXEC_STOP_POST;
1151 r = service_spawn(s,
1153 s->timeout_stop_usec,
1155 !s->permissions_start_only,
1156 !s->root_directory_start_only,
1163 service_set_state(s, SERVICE_STOP_POST);
1165 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_SUCCESS);
1170 log_warning_unit(UNIT(s)->id, "%s failed to run 'stop-post' task: %s", UNIT(s)->id, strerror(-r));
1171 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
1174 static void service_enter_signal(Service *s, ServiceState state, ServiceResult f) {
1179 if (f != SERVICE_SUCCESS)
1182 unit_watch_all_pids(UNIT(s));
1184 r = unit_kill_context(
1187 (state != SERVICE_STOP_SIGTERM && state != SERVICE_FINAL_SIGTERM && state != SERVICE_STOP_SIGABRT) ?
1188 KILL_KILL : (state == SERVICE_STOP_SIGABRT ? KILL_ABORT : KILL_TERMINATE),
1197 if (s->timeout_stop_usec > 0) {
1198 r = service_arm_timer(s, s->timeout_stop_usec);
1203 service_set_state(s, state);
1204 } else if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGABRT)
1205 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_SUCCESS);
1206 else if (state == SERVICE_STOP_SIGKILL)
1207 service_enter_stop_post(s, SERVICE_SUCCESS);
1208 else if (state == SERVICE_FINAL_SIGTERM)
1209 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_SUCCESS);
1211 service_enter_dead(s, SERVICE_SUCCESS, true);
1216 log_warning_unit(UNIT(s)->id, "%s failed to kill processes: %s", UNIT(s)->id, strerror(-r));
1218 if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL ||
1219 state == SERVICE_STOP_SIGABRT)
1220 service_enter_stop_post(s, SERVICE_FAILURE_RESOURCES);
1222 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
1225 static void service_enter_stop_by_notify(Service *s) {
1228 unit_watch_all_pids(UNIT(s));
1230 if (s->timeout_stop_usec > 0)
1231 service_arm_timer(s, s->timeout_stop_usec);
1233 /* The service told us it's stopping, so it's as if we SIGTERM'd it. */
1234 service_set_state(s, SERVICE_STOP_SIGTERM);
1237 static void service_enter_stop(Service *s, ServiceResult f) {
1242 if (f != SERVICE_SUCCESS)
1245 service_unwatch_control_pid(s);
1246 unit_watch_all_pids(UNIT(s));
1248 s->control_command = s->exec_command[SERVICE_EXEC_STOP];
1249 if (s->control_command) {
1250 s->control_command_id = SERVICE_EXEC_STOP;
1252 r = service_spawn(s,
1254 s->timeout_stop_usec,
1256 !s->permissions_start_only,
1257 !s->root_directory_start_only,
1264 service_set_state(s, SERVICE_STOP);
1266 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
1271 log_warning_unit(UNIT(s)->id, "%s failed to run 'stop' task: %s", UNIT(s)->id, strerror(-r));
1272 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
1275 static void service_enter_running(Service *s, ServiceResult f) {
1276 int main_pid_ok, cgroup_ok;
1279 if (f != SERVICE_SUCCESS)
1282 main_pid_ok = main_pid_good(s);
1283 cgroup_ok = cgroup_good(s);
1285 if ((main_pid_ok > 0 || (main_pid_ok < 0 && cgroup_ok != 0)) &&
1286 (s->bus_name_good || s->type != SERVICE_DBUS)) {
1288 /* If there are any queued up sd_notify()
1289 * notifications, process them now */
1290 if (s->notify_state == NOTIFY_RELOADING)
1291 service_enter_reload_by_notify(s);
1292 else if (s->notify_state == NOTIFY_STOPPING)
1293 service_enter_stop_by_notify(s);
1295 service_set_state(s, SERVICE_RUNNING);
1297 } else if (s->remain_after_exit)
1298 service_set_state(s, SERVICE_EXITED);
1300 service_enter_stop(s, SERVICE_SUCCESS);
1303 static void service_enter_start_post(Service *s) {
1307 service_unwatch_control_pid(s);
1308 service_reset_watchdog(s);
1310 s->control_command = s->exec_command[SERVICE_EXEC_START_POST];
1311 if (s->control_command) {
1312 s->control_command_id = SERVICE_EXEC_START_POST;
1314 r = service_spawn(s,
1316 s->timeout_start_usec,
1318 !s->permissions_start_only,
1319 !s->root_directory_start_only,
1326 service_set_state(s, SERVICE_START_POST);
1328 service_enter_running(s, SERVICE_SUCCESS);
1333 log_warning_unit(UNIT(s)->id, "%s failed to run 'start-post' task: %s", UNIT(s)->id, strerror(-r));
1334 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
1337 static void service_kill_control_processes(Service *s) {
1340 if (!UNIT(s)->cgroup_path)
1343 p = strappenda(UNIT(s)->cgroup_path, "/control");
1344 cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, p, SIGKILL, true, true, true, NULL);
1347 static void service_enter_start(Service *s) {
1354 service_unwatch_control_pid(s);
1355 service_unwatch_main_pid(s);
1357 /* We want to ensure that nobody leaks processes from
1358 * START_PRE here, so let's go on a killing spree, People
1359 * should not spawn long running processes from START_PRE. */
1360 service_kill_control_processes(s);
1362 if (s->type == SERVICE_FORKING) {
1363 s->control_command_id = SERVICE_EXEC_START;
1364 c = s->control_command = s->exec_command[SERVICE_EXEC_START];
1366 s->main_command = NULL;
1368 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1369 s->control_command = NULL;
1371 c = s->main_command = s->exec_command[SERVICE_EXEC_START];
1375 assert(s->type == SERVICE_ONESHOT);
1376 service_enter_start_post(s);
1380 r = service_spawn(s,
1382 IN_SET(s->type, SERVICE_FORKING, SERVICE_DBUS, SERVICE_NOTIFY, SERVICE_ONESHOT) ? s->timeout_start_usec : 0,
1392 if (s->type == SERVICE_SIMPLE || s->type == SERVICE_IDLE) {
1393 /* For simple services we immediately start
1394 * the START_POST binaries. */
1396 service_set_main_pid(s, pid);
1397 service_enter_start_post(s);
1399 } else if (s->type == SERVICE_FORKING) {
1401 /* For forking services we wait until the start
1402 * process exited. */
1404 s->control_pid = pid;
1405 service_set_state(s, SERVICE_START);
1407 } else if (s->type == SERVICE_ONESHOT ||
1408 s->type == SERVICE_DBUS ||
1409 s->type == SERVICE_NOTIFY) {
1411 /* For oneshot services we wait until the start
1412 * process exited, too, but it is our main process. */
1414 /* For D-Bus services we know the main pid right away,
1415 * but wait for the bus name to appear on the
1416 * bus. Notify services are similar. */
1418 service_set_main_pid(s, pid);
1419 service_set_state(s, SERVICE_START);
1421 assert_not_reached("Unknown service type");
1426 log_warning_unit(UNIT(s)->id, "%s failed to run 'start' task: %s", UNIT(s)->id, strerror(-r));
1427 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
1430 static void service_enter_start_pre(Service *s) {
1435 service_unwatch_control_pid(s);
1437 s->control_command = s->exec_command[SERVICE_EXEC_START_PRE];
1438 if (s->control_command) {
1439 /* Before we start anything, let's clear up what might
1440 * be left from previous runs. */
1441 service_kill_control_processes(s);
1443 s->control_command_id = SERVICE_EXEC_START_PRE;
1445 r = service_spawn(s,
1447 s->timeout_start_usec,
1449 !s->permissions_start_only,
1450 !s->root_directory_start_only,
1457 service_set_state(s, SERVICE_START_PRE);
1459 service_enter_start(s);
1464 log_warning_unit(UNIT(s)->id, "%s failed to run 'start-pre' task: %s", UNIT(s)->id, strerror(-r));
1465 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
1468 static void service_enter_restart(Service *s) {
1469 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
1474 if (UNIT(s)->job && UNIT(s)->job->type == JOB_STOP) {
1475 /* Don't restart things if we are going down anyway */
1476 log_info_unit(UNIT(s)->id, "Stop job pending for unit, delaying automatic restart.");
1478 r = service_arm_timer(s, s->restart_usec);
1485 /* Any units that are bound to this service must also be
1486 * restarted. We use JOB_RESTART (instead of the more obvious
1487 * JOB_START) here so that those dependency jobs will be added
1489 r = manager_add_job(UNIT(s)->manager, JOB_RESTART, UNIT(s), JOB_FAIL, false, &error, NULL);
1493 /* Note that we stay in the SERVICE_AUTO_RESTART state here,
1494 * it will be canceled as part of the service_stop() call that
1495 * is executed as part of JOB_RESTART. */
1497 log_debug_unit(UNIT(s)->id, "%s scheduled restart job.", UNIT(s)->id);
1501 log_warning_unit(UNIT(s)->id, "%s failed to schedule restart job: %s", UNIT(s)->id, bus_error_message(&error, -r));
1502 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, false);
1505 static void service_enter_reload_by_notify(Service *s) {
1508 if (s->timeout_start_usec > 0)
1509 service_arm_timer(s, s->timeout_start_usec);
1511 service_set_state(s, SERVICE_RELOAD);
1514 static void service_enter_reload(Service *s) {
1519 service_unwatch_control_pid(s);
1521 s->control_command = s->exec_command[SERVICE_EXEC_RELOAD];
1522 if (s->control_command) {
1523 s->control_command_id = SERVICE_EXEC_RELOAD;
1525 r = service_spawn(s,
1527 s->timeout_start_usec,
1529 !s->permissions_start_only,
1530 !s->root_directory_start_only,
1537 service_set_state(s, SERVICE_RELOAD);
1539 service_enter_running(s, SERVICE_SUCCESS);
1544 log_warning_unit(UNIT(s)->id, "%s failed to run 'reload' task: %s", UNIT(s)->id, strerror(-r));
1545 s->reload_result = SERVICE_FAILURE_RESOURCES;
1546 service_enter_running(s, SERVICE_SUCCESS);
1549 static void service_run_next_control(Service *s) {
1553 assert(s->control_command);
1554 assert(s->control_command->command_next);
1556 assert(s->control_command_id != SERVICE_EXEC_START);
1558 s->control_command = s->control_command->command_next;
1559 service_unwatch_control_pid(s);
1561 r = service_spawn(s,
1563 IN_SET(s->state, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD) ? s->timeout_start_usec : s->timeout_stop_usec,
1565 !s->permissions_start_only,
1566 !s->root_directory_start_only,
1567 s->control_command_id == SERVICE_EXEC_START_PRE ||
1568 s->control_command_id == SERVICE_EXEC_STOP_POST,
1577 log_warning_unit(UNIT(s)->id, "%s failed to run next control task: %s", UNIT(s)->id, strerror(-r));
1579 if (s->state == SERVICE_START_PRE)
1580 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
1581 else if (s->state == SERVICE_STOP)
1582 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
1583 else if (s->state == SERVICE_STOP_POST)
1584 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
1585 else if (s->state == SERVICE_RELOAD) {
1586 s->reload_result = SERVICE_FAILURE_RESOURCES;
1587 service_enter_running(s, SERVICE_SUCCESS);
1589 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
1592 static void service_run_next_main(Service *s) {
1597 assert(s->main_command);
1598 assert(s->main_command->command_next);
1599 assert(s->type == SERVICE_ONESHOT);
1601 s->main_command = s->main_command->command_next;
1602 service_unwatch_main_pid(s);
1604 r = service_spawn(s,
1606 s->timeout_start_usec,
1616 service_set_main_pid(s, pid);
1621 log_warning_unit(UNIT(s)->id, "%s failed to run next main task: %s", UNIT(s)->id, strerror(-r));
1622 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
1625 static int service_start_limit_test(Service *s) {
1628 if (ratelimit_test(&s->start_limit))
1631 log_warning_unit(UNIT(s)->id, "start request repeated too quickly for %s", UNIT(s)->id);
1633 return failure_action(UNIT(s)->manager, s->start_limit_action, s->reboot_arg);
1636 static int service_start(Unit *u) {
1637 Service *s = SERVICE(u);
1642 /* We cannot fulfill this request right now, try again later
1644 if (s->state == SERVICE_STOP ||
1645 s->state == SERVICE_STOP_SIGABRT ||
1646 s->state == SERVICE_STOP_SIGTERM ||
1647 s->state == SERVICE_STOP_SIGKILL ||
1648 s->state == SERVICE_STOP_POST ||
1649 s->state == SERVICE_FINAL_SIGTERM ||
1650 s->state == SERVICE_FINAL_SIGKILL)
1653 /* Already on it! */
1654 if (s->state == SERVICE_START_PRE ||
1655 s->state == SERVICE_START ||
1656 s->state == SERVICE_START_POST)
1659 /* A service that will be restarted must be stopped first to
1660 * trigger BindsTo and/or OnFailure dependencies. If a user
1661 * does not want to wait for the holdoff time to elapse, the
1662 * service should be manually restarted, not started. We
1663 * simply return EAGAIN here, so that any start jobs stay
1664 * queued, and assume that the auto restart timer will
1665 * eventually trigger the restart. */
1666 if (s->state == SERVICE_AUTO_RESTART)
1669 assert(s->state == SERVICE_DEAD || s->state == SERVICE_FAILED);
1671 /* Make sure we don't enter a busy loop of some kind. */
1672 r = service_start_limit_test(s);
1674 service_enter_dead(s, SERVICE_FAILURE_START_LIMIT, false);
1678 s->result = SERVICE_SUCCESS;
1679 s->reload_result = SERVICE_SUCCESS;
1680 s->main_pid_known = false;
1681 s->main_pid_alien = false;
1682 s->forbid_restart = false;
1684 free(s->status_text);
1685 s->status_text = NULL;
1686 s->status_errno = 0;
1688 s->notify_state = NOTIFY_UNKNOWN;
1690 service_enter_start_pre(s);
1694 static int service_stop(Unit *u) {
1695 Service *s = SERVICE(u);
1699 /* Don't create restart jobs from here. */
1700 s->forbid_restart = true;
1703 if (s->state == SERVICE_STOP ||
1704 s->state == SERVICE_STOP_SIGABRT ||
1705 s->state == SERVICE_STOP_SIGTERM ||
1706 s->state == SERVICE_STOP_SIGKILL ||
1707 s->state == SERVICE_STOP_POST ||
1708 s->state == SERVICE_FINAL_SIGTERM ||
1709 s->state == SERVICE_FINAL_SIGKILL)
1712 /* A restart will be scheduled or is in progress. */
1713 if (s->state == SERVICE_AUTO_RESTART) {
1714 service_set_state(s, SERVICE_DEAD);
1718 /* If there's already something running we go directly into
1720 if (s->state == SERVICE_START_PRE ||
1721 s->state == SERVICE_START ||
1722 s->state == SERVICE_START_POST ||
1723 s->state == SERVICE_RELOAD) {
1724 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
1728 assert(s->state == SERVICE_RUNNING ||
1729 s->state == SERVICE_EXITED);
1731 service_enter_stop(s, SERVICE_SUCCESS);
1735 static int service_reload(Unit *u) {
1736 Service *s = SERVICE(u);
1740 assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
1742 service_enter_reload(s);
1746 _pure_ static bool service_can_reload(Unit *u) {
1747 Service *s = SERVICE(u);
1751 return !!s->exec_command[SERVICE_EXEC_RELOAD];
1754 static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
1755 Service *s = SERVICE(u);
1761 unit_serialize_item(u, f, "state", service_state_to_string(s->state));
1762 unit_serialize_item(u, f, "result", service_result_to_string(s->result));
1763 unit_serialize_item(u, f, "reload-result", service_result_to_string(s->reload_result));
1765 if (s->control_pid > 0)
1766 unit_serialize_item_format(u, f, "control-pid", PID_FMT,
1769 if (s->main_pid_known && s->main_pid > 0)
1770 unit_serialize_item_format(u, f, "main-pid", PID_FMT, s->main_pid);
1772 unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
1775 unit_serialize_item(u, f, "status-text", s->status_text);
1777 /* FIXME: There's a minor uncleanliness here: if there are
1778 * multiple commands attached here, we will start from the
1779 * first one again */
1780 if (s->control_command_id >= 0)
1781 unit_serialize_item(u, f, "control-command",
1782 service_exec_command_to_string(s->control_command_id));
1784 if (s->socket_fd >= 0) {
1787 if ((copy = fdset_put_dup(fds, s->socket_fd)) < 0)
1790 unit_serialize_item_format(u, f, "socket-fd", "%i", copy);
1793 if (s->bus_endpoint_fd >= 0) {
1796 if ((copy = fdset_put_dup(fds, s->bus_endpoint_fd)) < 0)
1799 unit_serialize_item_format(u, f, "endpoint-fd", "%i", copy);
1802 if (s->main_exec_status.pid > 0) {
1803 unit_serialize_item_format(u, f, "main-exec-status-pid", PID_FMT,
1804 s->main_exec_status.pid);
1805 dual_timestamp_serialize(f, "main-exec-status-start",
1806 &s->main_exec_status.start_timestamp);
1807 dual_timestamp_serialize(f, "main-exec-status-exit",
1808 &s->main_exec_status.exit_timestamp);
1810 if (dual_timestamp_is_set(&s->main_exec_status.exit_timestamp)) {
1811 unit_serialize_item_format(u, f, "main-exec-status-code", "%i",
1812 s->main_exec_status.code);
1813 unit_serialize_item_format(u, f, "main-exec-status-status", "%i",
1814 s->main_exec_status.status);
1817 if (dual_timestamp_is_set(&s->watchdog_timestamp))
1818 dual_timestamp_serialize(f, "watchdog-timestamp", &s->watchdog_timestamp);
1820 if (s->forbid_restart)
1821 unit_serialize_item(u, f, "forbid-restart", yes_no(s->forbid_restart));
1826 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
1827 Service *s = SERVICE(u);
1834 if (streq(key, "state")) {
1837 state = service_state_from_string(value);
1839 log_debug_unit(u->id, "Failed to parse state value %s", value);
1841 s->deserialized_state = state;
1842 } else if (streq(key, "result")) {
1845 f = service_result_from_string(value);
1847 log_debug_unit(u->id, "Failed to parse result value %s", value);
1848 else if (f != SERVICE_SUCCESS)
1851 } else if (streq(key, "reload-result")) {
1854 f = service_result_from_string(value);
1856 log_debug_unit(u->id, "Failed to parse reload result value %s", value);
1857 else if (f != SERVICE_SUCCESS)
1858 s->reload_result = f;
1860 } else if (streq(key, "control-pid")) {
1863 if (parse_pid(value, &pid) < 0)
1864 log_debug_unit(u->id, "Failed to parse control-pid value %s", value);
1866 s->control_pid = pid;
1867 } else if (streq(key, "main-pid")) {
1870 if (parse_pid(value, &pid) < 0)
1871 log_debug_unit(u->id, "Failed to parse main-pid value %s", value);
1873 service_set_main_pid(s, pid);
1874 unit_watch_pid(UNIT(s), pid);
1876 } else if (streq(key, "main-pid-known")) {
1879 b = parse_boolean(value);
1881 log_debug_unit(u->id, "Failed to parse main-pid-known value %s", value);
1883 s->main_pid_known = b;
1884 } else if (streq(key, "status-text")) {
1891 free(s->status_text);
1895 } else if (streq(key, "control-command")) {
1896 ServiceExecCommand id;
1898 id = service_exec_command_from_string(value);
1900 log_debug_unit(u->id, "Failed to parse exec-command value %s", value);
1902 s->control_command_id = id;
1903 s->control_command = s->exec_command[id];
1905 } else if (streq(key, "socket-fd")) {
1908 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
1909 log_debug_unit(u->id, "Failed to parse socket-fd value %s", value);
1911 asynchronous_close(s->socket_fd);
1912 s->socket_fd = fdset_remove(fds, fd);
1914 } else if (streq(key, "endpoint-fd")) {
1917 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
1918 log_debug_unit(u->id, "Failed to parse endpoint-fd value %s", value);
1920 safe_close(s->bus_endpoint_fd);
1921 s->bus_endpoint_fd = fdset_remove(fds, fd);
1923 } else if (streq(key, "main-exec-status-pid")) {
1926 if (parse_pid(value, &pid) < 0)
1927 log_debug_unit(u->id, "Failed to parse main-exec-status-pid value %s", value);
1929 s->main_exec_status.pid = pid;
1930 } else if (streq(key, "main-exec-status-code")) {
1933 if (safe_atoi(value, &i) < 0)
1934 log_debug_unit(u->id, "Failed to parse main-exec-status-code value %s", value);
1936 s->main_exec_status.code = i;
1937 } else if (streq(key, "main-exec-status-status")) {
1940 if (safe_atoi(value, &i) < 0)
1941 log_debug_unit(u->id, "Failed to parse main-exec-status-status value %s", value);
1943 s->main_exec_status.status = i;
1944 } else if (streq(key, "main-exec-status-start"))
1945 dual_timestamp_deserialize(value, &s->main_exec_status.start_timestamp);
1946 else if (streq(key, "main-exec-status-exit"))
1947 dual_timestamp_deserialize(value, &s->main_exec_status.exit_timestamp);
1948 else if (streq(key, "watchdog-timestamp"))
1949 dual_timestamp_deserialize(value, &s->watchdog_timestamp);
1950 else if (streq(key, "forbid-restart")) {
1953 b = parse_boolean(value);
1955 log_debug_unit(u->id, "Failed to parse forbid-restart value %s", value);
1957 s->forbid_restart = b;
1959 log_debug_unit(u->id, "Unknown serialization key '%s'", key);
1964 _pure_ static UnitActiveState service_active_state(Unit *u) {
1965 const UnitActiveState *table;
1969 table = SERVICE(u)->type == SERVICE_IDLE ? state_translation_table_idle : state_translation_table;
1971 return table[SERVICE(u)->state];
1974 static const char *service_sub_state_to_string(Unit *u) {
1977 return service_state_to_string(SERVICE(u)->state);
1980 static bool service_check_gc(Unit *u) {
1981 Service *s = SERVICE(u);
1985 /* Never clean up services that still have a process around,
1986 * even if the service is formally dead. */
1987 if (cgroup_good(s) > 0 ||
1988 main_pid_good(s) > 0 ||
1989 control_pid_good(s) > 0)
1995 _pure_ static bool service_check_snapshot(Unit *u) {
1996 Service *s = SERVICE(u);
2000 return s->socket_fd < 0;
2003 static int service_retry_pid_file(Service *s) {
2006 assert(s->pid_file);
2007 assert(s->state == SERVICE_START || s->state == SERVICE_START_POST);
2009 r = service_load_pid_file(s, false);
2013 service_unwatch_pid_file(s);
2015 service_enter_running(s, SERVICE_SUCCESS);
2019 static int service_watch_pid_file(Service *s) {
2022 log_debug_unit(UNIT(s)->id, "Setting watch for %s's PID file %s", UNIT(s)->id, s->pid_file_pathspec->path);
2024 r = path_spec_watch(s->pid_file_pathspec, service_dispatch_io);
2028 /* the pidfile might have appeared just before we set the watch */
2029 log_debug_unit(UNIT(s)->id, "Trying to read %s's PID file %s in case it changed", UNIT(s)->id, s->pid_file_pathspec->path);
2030 service_retry_pid_file(s);
2034 log_error_unit(UNIT(s)->id, "Failed to set a watch for %s's PID file %s: %s", UNIT(s)->id, s->pid_file_pathspec->path, strerror(-r));
2035 service_unwatch_pid_file(s);
2039 static int service_demand_pid_file(Service *s) {
2042 assert(s->pid_file);
2043 assert(!s->pid_file_pathspec);
2045 ps = new0(PathSpec, 1);
2050 ps->path = strdup(s->pid_file);
2056 path_kill_slashes(ps->path);
2058 /* PATH_CHANGED would not be enough. There are daemons (sendmail) that
2059 * keep their PID file open all the time. */
2060 ps->type = PATH_MODIFIED;
2061 ps->inotify_fd = -1;
2063 s->pid_file_pathspec = ps;
2065 return service_watch_pid_file(s);
2068 static int service_dispatch_io(sd_event_source *source, int fd, uint32_t events, void *userdata) {
2069 PathSpec *p = userdata;
2074 s = SERVICE(p->unit);
2078 assert(s->state == SERVICE_START || s->state == SERVICE_START_POST);
2079 assert(s->pid_file_pathspec);
2080 assert(path_spec_owns_inotify_fd(s->pid_file_pathspec, fd));
2082 log_debug_unit(UNIT(s)->id, "inotify event for %s", UNIT(s)->id);
2084 if (path_spec_fd_event(p, events) < 0)
2087 if (service_retry_pid_file(s) == 0)
2090 if (service_watch_pid_file(s) < 0)
2096 service_unwatch_pid_file(s);
2097 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
2101 static void service_notify_cgroup_empty_event(Unit *u) {
2102 Service *s = SERVICE(u);
2106 log_debug_unit(u->id, "%s: cgroup is empty", u->id);
2110 /* Waiting for SIGCHLD is usually more interesting,
2111 * because it includes return codes/signals. Which is
2112 * why we ignore the cgroup events for most cases,
2113 * except when we don't know pid which to expect the
2117 case SERVICE_START_POST:
2118 /* If we were hoping for the daemon to write its PID file,
2119 * we can give up now. */
2120 if (s->pid_file_pathspec) {
2121 log_warning_unit(u->id, "%s never wrote its PID file. Failing.", UNIT(s)->id);
2123 service_unwatch_pid_file(s);
2124 if (s->state == SERVICE_START)
2125 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
2127 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2131 case SERVICE_RUNNING:
2132 /* service_enter_running() will figure out what to do */
2133 service_enter_running(s, SERVICE_SUCCESS);
2136 case SERVICE_STOP_SIGABRT:
2137 case SERVICE_STOP_SIGTERM:
2138 case SERVICE_STOP_SIGKILL:
2140 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2141 service_enter_stop_post(s, SERVICE_SUCCESS);
2145 case SERVICE_STOP_POST:
2146 case SERVICE_FINAL_SIGTERM:
2147 case SERVICE_FINAL_SIGKILL:
2148 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2149 service_enter_dead(s, SERVICE_SUCCESS, true);
2158 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2159 Service *s = SERVICE(u);
2165 if (UNIT(s)->fragment_path ? is_clean_exit(code, status, &s->success_status) :
2166 is_clean_exit_lsb(code, status, &s->success_status))
2167 f = SERVICE_SUCCESS;
2168 else if (code == CLD_EXITED)
2169 f = SERVICE_FAILURE_EXIT_CODE;
2170 else if (code == CLD_KILLED)
2171 f = SERVICE_FAILURE_SIGNAL;
2172 else if (code == CLD_DUMPED)
2173 f = SERVICE_FAILURE_CORE_DUMP;
2175 assert_not_reached("Unknown code");
2177 if (s->main_pid == pid) {
2178 /* Forking services may occasionally move to a new PID.
2179 * As long as they update the PID file before exiting the old
2180 * PID, they're fine. */
2181 if (service_load_pid_file(s, false) == 0)
2185 exec_status_exit(&s->main_exec_status, &s->exec_context, pid, code, status);
2187 if (s->main_command) {
2188 /* If this is not a forking service than the
2189 * main process got started and hence we copy
2190 * the exit status so that it is recorded both
2191 * as main and as control process exit
2194 s->main_command->exec_status = s->main_exec_status;
2196 if (s->main_command->ignore)
2197 f = SERVICE_SUCCESS;
2198 } else if (s->exec_command[SERVICE_EXEC_START]) {
2200 /* If this is a forked process, then we should
2201 * ignore the return value if this was
2202 * configured for the starter process */
2204 if (s->exec_command[SERVICE_EXEC_START]->ignore)
2205 f = SERVICE_SUCCESS;
2208 log_struct_unit(f == SERVICE_SUCCESS ? LOG_DEBUG : LOG_NOTICE,
2210 "MESSAGE=%s: main process exited, code=%s, status=%i/%s",
2211 u->id, sigchld_code_to_string(code), status,
2212 strna(code == CLD_EXITED
2213 ? exit_status_to_string(status, EXIT_STATUS_FULL)
2214 : signal_to_string(status)),
2215 "EXIT_CODE=%s", sigchld_code_to_string(code),
2216 "EXIT_STATUS=%i", status,
2219 if (f != SERVICE_SUCCESS)
2222 if (s->main_command &&
2223 s->main_command->command_next &&
2224 f == SERVICE_SUCCESS) {
2226 /* There is another command to *
2227 * execute, so let's do that. */
2229 log_debug_unit(u->id, "%s running next main command for state %s", u->id, service_state_to_string(s->state));
2230 service_run_next_main(s);
2234 /* The service exited, so the service is officially
2236 s->main_command = NULL;
2240 case SERVICE_START_POST:
2241 case SERVICE_RELOAD:
2243 /* Need to wait until the operation is
2248 if (s->type == SERVICE_ONESHOT) {
2249 /* This was our main goal, so let's go on */
2250 if (f == SERVICE_SUCCESS)
2251 service_enter_start_post(s);
2253 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
2259 case SERVICE_RUNNING:
2260 service_enter_running(s, f);
2263 case SERVICE_STOP_SIGABRT:
2264 case SERVICE_STOP_SIGTERM:
2265 case SERVICE_STOP_SIGKILL:
2267 if (!control_pid_good(s))
2268 service_enter_stop_post(s, f);
2270 /* If there is still a control process, wait for that first */
2273 case SERVICE_STOP_POST:
2274 case SERVICE_FINAL_SIGTERM:
2275 case SERVICE_FINAL_SIGKILL:
2277 if (!control_pid_good(s))
2278 service_enter_dead(s, f, true);
2282 assert_not_reached("Uh, main process died at wrong time.");
2286 } else if (s->control_pid == pid) {
2289 if (s->control_command) {
2290 exec_status_exit(&s->control_command->exec_status, &s->exec_context, pid, code, status);
2292 if (s->control_command->ignore)
2293 f = SERVICE_SUCCESS;
2296 log_full_unit(f == SERVICE_SUCCESS ? LOG_DEBUG : LOG_NOTICE, u->id,
2297 "%s: control process exited, code=%s status=%i",
2298 u->id, sigchld_code_to_string(code), status);
2300 if (f != SERVICE_SUCCESS)
2303 /* Immediately get rid of the cgroup, so that the
2304 * kernel doesn't delay the cgroup empty messages for
2305 * the service cgroup any longer than necessary */
2306 service_kill_control_processes(s);
2308 if (s->control_command &&
2309 s->control_command->command_next &&
2310 f == SERVICE_SUCCESS) {
2312 /* There is another command to *
2313 * execute, so let's do that. */
2315 log_debug_unit(u->id, "%s running next control command for state %s", u->id, service_state_to_string(s->state));
2316 service_run_next_control(s);
2319 /* No further commands for this step, so let's
2320 * figure out what to do next */
2322 s->control_command = NULL;
2323 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2325 log_debug_unit(u->id, "%s got final SIGCHLD for state %s", u->id, service_state_to_string(s->state));
2329 case SERVICE_START_PRE:
2330 if (f == SERVICE_SUCCESS)
2331 service_enter_start(s);
2333 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
2337 if (s->type != SERVICE_FORKING)
2338 /* Maybe spurious event due to a reload that changed the type? */
2341 if (f != SERVICE_SUCCESS) {
2342 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
2347 bool has_start_post;
2350 /* Let's try to load the pid file here if we can.
2351 * The PID file might actually be created by a START_POST
2352 * script. In that case don't worry if the loading fails. */
2354 has_start_post = !!s->exec_command[SERVICE_EXEC_START_POST];
2355 r = service_load_pid_file(s, !has_start_post);
2356 if (!has_start_post && r < 0) {
2357 r = service_demand_pid_file(s);
2358 if (r < 0 || !cgroup_good(s))
2359 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
2363 service_search_main_pid(s);
2365 service_enter_start_post(s);
2368 case SERVICE_START_POST:
2369 if (f != SERVICE_SUCCESS) {
2370 service_enter_stop(s, f);
2377 r = service_load_pid_file(s, true);
2379 r = service_demand_pid_file(s);
2380 if (r < 0 || !cgroup_good(s))
2381 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2385 service_search_main_pid(s);
2387 service_enter_running(s, SERVICE_SUCCESS);
2390 case SERVICE_RELOAD:
2391 if (f == SERVICE_SUCCESS) {
2392 service_load_pid_file(s, true);
2393 service_search_main_pid(s);
2396 s->reload_result = f;
2397 service_enter_running(s, SERVICE_SUCCESS);
2401 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
2404 case SERVICE_STOP_SIGABRT:
2405 case SERVICE_STOP_SIGTERM:
2406 case SERVICE_STOP_SIGKILL:
2407 if (main_pid_good(s) <= 0)
2408 service_enter_stop_post(s, f);
2410 /* If there is still a service
2411 * process around, wait until
2412 * that one quit, too */
2415 case SERVICE_STOP_POST:
2416 case SERVICE_FINAL_SIGTERM:
2417 case SERVICE_FINAL_SIGKILL:
2418 if (main_pid_good(s) <= 0)
2419 service_enter_dead(s, f, true);
2423 assert_not_reached("Uh, control process died at wrong time.");
2428 /* Notify clients about changed exit status */
2429 unit_add_to_dbus_queue(u);
2431 /* We got one SIGCHLD for the service, let's watch all
2432 * processes that are now running of the service, and watch
2433 * that. Among the PIDs we then watch will be children
2434 * reassigned to us, which hopefully allows us to identify
2435 * when all children are gone */
2436 unit_tidy_watch_pids(u, s->main_pid, s->control_pid);
2437 unit_watch_all_pids(u);
2439 /* If the PID set is empty now, then let's finish this off */
2440 if (set_isempty(u->pids))
2441 service_notify_cgroup_empty_event(u);
2444 static int service_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata) {
2445 Service *s = SERVICE(userdata);
2448 assert(source == s->timer_event_source);
2452 case SERVICE_START_PRE:
2454 log_warning_unit(UNIT(s)->id, "%s %s operation timed out. Terminating.", UNIT(s)->id, s->state == SERVICE_START ? "start" : "start-pre");
2455 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2458 case SERVICE_START_POST:
2459 log_warning_unit(UNIT(s)->id, "%s start-post operation timed out. Stopping.", UNIT(s)->id);
2460 service_enter_stop(s, SERVICE_FAILURE_TIMEOUT);
2463 case SERVICE_RELOAD:
2464 log_warning_unit(UNIT(s)->id, "%s reload operation timed out. Stopping.", UNIT(s)->id);
2465 s->reload_result = SERVICE_FAILURE_TIMEOUT;
2466 service_enter_running(s, SERVICE_SUCCESS);
2470 log_warning_unit(UNIT(s)->id, "%s stopping timed out. Terminating.", UNIT(s)->id);
2471 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2474 case SERVICE_STOP_SIGABRT:
2475 log_warning_unit(UNIT(s)->id,
2476 "%s stop-sigabrt timed out. Terminating.", UNIT(s)->id);
2477 service_enter_signal(s, SERVICE_STOP_SIGTERM, s->result);
2480 case SERVICE_STOP_SIGTERM:
2481 if (s->kill_context.send_sigkill) {
2482 log_warning_unit(UNIT(s)->id, "%s stop-sigterm timed out. Killing.", UNIT(s)->id);
2483 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_TIMEOUT);
2485 log_warning_unit(UNIT(s)->id, "%s stop-sigterm timed out. Skipping SIGKILL.", UNIT(s)->id);
2486 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
2491 case SERVICE_STOP_SIGKILL:
2492 /* Uh, we sent a SIGKILL and it is still not gone?
2493 * Must be something we cannot kill, so let's just be
2494 * weirded out and continue */
2496 log_warning_unit(UNIT(s)->id, "%s still around after SIGKILL. Ignoring.", UNIT(s)->id);
2497 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
2500 case SERVICE_STOP_POST:
2501 log_warning_unit(UNIT(s)->id, "%s stop-post timed out. Terminating.", UNIT(s)->id);
2502 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2505 case SERVICE_FINAL_SIGTERM:
2506 if (s->kill_context.send_sigkill) {
2507 log_warning_unit(UNIT(s)->id, "%s stop-final-sigterm timed out. Killing.", UNIT(s)->id);
2508 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_FAILURE_TIMEOUT);
2510 log_warning_unit(UNIT(s)->id, "%s stop-final-sigterm timed out. Skipping SIGKILL. Entering failed mode.", UNIT(s)->id);
2511 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, false);
2516 case SERVICE_FINAL_SIGKILL:
2517 log_warning_unit(UNIT(s)->id, "%s still around after final SIGKILL. Entering failed mode.", UNIT(s)->id);
2518 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, true);
2521 case SERVICE_AUTO_RESTART:
2522 log_info_unit(UNIT(s)->id,
2523 s->restart_usec > 0 ?
2524 "%s holdoff time over, scheduling restart." :
2525 "%s has no holdoff time, scheduling restart.",
2527 service_enter_restart(s);
2531 assert_not_reached("Timeout at wrong time.");
2537 static int service_dispatch_watchdog(sd_event_source *source, usec_t usec, void *userdata) {
2538 Service *s = SERVICE(userdata);
2539 char t[FORMAT_TIMESPAN_MAX];
2542 assert(source == s->watchdog_event_source);
2544 log_error_unit(UNIT(s)->id, "%s watchdog timeout (limit %s)!", UNIT(s)->id,
2545 format_timespan(t, sizeof(t), s->watchdog_usec, 1));
2547 service_enter_signal(s, SERVICE_STOP_SIGABRT, SERVICE_FAILURE_WATCHDOG);
2552 static void service_notify_message(Unit *u, pid_t pid, char **tags) {
2553 Service *s = SERVICE(u);
2554 _cleanup_free_ char *cc = NULL;
2555 bool notify_dbus = false;
2560 cc = strv_join(tags, ", ");
2561 log_debug_unit(u->id, "%s: Got notification message from PID "PID_FMT" (%s)",
2562 u->id, pid, isempty(cc) ? "n/a" : cc);
2564 if (s->notify_access == NOTIFY_NONE) {
2565 log_warning_unit(u->id, "%s: Got notification message from PID "PID_FMT", but reception is disabled.", u->id, pid);
2569 if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
2570 if (s->main_pid != 0)
2571 log_warning_unit(u->id, "%s: Got notification message from PID "PID_FMT", but reception only permitted for main PID "PID_FMT, u->id, pid, s->main_pid);
2573 log_debug_unit(u->id, "%s: Got notification message from PID "PID_FMT", but reception only permitted for main PID which is currently not known", u->id, pid);
2577 /* Interpret MAINPID= */
2578 e = strv_find_startswith(tags, "MAINPID=");
2579 if (e && IN_SET(s->state, SERVICE_START, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD)) {
2580 if (parse_pid(e, &pid) < 0)
2581 log_warning_unit(u->id, "Failed to parse MAINPID= field in notification message: %s", e);
2583 log_debug_unit(u->id, "%s: got MAINPID=%s", u->id, e);
2585 service_set_main_pid(s, pid);
2586 unit_watch_pid(UNIT(s), pid);
2591 /* Interpret RELOADING= */
2592 if (strv_find(tags, "RELOADING=1")) {
2594 log_debug_unit(u->id, "%s: got RELOADING=1", u->id);
2595 s->notify_state = NOTIFY_RELOADING;
2597 if (s->state == SERVICE_RUNNING)
2598 service_enter_reload_by_notify(s);
2603 /* Interpret READY= */
2604 if (strv_find(tags, "READY=1")) {
2606 log_debug_unit(u->id, "%s: got READY=1", u->id);
2607 s->notify_state = NOTIFY_READY;
2609 /* Type=notify services inform us about completed
2610 * initialization with READY=1 */
2611 if (s->type == SERVICE_NOTIFY && s->state == SERVICE_START)
2612 service_enter_start_post(s);
2614 /* Sending READY=1 while we are reloading informs us
2615 * that the reloading is complete */
2616 if (s->state == SERVICE_RELOAD && s->control_pid == 0)
2617 service_enter_running(s, SERVICE_SUCCESS);
2622 /* Interpret STOPPING= */
2623 if (strv_find(tags, "STOPPING=1")) {
2625 log_debug_unit(u->id, "%s: got STOPPING=1", u->id);
2626 s->notify_state = NOTIFY_STOPPING;
2628 if (s->state == SERVICE_RUNNING)
2629 service_enter_stop_by_notify(s);
2634 /* Interpret STATUS= */
2635 e = strv_find_startswith(tags, "STATUS=");
2637 _cleanup_free_ char *t = NULL;
2640 if (!utf8_is_valid(e))
2641 log_warning_unit(u->id, "Status message in notification is not UTF-8 clean.");
2643 log_debug_unit(u->id, "%s: got STATUS=%s", u->id, e);
2651 if (!streq_ptr(s->status_text, t)) {
2653 free(s->status_text);
2661 /* Interpret ERRNO= */
2662 e = strv_find_startswith(tags, "ERRNO=");
2666 if (safe_atoi(e, &status_errno) < 0 || status_errno < 0)
2667 log_warning_unit(u->id, "Failed to parse ERRNO= field in notification message: %s", e);
2669 log_debug_unit(u->id, "%s: got ERRNO=%s", u->id, e);
2671 if (s->status_errno != status_errno) {
2672 s->status_errno = status_errno;
2678 /* Interpret WATCHDOG= */
2679 if (strv_find(tags, "WATCHDOG=1")) {
2680 log_debug_unit(u->id, "%s: got WATCHDOG=1", u->id);
2681 service_reset_watchdog(s);
2684 /* Notify clients about changed status or main pid */
2686 unit_add_to_dbus_queue(u);
2689 static int service_get_timeout(Unit *u, uint64_t *timeout) {
2690 Service *s = SERVICE(u);
2693 if (!s->timer_event_source)
2696 r = sd_event_source_get_time(s->timer_event_source, timeout);
2703 static void service_bus_name_owner_change(
2706 const char *old_owner,
2707 const char *new_owner) {
2709 Service *s = SERVICE(u);
2715 assert(streq(s->bus_name, name));
2716 assert(old_owner || new_owner);
2718 if (old_owner && new_owner)
2719 log_debug_unit(u->id, "%s's D-Bus name %s changed owner from %s to %s", u->id, name, old_owner, new_owner);
2721 log_debug_unit(u->id, "%s's D-Bus name %s no longer registered by %s", u->id, name, old_owner);
2723 log_debug_unit(u->id, "%s's D-Bus name %s now registered by %s", u->id, name, new_owner);
2725 s->bus_name_good = !!new_owner;
2727 if (s->type == SERVICE_DBUS) {
2729 /* service_enter_running() will figure out what to
2731 if (s->state == SERVICE_RUNNING)
2732 service_enter_running(s, SERVICE_SUCCESS);
2733 else if (s->state == SERVICE_START && new_owner)
2734 service_enter_start_post(s);
2736 } else if (new_owner &&
2738 (s->state == SERVICE_START ||
2739 s->state == SERVICE_START_POST ||
2740 s->state == SERVICE_RUNNING ||
2741 s->state == SERVICE_RELOAD)) {
2743 _cleanup_bus_creds_unref_ sd_bus_creds *creds = NULL;
2746 /* Try to acquire PID from bus service */
2748 r = sd_bus_get_name_creds(u->manager->api_bus, name, SD_BUS_CREDS_PID, &creds);
2750 r = sd_bus_creds_get_pid(creds, &pid);
2752 log_debug_unit(u->id, "%s's D-Bus name %s is now owned by process %u", u->id, name, (unsigned) pid);
2754 service_set_main_pid(s, pid);
2755 unit_watch_pid(UNIT(s), pid);
2760 int service_set_socket_fd(Service *s, int fd, Socket *sock, bool selinux_context_net) {
2761 _cleanup_free_ char *peer = NULL;
2767 /* This is called by the socket code when instantiating a new
2768 * service for a stream socket and the socket needs to be
2771 if (UNIT(s)->load_state != UNIT_LOADED)
2774 if (s->socket_fd >= 0)
2777 if (s->state != SERVICE_DEAD)
2780 if (getpeername_pretty(fd, &peer) >= 0) {
2782 if (UNIT(s)->description) {
2783 _cleanup_free_ char *a;
2785 a = strjoin(UNIT(s)->description, " (", peer, ")", NULL);
2789 r = unit_set_description(UNIT(s), a);
2791 r = unit_set_description(UNIT(s), peer);
2798 s->socket_fd_selinux_context_net = selinux_context_net;
2800 unit_ref_set(&s->accept_socket, UNIT(sock));
2802 return unit_add_two_dependencies(UNIT(sock), UNIT_BEFORE, UNIT_TRIGGERS, UNIT(s), false);
2805 static void service_reset_failed(Unit *u) {
2806 Service *s = SERVICE(u);
2810 if (s->state == SERVICE_FAILED)
2811 service_set_state(s, SERVICE_DEAD);
2813 s->result = SERVICE_SUCCESS;
2814 s->reload_result = SERVICE_SUCCESS;
2816 RATELIMIT_RESET(s->start_limit);
2819 static int service_kill(Unit *u, KillWho who, int signo, sd_bus_error *error) {
2820 Service *s = SERVICE(u);
2822 return unit_kill_common(u, who, signo, s->main_pid, s->control_pid, error);
2825 static const char* const service_state_table[_SERVICE_STATE_MAX] = {
2826 [SERVICE_DEAD] = "dead",
2827 [SERVICE_START_PRE] = "start-pre",
2828 [SERVICE_START] = "start",
2829 [SERVICE_START_POST] = "start-post",
2830 [SERVICE_RUNNING] = "running",
2831 [SERVICE_EXITED] = "exited",
2832 [SERVICE_RELOAD] = "reload",
2833 [SERVICE_STOP] = "stop",
2834 [SERVICE_STOP_SIGABRT] = "stop-sigabrt",
2835 [SERVICE_STOP_SIGTERM] = "stop-sigterm",
2836 [SERVICE_STOP_SIGKILL] = "stop-sigkill",
2837 [SERVICE_STOP_POST] = "stop-post",
2838 [SERVICE_FINAL_SIGTERM] = "final-sigterm",
2839 [SERVICE_FINAL_SIGKILL] = "final-sigkill",
2840 [SERVICE_FAILED] = "failed",
2841 [SERVICE_AUTO_RESTART] = "auto-restart",
2844 DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
2846 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
2847 [SERVICE_RESTART_NO] = "no",
2848 [SERVICE_RESTART_ON_SUCCESS] = "on-success",
2849 [SERVICE_RESTART_ON_FAILURE] = "on-failure",
2850 [SERVICE_RESTART_ON_ABNORMAL] = "on-abnormal",
2851 [SERVICE_RESTART_ON_WATCHDOG] = "on-watchdog",
2852 [SERVICE_RESTART_ON_ABORT] = "on-abort",
2853 [SERVICE_RESTART_ALWAYS] = "always",
2856 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
2858 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
2859 [SERVICE_SIMPLE] = "simple",
2860 [SERVICE_FORKING] = "forking",
2861 [SERVICE_ONESHOT] = "oneshot",
2862 [SERVICE_DBUS] = "dbus",
2863 [SERVICE_NOTIFY] = "notify",
2864 [SERVICE_IDLE] = "idle"
2867 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
2869 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
2870 [SERVICE_EXEC_START_PRE] = "ExecStartPre",
2871 [SERVICE_EXEC_START] = "ExecStart",
2872 [SERVICE_EXEC_START_POST] = "ExecStartPost",
2873 [SERVICE_EXEC_RELOAD] = "ExecReload",
2874 [SERVICE_EXEC_STOP] = "ExecStop",
2875 [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
2878 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
2880 static const char* const notify_access_table[_NOTIFY_ACCESS_MAX] = {
2881 [NOTIFY_NONE] = "none",
2882 [NOTIFY_MAIN] = "main",
2883 [NOTIFY_ALL] = "all"
2886 DEFINE_STRING_TABLE_LOOKUP(notify_access, NotifyAccess);
2888 static const char* const notify_state_table[_NOTIFY_STATE_MAX] = {
2889 [NOTIFY_UNKNOWN] = "unknown",
2890 [NOTIFY_READY] = "ready",
2891 [NOTIFY_RELOADING] = "reloading",
2892 [NOTIFY_STOPPING] = "stopping",
2895 DEFINE_STRING_TABLE_LOOKUP(notify_state, NotifyState);
2897 static const char* const service_result_table[_SERVICE_RESULT_MAX] = {
2898 [SERVICE_SUCCESS] = "success",
2899 [SERVICE_FAILURE_RESOURCES] = "resources",
2900 [SERVICE_FAILURE_TIMEOUT] = "timeout",
2901 [SERVICE_FAILURE_EXIT_CODE] = "exit-code",
2902 [SERVICE_FAILURE_SIGNAL] = "signal",
2903 [SERVICE_FAILURE_CORE_DUMP] = "core-dump",
2904 [SERVICE_FAILURE_WATCHDOG] = "watchdog",
2905 [SERVICE_FAILURE_START_LIMIT] = "start-limit"
2908 DEFINE_STRING_TABLE_LOOKUP(service_result, ServiceResult);
2910 const UnitVTable service_vtable = {
2911 .object_size = sizeof(Service),
2912 .exec_context_offset = offsetof(Service, exec_context),
2913 .cgroup_context_offset = offsetof(Service, cgroup_context),
2914 .kill_context_offset = offsetof(Service, kill_context),
2915 .exec_runtime_offset = offsetof(Service, exec_runtime),
2921 .private_section = "Service",
2923 .init = service_init,
2924 .done = service_done,
2925 .load = service_load,
2927 .coldplug = service_coldplug,
2929 .dump = service_dump,
2931 .start = service_start,
2932 .stop = service_stop,
2933 .reload = service_reload,
2935 .can_reload = service_can_reload,
2937 .kill = service_kill,
2939 .serialize = service_serialize,
2940 .deserialize_item = service_deserialize_item,
2942 .active_state = service_active_state,
2943 .sub_state_to_string = service_sub_state_to_string,
2945 .check_gc = service_check_gc,
2946 .check_snapshot = service_check_snapshot,
2948 .sigchld_event = service_sigchld_event,
2950 .reset_failed = service_reset_failed,
2952 .notify_cgroup_empty = service_notify_cgroup_empty_event,
2953 .notify_message = service_notify_message,
2955 .bus_name_owner_change = service_bus_name_owner_change,
2957 .bus_interface = "org.freedesktop.systemd1.Service",
2958 .bus_vtable = bus_service_vtable,
2959 .bus_set_property = bus_service_set_property,
2960 .bus_commit_properties = bus_service_commit_properties,
2962 .get_timeout = service_get_timeout,
2963 .can_transient = true,
2965 .status_message_formats = {
2966 .starting_stopping = {
2967 [0] = "Starting %s...",
2968 [1] = "Stopping %s...",
2970 .finished_start_job = {
2971 [JOB_DONE] = "Started %s.",
2972 [JOB_FAILED] = "Failed to start %s.",
2973 [JOB_DEPENDENCY] = "Dependency failed for %s.",
2974 [JOB_TIMEOUT] = "Timed out starting %s.",
2976 .finished_stop_job = {
2977 [JOB_DONE] = "Stopped %s.",
2978 [JOB_FAILED] = "Stopped (with error) %s.",
2979 [JOB_TIMEOUT] = "Timed out stopping %s.",