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_SIGTERM] = UNIT_DEACTIVATING,
60 [SERVICE_STOP_SIGKILL] = UNIT_DEACTIVATING,
61 [SERVICE_STOP_POST] = UNIT_DEACTIVATING,
62 [SERVICE_FINAL_SIGTERM] = UNIT_DEACTIVATING,
63 [SERVICE_FINAL_SIGKILL] = UNIT_DEACTIVATING,
64 [SERVICE_FAILED] = UNIT_FAILED,
65 [SERVICE_AUTO_RESTART] = UNIT_ACTIVATING
68 /* For Type=idle we never want to delay any other jobs, hence we
69 * consider idle jobs active as soon as we start working on them */
70 static const UnitActiveState state_translation_table_idle[_SERVICE_STATE_MAX] = {
71 [SERVICE_DEAD] = UNIT_INACTIVE,
72 [SERVICE_START_PRE] = UNIT_ACTIVE,
73 [SERVICE_START] = UNIT_ACTIVE,
74 [SERVICE_START_POST] = UNIT_ACTIVE,
75 [SERVICE_RUNNING] = UNIT_ACTIVE,
76 [SERVICE_EXITED] = UNIT_ACTIVE,
77 [SERVICE_RELOAD] = UNIT_RELOADING,
78 [SERVICE_STOP] = UNIT_DEACTIVATING,
79 [SERVICE_STOP_SIGTERM] = UNIT_DEACTIVATING,
80 [SERVICE_STOP_SIGKILL] = UNIT_DEACTIVATING,
81 [SERVICE_STOP_POST] = UNIT_DEACTIVATING,
82 [SERVICE_FINAL_SIGTERM] = UNIT_DEACTIVATING,
83 [SERVICE_FINAL_SIGKILL] = UNIT_DEACTIVATING,
84 [SERVICE_FAILED] = UNIT_FAILED,
85 [SERVICE_AUTO_RESTART] = UNIT_ACTIVATING
88 static int service_dispatch_io(sd_event_source *source, int fd, uint32_t events, void *userdata);
89 static int service_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata);
90 static int service_dispatch_watchdog(sd_event_source *source, usec_t usec, void *userdata);
92 static void service_enter_signal(Service *s, ServiceState state, ServiceResult f);
93 static void service_enter_reload_by_notify(Service *s);
95 static void service_init(Unit *u) {
96 Service *s = SERVICE(u);
99 assert(u->load_state == UNIT_STUB);
101 s->timeout_start_usec = u->manager->default_timeout_start_usec;
102 s->timeout_stop_usec = u->manager->default_timeout_stop_usec;
103 s->restart_usec = u->manager->default_restart_usec;
104 s->type = _SERVICE_TYPE_INVALID;
106 s->bus_endpoint_fd = -1;
107 s->guess_main_pid = true;
109 RATELIMIT_INIT(s->start_limit, u->manager->default_start_limit_interval, u->manager->default_start_limit_burst);
111 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
114 static void service_unwatch_control_pid(Service *s) {
117 if (s->control_pid <= 0)
120 unit_unwatch_pid(UNIT(s), s->control_pid);
124 static void service_unwatch_main_pid(Service *s) {
127 if (s->main_pid <= 0)
130 unit_unwatch_pid(UNIT(s), s->main_pid);
134 static void service_unwatch_pid_file(Service *s) {
135 if (!s->pid_file_pathspec)
138 log_debug_unit(UNIT(s)->id, "Stopping watch for %s's PID file %s", UNIT(s)->id, s->pid_file_pathspec->path);
139 path_spec_unwatch(s->pid_file_pathspec);
140 path_spec_done(s->pid_file_pathspec);
141 free(s->pid_file_pathspec);
142 s->pid_file_pathspec = NULL;
145 static int service_set_main_pid(Service *s, pid_t pid) {
156 if (s->main_pid == pid && s->main_pid_known)
159 if (s->main_pid != pid) {
160 service_unwatch_main_pid(s);
161 exec_status_start(&s->main_exec_status, pid);
165 s->main_pid_known = true;
167 if (get_parent_of_pid(pid, &ppid) >= 0 && ppid != getpid()) {
168 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);
169 s->main_pid_alien = true;
171 s->main_pid_alien = false;
176 static void service_close_socket_fd(Service *s) {
179 s->socket_fd = asynchronous_close(s->socket_fd);
182 static void service_connection_unref(Service *s) {
185 if (!UNIT_ISSET(s->accept_socket))
188 socket_connection_unref(SOCKET(UNIT_DEREF(s->accept_socket)));
189 unit_ref_unset(&s->accept_socket);
192 static void service_stop_watchdog(Service *s) {
195 s->watchdog_event_source = sd_event_source_unref(s->watchdog_event_source);
196 s->watchdog_timestamp = DUAL_TIMESTAMP_NULL;
199 static void service_start_watchdog(Service *s) {
204 if (s->watchdog_usec <= 0)
207 if (s->watchdog_event_source) {
208 r = sd_event_source_set_time(s->watchdog_event_source, s->watchdog_timestamp.monotonic + s->watchdog_usec);
210 log_warning_unit(UNIT(s)->id, "%s failed to reset watchdog timer: %s", UNIT(s)->id, strerror(-r));
214 r = sd_event_source_set_enabled(s->watchdog_event_source, SD_EVENT_ONESHOT);
216 r = sd_event_add_time(
217 UNIT(s)->manager->event,
218 &s->watchdog_event_source,
220 s->watchdog_timestamp.monotonic + s->watchdog_usec, 0,
221 service_dispatch_watchdog, s);
223 log_warning_unit(UNIT(s)->id, "%s failed to add watchdog timer: %s", UNIT(s)->id, strerror(-r));
227 /* Let's process everything else which might be a sign
228 * of living before we consider a service died. */
229 r = sd_event_source_set_priority(s->watchdog_event_source, SD_EVENT_PRIORITY_IDLE);
233 log_warning_unit(UNIT(s)->id, "%s failed to install watchdog timer: %s", UNIT(s)->id, strerror(-r));
236 static void service_reset_watchdog(Service *s) {
239 dual_timestamp_get(&s->watchdog_timestamp);
240 service_start_watchdog(s);
243 static void service_done(Unit *u) {
244 Service *s = SERVICE(u);
251 free(s->status_text);
252 s->status_text = NULL;
255 s->reboot_arg = NULL;
257 s->exec_runtime = exec_runtime_unref(s->exec_runtime);
258 exec_command_free_array(s->exec_command, _SERVICE_EXEC_COMMAND_MAX);
259 s->control_command = NULL;
260 s->main_command = NULL;
262 exit_status_set_free(&s->restart_prevent_status);
263 exit_status_set_free(&s->restart_force_status);
264 exit_status_set_free(&s->success_status);
266 /* This will leak a process, but at least no memory or any of
268 service_unwatch_main_pid(s);
269 service_unwatch_control_pid(s);
270 service_unwatch_pid_file(s);
273 unit_unwatch_bus_name(u, s->bus_name);
278 s->bus_endpoint_fd = safe_close(s->bus_endpoint_fd);
279 service_close_socket_fd(s);
280 service_connection_unref(s);
282 unit_ref_unset(&s->accept_socket);
284 service_stop_watchdog(s);
286 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
289 static int service_arm_timer(Service *s, usec_t usec) {
294 if (s->timer_event_source) {
295 r = sd_event_source_set_time(s->timer_event_source, now(CLOCK_MONOTONIC) + usec);
299 return sd_event_source_set_enabled(s->timer_event_source, SD_EVENT_ONESHOT);
302 return sd_event_add_time(
303 UNIT(s)->manager->event,
304 &s->timer_event_source,
306 now(CLOCK_MONOTONIC) + usec, 0,
307 service_dispatch_timer, s);
310 static int service_verify(Service *s) {
313 if (UNIT(s)->load_state != UNIT_LOADED)
316 if (!s->exec_command[SERVICE_EXEC_START] && !s->exec_command[SERVICE_EXEC_STOP]) {
317 log_error_unit(UNIT(s)->id, "%s lacks both ExecStart= and ExecStop= setting. Refusing.", UNIT(s)->id);
321 if (s->type != SERVICE_ONESHOT && !s->exec_command[SERVICE_EXEC_START]) {
322 log_error_unit(UNIT(s)->id, "%s has no ExecStart= setting, which is only allowed for Type=oneshot services. Refusing.", UNIT(s)->id);
326 if (!s->remain_after_exit && !s->exec_command[SERVICE_EXEC_START]) {
327 log_error_unit(UNIT(s)->id, "%s has no ExecStart= setting, which is only allowed for RemainAfterExit=yes services. Refusing.", UNIT(s)->id);
331 if (s->type != SERVICE_ONESHOT && s->exec_command[SERVICE_EXEC_START]->command_next) {
332 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);
336 if (s->type == SERVICE_ONESHOT && s->restart != SERVICE_RESTART_NO) {
337 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);
341 if (s->type == SERVICE_ONESHOT && !exit_status_set_is_empty(&s->restart_force_status)) {
342 log_error_unit(UNIT(s)->id, "%s has RestartForceStatus= set, which isn't allowed for Type=oneshot services. Refusing.", UNIT(s)->id);
346 if (s->type == SERVICE_DBUS && !s->bus_name) {
347 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);
351 if (s->bus_name && s->type != SERVICE_DBUS)
352 log_warning_unit(UNIT(s)->id, "%s has a D-Bus service name specified, but is not of type dbus. Ignoring.", UNIT(s)->id);
354 if (s->exec_context.pam_name && !(s->kill_context.kill_mode == KILL_CONTROL_GROUP || s->kill_context.kill_mode == KILL_MIXED)) {
355 log_error_unit(UNIT(s)->id, "%s has PAM enabled. Kill mode must be set to 'control-group' or 'mixed'. Refusing.", UNIT(s)->id);
362 static int service_add_default_dependencies(Service *s) {
367 /* Add a number of automatic dependencies useful for the
368 * majority of services. */
370 /* First, pull in base system */
371 r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_BASIC_TARGET, NULL, true);
375 /* Second, activate normal shutdown */
376 r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true);
380 static void service_fix_output(Service *s) {
383 /* If nothing has been explicitly configured, patch default
384 * output in. If input is socket/tty we avoid this however,
385 * since in that case we want output to default to the same
386 * place as we read input from. */
388 if (s->exec_context.std_error == EXEC_OUTPUT_INHERIT &&
389 s->exec_context.std_output == EXEC_OUTPUT_INHERIT &&
390 s->exec_context.std_input == EXEC_INPUT_NULL)
391 s->exec_context.std_error = UNIT(s)->manager->default_std_error;
393 if (s->exec_context.std_output == EXEC_OUTPUT_INHERIT &&
394 s->exec_context.std_input == EXEC_INPUT_NULL)
395 s->exec_context.std_output = UNIT(s)->manager->default_std_output;
398 static int service_load(Unit *u) {
399 Service *s = SERVICE(u);
404 /* Load a .service file */
405 r = unit_load_fragment(u);
409 /* Still nothing found? Then let's give up */
410 if (u->load_state == UNIT_STUB)
413 /* This is a new unit? Then let's add in some extras */
414 if (u->load_state == UNIT_LOADED) {
416 /* We were able to load something, then let's add in
417 * the dropin directories. */
418 r = unit_load_dropin(u);
422 if (s->type == _SERVICE_TYPE_INVALID) {
423 /* Figure out a type automatically */
425 s->type = SERVICE_DBUS;
426 else if (s->exec_command[SERVICE_EXEC_START])
427 s->type = SERVICE_SIMPLE;
429 s->type = SERVICE_ONESHOT;
432 /* Oneshot services have disabled start timeout by default */
433 if (s->type == SERVICE_ONESHOT && !s->start_timeout_defined)
434 s->timeout_start_usec = 0;
436 service_fix_output(s);
438 r = unit_patch_contexts(u);
442 r = unit_add_exec_dependencies(u, &s->exec_context);
446 r = unit_add_default_slice(u, &s->cgroup_context);
450 if (s->type == SERVICE_NOTIFY && s->notify_access == NOTIFY_NONE)
451 s->notify_access = NOTIFY_MAIN;
453 if (s->watchdog_usec > 0 && s->notify_access == NOTIFY_NONE)
454 s->notify_access = NOTIFY_MAIN;
457 r = unit_watch_bus_name(u, s->bus_name);
462 if (u->default_dependencies) {
463 r = service_add_default_dependencies(s);
470 return service_verify(s);
473 static void service_dump(Unit *u, FILE *f, const char *prefix) {
474 ServiceExecCommand c;
475 Service *s = SERVICE(u);
480 prefix = strempty(prefix);
481 prefix2 = strappenda(prefix, "\t");
484 "%sService State: %s\n"
486 "%sReload Result: %s\n"
487 "%sPermissionsStartOnly: %s\n"
488 "%sRootDirectoryStartOnly: %s\n"
489 "%sRemainAfterExit: %s\n"
490 "%sGuessMainPID: %s\n"
493 "%sNotifyAccess: %s\n"
494 "%sNotifyState: %s\n",
495 prefix, service_state_to_string(s->state),
496 prefix, service_result_to_string(s->result),
497 prefix, service_result_to_string(s->reload_result),
498 prefix, yes_no(s->permissions_start_only),
499 prefix, yes_no(s->root_directory_start_only),
500 prefix, yes_no(s->remain_after_exit),
501 prefix, yes_no(s->guess_main_pid),
502 prefix, service_type_to_string(s->type),
503 prefix, service_restart_to_string(s->restart),
504 prefix, notify_access_to_string(s->notify_access),
505 prefix, notify_state_to_string(s->notify_state));
507 if (s->control_pid > 0)
509 "%sControl PID: "PID_FMT"\n",
510 prefix, s->control_pid);
514 "%sMain PID: "PID_FMT"\n"
515 "%sMain PID Known: %s\n"
516 "%sMain PID Alien: %s\n",
518 prefix, yes_no(s->main_pid_known),
519 prefix, yes_no(s->main_pid_alien));
524 prefix, s->pid_file);
529 "%sBus Name Good: %s\n",
531 prefix, yes_no(s->bus_name_good));
533 kill_context_dump(&s->kill_context, f, prefix);
534 exec_context_dump(&s->exec_context, f, prefix);
536 for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
538 if (!s->exec_command[c])
541 fprintf(f, "%s-> %s:\n",
542 prefix, service_exec_command_to_string(c));
544 exec_command_dump_list(s->exec_command[c], f, prefix2);
547 #ifdef HAVE_SYSV_COMPAT
548 if (s->sysv_start_priority >= 0)
550 "%sSysVStartPriority: %i\n",
551 prefix, s->sysv_start_priority);
555 fprintf(f, "%sStatus Text: %s\n",
556 prefix, s->status_text);
559 static int service_load_pid_file(Service *s, bool may_warn) {
560 _cleanup_free_ char *k = NULL;
569 r = read_one_line_file(s->pid_file, &k);
572 log_info_unit(UNIT(s)->id, "PID file %s not readable (yet?) after %s.", s->pid_file, service_state_to_string(s->state));
576 r = parse_pid(k, &pid);
579 log_info_unit(UNIT(s)->id, "Failed to read PID from file %s: %s", s->pid_file, strerror(-r));
583 if (!pid_is_alive(pid)) {
585 log_info_unit(UNIT(s)->id, "PID "PID_FMT" read from file %s does not exist or is a zombie.", pid, s->pid_file);
589 if (s->main_pid_known) {
590 if (pid == s->main_pid)
593 log_debug_unit(UNIT(s)->id, "Main PID changing: "PID_FMT" -> "PID_FMT, s->main_pid, pid);
595 service_unwatch_main_pid(s);
596 s->main_pid_known = false;
598 log_debug_unit(UNIT(s)->id, "Main PID loaded: "PID_FMT, pid);
600 r = service_set_main_pid(s, pid);
604 r = unit_watch_pid(UNIT(s), pid);
606 /* FIXME: we need to do something here */
607 log_warning_unit(UNIT(s)->id, "Failed to watch PID "PID_FMT" from service %s", pid, UNIT(s)->id);
614 static int service_search_main_pid(Service *s) {
620 /* If we know it anyway, don't ever fallback to unreliable
622 if (s->main_pid_known)
625 if (!s->guess_main_pid)
628 assert(s->main_pid <= 0);
630 pid = unit_search_main_pid(UNIT(s));
634 log_debug_unit(UNIT(s)->id, "Main PID guessed: "PID_FMT, pid);
635 r = service_set_main_pid(s, pid);
639 r = unit_watch_pid(UNIT(s), pid);
641 /* FIXME: we need to do something here */
642 log_warning_unit(UNIT(s)->id, "Failed to watch PID "PID_FMT" from service %s", pid, UNIT(s)->id);
649 static void service_set_state(Service *s, ServiceState state) {
650 ServiceState old_state;
651 const UnitActiveState *table;
655 table = s->type == SERVICE_IDLE ? state_translation_table_idle : state_translation_table;
657 old_state = s->state;
660 service_unwatch_pid_file(s);
663 SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
665 SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL,
667 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL,
668 SERVICE_AUTO_RESTART))
669 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
672 SERVICE_START, SERVICE_START_POST,
673 SERVICE_RUNNING, SERVICE_RELOAD,
674 SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL,
676 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL)) {
677 service_unwatch_main_pid(s);
678 s->main_command = NULL;
682 SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
684 SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL,
686 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL)) {
687 service_unwatch_control_pid(s);
688 s->control_command = NULL;
689 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
692 if (IN_SET(state, SERVICE_DEAD, SERVICE_FAILED, SERVICE_AUTO_RESTART))
693 unit_unwatch_all_pids(UNIT(s));
696 SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
697 SERVICE_RUNNING, SERVICE_RELOAD,
698 SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
699 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL) &&
700 !(state == SERVICE_DEAD && UNIT(s)->job)) {
701 service_close_socket_fd(s);
702 service_connection_unref(s);
705 if (!IN_SET(state, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD))
706 service_stop_watchdog(s);
708 /* For the inactive states unit_notify() will trim the cgroup,
709 * but for exit we have to do that ourselves... */
710 if (state == SERVICE_EXITED && UNIT(s)->manager->n_reloading <= 0)
711 unit_destroy_cgroup(UNIT(s));
713 /* For remain_after_exit services, let's see if we can "release" the
714 * hold on the console, since unit_notify() only does that in case of
716 if (state == SERVICE_EXITED &&
717 s->remain_after_exit &&
718 UNIT(s)->manager->n_on_console > 0) {
722 ec = unit_get_exec_context(UNIT(s));
723 if (ec && exec_context_may_touch_console(ec)) {
724 Manager *m = UNIT(s)->manager;
727 if (m->n_on_console == 0)
728 /* unset no_console_output flag, since the console is free */
729 m->no_console_output = false;
733 if (old_state != state)
734 log_debug_unit(UNIT(s)->id, "%s changed %s -> %s", UNIT(s)->id, service_state_to_string(old_state), service_state_to_string(state));
736 unit_notify(UNIT(s), table[old_state], table[state], s->reload_result == SERVICE_SUCCESS);
737 s->reload_result = SERVICE_SUCCESS;
740 static int service_coldplug(Unit *u) {
741 Service *s = SERVICE(u);
745 assert(s->state == SERVICE_DEAD);
747 if (s->deserialized_state != s->state) {
749 if (IN_SET(s->deserialized_state,
750 SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
752 SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL,
754 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL)) {
758 k = IN_SET(s->deserialized_state, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST, SERVICE_RELOAD) ? s->timeout_start_usec : s->timeout_stop_usec;
760 /* For the start/stop timeouts 0 means off */
762 r = service_arm_timer(s, k);
768 if (s->deserialized_state == SERVICE_AUTO_RESTART) {
770 /* The restart timeouts 0 means immediately */
771 r = service_arm_timer(s, s->restart_usec);
776 if (pid_is_unwaited(s->main_pid) &&
777 ((s->deserialized_state == SERVICE_START && IN_SET(s->type, SERVICE_FORKING, SERVICE_DBUS, SERVICE_ONESHOT, SERVICE_NOTIFY)) ||
778 IN_SET(s->deserialized_state,
779 SERVICE_START, SERVICE_START_POST,
780 SERVICE_RUNNING, SERVICE_RELOAD,
781 SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL,
783 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL))) {
784 r = unit_watch_pid(UNIT(s), s->main_pid);
789 if (pid_is_unwaited(s->control_pid) &&
790 IN_SET(s->deserialized_state,
791 SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
793 SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL,
795 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL)) {
796 r = unit_watch_pid(UNIT(s), s->control_pid);
801 if (!IN_SET(s->deserialized_state, SERVICE_DEAD, SERVICE_FAILED, SERVICE_AUTO_RESTART))
802 unit_watch_all_pids(UNIT(s));
804 if (IN_SET(s->deserialized_state, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD))
805 service_start_watchdog(s);
807 service_set_state(s, s->deserialized_state);
813 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
824 if (s->socket_fd >= 0)
827 SET_FOREACH(u, UNIT(s)->dependencies[UNIT_TRIGGERED_BY], i) {
832 if (u->type != UNIT_SOCKET)
837 r = socket_collect_fds(sock, &cfds, &cn_fds);
850 t = new(int, rn_fds+cn_fds);
857 memcpy(t, rfds, rn_fds * sizeof(int));
858 memcpy(t+rn_fds, cfds, cn_fds * sizeof(int));
863 rn_fds = rn_fds+cn_fds;
878 static int service_spawn(
883 bool apply_permissions,
885 bool apply_tty_stdin,
886 bool set_notify_socket,
893 _cleanup_free_ int *fdsbuf = NULL;
894 unsigned n_fds = 0, n_env = 0;
895 _cleanup_free_ char *bus_endpoint_path = NULL;
896 _cleanup_strv_free_ char
897 **argv = NULL, **final_env = NULL, **our_env = NULL;
899 ExecParameters exec_params = {
900 .apply_permissions = apply_permissions,
901 .apply_chroot = apply_chroot,
902 .apply_tty_stdin = apply_tty_stdin,
903 .bus_endpoint_fd = -1,
904 .selinux_context_net = s->socket_fd_selinux_context_net
911 unit_realize_cgroup(UNIT(s));
913 r = unit_setup_exec_runtime(UNIT(s));
918 s->exec_context.std_input == EXEC_INPUT_SOCKET ||
919 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
920 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
922 if (s->socket_fd >= 0) {
926 r = service_collect_fds(s, &fdsbuf, &n_fds);
935 r = service_arm_timer(s, timeout);
939 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
941 r = unit_full_printf_strv(UNIT(s), c->argv, &argv);
945 our_env = new0(char*, 4);
951 if (set_notify_socket)
952 if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=%s", UNIT(s)->manager->notify_socket) < 0) {
958 if (asprintf(our_env + n_env++, "MAINPID="PID_FMT, s->main_pid) < 0) {
963 if (UNIT(s)->manager->running_as != SYSTEMD_SYSTEM)
964 if (asprintf(our_env + n_env++, "MANAGERPID="PID_FMT, getpid()) < 0) {
969 final_env = strv_env_merge(2, UNIT(s)->manager->environment, our_env, NULL);
975 if (is_control && UNIT(s)->cgroup_path) {
976 path = strappenda(UNIT(s)->cgroup_path, "/control");
977 cg_create(SYSTEMD_CGROUP_CONTROLLER, path);
979 path = UNIT(s)->cgroup_path;
982 if (s->exec_context.bus_endpoint) {
983 r = bus_kernel_create_endpoint(UNIT(s)->manager->running_as == SYSTEMD_SYSTEM ? "system" : "user",
984 UNIT(s)->id, &bus_endpoint_path);
988 /* Pass the fd to the exec_params so that the child process can upload the policy.
989 * Keep a reference to the fd in the service, so the endpoint is kept alive as long
990 * as the service is running. */
991 exec_params.bus_endpoint_fd = s->bus_endpoint_fd = r;
995 exec_params.argv = argv;
996 exec_params.fds = fds;
997 exec_params.n_fds = n_fds;
998 exec_params.environment = final_env;
999 exec_params.confirm_spawn = UNIT(s)->manager->confirm_spawn;
1000 exec_params.cgroup_supported = UNIT(s)->manager->cgroup_supported;
1001 exec_params.cgroup_path = path;
1002 exec_params.runtime_prefix = manager_get_runtime_prefix(UNIT(s)->manager);
1003 exec_params.unit_id = UNIT(s)->id;
1004 exec_params.watchdog_usec = s->watchdog_usec;
1005 exec_params.bus_endpoint_path = bus_endpoint_path;
1006 if (s->type == SERVICE_IDLE)
1007 exec_params.idle_pipe = UNIT(s)->manager->idle_pipe;
1017 r = unit_watch_pid(UNIT(s), pid);
1019 /* FIXME: we need to do something here */
1028 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
1033 static int main_pid_good(Service *s) {
1036 /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1039 /* If we know the pid file, then lets just check if it is
1041 if (s->main_pid_known) {
1043 /* If it's an alien child let's check if it is still
1045 if (s->main_pid_alien && s->main_pid > 0)
1046 return pid_is_alive(s->main_pid);
1048 /* .. otherwise assume we'll get a SIGCHLD for it,
1049 * which we really should wait for to collect exit
1050 * status and code */
1051 return s->main_pid > 0;
1054 /* We don't know the pid */
1058 _pure_ static int control_pid_good(Service *s) {
1061 return s->control_pid > 0;
1064 static int cgroup_good(Service *s) {
1069 if (!UNIT(s)->cgroup_path)
1072 r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, UNIT(s)->cgroup_path, true);
1079 static void service_enter_dead(Service *s, ServiceResult f, bool allow_restart) {
1083 if (f != SERVICE_SUCCESS)
1086 service_set_state(s, s->result != SERVICE_SUCCESS ? SERVICE_FAILED : SERVICE_DEAD);
1088 if (s->result != SERVICE_SUCCESS) {
1089 log_warning_unit(UNIT(s)->id, "%s failed.", UNIT(s)->id);
1090 failure_action(UNIT(s)->manager, s->failure_action, s->reboot_arg);
1093 if (allow_restart &&
1094 !s->forbid_restart &&
1095 (s->restart == SERVICE_RESTART_ALWAYS ||
1096 (s->restart == SERVICE_RESTART_ON_SUCCESS && s->result == SERVICE_SUCCESS) ||
1097 (s->restart == SERVICE_RESTART_ON_FAILURE && s->result != SERVICE_SUCCESS) ||
1098 (s->restart == SERVICE_RESTART_ON_ABNORMAL && !IN_SET(s->result, SERVICE_SUCCESS, SERVICE_FAILURE_EXIT_CODE)) ||
1099 (s->restart == SERVICE_RESTART_ON_WATCHDOG && s->result == SERVICE_FAILURE_WATCHDOG) ||
1100 (s->restart == SERVICE_RESTART_ON_ABORT && IN_SET(s->result, SERVICE_FAILURE_SIGNAL, SERVICE_FAILURE_CORE_DUMP)) ||
1101 (s->main_exec_status.code == CLD_EXITED && set_contains(s->restart_force_status.status, INT_TO_PTR(s->main_exec_status.status))) ||
1102 (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)))) &&
1103 (s->main_exec_status.code != CLD_EXITED || !set_contains(s->restart_prevent_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_prevent_status.signal, INT_TO_PTR(s->main_exec_status.status)))) {
1106 r = service_arm_timer(s, s->restart_usec);
1110 service_set_state(s, SERVICE_AUTO_RESTART);
1113 s->forbid_restart = false;
1115 /* We want fresh tmpdirs in case service is started again immediately */
1116 exec_runtime_destroy(s->exec_runtime);
1117 s->exec_runtime = exec_runtime_unref(s->exec_runtime);
1119 /* Also, remove the runtime directory in */
1120 exec_context_destroy_runtime_directory(&s->exec_context, manager_get_runtime_prefix(UNIT(s)->manager));
1122 /* Try to delete the pid file. At this point it will be
1123 * out-of-date, and some software might be confused by it, so
1124 * let's remove it. */
1126 unlink_noerrno(s->pid_file);
1131 log_warning_unit(UNIT(s)->id, "%s failed to run install restart timer: %s", UNIT(s)->id, strerror(-r));
1132 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, false);
1135 static void service_enter_stop_post(Service *s, ServiceResult f) {
1139 if (f != SERVICE_SUCCESS)
1142 service_unwatch_control_pid(s);
1143 unit_watch_all_pids(UNIT(s));
1145 s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST];
1146 if (s->control_command) {
1147 s->control_command_id = SERVICE_EXEC_STOP_POST;
1149 r = service_spawn(s,
1151 s->timeout_stop_usec,
1153 !s->permissions_start_only,
1154 !s->root_directory_start_only,
1162 service_set_state(s, SERVICE_STOP_POST);
1164 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_SUCCESS);
1169 log_warning_unit(UNIT(s)->id, "%s failed to run 'stop-post' task: %s", UNIT(s)->id, strerror(-r));
1170 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
1173 static void service_enter_signal(Service *s, ServiceState state, ServiceResult f) {
1178 if (f != SERVICE_SUCCESS)
1181 unit_watch_all_pids(UNIT(s));
1183 r = unit_kill_context(
1186 state != SERVICE_STOP_SIGTERM && state != SERVICE_FINAL_SIGTERM,
1195 if (s->timeout_stop_usec > 0) {
1196 r = service_arm_timer(s, s->timeout_stop_usec);
1201 service_set_state(s, state);
1202 } else if (state == SERVICE_STOP_SIGTERM)
1203 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_SUCCESS);
1204 else if (state == SERVICE_STOP_SIGKILL)
1205 service_enter_stop_post(s, SERVICE_SUCCESS);
1206 else if (state == SERVICE_FINAL_SIGTERM)
1207 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_SUCCESS);
1209 service_enter_dead(s, SERVICE_SUCCESS, true);
1214 log_warning_unit(UNIT(s)->id, "%s failed to kill processes: %s", UNIT(s)->id, strerror(-r));
1216 if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1217 service_enter_stop_post(s, SERVICE_FAILURE_RESOURCES);
1219 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
1222 static void service_enter_stop_by_notify(Service *s) {
1225 unit_watch_all_pids(UNIT(s));
1227 if (s->timeout_stop_usec > 0)
1228 service_arm_timer(s, s->timeout_stop_usec);
1230 /* The service told us it's stopping, so it's as if we SIGTERM'd it. */
1231 service_set_state(s, SERVICE_STOP_SIGTERM);
1234 static void service_enter_stop(Service *s, ServiceResult f) {
1239 if (f != SERVICE_SUCCESS)
1242 service_unwatch_control_pid(s);
1243 unit_watch_all_pids(UNIT(s));
1245 s->control_command = s->exec_command[SERVICE_EXEC_STOP];
1246 if (s->control_command) {
1247 s->control_command_id = SERVICE_EXEC_STOP;
1249 r = service_spawn(s,
1251 s->timeout_stop_usec,
1253 !s->permissions_start_only,
1254 !s->root_directory_start_only,
1262 service_set_state(s, SERVICE_STOP);
1264 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
1269 log_warning_unit(UNIT(s)->id, "%s failed to run 'stop' task: %s", UNIT(s)->id, strerror(-r));
1270 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
1273 static void service_enter_running(Service *s, ServiceResult f) {
1274 int main_pid_ok, cgroup_ok;
1277 if (f != SERVICE_SUCCESS)
1280 main_pid_ok = main_pid_good(s);
1281 cgroup_ok = cgroup_good(s);
1283 if ((main_pid_ok > 0 || (main_pid_ok < 0 && cgroup_ok != 0)) &&
1284 (s->bus_name_good || s->type != SERVICE_DBUS)) {
1286 /* If there are any queued up sd_notify()
1287 * notifications, process them now */
1288 if (s->notify_state == NOTIFY_RELOADING)
1289 service_enter_reload_by_notify(s);
1290 else if (s->notify_state == NOTIFY_STOPPING)
1291 service_enter_stop_by_notify(s);
1293 service_set_state(s, SERVICE_RUNNING);
1295 } else if (s->remain_after_exit)
1296 service_set_state(s, SERVICE_EXITED);
1298 service_enter_stop(s, SERVICE_SUCCESS);
1301 static void service_enter_start_post(Service *s) {
1305 service_unwatch_control_pid(s);
1306 service_reset_watchdog(s);
1308 s->control_command = s->exec_command[SERVICE_EXEC_START_POST];
1309 if (s->control_command) {
1310 s->control_command_id = SERVICE_EXEC_START_POST;
1312 r = service_spawn(s,
1314 s->timeout_start_usec,
1316 !s->permissions_start_only,
1317 !s->root_directory_start_only,
1325 service_set_state(s, SERVICE_START_POST);
1327 service_enter_running(s, SERVICE_SUCCESS);
1332 log_warning_unit(UNIT(s)->id, "%s failed to run 'start-post' task: %s", UNIT(s)->id, strerror(-r));
1333 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
1336 static void service_kill_control_processes(Service *s) {
1339 if (!UNIT(s)->cgroup_path)
1342 p = strappenda(UNIT(s)->cgroup_path, "/control");
1343 cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, p, SIGKILL, true, true, true, NULL);
1346 static void service_enter_start(Service *s) {
1353 service_unwatch_control_pid(s);
1354 service_unwatch_main_pid(s);
1356 /* We want to ensure that nobody leaks processes from
1357 * START_PRE here, so let's go on a killing spree, People
1358 * should not spawn long running processes from START_PRE. */
1359 service_kill_control_processes(s);
1361 if (s->type == SERVICE_FORKING) {
1362 s->control_command_id = SERVICE_EXEC_START;
1363 c = s->control_command = s->exec_command[SERVICE_EXEC_START];
1365 s->main_command = NULL;
1367 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1368 s->control_command = NULL;
1370 c = s->main_command = s->exec_command[SERVICE_EXEC_START];
1374 assert(s->type == SERVICE_ONESHOT);
1375 service_enter_start_post(s);
1379 r = service_spawn(s,
1381 IN_SET(s->type, SERVICE_FORKING, SERVICE_DBUS, SERVICE_NOTIFY, SERVICE_ONESHOT) ? s->timeout_start_usec : 0,
1386 s->notify_access != NOTIFY_NONE,
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,
1458 service_set_state(s, SERVICE_START_PRE);
1460 service_enter_start(s);
1465 log_warning_unit(UNIT(s)->id, "%s failed to run 'start-pre' task: %s", UNIT(s)->id, strerror(-r));
1466 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
1469 static void service_enter_restart(Service *s) {
1470 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
1475 if (UNIT(s)->job && UNIT(s)->job->type == JOB_STOP) {
1476 /* Don't restart things if we are going down anyway */
1477 log_info_unit(UNIT(s)->id, "Stop job pending for unit, delaying automatic restart.");
1479 r = service_arm_timer(s, s->restart_usec);
1486 /* Any units that are bound to this service must also be
1487 * restarted. We use JOB_RESTART (instead of the more obvious
1488 * JOB_START) here so that those dependency jobs will be added
1490 r = manager_add_job(UNIT(s)->manager, JOB_RESTART, UNIT(s), JOB_FAIL, false, &error, NULL);
1494 /* Note that we stay in the SERVICE_AUTO_RESTART state here,
1495 * it will be canceled as part of the service_stop() call that
1496 * is executed as part of JOB_RESTART. */
1498 log_debug_unit(UNIT(s)->id, "%s scheduled restart job.", UNIT(s)->id);
1502 log_warning_unit(UNIT(s)->id, "%s failed to schedule restart job: %s", UNIT(s)->id, bus_error_message(&error, -r));
1503 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, false);
1506 static void service_enter_reload_by_notify(Service *s) {
1509 if (s->timeout_start_usec > 0)
1510 service_arm_timer(s, s->timeout_start_usec);
1512 service_set_state(s, SERVICE_RELOAD);
1515 static void service_enter_reload(Service *s) {
1520 service_unwatch_control_pid(s);
1522 s->control_command = s->exec_command[SERVICE_EXEC_RELOAD];
1523 if (s->control_command) {
1524 s->control_command_id = SERVICE_EXEC_RELOAD;
1526 r = service_spawn(s,
1528 s->timeout_start_usec,
1530 !s->permissions_start_only,
1531 !s->root_directory_start_only,
1539 service_set_state(s, SERVICE_RELOAD);
1541 service_enter_running(s, SERVICE_SUCCESS);
1546 log_warning_unit(UNIT(s)->id, "%s failed to run 'reload' task: %s", UNIT(s)->id, strerror(-r));
1547 s->reload_result = SERVICE_FAILURE_RESOURCES;
1548 service_enter_running(s, SERVICE_SUCCESS);
1551 static void service_run_next_control(Service *s) {
1555 assert(s->control_command);
1556 assert(s->control_command->command_next);
1558 assert(s->control_command_id != SERVICE_EXEC_START);
1560 s->control_command = s->control_command->command_next;
1561 service_unwatch_control_pid(s);
1563 r = service_spawn(s,
1565 IN_SET(s->state, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD) ? s->timeout_start_usec : s->timeout_stop_usec,
1567 !s->permissions_start_only,
1568 !s->root_directory_start_only,
1569 s->control_command_id == SERVICE_EXEC_START_PRE ||
1570 s->control_command_id == SERVICE_EXEC_STOP_POST,
1580 log_warning_unit(UNIT(s)->id, "%s failed to run next control task: %s", UNIT(s)->id, strerror(-r));
1582 if (s->state == SERVICE_START_PRE)
1583 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
1584 else if (s->state == SERVICE_STOP)
1585 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
1586 else if (s->state == SERVICE_STOP_POST)
1587 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
1588 else if (s->state == SERVICE_RELOAD) {
1589 s->reload_result = SERVICE_FAILURE_RESOURCES;
1590 service_enter_running(s, SERVICE_SUCCESS);
1592 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
1595 static void service_run_next_main(Service *s) {
1600 assert(s->main_command);
1601 assert(s->main_command->command_next);
1602 assert(s->type == SERVICE_ONESHOT);
1604 s->main_command = s->main_command->command_next;
1605 service_unwatch_main_pid(s);
1607 r = service_spawn(s,
1609 s->timeout_start_usec,
1614 s->notify_access != NOTIFY_NONE,
1620 service_set_main_pid(s, pid);
1625 log_warning_unit(UNIT(s)->id, "%s failed to run next main task: %s", UNIT(s)->id, strerror(-r));
1626 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
1629 static int service_start_limit_test(Service *s) {
1632 if (ratelimit_test(&s->start_limit))
1635 log_warning_unit(UNIT(s)->id, "start request repeated too quickly for %s", UNIT(s)->id);
1637 return failure_action(UNIT(s)->manager, s->start_limit_action, s->reboot_arg);
1640 static int service_start(Unit *u) {
1641 Service *s = SERVICE(u);
1646 /* We cannot fulfill this request right now, try again later
1648 if (s->state == SERVICE_STOP ||
1649 s->state == SERVICE_STOP_SIGTERM ||
1650 s->state == SERVICE_STOP_SIGKILL ||
1651 s->state == SERVICE_STOP_POST ||
1652 s->state == SERVICE_FINAL_SIGTERM ||
1653 s->state == SERVICE_FINAL_SIGKILL)
1656 /* Already on it! */
1657 if (s->state == SERVICE_START_PRE ||
1658 s->state == SERVICE_START ||
1659 s->state == SERVICE_START_POST)
1662 /* A service that will be restarted must be stopped first to
1663 * trigger BindsTo and/or OnFailure dependencies. If a user
1664 * does not want to wait for the holdoff time to elapse, the
1665 * service should be manually restarted, not started. We
1666 * simply return EAGAIN here, so that any start jobs stay
1667 * queued, and assume that the auto restart timer will
1668 * eventually trigger the restart. */
1669 if (s->state == SERVICE_AUTO_RESTART)
1672 assert(s->state == SERVICE_DEAD || s->state == SERVICE_FAILED);
1674 /* Make sure we don't enter a busy loop of some kind. */
1675 r = service_start_limit_test(s);
1677 service_enter_dead(s, SERVICE_FAILURE_START_LIMIT, false);
1681 s->result = SERVICE_SUCCESS;
1682 s->reload_result = SERVICE_SUCCESS;
1683 s->main_pid_known = false;
1684 s->main_pid_alien = false;
1685 s->forbid_restart = false;
1687 free(s->status_text);
1688 s->status_text = NULL;
1689 s->status_errno = 0;
1691 s->notify_state = NOTIFY_UNKNOWN;
1693 service_enter_start_pre(s);
1697 static int service_stop(Unit *u) {
1698 Service *s = SERVICE(u);
1702 /* Don't create restart jobs from here. */
1703 s->forbid_restart = true;
1706 if (s->state == SERVICE_STOP ||
1707 s->state == SERVICE_STOP_SIGTERM ||
1708 s->state == SERVICE_STOP_SIGKILL ||
1709 s->state == SERVICE_STOP_POST ||
1710 s->state == SERVICE_FINAL_SIGTERM ||
1711 s->state == SERVICE_FINAL_SIGKILL)
1714 /* A restart will be scheduled or is in progress. */
1715 if (s->state == SERVICE_AUTO_RESTART) {
1716 service_set_state(s, SERVICE_DEAD);
1720 /* If there's already something running we go directly into
1722 if (s->state == SERVICE_START_PRE ||
1723 s->state == SERVICE_START ||
1724 s->state == SERVICE_START_POST ||
1725 s->state == SERVICE_RELOAD) {
1726 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
1730 assert(s->state == SERVICE_RUNNING ||
1731 s->state == SERVICE_EXITED);
1733 service_enter_stop(s, SERVICE_SUCCESS);
1737 static int service_reload(Unit *u) {
1738 Service *s = SERVICE(u);
1742 assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
1744 service_enter_reload(s);
1748 _pure_ static bool service_can_reload(Unit *u) {
1749 Service *s = SERVICE(u);
1753 return !!s->exec_command[SERVICE_EXEC_RELOAD];
1756 static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
1757 Service *s = SERVICE(u);
1763 unit_serialize_item(u, f, "state", service_state_to_string(s->state));
1764 unit_serialize_item(u, f, "result", service_result_to_string(s->result));
1765 unit_serialize_item(u, f, "reload-result", service_result_to_string(s->reload_result));
1767 if (s->control_pid > 0)
1768 unit_serialize_item_format(u, f, "control-pid", PID_FMT,
1771 if (s->main_pid_known && s->main_pid > 0)
1772 unit_serialize_item_format(u, f, "main-pid", PID_FMT, s->main_pid);
1774 unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
1777 unit_serialize_item(u, f, "status-text", s->status_text);
1779 /* FIXME: There's a minor uncleanliness here: if there are
1780 * multiple commands attached here, we will start from the
1781 * first one again */
1782 if (s->control_command_id >= 0)
1783 unit_serialize_item(u, f, "control-command",
1784 service_exec_command_to_string(s->control_command_id));
1786 if (s->socket_fd >= 0) {
1789 if ((copy = fdset_put_dup(fds, s->socket_fd)) < 0)
1792 unit_serialize_item_format(u, f, "socket-fd", "%i", copy);
1795 if (s->bus_endpoint_fd >= 0) {
1798 if ((copy = fdset_put_dup(fds, s->bus_endpoint_fd)) < 0)
1801 unit_serialize_item_format(u, f, "endpoint-fd", "%i", copy);
1804 if (s->main_exec_status.pid > 0) {
1805 unit_serialize_item_format(u, f, "main-exec-status-pid", PID_FMT,
1806 s->main_exec_status.pid);
1807 dual_timestamp_serialize(f, "main-exec-status-start",
1808 &s->main_exec_status.start_timestamp);
1809 dual_timestamp_serialize(f, "main-exec-status-exit",
1810 &s->main_exec_status.exit_timestamp);
1812 if (dual_timestamp_is_set(&s->main_exec_status.exit_timestamp)) {
1813 unit_serialize_item_format(u, f, "main-exec-status-code", "%i",
1814 s->main_exec_status.code);
1815 unit_serialize_item_format(u, f, "main-exec-status-status", "%i",
1816 s->main_exec_status.status);
1819 if (dual_timestamp_is_set(&s->watchdog_timestamp))
1820 dual_timestamp_serialize(f, "watchdog-timestamp", &s->watchdog_timestamp);
1822 if (s->forbid_restart)
1823 unit_serialize_item(u, f, "forbid-restart", yes_no(s->forbid_restart));
1828 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
1829 Service *s = SERVICE(u);
1836 if (streq(key, "state")) {
1839 state = service_state_from_string(value);
1841 log_debug_unit(u->id, "Failed to parse state value %s", value);
1843 s->deserialized_state = state;
1844 } else if (streq(key, "result")) {
1847 f = service_result_from_string(value);
1849 log_debug_unit(u->id, "Failed to parse result value %s", value);
1850 else if (f != SERVICE_SUCCESS)
1853 } else if (streq(key, "reload-result")) {
1856 f = service_result_from_string(value);
1858 log_debug_unit(u->id, "Failed to parse reload result value %s", value);
1859 else if (f != SERVICE_SUCCESS)
1860 s->reload_result = f;
1862 } else if (streq(key, "control-pid")) {
1865 if (parse_pid(value, &pid) < 0)
1866 log_debug_unit(u->id, "Failed to parse control-pid value %s", value);
1868 s->control_pid = pid;
1869 } else if (streq(key, "main-pid")) {
1872 if (parse_pid(value, &pid) < 0)
1873 log_debug_unit(u->id, "Failed to parse main-pid value %s", value);
1875 service_set_main_pid(s, pid);
1876 unit_watch_pid(UNIT(s), pid);
1878 } else if (streq(key, "main-pid-known")) {
1881 b = parse_boolean(value);
1883 log_debug_unit(u->id, "Failed to parse main-pid-known value %s", value);
1885 s->main_pid_known = b;
1886 } else if (streq(key, "status-text")) {
1893 free(s->status_text);
1897 } else if (streq(key, "control-command")) {
1898 ServiceExecCommand id;
1900 id = service_exec_command_from_string(value);
1902 log_debug_unit(u->id, "Failed to parse exec-command value %s", value);
1904 s->control_command_id = id;
1905 s->control_command = s->exec_command[id];
1907 } else if (streq(key, "socket-fd")) {
1910 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
1911 log_debug_unit(u->id, "Failed to parse socket-fd value %s", value);
1913 asynchronous_close(s->socket_fd);
1914 s->socket_fd = fdset_remove(fds, fd);
1916 } else if (streq(key, "endpoint-fd")) {
1919 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
1920 log_debug_unit(u->id, "Failed to parse endpoint-fd value %s", value);
1922 safe_close(s->bus_endpoint_fd);
1923 s->bus_endpoint_fd = fdset_remove(fds, fd);
1925 } else if (streq(key, "main-exec-status-pid")) {
1928 if (parse_pid(value, &pid) < 0)
1929 log_debug_unit(u->id, "Failed to parse main-exec-status-pid value %s", value);
1931 s->main_exec_status.pid = pid;
1932 } else if (streq(key, "main-exec-status-code")) {
1935 if (safe_atoi(value, &i) < 0)
1936 log_debug_unit(u->id, "Failed to parse main-exec-status-code value %s", value);
1938 s->main_exec_status.code = i;
1939 } else if (streq(key, "main-exec-status-status")) {
1942 if (safe_atoi(value, &i) < 0)
1943 log_debug_unit(u->id, "Failed to parse main-exec-status-status value %s", value);
1945 s->main_exec_status.status = i;
1946 } else if (streq(key, "main-exec-status-start"))
1947 dual_timestamp_deserialize(value, &s->main_exec_status.start_timestamp);
1948 else if (streq(key, "main-exec-status-exit"))
1949 dual_timestamp_deserialize(value, &s->main_exec_status.exit_timestamp);
1950 else if (streq(key, "watchdog-timestamp"))
1951 dual_timestamp_deserialize(value, &s->watchdog_timestamp);
1952 else if (streq(key, "forbid-restart")) {
1955 b = parse_boolean(value);
1957 log_debug_unit(u->id, "Failed to parse forbid-restart value %s", value);
1959 s->forbid_restart = b;
1961 log_debug_unit(u->id, "Unknown serialization key '%s'", key);
1966 _pure_ static UnitActiveState service_active_state(Unit *u) {
1967 const UnitActiveState *table;
1971 table = SERVICE(u)->type == SERVICE_IDLE ? state_translation_table_idle : state_translation_table;
1973 return table[SERVICE(u)->state];
1976 static const char *service_sub_state_to_string(Unit *u) {
1979 return service_state_to_string(SERVICE(u)->state);
1982 static bool service_check_gc(Unit *u) {
1983 Service *s = SERVICE(u);
1987 /* Never clean up services that still have a process around,
1988 * even if the service is formally dead. */
1989 if (cgroup_good(s) > 0 ||
1990 main_pid_good(s) > 0 ||
1991 control_pid_good(s) > 0)
1997 _pure_ static bool service_check_snapshot(Unit *u) {
1998 Service *s = SERVICE(u);
2002 return s->socket_fd < 0;
2005 static int service_retry_pid_file(Service *s) {
2008 assert(s->pid_file);
2009 assert(s->state == SERVICE_START || s->state == SERVICE_START_POST);
2011 r = service_load_pid_file(s, false);
2015 service_unwatch_pid_file(s);
2017 service_enter_running(s, SERVICE_SUCCESS);
2021 static int service_watch_pid_file(Service *s) {
2024 log_debug_unit(UNIT(s)->id, "Setting watch for %s's PID file %s", UNIT(s)->id, s->pid_file_pathspec->path);
2026 r = path_spec_watch(s->pid_file_pathspec, service_dispatch_io);
2030 /* the pidfile might have appeared just before we set the watch */
2031 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);
2032 service_retry_pid_file(s);
2036 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));
2037 service_unwatch_pid_file(s);
2041 static int service_demand_pid_file(Service *s) {
2044 assert(s->pid_file);
2045 assert(!s->pid_file_pathspec);
2047 ps = new0(PathSpec, 1);
2052 ps->path = strdup(s->pid_file);
2058 path_kill_slashes(ps->path);
2060 /* PATH_CHANGED would not be enough. There are daemons (sendmail) that
2061 * keep their PID file open all the time. */
2062 ps->type = PATH_MODIFIED;
2063 ps->inotify_fd = -1;
2065 s->pid_file_pathspec = ps;
2067 return service_watch_pid_file(s);
2070 static int service_dispatch_io(sd_event_source *source, int fd, uint32_t events, void *userdata) {
2071 PathSpec *p = userdata;
2076 s = SERVICE(p->unit);
2080 assert(s->state == SERVICE_START || s->state == SERVICE_START_POST);
2081 assert(s->pid_file_pathspec);
2082 assert(path_spec_owns_inotify_fd(s->pid_file_pathspec, fd));
2084 log_debug_unit(UNIT(s)->id, "inotify event for %s", UNIT(s)->id);
2086 if (path_spec_fd_event(p, events) < 0)
2089 if (service_retry_pid_file(s) == 0)
2092 if (service_watch_pid_file(s) < 0)
2098 service_unwatch_pid_file(s);
2099 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
2103 static void service_notify_cgroup_empty_event(Unit *u) {
2104 Service *s = SERVICE(u);
2108 log_debug_unit(u->id, "%s: cgroup is empty", u->id);
2112 /* Waiting for SIGCHLD is usually more interesting,
2113 * because it includes return codes/signals. Which is
2114 * why we ignore the cgroup events for most cases,
2115 * except when we don't know pid which to expect the
2119 case SERVICE_START_POST:
2120 /* If we were hoping for the daemon to write its PID file,
2121 * we can give up now. */
2122 if (s->pid_file_pathspec) {
2123 log_warning_unit(u->id, "%s never wrote its PID file. Failing.", UNIT(s)->id);
2125 service_unwatch_pid_file(s);
2126 if (s->state == SERVICE_START)
2127 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
2129 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2133 case SERVICE_RUNNING:
2134 /* service_enter_running() will figure out what to do */
2135 service_enter_running(s, SERVICE_SUCCESS);
2138 case SERVICE_STOP_SIGTERM:
2139 case SERVICE_STOP_SIGKILL:
2141 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2142 service_enter_stop_post(s, SERVICE_SUCCESS);
2146 case SERVICE_STOP_POST:
2147 case SERVICE_FINAL_SIGTERM:
2148 case SERVICE_FINAL_SIGKILL:
2149 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2150 service_enter_dead(s, SERVICE_SUCCESS, true);
2159 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2160 Service *s = SERVICE(u);
2166 if (UNIT(s)->fragment_path ? is_clean_exit(code, status, &s->success_status) :
2167 is_clean_exit_lsb(code, status, &s->success_status))
2168 f = SERVICE_SUCCESS;
2169 else if (code == CLD_EXITED)
2170 f = SERVICE_FAILURE_EXIT_CODE;
2171 else if (code == CLD_KILLED)
2172 f = SERVICE_FAILURE_SIGNAL;
2173 else if (code == CLD_DUMPED)
2174 f = SERVICE_FAILURE_CORE_DUMP;
2176 assert_not_reached("Unknown code");
2178 if (s->main_pid == pid) {
2179 /* Forking services may occasionally move to a new PID.
2180 * As long as they update the PID file before exiting the old
2181 * PID, they're fine. */
2182 if (service_load_pid_file(s, false) == 0)
2186 exec_status_exit(&s->main_exec_status, &s->exec_context, pid, code, status);
2188 if (s->main_command) {
2189 /* If this is not a forking service than the
2190 * main process got started and hence we copy
2191 * the exit status so that it is recorded both
2192 * as main and as control process exit
2195 s->main_command->exec_status = s->main_exec_status;
2197 if (s->main_command->ignore)
2198 f = SERVICE_SUCCESS;
2199 } else if (s->exec_command[SERVICE_EXEC_START]) {
2201 /* If this is a forked process, then we should
2202 * ignore the return value if this was
2203 * configured for the starter process */
2205 if (s->exec_command[SERVICE_EXEC_START]->ignore)
2206 f = SERVICE_SUCCESS;
2209 log_struct_unit(f == SERVICE_SUCCESS ? LOG_DEBUG : LOG_NOTICE,
2211 "MESSAGE=%s: main process exited, code=%s, status=%i/%s",
2212 u->id, sigchld_code_to_string(code), status,
2213 strna(code == CLD_EXITED
2214 ? exit_status_to_string(status, EXIT_STATUS_FULL)
2215 : signal_to_string(status)),
2216 "EXIT_CODE=%s", sigchld_code_to_string(code),
2217 "EXIT_STATUS=%i", status,
2220 if (f != SERVICE_SUCCESS)
2223 if (s->main_command &&
2224 s->main_command->command_next &&
2225 f == SERVICE_SUCCESS) {
2227 /* There is another command to *
2228 * execute, so let's do that. */
2230 log_debug_unit(u->id, "%s running next main command for state %s", u->id, service_state_to_string(s->state));
2231 service_run_next_main(s);
2235 /* The service exited, so the service is officially
2237 s->main_command = NULL;
2241 case SERVICE_START_POST:
2242 case SERVICE_RELOAD:
2244 /* Need to wait until the operation is
2249 if (s->type == SERVICE_ONESHOT) {
2250 /* This was our main goal, so let's go on */
2251 if (f == SERVICE_SUCCESS)
2252 service_enter_start_post(s);
2254 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
2260 case SERVICE_RUNNING:
2261 service_enter_running(s, f);
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_SIGTERM:
2405 case SERVICE_STOP_SIGKILL:
2406 if (main_pid_good(s) <= 0)
2407 service_enter_stop_post(s, f);
2409 /* If there is still a service
2410 * process around, wait until
2411 * that one quit, too */
2414 case SERVICE_STOP_POST:
2415 case SERVICE_FINAL_SIGTERM:
2416 case SERVICE_FINAL_SIGKILL:
2417 if (main_pid_good(s) <= 0)
2418 service_enter_dead(s, f, true);
2422 assert_not_reached("Uh, control process died at wrong time.");
2427 /* Notify clients about changed exit status */
2428 unit_add_to_dbus_queue(u);
2430 /* We got one SIGCHLD for the service, let's watch all
2431 * processes that are now running of the service, and watch
2432 * that. Among the PIDs we then watch will be children
2433 * reassigned to us, which hopefully allows us to identify
2434 * when all children are gone */
2435 unit_tidy_watch_pids(u, s->main_pid, s->control_pid);
2436 unit_watch_all_pids(u);
2438 /* If the PID set is empty now, then let's finish this off */
2439 if (set_isempty(u->pids))
2440 service_notify_cgroup_empty_event(u);
2443 static int service_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata) {
2444 Service *s = SERVICE(userdata);
2447 assert(source == s->timer_event_source);
2451 case SERVICE_START_PRE:
2453 log_warning_unit(UNIT(s)->id, "%s %s operation timed out. Terminating.", UNIT(s)->id, s->state == SERVICE_START ? "start" : "start-pre");
2454 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2457 case SERVICE_START_POST:
2458 log_warning_unit(UNIT(s)->id, "%s start-post operation timed out. Stopping.", UNIT(s)->id);
2459 service_enter_stop(s, SERVICE_FAILURE_TIMEOUT);
2462 case SERVICE_RELOAD:
2463 log_warning_unit(UNIT(s)->id, "%s reload operation timed out. Stopping.", UNIT(s)->id);
2464 s->reload_result = SERVICE_FAILURE_TIMEOUT;
2465 service_enter_running(s, SERVICE_SUCCESS);
2469 log_warning_unit(UNIT(s)->id, "%s stopping timed out. Terminating.", UNIT(s)->id);
2470 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2473 case SERVICE_STOP_SIGTERM:
2474 if (s->kill_context.send_sigkill) {
2475 log_warning_unit(UNIT(s)->id, "%s stop-sigterm timed out. Killing.", UNIT(s)->id);
2476 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_TIMEOUT);
2478 log_warning_unit(UNIT(s)->id, "%s stop-sigterm timed out. Skipping SIGKILL.", UNIT(s)->id);
2479 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
2484 case SERVICE_STOP_SIGKILL:
2485 /* Uh, we sent a SIGKILL and it is still not gone?
2486 * Must be something we cannot kill, so let's just be
2487 * weirded out and continue */
2489 log_warning_unit(UNIT(s)->id, "%s still around after SIGKILL. Ignoring.", UNIT(s)->id);
2490 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
2493 case SERVICE_STOP_POST:
2494 log_warning_unit(UNIT(s)->id, "%s stop-post timed out. Terminating.", UNIT(s)->id);
2495 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2498 case SERVICE_FINAL_SIGTERM:
2499 if (s->kill_context.send_sigkill) {
2500 log_warning_unit(UNIT(s)->id, "%s stop-final-sigterm timed out. Killing.", UNIT(s)->id);
2501 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_FAILURE_TIMEOUT);
2503 log_warning_unit(UNIT(s)->id, "%s stop-final-sigterm timed out. Skipping SIGKILL. Entering failed mode.", UNIT(s)->id);
2504 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, false);
2509 case SERVICE_FINAL_SIGKILL:
2510 log_warning_unit(UNIT(s)->id, "%s still around after final SIGKILL. Entering failed mode.", UNIT(s)->id);
2511 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, true);
2514 case SERVICE_AUTO_RESTART:
2515 log_info_unit(UNIT(s)->id,
2516 s->restart_usec > 0 ?
2517 "%s holdoff time over, scheduling restart." :
2518 "%s has no holdoff time, scheduling restart.",
2520 service_enter_restart(s);
2524 assert_not_reached("Timeout at wrong time.");
2530 static int service_dispatch_watchdog(sd_event_source *source, usec_t usec, void *userdata) {
2531 Service *s = SERVICE(userdata);
2532 char t[FORMAT_TIMESPAN_MAX];
2535 assert(source == s->watchdog_event_source);
2537 log_error_unit(UNIT(s)->id, "%s watchdog timeout (limit %s)!", UNIT(s)->id,
2538 format_timespan(t, sizeof(t), s->watchdog_usec, 1));
2540 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_WATCHDOG);
2545 static void service_notify_message(Unit *u, pid_t pid, char **tags) {
2546 Service *s = SERVICE(u);
2547 _cleanup_free_ char *cc = NULL;
2548 bool notify_dbus = false;
2553 cc = strv_join(tags, ", ");
2554 log_debug_unit(u->id, "%s: Got notification message from PID "PID_FMT" (%s)",
2555 u->id, pid, isempty(cc) ? "n/a" : cc);
2557 if (s->notify_access == NOTIFY_NONE) {
2558 log_warning_unit(u->id, "%s: Got notification message from PID "PID_FMT", but reception is disabled.", u->id, pid);
2562 if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
2563 if (s->main_pid != 0)
2564 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);
2566 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);
2570 /* Interpret MAINPID= */
2571 e = strv_find_startswith(tags, "MAINPID=");
2572 if (e && IN_SET(s->state, SERVICE_START, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD)) {
2573 if (parse_pid(e, &pid) < 0)
2574 log_warning_unit(u->id, "Failed to parse MAINPID= field in notification message: %s", e);
2576 log_debug_unit(u->id, "%s: got MAINPID=%s", u->id, e);
2578 service_set_main_pid(s, pid);
2579 unit_watch_pid(UNIT(s), pid);
2584 /* Interpret RELOADING= */
2585 if (strv_find(tags, "RELOADING=1")) {
2587 log_debug_unit(u->id, "%s: got RELOADING=1", u->id);
2588 s->notify_state = NOTIFY_RELOADING;
2590 if (s->state == SERVICE_RUNNING)
2591 service_enter_reload_by_notify(s);
2596 /* Interpret READY= */
2597 if (strv_find(tags, "READY=1")) {
2599 log_debug_unit(u->id, "%s: got READY=1", u->id);
2600 s->notify_state = NOTIFY_READY;
2602 /* Type=notify services inform us about completed
2603 * initialization with READY=1 */
2604 if (s->type == SERVICE_NOTIFY && s->state == SERVICE_START)
2605 service_enter_start_post(s);
2607 /* Sending READY=1 while we are reloading informs us
2608 * that the reloading is complete */
2609 if (s->state == SERVICE_RELOAD && s->control_pid == 0)
2610 service_enter_running(s, SERVICE_SUCCESS);
2615 /* Interpret STOPPING= */
2616 if (strv_find(tags, "STOPPING=1")) {
2618 log_debug_unit(u->id, "%s: got STOPPING=1", u->id);
2619 s->notify_state = NOTIFY_STOPPING;
2621 if (s->state == SERVICE_RUNNING)
2622 service_enter_stop_by_notify(s);
2627 /* Interpret STATUS= */
2628 e = strv_find_startswith(tags, "STATUS=");
2630 _cleanup_free_ char *t = NULL;
2633 if (!utf8_is_valid(e))
2634 log_warning_unit(u->id, "Status message in notification is not UTF-8 clean.");
2636 log_debug_unit(u->id, "%s: got STATUS=%s", u->id, e);
2644 if (!streq_ptr(s->status_text, t)) {
2646 free(s->status_text);
2654 /* Interpret ERRNO= */
2655 e = strv_find_startswith(tags, "ERRNO=");
2659 if (safe_atoi(e, &status_errno) < 0 || status_errno < 0)
2660 log_warning_unit(u->id, "Failed to parse ERRNO= field in notification message: %s", e);
2662 log_debug_unit(u->id, "%s: got ERRNO=%s", u->id, e);
2664 if (s->status_errno != status_errno) {
2665 s->status_errno = status_errno;
2671 /* Interpret WATCHDOG= */
2672 if (strv_find(tags, "WATCHDOG=1")) {
2673 log_debug_unit(u->id, "%s: got WATCHDOG=1", u->id);
2674 service_reset_watchdog(s);
2677 /* Notify clients about changed status or main pid */
2679 unit_add_to_dbus_queue(u);
2682 static int service_get_timeout(Unit *u, uint64_t *timeout) {
2683 Service *s = SERVICE(u);
2686 if (!s->timer_event_source)
2689 r = sd_event_source_get_time(s->timer_event_source, timeout);
2696 static void service_bus_name_owner_change(
2699 const char *old_owner,
2700 const char *new_owner) {
2702 Service *s = SERVICE(u);
2708 assert(streq(s->bus_name, name));
2709 assert(old_owner || new_owner);
2711 if (old_owner && new_owner)
2712 log_debug_unit(u->id, "%s's D-Bus name %s changed owner from %s to %s", u->id, name, old_owner, new_owner);
2714 log_debug_unit(u->id, "%s's D-Bus name %s no longer registered by %s", u->id, name, old_owner);
2716 log_debug_unit(u->id, "%s's D-Bus name %s now registered by %s", u->id, name, new_owner);
2718 s->bus_name_good = !!new_owner;
2720 if (s->type == SERVICE_DBUS) {
2722 /* service_enter_running() will figure out what to
2724 if (s->state == SERVICE_RUNNING)
2725 service_enter_running(s, SERVICE_SUCCESS);
2726 else if (s->state == SERVICE_START && new_owner)
2727 service_enter_start_post(s);
2729 } else if (new_owner &&
2731 (s->state == SERVICE_START ||
2732 s->state == SERVICE_START_POST ||
2733 s->state == SERVICE_RUNNING ||
2734 s->state == SERVICE_RELOAD)) {
2736 _cleanup_bus_creds_unref_ sd_bus_creds *creds = NULL;
2739 /* Try to acquire PID from bus service */
2741 r = sd_bus_get_owner(u->manager->api_bus, name, SD_BUS_CREDS_PID, &creds);
2743 r = sd_bus_creds_get_pid(creds, &pid);
2745 log_debug_unit(u->id, "%s's D-Bus name %s is now owned by process %u", u->id, name, (unsigned) pid);
2747 service_set_main_pid(s, pid);
2748 unit_watch_pid(UNIT(s), pid);
2753 int service_set_socket_fd(Service *s, int fd, Socket *sock, bool selinux_context_net) {
2754 _cleanup_free_ char *peer = NULL;
2760 /* This is called by the socket code when instantiating a new
2761 * service for a stream socket and the socket needs to be
2764 if (UNIT(s)->load_state != UNIT_LOADED)
2767 if (s->socket_fd >= 0)
2770 if (s->state != SERVICE_DEAD)
2773 if (getpeername_pretty(fd, &peer) >= 0) {
2775 if (UNIT(s)->description) {
2776 _cleanup_free_ char *a;
2778 a = strjoin(UNIT(s)->description, " (", peer, ")", NULL);
2782 r = unit_set_description(UNIT(s), a);
2784 r = unit_set_description(UNIT(s), peer);
2791 s->socket_fd_selinux_context_net = selinux_context_net;
2793 unit_ref_set(&s->accept_socket, UNIT(sock));
2795 return unit_add_two_dependencies(UNIT(sock), UNIT_BEFORE, UNIT_TRIGGERS, UNIT(s), false);
2798 static void service_reset_failed(Unit *u) {
2799 Service *s = SERVICE(u);
2803 if (s->state == SERVICE_FAILED)
2804 service_set_state(s, SERVICE_DEAD);
2806 s->result = SERVICE_SUCCESS;
2807 s->reload_result = SERVICE_SUCCESS;
2809 RATELIMIT_RESET(s->start_limit);
2812 static int service_kill(Unit *u, KillWho who, int signo, sd_bus_error *error) {
2813 Service *s = SERVICE(u);
2815 return unit_kill_common(u, who, signo, s->main_pid, s->control_pid, error);
2818 static const char* const service_state_table[_SERVICE_STATE_MAX] = {
2819 [SERVICE_DEAD] = "dead",
2820 [SERVICE_START_PRE] = "start-pre",
2821 [SERVICE_START] = "start",
2822 [SERVICE_START_POST] = "start-post",
2823 [SERVICE_RUNNING] = "running",
2824 [SERVICE_EXITED] = "exited",
2825 [SERVICE_RELOAD] = "reload",
2826 [SERVICE_STOP] = "stop",
2827 [SERVICE_STOP_SIGTERM] = "stop-sigterm",
2828 [SERVICE_STOP_SIGKILL] = "stop-sigkill",
2829 [SERVICE_STOP_POST] = "stop-post",
2830 [SERVICE_FINAL_SIGTERM] = "final-sigterm",
2831 [SERVICE_FINAL_SIGKILL] = "final-sigkill",
2832 [SERVICE_FAILED] = "failed",
2833 [SERVICE_AUTO_RESTART] = "auto-restart",
2836 DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
2838 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
2839 [SERVICE_RESTART_NO] = "no",
2840 [SERVICE_RESTART_ON_SUCCESS] = "on-success",
2841 [SERVICE_RESTART_ON_FAILURE] = "on-failure",
2842 [SERVICE_RESTART_ON_ABNORMAL] = "on-abnormal",
2843 [SERVICE_RESTART_ON_WATCHDOG] = "on-watchdog",
2844 [SERVICE_RESTART_ON_ABORT] = "on-abort",
2845 [SERVICE_RESTART_ALWAYS] = "always",
2848 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
2850 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
2851 [SERVICE_SIMPLE] = "simple",
2852 [SERVICE_FORKING] = "forking",
2853 [SERVICE_ONESHOT] = "oneshot",
2854 [SERVICE_DBUS] = "dbus",
2855 [SERVICE_NOTIFY] = "notify",
2856 [SERVICE_IDLE] = "idle"
2859 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
2861 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
2862 [SERVICE_EXEC_START_PRE] = "ExecStartPre",
2863 [SERVICE_EXEC_START] = "ExecStart",
2864 [SERVICE_EXEC_START_POST] = "ExecStartPost",
2865 [SERVICE_EXEC_RELOAD] = "ExecReload",
2866 [SERVICE_EXEC_STOP] = "ExecStop",
2867 [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
2870 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
2872 static const char* const notify_access_table[_NOTIFY_ACCESS_MAX] = {
2873 [NOTIFY_NONE] = "none",
2874 [NOTIFY_MAIN] = "main",
2875 [NOTIFY_ALL] = "all"
2878 DEFINE_STRING_TABLE_LOOKUP(notify_access, NotifyAccess);
2880 static const char* const notify_state_table[_NOTIFY_STATE_MAX] = {
2881 [NOTIFY_UNKNOWN] = "unknown",
2882 [NOTIFY_READY] = "ready",
2883 [NOTIFY_RELOADING] = "reloading",
2884 [NOTIFY_STOPPING] = "stopping",
2887 DEFINE_STRING_TABLE_LOOKUP(notify_state, NotifyState);
2889 static const char* const service_result_table[_SERVICE_RESULT_MAX] = {
2890 [SERVICE_SUCCESS] = "success",
2891 [SERVICE_FAILURE_RESOURCES] = "resources",
2892 [SERVICE_FAILURE_TIMEOUT] = "timeout",
2893 [SERVICE_FAILURE_EXIT_CODE] = "exit-code",
2894 [SERVICE_FAILURE_SIGNAL] = "signal",
2895 [SERVICE_FAILURE_CORE_DUMP] = "core-dump",
2896 [SERVICE_FAILURE_WATCHDOG] = "watchdog",
2897 [SERVICE_FAILURE_START_LIMIT] = "start-limit"
2900 DEFINE_STRING_TABLE_LOOKUP(service_result, ServiceResult);
2902 const UnitVTable service_vtable = {
2903 .object_size = sizeof(Service),
2904 .exec_context_offset = offsetof(Service, exec_context),
2905 .cgroup_context_offset = offsetof(Service, cgroup_context),
2906 .kill_context_offset = offsetof(Service, kill_context),
2907 .exec_runtime_offset = offsetof(Service, exec_runtime),
2913 .private_section = "Service",
2915 .init = service_init,
2916 .done = service_done,
2917 .load = service_load,
2919 .coldplug = service_coldplug,
2921 .dump = service_dump,
2923 .start = service_start,
2924 .stop = service_stop,
2925 .reload = service_reload,
2927 .can_reload = service_can_reload,
2929 .kill = service_kill,
2931 .serialize = service_serialize,
2932 .deserialize_item = service_deserialize_item,
2934 .active_state = service_active_state,
2935 .sub_state_to_string = service_sub_state_to_string,
2937 .check_gc = service_check_gc,
2938 .check_snapshot = service_check_snapshot,
2940 .sigchld_event = service_sigchld_event,
2942 .reset_failed = service_reset_failed,
2944 .notify_cgroup_empty = service_notify_cgroup_empty_event,
2945 .notify_message = service_notify_message,
2947 .bus_name_owner_change = service_bus_name_owner_change,
2949 .bus_interface = "org.freedesktop.systemd1.Service",
2950 .bus_vtable = bus_service_vtable,
2951 .bus_set_property = bus_service_set_property,
2952 .bus_commit_properties = bus_service_commit_properties,
2954 .get_timeout = service_get_timeout,
2955 .can_transient = true,
2957 .status_message_formats = {
2958 .starting_stopping = {
2959 [0] = "Starting %s...",
2960 [1] = "Stopping %s...",
2962 .finished_start_job = {
2963 [JOB_DONE] = "Started %s.",
2964 [JOB_FAILED] = "Failed to start %s.",
2965 [JOB_DEPENDENCY] = "Dependency failed for %s.",
2966 [JOB_TIMEOUT] = "Timed out starting %s.",
2968 .finished_stop_job = {
2969 [JOB_DONE] = "Stopped %s.",
2970 [JOB_FAILED] = "Stopped (with error) %s.",
2971 [JOB_TIMEOUT] = "Timed out stopping %s.",