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_unit_debug(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_unit_warning(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_unit_warning_errno(UNIT(s)->id, r, "%s failed to reset watchdog timer: %m", UNIT(s)->id);
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_unit_warning_errno(UNIT(s)->id, r, "%s failed to add watchdog timer: %m", UNIT(s)->id);
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_unit_warning_errno(UNIT(s)->id, r, "%s failed to install watchdog timer: %m", UNIT(s)->id);
238 static void service_reset_watchdog(Service *s) {
241 dual_timestamp_get(&s->watchdog_timestamp);
242 service_start_watchdog(s);
245 static void service_fd_store_unlink(ServiceFDStore *fs) {
251 assert(fs->service->n_fd_store > 0);
252 LIST_REMOVE(fd_store, fs->service->fd_store, fs);
253 fs->service->n_fd_store--;
256 if (fs->event_source) {
257 sd_event_source_set_enabled(fs->event_source, SD_EVENT_OFF);
258 sd_event_source_unref(fs->event_source);
265 static void service_release_resources(Unit *u) {
266 Service *s = SERVICE(u);
273 log_debug("Releasing all resources for %s", u->id);
276 service_fd_store_unlink(s->fd_store);
278 assert(s->n_fd_store == 0);
281 static void service_done(Unit *u) {
282 Service *s = SERVICE(u);
289 free(s->status_text);
290 s->status_text = NULL;
293 s->reboot_arg = NULL;
295 s->exec_runtime = exec_runtime_unref(s->exec_runtime);
296 exec_command_free_array(s->exec_command, _SERVICE_EXEC_COMMAND_MAX);
297 s->control_command = NULL;
298 s->main_command = NULL;
300 exit_status_set_free(&s->restart_prevent_status);
301 exit_status_set_free(&s->restart_force_status);
302 exit_status_set_free(&s->success_status);
304 /* This will leak a process, but at least no memory or any of
306 service_unwatch_main_pid(s);
307 service_unwatch_control_pid(s);
308 service_unwatch_pid_file(s);
311 unit_unwatch_bus_name(u, s->bus_name);
316 s->bus_endpoint_fd = safe_close(s->bus_endpoint_fd);
317 service_close_socket_fd(s);
318 service_connection_unref(s);
320 unit_ref_unset(&s->accept_socket);
322 service_stop_watchdog(s);
324 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
326 service_release_resources(u);
329 static int service_arm_timer(Service *s, usec_t usec) {
334 if (s->timer_event_source) {
335 r = sd_event_source_set_time(s->timer_event_source, now(CLOCK_MONOTONIC) + usec);
339 return sd_event_source_set_enabled(s->timer_event_source, SD_EVENT_ONESHOT);
342 return sd_event_add_time(
343 UNIT(s)->manager->event,
344 &s->timer_event_source,
346 now(CLOCK_MONOTONIC) + usec, 0,
347 service_dispatch_timer, s);
350 static int service_verify(Service *s) {
353 if (UNIT(s)->load_state != UNIT_LOADED)
356 if (!s->exec_command[SERVICE_EXEC_START] && !s->exec_command[SERVICE_EXEC_STOP]) {
357 log_unit_error(UNIT(s)->id, "%s lacks both ExecStart= and ExecStop= setting. Refusing.", UNIT(s)->id);
361 if (s->type != SERVICE_ONESHOT && !s->exec_command[SERVICE_EXEC_START]) {
362 log_unit_error(UNIT(s)->id, "%s has no ExecStart= setting, which is only allowed for Type=oneshot services. Refusing.", UNIT(s)->id);
366 if (!s->remain_after_exit && !s->exec_command[SERVICE_EXEC_START]) {
367 log_unit_error(UNIT(s)->id, "%s has no ExecStart= setting, which is only allowed for RemainAfterExit=yes services. Refusing.", UNIT(s)->id);
371 if (s->type != SERVICE_ONESHOT && s->exec_command[SERVICE_EXEC_START]->command_next) {
372 log_unit_error(UNIT(s)->id, "%s has more than one ExecStart= setting, which is only allowed for Type=oneshot services. Refusing.", UNIT(s)->id);
376 if (s->type == SERVICE_ONESHOT && s->restart != SERVICE_RESTART_NO) {
377 log_unit_error(UNIT(s)->id, "%s has Restart= setting other than no, which isn't allowed for Type=oneshot services. Refusing.", UNIT(s)->id);
381 if (s->type == SERVICE_ONESHOT && !exit_status_set_is_empty(&s->restart_force_status)) {
382 log_unit_error(UNIT(s)->id, "%s has RestartForceStatus= set, which isn't allowed for Type=oneshot services. Refusing.", UNIT(s)->id);
386 if (s->type == SERVICE_DBUS && !s->bus_name) {
387 log_unit_error(UNIT(s)->id, "%s is of type D-Bus but no D-Bus service name has been specified. Refusing.", UNIT(s)->id);
391 if (s->bus_name && s->type != SERVICE_DBUS)
392 log_unit_warning(UNIT(s)->id, "%s has a D-Bus service name specified, but is not of type dbus. Ignoring.", UNIT(s)->id);
394 if (s->exec_context.pam_name && !(s->kill_context.kill_mode == KILL_CONTROL_GROUP || s->kill_context.kill_mode == KILL_MIXED)) {
395 log_unit_error(UNIT(s)->id, "%s has PAM enabled. Kill mode must be set to 'control-group' or 'mixed'. Refusing.", UNIT(s)->id);
402 static int service_add_default_dependencies(Service *s) {
407 /* Add a number of automatic dependencies useful for the
408 * majority of services. */
410 /* First, pull in base system */
411 r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_BASIC_TARGET, NULL, true);
415 /* Second, activate normal shutdown */
416 r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true);
420 static void service_fix_output(Service *s) {
423 /* If nothing has been explicitly configured, patch default
424 * output in. If input is socket/tty we avoid this however,
425 * since in that case we want output to default to the same
426 * place as we read input from. */
428 if (s->exec_context.std_error == EXEC_OUTPUT_INHERIT &&
429 s->exec_context.std_output == EXEC_OUTPUT_INHERIT &&
430 s->exec_context.std_input == EXEC_INPUT_NULL)
431 s->exec_context.std_error = UNIT(s)->manager->default_std_error;
433 if (s->exec_context.std_output == EXEC_OUTPUT_INHERIT &&
434 s->exec_context.std_input == EXEC_INPUT_NULL)
435 s->exec_context.std_output = UNIT(s)->manager->default_std_output;
438 static int service_load(Unit *u) {
439 Service *s = SERVICE(u);
444 /* Load a .service file */
445 r = unit_load_fragment(u);
449 /* Still nothing found? Then let's give up */
450 if (u->load_state == UNIT_STUB)
453 /* This is a new unit? Then let's add in some extras */
454 if (u->load_state == UNIT_LOADED) {
456 /* We were able to load something, then let's add in
457 * the dropin directories. */
458 r = unit_load_dropin(u);
462 if (s->type == _SERVICE_TYPE_INVALID) {
463 /* Figure out a type automatically */
465 s->type = SERVICE_DBUS;
466 else if (s->exec_command[SERVICE_EXEC_START])
467 s->type = SERVICE_SIMPLE;
469 s->type = SERVICE_ONESHOT;
472 /* Oneshot services have disabled start timeout by default */
473 if (s->type == SERVICE_ONESHOT && !s->start_timeout_defined)
474 s->timeout_start_usec = 0;
476 service_fix_output(s);
478 r = unit_patch_contexts(u);
482 r = unit_add_exec_dependencies(u, &s->exec_context);
486 r = unit_add_default_slice(u, &s->cgroup_context);
490 if (s->type == SERVICE_NOTIFY && s->notify_access == NOTIFY_NONE)
491 s->notify_access = NOTIFY_MAIN;
493 if (s->watchdog_usec > 0 && s->notify_access == NOTIFY_NONE)
494 s->notify_access = NOTIFY_MAIN;
497 r = unit_watch_bus_name(u, s->bus_name);
502 if (u->default_dependencies) {
503 r = service_add_default_dependencies(s);
510 return service_verify(s);
513 static void service_dump(Unit *u, FILE *f, const char *prefix) {
514 ServiceExecCommand c;
515 Service *s = SERVICE(u);
520 prefix = strempty(prefix);
521 prefix2 = strappenda(prefix, "\t");
524 "%sService State: %s\n"
526 "%sReload Result: %s\n"
527 "%sPermissionsStartOnly: %s\n"
528 "%sRootDirectoryStartOnly: %s\n"
529 "%sRemainAfterExit: %s\n"
530 "%sGuessMainPID: %s\n"
533 "%sNotifyAccess: %s\n"
534 "%sNotifyState: %s\n",
535 prefix, service_state_to_string(s->state),
536 prefix, service_result_to_string(s->result),
537 prefix, service_result_to_string(s->reload_result),
538 prefix, yes_no(s->permissions_start_only),
539 prefix, yes_no(s->root_directory_start_only),
540 prefix, yes_no(s->remain_after_exit),
541 prefix, yes_no(s->guess_main_pid),
542 prefix, service_type_to_string(s->type),
543 prefix, service_restart_to_string(s->restart),
544 prefix, notify_access_to_string(s->notify_access),
545 prefix, notify_state_to_string(s->notify_state));
547 if (s->control_pid > 0)
549 "%sControl PID: "PID_FMT"\n",
550 prefix, s->control_pid);
554 "%sMain PID: "PID_FMT"\n"
555 "%sMain PID Known: %s\n"
556 "%sMain PID Alien: %s\n",
558 prefix, yes_no(s->main_pid_known),
559 prefix, yes_no(s->main_pid_alien));
564 prefix, s->pid_file);
569 "%sBus Name Good: %s\n",
571 prefix, yes_no(s->bus_name_good));
573 kill_context_dump(&s->kill_context, f, prefix);
574 exec_context_dump(&s->exec_context, f, prefix);
576 for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
578 if (!s->exec_command[c])
581 fprintf(f, "%s-> %s:\n",
582 prefix, service_exec_command_to_string(c));
584 exec_command_dump_list(s->exec_command[c], f, prefix2);
588 fprintf(f, "%sStatus Text: %s\n",
589 prefix, s->status_text);
591 if (s->n_fd_store_max > 0) {
593 "%sFile Descriptor Store Max: %u\n"
594 "%sFile Descriptor Store Current: %u\n",
595 prefix, s->n_fd_store_max,
596 prefix, s->n_fd_store);
600 static int service_load_pid_file(Service *s, bool may_warn) {
601 _cleanup_free_ char *k = NULL;
610 r = read_one_line_file(s->pid_file, &k);
613 log_unit_info(UNIT(s)->id, "PID file %s not readable (yet?) after %s.", s->pid_file, service_state_to_string(s->state));
617 r = parse_pid(k, &pid);
620 log_unit_info_errno(UNIT(s)->id, r, "Failed to read PID from file %s: %m", s->pid_file);
624 if (!pid_is_alive(pid)) {
626 log_unit_info(UNIT(s)->id, "PID "PID_FMT" read from file %s does not exist or is a zombie.", pid, s->pid_file);
630 if (s->main_pid_known) {
631 if (pid == s->main_pid)
634 log_unit_debug(UNIT(s)->id, "Main PID changing: "PID_FMT" -> "PID_FMT, s->main_pid, pid);
636 service_unwatch_main_pid(s);
637 s->main_pid_known = false;
639 log_unit_debug(UNIT(s)->id, "Main PID loaded: "PID_FMT, pid);
641 r = service_set_main_pid(s, pid);
645 r = unit_watch_pid(UNIT(s), pid);
647 /* FIXME: we need to do something here */
648 log_unit_warning(UNIT(s)->id, "Failed to watch PID "PID_FMT" from service %s", pid, UNIT(s)->id);
655 static int service_search_main_pid(Service *s) {
661 /* If we know it anyway, don't ever fallback to unreliable
663 if (s->main_pid_known)
666 if (!s->guess_main_pid)
669 assert(s->main_pid <= 0);
671 pid = unit_search_main_pid(UNIT(s));
675 log_unit_debug(UNIT(s)->id, "Main PID guessed: "PID_FMT, pid);
676 r = service_set_main_pid(s, pid);
680 r = unit_watch_pid(UNIT(s), pid);
682 /* FIXME: we need to do something here */
683 log_unit_warning(UNIT(s)->id, "Failed to watch PID "PID_FMT" from service %s", pid, UNIT(s)->id);
690 static void service_set_state(Service *s, ServiceState state) {
691 ServiceState old_state;
692 const UnitActiveState *table;
696 table = s->type == SERVICE_IDLE ? state_translation_table_idle : state_translation_table;
698 old_state = s->state;
701 service_unwatch_pid_file(s);
704 SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
706 SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL,
707 SERVICE_STOP_SIGABRT, SERVICE_STOP_POST,
708 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL,
709 SERVICE_AUTO_RESTART))
710 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
713 SERVICE_START, SERVICE_START_POST,
714 SERVICE_RUNNING, SERVICE_RELOAD,
715 SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL,
716 SERVICE_STOP_SIGABRT, SERVICE_STOP_POST,
717 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL)) {
718 service_unwatch_main_pid(s);
719 s->main_command = NULL;
723 SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
725 SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL,
726 SERVICE_STOP_SIGABRT, SERVICE_STOP_POST,
727 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL)) {
728 service_unwatch_control_pid(s);
729 s->control_command = NULL;
730 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
733 if (IN_SET(state, SERVICE_DEAD, SERVICE_FAILED, SERVICE_AUTO_RESTART))
734 unit_unwatch_all_pids(UNIT(s));
737 SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
738 SERVICE_RUNNING, SERVICE_RELOAD,
739 SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
740 SERVICE_STOP_SIGABRT, SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL) &&
741 !(state == SERVICE_DEAD && UNIT(s)->job)) {
742 service_close_socket_fd(s);
743 service_connection_unref(s);
746 if (!IN_SET(state, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD))
747 service_stop_watchdog(s);
749 /* For the inactive states unit_notify() will trim the cgroup,
750 * but for exit we have to do that ourselves... */
751 if (state == SERVICE_EXITED && UNIT(s)->manager->n_reloading <= 0)
752 unit_destroy_cgroup_if_empty(UNIT(s));
754 /* For remain_after_exit services, let's see if we can "release" the
755 * hold on the console, since unit_notify() only does that in case of
757 if (state == SERVICE_EXITED &&
758 s->remain_after_exit &&
759 UNIT(s)->manager->n_on_console > 0) {
763 ec = unit_get_exec_context(UNIT(s));
764 if (ec && exec_context_may_touch_console(ec)) {
765 Manager *m = UNIT(s)->manager;
768 if (m->n_on_console == 0)
769 /* unset no_console_output flag, since the console is free */
770 m->no_console_output = false;
774 if (old_state != state)
775 log_unit_debug(UNIT(s)->id, "%s changed %s -> %s", UNIT(s)->id, service_state_to_string(old_state), service_state_to_string(state));
777 unit_notify(UNIT(s), table[old_state], table[state], s->reload_result == SERVICE_SUCCESS);
778 s->reload_result = SERVICE_SUCCESS;
781 static int service_coldplug(Unit *u) {
782 Service *s = SERVICE(u);
786 assert(s->state == SERVICE_DEAD);
788 if (s->deserialized_state != s->state) {
790 if (IN_SET(s->deserialized_state,
791 SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
793 SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL,
794 SERVICE_STOP_SIGABRT, SERVICE_STOP_POST,
795 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL)) {
799 k = IN_SET(s->deserialized_state, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST, SERVICE_RELOAD) ? s->timeout_start_usec : s->timeout_stop_usec;
801 /* For the start/stop timeouts 0 means off */
803 r = service_arm_timer(s, k);
809 if (s->deserialized_state == SERVICE_AUTO_RESTART) {
811 /* The restart timeouts 0 means immediately */
812 r = service_arm_timer(s, s->restart_usec);
817 if (pid_is_unwaited(s->main_pid) &&
818 ((s->deserialized_state == SERVICE_START && IN_SET(s->type, SERVICE_FORKING, SERVICE_DBUS, SERVICE_ONESHOT, SERVICE_NOTIFY)) ||
819 IN_SET(s->deserialized_state,
820 SERVICE_START, SERVICE_START_POST,
821 SERVICE_RUNNING, SERVICE_RELOAD,
822 SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL,
823 SERVICE_STOP_SIGABRT, SERVICE_STOP_POST,
824 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL))) {
825 r = unit_watch_pid(UNIT(s), s->main_pid);
830 if (pid_is_unwaited(s->control_pid) &&
831 IN_SET(s->deserialized_state,
832 SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
834 SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL,
835 SERVICE_STOP_SIGABRT, SERVICE_STOP_POST,
836 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL)) {
837 r = unit_watch_pid(UNIT(s), s->control_pid);
842 if (!IN_SET(s->deserialized_state, SERVICE_DEAD, SERVICE_FAILED, SERVICE_AUTO_RESTART))
843 unit_watch_all_pids(UNIT(s));
845 if (IN_SET(s->deserialized_state, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD))
846 service_start_watchdog(s);
848 service_set_state(s, s->deserialized_state);
854 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
855 _cleanup_free_ int *rfds = NULL;
865 if (s->socket_fd >= 0)
868 SET_FOREACH(u, UNIT(s)->dependencies[UNIT_TRIGGERED_BY], i) {
873 if (u->type != UNIT_SOCKET)
878 r = socket_collect_fds(sock, &cfds, &cn_fds);
893 t = realloc(rfds, (rn_fds + cn_fds) * sizeof(int));
899 memcpy(t + rn_fds, cfds, cn_fds * sizeof(int));
908 if (s->n_fd_store > 0) {
912 t = realloc(rfds, (rn_fds + s->n_fd_store) * sizeof(int));
917 LIST_FOREACH(fd_store, fs, s->fd_store)
918 rfds[rn_fds++] = fs->fd;
928 static int service_spawn(
933 bool apply_permissions,
935 bool apply_tty_stdin,
942 _cleanup_free_ int *fdsbuf = NULL;
943 unsigned n_fds = 0, n_env = 0;
944 _cleanup_free_ char *bus_endpoint_path = NULL;
945 _cleanup_strv_free_ char
946 **argv = NULL, **final_env = NULL, **our_env = NULL;
948 ExecParameters exec_params = {
949 .apply_permissions = apply_permissions,
950 .apply_chroot = apply_chroot,
951 .apply_tty_stdin = apply_tty_stdin,
952 .bus_endpoint_fd = -1,
953 .selinux_context_net = s->socket_fd_selinux_context_net
960 unit_realize_cgroup(UNIT(s));
962 r = unit_setup_exec_runtime(UNIT(s));
967 s->exec_context.std_input == EXEC_INPUT_SOCKET ||
968 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
969 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
971 if (s->socket_fd >= 0) {
975 r = service_collect_fds(s, &fdsbuf, &n_fds);
984 r = service_arm_timer(s, timeout);
988 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
990 r = unit_full_printf_strv(UNIT(s), c->argv, &argv);
994 our_env = new0(char*, 4);
1000 if (is_control ? s->notify_access == NOTIFY_ALL : s->notify_access != NOTIFY_NONE)
1001 if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=%s", UNIT(s)->manager->notify_socket) < 0) {
1006 if (s->main_pid > 0)
1007 if (asprintf(our_env + n_env++, "MAINPID="PID_FMT, s->main_pid) < 0) {
1012 if (UNIT(s)->manager->running_as != SYSTEMD_SYSTEM)
1013 if (asprintf(our_env + n_env++, "MANAGERPID="PID_FMT, getpid()) < 0) {
1018 final_env = strv_env_merge(2, UNIT(s)->manager->environment, our_env, NULL);
1024 if (is_control && UNIT(s)->cgroup_path) {
1025 path = strappenda(UNIT(s)->cgroup_path, "/control");
1026 cg_create(SYSTEMD_CGROUP_CONTROLLER, path);
1028 path = UNIT(s)->cgroup_path;
1031 if (s->exec_context.bus_endpoint) {
1032 r = bus_kernel_create_endpoint(UNIT(s)->manager->running_as == SYSTEMD_SYSTEM ? "system" : "user",
1033 UNIT(s)->id, &bus_endpoint_path);
1037 /* Pass the fd to the exec_params so that the child process can upload the policy.
1038 * Keep a reference to the fd in the service, so the endpoint is kept alive as long
1039 * as the service is running. */
1040 exec_params.bus_endpoint_fd = s->bus_endpoint_fd = r;
1044 exec_params.argv = argv;
1045 exec_params.fds = fds;
1046 exec_params.n_fds = n_fds;
1047 exec_params.environment = final_env;
1048 exec_params.confirm_spawn = UNIT(s)->manager->confirm_spawn;
1049 exec_params.cgroup_supported = UNIT(s)->manager->cgroup_supported;
1050 exec_params.cgroup_path = path;
1051 exec_params.cgroup_delegate = s->cgroup_context.delegate;
1052 exec_params.runtime_prefix = manager_get_runtime_prefix(UNIT(s)->manager);
1053 exec_params.unit_id = UNIT(s)->id;
1054 exec_params.watchdog_usec = s->watchdog_usec;
1055 exec_params.bus_endpoint_path = bus_endpoint_path;
1056 if (s->type == SERVICE_IDLE)
1057 exec_params.idle_pipe = UNIT(s)->manager->idle_pipe;
1067 r = unit_watch_pid(UNIT(s), pid);
1069 /* FIXME: we need to do something here */
1078 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
1083 static int main_pid_good(Service *s) {
1086 /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1089 /* If we know the pid file, then lets just check if it is
1091 if (s->main_pid_known) {
1093 /* If it's an alien child let's check if it is still
1095 if (s->main_pid_alien && s->main_pid > 0)
1096 return pid_is_alive(s->main_pid);
1098 /* .. otherwise assume we'll get a SIGCHLD for it,
1099 * which we really should wait for to collect exit
1100 * status and code */
1101 return s->main_pid > 0;
1104 /* We don't know the pid */
1108 _pure_ static int control_pid_good(Service *s) {
1111 return s->control_pid > 0;
1114 static int cgroup_good(Service *s) {
1119 if (!UNIT(s)->cgroup_path)
1122 r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, UNIT(s)->cgroup_path, true);
1129 static void service_enter_dead(Service *s, ServiceResult f, bool allow_restart) {
1133 if (f != SERVICE_SUCCESS)
1136 service_set_state(s, s->result != SERVICE_SUCCESS ? SERVICE_FAILED : SERVICE_DEAD);
1138 if (s->result != SERVICE_SUCCESS) {
1139 log_unit_warning(UNIT(s)->id, "%s failed.", UNIT(s)->id);
1140 failure_action(UNIT(s)->manager, s->failure_action, s->reboot_arg);
1143 if (allow_restart &&
1144 !s->forbid_restart &&
1145 (s->restart == SERVICE_RESTART_ALWAYS ||
1146 (s->restart == SERVICE_RESTART_ON_SUCCESS && s->result == SERVICE_SUCCESS) ||
1147 (s->restart == SERVICE_RESTART_ON_FAILURE && s->result != SERVICE_SUCCESS) ||
1148 (s->restart == SERVICE_RESTART_ON_ABNORMAL && !IN_SET(s->result, SERVICE_SUCCESS, SERVICE_FAILURE_EXIT_CODE)) ||
1149 (s->restart == SERVICE_RESTART_ON_WATCHDOG && s->result == SERVICE_FAILURE_WATCHDOG) ||
1150 (s->restart == SERVICE_RESTART_ON_ABORT && IN_SET(s->result, SERVICE_FAILURE_SIGNAL, SERVICE_FAILURE_CORE_DUMP)) ||
1151 (s->main_exec_status.code == CLD_EXITED && set_contains(s->restart_force_status.status, INT_TO_PTR(s->main_exec_status.status))) ||
1152 (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)))) &&
1153 (s->main_exec_status.code != CLD_EXITED || !set_contains(s->restart_prevent_status.status, INT_TO_PTR(s->main_exec_status.status))) &&
1154 (!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)))) {
1156 r = service_arm_timer(s, s->restart_usec);
1160 service_set_state(s, SERVICE_AUTO_RESTART);
1163 s->forbid_restart = false;
1165 /* We want fresh tmpdirs in case service is started again immediately */
1166 exec_runtime_destroy(s->exec_runtime);
1167 s->exec_runtime = exec_runtime_unref(s->exec_runtime);
1169 /* Also, remove the runtime directory in */
1170 exec_context_destroy_runtime_directory(&s->exec_context, manager_get_runtime_prefix(UNIT(s)->manager));
1172 /* Try to delete the pid file. At this point it will be
1173 * out-of-date, and some software might be confused by it, so
1174 * let's remove it. */
1176 unlink_noerrno(s->pid_file);
1181 log_unit_warning_errno(UNIT(s)->id, r, "%s failed to run install restart timer: %m", UNIT(s)->id);
1182 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, false);
1185 static void service_enter_stop_post(Service *s, ServiceResult f) {
1189 if (f != SERVICE_SUCCESS)
1192 service_unwatch_control_pid(s);
1193 unit_watch_all_pids(UNIT(s));
1195 s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST];
1196 if (s->control_command) {
1197 s->control_command_id = SERVICE_EXEC_STOP_POST;
1199 r = service_spawn(s,
1201 s->timeout_stop_usec,
1203 !s->permissions_start_only,
1204 !s->root_directory_start_only,
1211 service_set_state(s, SERVICE_STOP_POST);
1213 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_SUCCESS);
1218 log_unit_warning_errno(UNIT(s)->id, r, "%s failed to run 'stop-post' task: %m", UNIT(s)->id);
1219 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
1222 static void service_enter_signal(Service *s, ServiceState state, ServiceResult f) {
1227 if (f != SERVICE_SUCCESS)
1230 unit_watch_all_pids(UNIT(s));
1232 r = unit_kill_context(
1235 (state != SERVICE_STOP_SIGTERM && state != SERVICE_FINAL_SIGTERM && state != SERVICE_STOP_SIGABRT) ?
1236 KILL_KILL : (state == SERVICE_STOP_SIGABRT ? KILL_ABORT : KILL_TERMINATE),
1245 if (s->timeout_stop_usec > 0) {
1246 r = service_arm_timer(s, s->timeout_stop_usec);
1251 service_set_state(s, state);
1252 } else if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGABRT)
1253 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_SUCCESS);
1254 else if (state == SERVICE_STOP_SIGKILL)
1255 service_enter_stop_post(s, SERVICE_SUCCESS);
1256 else if (state == SERVICE_FINAL_SIGTERM)
1257 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_SUCCESS);
1259 service_enter_dead(s, SERVICE_SUCCESS, true);
1264 log_unit_warning_errno(UNIT(s)->id, r, "%s failed to kill processes: %m", UNIT(s)->id);
1266 if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL ||
1267 state == SERVICE_STOP_SIGABRT)
1268 service_enter_stop_post(s, SERVICE_FAILURE_RESOURCES);
1270 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
1273 static void service_enter_stop_by_notify(Service *s) {
1276 unit_watch_all_pids(UNIT(s));
1278 if (s->timeout_stop_usec > 0)
1279 service_arm_timer(s, s->timeout_stop_usec);
1281 /* The service told us it's stopping, so it's as if we SIGTERM'd it. */
1282 service_set_state(s, SERVICE_STOP_SIGTERM);
1285 static void service_enter_stop(Service *s, ServiceResult f) {
1290 if (f != SERVICE_SUCCESS)
1293 service_unwatch_control_pid(s);
1294 unit_watch_all_pids(UNIT(s));
1296 s->control_command = s->exec_command[SERVICE_EXEC_STOP];
1297 if (s->control_command) {
1298 s->control_command_id = SERVICE_EXEC_STOP;
1300 r = service_spawn(s,
1302 s->timeout_stop_usec,
1304 !s->permissions_start_only,
1305 !s->root_directory_start_only,
1312 service_set_state(s, SERVICE_STOP);
1314 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
1319 log_unit_warning_errno(UNIT(s)->id, r, "%s failed to run 'stop' task: %m", UNIT(s)->id);
1320 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
1323 static void service_enter_running(Service *s, ServiceResult f) {
1324 int main_pid_ok, cgroup_ok;
1327 if (f != SERVICE_SUCCESS)
1330 main_pid_ok = main_pid_good(s);
1331 cgroup_ok = cgroup_good(s);
1333 if ((main_pid_ok > 0 || (main_pid_ok < 0 && cgroup_ok != 0)) &&
1334 (s->bus_name_good || s->type != SERVICE_DBUS)) {
1336 /* If there are any queued up sd_notify()
1337 * notifications, process them now */
1338 if (s->notify_state == NOTIFY_RELOADING)
1339 service_enter_reload_by_notify(s);
1340 else if (s->notify_state == NOTIFY_STOPPING)
1341 service_enter_stop_by_notify(s);
1343 service_set_state(s, SERVICE_RUNNING);
1345 } else if (s->remain_after_exit)
1346 service_set_state(s, SERVICE_EXITED);
1348 service_enter_stop(s, SERVICE_SUCCESS);
1351 static void service_enter_start_post(Service *s) {
1355 service_unwatch_control_pid(s);
1356 service_reset_watchdog(s);
1358 s->control_command = s->exec_command[SERVICE_EXEC_START_POST];
1359 if (s->control_command) {
1360 s->control_command_id = SERVICE_EXEC_START_POST;
1362 r = service_spawn(s,
1364 s->timeout_start_usec,
1366 !s->permissions_start_only,
1367 !s->root_directory_start_only,
1374 service_set_state(s, SERVICE_START_POST);
1376 service_enter_running(s, SERVICE_SUCCESS);
1381 log_unit_warning_errno(UNIT(s)->id, r, "%s failed to run 'start-post' task: %m", UNIT(s)->id);
1382 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
1385 static void service_kill_control_processes(Service *s) {
1388 if (!UNIT(s)->cgroup_path)
1391 p = strappenda(UNIT(s)->cgroup_path, "/control");
1392 cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, p, SIGKILL, true, true, true, NULL);
1395 static void service_enter_start(Service *s) {
1402 service_unwatch_control_pid(s);
1403 service_unwatch_main_pid(s);
1405 /* We want to ensure that nobody leaks processes from
1406 * START_PRE here, so let's go on a killing spree, People
1407 * should not spawn long running processes from START_PRE. */
1408 service_kill_control_processes(s);
1410 if (s->type == SERVICE_FORKING) {
1411 s->control_command_id = SERVICE_EXEC_START;
1412 c = s->control_command = s->exec_command[SERVICE_EXEC_START];
1414 s->main_command = NULL;
1416 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1417 s->control_command = NULL;
1419 c = s->main_command = s->exec_command[SERVICE_EXEC_START];
1423 assert(s->type == SERVICE_ONESHOT);
1424 service_enter_start_post(s);
1428 r = service_spawn(s,
1430 IN_SET(s->type, SERVICE_FORKING, SERVICE_DBUS, SERVICE_NOTIFY, SERVICE_ONESHOT) ? s->timeout_start_usec : 0,
1440 if (s->type == SERVICE_SIMPLE || s->type == SERVICE_IDLE) {
1441 /* For simple services we immediately start
1442 * the START_POST binaries. */
1444 service_set_main_pid(s, pid);
1445 service_enter_start_post(s);
1447 } else if (s->type == SERVICE_FORKING) {
1449 /* For forking services we wait until the start
1450 * process exited. */
1452 s->control_pid = pid;
1453 service_set_state(s, SERVICE_START);
1455 } else if (s->type == SERVICE_ONESHOT ||
1456 s->type == SERVICE_DBUS ||
1457 s->type == SERVICE_NOTIFY) {
1459 /* For oneshot services we wait until the start
1460 * process exited, too, but it is our main process. */
1462 /* For D-Bus services we know the main pid right away,
1463 * but wait for the bus name to appear on the
1464 * bus. Notify services are similar. */
1466 service_set_main_pid(s, pid);
1467 service_set_state(s, SERVICE_START);
1469 assert_not_reached("Unknown service type");
1474 log_unit_warning_errno(UNIT(s)->id, r, "%s failed to run 'start' task: %m", UNIT(s)->id);
1475 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
1478 static void service_enter_start_pre(Service *s) {
1483 service_unwatch_control_pid(s);
1485 s->control_command = s->exec_command[SERVICE_EXEC_START_PRE];
1486 if (s->control_command) {
1487 /* Before we start anything, let's clear up what might
1488 * be left from previous runs. */
1489 service_kill_control_processes(s);
1491 s->control_command_id = SERVICE_EXEC_START_PRE;
1493 r = service_spawn(s,
1495 s->timeout_start_usec,
1497 !s->permissions_start_only,
1498 !s->root_directory_start_only,
1505 service_set_state(s, SERVICE_START_PRE);
1507 service_enter_start(s);
1512 log_unit_warning_errno(UNIT(s)->id, r, "%s failed to run 'start-pre' task: %m", UNIT(s)->id);
1513 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
1516 static void service_enter_restart(Service *s) {
1517 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
1522 if (UNIT(s)->job && UNIT(s)->job->type == JOB_STOP) {
1523 /* Don't restart things if we are going down anyway */
1524 log_unit_info(UNIT(s)->id, "Stop job pending for unit, delaying automatic restart.");
1526 r = service_arm_timer(s, s->restart_usec);
1533 /* Any units that are bound to this service must also be
1534 * restarted. We use JOB_RESTART (instead of the more obvious
1535 * JOB_START) here so that those dependency jobs will be added
1537 r = manager_add_job(UNIT(s)->manager, JOB_RESTART, UNIT(s), JOB_FAIL, false, &error, NULL);
1541 /* Note that we stay in the SERVICE_AUTO_RESTART state here,
1542 * it will be canceled as part of the service_stop() call that
1543 * is executed as part of JOB_RESTART. */
1545 log_unit_debug(UNIT(s)->id, "%s scheduled restart job.", UNIT(s)->id);
1549 log_unit_warning(UNIT(s)->id, "%s failed to schedule restart job: %s", UNIT(s)->id, bus_error_message(&error, -r));
1550 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, false);
1553 static void service_enter_reload_by_notify(Service *s) {
1556 if (s->timeout_start_usec > 0)
1557 service_arm_timer(s, s->timeout_start_usec);
1559 service_set_state(s, SERVICE_RELOAD);
1562 static void service_enter_reload(Service *s) {
1567 service_unwatch_control_pid(s);
1569 s->control_command = s->exec_command[SERVICE_EXEC_RELOAD];
1570 if (s->control_command) {
1571 s->control_command_id = SERVICE_EXEC_RELOAD;
1573 r = service_spawn(s,
1575 s->timeout_start_usec,
1577 !s->permissions_start_only,
1578 !s->root_directory_start_only,
1585 service_set_state(s, SERVICE_RELOAD);
1587 service_enter_running(s, SERVICE_SUCCESS);
1592 log_unit_warning_errno(UNIT(s)->id, r, "%s failed to run 'reload' task: %m", UNIT(s)->id);
1593 s->reload_result = SERVICE_FAILURE_RESOURCES;
1594 service_enter_running(s, SERVICE_SUCCESS);
1597 static void service_run_next_control(Service *s) {
1601 assert(s->control_command);
1602 assert(s->control_command->command_next);
1604 assert(s->control_command_id != SERVICE_EXEC_START);
1606 s->control_command = s->control_command->command_next;
1607 service_unwatch_control_pid(s);
1609 r = service_spawn(s,
1611 IN_SET(s->state, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD) ? s->timeout_start_usec : s->timeout_stop_usec,
1613 !s->permissions_start_only,
1614 !s->root_directory_start_only,
1615 s->control_command_id == SERVICE_EXEC_START_PRE ||
1616 s->control_command_id == SERVICE_EXEC_STOP_POST,
1625 log_unit_warning_errno(UNIT(s)->id, r, "%s failed to run next control task: %m", UNIT(s)->id);
1627 if (s->state == SERVICE_START_PRE)
1628 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
1629 else if (s->state == SERVICE_STOP)
1630 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
1631 else if (s->state == SERVICE_STOP_POST)
1632 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
1633 else if (s->state == SERVICE_RELOAD) {
1634 s->reload_result = SERVICE_FAILURE_RESOURCES;
1635 service_enter_running(s, SERVICE_SUCCESS);
1637 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
1640 static void service_run_next_main(Service *s) {
1645 assert(s->main_command);
1646 assert(s->main_command->command_next);
1647 assert(s->type == SERVICE_ONESHOT);
1649 s->main_command = s->main_command->command_next;
1650 service_unwatch_main_pid(s);
1652 r = service_spawn(s,
1654 s->timeout_start_usec,
1664 service_set_main_pid(s, pid);
1669 log_unit_warning_errno(UNIT(s)->id, r, "%s failed to run next main task: %m", UNIT(s)->id);
1670 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
1673 static int service_start_limit_test(Service *s) {
1676 if (ratelimit_test(&s->start_limit))
1679 log_unit_warning(UNIT(s)->id, "start request repeated too quickly for %s", UNIT(s)->id);
1681 return failure_action(UNIT(s)->manager, s->start_limit_action, s->reboot_arg);
1684 static int service_start(Unit *u) {
1685 Service *s = SERVICE(u);
1690 /* We cannot fulfill this request right now, try again later
1692 if (s->state == SERVICE_STOP ||
1693 s->state == SERVICE_STOP_SIGABRT ||
1694 s->state == SERVICE_STOP_SIGTERM ||
1695 s->state == SERVICE_STOP_SIGKILL ||
1696 s->state == SERVICE_STOP_POST ||
1697 s->state == SERVICE_FINAL_SIGTERM ||
1698 s->state == SERVICE_FINAL_SIGKILL)
1701 /* Already on it! */
1702 if (s->state == SERVICE_START_PRE ||
1703 s->state == SERVICE_START ||
1704 s->state == SERVICE_START_POST)
1707 /* A service that will be restarted must be stopped first to
1708 * trigger BindsTo and/or OnFailure dependencies. If a user
1709 * does not want to wait for the holdoff time to elapse, the
1710 * service should be manually restarted, not started. We
1711 * simply return EAGAIN here, so that any start jobs stay
1712 * queued, and assume that the auto restart timer will
1713 * eventually trigger the restart. */
1714 if (s->state == SERVICE_AUTO_RESTART)
1717 assert(s->state == SERVICE_DEAD || s->state == SERVICE_FAILED);
1719 /* Make sure we don't enter a busy loop of some kind. */
1720 r = service_start_limit_test(s);
1722 service_enter_dead(s, SERVICE_FAILURE_START_LIMIT, false);
1726 s->result = SERVICE_SUCCESS;
1727 s->reload_result = SERVICE_SUCCESS;
1728 s->main_pid_known = false;
1729 s->main_pid_alien = false;
1730 s->forbid_restart = false;
1732 free(s->status_text);
1733 s->status_text = NULL;
1734 s->status_errno = 0;
1736 s->notify_state = NOTIFY_UNKNOWN;
1738 service_enter_start_pre(s);
1742 static int service_stop(Unit *u) {
1743 Service *s = SERVICE(u);
1747 /* Don't create restart jobs from here. */
1748 s->forbid_restart = true;
1751 if (s->state == SERVICE_STOP ||
1752 s->state == SERVICE_STOP_SIGABRT ||
1753 s->state == SERVICE_STOP_SIGTERM ||
1754 s->state == SERVICE_STOP_SIGKILL ||
1755 s->state == SERVICE_STOP_POST ||
1756 s->state == SERVICE_FINAL_SIGTERM ||
1757 s->state == SERVICE_FINAL_SIGKILL)
1760 /* A restart will be scheduled or is in progress. */
1761 if (s->state == SERVICE_AUTO_RESTART) {
1762 service_set_state(s, SERVICE_DEAD);
1766 /* If there's already something running we go directly into
1768 if (s->state == SERVICE_START_PRE ||
1769 s->state == SERVICE_START ||
1770 s->state == SERVICE_START_POST ||
1771 s->state == SERVICE_RELOAD) {
1772 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
1776 assert(s->state == SERVICE_RUNNING ||
1777 s->state == SERVICE_EXITED);
1779 service_enter_stop(s, SERVICE_SUCCESS);
1783 static int service_reload(Unit *u) {
1784 Service *s = SERVICE(u);
1788 assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
1790 service_enter_reload(s);
1794 _pure_ static bool service_can_reload(Unit *u) {
1795 Service *s = SERVICE(u);
1799 return !!s->exec_command[SERVICE_EXEC_RELOAD];
1802 static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
1803 Service *s = SERVICE(u);
1809 unit_serialize_item(u, f, "state", service_state_to_string(s->state));
1810 unit_serialize_item(u, f, "result", service_result_to_string(s->result));
1811 unit_serialize_item(u, f, "reload-result", service_result_to_string(s->reload_result));
1813 if (s->control_pid > 0)
1814 unit_serialize_item_format(u, f, "control-pid", PID_FMT,
1817 if (s->main_pid_known && s->main_pid > 0)
1818 unit_serialize_item_format(u, f, "main-pid", PID_FMT, s->main_pid);
1820 unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
1823 unit_serialize_item(u, f, "status-text", s->status_text);
1825 /* FIXME: There's a minor uncleanliness here: if there are
1826 * multiple commands attached here, we will start from the
1827 * first one again */
1828 if (s->control_command_id >= 0)
1829 unit_serialize_item(u, f, "control-command",
1830 service_exec_command_to_string(s->control_command_id));
1832 if (s->socket_fd >= 0) {
1835 if ((copy = fdset_put_dup(fds, s->socket_fd)) < 0)
1838 unit_serialize_item_format(u, f, "socket-fd", "%i", copy);
1841 if (s->bus_endpoint_fd >= 0) {
1844 if ((copy = fdset_put_dup(fds, s->bus_endpoint_fd)) < 0)
1847 unit_serialize_item_format(u, f, "endpoint-fd", "%i", copy);
1850 if (s->main_exec_status.pid > 0) {
1851 unit_serialize_item_format(u, f, "main-exec-status-pid", PID_FMT,
1852 s->main_exec_status.pid);
1853 dual_timestamp_serialize(f, "main-exec-status-start",
1854 &s->main_exec_status.start_timestamp);
1855 dual_timestamp_serialize(f, "main-exec-status-exit",
1856 &s->main_exec_status.exit_timestamp);
1858 if (dual_timestamp_is_set(&s->main_exec_status.exit_timestamp)) {
1859 unit_serialize_item_format(u, f, "main-exec-status-code", "%i",
1860 s->main_exec_status.code);
1861 unit_serialize_item_format(u, f, "main-exec-status-status", "%i",
1862 s->main_exec_status.status);
1865 if (dual_timestamp_is_set(&s->watchdog_timestamp))
1866 dual_timestamp_serialize(f, "watchdog-timestamp", &s->watchdog_timestamp);
1868 if (s->forbid_restart)
1869 unit_serialize_item(u, f, "forbid-restart", yes_no(s->forbid_restart));
1874 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
1875 Service *s = SERVICE(u);
1882 if (streq(key, "state")) {
1885 state = service_state_from_string(value);
1887 log_unit_debug(u->id, "Failed to parse state value %s", value);
1889 s->deserialized_state = state;
1890 } else if (streq(key, "result")) {
1893 f = service_result_from_string(value);
1895 log_unit_debug(u->id, "Failed to parse result value %s", value);
1896 else if (f != SERVICE_SUCCESS)
1899 } else if (streq(key, "reload-result")) {
1902 f = service_result_from_string(value);
1904 log_unit_debug(u->id, "Failed to parse reload result value %s", value);
1905 else if (f != SERVICE_SUCCESS)
1906 s->reload_result = f;
1908 } else if (streq(key, "control-pid")) {
1911 if (parse_pid(value, &pid) < 0)
1912 log_unit_debug(u->id, "Failed to parse control-pid value %s", value);
1914 s->control_pid = pid;
1915 } else if (streq(key, "main-pid")) {
1918 if (parse_pid(value, &pid) < 0)
1919 log_unit_debug(u->id, "Failed to parse main-pid value %s", value);
1921 service_set_main_pid(s, pid);
1922 unit_watch_pid(UNIT(s), pid);
1924 } else if (streq(key, "main-pid-known")) {
1927 b = parse_boolean(value);
1929 log_unit_debug(u->id, "Failed to parse main-pid-known value %s", value);
1931 s->main_pid_known = b;
1932 } else if (streq(key, "status-text")) {
1939 free(s->status_text);
1943 } else if (streq(key, "control-command")) {
1944 ServiceExecCommand id;
1946 id = service_exec_command_from_string(value);
1948 log_unit_debug(u->id, "Failed to parse exec-command value %s", value);
1950 s->control_command_id = id;
1951 s->control_command = s->exec_command[id];
1953 } else if (streq(key, "socket-fd")) {
1956 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
1957 log_unit_debug(u->id, "Failed to parse socket-fd value %s", value);
1959 asynchronous_close(s->socket_fd);
1960 s->socket_fd = fdset_remove(fds, fd);
1962 } else if (streq(key, "endpoint-fd")) {
1965 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
1966 log_unit_debug(u->id, "Failed to parse endpoint-fd value %s", value);
1968 safe_close(s->bus_endpoint_fd);
1969 s->bus_endpoint_fd = fdset_remove(fds, fd);
1971 } else if (streq(key, "main-exec-status-pid")) {
1974 if (parse_pid(value, &pid) < 0)
1975 log_unit_debug(u->id, "Failed to parse main-exec-status-pid value %s", value);
1977 s->main_exec_status.pid = pid;
1978 } else if (streq(key, "main-exec-status-code")) {
1981 if (safe_atoi(value, &i) < 0)
1982 log_unit_debug(u->id, "Failed to parse main-exec-status-code value %s", value);
1984 s->main_exec_status.code = i;
1985 } else if (streq(key, "main-exec-status-status")) {
1988 if (safe_atoi(value, &i) < 0)
1989 log_unit_debug(u->id, "Failed to parse main-exec-status-status value %s", value);
1991 s->main_exec_status.status = i;
1992 } else if (streq(key, "main-exec-status-start"))
1993 dual_timestamp_deserialize(value, &s->main_exec_status.start_timestamp);
1994 else if (streq(key, "main-exec-status-exit"))
1995 dual_timestamp_deserialize(value, &s->main_exec_status.exit_timestamp);
1996 else if (streq(key, "watchdog-timestamp"))
1997 dual_timestamp_deserialize(value, &s->watchdog_timestamp);
1998 else if (streq(key, "forbid-restart")) {
2001 b = parse_boolean(value);
2003 log_unit_debug(u->id, "Failed to parse forbid-restart value %s", value);
2005 s->forbid_restart = b;
2007 log_unit_debug(u->id, "Unknown serialization key '%s'", key);
2012 _pure_ static UnitActiveState service_active_state(Unit *u) {
2013 const UnitActiveState *table;
2017 table = SERVICE(u)->type == SERVICE_IDLE ? state_translation_table_idle : state_translation_table;
2019 return table[SERVICE(u)->state];
2022 static const char *service_sub_state_to_string(Unit *u) {
2025 return service_state_to_string(SERVICE(u)->state);
2028 static bool service_check_gc(Unit *u) {
2029 Service *s = SERVICE(u);
2033 /* Never clean up services that still have a process around,
2034 * even if the service is formally dead. */
2035 if (cgroup_good(s) > 0 ||
2036 main_pid_good(s) > 0 ||
2037 control_pid_good(s) > 0)
2043 _pure_ static bool service_check_snapshot(Unit *u) {
2044 Service *s = SERVICE(u);
2048 return s->socket_fd < 0;
2051 static int service_retry_pid_file(Service *s) {
2054 assert(s->pid_file);
2055 assert(s->state == SERVICE_START || s->state == SERVICE_START_POST);
2057 r = service_load_pid_file(s, false);
2061 service_unwatch_pid_file(s);
2063 service_enter_running(s, SERVICE_SUCCESS);
2067 static int service_watch_pid_file(Service *s) {
2070 log_unit_debug(UNIT(s)->id, "Setting watch for %s's PID file %s", UNIT(s)->id, s->pid_file_pathspec->path);
2072 r = path_spec_watch(s->pid_file_pathspec, service_dispatch_io);
2076 /* the pidfile might have appeared just before we set the watch */
2077 log_unit_debug(UNIT(s)->id, "Trying to read %s's PID file %s in case it changed", UNIT(s)->id, s->pid_file_pathspec->path);
2078 service_retry_pid_file(s);
2082 log_unit_error_errno(UNIT(s)->id, r, "Failed to set a watch for %s's PID file %s: %m", UNIT(s)->id, s->pid_file_pathspec->path);
2083 service_unwatch_pid_file(s);
2087 static int service_demand_pid_file(Service *s) {
2090 assert(s->pid_file);
2091 assert(!s->pid_file_pathspec);
2093 ps = new0(PathSpec, 1);
2098 ps->path = strdup(s->pid_file);
2104 path_kill_slashes(ps->path);
2106 /* PATH_CHANGED would not be enough. There are daemons (sendmail) that
2107 * keep their PID file open all the time. */
2108 ps->type = PATH_MODIFIED;
2109 ps->inotify_fd = -1;
2111 s->pid_file_pathspec = ps;
2113 return service_watch_pid_file(s);
2116 static int service_dispatch_io(sd_event_source *source, int fd, uint32_t events, void *userdata) {
2117 PathSpec *p = userdata;
2122 s = SERVICE(p->unit);
2126 assert(s->state == SERVICE_START || s->state == SERVICE_START_POST);
2127 assert(s->pid_file_pathspec);
2128 assert(path_spec_owns_inotify_fd(s->pid_file_pathspec, fd));
2130 log_unit_debug(UNIT(s)->id, "inotify event for %s", UNIT(s)->id);
2132 if (path_spec_fd_event(p, events) < 0)
2135 if (service_retry_pid_file(s) == 0)
2138 if (service_watch_pid_file(s) < 0)
2144 service_unwatch_pid_file(s);
2145 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
2149 static void service_notify_cgroup_empty_event(Unit *u) {
2150 Service *s = SERVICE(u);
2154 log_unit_debug(u->id, "%s: cgroup is empty", u->id);
2158 /* Waiting for SIGCHLD is usually more interesting,
2159 * because it includes return codes/signals. Which is
2160 * why we ignore the cgroup events for most cases,
2161 * except when we don't know pid which to expect the
2165 case SERVICE_START_POST:
2166 /* If we were hoping for the daemon to write its PID file,
2167 * we can give up now. */
2168 if (s->pid_file_pathspec) {
2169 log_unit_warning(u->id, "%s never wrote its PID file. Failing.", UNIT(s)->id);
2171 service_unwatch_pid_file(s);
2172 if (s->state == SERVICE_START)
2173 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
2175 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2179 case SERVICE_RUNNING:
2180 /* service_enter_running() will figure out what to do */
2181 service_enter_running(s, SERVICE_SUCCESS);
2184 case SERVICE_STOP_SIGABRT:
2185 case SERVICE_STOP_SIGTERM:
2186 case SERVICE_STOP_SIGKILL:
2188 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2189 service_enter_stop_post(s, SERVICE_SUCCESS);
2193 case SERVICE_STOP_POST:
2194 case SERVICE_FINAL_SIGTERM:
2195 case SERVICE_FINAL_SIGKILL:
2196 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2197 service_enter_dead(s, SERVICE_SUCCESS, true);
2206 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2207 Service *s = SERVICE(u);
2213 if (UNIT(s)->fragment_path ? is_clean_exit(code, status, &s->success_status) :
2214 is_clean_exit_lsb(code, status, &s->success_status))
2215 f = SERVICE_SUCCESS;
2216 else if (code == CLD_EXITED)
2217 f = SERVICE_FAILURE_EXIT_CODE;
2218 else if (code == CLD_KILLED)
2219 f = SERVICE_FAILURE_SIGNAL;
2220 else if (code == CLD_DUMPED)
2221 f = SERVICE_FAILURE_CORE_DUMP;
2223 assert_not_reached("Unknown code");
2225 if (s->main_pid == pid) {
2226 /* Forking services may occasionally move to a new PID.
2227 * As long as they update the PID file before exiting the old
2228 * PID, they're fine. */
2229 if (service_load_pid_file(s, false) == 0)
2233 exec_status_exit(&s->main_exec_status, &s->exec_context, pid, code, status);
2235 if (s->main_command) {
2236 /* If this is not a forking service than the
2237 * main process got started and hence we copy
2238 * the exit status so that it is recorded both
2239 * as main and as control process exit
2242 s->main_command->exec_status = s->main_exec_status;
2244 if (s->main_command->ignore)
2245 f = SERVICE_SUCCESS;
2246 } else if (s->exec_command[SERVICE_EXEC_START]) {
2248 /* If this is a forked process, then we should
2249 * ignore the return value if this was
2250 * configured for the starter process */
2252 if (s->exec_command[SERVICE_EXEC_START]->ignore)
2253 f = SERVICE_SUCCESS;
2256 log_unit_struct(u->id,
2257 f == SERVICE_SUCCESS ? LOG_DEBUG : LOG_NOTICE,
2258 LOG_MESSAGE("%s: main process exited, code=%s, status=%i/%s",
2259 u->id, sigchld_code_to_string(code), status,
2260 strna(code == CLD_EXITED
2261 ? exit_status_to_string(status, EXIT_STATUS_FULL)
2262 : signal_to_string(status))),
2263 "EXIT_CODE=%s", sigchld_code_to_string(code),
2264 "EXIT_STATUS=%i", status,
2267 if (f != SERVICE_SUCCESS)
2270 if (s->main_command &&
2271 s->main_command->command_next &&
2272 f == SERVICE_SUCCESS) {
2274 /* There is another command to *
2275 * execute, so let's do that. */
2277 log_unit_debug(u->id, "%s running next main command for state %s", u->id, service_state_to_string(s->state));
2278 service_run_next_main(s);
2282 /* The service exited, so the service is officially
2284 s->main_command = NULL;
2288 case SERVICE_START_POST:
2289 case SERVICE_RELOAD:
2291 /* Need to wait until the operation is
2296 if (s->type == SERVICE_ONESHOT) {
2297 /* This was our main goal, so let's go on */
2298 if (f == SERVICE_SUCCESS)
2299 service_enter_start_post(s);
2301 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
2307 case SERVICE_RUNNING:
2308 service_enter_running(s, f);
2311 case SERVICE_STOP_SIGABRT:
2312 case SERVICE_STOP_SIGTERM:
2313 case SERVICE_STOP_SIGKILL:
2315 if (!control_pid_good(s))
2316 service_enter_stop_post(s, f);
2318 /* If there is still a control process, wait for that first */
2321 case SERVICE_STOP_POST:
2322 case SERVICE_FINAL_SIGTERM:
2323 case SERVICE_FINAL_SIGKILL:
2325 if (!control_pid_good(s))
2326 service_enter_dead(s, f, true);
2330 assert_not_reached("Uh, main process died at wrong time.");
2334 } else if (s->control_pid == pid) {
2337 if (s->control_command) {
2338 exec_status_exit(&s->control_command->exec_status, &s->exec_context, pid, code, status);
2340 if (s->control_command->ignore)
2341 f = SERVICE_SUCCESS;
2344 log_unit_full(u->id,
2345 f == SERVICE_SUCCESS ? LOG_DEBUG : LOG_NOTICE,
2346 "%s: control process exited, code=%s status=%i",
2347 u->id, sigchld_code_to_string(code), status);
2349 if (f != SERVICE_SUCCESS)
2352 /* Immediately get rid of the cgroup, so that the
2353 * kernel doesn't delay the cgroup empty messages for
2354 * the service cgroup any longer than necessary */
2355 service_kill_control_processes(s);
2357 if (s->control_command &&
2358 s->control_command->command_next &&
2359 f == SERVICE_SUCCESS) {
2361 /* There is another command to *
2362 * execute, so let's do that. */
2364 log_unit_debug(u->id, "%s running next control command for state %s", u->id, service_state_to_string(s->state));
2365 service_run_next_control(s);
2368 /* No further commands for this step, so let's
2369 * figure out what to do next */
2371 s->control_command = NULL;
2372 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2374 log_unit_debug(u->id, "%s got final SIGCHLD for state %s", u->id, service_state_to_string(s->state));
2378 case SERVICE_START_PRE:
2379 if (f == SERVICE_SUCCESS)
2380 service_enter_start(s);
2382 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
2386 if (s->type != SERVICE_FORKING)
2387 /* Maybe spurious event due to a reload that changed the type? */
2390 if (f != SERVICE_SUCCESS) {
2391 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
2396 bool has_start_post;
2399 /* Let's try to load the pid file here if we can.
2400 * The PID file might actually be created by a START_POST
2401 * script. In that case don't worry if the loading fails. */
2403 has_start_post = !!s->exec_command[SERVICE_EXEC_START_POST];
2404 r = service_load_pid_file(s, !has_start_post);
2405 if (!has_start_post && r < 0) {
2406 r = service_demand_pid_file(s);
2407 if (r < 0 || !cgroup_good(s))
2408 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
2412 service_search_main_pid(s);
2414 service_enter_start_post(s);
2417 case SERVICE_START_POST:
2418 if (f != SERVICE_SUCCESS) {
2419 service_enter_stop(s, f);
2426 r = service_load_pid_file(s, true);
2428 r = service_demand_pid_file(s);
2429 if (r < 0 || !cgroup_good(s))
2430 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2434 service_search_main_pid(s);
2436 service_enter_running(s, SERVICE_SUCCESS);
2439 case SERVICE_RELOAD:
2440 if (f == SERVICE_SUCCESS) {
2441 service_load_pid_file(s, true);
2442 service_search_main_pid(s);
2445 s->reload_result = f;
2446 service_enter_running(s, SERVICE_SUCCESS);
2450 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
2453 case SERVICE_STOP_SIGABRT:
2454 case SERVICE_STOP_SIGTERM:
2455 case SERVICE_STOP_SIGKILL:
2456 if (main_pid_good(s) <= 0)
2457 service_enter_stop_post(s, f);
2459 /* If there is still a service
2460 * process around, wait until
2461 * that one quit, too */
2464 case SERVICE_STOP_POST:
2465 case SERVICE_FINAL_SIGTERM:
2466 case SERVICE_FINAL_SIGKILL:
2467 if (main_pid_good(s) <= 0)
2468 service_enter_dead(s, f, true);
2472 assert_not_reached("Uh, control process died at wrong time.");
2477 /* Notify clients about changed exit status */
2478 unit_add_to_dbus_queue(u);
2480 /* We got one SIGCHLD for the service, let's watch all
2481 * processes that are now running of the service, and watch
2482 * that. Among the PIDs we then watch will be children
2483 * reassigned to us, which hopefully allows us to identify
2484 * when all children are gone */
2485 unit_tidy_watch_pids(u, s->main_pid, s->control_pid);
2486 unit_watch_all_pids(u);
2488 /* If the PID set is empty now, then let's finish this off */
2489 if (set_isempty(u->pids))
2490 service_notify_cgroup_empty_event(u);
2493 static int service_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata) {
2494 Service *s = SERVICE(userdata);
2497 assert(source == s->timer_event_source);
2501 case SERVICE_START_PRE:
2503 log_unit_warning(UNIT(s)->id, "%s %s operation timed out. Terminating.", UNIT(s)->id, s->state == SERVICE_START ? "start" : "start-pre");
2504 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2507 case SERVICE_START_POST:
2508 log_unit_warning(UNIT(s)->id, "%s start-post operation timed out. Stopping.", UNIT(s)->id);
2509 service_enter_stop(s, SERVICE_FAILURE_TIMEOUT);
2512 case SERVICE_RELOAD:
2513 log_unit_warning(UNIT(s)->id, "%s reload operation timed out. Stopping.", UNIT(s)->id);
2514 s->reload_result = SERVICE_FAILURE_TIMEOUT;
2515 service_enter_running(s, SERVICE_SUCCESS);
2519 log_unit_warning(UNIT(s)->id, "%s stopping timed out. Terminating.", UNIT(s)->id);
2520 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2523 case SERVICE_STOP_SIGABRT:
2524 log_unit_warning(UNIT(s)->id,
2525 "%s stop-sigabrt timed out. Terminating.", UNIT(s)->id);
2526 service_enter_signal(s, SERVICE_STOP_SIGTERM, s->result);
2529 case SERVICE_STOP_SIGTERM:
2530 if (s->kill_context.send_sigkill) {
2531 log_unit_warning(UNIT(s)->id, "%s stop-sigterm timed out. Killing.", UNIT(s)->id);
2532 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_TIMEOUT);
2534 log_unit_warning(UNIT(s)->id, "%s stop-sigterm timed out. Skipping SIGKILL.", UNIT(s)->id);
2535 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
2540 case SERVICE_STOP_SIGKILL:
2541 /* Uh, we sent a SIGKILL and it is still not gone?
2542 * Must be something we cannot kill, so let's just be
2543 * weirded out and continue */
2545 log_unit_warning(UNIT(s)->id, "%s still around after SIGKILL. Ignoring.", UNIT(s)->id);
2546 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
2549 case SERVICE_STOP_POST:
2550 log_unit_warning(UNIT(s)->id, "%s stop-post timed out. Terminating.", UNIT(s)->id);
2551 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2554 case SERVICE_FINAL_SIGTERM:
2555 if (s->kill_context.send_sigkill) {
2556 log_unit_warning(UNIT(s)->id, "%s stop-final-sigterm timed out. Killing.", UNIT(s)->id);
2557 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_FAILURE_TIMEOUT);
2559 log_unit_warning(UNIT(s)->id, "%s stop-final-sigterm timed out. Skipping SIGKILL. Entering failed mode.", UNIT(s)->id);
2560 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, false);
2565 case SERVICE_FINAL_SIGKILL:
2566 log_unit_warning(UNIT(s)->id, "%s still around after final SIGKILL. Entering failed mode.", UNIT(s)->id);
2567 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, true);
2570 case SERVICE_AUTO_RESTART:
2571 log_unit_info(UNIT(s)->id,
2572 s->restart_usec > 0 ?
2573 "%s holdoff time over, scheduling restart." :
2574 "%s has no holdoff time, scheduling restart.",
2576 service_enter_restart(s);
2580 assert_not_reached("Timeout at wrong time.");
2586 static int service_dispatch_watchdog(sd_event_source *source, usec_t usec, void *userdata) {
2587 Service *s = SERVICE(userdata);
2588 char t[FORMAT_TIMESPAN_MAX];
2591 assert(source == s->watchdog_event_source);
2593 log_unit_error(UNIT(s)->id, "%s watchdog timeout (limit %s)!", UNIT(s)->id,
2594 format_timespan(t, sizeof(t), s->watchdog_usec, 1));
2596 service_enter_signal(s, SERVICE_STOP_SIGABRT, SERVICE_FAILURE_WATCHDOG);
2601 static int on_fd_store_io(sd_event_source *e, int fd, uint32_t revents, void *userdata) {
2602 ServiceFDStore *fs = userdata;
2607 /* If we get either EPOLLHUP or EPOLLERR, it's time to remove this entry from the fd store */
2608 service_fd_store_unlink(fs);
2612 static int service_add_fd_set(Service *s, FDSet *fds) {
2617 if (fdset_size(fds) <= 0)
2620 while (s->n_fd_store < s->n_fd_store_max) {
2621 _cleanup_close_ int fd = -1;
2625 fd = fdset_steal_first(fds);
2629 LIST_FOREACH(fd_store, fs, s->fd_store) {
2630 r = same_fd(fs->fd, fd);
2632 return log_unit_error_errno(UNIT(s)->id, r, "%s: Couldn't check if same fd: %m", UNIT(s)->id);
2642 fs = new0(ServiceFDStore, 1);
2649 r = sd_event_add_io(UNIT(s)->manager->event, &fs->event_source, fd, 0, on_fd_store_io, fs);
2652 return log_unit_error_errno(UNIT(s)->id, r, "%s: Failed to add even source: %m", UNIT(s)->id);
2655 LIST_PREPEND(fd_store, s->fd_store, fs);
2660 log_unit_debug(UNIT(s)->id, "%s: added fd to fd store.", UNIT(s)->id);
2663 if (fdset_size(fds) > 0)
2664 log_unit_warning(UNIT(s)->id, "%s: tried to store more fds than FDStoreMax=%u allows, closing remaining.", UNIT(s)->id, s->n_fd_store_max);
2669 static void service_notify_message(Unit *u, pid_t pid, char **tags, FDSet *fds) {
2670 Service *s = SERVICE(u);
2671 _cleanup_free_ char *cc = NULL;
2672 bool notify_dbus = false;
2677 cc = strv_join(tags, ", ");
2678 log_unit_debug(u->id, "%s: Got notification message from PID "PID_FMT" (%s)",
2679 u->id, pid, isempty(cc) ? "n/a" : cc);
2681 if (s->notify_access == NOTIFY_NONE) {
2682 log_unit_warning(u->id, "%s: Got notification message from PID "PID_FMT", but reception is disabled.", u->id, pid);
2686 if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
2687 if (s->main_pid != 0)
2688 log_unit_warning(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);
2690 log_unit_debug(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);
2694 /* Interpret MAINPID= */
2695 e = strv_find_startswith(tags, "MAINPID=");
2696 if (e && IN_SET(s->state, SERVICE_START, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD)) {
2697 if (parse_pid(e, &pid) < 0)
2698 log_unit_warning(u->id, "Failed to parse MAINPID= field in notification message: %s", e);
2700 log_unit_debug(u->id, "%s: got MAINPID=%s", u->id, e);
2702 service_set_main_pid(s, pid);
2703 unit_watch_pid(UNIT(s), pid);
2708 /* Interpret RELOADING= */
2709 if (strv_find(tags, "RELOADING=1")) {
2711 log_unit_debug(u->id, "%s: got RELOADING=1", u->id);
2712 s->notify_state = NOTIFY_RELOADING;
2714 if (s->state == SERVICE_RUNNING)
2715 service_enter_reload_by_notify(s);
2720 /* Interpret READY= */
2721 if (strv_find(tags, "READY=1")) {
2723 log_unit_debug(u->id, "%s: got READY=1", u->id);
2724 s->notify_state = NOTIFY_READY;
2726 /* Type=notify services inform us about completed
2727 * initialization with READY=1 */
2728 if (s->type == SERVICE_NOTIFY && s->state == SERVICE_START)
2729 service_enter_start_post(s);
2731 /* Sending READY=1 while we are reloading informs us
2732 * that the reloading is complete */
2733 if (s->state == SERVICE_RELOAD && s->control_pid == 0)
2734 service_enter_running(s, SERVICE_SUCCESS);
2739 /* Interpret STOPPING= */
2740 if (strv_find(tags, "STOPPING=1")) {
2742 log_unit_debug(u->id, "%s: got STOPPING=1", u->id);
2743 s->notify_state = NOTIFY_STOPPING;
2745 if (s->state == SERVICE_RUNNING)
2746 service_enter_stop_by_notify(s);
2751 /* Interpret STATUS= */
2752 e = strv_find_startswith(tags, "STATUS=");
2754 _cleanup_free_ char *t = NULL;
2757 if (!utf8_is_valid(e))
2758 log_unit_warning(u->id, "Status message in notification is not UTF-8 clean.");
2760 log_unit_debug(u->id, "%s: got STATUS=%s", u->id, e);
2768 if (!streq_ptr(s->status_text, t)) {
2770 free(s->status_text);
2778 /* Interpret ERRNO= */
2779 e = strv_find_startswith(tags, "ERRNO=");
2783 if (safe_atoi(e, &status_errno) < 0 || status_errno < 0)
2784 log_unit_warning(u->id, "Failed to parse ERRNO= field in notification message: %s", e);
2786 log_unit_debug(u->id, "%s: got ERRNO=%s", u->id, e);
2788 if (s->status_errno != status_errno) {
2789 s->status_errno = status_errno;
2795 /* Interpret WATCHDOG= */
2796 if (strv_find(tags, "WATCHDOG=1")) {
2797 log_unit_debug(u->id, "%s: got WATCHDOG=1", u->id);
2798 service_reset_watchdog(s);
2801 /* Add the passed fds to the fd store */
2802 if (strv_find(tags, "FDSTORE=1")) {
2803 log_unit_debug(u->id, "%s: got FDSTORE=1", u->id);
2804 service_add_fd_set(s, fds);
2807 /* Notify clients about changed status or main pid */
2809 unit_add_to_dbus_queue(u);
2812 static int service_get_timeout(Unit *u, uint64_t *timeout) {
2813 Service *s = SERVICE(u);
2816 if (!s->timer_event_source)
2819 r = sd_event_source_get_time(s->timer_event_source, timeout);
2826 static void service_bus_name_owner_change(
2829 const char *old_owner,
2830 const char *new_owner) {
2832 Service *s = SERVICE(u);
2838 assert(streq(s->bus_name, name));
2839 assert(old_owner || new_owner);
2841 if (old_owner && new_owner)
2842 log_unit_debug(u->id, "%s's D-Bus name %s changed owner from %s to %s", u->id, name, old_owner, new_owner);
2844 log_unit_debug(u->id, "%s's D-Bus name %s no longer registered by %s", u->id, name, old_owner);
2846 log_unit_debug(u->id, "%s's D-Bus name %s now registered by %s", u->id, name, new_owner);
2848 s->bus_name_good = !!new_owner;
2850 if (s->type == SERVICE_DBUS) {
2852 /* service_enter_running() will figure out what to
2854 if (s->state == SERVICE_RUNNING)
2855 service_enter_running(s, SERVICE_SUCCESS);
2856 else if (s->state == SERVICE_START && new_owner)
2857 service_enter_start_post(s);
2859 } else if (new_owner &&
2861 (s->state == SERVICE_START ||
2862 s->state == SERVICE_START_POST ||
2863 s->state == SERVICE_RUNNING ||
2864 s->state == SERVICE_RELOAD)) {
2866 _cleanup_bus_creds_unref_ sd_bus_creds *creds = NULL;
2869 /* Try to acquire PID from bus service */
2871 r = sd_bus_get_name_creds(u->manager->api_bus, name, SD_BUS_CREDS_PID, &creds);
2873 r = sd_bus_creds_get_pid(creds, &pid);
2875 log_unit_debug(u->id, "%s's D-Bus name %s is now owned by process %u", u->id, name, (unsigned) pid);
2877 service_set_main_pid(s, pid);
2878 unit_watch_pid(UNIT(s), pid);
2883 int service_set_socket_fd(Service *s, int fd, Socket *sock, bool selinux_context_net) {
2884 _cleanup_free_ char *peer = NULL;
2890 /* This is called by the socket code when instantiating a new
2891 * service for a stream socket and the socket needs to be
2894 if (UNIT(s)->load_state != UNIT_LOADED)
2897 if (s->socket_fd >= 0)
2900 if (s->state != SERVICE_DEAD)
2903 if (getpeername_pretty(fd, &peer) >= 0) {
2905 if (UNIT(s)->description) {
2906 _cleanup_free_ char *a;
2908 a = strjoin(UNIT(s)->description, " (", peer, ")", NULL);
2912 r = unit_set_description(UNIT(s), a);
2914 r = unit_set_description(UNIT(s), peer);
2921 s->socket_fd_selinux_context_net = selinux_context_net;
2923 unit_ref_set(&s->accept_socket, UNIT(sock));
2925 return unit_add_two_dependencies(UNIT(sock), UNIT_BEFORE, UNIT_TRIGGERS, UNIT(s), false);
2928 static void service_reset_failed(Unit *u) {
2929 Service *s = SERVICE(u);
2933 if (s->state == SERVICE_FAILED)
2934 service_set_state(s, SERVICE_DEAD);
2936 s->result = SERVICE_SUCCESS;
2937 s->reload_result = SERVICE_SUCCESS;
2939 RATELIMIT_RESET(s->start_limit);
2942 static int service_kill(Unit *u, KillWho who, int signo, sd_bus_error *error) {
2943 Service *s = SERVICE(u);
2945 return unit_kill_common(u, who, signo, s->main_pid, s->control_pid, error);
2948 static const char* const service_state_table[_SERVICE_STATE_MAX] = {
2949 [SERVICE_DEAD] = "dead",
2950 [SERVICE_START_PRE] = "start-pre",
2951 [SERVICE_START] = "start",
2952 [SERVICE_START_POST] = "start-post",
2953 [SERVICE_RUNNING] = "running",
2954 [SERVICE_EXITED] = "exited",
2955 [SERVICE_RELOAD] = "reload",
2956 [SERVICE_STOP] = "stop",
2957 [SERVICE_STOP_SIGABRT] = "stop-sigabrt",
2958 [SERVICE_STOP_SIGTERM] = "stop-sigterm",
2959 [SERVICE_STOP_SIGKILL] = "stop-sigkill",
2960 [SERVICE_STOP_POST] = "stop-post",
2961 [SERVICE_FINAL_SIGTERM] = "final-sigterm",
2962 [SERVICE_FINAL_SIGKILL] = "final-sigkill",
2963 [SERVICE_FAILED] = "failed",
2964 [SERVICE_AUTO_RESTART] = "auto-restart",
2967 DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
2969 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
2970 [SERVICE_RESTART_NO] = "no",
2971 [SERVICE_RESTART_ON_SUCCESS] = "on-success",
2972 [SERVICE_RESTART_ON_FAILURE] = "on-failure",
2973 [SERVICE_RESTART_ON_ABNORMAL] = "on-abnormal",
2974 [SERVICE_RESTART_ON_WATCHDOG] = "on-watchdog",
2975 [SERVICE_RESTART_ON_ABORT] = "on-abort",
2976 [SERVICE_RESTART_ALWAYS] = "always",
2979 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
2981 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
2982 [SERVICE_SIMPLE] = "simple",
2983 [SERVICE_FORKING] = "forking",
2984 [SERVICE_ONESHOT] = "oneshot",
2985 [SERVICE_DBUS] = "dbus",
2986 [SERVICE_NOTIFY] = "notify",
2987 [SERVICE_IDLE] = "idle"
2990 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
2992 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
2993 [SERVICE_EXEC_START_PRE] = "ExecStartPre",
2994 [SERVICE_EXEC_START] = "ExecStart",
2995 [SERVICE_EXEC_START_POST] = "ExecStartPost",
2996 [SERVICE_EXEC_RELOAD] = "ExecReload",
2997 [SERVICE_EXEC_STOP] = "ExecStop",
2998 [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
3001 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
3003 static const char* const notify_access_table[_NOTIFY_ACCESS_MAX] = {
3004 [NOTIFY_NONE] = "none",
3005 [NOTIFY_MAIN] = "main",
3006 [NOTIFY_ALL] = "all"
3009 DEFINE_STRING_TABLE_LOOKUP(notify_access, NotifyAccess);
3011 static const char* const notify_state_table[_NOTIFY_STATE_MAX] = {
3012 [NOTIFY_UNKNOWN] = "unknown",
3013 [NOTIFY_READY] = "ready",
3014 [NOTIFY_RELOADING] = "reloading",
3015 [NOTIFY_STOPPING] = "stopping",
3018 DEFINE_STRING_TABLE_LOOKUP(notify_state, NotifyState);
3020 static const char* const service_result_table[_SERVICE_RESULT_MAX] = {
3021 [SERVICE_SUCCESS] = "success",
3022 [SERVICE_FAILURE_RESOURCES] = "resources",
3023 [SERVICE_FAILURE_TIMEOUT] = "timeout",
3024 [SERVICE_FAILURE_EXIT_CODE] = "exit-code",
3025 [SERVICE_FAILURE_SIGNAL] = "signal",
3026 [SERVICE_FAILURE_CORE_DUMP] = "core-dump",
3027 [SERVICE_FAILURE_WATCHDOG] = "watchdog",
3028 [SERVICE_FAILURE_START_LIMIT] = "start-limit"
3031 DEFINE_STRING_TABLE_LOOKUP(service_result, ServiceResult);
3033 const UnitVTable service_vtable = {
3034 .object_size = sizeof(Service),
3035 .exec_context_offset = offsetof(Service, exec_context),
3036 .cgroup_context_offset = offsetof(Service, cgroup_context),
3037 .kill_context_offset = offsetof(Service, kill_context),
3038 .exec_runtime_offset = offsetof(Service, exec_runtime),
3044 .private_section = "Service",
3046 .init = service_init,
3047 .done = service_done,
3048 .load = service_load,
3049 .release_resources = service_release_resources,
3051 .coldplug = service_coldplug,
3053 .dump = service_dump,
3055 .start = service_start,
3056 .stop = service_stop,
3057 .reload = service_reload,
3059 .can_reload = service_can_reload,
3061 .kill = service_kill,
3063 .serialize = service_serialize,
3064 .deserialize_item = service_deserialize_item,
3066 .active_state = service_active_state,
3067 .sub_state_to_string = service_sub_state_to_string,
3069 .check_gc = service_check_gc,
3070 .check_snapshot = service_check_snapshot,
3072 .sigchld_event = service_sigchld_event,
3074 .reset_failed = service_reset_failed,
3076 .notify_cgroup_empty = service_notify_cgroup_empty_event,
3077 .notify_message = service_notify_message,
3079 .bus_name_owner_change = service_bus_name_owner_change,
3081 .bus_interface = "org.freedesktop.systemd1.Service",
3082 .bus_vtable = bus_service_vtable,
3083 .bus_set_property = bus_service_set_property,
3084 .bus_commit_properties = bus_service_commit_properties,
3086 .get_timeout = service_get_timeout,
3087 .can_transient = true,
3089 .status_message_formats = {
3090 .starting_stopping = {
3091 [0] = "Starting %s...",
3092 [1] = "Stopping %s...",
3094 .finished_start_job = {
3095 [JOB_DONE] = "Started %s.",
3096 [JOB_FAILED] = "Failed to start %s.",
3097 [JOB_DEPENDENCY] = "Dependency failed for %s.",
3098 [JOB_TIMEOUT] = "Timed out starting %s.",
3100 .finished_stop_job = {
3101 [JOB_DONE] = "Stopped %s.",
3102 [JOB_FAILED] = "Stopped (with error) %s.",
3103 [JOB_TIMEOUT] = "Timed out stopping %s.",