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/>.
26 #include <sys/reboot.h>
27 #include <linux/reboot.h>
28 #include <sys/syscall.h>
34 #include "load-fragment.h"
35 #include "load-dropin.h"
38 #include "unit-name.h"
39 #include "unit-printf.h"
40 #include "dbus-service.h"
42 #include "exit-status.h"
44 #include "path-util.h"
49 #include "bus-error.h"
52 static const UnitActiveState state_translation_table[_SERVICE_STATE_MAX] = {
53 [SERVICE_DEAD] = UNIT_INACTIVE,
54 [SERVICE_START_PRE] = UNIT_ACTIVATING,
55 [SERVICE_START] = UNIT_ACTIVATING,
56 [SERVICE_START_POST] = UNIT_ACTIVATING,
57 [SERVICE_RUNNING] = UNIT_ACTIVE,
58 [SERVICE_EXITED] = UNIT_ACTIVE,
59 [SERVICE_RELOAD] = UNIT_RELOADING,
60 [SERVICE_STOP] = UNIT_DEACTIVATING,
61 [SERVICE_STOP_SIGTERM] = UNIT_DEACTIVATING,
62 [SERVICE_STOP_SIGKILL] = UNIT_DEACTIVATING,
63 [SERVICE_STOP_POST] = UNIT_DEACTIVATING,
64 [SERVICE_FINAL_SIGTERM] = UNIT_DEACTIVATING,
65 [SERVICE_FINAL_SIGKILL] = UNIT_DEACTIVATING,
66 [SERVICE_FAILED] = UNIT_FAILED,
67 [SERVICE_AUTO_RESTART] = UNIT_ACTIVATING
70 /* For Type=idle we never want to delay any other jobs, hence we
71 * consider idle jobs active as soon as we start working on them */
72 static const UnitActiveState state_translation_table_idle[_SERVICE_STATE_MAX] = {
73 [SERVICE_DEAD] = UNIT_INACTIVE,
74 [SERVICE_START_PRE] = UNIT_ACTIVE,
75 [SERVICE_START] = UNIT_ACTIVE,
76 [SERVICE_START_POST] = UNIT_ACTIVE,
77 [SERVICE_RUNNING] = UNIT_ACTIVE,
78 [SERVICE_EXITED] = UNIT_ACTIVE,
79 [SERVICE_RELOAD] = UNIT_RELOADING,
80 [SERVICE_STOP] = 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->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_debug_unit(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_warning_unit(UNIT(s)->id, "%s: Supervising process "PID_FMT" which is not our child. We'll most likely not notice when it exits.", UNIT(s)->id, pid);
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_warning_unit(UNIT(s)->id, "%s failed to reset watchdog timer: %s", UNIT(s)->id, strerror(-r));
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_warning_unit(UNIT(s)->id, "%s failed to add watchdog timer: %s", UNIT(s)->id, strerror(-r));
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_warning_unit(UNIT(s)->id, "%s failed to install watchdog timer: %s", UNIT(s)->id, strerror(-r));
237 static void service_reset_watchdog(Service *s) {
240 dual_timestamp_get(&s->watchdog_timestamp);
241 service_start_watchdog(s);
244 static void service_done(Unit *u) {
245 Service *s = SERVICE(u);
252 free(s->status_text);
253 s->status_text = NULL;
256 s->reboot_arg = NULL;
258 s->exec_runtime = exec_runtime_unref(s->exec_runtime);
259 exec_command_free_array(s->exec_command, _SERVICE_EXEC_COMMAND_MAX);
260 s->control_command = NULL;
261 s->main_command = NULL;
263 exit_status_set_free(&s->restart_prevent_status);
264 exit_status_set_free(&s->restart_force_status);
265 exit_status_set_free(&s->success_status);
267 /* This will leak a process, but at least no memory or any of
269 service_unwatch_main_pid(s);
270 service_unwatch_control_pid(s);
271 service_unwatch_pid_file(s);
274 unit_unwatch_bus_name(u, s->bus_name);
279 service_close_socket_fd(s);
280 service_connection_unref(s);
282 unit_ref_unset(&s->accept_socket);
284 service_stop_watchdog(s);
286 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
289 static int service_arm_timer(Service *s, usec_t usec) {
294 if (s->timer_event_source) {
295 r = sd_event_source_set_time(s->timer_event_source, now(CLOCK_MONOTONIC) + usec);
299 return sd_event_source_set_enabled(s->timer_event_source, SD_EVENT_ONESHOT);
302 return sd_event_add_time(
303 UNIT(s)->manager->event,
304 &s->timer_event_source,
306 now(CLOCK_MONOTONIC) + usec, 0,
307 service_dispatch_timer, s);
310 static int service_verify(Service *s) {
313 if (UNIT(s)->load_state != UNIT_LOADED)
316 if (!s->exec_command[SERVICE_EXEC_START]) {
317 log_error_unit(UNIT(s)->id, "%s lacks ExecStart setting. Refusing.", UNIT(s)->id);
321 if (s->type != SERVICE_ONESHOT &&
322 s->exec_command[SERVICE_EXEC_START]->command_next) {
323 log_error_unit(UNIT(s)->id, "%s has more than one ExecStart setting, which is only allowed for Type=oneshot services. Refusing.", UNIT(s)->id);
327 if (s->type == SERVICE_ONESHOT && s->restart != SERVICE_RESTART_NO) {
328 log_error_unit(UNIT(s)->id, "%s has Restart= setting other than no, which isn't allowed for Type=oneshot services. Refusing.", UNIT(s)->id);
332 if (s->type == SERVICE_ONESHOT && !exit_status_set_is_empty(&s->restart_force_status)) {
333 log_error_unit(UNIT(s)->id, "%s has RestartForceStatus= set, which isn't allowed for Type=oneshot services. Refusing.", UNIT(s)->id);
337 if (s->type == SERVICE_DBUS && !s->bus_name) {
338 log_error_unit(UNIT(s)->id, "%s is of type D-Bus but no D-Bus service name has been specified. Refusing.", UNIT(s)->id);
342 if (s->bus_name && s->type != SERVICE_DBUS)
343 log_warning_unit(UNIT(s)->id, "%s has a D-Bus service name specified, but is not of type dbus. Ignoring.", UNIT(s)->id);
345 if (s->exec_context.pam_name && !(s->kill_context.kill_mode == KILL_CONTROL_GROUP || s->kill_context.kill_mode == KILL_MIXED)) {
346 log_error_unit(UNIT(s)->id, "%s has PAM enabled. Kill mode must be set to 'control-group' or 'mixed'. Refusing.", UNIT(s)->id);
353 static int service_add_default_dependencies(Service *s) {
358 /* Add a number of automatic dependencies useful for the
359 * majority of services. */
361 /* First, pull in base system */
362 r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_BASIC_TARGET, NULL, true);
366 /* Second, activate normal shutdown */
367 r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true);
371 static void service_fix_output(Service *s) {
374 /* If nothing has been explicitly configured, patch default
375 * output in. If input is socket/tty we avoid this however,
376 * since in that case we want output to default to the same
377 * place as we read input from. */
379 if (s->exec_context.std_error == EXEC_OUTPUT_INHERIT &&
380 s->exec_context.std_output == EXEC_OUTPUT_INHERIT &&
381 s->exec_context.std_input == EXEC_INPUT_NULL)
382 s->exec_context.std_error = UNIT(s)->manager->default_std_error;
384 if (s->exec_context.std_output == EXEC_OUTPUT_INHERIT &&
385 s->exec_context.std_input == EXEC_INPUT_NULL)
386 s->exec_context.std_output = UNIT(s)->manager->default_std_output;
389 static int service_load(Unit *u) {
390 Service *s = SERVICE(u);
395 /* Load a .service file */
396 r = unit_load_fragment(u);
400 /* Still nothing found? Then let's give up */
401 if (u->load_state == UNIT_STUB)
404 /* This is a new unit? Then let's add in some extras */
405 if (u->load_state == UNIT_LOADED) {
407 /* We were able to load something, then let's add in
408 * the dropin directories. */
409 r = unit_load_dropin(u);
413 if (s->type == _SERVICE_TYPE_INVALID)
414 s->type = s->bus_name ? SERVICE_DBUS : SERVICE_SIMPLE;
416 /* Oneshot services have disabled start timeout by default */
417 if (s->type == SERVICE_ONESHOT && !s->start_timeout_defined)
418 s->timeout_start_usec = 0;
420 service_fix_output(s);
422 r = unit_patch_contexts(u);
426 r = unit_add_exec_dependencies(u, &s->exec_context);
430 r = unit_add_default_slice(u, &s->cgroup_context);
434 if (s->type == SERVICE_NOTIFY && s->notify_access == NOTIFY_NONE)
435 s->notify_access = NOTIFY_MAIN;
437 if (s->watchdog_usec > 0 && s->notify_access == NOTIFY_NONE)
438 s->notify_access = NOTIFY_MAIN;
441 r = unit_watch_bus_name(u, s->bus_name);
446 if (u->default_dependencies) {
447 r = service_add_default_dependencies(s);
454 return service_verify(s);
457 static void service_dump(Unit *u, FILE *f, const char *prefix) {
458 ServiceExecCommand c;
459 Service *s = SERVICE(u);
464 prefix = strempty(prefix);
465 prefix2 = strappenda(prefix, "\t");
468 "%sService State: %s\n"
470 "%sReload Result: %s\n"
471 "%sPermissionsStartOnly: %s\n"
472 "%sRootDirectoryStartOnly: %s\n"
473 "%sRemainAfterExit: %s\n"
474 "%sGuessMainPID: %s\n"
477 "%sNotifyAccess: %s\n"
478 "%sNotifyState: %s\n",
479 prefix, service_state_to_string(s->state),
480 prefix, service_result_to_string(s->result),
481 prefix, service_result_to_string(s->reload_result),
482 prefix, yes_no(s->permissions_start_only),
483 prefix, yes_no(s->root_directory_start_only),
484 prefix, yes_no(s->remain_after_exit),
485 prefix, yes_no(s->guess_main_pid),
486 prefix, service_type_to_string(s->type),
487 prefix, service_restart_to_string(s->restart),
488 prefix, notify_access_to_string(s->notify_access),
489 prefix, notify_state_to_string(s->notify_state));
491 if (s->control_pid > 0)
493 "%sControl PID: "PID_FMT"\n",
494 prefix, s->control_pid);
498 "%sMain PID: "PID_FMT"\n"
499 "%sMain PID Known: %s\n"
500 "%sMain PID Alien: %s\n",
502 prefix, yes_no(s->main_pid_known),
503 prefix, yes_no(s->main_pid_alien));
508 prefix, s->pid_file);
513 "%sBus Name Good: %s\n",
515 prefix, yes_no(s->bus_name_good));
517 kill_context_dump(&s->kill_context, f, prefix);
518 exec_context_dump(&s->exec_context, f, prefix);
520 for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
522 if (!s->exec_command[c])
525 fprintf(f, "%s-> %s:\n",
526 prefix, service_exec_command_to_string(c));
528 exec_command_dump_list(s->exec_command[c], f, prefix2);
531 #ifdef HAVE_SYSV_COMPAT
532 if (s->sysv_start_priority >= 0)
534 "%sSysVStartPriority: %i\n",
535 prefix, s->sysv_start_priority);
539 fprintf(f, "%sStatus Text: %s\n",
540 prefix, s->status_text);
543 static int service_load_pid_file(Service *s, bool may_warn) {
544 _cleanup_free_ char *k = NULL;
553 r = read_one_line_file(s->pid_file, &k);
556 log_info_unit(UNIT(s)->id, "PID file %s not readable (yet?) after %s.", s->pid_file, service_state_to_string(s->state));
560 r = parse_pid(k, &pid);
563 log_info_unit(UNIT(s)->id, "Failed to read PID from file %s: %s", s->pid_file, strerror(-r));
567 if (!pid_is_alive(pid)) {
569 log_info_unit(UNIT(s)->id, "PID "PID_FMT" read from file %s does not exist or is a zombie.", pid, s->pid_file);
573 if (s->main_pid_known) {
574 if (pid == s->main_pid)
577 log_debug_unit(UNIT(s)->id, "Main PID changing: "PID_FMT" -> "PID_FMT, s->main_pid, pid);
579 service_unwatch_main_pid(s);
580 s->main_pid_known = false;
582 log_debug_unit(UNIT(s)->id, "Main PID loaded: "PID_FMT, pid);
584 r = service_set_main_pid(s, pid);
588 r = unit_watch_pid(UNIT(s), pid);
590 /* FIXME: we need to do something here */
591 log_warning_unit(UNIT(s)->id, "Failed to watch PID "PID_FMT" from service %s", pid, UNIT(s)->id);
598 static int service_search_main_pid(Service *s) {
604 /* If we know it anyway, don't ever fallback to unreliable
606 if (s->main_pid_known)
609 if (!s->guess_main_pid)
612 assert(s->main_pid <= 0);
614 pid = unit_search_main_pid(UNIT(s));
618 log_debug_unit(UNIT(s)->id, "Main PID guessed: "PID_FMT, pid);
619 r = service_set_main_pid(s, pid);
623 r = unit_watch_pid(UNIT(s), pid);
625 /* FIXME: we need to do something here */
626 log_warning_unit(UNIT(s)->id, "Failed to watch PID "PID_FMT" from service %s", pid, UNIT(s)->id);
633 static void service_set_state(Service *s, ServiceState state) {
634 ServiceState old_state;
635 const UnitActiveState *table;
639 table = s->type == SERVICE_IDLE ? state_translation_table_idle : state_translation_table;
641 old_state = s->state;
644 service_unwatch_pid_file(s);
647 SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
649 SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL,
651 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL,
652 SERVICE_AUTO_RESTART))
653 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
656 SERVICE_START, SERVICE_START_POST,
657 SERVICE_RUNNING, SERVICE_RELOAD,
658 SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL,
660 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL)) {
661 service_unwatch_main_pid(s);
662 s->main_command = NULL;
666 SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
668 SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL,
670 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL)) {
671 service_unwatch_control_pid(s);
672 s->control_command = NULL;
673 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
676 if (IN_SET(state, SERVICE_DEAD, SERVICE_FAILED, SERVICE_AUTO_RESTART))
677 unit_unwatch_all_pids(UNIT(s));
680 SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
681 SERVICE_RUNNING, SERVICE_RELOAD,
682 SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
683 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL) &&
684 !(state == SERVICE_DEAD && UNIT(s)->job)) {
685 service_close_socket_fd(s);
686 service_connection_unref(s);
689 if (!IN_SET(state, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD))
690 service_stop_watchdog(s);
692 /* For the inactive states unit_notify() will trim the cgroup,
693 * but for exit we have to do that ourselves... */
694 if (state == SERVICE_EXITED && UNIT(s)->manager->n_reloading <= 0)
695 unit_destroy_cgroup(UNIT(s));
697 /* For remain_after_exit services, let's see if we can "release" the
698 * hold on the console, since unit_notify() only does that in case of
700 if (state == SERVICE_EXITED &&
701 s->remain_after_exit &&
702 UNIT(s)->manager->n_on_console > 0) {
706 ec = unit_get_exec_context(UNIT(s));
707 if (ec && exec_context_may_touch_console(ec)) {
708 Manager *m = UNIT(s)->manager;
711 if (m->n_on_console == 0)
712 /* unset no_console_output flag, since the console is free */
713 m->no_console_output = false;
717 if (old_state != state)
718 log_debug_unit(UNIT(s)->id, "%s changed %s -> %s", UNIT(s)->id, service_state_to_string(old_state), service_state_to_string(state));
720 unit_notify(UNIT(s), table[old_state], table[state], s->reload_result == SERVICE_SUCCESS);
721 s->reload_result = SERVICE_SUCCESS;
724 static int service_coldplug(Unit *u) {
725 Service *s = SERVICE(u);
729 assert(s->state == SERVICE_DEAD);
731 if (s->deserialized_state != s->state) {
733 if (IN_SET(s->deserialized_state,
734 SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
736 SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL,
738 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL)) {
742 k = IN_SET(s->deserialized_state, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST, SERVICE_RELOAD) ? s->timeout_start_usec : s->timeout_stop_usec;
744 /* For the start/stop timeouts 0 means off */
746 r = service_arm_timer(s, k);
752 if (s->deserialized_state == SERVICE_AUTO_RESTART) {
754 /* The restart timeouts 0 means immediately */
755 r = service_arm_timer(s, s->restart_usec);
760 if (pid_is_unwaited(s->main_pid) &&
761 ((s->deserialized_state == SERVICE_START && IN_SET(s->type, SERVICE_FORKING, SERVICE_DBUS, SERVICE_ONESHOT, SERVICE_NOTIFY)) ||
762 IN_SET(s->deserialized_state,
763 SERVICE_START, SERVICE_START_POST,
764 SERVICE_RUNNING, SERVICE_RELOAD,
765 SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL,
767 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL))) {
768 r = unit_watch_pid(UNIT(s), s->main_pid);
773 if (pid_is_unwaited(s->control_pid) &&
774 IN_SET(s->deserialized_state,
775 SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
777 SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL,
779 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL)) {
780 r = unit_watch_pid(UNIT(s), s->control_pid);
785 if (!IN_SET(s->deserialized_state, SERVICE_DEAD, SERVICE_FAILED, SERVICE_AUTO_RESTART))
786 unit_watch_all_pids(UNIT(s));
788 if (IN_SET(s->deserialized_state, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD))
789 service_start_watchdog(s);
791 service_set_state(s, s->deserialized_state);
797 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
808 if (s->socket_fd >= 0)
811 SET_FOREACH(u, UNIT(s)->dependencies[UNIT_TRIGGERED_BY], i) {
816 if (u->type != UNIT_SOCKET)
821 r = socket_collect_fds(sock, &cfds, &cn_fds);
834 t = new(int, rn_fds+cn_fds);
841 memcpy(t, rfds, rn_fds * sizeof(int));
842 memcpy(t+rn_fds, cfds, cn_fds * sizeof(int));
847 rn_fds = rn_fds+cn_fds;
862 static int service_spawn(
867 bool apply_permissions,
869 bool apply_tty_stdin,
870 bool set_notify_socket,
877 _cleanup_free_ int *fdsbuf = NULL;
878 unsigned n_fds = 0, n_env = 0;
879 _cleanup_strv_free_ char
880 **argv = NULL, **final_env = NULL, **our_env = NULL;
887 unit_realize_cgroup(UNIT(s));
889 r = unit_setup_exec_runtime(UNIT(s));
894 s->exec_context.std_input == EXEC_INPUT_SOCKET ||
895 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
896 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
898 if (s->socket_fd >= 0) {
902 r = service_collect_fds(s, &fdsbuf, &n_fds);
910 if (timeout && s->timeout_start_usec > 0) {
911 r = service_arm_timer(s, s->timeout_start_usec);
915 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
917 r = unit_full_printf_strv(UNIT(s), c->argv, &argv);
921 our_env = new0(char*, 4);
927 if (set_notify_socket)
928 if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=%s", UNIT(s)->manager->notify_socket) < 0) {
934 if (asprintf(our_env + n_env++, "MAINPID="PID_FMT, s->main_pid) < 0) {
939 if (UNIT(s)->manager->running_as != SYSTEMD_SYSTEM)
940 if (asprintf(our_env + n_env++, "MANAGERPID="PID_FMT, getpid()) < 0) {
945 final_env = strv_env_merge(2, UNIT(s)->manager->environment, our_env, NULL);
951 if (is_control && UNIT(s)->cgroup_path) {
952 path = strappenda(UNIT(s)->cgroup_path, "/control");
953 cg_create(SYSTEMD_CGROUP_CONTROLLER, path);
955 path = UNIT(s)->cgroup_path;
965 UNIT(s)->manager->confirm_spawn,
966 UNIT(s)->manager->cgroup_supported,
968 manager_get_runtime_prefix(UNIT(s)->manager),
971 s->type == SERVICE_IDLE ? UNIT(s)->manager->idle_pipe : NULL,
977 r = unit_watch_pid(UNIT(s), pid);
979 /* FIXME: we need to do something here */
988 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
993 static int main_pid_good(Service *s) {
996 /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
999 /* If we know the pid file, then lets just check if it is
1001 if (s->main_pid_known) {
1003 /* If it's an alien child let's check if it is still
1005 if (s->main_pid_alien && s->main_pid > 0)
1006 return pid_is_alive(s->main_pid);
1008 /* .. otherwise assume we'll get a SIGCHLD for it,
1009 * which we really should wait for to collect exit
1010 * status and code */
1011 return s->main_pid > 0;
1014 /* We don't know the pid */
1018 _pure_ static int control_pid_good(Service *s) {
1021 return s->control_pid > 0;
1024 static int cgroup_good(Service *s) {
1029 if (!UNIT(s)->cgroup_path)
1032 r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, UNIT(s)->cgroup_path, true);
1039 static int service_execute_action(Service *s, FailureAction action, const char *reason, bool log_action_none);
1041 static void service_enter_dead(Service *s, ServiceResult f, bool allow_restart) {
1045 if (f != SERVICE_SUCCESS)
1048 service_set_state(s, s->result != SERVICE_SUCCESS ? SERVICE_FAILED : SERVICE_DEAD);
1050 if (s->result != SERVICE_SUCCESS)
1051 service_execute_action(s, s->failure_action, "failed", false);
1053 if (allow_restart &&
1054 !s->forbid_restart &&
1055 (s->restart == SERVICE_RESTART_ALWAYS ||
1056 (s->restart == SERVICE_RESTART_ON_SUCCESS && s->result == SERVICE_SUCCESS) ||
1057 (s->restart == SERVICE_RESTART_ON_FAILURE && s->result != SERVICE_SUCCESS) ||
1058 (s->restart == SERVICE_RESTART_ON_ABNORMAL && !IN_SET(s->result, SERVICE_SUCCESS, SERVICE_FAILURE_EXIT_CODE)) ||
1059 (s->restart == SERVICE_RESTART_ON_WATCHDOG && s->result == SERVICE_FAILURE_WATCHDOG) ||
1060 (s->restart == SERVICE_RESTART_ON_ABORT && IN_SET(s->result, SERVICE_FAILURE_SIGNAL, SERVICE_FAILURE_CORE_DUMP)) ||
1061 (s->main_exec_status.code == CLD_EXITED && set_contains(s->restart_force_status.status, INT_TO_PTR(s->main_exec_status.status))) ||
1062 (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)))) &&
1063 (s->main_exec_status.code != CLD_EXITED || !set_contains(s->restart_prevent_status.status, INT_TO_PTR(s->main_exec_status.status))) &&
1064 (!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)))) {
1066 r = service_arm_timer(s, s->restart_usec);
1070 service_set_state(s, SERVICE_AUTO_RESTART);
1073 s->forbid_restart = false;
1075 /* We want fresh tmpdirs in case service is started again immediately */
1076 exec_runtime_destroy(s->exec_runtime);
1077 s->exec_runtime = exec_runtime_unref(s->exec_runtime);
1079 /* Also, remove the runtime directory in */
1080 exec_context_destroy_runtime_directory(&s->exec_context, manager_get_runtime_prefix(UNIT(s)->manager));
1082 /* Try to delete the pid file. At this point it will be
1083 * out-of-date, and some software might be confused by it, so
1084 * let's remove it. */
1086 unlink_noerrno(s->pid_file);
1091 log_warning_unit(UNIT(s)->id, "%s failed to run install restart timer: %s", UNIT(s)->id, strerror(-r));
1092 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, false);
1095 static void service_enter_stop_post(Service *s, ServiceResult f) {
1099 if (f != SERVICE_SUCCESS)
1102 service_unwatch_control_pid(s);
1103 unit_watch_all_pids(UNIT(s));
1105 s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST];
1106 if (s->control_command) {
1107 s->control_command_id = SERVICE_EXEC_STOP_POST;
1109 r = service_spawn(s,
1113 !s->permissions_start_only,
1114 !s->root_directory_start_only,
1122 service_set_state(s, SERVICE_STOP_POST);
1124 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_SUCCESS);
1129 log_warning_unit(UNIT(s)->id, "%s failed to run 'stop-post' task: %s", UNIT(s)->id, strerror(-r));
1130 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
1133 static void service_enter_signal(Service *s, ServiceState state, ServiceResult f) {
1138 if (f != SERVICE_SUCCESS)
1141 unit_watch_all_pids(UNIT(s));
1143 r = unit_kill_context(
1146 state != SERVICE_STOP_SIGTERM && state != SERVICE_FINAL_SIGTERM,
1155 if (s->timeout_stop_usec > 0) {
1156 r = service_arm_timer(s, s->timeout_stop_usec);
1161 service_set_state(s, state);
1162 } else if (state == SERVICE_STOP_SIGTERM)
1163 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_SUCCESS);
1164 else if (state == SERVICE_STOP_SIGKILL)
1165 service_enter_stop_post(s, SERVICE_SUCCESS);
1166 else if (state == SERVICE_FINAL_SIGTERM)
1167 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_SUCCESS);
1169 service_enter_dead(s, SERVICE_SUCCESS, true);
1174 log_warning_unit(UNIT(s)->id, "%s failed to kill processes: %s", UNIT(s)->id, strerror(-r));
1176 if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1177 service_enter_stop_post(s, SERVICE_FAILURE_RESOURCES);
1179 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
1182 static void service_enter_stop_by_notify(Service *s) {
1185 unit_watch_all_pids(UNIT(s));
1187 if (s->timeout_stop_usec > 0)
1188 service_arm_timer(s, s->timeout_stop_usec);
1190 service_set_state(s, SERVICE_STOP);
1193 static void service_enter_stop(Service *s, ServiceResult f) {
1198 if (f != SERVICE_SUCCESS)
1201 service_unwatch_control_pid(s);
1202 unit_watch_all_pids(UNIT(s));
1204 s->control_command = s->exec_command[SERVICE_EXEC_STOP];
1205 if (s->control_command) {
1206 s->control_command_id = SERVICE_EXEC_STOP;
1208 r = service_spawn(s,
1212 !s->permissions_start_only,
1213 !s->root_directory_start_only,
1221 service_set_state(s, SERVICE_STOP);
1223 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
1228 log_warning_unit(UNIT(s)->id, "%s failed to run 'stop' task: %s", UNIT(s)->id, strerror(-r));
1229 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
1232 static void service_enter_running(Service *s, ServiceResult f) {
1233 int main_pid_ok, cgroup_ok;
1236 if (f != SERVICE_SUCCESS)
1239 main_pid_ok = main_pid_good(s);
1240 cgroup_ok = cgroup_good(s);
1242 if ((main_pid_ok > 0 || (main_pid_ok < 0 && cgroup_ok != 0)) &&
1243 (s->bus_name_good || s->type != SERVICE_DBUS)) {
1245 /* If there are any queued up sd_notify()
1246 * notifications, process them now */
1247 if (s->notify_state == NOTIFY_RELOADING)
1248 service_enter_reload_by_notify(s);
1249 else if (s->notify_state == NOTIFY_STOPPING)
1250 service_enter_stop_by_notify(s);
1252 service_set_state(s, SERVICE_RUNNING);
1254 } else if (s->remain_after_exit)
1255 service_set_state(s, SERVICE_EXITED);
1257 service_enter_stop(s, SERVICE_SUCCESS);
1260 static void service_enter_start_post(Service *s) {
1264 service_unwatch_control_pid(s);
1265 service_reset_watchdog(s);
1267 s->control_command = s->exec_command[SERVICE_EXEC_START_POST];
1268 if (s->control_command) {
1269 s->control_command_id = SERVICE_EXEC_START_POST;
1271 r = service_spawn(s,
1275 !s->permissions_start_only,
1276 !s->root_directory_start_only,
1284 service_set_state(s, SERVICE_START_POST);
1286 service_enter_running(s, SERVICE_SUCCESS);
1291 log_warning_unit(UNIT(s)->id, "%s failed to run 'start-post' task: %s", UNIT(s)->id, strerror(-r));
1292 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
1295 static void service_kill_control_processes(Service *s) {
1298 if (!UNIT(s)->cgroup_path)
1301 p = strappenda(UNIT(s)->cgroup_path, "/control");
1302 cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, p, SIGKILL, true, true, true, NULL);
1305 static void service_enter_start(Service *s) {
1312 assert(s->exec_command[SERVICE_EXEC_START]);
1313 assert(!s->exec_command[SERVICE_EXEC_START]->command_next || s->type == SERVICE_ONESHOT);
1315 service_unwatch_control_pid(s);
1316 service_unwatch_main_pid(s);
1318 /* We want to ensure that nobody leaks processes from
1319 * START_PRE here, so let's go on a killing spree, People
1320 * should not spawn long running processes from START_PRE. */
1321 service_kill_control_processes(s);
1323 if (s->type == SERVICE_FORKING) {
1324 s->control_command_id = SERVICE_EXEC_START;
1325 c = s->control_command = s->exec_command[SERVICE_EXEC_START];
1327 s->main_command = NULL;
1329 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1330 s->control_command = NULL;
1332 c = s->main_command = s->exec_command[SERVICE_EXEC_START];
1335 r = service_spawn(s,
1337 s->type == SERVICE_FORKING || s->type == SERVICE_DBUS ||
1338 s->type == SERVICE_NOTIFY || s->type == SERVICE_ONESHOT,
1343 s->notify_access != NOTIFY_NONE,
1349 if (s->type == SERVICE_SIMPLE || s->type == SERVICE_IDLE) {
1350 /* For simple services we immediately start
1351 * the START_POST binaries. */
1353 service_set_main_pid(s, pid);
1354 service_enter_start_post(s);
1356 } else if (s->type == SERVICE_FORKING) {
1358 /* For forking services we wait until the start
1359 * process exited. */
1361 s->control_pid = pid;
1362 service_set_state(s, SERVICE_START);
1364 } else if (s->type == SERVICE_ONESHOT ||
1365 s->type == SERVICE_DBUS ||
1366 s->type == SERVICE_NOTIFY) {
1368 /* For oneshot services we wait until the start
1369 * process exited, too, but it is our main process. */
1371 /* For D-Bus services we know the main pid right away,
1372 * but wait for the bus name to appear on the
1373 * bus. Notify services are similar. */
1375 service_set_main_pid(s, pid);
1376 service_set_state(s, SERVICE_START);
1378 assert_not_reached("Unknown service type");
1383 log_warning_unit(UNIT(s)->id, "%s failed to run 'start' task: %s", UNIT(s)->id, strerror(-r));
1384 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
1387 static void service_enter_start_pre(Service *s) {
1392 service_unwatch_control_pid(s);
1394 s->control_command = s->exec_command[SERVICE_EXEC_START_PRE];
1395 if (s->control_command) {
1396 /* Before we start anything, let's clear up what might
1397 * be left from previous runs. */
1398 service_kill_control_processes(s);
1400 s->control_command_id = SERVICE_EXEC_START_PRE;
1402 r = service_spawn(s,
1406 !s->permissions_start_only,
1407 !s->root_directory_start_only,
1415 service_set_state(s, SERVICE_START_PRE);
1417 service_enter_start(s);
1422 log_warning_unit(UNIT(s)->id, "%s failed to run 'start-pre' task: %s", UNIT(s)->id, strerror(-r));
1423 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
1426 static void service_enter_restart(Service *s) {
1427 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
1432 if (UNIT(s)->job && UNIT(s)->job->type == JOB_STOP) {
1433 /* Don't restart things if we are going down anyway */
1434 log_info_unit(UNIT(s)->id, "Stop job pending for unit, delaying automatic restart.");
1436 r = service_arm_timer(s, s->restart_usec);
1443 /* Any units that are bound to this service must also be
1444 * restarted. We use JOB_RESTART (instead of the more obvious
1445 * JOB_START) here so that those dependency jobs will be added
1447 r = manager_add_job(UNIT(s)->manager, JOB_RESTART, UNIT(s), JOB_FAIL, false, &error, NULL);
1451 /* Note that we stay in the SERVICE_AUTO_RESTART state here,
1452 * it will be canceled as part of the service_stop() call that
1453 * is executed as part of JOB_RESTART. */
1455 log_debug_unit(UNIT(s)->id, "%s scheduled restart job.", UNIT(s)->id);
1459 log_warning_unit(UNIT(s)->id, "%s failed to schedule restart job: %s", UNIT(s)->id, bus_error_message(&error, -r));
1460 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, false);
1463 static void service_enter_reload_by_notify(Service *s) {
1466 if (s->timeout_start_usec > 0)
1467 service_arm_timer(s, s->timeout_start_usec);
1469 service_set_state(s, SERVICE_RELOAD);
1472 static void service_enter_reload(Service *s) {
1477 service_unwatch_control_pid(s);
1479 s->control_command = s->exec_command[SERVICE_EXEC_RELOAD];
1480 if (s->control_command) {
1481 s->control_command_id = SERVICE_EXEC_RELOAD;
1483 r = service_spawn(s,
1487 !s->permissions_start_only,
1488 !s->root_directory_start_only,
1496 service_set_state(s, SERVICE_RELOAD);
1498 service_enter_running(s, SERVICE_SUCCESS);
1503 log_warning_unit(UNIT(s)->id, "%s failed to run 'reload' task: %s", UNIT(s)->id, strerror(-r));
1504 s->reload_result = SERVICE_FAILURE_RESOURCES;
1505 service_enter_running(s, SERVICE_SUCCESS);
1508 static void service_run_next_control(Service *s) {
1512 assert(s->control_command);
1513 assert(s->control_command->command_next);
1515 assert(s->control_command_id != SERVICE_EXEC_START);
1517 s->control_command = s->control_command->command_next;
1518 service_unwatch_control_pid(s);
1520 r = service_spawn(s,
1524 !s->permissions_start_only,
1525 !s->root_directory_start_only,
1526 s->control_command_id == SERVICE_EXEC_START_PRE ||
1527 s->control_command_id == SERVICE_EXEC_STOP_POST,
1537 log_warning_unit(UNIT(s)->id, "%s failed to run next control task: %s", UNIT(s)->id, strerror(-r));
1539 if (s->state == SERVICE_START_PRE)
1540 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
1541 else if (s->state == SERVICE_STOP)
1542 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
1543 else if (s->state == SERVICE_STOP_POST)
1544 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
1545 else if (s->state == SERVICE_RELOAD) {
1546 s->reload_result = SERVICE_FAILURE_RESOURCES;
1547 service_enter_running(s, SERVICE_SUCCESS);
1549 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
1552 static void service_run_next_main(Service *s) {
1557 assert(s->main_command);
1558 assert(s->main_command->command_next);
1559 assert(s->type == SERVICE_ONESHOT);
1561 s->main_command = s->main_command->command_next;
1562 service_unwatch_main_pid(s);
1564 r = service_spawn(s,
1571 s->notify_access != NOTIFY_NONE,
1577 service_set_main_pid(s, pid);
1582 log_warning_unit(UNIT(s)->id, "%s failed to run next main task: %s", UNIT(s)->id, strerror(-r));
1583 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
1586 static int service_execute_action(Service *s, FailureAction action, const char *reason, bool log_action_none) {
1589 if (action == SERVICE_FAILURE_ACTION_REBOOT ||
1590 action == SERVICE_FAILURE_ACTION_REBOOT_FORCE)
1591 update_reboot_param_file(s->reboot_arg);
1595 case SERVICE_FAILURE_ACTION_NONE:
1596 if (log_action_none)
1597 log_warning_unit(UNIT(s)->id, "%s %s, refusing to start.", UNIT(s)->id, reason);
1600 case SERVICE_FAILURE_ACTION_REBOOT: {
1601 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
1604 log_warning_unit(UNIT(s)->id, "%s %s, rebooting.", UNIT(s)->id, reason);
1606 r = manager_add_job_by_name(UNIT(s)->manager, JOB_START, SPECIAL_REBOOT_TARGET, JOB_REPLACE, true, &error, NULL);
1608 log_error_unit(UNIT(s)->id, "Failed to reboot: %s.", bus_error_message(&error, r));
1613 case SERVICE_FAILURE_ACTION_REBOOT_FORCE:
1614 log_warning_unit(UNIT(s)->id, "%s %s, forcibly rebooting.", UNIT(s)->id, reason);
1615 UNIT(s)->manager->exit_code = MANAGER_REBOOT;
1618 case SERVICE_FAILURE_ACTION_REBOOT_IMMEDIATE:
1619 log_warning_unit(UNIT(s)->id, "%s %s, rebooting immediately.", UNIT(s)->id, reason);
1623 if (s->reboot_arg) {
1624 log_info("Rebooting with argument '%s'.", s->reboot_arg);
1625 syscall(SYS_reboot, LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, s->reboot_arg);
1628 log_info("Rebooting.");
1629 reboot(RB_AUTOBOOT);
1633 log_error_unit(UNIT(s)->id, "failure action=%i", action);
1634 assert_not_reached("Unknown FailureAction.");
1640 static int service_start_limit_test(Service *s) {
1643 if (ratelimit_test(&s->start_limit))
1646 return service_execute_action(s, s->start_limit_action, "start request repeated too quickly", true);
1649 static int service_start(Unit *u) {
1650 Service *s = SERVICE(u);
1655 /* We cannot fulfill this request right now, try again later
1657 if (s->state == SERVICE_STOP ||
1658 s->state == SERVICE_STOP_SIGTERM ||
1659 s->state == SERVICE_STOP_SIGKILL ||
1660 s->state == SERVICE_STOP_POST ||
1661 s->state == SERVICE_FINAL_SIGTERM ||
1662 s->state == SERVICE_FINAL_SIGKILL)
1665 /* Already on it! */
1666 if (s->state == SERVICE_START_PRE ||
1667 s->state == SERVICE_START ||
1668 s->state == SERVICE_START_POST)
1671 /* A service that will be restarted must be stopped first to
1672 * trigger BindsTo and/or OnFailure dependencies. If a user
1673 * does not want to wait for the holdoff time to elapse, the
1674 * service should be manually restarted, not started. We
1675 * simply return EAGAIN here, so that any start jobs stay
1676 * queued, and assume that the auto restart timer will
1677 * eventually trigger the restart. */
1678 if (s->state == SERVICE_AUTO_RESTART)
1681 assert(s->state == SERVICE_DEAD || s->state == SERVICE_FAILED);
1683 /* Make sure we don't enter a busy loop of some kind. */
1684 r = service_start_limit_test(s);
1686 service_enter_dead(s, SERVICE_FAILURE_START_LIMIT, false);
1690 s->result = SERVICE_SUCCESS;
1691 s->reload_result = SERVICE_SUCCESS;
1692 s->main_pid_known = false;
1693 s->main_pid_alien = false;
1694 s->forbid_restart = false;
1696 free(s->status_text);
1697 s->status_text = NULL;
1698 s->status_errno = 0;
1700 s->notify_state = NOTIFY_UNKNOWN;
1702 service_enter_start_pre(s);
1706 static int service_stop(Unit *u) {
1707 Service *s = SERVICE(u);
1711 /* Don't create restart jobs from here. */
1712 s->forbid_restart = true;
1715 if (s->state == SERVICE_STOP ||
1716 s->state == SERVICE_STOP_SIGTERM ||
1717 s->state == SERVICE_STOP_SIGKILL ||
1718 s->state == SERVICE_STOP_POST ||
1719 s->state == SERVICE_FINAL_SIGTERM ||
1720 s->state == SERVICE_FINAL_SIGKILL)
1723 /* A restart will be scheduled or is in progress. */
1724 if (s->state == SERVICE_AUTO_RESTART) {
1725 service_set_state(s, SERVICE_DEAD);
1729 /* If there's already something running we go directly into
1731 if (s->state == SERVICE_START_PRE ||
1732 s->state == SERVICE_START ||
1733 s->state == SERVICE_START_POST ||
1734 s->state == SERVICE_RELOAD) {
1735 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
1739 assert(s->state == SERVICE_RUNNING ||
1740 s->state == SERVICE_EXITED);
1742 service_enter_stop(s, SERVICE_SUCCESS);
1746 static int service_reload(Unit *u) {
1747 Service *s = SERVICE(u);
1751 assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
1753 service_enter_reload(s);
1757 _pure_ static bool service_can_reload(Unit *u) {
1758 Service *s = SERVICE(u);
1762 return !!s->exec_command[SERVICE_EXEC_RELOAD];
1765 static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
1766 Service *s = SERVICE(u);
1772 unit_serialize_item(u, f, "state", service_state_to_string(s->state));
1773 unit_serialize_item(u, f, "result", service_result_to_string(s->result));
1774 unit_serialize_item(u, f, "reload-result", service_result_to_string(s->reload_result));
1776 if (s->control_pid > 0)
1777 unit_serialize_item_format(u, f, "control-pid", PID_FMT,
1780 if (s->main_pid_known && s->main_pid > 0)
1781 unit_serialize_item_format(u, f, "main-pid", PID_FMT, s->main_pid);
1783 unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
1786 unit_serialize_item(u, f, "status-text", s->status_text);
1788 /* FIXME: There's a minor uncleanliness here: if there are
1789 * multiple commands attached here, we will start from the
1790 * first one again */
1791 if (s->control_command_id >= 0)
1792 unit_serialize_item(u, f, "control-command",
1793 service_exec_command_to_string(s->control_command_id));
1795 if (s->socket_fd >= 0) {
1798 if ((copy = fdset_put_dup(fds, s->socket_fd)) < 0)
1801 unit_serialize_item_format(u, f, "socket-fd", "%i", copy);
1804 if (s->main_exec_status.pid > 0) {
1805 unit_serialize_item_format(u, f, "main-exec-status-pid", PID_FMT,
1806 s->main_exec_status.pid);
1807 dual_timestamp_serialize(f, "main-exec-status-start",
1808 &s->main_exec_status.start_timestamp);
1809 dual_timestamp_serialize(f, "main-exec-status-exit",
1810 &s->main_exec_status.exit_timestamp);
1812 if (dual_timestamp_is_set(&s->main_exec_status.exit_timestamp)) {
1813 unit_serialize_item_format(u, f, "main-exec-status-code", "%i",
1814 s->main_exec_status.code);
1815 unit_serialize_item_format(u, f, "main-exec-status-status", "%i",
1816 s->main_exec_status.status);
1819 if (dual_timestamp_is_set(&s->watchdog_timestamp))
1820 dual_timestamp_serialize(f, "watchdog-timestamp", &s->watchdog_timestamp);
1822 if (s->forbid_restart)
1823 unit_serialize_item(u, f, "forbid-restart", yes_no(s->forbid_restart));
1828 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
1829 Service *s = SERVICE(u);
1836 if (streq(key, "state")) {
1839 state = service_state_from_string(value);
1841 log_debug_unit(u->id, "Failed to parse state value %s", value);
1843 s->deserialized_state = state;
1844 } else if (streq(key, "result")) {
1847 f = service_result_from_string(value);
1849 log_debug_unit(u->id, "Failed to parse result value %s", value);
1850 else if (f != SERVICE_SUCCESS)
1853 } else if (streq(key, "reload-result")) {
1856 f = service_result_from_string(value);
1858 log_debug_unit(u->id, "Failed to parse reload result value %s", value);
1859 else if (f != SERVICE_SUCCESS)
1860 s->reload_result = f;
1862 } else if (streq(key, "control-pid")) {
1865 if (parse_pid(value, &pid) < 0)
1866 log_debug_unit(u->id, "Failed to parse control-pid value %s", value);
1868 s->control_pid = pid;
1869 } else if (streq(key, "main-pid")) {
1872 if (parse_pid(value, &pid) < 0)
1873 log_debug_unit(u->id, "Failed to parse main-pid value %s", value);
1875 service_set_main_pid(s, pid);
1876 unit_watch_pid(UNIT(s), pid);
1878 } else if (streq(key, "main-pid-known")) {
1881 b = parse_boolean(value);
1883 log_debug_unit(u->id, "Failed to parse main-pid-known value %s", value);
1885 s->main_pid_known = b;
1886 } else if (streq(key, "status-text")) {
1893 free(s->status_text);
1897 } else if (streq(key, "control-command")) {
1898 ServiceExecCommand id;
1900 id = service_exec_command_from_string(value);
1902 log_debug_unit(u->id, "Failed to parse exec-command value %s", value);
1904 s->control_command_id = id;
1905 s->control_command = s->exec_command[id];
1907 } else if (streq(key, "socket-fd")) {
1910 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
1911 log_debug_unit(u->id, "Failed to parse socket-fd value %s", value);
1914 asynchronous_close(s->socket_fd);
1915 s->socket_fd = fdset_remove(fds, fd);
1917 } else if (streq(key, "main-exec-status-pid")) {
1920 if (parse_pid(value, &pid) < 0)
1921 log_debug_unit(u->id, "Failed to parse main-exec-status-pid value %s", value);
1923 s->main_exec_status.pid = pid;
1924 } else if (streq(key, "main-exec-status-code")) {
1927 if (safe_atoi(value, &i) < 0)
1928 log_debug_unit(u->id, "Failed to parse main-exec-status-code value %s", value);
1930 s->main_exec_status.code = i;
1931 } else if (streq(key, "main-exec-status-status")) {
1934 if (safe_atoi(value, &i) < 0)
1935 log_debug_unit(u->id, "Failed to parse main-exec-status-status value %s", value);
1937 s->main_exec_status.status = i;
1938 } else if (streq(key, "main-exec-status-start"))
1939 dual_timestamp_deserialize(value, &s->main_exec_status.start_timestamp);
1940 else if (streq(key, "main-exec-status-exit"))
1941 dual_timestamp_deserialize(value, &s->main_exec_status.exit_timestamp);
1942 else if (streq(key, "watchdog-timestamp"))
1943 dual_timestamp_deserialize(value, &s->watchdog_timestamp);
1944 else if (streq(key, "forbid-restart")) {
1947 b = parse_boolean(value);
1949 log_debug_unit(u->id, "Failed to parse forbid-restart value %s", value);
1951 s->forbid_restart = b;
1953 log_debug_unit(u->id, "Unknown serialization key '%s'", key);
1958 _pure_ static UnitActiveState service_active_state(Unit *u) {
1959 const UnitActiveState *table;
1963 table = SERVICE(u)->type == SERVICE_IDLE ? state_translation_table_idle : state_translation_table;
1965 return table[SERVICE(u)->state];
1968 static const char *service_sub_state_to_string(Unit *u) {
1971 return service_state_to_string(SERVICE(u)->state);
1974 static bool service_check_gc(Unit *u) {
1975 Service *s = SERVICE(u);
1979 /* Never clean up services that still have a process around,
1980 * even if the service is formally dead. */
1981 if (cgroup_good(s) > 0 ||
1982 main_pid_good(s) > 0 ||
1983 control_pid_good(s) > 0)
1989 _pure_ static bool service_check_snapshot(Unit *u) {
1990 Service *s = SERVICE(u);
1994 return s->socket_fd < 0;
1997 static int service_retry_pid_file(Service *s) {
2000 assert(s->pid_file);
2001 assert(s->state == SERVICE_START || s->state == SERVICE_START_POST);
2003 r = service_load_pid_file(s, false);
2007 service_unwatch_pid_file(s);
2009 service_enter_running(s, SERVICE_SUCCESS);
2013 static int service_watch_pid_file(Service *s) {
2016 log_debug_unit(UNIT(s)->id, "Setting watch for %s's PID file %s", UNIT(s)->id, s->pid_file_pathspec->path);
2018 r = path_spec_watch(s->pid_file_pathspec, service_dispatch_io);
2022 /* the pidfile might have appeared just before we set the watch */
2023 log_debug_unit(UNIT(s)->id, "Trying to read %s's PID file %s in case it changed", UNIT(s)->id, s->pid_file_pathspec->path);
2024 service_retry_pid_file(s);
2028 log_error_unit(UNIT(s)->id, "Failed to set a watch for %s's PID file %s: %s", UNIT(s)->id, s->pid_file_pathspec->path, strerror(-r));
2029 service_unwatch_pid_file(s);
2033 static int service_demand_pid_file(Service *s) {
2036 assert(s->pid_file);
2037 assert(!s->pid_file_pathspec);
2039 ps = new0(PathSpec, 1);
2044 ps->path = strdup(s->pid_file);
2050 path_kill_slashes(ps->path);
2052 /* PATH_CHANGED would not be enough. There are daemons (sendmail) that
2053 * keep their PID file open all the time. */
2054 ps->type = PATH_MODIFIED;
2055 ps->inotify_fd = -1;
2057 s->pid_file_pathspec = ps;
2059 return service_watch_pid_file(s);
2062 static int service_dispatch_io(sd_event_source *source, int fd, uint32_t events, void *userdata) {
2063 PathSpec *p = userdata;
2068 s = SERVICE(p->unit);
2072 assert(s->state == SERVICE_START || s->state == SERVICE_START_POST);
2073 assert(s->pid_file_pathspec);
2074 assert(path_spec_owns_inotify_fd(s->pid_file_pathspec, fd));
2076 log_debug_unit(UNIT(s)->id, "inotify event for %s", UNIT(s)->id);
2078 if (path_spec_fd_event(p, events) < 0)
2081 if (service_retry_pid_file(s) == 0)
2084 if (service_watch_pid_file(s) < 0)
2090 service_unwatch_pid_file(s);
2091 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
2095 static void service_notify_cgroup_empty_event(Unit *u) {
2096 Service *s = SERVICE(u);
2100 log_debug_unit(u->id, "%s: cgroup is empty", u->id);
2104 /* Waiting for SIGCHLD is usually more interesting,
2105 * because it includes return codes/signals. Which is
2106 * why we ignore the cgroup events for most cases,
2107 * except when we don't know pid which to expect the
2111 case SERVICE_START_POST:
2112 /* If we were hoping for the daemon to write its PID file,
2113 * we can give up now. */
2114 if (s->pid_file_pathspec) {
2115 log_warning_unit(u->id, "%s never wrote its PID file. Failing.", UNIT(s)->id);
2117 service_unwatch_pid_file(s);
2118 if (s->state == SERVICE_START)
2119 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
2121 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2125 case SERVICE_RUNNING:
2126 /* service_enter_running() will figure out what to do */
2127 service_enter_running(s, SERVICE_SUCCESS);
2130 case SERVICE_STOP_SIGTERM:
2131 case SERVICE_STOP_SIGKILL:
2133 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2134 service_enter_stop_post(s, SERVICE_SUCCESS);
2138 case SERVICE_STOP_POST:
2139 case SERVICE_FINAL_SIGTERM:
2140 case SERVICE_FINAL_SIGKILL:
2141 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2142 service_enter_dead(s, SERVICE_SUCCESS, true);
2151 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2152 Service *s = SERVICE(u);
2158 if (UNIT(s)->fragment_path ? is_clean_exit(code, status, &s->success_status) :
2159 is_clean_exit_lsb(code, status, &s->success_status))
2160 f = SERVICE_SUCCESS;
2161 else if (code == CLD_EXITED)
2162 f = SERVICE_FAILURE_EXIT_CODE;
2163 else if (code == CLD_KILLED)
2164 f = SERVICE_FAILURE_SIGNAL;
2165 else if (code == CLD_DUMPED)
2166 f = SERVICE_FAILURE_CORE_DUMP;
2168 assert_not_reached("Unknown code");
2170 if (s->main_pid == pid) {
2171 /* Forking services may occasionally move to a new PID.
2172 * As long as they update the PID file before exiting the old
2173 * PID, they're fine. */
2174 if (service_load_pid_file(s, false) == 0)
2178 exec_status_exit(&s->main_exec_status, &s->exec_context, pid, code, status);
2180 if (s->main_command) {
2181 /* If this is not a forking service than the
2182 * main process got started and hence we copy
2183 * the exit status so that it is recorded both
2184 * as main and as control process exit
2187 s->main_command->exec_status = s->main_exec_status;
2189 if (s->main_command->ignore)
2190 f = SERVICE_SUCCESS;
2191 } else if (s->exec_command[SERVICE_EXEC_START]) {
2193 /* If this is a forked process, then we should
2194 * ignore the return value if this was
2195 * configured for the starter process */
2197 if (s->exec_command[SERVICE_EXEC_START]->ignore)
2198 f = SERVICE_SUCCESS;
2201 log_struct_unit(f == SERVICE_SUCCESS ? LOG_DEBUG : LOG_NOTICE,
2203 "MESSAGE=%s: main process exited, code=%s, status=%i/%s",
2204 u->id, sigchld_code_to_string(code), status,
2205 strna(code == CLD_EXITED
2206 ? exit_status_to_string(status, EXIT_STATUS_FULL)
2207 : signal_to_string(status)),
2208 "EXIT_CODE=%s", sigchld_code_to_string(code),
2209 "EXIT_STATUS=%i", status,
2212 if (f != SERVICE_SUCCESS)
2215 if (s->main_command &&
2216 s->main_command->command_next &&
2217 f == SERVICE_SUCCESS) {
2219 /* There is another command to *
2220 * execute, so let's do that. */
2222 log_debug_unit(u->id, "%s running next main command for state %s", u->id, service_state_to_string(s->state));
2223 service_run_next_main(s);
2227 /* The service exited, so the service is officially
2229 s->main_command = NULL;
2233 case SERVICE_START_POST:
2234 case SERVICE_RELOAD:
2236 /* Need to wait until the operation is
2241 if (s->type == SERVICE_ONESHOT) {
2242 /* This was our main goal, so let's go on */
2243 if (f == SERVICE_SUCCESS)
2244 service_enter_start_post(s);
2246 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
2252 case SERVICE_RUNNING:
2253 service_enter_running(s, f);
2256 case SERVICE_STOP_SIGTERM:
2257 case SERVICE_STOP_SIGKILL:
2259 if (!control_pid_good(s))
2260 service_enter_stop_post(s, f);
2262 /* If there is still a control process, wait for that first */
2265 case SERVICE_STOP_POST:
2266 case SERVICE_FINAL_SIGTERM:
2267 case SERVICE_FINAL_SIGKILL:
2269 if (!control_pid_good(s))
2270 service_enter_dead(s, f, true);
2274 assert_not_reached("Uh, main process died at wrong time.");
2278 } else if (s->control_pid == pid) {
2281 if (s->control_command) {
2282 exec_status_exit(&s->control_command->exec_status, &s->exec_context, pid, code, status);
2284 if (s->control_command->ignore)
2285 f = SERVICE_SUCCESS;
2288 log_full_unit(f == SERVICE_SUCCESS ? LOG_DEBUG : LOG_NOTICE, u->id,
2289 "%s: control process exited, code=%s status=%i",
2290 u->id, sigchld_code_to_string(code), status);
2292 if (f != SERVICE_SUCCESS)
2295 /* Immediately get rid of the cgroup, so that the
2296 * kernel doesn't delay the cgroup empty messages for
2297 * the service cgroup any longer than necessary */
2298 service_kill_control_processes(s);
2300 if (s->control_command &&
2301 s->control_command->command_next &&
2302 f == SERVICE_SUCCESS) {
2304 /* There is another command to *
2305 * execute, so let's do that. */
2307 log_debug_unit(u->id, "%s running next control command for state %s", u->id, service_state_to_string(s->state));
2308 service_run_next_control(s);
2311 /* No further commands for this step, so let's
2312 * figure out what to do next */
2314 s->control_command = NULL;
2315 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2317 log_debug_unit(u->id, "%s got final SIGCHLD for state %s", u->id, service_state_to_string(s->state));
2321 case SERVICE_START_PRE:
2322 if (f == SERVICE_SUCCESS)
2323 service_enter_start(s);
2325 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
2329 if (s->type != SERVICE_FORKING)
2330 /* Maybe spurious event due to a reload that changed the type? */
2333 if (f != SERVICE_SUCCESS) {
2334 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
2339 bool has_start_post;
2342 /* Let's try to load the pid file here if we can.
2343 * The PID file might actually be created by a START_POST
2344 * script. In that case don't worry if the loading fails. */
2346 has_start_post = !!s->exec_command[SERVICE_EXEC_START_POST];
2347 r = service_load_pid_file(s, !has_start_post);
2348 if (!has_start_post && r < 0) {
2349 r = service_demand_pid_file(s);
2350 if (r < 0 || !cgroup_good(s))
2351 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
2355 service_search_main_pid(s);
2357 service_enter_start_post(s);
2360 case SERVICE_START_POST:
2361 if (f != SERVICE_SUCCESS) {
2362 service_enter_stop(s, f);
2369 r = service_load_pid_file(s, true);
2371 r = service_demand_pid_file(s);
2372 if (r < 0 || !cgroup_good(s))
2373 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2377 service_search_main_pid(s);
2379 service_enter_running(s, SERVICE_SUCCESS);
2382 case SERVICE_RELOAD:
2383 if (f == SERVICE_SUCCESS) {
2384 service_load_pid_file(s, true);
2385 service_search_main_pid(s);
2388 s->reload_result = f;
2389 service_enter_running(s, SERVICE_SUCCESS);
2393 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
2396 case SERVICE_STOP_SIGTERM:
2397 case SERVICE_STOP_SIGKILL:
2398 if (main_pid_good(s) <= 0)
2399 service_enter_stop_post(s, f);
2401 /* If there is still a service
2402 * process around, wait until
2403 * that one quit, too */
2406 case SERVICE_STOP_POST:
2407 case SERVICE_FINAL_SIGTERM:
2408 case SERVICE_FINAL_SIGKILL:
2409 if (main_pid_good(s) <= 0)
2410 service_enter_dead(s, f, true);
2414 assert_not_reached("Uh, control process died at wrong time.");
2419 /* Notify clients about changed exit status */
2420 unit_add_to_dbus_queue(u);
2422 /* We got one SIGCHLD for the service, let's watch all
2423 * processes that are now running of the service, and watch
2424 * that. Among the PIDs we then watch will be children
2425 * reassigned to us, which hopefully allows us to identify
2426 * when all children are gone */
2427 unit_tidy_watch_pids(u, s->main_pid, s->control_pid);
2428 unit_watch_all_pids(u);
2430 /* If the PID set is empty now, then let's finish this off */
2431 if (set_isempty(u->pids))
2432 service_notify_cgroup_empty_event(u);
2435 static int service_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata) {
2436 Service *s = SERVICE(userdata);
2439 assert(source == s->timer_event_source);
2443 case SERVICE_START_PRE:
2445 log_warning_unit(UNIT(s)->id, "%s %s operation timed out. Terminating.", UNIT(s)->id, s->state == SERVICE_START ? "start" : "start-pre");
2446 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2449 case SERVICE_START_POST:
2450 log_warning_unit(UNIT(s)->id, "%s start-post operation timed out. Stopping.", UNIT(s)->id);
2451 service_enter_stop(s, SERVICE_FAILURE_TIMEOUT);
2454 case SERVICE_RELOAD:
2455 log_warning_unit(UNIT(s)->id, "%s reload operation timed out. Stopping.", UNIT(s)->id);
2456 s->reload_result = SERVICE_FAILURE_TIMEOUT;
2457 service_enter_running(s, SERVICE_SUCCESS);
2461 log_warning_unit(UNIT(s)->id, "%s stopping timed out. Terminating.", UNIT(s)->id);
2462 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2465 case SERVICE_STOP_SIGTERM:
2466 if (s->kill_context.send_sigkill) {
2467 log_warning_unit(UNIT(s)->id, "%s stop-sigterm timed out. Killing.", UNIT(s)->id);
2468 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_TIMEOUT);
2470 log_warning_unit(UNIT(s)->id, "%s stop-sigterm timed out. Skipping SIGKILL.", UNIT(s)->id);
2471 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
2476 case SERVICE_STOP_SIGKILL:
2477 /* Uh, we sent a SIGKILL and it is still not gone?
2478 * Must be something we cannot kill, so let's just be
2479 * weirded out and continue */
2481 log_warning_unit(UNIT(s)->id, "%s still around after SIGKILL. Ignoring.", UNIT(s)->id);
2482 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
2485 case SERVICE_STOP_POST:
2486 log_warning_unit(UNIT(s)->id, "%s stop-post timed out. Terminating.", UNIT(s)->id);
2487 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2490 case SERVICE_FINAL_SIGTERM:
2491 if (s->kill_context.send_sigkill) {
2492 log_warning_unit(UNIT(s)->id, "%s stop-final-sigterm timed out. Killing.", UNIT(s)->id);
2493 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_FAILURE_TIMEOUT);
2495 log_warning_unit(UNIT(s)->id, "%s stop-final-sigterm timed out. Skipping SIGKILL. Entering failed mode.", UNIT(s)->id);
2496 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, false);
2501 case SERVICE_FINAL_SIGKILL:
2502 log_warning_unit(UNIT(s)->id, "%s still around after final SIGKILL. Entering failed mode.", UNIT(s)->id);
2503 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, true);
2506 case SERVICE_AUTO_RESTART:
2507 log_info_unit(UNIT(s)->id,
2508 s->restart_usec > 0 ?
2509 "%s holdoff time over, scheduling restart." :
2510 "%s has no holdoff time, scheduling restart.",
2512 service_enter_restart(s);
2516 assert_not_reached("Timeout at wrong time.");
2522 static int service_dispatch_watchdog(sd_event_source *source, usec_t usec, void *userdata) {
2523 Service *s = SERVICE(userdata);
2524 char t[FORMAT_TIMESPAN_MAX];
2527 assert(source == s->watchdog_event_source);
2529 log_error_unit(UNIT(s)->id, "%s watchdog timeout (limit %s)!", UNIT(s)->id,
2530 format_timespan(t, sizeof(t), s->watchdog_usec, 1));
2532 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_WATCHDOG);
2537 static void service_notify_message(Unit *u, pid_t pid, char **tags) {
2538 Service *s = SERVICE(u);
2539 _cleanup_free_ char *cc = NULL;
2540 bool notify_dbus = false;
2545 cc = strv_join(tags, ", ");
2546 log_debug_unit(u->id, "%s: Got notification message from PID "PID_FMT" (%s)",
2547 u->id, pid, isempty(cc) ? "n/a" : cc);
2549 if (s->notify_access == NOTIFY_NONE) {
2550 log_warning_unit(u->id, "%s: Got notification message from PID "PID_FMT", but reception is disabled.", u->id, pid);
2554 if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
2555 if (s->main_pid != 0)
2556 log_warning_unit(u->id, "%s: Got notification message from PID "PID_FMT", but reception only permitted for main PID "PID_FMT, u->id, pid, s->main_pid);
2558 log_debug_unit(u->id, "%s: Got notification message from PID "PID_FMT", but reception only permitted for main PID which is currently not known", u->id, pid);
2562 /* Interpret MAINPID= */
2563 e = strv_find_startswith(tags, "MAINPID=");
2564 if (e && IN_SET(s->state, SERVICE_START, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD)) {
2565 if (parse_pid(e, &pid) < 0)
2566 log_warning_unit(u->id, "Failed to parse MAINPID= field in notification message: %s", e);
2568 log_debug_unit(u->id, "%s: got MAINPID=%s", u->id, e);
2570 service_set_main_pid(s, pid);
2571 unit_watch_pid(UNIT(s), pid);
2576 /* Interpret RELOADING= */
2577 if (strv_find(tags, "RELOADING=1")) {
2579 log_debug_unit(u->id, "%s: got RELOADING=1", u->id);
2580 s->notify_state = NOTIFY_RELOADING;
2582 if (s->state == SERVICE_RUNNING)
2583 service_enter_reload_by_notify(s);
2588 /* Interpret READY= */
2589 if (strv_find(tags, "READY=1")) {
2591 log_debug_unit(u->id, "%s: got READY=1", u->id);
2592 s->notify_state = NOTIFY_READY;
2594 /* Type=notify services inform us about completed
2595 * initialization with READY=1 */
2596 if (s->type == SERVICE_NOTIFY && s->state == SERVICE_START)
2597 service_enter_start_post(s);
2599 /* Sending READY=1 while we are reloading informs us
2600 * that the reloading is complete */
2601 if (s->state == SERVICE_RELOAD && s->control_pid == 0)
2602 service_enter_running(s, SERVICE_SUCCESS);
2607 /* Interpret STOPPING= */
2608 if (strv_find(tags, "STOPPING=1")) {
2610 log_debug_unit(u->id, "%s: got STOPPING=1", u->id);
2611 s->notify_state = NOTIFY_STOPPING;
2613 if (s->state == SERVICE_RUNNING)
2614 service_enter_stop_by_notify(s);
2619 /* Interpret STATUS= */
2620 e = strv_find_startswith(tags, "STATUS=");
2622 _cleanup_free_ char *t = NULL;
2625 if (!utf8_is_valid(e))
2626 log_warning_unit(u->id, "Status message in notification is not UTF-8 clean.");
2628 log_debug_unit(u->id, "%s: got STATUS=%s", u->id, e);
2636 if (!streq_ptr(s->status_text, t)) {
2638 free(s->status_text);
2646 /* Interpret ERRNO= */
2647 e = strv_find_startswith(tags, "ERRNO=");
2651 if (safe_atoi(e, &status_errno) < 0 || status_errno < 0)
2652 log_warning_unit(u->id, "Failed to parse ERRNO= field in notification message: %s", e);
2654 log_debug_unit(u->id, "%s: got ERRNO=%s", u->id, e);
2656 if (s->status_errno != status_errno) {
2657 s->status_errno = status_errno;
2663 /* Interpret WATCHDOG= */
2664 if (strv_find(tags, "WATCHDOG=1")) {
2665 log_debug_unit(u->id, "%s: got WATCHDOG=1", u->id);
2666 service_reset_watchdog(s);
2669 /* Notify clients about changed status or main pid */
2671 unit_add_to_dbus_queue(u);
2674 static int service_get_timeout(Unit *u, uint64_t *timeout) {
2675 Service *s = SERVICE(u);
2678 if (!s->timer_event_source)
2681 r = sd_event_source_get_time(s->timer_event_source, timeout);
2688 static void service_bus_name_owner_change(
2691 const char *old_owner,
2692 const char *new_owner) {
2694 Service *s = SERVICE(u);
2700 assert(streq(s->bus_name, name));
2701 assert(old_owner || new_owner);
2703 if (old_owner && new_owner)
2704 log_debug_unit(u->id, "%s's D-Bus name %s changed owner from %s to %s", u->id, name, old_owner, new_owner);
2706 log_debug_unit(u->id, "%s's D-Bus name %s no longer registered by %s", u->id, name, old_owner);
2708 log_debug_unit(u->id, "%s's D-Bus name %s now registered by %s", u->id, name, new_owner);
2710 s->bus_name_good = !!new_owner;
2712 if (s->type == SERVICE_DBUS) {
2714 /* service_enter_running() will figure out what to
2716 if (s->state == SERVICE_RUNNING)
2717 service_enter_running(s, SERVICE_SUCCESS);
2718 else if (s->state == SERVICE_START && new_owner)
2719 service_enter_start_post(s);
2721 } else if (new_owner &&
2723 (s->state == SERVICE_START ||
2724 s->state == SERVICE_START_POST ||
2725 s->state == SERVICE_RUNNING ||
2726 s->state == SERVICE_RELOAD)) {
2728 _cleanup_bus_creds_unref_ sd_bus_creds *creds = NULL;
2731 /* Try to acquire PID from bus service */
2733 r = sd_bus_get_owner(u->manager->api_bus, name, SD_BUS_CREDS_PID, &creds);
2735 r = sd_bus_creds_get_pid(creds, &pid);
2737 log_debug_unit(u->id, "%s's D-Bus name %s is now owned by process %u", u->id, name, (unsigned) pid);
2739 service_set_main_pid(s, pid);
2740 unit_watch_pid(UNIT(s), pid);
2745 int service_set_socket_fd(Service *s, int fd, Socket *sock) {
2746 _cleanup_free_ char *peer = NULL;
2752 /* This is called by the socket code when instantiating a new
2753 * service for a stream socket and the socket needs to be
2756 if (UNIT(s)->load_state != UNIT_LOADED)
2759 if (s->socket_fd >= 0)
2762 if (s->state != SERVICE_DEAD)
2765 if (getpeername_pretty(fd, &peer) >= 0) {
2767 if (UNIT(s)->description) {
2768 _cleanup_free_ char *a;
2770 a = strjoin(UNIT(s)->description, " (", peer, ")", NULL);
2774 r = unit_set_description(UNIT(s), a);
2776 r = unit_set_description(UNIT(s), peer);
2784 unit_ref_set(&s->accept_socket, UNIT(sock));
2786 return unit_add_two_dependencies(UNIT(sock), UNIT_BEFORE, UNIT_TRIGGERS, UNIT(s), false);
2789 static void service_reset_failed(Unit *u) {
2790 Service *s = SERVICE(u);
2794 if (s->state == SERVICE_FAILED)
2795 service_set_state(s, SERVICE_DEAD);
2797 s->result = SERVICE_SUCCESS;
2798 s->reload_result = SERVICE_SUCCESS;
2800 RATELIMIT_RESET(s->start_limit);
2803 static int service_kill(Unit *u, KillWho who, int signo, sd_bus_error *error) {
2804 Service *s = SERVICE(u);
2806 return unit_kill_common(u, who, signo, s->main_pid, s->control_pid, error);
2809 static const char* const service_state_table[_SERVICE_STATE_MAX] = {
2810 [SERVICE_DEAD] = "dead",
2811 [SERVICE_START_PRE] = "start-pre",
2812 [SERVICE_START] = "start",
2813 [SERVICE_START_POST] = "start-post",
2814 [SERVICE_RUNNING] = "running",
2815 [SERVICE_EXITED] = "exited",
2816 [SERVICE_RELOAD] = "reload",
2817 [SERVICE_STOP] = "stop",
2818 [SERVICE_STOP_SIGTERM] = "stop-sigterm",
2819 [SERVICE_STOP_SIGKILL] = "stop-sigkill",
2820 [SERVICE_STOP_POST] = "stop-post",
2821 [SERVICE_FINAL_SIGTERM] = "final-sigterm",
2822 [SERVICE_FINAL_SIGKILL] = "final-sigkill",
2823 [SERVICE_FAILED] = "failed",
2824 [SERVICE_AUTO_RESTART] = "auto-restart",
2827 DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
2829 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
2830 [SERVICE_RESTART_NO] = "no",
2831 [SERVICE_RESTART_ON_SUCCESS] = "on-success",
2832 [SERVICE_RESTART_ON_FAILURE] = "on-failure",
2833 [SERVICE_RESTART_ON_ABNORMAL] = "on-abnormal",
2834 [SERVICE_RESTART_ON_WATCHDOG] = "on-watchdog",
2835 [SERVICE_RESTART_ON_ABORT] = "on-abort",
2836 [SERVICE_RESTART_ALWAYS] = "always",
2839 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
2841 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
2842 [SERVICE_SIMPLE] = "simple",
2843 [SERVICE_FORKING] = "forking",
2844 [SERVICE_ONESHOT] = "oneshot",
2845 [SERVICE_DBUS] = "dbus",
2846 [SERVICE_NOTIFY] = "notify",
2847 [SERVICE_IDLE] = "idle"
2850 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
2852 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
2853 [SERVICE_EXEC_START_PRE] = "ExecStartPre",
2854 [SERVICE_EXEC_START] = "ExecStart",
2855 [SERVICE_EXEC_START_POST] = "ExecStartPost",
2856 [SERVICE_EXEC_RELOAD] = "ExecReload",
2857 [SERVICE_EXEC_STOP] = "ExecStop",
2858 [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
2861 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
2863 static const char* const notify_access_table[_NOTIFY_ACCESS_MAX] = {
2864 [NOTIFY_NONE] = "none",
2865 [NOTIFY_MAIN] = "main",
2866 [NOTIFY_ALL] = "all"
2869 DEFINE_STRING_TABLE_LOOKUP(notify_access, NotifyAccess);
2871 static const char* const notify_state_table[_NOTIFY_STATE_MAX] = {
2872 [NOTIFY_UNKNOWN] = "unknown",
2873 [NOTIFY_READY] = "ready",
2874 [NOTIFY_RELOADING] = "reloading",
2875 [NOTIFY_STOPPING] = "stopping",
2878 DEFINE_STRING_TABLE_LOOKUP(notify_state, NotifyState);
2880 static const char* const service_result_table[_SERVICE_RESULT_MAX] = {
2881 [SERVICE_SUCCESS] = "success",
2882 [SERVICE_FAILURE_RESOURCES] = "resources",
2883 [SERVICE_FAILURE_TIMEOUT] = "timeout",
2884 [SERVICE_FAILURE_EXIT_CODE] = "exit-code",
2885 [SERVICE_FAILURE_SIGNAL] = "signal",
2886 [SERVICE_FAILURE_CORE_DUMP] = "core-dump",
2887 [SERVICE_FAILURE_WATCHDOG] = "watchdog",
2888 [SERVICE_FAILURE_START_LIMIT] = "start-limit"
2891 DEFINE_STRING_TABLE_LOOKUP(service_result, ServiceResult);
2893 static const char* const failure_action_table[_SERVICE_FAILURE_ACTION_MAX] = {
2894 [SERVICE_FAILURE_ACTION_NONE] = "none",
2895 [SERVICE_FAILURE_ACTION_REBOOT] = "reboot",
2896 [SERVICE_FAILURE_ACTION_REBOOT_FORCE] = "reboot-force",
2897 [SERVICE_FAILURE_ACTION_REBOOT_IMMEDIATE] = "reboot-immediate"
2899 DEFINE_STRING_TABLE_LOOKUP(failure_action, FailureAction);
2901 const UnitVTable service_vtable = {
2902 .object_size = sizeof(Service),
2903 .exec_context_offset = offsetof(Service, exec_context),
2904 .cgroup_context_offset = offsetof(Service, cgroup_context),
2905 .kill_context_offset = offsetof(Service, kill_context),
2906 .exec_runtime_offset = offsetof(Service, exec_runtime),
2912 .private_section = "Service",
2914 .init = service_init,
2915 .done = service_done,
2916 .load = service_load,
2918 .coldplug = service_coldplug,
2920 .dump = service_dump,
2922 .start = service_start,
2923 .stop = service_stop,
2924 .reload = service_reload,
2926 .can_reload = service_can_reload,
2928 .kill = service_kill,
2930 .serialize = service_serialize,
2931 .deserialize_item = service_deserialize_item,
2933 .active_state = service_active_state,
2934 .sub_state_to_string = service_sub_state_to_string,
2936 .check_gc = service_check_gc,
2937 .check_snapshot = service_check_snapshot,
2939 .sigchld_event = service_sigchld_event,
2941 .reset_failed = service_reset_failed,
2943 .notify_cgroup_empty = service_notify_cgroup_empty_event,
2944 .notify_message = service_notify_message,
2946 .bus_name_owner_change = service_bus_name_owner_change,
2948 .bus_interface = "org.freedesktop.systemd1.Service",
2949 .bus_vtable = bus_service_vtable,
2950 .bus_set_property = bus_service_set_property,
2951 .bus_commit_properties = bus_service_commit_properties,
2953 .get_timeout = service_get_timeout,
2954 .can_transient = true,
2956 .status_message_formats = {
2957 .starting_stopping = {
2958 [0] = "Starting %s...",
2959 [1] = "Stopping %s...",
2961 .finished_start_job = {
2962 [JOB_DONE] = "Started %s.",
2963 [JOB_FAILED] = "Failed to start %s.",
2964 [JOB_DEPENDENCY] = "Dependency failed for %s.",
2965 [JOB_TIMEOUT] = "Timed out starting %s.",
2967 .finished_stop_job = {
2968 [JOB_DONE] = "Stopped %s.",
2969 [JOB_FAILED] = "Stopped (with error) %s.",
2970 [JOB_TIMEOUT] = "Timed out stopping %s.",