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/>.
30 #include "load-fragment.h"
31 #include "load-dropin.h"
34 #include "unit-name.h"
35 #include "unit-printf.h"
36 #include "dbus-service.h"
38 #include "exit-status.h"
40 #include "path-util.h"
45 #include "bus-error.h"
47 #include "bus-kernel.h"
49 static const UnitActiveState state_translation_table[_SERVICE_STATE_MAX] = {
50 [SERVICE_DEAD] = UNIT_INACTIVE,
51 [SERVICE_START_PRE] = UNIT_ACTIVATING,
52 [SERVICE_START] = UNIT_ACTIVATING,
53 [SERVICE_START_POST] = UNIT_ACTIVATING,
54 [SERVICE_RUNNING] = UNIT_ACTIVE,
55 [SERVICE_EXITED] = UNIT_ACTIVE,
56 [SERVICE_RELOAD] = UNIT_RELOADING,
57 [SERVICE_STOP] = UNIT_DEACTIVATING,
58 [SERVICE_STOP_SIGABRT] = 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_SIGABRT] = UNIT_DEACTIVATING,
80 [SERVICE_STOP_SIGTERM] = UNIT_DEACTIVATING,
81 [SERVICE_STOP_SIGKILL] = UNIT_DEACTIVATING,
82 [SERVICE_STOP_POST] = UNIT_DEACTIVATING,
83 [SERVICE_FINAL_SIGTERM] = UNIT_DEACTIVATING,
84 [SERVICE_FINAL_SIGKILL] = UNIT_DEACTIVATING,
85 [SERVICE_FAILED] = UNIT_FAILED,
86 [SERVICE_AUTO_RESTART] = UNIT_ACTIVATING
89 static int service_dispatch_io(sd_event_source *source, int fd, uint32_t events, void *userdata);
90 static int service_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata);
91 static int service_dispatch_watchdog(sd_event_source *source, usec_t usec, void *userdata);
93 static void service_enter_signal(Service *s, ServiceState state, ServiceResult f);
94 static void service_enter_reload_by_notify(Service *s);
96 static void service_init(Unit *u) {
97 Service *s = SERVICE(u);
100 assert(u->load_state == UNIT_STUB);
102 s->timeout_start_usec = u->manager->default_timeout_start_usec;
103 s->timeout_stop_usec = u->manager->default_timeout_stop_usec;
104 s->restart_usec = u->manager->default_restart_usec;
105 s->type = _SERVICE_TYPE_INVALID;
107 s->bus_endpoint_fd = -1;
108 s->guess_main_pid = true;
110 RATELIMIT_INIT(s->start_limit, u->manager->default_start_limit_interval, u->manager->default_start_limit_burst);
112 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
115 static void service_unwatch_control_pid(Service *s) {
118 if (s->control_pid <= 0)
121 unit_unwatch_pid(UNIT(s), s->control_pid);
125 static void service_unwatch_main_pid(Service *s) {
128 if (s->main_pid <= 0)
131 unit_unwatch_pid(UNIT(s), s->main_pid);
135 static void service_unwatch_pid_file(Service *s) {
136 if (!s->pid_file_pathspec)
139 log_unit_debug(UNIT(s)->id, "Stopping watch for %s's PID file %s", UNIT(s)->id, s->pid_file_pathspec->path);
140 path_spec_unwatch(s->pid_file_pathspec);
141 path_spec_done(s->pid_file_pathspec);
142 free(s->pid_file_pathspec);
143 s->pid_file_pathspec = NULL;
146 static int service_set_main_pid(Service *s, pid_t pid) {
157 if (s->main_pid == pid && s->main_pid_known)
160 if (s->main_pid != pid) {
161 service_unwatch_main_pid(s);
162 exec_status_start(&s->main_exec_status, pid);
166 s->main_pid_known = true;
168 if (get_parent_of_pid(pid, &ppid) >= 0 && ppid != getpid()) {
169 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);
170 s->main_pid_alien = true;
172 s->main_pid_alien = false;
177 static void service_close_socket_fd(Service *s) {
180 s->socket_fd = asynchronous_close(s->socket_fd);
183 static void service_connection_unref(Service *s) {
186 if (!UNIT_ISSET(s->accept_socket))
189 socket_connection_unref(SOCKET(UNIT_DEREF(s->accept_socket)));
190 unit_ref_unset(&s->accept_socket);
193 static void service_stop_watchdog(Service *s) {
196 s->watchdog_event_source = sd_event_source_unref(s->watchdog_event_source);
197 s->watchdog_timestamp = DUAL_TIMESTAMP_NULL;
200 static void service_start_watchdog(Service *s) {
205 if (s->watchdog_usec <= 0)
208 if (s->watchdog_event_source) {
209 r = sd_event_source_set_time(s->watchdog_event_source, s->watchdog_timestamp.monotonic + s->watchdog_usec);
211 log_unit_warning_errno(UNIT(s)->id, r, "%s failed to reset watchdog timer: %m", UNIT(s)->id);
215 r = sd_event_source_set_enabled(s->watchdog_event_source, SD_EVENT_ONESHOT);
217 r = sd_event_add_time(
218 UNIT(s)->manager->event,
219 &s->watchdog_event_source,
221 s->watchdog_timestamp.monotonic + s->watchdog_usec, 0,
222 service_dispatch_watchdog, s);
224 log_unit_warning_errno(UNIT(s)->id, r, "%s failed to add watchdog timer: %m", UNIT(s)->id);
228 /* Let's process everything else which might be a sign
229 * of living before we consider a service died. */
230 r = sd_event_source_set_priority(s->watchdog_event_source, SD_EVENT_PRIORITY_IDLE);
234 log_unit_warning_errno(UNIT(s)->id, r, "%s failed to install watchdog timer: %m", UNIT(s)->id);
237 static void service_reset_watchdog(Service *s) {
240 dual_timestamp_get(&s->watchdog_timestamp);
241 service_start_watchdog(s);
244 static void service_fd_store_unlink(ServiceFDStore *fs) {
250 assert(fs->service->n_fd_store > 0);
251 LIST_REMOVE(fd_store, fs->service->fd_store, fs);
252 fs->service->n_fd_store--;
255 if (fs->event_source) {
256 sd_event_source_set_enabled(fs->event_source, SD_EVENT_OFF);
257 sd_event_source_unref(fs->event_source);
264 static void service_release_resources(Unit *u) {
265 Service *s = SERVICE(u);
272 log_debug("Releasing all resources for %s", u->id);
275 service_fd_store_unlink(s->fd_store);
277 assert(s->n_fd_store == 0);
280 static void service_done(Unit *u) {
281 Service *s = SERVICE(u);
288 free(s->status_text);
289 s->status_text = NULL;
292 s->reboot_arg = NULL;
294 s->exec_runtime = exec_runtime_unref(s->exec_runtime);
295 exec_command_free_array(s->exec_command, _SERVICE_EXEC_COMMAND_MAX);
296 s->control_command = NULL;
297 s->main_command = NULL;
299 exit_status_set_free(&s->restart_prevent_status);
300 exit_status_set_free(&s->restart_force_status);
301 exit_status_set_free(&s->success_status);
303 /* This will leak a process, but at least no memory or any of
305 service_unwatch_main_pid(s);
306 service_unwatch_control_pid(s);
307 service_unwatch_pid_file(s);
310 unit_unwatch_bus_name(u, s->bus_name);
315 s->bus_endpoint_fd = safe_close(s->bus_endpoint_fd);
316 service_close_socket_fd(s);
317 service_connection_unref(s);
319 unit_ref_unset(&s->accept_socket);
321 service_stop_watchdog(s);
323 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
325 service_release_resources(u);
328 static int on_fd_store_io(sd_event_source *e, int fd, uint32_t revents, void *userdata) {
329 ServiceFDStore *fs = userdata;
334 /* If we get either EPOLLHUP or EPOLLERR, it's time to remove this entry from the fd store */
335 service_fd_store_unlink(fs);
339 static int service_add_fd_store(Service *s, int fd) {
346 if (s->n_fd_store >= s->n_fd_store_max)
349 LIST_FOREACH(fd_store, fs, s->fd_store) {
350 r = same_fd(fs->fd, fd);
354 /* Already included */
360 fs = new0(ServiceFDStore, 1);
367 r = sd_event_add_io(UNIT(s)->manager->event, &fs->event_source, fd, 0, on_fd_store_io, fs);
373 LIST_PREPEND(fd_store, s->fd_store, fs);
379 static int service_add_fd_store_set(Service *s, FDSet *fds) {
384 if (fdset_size(fds) <= 0)
387 while (s->n_fd_store < s->n_fd_store_max) {
388 _cleanup_close_ int fd = -1;
390 fd = fdset_steal_first(fds);
394 r = service_add_fd_store(s, fd);
396 return log_unit_error_errno(UNIT(s)->id, r, "%s: Couldn't add fd to fd store: %m", UNIT(s)->id);
399 log_unit_debug(UNIT(s)->id, "%s: added fd to fd store.", UNIT(s)->id);
404 if (fdset_size(fds) > 0)
405 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);
410 static int service_arm_timer(Service *s, usec_t usec) {
415 if (s->timer_event_source) {
416 r = sd_event_source_set_time(s->timer_event_source, now(CLOCK_MONOTONIC) + usec);
420 return sd_event_source_set_enabled(s->timer_event_source, SD_EVENT_ONESHOT);
423 return sd_event_add_time(
424 UNIT(s)->manager->event,
425 &s->timer_event_source,
427 now(CLOCK_MONOTONIC) + usec, 0,
428 service_dispatch_timer, s);
431 static int service_verify(Service *s) {
434 if (UNIT(s)->load_state != UNIT_LOADED)
437 if (!s->exec_command[SERVICE_EXEC_START] && !s->exec_command[SERVICE_EXEC_STOP]) {
438 log_unit_error(UNIT(s)->id, "%s lacks both ExecStart= and ExecStop= setting. Refusing.", UNIT(s)->id);
442 if (s->type != SERVICE_ONESHOT && !s->exec_command[SERVICE_EXEC_START]) {
443 log_unit_error(UNIT(s)->id, "%s has no ExecStart= setting, which is only allowed for Type=oneshot services. Refusing.", UNIT(s)->id);
447 if (!s->remain_after_exit && !s->exec_command[SERVICE_EXEC_START]) {
448 log_unit_error(UNIT(s)->id, "%s has no ExecStart= setting, which is only allowed for RemainAfterExit=yes services. Refusing.", UNIT(s)->id);
452 if (s->type != SERVICE_ONESHOT && s->exec_command[SERVICE_EXEC_START]->command_next) {
453 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);
457 if (s->type == SERVICE_ONESHOT && s->restart != SERVICE_RESTART_NO) {
458 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);
462 if (s->type == SERVICE_ONESHOT && !exit_status_set_is_empty(&s->restart_force_status)) {
463 log_unit_error(UNIT(s)->id, "%s has RestartForceStatus= set, which isn't allowed for Type=oneshot services. Refusing.", UNIT(s)->id);
467 if (s->type == SERVICE_DBUS && !s->bus_name) {
468 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);
472 if (s->bus_name && s->type != SERVICE_DBUS)
473 log_unit_warning(UNIT(s)->id, "%s has a D-Bus service name specified, but is not of type dbus. Ignoring.", UNIT(s)->id);
475 if (s->exec_context.pam_name && !(s->kill_context.kill_mode == KILL_CONTROL_GROUP || s->kill_context.kill_mode == KILL_MIXED)) {
476 log_unit_error(UNIT(s)->id, "%s has PAM enabled. Kill mode must be set to 'control-group' or 'mixed'. Refusing.", UNIT(s)->id);
483 static int service_add_default_dependencies(Service *s) {
488 /* Add a number of automatic dependencies useful for the
489 * majority of services. */
491 /* First, pull in base system */
492 r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_BASIC_TARGET, NULL, true);
496 /* Second, activate normal shutdown */
497 return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true);
500 static void service_fix_output(Service *s) {
503 /* If nothing has been explicitly configured, patch default
504 * output in. If input is socket/tty we avoid this however,
505 * since in that case we want output to default to the same
506 * place as we read input from. */
508 if (s->exec_context.std_error == EXEC_OUTPUT_INHERIT &&
509 s->exec_context.std_output == EXEC_OUTPUT_INHERIT &&
510 s->exec_context.std_input == EXEC_INPUT_NULL)
511 s->exec_context.std_error = UNIT(s)->manager->default_std_error;
513 if (s->exec_context.std_output == EXEC_OUTPUT_INHERIT &&
514 s->exec_context.std_input == EXEC_INPUT_NULL)
515 s->exec_context.std_output = UNIT(s)->manager->default_std_output;
518 static int service_add_extras(Service *s) {
523 if (s->type == _SERVICE_TYPE_INVALID) {
524 /* Figure out a type automatically */
526 s->type = SERVICE_DBUS;
527 else if (s->exec_command[SERVICE_EXEC_START])
528 s->type = SERVICE_SIMPLE;
530 s->type = SERVICE_ONESHOT;
533 /* Oneshot services have disabled start timeout by default */
534 if (s->type == SERVICE_ONESHOT && !s->start_timeout_defined)
535 s->timeout_start_usec = 0;
537 service_fix_output(s);
539 r = unit_patch_contexts(UNIT(s));
543 r = unit_add_exec_dependencies(UNIT(s), &s->exec_context);
547 r = unit_add_default_slice(UNIT(s), &s->cgroup_context);
551 if (s->type == SERVICE_NOTIFY && s->notify_access == NOTIFY_NONE)
552 s->notify_access = NOTIFY_MAIN;
554 if (s->watchdog_usec > 0 && s->notify_access == NOTIFY_NONE)
555 s->notify_access = NOTIFY_MAIN;
560 r = unit_watch_bus_name(UNIT(s), s->bus_name);
564 n = strjoina(s->bus_name, ".busname");
565 r = unit_add_dependency_by_name(UNIT(s), UNIT_AFTER, n, NULL, true);
570 if (UNIT(s)->default_dependencies) {
571 r = service_add_default_dependencies(s);
579 static int service_load(Unit *u) {
580 Service *s = SERVICE(u);
585 /* Load a .service file */
586 r = unit_load_fragment(u);
590 /* Still nothing found? Then let's give up */
591 if (u->load_state == UNIT_STUB)
594 /* This is a new unit? Then let's add in some extras */
595 if (u->load_state == UNIT_LOADED) {
597 /* We were able to load something, then let's add in
598 * the dropin directories. */
599 r = unit_load_dropin(u);
603 /* This is a new unit? Then let's add in some
605 r = service_add_extras(s);
610 return service_verify(s);
613 static void service_dump(Unit *u, FILE *f, const char *prefix) {
614 ServiceExecCommand c;
615 Service *s = SERVICE(u);
620 prefix = strempty(prefix);
621 prefix2 = strjoina(prefix, "\t");
624 "%sService State: %s\n"
626 "%sReload Result: %s\n"
627 "%sPermissionsStartOnly: %s\n"
628 "%sRootDirectoryStartOnly: %s\n"
629 "%sRemainAfterExit: %s\n"
630 "%sGuessMainPID: %s\n"
633 "%sNotifyAccess: %s\n"
634 "%sNotifyState: %s\n",
635 prefix, service_state_to_string(s->state),
636 prefix, service_result_to_string(s->result),
637 prefix, service_result_to_string(s->reload_result),
638 prefix, yes_no(s->permissions_start_only),
639 prefix, yes_no(s->root_directory_start_only),
640 prefix, yes_no(s->remain_after_exit),
641 prefix, yes_no(s->guess_main_pid),
642 prefix, service_type_to_string(s->type),
643 prefix, service_restart_to_string(s->restart),
644 prefix, notify_access_to_string(s->notify_access),
645 prefix, notify_state_to_string(s->notify_state));
647 if (s->control_pid > 0)
649 "%sControl PID: "PID_FMT"\n",
650 prefix, s->control_pid);
654 "%sMain PID: "PID_FMT"\n"
655 "%sMain PID Known: %s\n"
656 "%sMain PID Alien: %s\n",
658 prefix, yes_no(s->main_pid_known),
659 prefix, yes_no(s->main_pid_alien));
664 prefix, s->pid_file);
669 "%sBus Name Good: %s\n",
671 prefix, yes_no(s->bus_name_good));
673 kill_context_dump(&s->kill_context, f, prefix);
674 exec_context_dump(&s->exec_context, f, prefix);
676 for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
678 if (!s->exec_command[c])
681 fprintf(f, "%s-> %s:\n",
682 prefix, service_exec_command_to_string(c));
684 exec_command_dump_list(s->exec_command[c], f, prefix2);
688 fprintf(f, "%sStatus Text: %s\n",
689 prefix, s->status_text);
691 if (s->n_fd_store_max > 0) {
693 "%sFile Descriptor Store Max: %u\n"
694 "%sFile Descriptor Store Current: %u\n",
695 prefix, s->n_fd_store_max,
696 prefix, s->n_fd_store);
700 static int service_load_pid_file(Service *s, bool may_warn) {
701 _cleanup_free_ char *k = NULL;
710 r = read_one_line_file(s->pid_file, &k);
713 log_unit_info(UNIT(s)->id, "PID file %s not readable (yet?) after %s.", s->pid_file, service_state_to_string(s->state));
717 r = parse_pid(k, &pid);
720 log_unit_info_errno(UNIT(s)->id, r, "Failed to read PID from file %s: %m", s->pid_file);
724 if (!pid_is_alive(pid)) {
726 log_unit_info(UNIT(s)->id, "PID "PID_FMT" read from file %s does not exist or is a zombie.", pid, s->pid_file);
730 if (s->main_pid_known) {
731 if (pid == s->main_pid)
734 log_unit_debug(UNIT(s)->id, "Main PID changing: "PID_FMT" -> "PID_FMT, s->main_pid, pid);
736 service_unwatch_main_pid(s);
737 s->main_pid_known = false;
739 log_unit_debug(UNIT(s)->id, "Main PID loaded: "PID_FMT, pid);
741 r = service_set_main_pid(s, pid);
745 r = unit_watch_pid(UNIT(s), pid);
747 /* FIXME: we need to do something here */
748 log_unit_warning(UNIT(s)->id, "Failed to watch PID "PID_FMT" from service %s", pid, UNIT(s)->id);
755 static int service_search_main_pid(Service *s) {
761 /* If we know it anyway, don't ever fallback to unreliable
763 if (s->main_pid_known)
766 if (!s->guess_main_pid)
769 assert(s->main_pid <= 0);
771 pid = unit_search_main_pid(UNIT(s));
775 log_unit_debug(UNIT(s)->id, "Main PID guessed: "PID_FMT, pid);
776 r = service_set_main_pid(s, pid);
780 r = unit_watch_pid(UNIT(s), pid);
782 /* FIXME: we need to do something here */
783 log_unit_warning(UNIT(s)->id, "Failed to watch PID "PID_FMT" from service %s", pid, UNIT(s)->id);
790 static void service_set_state(Service *s, ServiceState state) {
791 ServiceState old_state;
792 const UnitActiveState *table;
796 table = s->type == SERVICE_IDLE ? state_translation_table_idle : state_translation_table;
798 old_state = s->state;
801 service_unwatch_pid_file(s);
804 SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
806 SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL,
807 SERVICE_STOP_SIGABRT, SERVICE_STOP_POST,
808 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL,
809 SERVICE_AUTO_RESTART))
810 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
813 SERVICE_START, SERVICE_START_POST,
814 SERVICE_RUNNING, SERVICE_RELOAD,
815 SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL,
816 SERVICE_STOP_SIGABRT, SERVICE_STOP_POST,
817 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL)) {
818 service_unwatch_main_pid(s);
819 s->main_command = NULL;
823 SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
825 SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL,
826 SERVICE_STOP_SIGABRT, SERVICE_STOP_POST,
827 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL)) {
828 service_unwatch_control_pid(s);
829 s->control_command = NULL;
830 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
833 if (IN_SET(state, SERVICE_DEAD, SERVICE_FAILED, SERVICE_AUTO_RESTART))
834 unit_unwatch_all_pids(UNIT(s));
837 SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
838 SERVICE_RUNNING, SERVICE_RELOAD,
839 SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
840 SERVICE_STOP_SIGABRT, SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL) &&
841 !(state == SERVICE_DEAD && UNIT(s)->job)) {
842 service_close_socket_fd(s);
843 service_connection_unref(s);
846 if (!IN_SET(state, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD))
847 service_stop_watchdog(s);
849 /* For the inactive states unit_notify() will trim the cgroup,
850 * but for exit we have to do that ourselves... */
851 if (state == SERVICE_EXITED && UNIT(s)->manager->n_reloading <= 0)
852 unit_destroy_cgroup_if_empty(UNIT(s));
854 /* For remain_after_exit services, let's see if we can "release" the
855 * hold on the console, since unit_notify() only does that in case of
857 if (state == SERVICE_EXITED &&
858 s->remain_after_exit &&
859 UNIT(s)->manager->n_on_console > 0) {
863 ec = unit_get_exec_context(UNIT(s));
864 if (ec && exec_context_may_touch_console(ec)) {
865 Manager *m = UNIT(s)->manager;
868 if (m->n_on_console == 0)
869 /* unset no_console_output flag, since the console is free */
870 m->no_console_output = false;
874 if (old_state != state)
875 log_unit_debug(UNIT(s)->id, "%s changed %s -> %s", UNIT(s)->id, service_state_to_string(old_state), service_state_to_string(state));
877 unit_notify(UNIT(s), table[old_state], table[state], s->reload_result == SERVICE_SUCCESS);
878 s->reload_result = SERVICE_SUCCESS;
881 static int service_coldplug(Unit *u) {
882 Service *s = SERVICE(u);
886 assert(s->state == SERVICE_DEAD);
888 if (s->deserialized_state != s->state) {
890 if (IN_SET(s->deserialized_state,
891 SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
893 SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL,
894 SERVICE_STOP_SIGABRT, SERVICE_STOP_POST,
895 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL)) {
899 k = IN_SET(s->deserialized_state, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST, SERVICE_RELOAD) ? s->timeout_start_usec : s->timeout_stop_usec;
901 /* For the start/stop timeouts 0 means off */
903 r = service_arm_timer(s, k);
909 if (s->deserialized_state == SERVICE_AUTO_RESTART) {
911 /* The restart timeouts 0 means immediately */
912 r = service_arm_timer(s, s->restart_usec);
917 if (pid_is_unwaited(s->main_pid) &&
918 ((s->deserialized_state == SERVICE_START && IN_SET(s->type, SERVICE_FORKING, SERVICE_DBUS, SERVICE_ONESHOT, SERVICE_NOTIFY)) ||
919 IN_SET(s->deserialized_state,
920 SERVICE_START, SERVICE_START_POST,
921 SERVICE_RUNNING, SERVICE_RELOAD,
922 SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL,
923 SERVICE_STOP_SIGABRT, SERVICE_STOP_POST,
924 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL))) {
925 r = unit_watch_pid(UNIT(s), s->main_pid);
930 if (pid_is_unwaited(s->control_pid) &&
931 IN_SET(s->deserialized_state,
932 SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
934 SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL,
935 SERVICE_STOP_SIGABRT, SERVICE_STOP_POST,
936 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL)) {
937 r = unit_watch_pid(UNIT(s), s->control_pid);
942 if (!IN_SET(s->deserialized_state, SERVICE_DEAD, SERVICE_FAILED, SERVICE_AUTO_RESTART))
943 unit_watch_all_pids(UNIT(s));
945 if (IN_SET(s->deserialized_state, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD))
946 service_start_watchdog(s);
948 service_set_state(s, s->deserialized_state);
954 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
955 _cleanup_free_ int *rfds = NULL;
965 if (s->socket_fd >= 0)
968 SET_FOREACH(u, UNIT(s)->dependencies[UNIT_TRIGGERED_BY], i) {
973 if (u->type != UNIT_SOCKET)
978 r = socket_collect_fds(sock, &cfds, &cn_fds);
993 t = realloc(rfds, (rn_fds + cn_fds) * sizeof(int));
999 memcpy(t + rn_fds, cfds, cn_fds * sizeof(int));
1008 if (s->n_fd_store > 0) {
1012 t = realloc(rfds, (rn_fds + s->n_fd_store) * sizeof(int));
1017 LIST_FOREACH(fd_store, fs, s->fd_store)
1018 rfds[rn_fds++] = fs->fd;
1028 static int service_spawn(
1033 bool apply_permissions,
1035 bool apply_tty_stdin,
1042 _cleanup_free_ int *fdsbuf = NULL;
1043 unsigned n_fds = 0, n_env = 0;
1044 _cleanup_free_ char *bus_endpoint_path = NULL;
1045 _cleanup_strv_free_ char
1046 **argv = NULL, **final_env = NULL, **our_env = NULL;
1048 ExecParameters exec_params = {
1049 .apply_permissions = apply_permissions,
1050 .apply_chroot = apply_chroot,
1051 .apply_tty_stdin = apply_tty_stdin,
1052 .bus_endpoint_fd = -1,
1053 .selinux_context_net = s->socket_fd_selinux_context_net
1060 unit_realize_cgroup(UNIT(s));
1062 r = unit_setup_exec_runtime(UNIT(s));
1067 s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1068 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1069 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
1071 if (s->socket_fd >= 0) {
1072 fds = &s->socket_fd;
1075 r = service_collect_fds(s, &fdsbuf, &n_fds);
1084 r = service_arm_timer(s, timeout);
1088 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
1090 r = unit_full_printf_strv(UNIT(s), c->argv, &argv);
1094 our_env = new0(char*, 4);
1100 if (is_control ? s->notify_access == NOTIFY_ALL : s->notify_access != NOTIFY_NONE)
1101 if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=%s", UNIT(s)->manager->notify_socket) < 0) {
1106 if (s->main_pid > 0)
1107 if (asprintf(our_env + n_env++, "MAINPID="PID_FMT, s->main_pid) < 0) {
1112 if (UNIT(s)->manager->running_as != SYSTEMD_SYSTEM)
1113 if (asprintf(our_env + n_env++, "MANAGERPID="PID_FMT, getpid()) < 0) {
1118 final_env = strv_env_merge(2, UNIT(s)->manager->environment, our_env, NULL);
1124 if (is_control && UNIT(s)->cgroup_path) {
1125 path = strjoina(UNIT(s)->cgroup_path, "/control");
1126 cg_create(SYSTEMD_CGROUP_CONTROLLER, path);
1128 path = UNIT(s)->cgroup_path;
1131 if (s->exec_context.bus_endpoint) {
1132 r = bus_kernel_create_endpoint(UNIT(s)->manager->running_as == SYSTEMD_SYSTEM ? "system" : "user",
1133 UNIT(s)->id, &bus_endpoint_path);
1137 /* Pass the fd to the exec_params so that the child process can upload the policy.
1138 * Keep a reference to the fd in the service, so the endpoint is kept alive as long
1139 * as the service is running. */
1140 exec_params.bus_endpoint_fd = s->bus_endpoint_fd = r;
1144 exec_params.argv = argv;
1145 exec_params.fds = fds;
1146 exec_params.n_fds = n_fds;
1147 exec_params.environment = final_env;
1148 exec_params.confirm_spawn = UNIT(s)->manager->confirm_spawn;
1149 exec_params.cgroup_supported = UNIT(s)->manager->cgroup_supported;
1150 exec_params.cgroup_path = path;
1151 exec_params.cgroup_delegate = s->cgroup_context.delegate;
1152 exec_params.runtime_prefix = manager_get_runtime_prefix(UNIT(s)->manager);
1153 exec_params.unit_id = UNIT(s)->id;
1154 exec_params.watchdog_usec = s->watchdog_usec;
1155 exec_params.bus_endpoint_path = bus_endpoint_path;
1156 if (s->type == SERVICE_IDLE)
1157 exec_params.idle_pipe = UNIT(s)->manager->idle_pipe;
1167 r = unit_watch_pid(UNIT(s), pid);
1169 /* FIXME: we need to do something here */
1178 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
1183 static int main_pid_good(Service *s) {
1186 /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1189 /* If we know the pid file, then lets just check if it is
1191 if (s->main_pid_known) {
1193 /* If it's an alien child let's check if it is still
1195 if (s->main_pid_alien && s->main_pid > 0)
1196 return pid_is_alive(s->main_pid);
1198 /* .. otherwise assume we'll get a SIGCHLD for it,
1199 * which we really should wait for to collect exit
1200 * status and code */
1201 return s->main_pid > 0;
1204 /* We don't know the pid */
1208 _pure_ static int control_pid_good(Service *s) {
1211 return s->control_pid > 0;
1214 static int cgroup_good(Service *s) {
1219 if (!UNIT(s)->cgroup_path)
1222 r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, UNIT(s)->cgroup_path, true);
1229 static void service_enter_dead(Service *s, ServiceResult f, bool allow_restart) {
1233 if (f != SERVICE_SUCCESS)
1236 service_set_state(s, s->result != SERVICE_SUCCESS ? SERVICE_FAILED : SERVICE_DEAD);
1238 if (s->result != SERVICE_SUCCESS) {
1239 log_unit_warning(UNIT(s)->id, "%s failed.", UNIT(s)->id);
1240 failure_action(UNIT(s)->manager, s->failure_action, s->reboot_arg);
1243 if (allow_restart &&
1244 !s->forbid_restart &&
1245 (s->restart == SERVICE_RESTART_ALWAYS ||
1246 (s->restart == SERVICE_RESTART_ON_SUCCESS && s->result == SERVICE_SUCCESS) ||
1247 (s->restart == SERVICE_RESTART_ON_FAILURE && s->result != SERVICE_SUCCESS) ||
1248 (s->restart == SERVICE_RESTART_ON_ABNORMAL && !IN_SET(s->result, SERVICE_SUCCESS, SERVICE_FAILURE_EXIT_CODE)) ||
1249 (s->restart == SERVICE_RESTART_ON_WATCHDOG && s->result == SERVICE_FAILURE_WATCHDOG) ||
1250 (s->restart == SERVICE_RESTART_ON_ABORT && IN_SET(s->result, SERVICE_FAILURE_SIGNAL, SERVICE_FAILURE_CORE_DUMP)) ||
1251 (s->main_exec_status.code == CLD_EXITED && set_contains(s->restart_force_status.status, INT_TO_PTR(s->main_exec_status.status))) ||
1252 (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)))) &&
1253 (s->main_exec_status.code != CLD_EXITED || !set_contains(s->restart_prevent_status.status, INT_TO_PTR(s->main_exec_status.status))) &&
1254 (!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)))) {
1256 r = service_arm_timer(s, s->restart_usec);
1260 service_set_state(s, SERVICE_AUTO_RESTART);
1263 s->forbid_restart = false;
1265 /* We want fresh tmpdirs in case service is started again immediately */
1266 exec_runtime_destroy(s->exec_runtime);
1267 s->exec_runtime = exec_runtime_unref(s->exec_runtime);
1269 /* Also, remove the runtime directory in */
1270 exec_context_destroy_runtime_directory(&s->exec_context, manager_get_runtime_prefix(UNIT(s)->manager));
1272 /* Try to delete the pid file. At this point it will be
1273 * out-of-date, and some software might be confused by it, so
1274 * let's remove it. */
1276 unlink_noerrno(s->pid_file);
1281 log_unit_warning_errno(UNIT(s)->id, r, "%s failed to run install restart timer: %m", UNIT(s)->id);
1282 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, false);
1285 static void service_enter_stop_post(Service *s, ServiceResult f) {
1289 if (f != SERVICE_SUCCESS)
1292 service_unwatch_control_pid(s);
1293 unit_watch_all_pids(UNIT(s));
1295 s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST];
1296 if (s->control_command) {
1297 s->control_command_id = SERVICE_EXEC_STOP_POST;
1299 r = service_spawn(s,
1301 s->timeout_stop_usec,
1303 !s->permissions_start_only,
1304 !s->root_directory_start_only,
1311 service_set_state(s, SERVICE_STOP_POST);
1313 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_SUCCESS);
1318 log_unit_warning_errno(UNIT(s)->id, r, "%s failed to run 'stop-post' task: %m", UNIT(s)->id);
1319 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
1322 static void service_enter_signal(Service *s, ServiceState state, ServiceResult f) {
1327 if (f != SERVICE_SUCCESS)
1330 unit_watch_all_pids(UNIT(s));
1332 r = unit_kill_context(
1335 (state != SERVICE_STOP_SIGTERM && state != SERVICE_FINAL_SIGTERM && state != SERVICE_STOP_SIGABRT) ?
1336 KILL_KILL : (state == SERVICE_STOP_SIGABRT ? KILL_ABORT : KILL_TERMINATE),
1345 if (s->timeout_stop_usec > 0) {
1346 r = service_arm_timer(s, s->timeout_stop_usec);
1351 service_set_state(s, state);
1352 } else if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGABRT)
1353 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_SUCCESS);
1354 else if (state == SERVICE_STOP_SIGKILL)
1355 service_enter_stop_post(s, SERVICE_SUCCESS);
1356 else if (state == SERVICE_FINAL_SIGTERM)
1357 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_SUCCESS);
1359 service_enter_dead(s, SERVICE_SUCCESS, true);
1364 log_unit_warning_errno(UNIT(s)->id, r, "%s failed to kill processes: %m", UNIT(s)->id);
1366 if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL ||
1367 state == SERVICE_STOP_SIGABRT)
1368 service_enter_stop_post(s, SERVICE_FAILURE_RESOURCES);
1370 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
1373 static void service_enter_stop_by_notify(Service *s) {
1376 unit_watch_all_pids(UNIT(s));
1378 if (s->timeout_stop_usec > 0)
1379 service_arm_timer(s, s->timeout_stop_usec);
1381 /* The service told us it's stopping, so it's as if we SIGTERM'd it. */
1382 service_set_state(s, SERVICE_STOP_SIGTERM);
1385 static void service_enter_stop(Service *s, ServiceResult f) {
1390 if (f != SERVICE_SUCCESS)
1393 service_unwatch_control_pid(s);
1394 unit_watch_all_pids(UNIT(s));
1396 s->control_command = s->exec_command[SERVICE_EXEC_STOP];
1397 if (s->control_command) {
1398 s->control_command_id = SERVICE_EXEC_STOP;
1400 r = service_spawn(s,
1402 s->timeout_stop_usec,
1404 !s->permissions_start_only,
1405 !s->root_directory_start_only,
1412 service_set_state(s, SERVICE_STOP);
1414 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
1419 log_unit_warning_errno(UNIT(s)->id, r, "%s failed to run 'stop' task: %m", UNIT(s)->id);
1420 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
1423 static void service_enter_running(Service *s, ServiceResult f) {
1424 int main_pid_ok, cgroup_ok;
1427 if (f != SERVICE_SUCCESS)
1430 main_pid_ok = main_pid_good(s);
1431 cgroup_ok = cgroup_good(s);
1433 if ((main_pid_ok > 0 || (main_pid_ok < 0 && cgroup_ok != 0)) &&
1434 (s->bus_name_good || s->type != SERVICE_DBUS)) {
1436 /* If there are any queued up sd_notify()
1437 * notifications, process them now */
1438 if (s->notify_state == NOTIFY_RELOADING)
1439 service_enter_reload_by_notify(s);
1440 else if (s->notify_state == NOTIFY_STOPPING)
1441 service_enter_stop_by_notify(s);
1443 service_set_state(s, SERVICE_RUNNING);
1445 } else if (s->remain_after_exit)
1446 service_set_state(s, SERVICE_EXITED);
1448 service_enter_stop(s, SERVICE_SUCCESS);
1451 static void service_enter_start_post(Service *s) {
1455 service_unwatch_control_pid(s);
1456 service_reset_watchdog(s);
1458 s->control_command = s->exec_command[SERVICE_EXEC_START_POST];
1459 if (s->control_command) {
1460 s->control_command_id = SERVICE_EXEC_START_POST;
1462 r = service_spawn(s,
1464 s->timeout_start_usec,
1466 !s->permissions_start_only,
1467 !s->root_directory_start_only,
1474 service_set_state(s, SERVICE_START_POST);
1476 service_enter_running(s, SERVICE_SUCCESS);
1481 log_unit_warning_errno(UNIT(s)->id, r, "%s failed to run 'start-post' task: %m", UNIT(s)->id);
1482 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
1485 static void service_kill_control_processes(Service *s) {
1488 if (!UNIT(s)->cgroup_path)
1491 p = strjoina(UNIT(s)->cgroup_path, "/control");
1492 cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, p, SIGKILL, true, true, true, NULL);
1495 static void service_enter_start(Service *s) {
1502 service_unwatch_control_pid(s);
1503 service_unwatch_main_pid(s);
1505 /* We want to ensure that nobody leaks processes from
1506 * START_PRE here, so let's go on a killing spree, People
1507 * should not spawn long running processes from START_PRE. */
1508 service_kill_control_processes(s);
1510 if (s->type == SERVICE_FORKING) {
1511 s->control_command_id = SERVICE_EXEC_START;
1512 c = s->control_command = s->exec_command[SERVICE_EXEC_START];
1514 s->main_command = NULL;
1516 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1517 s->control_command = NULL;
1519 c = s->main_command = s->exec_command[SERVICE_EXEC_START];
1523 assert(s->type == SERVICE_ONESHOT);
1524 service_enter_start_post(s);
1528 r = service_spawn(s,
1530 IN_SET(s->type, SERVICE_FORKING, SERVICE_DBUS, SERVICE_NOTIFY, SERVICE_ONESHOT) ? s->timeout_start_usec : 0,
1540 if (s->type == SERVICE_SIMPLE || s->type == SERVICE_IDLE) {
1541 /* For simple services we immediately start
1542 * the START_POST binaries. */
1544 service_set_main_pid(s, pid);
1545 service_enter_start_post(s);
1547 } else if (s->type == SERVICE_FORKING) {
1549 /* For forking services we wait until the start
1550 * process exited. */
1552 s->control_pid = pid;
1553 service_set_state(s, SERVICE_START);
1555 } else if (s->type == SERVICE_ONESHOT ||
1556 s->type == SERVICE_DBUS ||
1557 s->type == SERVICE_NOTIFY) {
1559 /* For oneshot services we wait until the start
1560 * process exited, too, but it is our main process. */
1562 /* For D-Bus services we know the main pid right away,
1563 * but wait for the bus name to appear on the
1564 * bus. Notify services are similar. */
1566 service_set_main_pid(s, pid);
1567 service_set_state(s, SERVICE_START);
1569 assert_not_reached("Unknown service type");
1574 log_unit_warning_errno(UNIT(s)->id, r, "%s failed to run 'start' task: %m", UNIT(s)->id);
1575 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
1578 static void service_enter_start_pre(Service *s) {
1583 service_unwatch_control_pid(s);
1585 s->control_command = s->exec_command[SERVICE_EXEC_START_PRE];
1586 if (s->control_command) {
1587 /* Before we start anything, let's clear up what might
1588 * be left from previous runs. */
1589 service_kill_control_processes(s);
1591 s->control_command_id = SERVICE_EXEC_START_PRE;
1593 r = service_spawn(s,
1595 s->timeout_start_usec,
1597 !s->permissions_start_only,
1598 !s->root_directory_start_only,
1605 service_set_state(s, SERVICE_START_PRE);
1607 service_enter_start(s);
1612 log_unit_warning_errno(UNIT(s)->id, r, "%s failed to run 'start-pre' task: %m", UNIT(s)->id);
1613 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
1616 static void service_enter_restart(Service *s) {
1617 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
1622 if (UNIT(s)->job && UNIT(s)->job->type == JOB_STOP) {
1623 /* Don't restart things if we are going down anyway */
1624 log_unit_info(UNIT(s)->id, "Stop job pending for unit, delaying automatic restart.");
1626 r = service_arm_timer(s, s->restart_usec);
1633 /* Any units that are bound to this service must also be
1634 * restarted. We use JOB_RESTART (instead of the more obvious
1635 * JOB_START) here so that those dependency jobs will be added
1637 r = manager_add_job(UNIT(s)->manager, JOB_RESTART, UNIT(s), JOB_FAIL, false, &error, NULL);
1641 /* Note that we stay in the SERVICE_AUTO_RESTART state here,
1642 * it will be canceled as part of the service_stop() call that
1643 * is executed as part of JOB_RESTART. */
1645 log_unit_debug(UNIT(s)->id, "%s scheduled restart job.", UNIT(s)->id);
1649 log_unit_warning(UNIT(s)->id, "%s failed to schedule restart job: %s", UNIT(s)->id, bus_error_message(&error, -r));
1650 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, false);
1653 static void service_enter_reload_by_notify(Service *s) {
1656 if (s->timeout_start_usec > 0)
1657 service_arm_timer(s, s->timeout_start_usec);
1659 service_set_state(s, SERVICE_RELOAD);
1662 static void service_enter_reload(Service *s) {
1667 service_unwatch_control_pid(s);
1669 s->control_command = s->exec_command[SERVICE_EXEC_RELOAD];
1670 if (s->control_command) {
1671 s->control_command_id = SERVICE_EXEC_RELOAD;
1673 r = service_spawn(s,
1675 s->timeout_start_usec,
1677 !s->permissions_start_only,
1678 !s->root_directory_start_only,
1685 service_set_state(s, SERVICE_RELOAD);
1687 service_enter_running(s, SERVICE_SUCCESS);
1692 log_unit_warning_errno(UNIT(s)->id, r, "%s failed to run 'reload' task: %m", UNIT(s)->id);
1693 s->reload_result = SERVICE_FAILURE_RESOURCES;
1694 service_enter_running(s, SERVICE_SUCCESS);
1697 static void service_run_next_control(Service *s) {
1701 assert(s->control_command);
1702 assert(s->control_command->command_next);
1704 assert(s->control_command_id != SERVICE_EXEC_START);
1706 s->control_command = s->control_command->command_next;
1707 service_unwatch_control_pid(s);
1709 r = service_spawn(s,
1711 IN_SET(s->state, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD) ? s->timeout_start_usec : s->timeout_stop_usec,
1713 !s->permissions_start_only,
1714 !s->root_directory_start_only,
1715 s->control_command_id == SERVICE_EXEC_START_PRE ||
1716 s->control_command_id == SERVICE_EXEC_STOP_POST,
1725 log_unit_warning_errno(UNIT(s)->id, r, "%s failed to run next control task: %m", UNIT(s)->id);
1727 if (s->state == SERVICE_START_PRE)
1728 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
1729 else if (s->state == SERVICE_STOP)
1730 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
1731 else if (s->state == SERVICE_STOP_POST)
1732 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
1733 else if (s->state == SERVICE_RELOAD) {
1734 s->reload_result = SERVICE_FAILURE_RESOURCES;
1735 service_enter_running(s, SERVICE_SUCCESS);
1737 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
1740 static void service_run_next_main(Service *s) {
1745 assert(s->main_command);
1746 assert(s->main_command->command_next);
1747 assert(s->type == SERVICE_ONESHOT);
1749 s->main_command = s->main_command->command_next;
1750 service_unwatch_main_pid(s);
1752 r = service_spawn(s,
1754 s->timeout_start_usec,
1764 service_set_main_pid(s, pid);
1769 log_unit_warning_errno(UNIT(s)->id, r, "%s failed to run next main task: %m", UNIT(s)->id);
1770 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
1773 static int service_start_limit_test(Service *s) {
1776 if (ratelimit_test(&s->start_limit))
1779 log_unit_warning(UNIT(s)->id, "start request repeated too quickly for %s", UNIT(s)->id);
1781 return failure_action(UNIT(s)->manager, s->start_limit_action, s->reboot_arg);
1784 static int service_start(Unit *u) {
1785 Service *s = SERVICE(u);
1790 /* We cannot fulfill this request right now, try again later
1792 if (s->state == SERVICE_STOP ||
1793 s->state == SERVICE_STOP_SIGABRT ||
1794 s->state == SERVICE_STOP_SIGTERM ||
1795 s->state == SERVICE_STOP_SIGKILL ||
1796 s->state == SERVICE_STOP_POST ||
1797 s->state == SERVICE_FINAL_SIGTERM ||
1798 s->state == SERVICE_FINAL_SIGKILL)
1801 /* Already on it! */
1802 if (s->state == SERVICE_START_PRE ||
1803 s->state == SERVICE_START ||
1804 s->state == SERVICE_START_POST)
1807 /* A service that will be restarted must be stopped first to
1808 * trigger BindsTo and/or OnFailure dependencies. If a user
1809 * does not want to wait for the holdoff time to elapse, the
1810 * service should be manually restarted, not started. We
1811 * simply return EAGAIN here, so that any start jobs stay
1812 * queued, and assume that the auto restart timer will
1813 * eventually trigger the restart. */
1814 if (s->state == SERVICE_AUTO_RESTART)
1817 assert(s->state == SERVICE_DEAD || s->state == SERVICE_FAILED);
1819 /* Make sure we don't enter a busy loop of some kind. */
1820 r = service_start_limit_test(s);
1822 service_enter_dead(s, SERVICE_FAILURE_START_LIMIT, false);
1826 s->result = SERVICE_SUCCESS;
1827 s->reload_result = SERVICE_SUCCESS;
1828 s->main_pid_known = false;
1829 s->main_pid_alien = false;
1830 s->forbid_restart = false;
1832 free(s->status_text);
1833 s->status_text = NULL;
1834 s->status_errno = 0;
1836 s->notify_state = NOTIFY_UNKNOWN;
1838 service_enter_start_pre(s);
1842 static int service_stop(Unit *u) {
1843 Service *s = SERVICE(u);
1847 /* Don't create restart jobs from here. */
1848 s->forbid_restart = true;
1851 if (s->state == SERVICE_STOP ||
1852 s->state == SERVICE_STOP_SIGABRT ||
1853 s->state == SERVICE_STOP_SIGTERM ||
1854 s->state == SERVICE_STOP_SIGKILL ||
1855 s->state == SERVICE_STOP_POST ||
1856 s->state == SERVICE_FINAL_SIGTERM ||
1857 s->state == SERVICE_FINAL_SIGKILL)
1860 /* A restart will be scheduled or is in progress. */
1861 if (s->state == SERVICE_AUTO_RESTART) {
1862 service_set_state(s, SERVICE_DEAD);
1866 /* If there's already something running we go directly into
1868 if (s->state == SERVICE_START_PRE ||
1869 s->state == SERVICE_START ||
1870 s->state == SERVICE_START_POST ||
1871 s->state == SERVICE_RELOAD) {
1872 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
1876 assert(s->state == SERVICE_RUNNING ||
1877 s->state == SERVICE_EXITED);
1879 service_enter_stop(s, SERVICE_SUCCESS);
1883 static int service_reload(Unit *u) {
1884 Service *s = SERVICE(u);
1888 assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
1890 service_enter_reload(s);
1894 _pure_ static bool service_can_reload(Unit *u) {
1895 Service *s = SERVICE(u);
1899 return !!s->exec_command[SERVICE_EXEC_RELOAD];
1902 static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
1903 Service *s = SERVICE(u);
1910 unit_serialize_item(u, f, "state", service_state_to_string(s->state));
1911 unit_serialize_item(u, f, "result", service_result_to_string(s->result));
1912 unit_serialize_item(u, f, "reload-result", service_result_to_string(s->reload_result));
1914 if (s->control_pid > 0)
1915 unit_serialize_item_format(u, f, "control-pid", PID_FMT,
1918 if (s->main_pid_known && s->main_pid > 0)
1919 unit_serialize_item_format(u, f, "main-pid", PID_FMT, s->main_pid);
1921 unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
1924 unit_serialize_item(u, f, "status-text", s->status_text);
1926 /* FIXME: There's a minor uncleanliness here: if there are
1927 * multiple commands attached here, we will start from the
1928 * first one again */
1929 if (s->control_command_id >= 0)
1930 unit_serialize_item(u, f, "control-command",
1931 service_exec_command_to_string(s->control_command_id));
1933 if (s->socket_fd >= 0) {
1936 copy = fdset_put_dup(fds, s->socket_fd);
1940 unit_serialize_item_format(u, f, "socket-fd", "%i", copy);
1943 if (s->bus_endpoint_fd >= 0) {
1946 copy = fdset_put_dup(fds, s->bus_endpoint_fd);
1950 unit_serialize_item_format(u, f, "endpoint-fd", "%i", copy);
1953 LIST_FOREACH(fd_store, fs, s->fd_store) {
1956 copy = fdset_put_dup(fds, fs->fd);
1960 unit_serialize_item_format(u, f, "fd-store-fd", "%i", copy);
1963 if (s->main_exec_status.pid > 0) {
1964 unit_serialize_item_format(u, f, "main-exec-status-pid", PID_FMT,
1965 s->main_exec_status.pid);
1966 dual_timestamp_serialize(f, "main-exec-status-start",
1967 &s->main_exec_status.start_timestamp);
1968 dual_timestamp_serialize(f, "main-exec-status-exit",
1969 &s->main_exec_status.exit_timestamp);
1971 if (dual_timestamp_is_set(&s->main_exec_status.exit_timestamp)) {
1972 unit_serialize_item_format(u, f, "main-exec-status-code", "%i",
1973 s->main_exec_status.code);
1974 unit_serialize_item_format(u, f, "main-exec-status-status", "%i",
1975 s->main_exec_status.status);
1978 if (dual_timestamp_is_set(&s->watchdog_timestamp))
1979 dual_timestamp_serialize(f, "watchdog-timestamp", &s->watchdog_timestamp);
1981 if (s->forbid_restart)
1982 unit_serialize_item(u, f, "forbid-restart", yes_no(s->forbid_restart));
1987 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
1988 Service *s = SERVICE(u);
1996 if (streq(key, "state")) {
1999 state = service_state_from_string(value);
2001 log_unit_debug(u->id, "Failed to parse state value %s", value);
2003 s->deserialized_state = state;
2004 } else if (streq(key, "result")) {
2007 f = service_result_from_string(value);
2009 log_unit_debug(u->id, "Failed to parse result value %s", value);
2010 else if (f != SERVICE_SUCCESS)
2013 } else if (streq(key, "reload-result")) {
2016 f = service_result_from_string(value);
2018 log_unit_debug(u->id, "Failed to parse reload result value %s", value);
2019 else if (f != SERVICE_SUCCESS)
2020 s->reload_result = f;
2022 } else if (streq(key, "control-pid")) {
2025 if (parse_pid(value, &pid) < 0)
2026 log_unit_debug(u->id, "Failed to parse control-pid value %s", value);
2028 s->control_pid = pid;
2029 } else if (streq(key, "main-pid")) {
2032 if (parse_pid(value, &pid) < 0)
2033 log_unit_debug(u->id, "Failed to parse main-pid value %s", value);
2035 service_set_main_pid(s, pid);
2036 unit_watch_pid(UNIT(s), pid);
2038 } else if (streq(key, "main-pid-known")) {
2041 b = parse_boolean(value);
2043 log_unit_debug(u->id, "Failed to parse main-pid-known value %s", value);
2045 s->main_pid_known = b;
2046 } else if (streq(key, "status-text")) {
2053 free(s->status_text);
2057 } else if (streq(key, "control-command")) {
2058 ServiceExecCommand id;
2060 id = service_exec_command_from_string(value);
2062 log_unit_debug(u->id, "Failed to parse exec-command value %s", value);
2064 s->control_command_id = id;
2065 s->control_command = s->exec_command[id];
2067 } else if (streq(key, "socket-fd")) {
2070 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2071 log_unit_debug(u->id, "Failed to parse socket-fd value %s", value);
2073 asynchronous_close(s->socket_fd);
2074 s->socket_fd = fdset_remove(fds, fd);
2076 } else if (streq(key, "endpoint-fd")) {
2079 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2080 log_unit_debug(u->id, "Failed to parse endpoint-fd value %s", value);
2082 safe_close(s->bus_endpoint_fd);
2083 s->bus_endpoint_fd = fdset_remove(fds, fd);
2085 } else if (streq(key, "fd-store-fd")) {
2088 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2089 log_unit_debug(u->id, "Failed to parse fd-store-fd value %s", value);
2091 r = service_add_fd_store(s, fd);
2093 log_unit_error_errno(u->id, r, "Failed to add fd to store: %m");
2095 fdset_remove(fds, fd);
2098 } else if (streq(key, "main-exec-status-pid")) {
2101 if (parse_pid(value, &pid) < 0)
2102 log_unit_debug(u->id, "Failed to parse main-exec-status-pid value %s", value);
2104 s->main_exec_status.pid = pid;
2105 } else if (streq(key, "main-exec-status-code")) {
2108 if (safe_atoi(value, &i) < 0)
2109 log_unit_debug(u->id, "Failed to parse main-exec-status-code value %s", value);
2111 s->main_exec_status.code = i;
2112 } else if (streq(key, "main-exec-status-status")) {
2115 if (safe_atoi(value, &i) < 0)
2116 log_unit_debug(u->id, "Failed to parse main-exec-status-status value %s", value);
2118 s->main_exec_status.status = i;
2119 } else if (streq(key, "main-exec-status-start"))
2120 dual_timestamp_deserialize(value, &s->main_exec_status.start_timestamp);
2121 else if (streq(key, "main-exec-status-exit"))
2122 dual_timestamp_deserialize(value, &s->main_exec_status.exit_timestamp);
2123 else if (streq(key, "watchdog-timestamp"))
2124 dual_timestamp_deserialize(value, &s->watchdog_timestamp);
2125 else if (streq(key, "forbid-restart")) {
2128 b = parse_boolean(value);
2130 log_unit_debug(u->id, "Failed to parse forbid-restart value %s", value);
2132 s->forbid_restart = b;
2134 log_unit_debug(u->id, "Unknown serialization key '%s'", key);
2139 _pure_ static UnitActiveState service_active_state(Unit *u) {
2140 const UnitActiveState *table;
2144 table = SERVICE(u)->type == SERVICE_IDLE ? state_translation_table_idle : state_translation_table;
2146 return table[SERVICE(u)->state];
2149 static const char *service_sub_state_to_string(Unit *u) {
2152 return service_state_to_string(SERVICE(u)->state);
2155 static bool service_check_gc(Unit *u) {
2156 Service *s = SERVICE(u);
2160 /* Never clean up services that still have a process around,
2161 * even if the service is formally dead. */
2162 if (cgroup_good(s) > 0 ||
2163 main_pid_good(s) > 0 ||
2164 control_pid_good(s) > 0)
2170 _pure_ static bool service_check_snapshot(Unit *u) {
2171 Service *s = SERVICE(u);
2175 return s->socket_fd < 0;
2178 static int service_retry_pid_file(Service *s) {
2181 assert(s->pid_file);
2182 assert(s->state == SERVICE_START || s->state == SERVICE_START_POST);
2184 r = service_load_pid_file(s, false);
2188 service_unwatch_pid_file(s);
2190 service_enter_running(s, SERVICE_SUCCESS);
2194 static int service_watch_pid_file(Service *s) {
2197 log_unit_debug(UNIT(s)->id, "Setting watch for %s's PID file %s", UNIT(s)->id, s->pid_file_pathspec->path);
2199 r = path_spec_watch(s->pid_file_pathspec, service_dispatch_io);
2203 /* the pidfile might have appeared just before we set the watch */
2204 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);
2205 service_retry_pid_file(s);
2209 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);
2210 service_unwatch_pid_file(s);
2214 static int service_demand_pid_file(Service *s) {
2217 assert(s->pid_file);
2218 assert(!s->pid_file_pathspec);
2220 ps = new0(PathSpec, 1);
2225 ps->path = strdup(s->pid_file);
2231 path_kill_slashes(ps->path);
2233 /* PATH_CHANGED would not be enough. There are daemons (sendmail) that
2234 * keep their PID file open all the time. */
2235 ps->type = PATH_MODIFIED;
2236 ps->inotify_fd = -1;
2238 s->pid_file_pathspec = ps;
2240 return service_watch_pid_file(s);
2243 static int service_dispatch_io(sd_event_source *source, int fd, uint32_t events, void *userdata) {
2244 PathSpec *p = userdata;
2249 s = SERVICE(p->unit);
2253 assert(s->state == SERVICE_START || s->state == SERVICE_START_POST);
2254 assert(s->pid_file_pathspec);
2255 assert(path_spec_owns_inotify_fd(s->pid_file_pathspec, fd));
2257 log_unit_debug(UNIT(s)->id, "inotify event for %s", UNIT(s)->id);
2259 if (path_spec_fd_event(p, events) < 0)
2262 if (service_retry_pid_file(s) == 0)
2265 if (service_watch_pid_file(s) < 0)
2271 service_unwatch_pid_file(s);
2272 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
2276 static void service_notify_cgroup_empty_event(Unit *u) {
2277 Service *s = SERVICE(u);
2281 log_unit_debug(u->id, "%s: cgroup is empty", u->id);
2285 /* Waiting for SIGCHLD is usually more interesting,
2286 * because it includes return codes/signals. Which is
2287 * why we ignore the cgroup events for most cases,
2288 * except when we don't know pid which to expect the
2292 case SERVICE_START_POST:
2293 /* If we were hoping for the daemon to write its PID file,
2294 * we can give up now. */
2295 if (s->pid_file_pathspec) {
2296 log_unit_warning(u->id, "%s never wrote its PID file. Failing.", UNIT(s)->id);
2298 service_unwatch_pid_file(s);
2299 if (s->state == SERVICE_START)
2300 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
2302 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2306 case SERVICE_RUNNING:
2307 /* service_enter_running() will figure out what to do */
2308 service_enter_running(s, SERVICE_SUCCESS);
2311 case SERVICE_STOP_SIGABRT:
2312 case SERVICE_STOP_SIGTERM:
2313 case SERVICE_STOP_SIGKILL:
2315 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2316 service_enter_stop_post(s, SERVICE_SUCCESS);
2320 case SERVICE_STOP_POST:
2321 case SERVICE_FINAL_SIGTERM:
2322 case SERVICE_FINAL_SIGKILL:
2323 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2324 service_enter_dead(s, SERVICE_SUCCESS, true);
2333 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2334 Service *s = SERVICE(u);
2340 if (UNIT(s)->fragment_path ? is_clean_exit(code, status, &s->success_status) :
2341 is_clean_exit_lsb(code, status, &s->success_status))
2342 f = SERVICE_SUCCESS;
2343 else if (code == CLD_EXITED)
2344 f = SERVICE_FAILURE_EXIT_CODE;
2345 else if (code == CLD_KILLED)
2346 f = SERVICE_FAILURE_SIGNAL;
2347 else if (code == CLD_DUMPED)
2348 f = SERVICE_FAILURE_CORE_DUMP;
2350 assert_not_reached("Unknown code");
2352 if (s->main_pid == pid) {
2353 /* Forking services may occasionally move to a new PID.
2354 * As long as they update the PID file before exiting the old
2355 * PID, they're fine. */
2356 if (service_load_pid_file(s, false) == 0)
2360 exec_status_exit(&s->main_exec_status, &s->exec_context, pid, code, status);
2362 if (s->main_command) {
2363 /* If this is not a forking service than the
2364 * main process got started and hence we copy
2365 * the exit status so that it is recorded both
2366 * as main and as control process exit
2369 s->main_command->exec_status = s->main_exec_status;
2371 if (s->main_command->ignore)
2372 f = SERVICE_SUCCESS;
2373 } else if (s->exec_command[SERVICE_EXEC_START]) {
2375 /* If this is a forked process, then we should
2376 * ignore the return value if this was
2377 * configured for the starter process */
2379 if (s->exec_command[SERVICE_EXEC_START]->ignore)
2380 f = SERVICE_SUCCESS;
2383 log_unit_struct(u->id,
2384 f == SERVICE_SUCCESS ? LOG_DEBUG : LOG_NOTICE,
2385 LOG_MESSAGE("%s: main process exited, code=%s, status=%i/%s",
2386 u->id, sigchld_code_to_string(code), status,
2387 strna(code == CLD_EXITED
2388 ? exit_status_to_string(status, EXIT_STATUS_FULL)
2389 : signal_to_string(status))),
2390 "EXIT_CODE=%s", sigchld_code_to_string(code),
2391 "EXIT_STATUS=%i", status,
2394 if (f != SERVICE_SUCCESS)
2397 if (s->main_command &&
2398 s->main_command->command_next &&
2399 f == SERVICE_SUCCESS) {
2401 /* There is another command to *
2402 * execute, so let's do that. */
2404 log_unit_debug(u->id, "%s running next main command for state %s", u->id, service_state_to_string(s->state));
2405 service_run_next_main(s);
2409 /* The service exited, so the service is officially
2411 s->main_command = NULL;
2415 case SERVICE_START_POST:
2416 case SERVICE_RELOAD:
2418 /* Need to wait until the operation is
2423 if (s->type == SERVICE_ONESHOT) {
2424 /* This was our main goal, so let's go on */
2425 if (f == SERVICE_SUCCESS)
2426 service_enter_start_post(s);
2428 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
2434 case SERVICE_RUNNING:
2435 service_enter_running(s, f);
2438 case SERVICE_STOP_SIGABRT:
2439 case SERVICE_STOP_SIGTERM:
2440 case SERVICE_STOP_SIGKILL:
2442 if (!control_pid_good(s))
2443 service_enter_stop_post(s, f);
2445 /* If there is still a control process, wait for that first */
2448 case SERVICE_STOP_POST:
2449 case SERVICE_FINAL_SIGTERM:
2450 case SERVICE_FINAL_SIGKILL:
2452 if (!control_pid_good(s))
2453 service_enter_dead(s, f, true);
2457 assert_not_reached("Uh, main process died at wrong time.");
2461 } else if (s->control_pid == pid) {
2464 if (s->control_command) {
2465 exec_status_exit(&s->control_command->exec_status, &s->exec_context, pid, code, status);
2467 if (s->control_command->ignore)
2468 f = SERVICE_SUCCESS;
2471 log_unit_full(u->id,
2472 f == SERVICE_SUCCESS ? LOG_DEBUG : LOG_NOTICE,
2473 "%s: control process exited, code=%s status=%i",
2474 u->id, sigchld_code_to_string(code), status);
2476 if (f != SERVICE_SUCCESS)
2479 /* Immediately get rid of the cgroup, so that the
2480 * kernel doesn't delay the cgroup empty messages for
2481 * the service cgroup any longer than necessary */
2482 service_kill_control_processes(s);
2484 if (s->control_command &&
2485 s->control_command->command_next &&
2486 f == SERVICE_SUCCESS) {
2488 /* There is another command to *
2489 * execute, so let's do that. */
2491 log_unit_debug(u->id, "%s running next control command for state %s", u->id, service_state_to_string(s->state));
2492 service_run_next_control(s);
2495 /* No further commands for this step, so let's
2496 * figure out what to do next */
2498 s->control_command = NULL;
2499 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2501 log_unit_debug(u->id, "%s got final SIGCHLD for state %s", u->id, service_state_to_string(s->state));
2505 case SERVICE_START_PRE:
2506 if (f == SERVICE_SUCCESS)
2507 service_enter_start(s);
2509 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
2513 if (s->type != SERVICE_FORKING)
2514 /* Maybe spurious event due to a reload that changed the type? */
2517 if (f != SERVICE_SUCCESS) {
2518 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
2523 bool has_start_post;
2526 /* Let's try to load the pid file here if we can.
2527 * The PID file might actually be created by a START_POST
2528 * script. In that case don't worry if the loading fails. */
2530 has_start_post = !!s->exec_command[SERVICE_EXEC_START_POST];
2531 r = service_load_pid_file(s, !has_start_post);
2532 if (!has_start_post && r < 0) {
2533 r = service_demand_pid_file(s);
2534 if (r < 0 || !cgroup_good(s))
2535 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
2539 service_search_main_pid(s);
2541 service_enter_start_post(s);
2544 case SERVICE_START_POST:
2545 if (f != SERVICE_SUCCESS) {
2546 service_enter_stop(s, f);
2553 r = service_load_pid_file(s, true);
2555 r = service_demand_pid_file(s);
2556 if (r < 0 || !cgroup_good(s))
2557 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2561 service_search_main_pid(s);
2563 service_enter_running(s, SERVICE_SUCCESS);
2566 case SERVICE_RELOAD:
2567 if (f == SERVICE_SUCCESS) {
2568 service_load_pid_file(s, true);
2569 service_search_main_pid(s);
2572 s->reload_result = f;
2573 service_enter_running(s, SERVICE_SUCCESS);
2577 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
2580 case SERVICE_STOP_SIGABRT:
2581 case SERVICE_STOP_SIGTERM:
2582 case SERVICE_STOP_SIGKILL:
2583 if (main_pid_good(s) <= 0)
2584 service_enter_stop_post(s, f);
2586 /* If there is still a service
2587 * process around, wait until
2588 * that one quit, too */
2591 case SERVICE_STOP_POST:
2592 case SERVICE_FINAL_SIGTERM:
2593 case SERVICE_FINAL_SIGKILL:
2594 if (main_pid_good(s) <= 0)
2595 service_enter_dead(s, f, true);
2599 assert_not_reached("Uh, control process died at wrong time.");
2604 /* Notify clients about changed exit status */
2605 unit_add_to_dbus_queue(u);
2607 /* We got one SIGCHLD for the service, let's watch all
2608 * processes that are now running of the service, and watch
2609 * that. Among the PIDs we then watch will be children
2610 * reassigned to us, which hopefully allows us to identify
2611 * when all children are gone */
2612 unit_tidy_watch_pids(u, s->main_pid, s->control_pid);
2613 unit_watch_all_pids(u);
2615 /* If the PID set is empty now, then let's finish this off */
2616 if (set_isempty(u->pids))
2617 service_notify_cgroup_empty_event(u);
2620 static int service_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata) {
2621 Service *s = SERVICE(userdata);
2624 assert(source == s->timer_event_source);
2628 case SERVICE_START_PRE:
2630 log_unit_warning(UNIT(s)->id, "%s %s operation timed out. Terminating.", UNIT(s)->id, s->state == SERVICE_START ? "start" : "start-pre");
2631 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2634 case SERVICE_START_POST:
2635 log_unit_warning(UNIT(s)->id, "%s start-post operation timed out. Stopping.", UNIT(s)->id);
2636 service_enter_stop(s, SERVICE_FAILURE_TIMEOUT);
2639 case SERVICE_RELOAD:
2640 log_unit_warning(UNIT(s)->id, "%s reload operation timed out. Stopping.", UNIT(s)->id);
2641 s->reload_result = SERVICE_FAILURE_TIMEOUT;
2642 service_enter_running(s, SERVICE_SUCCESS);
2646 log_unit_warning(UNIT(s)->id, "%s stopping timed out. Terminating.", UNIT(s)->id);
2647 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2650 case SERVICE_STOP_SIGABRT:
2651 log_unit_warning(UNIT(s)->id,
2652 "%s stop-sigabrt timed out. Terminating.", UNIT(s)->id);
2653 service_enter_signal(s, SERVICE_STOP_SIGTERM, s->result);
2656 case SERVICE_STOP_SIGTERM:
2657 if (s->kill_context.send_sigkill) {
2658 log_unit_warning(UNIT(s)->id, "%s stop-sigterm timed out. Killing.", UNIT(s)->id);
2659 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_TIMEOUT);
2661 log_unit_warning(UNIT(s)->id, "%s stop-sigterm timed out. Skipping SIGKILL.", UNIT(s)->id);
2662 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
2667 case SERVICE_STOP_SIGKILL:
2668 /* Uh, we sent a SIGKILL and it is still not gone?
2669 * Must be something we cannot kill, so let's just be
2670 * weirded out and continue */
2672 log_unit_warning(UNIT(s)->id, "%s still around after SIGKILL. Ignoring.", UNIT(s)->id);
2673 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
2676 case SERVICE_STOP_POST:
2677 log_unit_warning(UNIT(s)->id, "%s stop-post timed out. Terminating.", UNIT(s)->id);
2678 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2681 case SERVICE_FINAL_SIGTERM:
2682 if (s->kill_context.send_sigkill) {
2683 log_unit_warning(UNIT(s)->id, "%s stop-final-sigterm timed out. Killing.", UNIT(s)->id);
2684 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_FAILURE_TIMEOUT);
2686 log_unit_warning(UNIT(s)->id, "%s stop-final-sigterm timed out. Skipping SIGKILL. Entering failed mode.", UNIT(s)->id);
2687 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, false);
2692 case SERVICE_FINAL_SIGKILL:
2693 log_unit_warning(UNIT(s)->id, "%s still around after final SIGKILL. Entering failed mode.", UNIT(s)->id);
2694 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, true);
2697 case SERVICE_AUTO_RESTART:
2698 log_unit_info(UNIT(s)->id,
2699 s->restart_usec > 0 ?
2700 "%s holdoff time over, scheduling restart." :
2701 "%s has no holdoff time, scheduling restart.",
2703 service_enter_restart(s);
2707 assert_not_reached("Timeout at wrong time.");
2713 static int service_dispatch_watchdog(sd_event_source *source, usec_t usec, void *userdata) {
2714 Service *s = SERVICE(userdata);
2715 char t[FORMAT_TIMESPAN_MAX];
2718 assert(source == s->watchdog_event_source);
2720 log_unit_error(UNIT(s)->id, "%s watchdog timeout (limit %s)!", UNIT(s)->id,
2721 format_timespan(t, sizeof(t), s->watchdog_usec, 1));
2723 service_enter_signal(s, SERVICE_STOP_SIGABRT, SERVICE_FAILURE_WATCHDOG);
2728 static void service_notify_message(Unit *u, pid_t pid, char **tags, FDSet *fds) {
2729 Service *s = SERVICE(u);
2730 _cleanup_free_ char *cc = NULL;
2731 bool notify_dbus = false;
2736 cc = strv_join(tags, ", ");
2737 log_unit_debug(u->id, "%s: Got notification message from PID "PID_FMT" (%s)",
2738 u->id, pid, isempty(cc) ? "n/a" : cc);
2740 if (s->notify_access == NOTIFY_NONE) {
2741 log_unit_warning(u->id, "%s: Got notification message from PID "PID_FMT", but reception is disabled.", u->id, pid);
2745 if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
2746 if (s->main_pid != 0)
2747 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);
2749 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);
2753 /* Interpret MAINPID= */
2754 e = strv_find_startswith(tags, "MAINPID=");
2755 if (e && IN_SET(s->state, SERVICE_START, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD)) {
2756 if (parse_pid(e, &pid) < 0)
2757 log_unit_warning(u->id, "Failed to parse MAINPID= field in notification message: %s", e);
2759 log_unit_debug(u->id, "%s: got MAINPID=%s", u->id, e);
2761 service_set_main_pid(s, pid);
2762 unit_watch_pid(UNIT(s), pid);
2767 /* Interpret RELOADING= */
2768 if (strv_find(tags, "RELOADING=1")) {
2770 log_unit_debug(u->id, "%s: got RELOADING=1", u->id);
2771 s->notify_state = NOTIFY_RELOADING;
2773 if (s->state == SERVICE_RUNNING)
2774 service_enter_reload_by_notify(s);
2779 /* Interpret READY= */
2780 if (strv_find(tags, "READY=1")) {
2782 log_unit_debug(u->id, "%s: got READY=1", u->id);
2783 s->notify_state = NOTIFY_READY;
2785 /* Type=notify services inform us about completed
2786 * initialization with READY=1 */
2787 if (s->type == SERVICE_NOTIFY && s->state == SERVICE_START)
2788 service_enter_start_post(s);
2790 /* Sending READY=1 while we are reloading informs us
2791 * that the reloading is complete */
2792 if (s->state == SERVICE_RELOAD && s->control_pid == 0)
2793 service_enter_running(s, SERVICE_SUCCESS);
2798 /* Interpret STOPPING= */
2799 if (strv_find(tags, "STOPPING=1")) {
2801 log_unit_debug(u->id, "%s: got STOPPING=1", u->id);
2802 s->notify_state = NOTIFY_STOPPING;
2804 if (s->state == SERVICE_RUNNING)
2805 service_enter_stop_by_notify(s);
2810 /* Interpret STATUS= */
2811 e = strv_find_startswith(tags, "STATUS=");
2813 _cleanup_free_ char *t = NULL;
2816 if (!utf8_is_valid(e))
2817 log_unit_warning(u->id, "Status message in notification is not UTF-8 clean.");
2819 log_unit_debug(u->id, "%s: got STATUS=%s", u->id, e);
2827 if (!streq_ptr(s->status_text, t)) {
2829 free(s->status_text);
2837 /* Interpret ERRNO= */
2838 e = strv_find_startswith(tags, "ERRNO=");
2842 if (safe_atoi(e, &status_errno) < 0 || status_errno < 0)
2843 log_unit_warning(u->id, "Failed to parse ERRNO= field in notification message: %s", e);
2845 log_unit_debug(u->id, "%s: got ERRNO=%s", u->id, e);
2847 if (s->status_errno != status_errno) {
2848 s->status_errno = status_errno;
2854 /* Interpret WATCHDOG= */
2855 if (strv_find(tags, "WATCHDOG=1")) {
2856 log_unit_debug(u->id, "%s: got WATCHDOG=1", u->id);
2857 service_reset_watchdog(s);
2860 /* Add the passed fds to the fd store */
2861 if (strv_find(tags, "FDSTORE=1")) {
2862 log_unit_debug(u->id, "%s: got FDSTORE=1", u->id);
2863 service_add_fd_store_set(s, fds);
2866 /* Notify clients about changed status or main pid */
2868 unit_add_to_dbus_queue(u);
2871 static int service_get_timeout(Unit *u, uint64_t *timeout) {
2872 Service *s = SERVICE(u);
2875 if (!s->timer_event_source)
2878 r = sd_event_source_get_time(s->timer_event_source, timeout);
2885 static void service_bus_name_owner_change(
2888 const char *old_owner,
2889 const char *new_owner) {
2891 Service *s = SERVICE(u);
2897 assert(streq(s->bus_name, name));
2898 assert(old_owner || new_owner);
2900 if (old_owner && new_owner)
2901 log_unit_debug(u->id, "%s's D-Bus name %s changed owner from %s to %s", u->id, name, old_owner, new_owner);
2903 log_unit_debug(u->id, "%s's D-Bus name %s no longer registered by %s", u->id, name, old_owner);
2905 log_unit_debug(u->id, "%s's D-Bus name %s now registered by %s", u->id, name, new_owner);
2907 s->bus_name_good = !!new_owner;
2909 if (s->type == SERVICE_DBUS) {
2911 /* service_enter_running() will figure out what to
2913 if (s->state == SERVICE_RUNNING)
2914 service_enter_running(s, SERVICE_SUCCESS);
2915 else if (s->state == SERVICE_START && new_owner)
2916 service_enter_start_post(s);
2918 } else if (new_owner &&
2920 (s->state == SERVICE_START ||
2921 s->state == SERVICE_START_POST ||
2922 s->state == SERVICE_RUNNING ||
2923 s->state == SERVICE_RELOAD)) {
2925 _cleanup_bus_creds_unref_ sd_bus_creds *creds = NULL;
2928 /* Try to acquire PID from bus service */
2930 r = sd_bus_get_name_creds(u->manager->api_bus, name, SD_BUS_CREDS_PID, &creds);
2932 r = sd_bus_creds_get_pid(creds, &pid);
2934 log_unit_debug(u->id, "%s's D-Bus name %s is now owned by process %u", u->id, name, (unsigned) pid);
2936 service_set_main_pid(s, pid);
2937 unit_watch_pid(UNIT(s), pid);
2942 int service_set_socket_fd(Service *s, int fd, Socket *sock, bool selinux_context_net) {
2943 _cleanup_free_ char *peer = NULL;
2949 /* This is called by the socket code when instantiating a new
2950 * service for a stream socket and the socket needs to be
2953 if (UNIT(s)->load_state != UNIT_LOADED)
2956 if (s->socket_fd >= 0)
2959 if (s->state != SERVICE_DEAD)
2962 if (getpeername_pretty(fd, &peer) >= 0) {
2964 if (UNIT(s)->description) {
2965 _cleanup_free_ char *a;
2967 a = strjoin(UNIT(s)->description, " (", peer, ")", NULL);
2971 r = unit_set_description(UNIT(s), a);
2973 r = unit_set_description(UNIT(s), peer);
2980 s->socket_fd_selinux_context_net = selinux_context_net;
2982 unit_ref_set(&s->accept_socket, UNIT(sock));
2984 return unit_add_two_dependencies(UNIT(sock), UNIT_BEFORE, UNIT_TRIGGERS, UNIT(s), false);
2987 static void service_reset_failed(Unit *u) {
2988 Service *s = SERVICE(u);
2992 if (s->state == SERVICE_FAILED)
2993 service_set_state(s, SERVICE_DEAD);
2995 s->result = SERVICE_SUCCESS;
2996 s->reload_result = SERVICE_SUCCESS;
2998 RATELIMIT_RESET(s->start_limit);
3001 static int service_kill(Unit *u, KillWho who, int signo, sd_bus_error *error) {
3002 Service *s = SERVICE(u);
3004 return unit_kill_common(u, who, signo, s->main_pid, s->control_pid, error);
3007 static const char* const service_state_table[_SERVICE_STATE_MAX] = {
3008 [SERVICE_DEAD] = "dead",
3009 [SERVICE_START_PRE] = "start-pre",
3010 [SERVICE_START] = "start",
3011 [SERVICE_START_POST] = "start-post",
3012 [SERVICE_RUNNING] = "running",
3013 [SERVICE_EXITED] = "exited",
3014 [SERVICE_RELOAD] = "reload",
3015 [SERVICE_STOP] = "stop",
3016 [SERVICE_STOP_SIGABRT] = "stop-sigabrt",
3017 [SERVICE_STOP_SIGTERM] = "stop-sigterm",
3018 [SERVICE_STOP_SIGKILL] = "stop-sigkill",
3019 [SERVICE_STOP_POST] = "stop-post",
3020 [SERVICE_FINAL_SIGTERM] = "final-sigterm",
3021 [SERVICE_FINAL_SIGKILL] = "final-sigkill",
3022 [SERVICE_FAILED] = "failed",
3023 [SERVICE_AUTO_RESTART] = "auto-restart",
3026 DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
3028 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
3029 [SERVICE_RESTART_NO] = "no",
3030 [SERVICE_RESTART_ON_SUCCESS] = "on-success",
3031 [SERVICE_RESTART_ON_FAILURE] = "on-failure",
3032 [SERVICE_RESTART_ON_ABNORMAL] = "on-abnormal",
3033 [SERVICE_RESTART_ON_WATCHDOG] = "on-watchdog",
3034 [SERVICE_RESTART_ON_ABORT] = "on-abort",
3035 [SERVICE_RESTART_ALWAYS] = "always",
3038 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
3040 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
3041 [SERVICE_SIMPLE] = "simple",
3042 [SERVICE_FORKING] = "forking",
3043 [SERVICE_ONESHOT] = "oneshot",
3044 [SERVICE_DBUS] = "dbus",
3045 [SERVICE_NOTIFY] = "notify",
3046 [SERVICE_IDLE] = "idle"
3049 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
3051 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
3052 [SERVICE_EXEC_START_PRE] = "ExecStartPre",
3053 [SERVICE_EXEC_START] = "ExecStart",
3054 [SERVICE_EXEC_START_POST] = "ExecStartPost",
3055 [SERVICE_EXEC_RELOAD] = "ExecReload",
3056 [SERVICE_EXEC_STOP] = "ExecStop",
3057 [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
3060 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
3062 static const char* const notify_access_table[_NOTIFY_ACCESS_MAX] = {
3063 [NOTIFY_NONE] = "none",
3064 [NOTIFY_MAIN] = "main",
3065 [NOTIFY_ALL] = "all"
3068 DEFINE_STRING_TABLE_LOOKUP(notify_access, NotifyAccess);
3070 static const char* const notify_state_table[_NOTIFY_STATE_MAX] = {
3071 [NOTIFY_UNKNOWN] = "unknown",
3072 [NOTIFY_READY] = "ready",
3073 [NOTIFY_RELOADING] = "reloading",
3074 [NOTIFY_STOPPING] = "stopping",
3077 DEFINE_STRING_TABLE_LOOKUP(notify_state, NotifyState);
3079 static const char* const service_result_table[_SERVICE_RESULT_MAX] = {
3080 [SERVICE_SUCCESS] = "success",
3081 [SERVICE_FAILURE_RESOURCES] = "resources",
3082 [SERVICE_FAILURE_TIMEOUT] = "timeout",
3083 [SERVICE_FAILURE_EXIT_CODE] = "exit-code",
3084 [SERVICE_FAILURE_SIGNAL] = "signal",
3085 [SERVICE_FAILURE_CORE_DUMP] = "core-dump",
3086 [SERVICE_FAILURE_WATCHDOG] = "watchdog",
3087 [SERVICE_FAILURE_START_LIMIT] = "start-limit"
3090 DEFINE_STRING_TABLE_LOOKUP(service_result, ServiceResult);
3092 const UnitVTable service_vtable = {
3093 .object_size = sizeof(Service),
3094 .exec_context_offset = offsetof(Service, exec_context),
3095 .cgroup_context_offset = offsetof(Service, cgroup_context),
3096 .kill_context_offset = offsetof(Service, kill_context),
3097 .exec_runtime_offset = offsetof(Service, exec_runtime),
3103 .private_section = "Service",
3105 .init = service_init,
3106 .done = service_done,
3107 .load = service_load,
3108 .release_resources = service_release_resources,
3110 .coldplug = service_coldplug,
3112 .dump = service_dump,
3114 .start = service_start,
3115 .stop = service_stop,
3116 .reload = service_reload,
3118 .can_reload = service_can_reload,
3120 .kill = service_kill,
3122 .serialize = service_serialize,
3123 .deserialize_item = service_deserialize_item,
3125 .active_state = service_active_state,
3126 .sub_state_to_string = service_sub_state_to_string,
3128 .check_gc = service_check_gc,
3129 .check_snapshot = service_check_snapshot,
3131 .sigchld_event = service_sigchld_event,
3133 .reset_failed = service_reset_failed,
3135 .notify_cgroup_empty = service_notify_cgroup_empty_event,
3136 .notify_message = service_notify_message,
3138 .bus_name_owner_change = service_bus_name_owner_change,
3140 .bus_interface = "org.freedesktop.systemd1.Service",
3141 .bus_vtable = bus_service_vtable,
3142 .bus_set_property = bus_service_set_property,
3143 .bus_commit_properties = bus_service_commit_properties,
3145 .get_timeout = service_get_timeout,
3146 .can_transient = true,
3148 .status_message_formats = {
3149 .starting_stopping = {
3150 [0] = "Starting %s...",
3151 [1] = "Stopping %s...",
3153 .finished_start_job = {
3154 [JOB_DONE] = "Started %s.",
3155 [JOB_FAILED] = "Failed to start %s.",
3156 [JOB_DEPENDENCY] = "Dependency failed for %s.",
3157 [JOB_TIMEOUT] = "Timed out starting %s.",
3159 .finished_stop_job = {
3160 [JOB_DONE] = "Stopped %s.",
3161 [JOB_FAILED] = "Stopped (with error) %s.",
3162 [JOB_TIMEOUT] = "Timed out stopping %s.",