1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
9 #include "sd-messages.h"
11 #include "alloc-util.h"
13 #include "bus-error.h"
14 #include "bus-kernel.h"
17 #include "constants.h"
18 #include "dbus-service.h"
19 #include "dbus-unit.h"
20 #include "devnum-util.h"
23 #include "exit-status.h"
26 #include "format-util.h"
27 #include "load-dropin.h"
28 #include "load-fragment.h"
31 #include "missing_audit.h"
32 #include "open-file.h"
33 #include "parse-util.h"
34 #include "path-util.h"
35 #include "process-util.h"
36 #include "random-util.h"
37 #include "serialize.h"
39 #include "signal-util.h"
41 #include "stdio-util.h"
42 #include "string-table.h"
43 #include "string-util.h"
45 #include "unit-name.h"
49 #define service_spawn(...) service_spawn_internal(__func__, __VA_ARGS__)
51 static const UnitActiveState state_translation_table
[_SERVICE_STATE_MAX
] = {
52 [SERVICE_DEAD
] = UNIT_INACTIVE
,
53 [SERVICE_CONDITION
] = UNIT_ACTIVATING
,
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_RELOAD_SIGNAL
] = UNIT_RELOADING
,
61 [SERVICE_RELOAD_NOTIFY
] = UNIT_RELOADING
,
62 [SERVICE_STOP
] = UNIT_DEACTIVATING
,
63 [SERVICE_STOP_WATCHDOG
] = UNIT_DEACTIVATING
,
64 [SERVICE_STOP_SIGTERM
] = UNIT_DEACTIVATING
,
65 [SERVICE_STOP_SIGKILL
] = UNIT_DEACTIVATING
,
66 [SERVICE_STOP_POST
] = UNIT_DEACTIVATING
,
67 [SERVICE_FINAL_WATCHDOG
] = UNIT_DEACTIVATING
,
68 [SERVICE_FINAL_SIGTERM
] = UNIT_DEACTIVATING
,
69 [SERVICE_FINAL_SIGKILL
] = UNIT_DEACTIVATING
,
70 [SERVICE_FAILED
] = UNIT_FAILED
,
71 [SERVICE_DEAD_BEFORE_AUTO_RESTART
] = UNIT_INACTIVE
,
72 [SERVICE_FAILED_BEFORE_AUTO_RESTART
] = UNIT_FAILED
,
73 [SERVICE_DEAD_RESOURCES_PINNED
] = UNIT_INACTIVE
,
74 [SERVICE_AUTO_RESTART
] = UNIT_ACTIVATING
,
75 [SERVICE_AUTO_RESTART_QUEUED
] = UNIT_ACTIVATING
,
76 [SERVICE_CLEANING
] = UNIT_MAINTENANCE
,
79 /* For Type=idle we never want to delay any other jobs, hence we
80 * consider idle jobs active as soon as we start working on them */
81 static const UnitActiveState state_translation_table_idle
[_SERVICE_STATE_MAX
] = {
82 [SERVICE_DEAD
] = UNIT_INACTIVE
,
83 [SERVICE_CONDITION
] = UNIT_ACTIVE
,
84 [SERVICE_START_PRE
] = UNIT_ACTIVE
,
85 [SERVICE_START
] = UNIT_ACTIVE
,
86 [SERVICE_START_POST
] = UNIT_ACTIVE
,
87 [SERVICE_RUNNING
] = UNIT_ACTIVE
,
88 [SERVICE_EXITED
] = UNIT_ACTIVE
,
89 [SERVICE_RELOAD
] = UNIT_RELOADING
,
90 [SERVICE_RELOAD_SIGNAL
] = UNIT_RELOADING
,
91 [SERVICE_RELOAD_NOTIFY
] = UNIT_RELOADING
,
92 [SERVICE_STOP
] = UNIT_DEACTIVATING
,
93 [SERVICE_STOP_WATCHDOG
] = UNIT_DEACTIVATING
,
94 [SERVICE_STOP_SIGTERM
] = UNIT_DEACTIVATING
,
95 [SERVICE_STOP_SIGKILL
] = UNIT_DEACTIVATING
,
96 [SERVICE_STOP_POST
] = UNIT_DEACTIVATING
,
97 [SERVICE_FINAL_WATCHDOG
] = UNIT_DEACTIVATING
,
98 [SERVICE_FINAL_SIGTERM
] = UNIT_DEACTIVATING
,
99 [SERVICE_FINAL_SIGKILL
] = UNIT_DEACTIVATING
,
100 [SERVICE_FAILED
] = UNIT_FAILED
,
101 [SERVICE_DEAD_BEFORE_AUTO_RESTART
] = UNIT_INACTIVE
,
102 [SERVICE_FAILED_BEFORE_AUTO_RESTART
] = UNIT_FAILED
,
103 [SERVICE_DEAD_RESOURCES_PINNED
] = UNIT_INACTIVE
,
104 [SERVICE_AUTO_RESTART
] = UNIT_ACTIVATING
,
105 [SERVICE_AUTO_RESTART_QUEUED
] = UNIT_ACTIVATING
,
106 [SERVICE_CLEANING
] = UNIT_MAINTENANCE
,
109 static int service_dispatch_inotify_io(sd_event_source
*source
, int fd
, uint32_t events
, void *userdata
);
110 static int service_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
);
111 static int service_dispatch_watchdog(sd_event_source
*source
, usec_t usec
, void *userdata
);
112 static int service_dispatch_exec_io(sd_event_source
*source
, int fd
, uint32_t events
, void *userdata
);
114 static void service_enter_signal(Service
*s
, ServiceState state
, ServiceResult f
);
115 static void service_enter_reload_by_notify(Service
*s
);
117 static void service_init(Unit
*u
) {
118 Service
*s
= SERVICE(u
);
121 assert(u
->load_state
== UNIT_STUB
);
123 s
->timeout_start_usec
= u
->manager
->defaults
.timeout_start_usec
;
124 s
->timeout_stop_usec
= u
->manager
->defaults
.timeout_stop_usec
;
125 s
->timeout_abort_usec
= u
->manager
->defaults
.timeout_abort_usec
;
126 s
->timeout_abort_set
= u
->manager
->defaults
.timeout_abort_set
;
127 s
->restart_usec
= u
->manager
->defaults
.restart_usec
;
128 s
->restart_max_delay_usec
= USEC_INFINITY
;
129 s
->runtime_max_usec
= USEC_INFINITY
;
130 s
->type
= _SERVICE_TYPE_INVALID
;
131 s
->socket_fd
= -EBADF
;
132 s
->stdin_fd
= s
->stdout_fd
= s
->stderr_fd
= -EBADF
;
133 s
->guess_main_pid
= true;
134 s
->main_pid
= PIDREF_NULL
;
135 s
->control_pid
= PIDREF_NULL
;
136 s
->control_command_id
= _SERVICE_EXEC_COMMAND_INVALID
;
138 s
->exec_context
.keyring_mode
= MANAGER_IS_SYSTEM(u
->manager
) ?
139 EXEC_KEYRING_PRIVATE
: EXEC_KEYRING_INHERIT
;
141 s
->notify_access_override
= _NOTIFY_ACCESS_INVALID
;
143 s
->watchdog_original_usec
= USEC_INFINITY
;
145 s
->oom_policy
= _OOM_POLICY_INVALID
;
146 s
->reload_begin_usec
= USEC_INFINITY
;
147 s
->reload_signal
= SIGHUP
;
149 s
->fd_store_preserve_mode
= EXEC_PRESERVE_RESTART
;
152 static void service_unwatch_control_pid(Service
*s
) {
155 if (!pidref_is_set(&s
->control_pid
))
158 unit_unwatch_pidref(UNIT(s
), &s
->control_pid
);
159 pidref_done(&s
->control_pid
);
162 static void service_unwatch_main_pid(Service
*s
) {
165 if (!pidref_is_set(&s
->main_pid
))
168 unit_unwatch_pidref(UNIT(s
), &s
->main_pid
);
169 pidref_done(&s
->main_pid
);
172 static void service_unwatch_pid_file(Service
*s
) {
173 if (!s
->pid_file_pathspec
)
176 log_unit_debug(UNIT(s
), "Stopping watch for PID file %s", s
->pid_file_pathspec
->path
);
177 path_spec_unwatch(s
->pid_file_pathspec
);
178 path_spec_done(s
->pid_file_pathspec
);
179 s
->pid_file_pathspec
= mfree(s
->pid_file_pathspec
);
182 static int service_set_main_pidref(Service
*s
, PidRef
*pidref
) {
187 /* Takes ownership of the specified pidref on success, but not on failure. */
189 if (!pidref_is_set(pidref
))
192 if (pidref
->pid
<= 1)
195 if (pidref_is_self(pidref
))
198 if (pidref_equal(&s
->main_pid
, pidref
) && s
->main_pid_known
) {
203 if (!pidref_equal(&s
->main_pid
, pidref
)) {
204 service_unwatch_main_pid(s
);
205 exec_status_start(&s
->main_exec_status
, pidref
->pid
);
208 s
->main_pid
= TAKE_PIDREF(*pidref
);
209 s
->main_pid_known
= true;
211 r
= pidref_is_my_child(&s
->main_pid
);
213 log_unit_warning_errno(UNIT(s
), r
, "Can't determine if process "PID_FMT
" is our child, assuming it is not: %m", s
->main_pid
.pid
);
215 log_unit_warning(UNIT(s
), "Supervising process "PID_FMT
" which is not our child. We'll most likely not notice when it exits.", s
->main_pid
.pid
);
217 s
->main_pid_alien
= r
<= 0;
221 void service_release_socket_fd(Service
*s
) {
224 if (s
->socket_fd
< 0 && !UNIT_ISSET(s
->accept_socket
) && !s
->socket_peer
)
227 log_unit_debug(UNIT(s
), "Closing connection socket.");
229 /* Undo the effect of service_set_socket_fd(). */
231 s
->socket_fd
= asynchronous_close(s
->socket_fd
);
233 if (UNIT_ISSET(s
->accept_socket
)) {
234 socket_connection_unref(SOCKET(UNIT_DEREF(s
->accept_socket
)));
235 unit_ref_unset(&s
->accept_socket
);
238 s
->socket_peer
= socket_peer_unref(s
->socket_peer
);
241 static void service_override_notify_access(Service
*s
, NotifyAccess notify_access_override
) {
244 s
->notify_access_override
= notify_access_override
;
246 log_unit_debug(UNIT(s
), "notify_access=%s", notify_access_to_string(s
->notify_access
));
247 log_unit_debug(UNIT(s
), "notify_access_override=%s", notify_access_to_string(s
->notify_access_override
));
250 static void service_stop_watchdog(Service
*s
) {
253 s
->watchdog_event_source
= sd_event_source_disable_unref(s
->watchdog_event_source
);
254 s
->watchdog_timestamp
= DUAL_TIMESTAMP_NULL
;
257 static void service_start_watchdog(Service
*s
) {
258 usec_t watchdog_usec
;
263 watchdog_usec
= service_get_watchdog_usec(s
);
264 if (!timestamp_is_set(watchdog_usec
)) {
265 service_stop_watchdog(s
);
269 if (s
->watchdog_event_source
) {
270 r
= sd_event_source_set_time(s
->watchdog_event_source
, usec_add(s
->watchdog_timestamp
.monotonic
, watchdog_usec
));
272 log_unit_warning_errno(UNIT(s
), r
, "Failed to reset watchdog timer: %m");
276 r
= sd_event_source_set_enabled(s
->watchdog_event_source
, SD_EVENT_ONESHOT
);
278 r
= sd_event_add_time(
279 UNIT(s
)->manager
->event
,
280 &s
->watchdog_event_source
,
282 usec_add(s
->watchdog_timestamp
.monotonic
, watchdog_usec
), 0,
283 service_dispatch_watchdog
, s
);
285 log_unit_warning_errno(UNIT(s
), r
, "Failed to add watchdog timer: %m");
289 (void) sd_event_source_set_description(s
->watchdog_event_source
, "service-watchdog");
291 /* Let's process everything else which might be a sign
292 * of living before we consider a service died. */
293 r
= sd_event_source_set_priority(s
->watchdog_event_source
, SD_EVENT_PRIORITY_IDLE
);
296 log_unit_warning_errno(UNIT(s
), r
, "Failed to install watchdog timer: %m");
299 usec_t
service_restart_usec_next(Service
*s
) {
300 unsigned n_restarts_next
;
304 /* When the service state is in SERVICE_*_BEFORE_AUTO_RESTART or SERVICE_AUTO_RESTART, we still need
305 * to add 1 to s->n_restarts manually, because s->n_restarts is not updated until a restart job is
306 * enqueued, i.e. state has transitioned to SERVICE_AUTO_RESTART_QUEUED. */
307 n_restarts_next
= s
->n_restarts
+ (s
->state
== SERVICE_AUTO_RESTART_QUEUED
? 0 : 1);
309 if (n_restarts_next
<= 1 ||
310 s
->restart_steps
== 0 ||
311 s
->restart_usec
== 0 ||
312 s
->restart_max_delay_usec
== USEC_INFINITY
||
313 s
->restart_usec
>= s
->restart_max_delay_usec
)
314 return s
->restart_usec
;
316 if (n_restarts_next
> s
->restart_steps
)
317 return s
->restart_max_delay_usec
;
319 /* Enforced in service_verify() and above */
320 assert(s
->restart_max_delay_usec
> s
->restart_usec
);
322 /* r_i / r_0 = (r_n / r_0) ^ (i / n)
324 * r_0 : initial restart usec (s->restart_usec),
325 * r_i : i-th restart usec (value),
326 * r_n : maximum restart usec (s->restart_max_delay_usec),
327 * i : index of the next step (n_restarts_next - 1)
328 * n : num maximum steps (s->restart_steps) */
329 return (usec_t
) (s
->restart_usec
* powl((long double) s
->restart_max_delay_usec
/ s
->restart_usec
,
330 (long double) (n_restarts_next
- 1) / s
->restart_steps
));
333 static void service_extend_event_source_timeout(Service
*s
, sd_event_source
*source
, usec_t extended
) {
339 /* Extends the specified event source timer to at least the specified time, unless it is already later
345 r
= sd_event_source_get_time(source
, ¤t
);
348 (void) sd_event_source_get_description(s
->timer_event_source
, &desc
);
349 log_unit_warning_errno(UNIT(s
), r
, "Failed to retrieve timeout time for event source '%s', ignoring: %m", strna(desc
));
353 if (current
>= extended
) /* Current timeout is already longer, ignore this. */
356 r
= sd_event_source_set_time(source
, extended
);
359 (void) sd_event_source_get_description(s
->timer_event_source
, &desc
);
360 log_unit_warning_errno(UNIT(s
), r
, "Failed to set timeout time for event source '%s', ignoring %m", strna(desc
));
364 static void service_extend_timeout(Service
*s
, usec_t extend_timeout_usec
) {
369 if (!timestamp_is_set(extend_timeout_usec
))
372 extended
= usec_add(now(CLOCK_MONOTONIC
), extend_timeout_usec
);
374 service_extend_event_source_timeout(s
, s
->timer_event_source
, extended
);
375 service_extend_event_source_timeout(s
, s
->watchdog_event_source
, extended
);
378 static void service_reset_watchdog(Service
*s
) {
381 dual_timestamp_get(&s
->watchdog_timestamp
);
382 service_start_watchdog(s
);
385 static void service_override_watchdog_timeout(Service
*s
, usec_t watchdog_override_usec
) {
388 s
->watchdog_override_enable
= true;
389 s
->watchdog_override_usec
= watchdog_override_usec
;
390 service_reset_watchdog(s
);
392 log_unit_debug(UNIT(s
), "watchdog_usec="USEC_FMT
, s
->watchdog_usec
);
393 log_unit_debug(UNIT(s
), "watchdog_override_usec="USEC_FMT
, s
->watchdog_override_usec
);
396 static ServiceFDStore
* service_fd_store_unlink(ServiceFDStore
*fs
) {
401 assert(fs
->service
->n_fd_store
> 0);
402 LIST_REMOVE(fd_store
, fs
->service
->fd_store
, fs
);
403 fs
->service
->n_fd_store
--;
406 sd_event_source_disable_unref(fs
->event_source
);
409 asynchronous_close(fs
->fd
);
413 DEFINE_TRIVIAL_CLEANUP_FUNC(ServiceFDStore
*, service_fd_store_unlink
);
415 static void service_release_fd_store(Service
*s
) {
421 log_unit_debug(UNIT(s
), "Releasing all stored fds");
424 service_fd_store_unlink(s
->fd_store
);
426 assert(s
->n_fd_store
== 0);
429 static void service_release_stdio_fd(Service
*s
) {
432 if (s
->stdin_fd
< 0 && s
->stdout_fd
< 0 && s
->stdout_fd
< 0)
435 log_unit_debug(UNIT(s
), "Releasing stdin/stdout/stderr file descriptors.");
437 s
->stdin_fd
= asynchronous_close(s
->stdin_fd
);
438 s
->stdout_fd
= asynchronous_close(s
->stdout_fd
);
439 s
->stderr_fd
= asynchronous_close(s
->stderr_fd
);
441 static void service_done(Unit
*u
) {
442 Service
*s
= SERVICE(u
);
446 open_file_free_many(&s
->open_files
);
448 s
->pid_file
= mfree(s
->pid_file
);
449 s
->status_text
= mfree(s
->status_text
);
451 s
->exec_runtime
= exec_runtime_free(s
->exec_runtime
);
452 exec_command_free_array(s
->exec_command
, _SERVICE_EXEC_COMMAND_MAX
);
453 s
->control_command
= NULL
;
454 s
->main_command
= NULL
;
456 exit_status_set_free(&s
->restart_prevent_status
);
457 exit_status_set_free(&s
->restart_force_status
);
458 exit_status_set_free(&s
->success_status
);
460 /* This will leak a process, but at least no memory or any of our resources */
461 service_unwatch_main_pid(s
);
462 service_unwatch_control_pid(s
);
463 service_unwatch_pid_file(s
);
466 unit_unwatch_bus_name(u
, s
->bus_name
);
467 s
->bus_name
= mfree(s
->bus_name
);
470 s
->bus_name_owner
= mfree(s
->bus_name_owner
);
472 s
->usb_function_descriptors
= mfree(s
->usb_function_descriptors
);
473 s
->usb_function_strings
= mfree(s
->usb_function_strings
);
475 service_stop_watchdog(s
);
477 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
478 s
->exec_fd_event_source
= sd_event_source_disable_unref(s
->exec_fd_event_source
);
480 s
->bus_name_pid_lookup_slot
= sd_bus_slot_unref(s
->bus_name_pid_lookup_slot
);
482 service_release_socket_fd(s
);
483 service_release_stdio_fd(s
);
484 service_release_fd_store(s
);
487 static int on_fd_store_io(sd_event_source
*e
, int fd
, uint32_t revents
, void *userdata
) {
488 ServiceFDStore
*fs
= ASSERT_PTR(userdata
);
492 /* If we get either EPOLLHUP or EPOLLERR, it's time to remove this entry from the fd store */
493 log_unit_debug(UNIT(fs
->service
),
494 "Received %s on stored fd %d (%s), closing.",
495 revents
& EPOLLERR
? "EPOLLERR" : "EPOLLHUP",
496 fs
->fd
, strna(fs
->fdname
));
497 service_fd_store_unlink(fs
);
501 static int service_add_fd_store(Service
*s
, int fd_in
, const char *name
, bool do_poll
) {
502 _cleanup_(service_fd_store_unlinkp
) ServiceFDStore
*fs
= NULL
;
503 _cleanup_(asynchronous_closep
) int fd
= ASSERT_FD(fd_in
);
507 /* fd is always consumed even if the function fails. */
511 if (fstat(fd
, &st
) < 0)
514 log_unit_debug(UNIT(s
), "Trying to stash fd for dev=" DEVNUM_FORMAT_STR
"/inode=%" PRIu64
, DEVNUM_FORMAT_VAL(st
.st_dev
), (uint64_t) st
.st_ino
);
516 if (s
->n_fd_store
>= s
->n_fd_store_max
)
517 /* Our store is full. Use this errno rather than E[NM]FILE to distinguish from the case
518 * where systemd itself hits the file limit. */
519 return log_unit_debug_errno(UNIT(s
), SYNTHETIC_ERRNO(EXFULL
), "Hit fd store limit.");
521 LIST_FOREACH(fd_store
, i
, s
->fd_store
) {
522 r
= same_fd(i
->fd
, fd
);
526 log_unit_debug(UNIT(s
), "Suppressing duplicate fd %i in fd store.", fd
);
527 return 0; /* fd already included */
531 fs
= new(ServiceFDStore
, 1);
535 *fs
= (ServiceFDStore
) {
538 .fdname
= strdup(name
?: "stored"),
545 r
= sd_event_add_io(UNIT(s
)->manager
->event
, &fs
->event_source
, fs
->fd
, 0, on_fd_store_io
, fs
);
546 if (r
< 0 && r
!= -EPERM
) /* EPERM indicates fds that aren't pollable, which is OK */
549 (void) sd_event_source_set_description(fs
->event_source
, "service-fd-store");
553 LIST_PREPEND(fd_store
, s
->fd_store
, fs
);
556 log_unit_debug(UNIT(s
), "Added fd %i (%s) to fd store.", fs
->fd
, fs
->fdname
);
559 return 1; /* fd newly stored */
562 static int service_add_fd_store_set(Service
*s
, FDSet
*fds
, const char *name
, bool do_poll
) {
570 fd
= fdset_steal_first(fds
);
574 r
= service_add_fd_store(s
, fd
, name
, do_poll
);
576 return log_unit_warning_errno(UNIT(s
), r
,
577 "Cannot store more fds than FileDescriptorStoreMax=%u, closing remaining.",
580 return log_unit_error_errno(UNIT(s
), r
, "Failed to add fd to store: %m");
586 static void service_remove_fd_store(Service
*s
, const char *name
) {
590 LIST_FOREACH(fd_store
, fs
, s
->fd_store
) {
591 if (!streq(fs
->fdname
, name
))
594 log_unit_debug(UNIT(s
), "Got explicit request to remove fd %i (%s), closing.", fs
->fd
, name
);
595 service_fd_store_unlink(fs
);
599 static usec_t
service_running_timeout(Service
*s
) {
604 if (s
->runtime_rand_extra_usec
!= 0) {
605 delta
= random_u64_range(s
->runtime_rand_extra_usec
);
606 log_unit_debug(UNIT(s
), "Adding delta of %s sec to timeout", FORMAT_TIMESPAN(delta
, USEC_PER_SEC
));
609 return usec_add(usec_add(UNIT(s
)->active_enter_timestamp
.monotonic
,
610 s
->runtime_max_usec
),
614 static int service_arm_timer(Service
*s
, bool relative
, usec_t usec
) {
617 return unit_arm_timer(UNIT(s
), &s
->timer_event_source
, relative
, usec
, service_dispatch_timer
);
620 static int service_verify(Service
*s
) {
622 assert(UNIT(s
)->load_state
== UNIT_LOADED
);
624 for (ServiceExecCommand c
= 0; c
< _SERVICE_EXEC_COMMAND_MAX
; c
++)
625 LIST_FOREACH(command
, command
, s
->exec_command
[c
]) {
626 if (!path_is_absolute(command
->path
) && !filename_is_valid(command
->path
))
627 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
),
628 "Service %s= binary path \"%s\" is neither a valid executable name nor an absolute path. Refusing.",
630 service_exec_command_to_string(c
));
631 if (strv_isempty(command
->argv
))
632 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
),
633 "Service has an empty argv in %s=. Refusing.",
634 service_exec_command_to_string(c
));
637 if (!s
->exec_command
[SERVICE_EXEC_START
] && !s
->exec_command
[SERVICE_EXEC_STOP
] &&
638 UNIT(s
)->success_action
== EMERGENCY_ACTION_NONE
)
639 /* FailureAction= only makes sense if one of the start or stop commands is specified.
640 * SuccessAction= will be executed unconditionally if no commands are specified. Hence,
641 * either a command or SuccessAction= are required. */
643 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Service has no ExecStart=, ExecStop=, or SuccessAction=. Refusing.");
645 if (s
->type
!= SERVICE_ONESHOT
&& !s
->exec_command
[SERVICE_EXEC_START
])
646 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Service has no ExecStart= setting, which is only allowed for Type=oneshot services. Refusing.");
648 if (!s
->remain_after_exit
&& !s
->exec_command
[SERVICE_EXEC_START
] && UNIT(s
)->success_action
== EMERGENCY_ACTION_NONE
)
649 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Service has no ExecStart= and no SuccessAction= settings and does not have RemainAfterExit=yes set. Refusing.");
651 if (s
->type
!= SERVICE_ONESHOT
&& s
->exec_command
[SERVICE_EXEC_START
]->command_next
)
652 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Service has more than one ExecStart= setting, which is only allowed for Type=oneshot services. Refusing.");
654 if (s
->type
== SERVICE_ONESHOT
&&
655 !IN_SET(s
->restart
, SERVICE_RESTART_NO
, SERVICE_RESTART_ON_FAILURE
, SERVICE_RESTART_ON_ABNORMAL
, SERVICE_RESTART_ON_WATCHDOG
, SERVICE_RESTART_ON_ABORT
))
656 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Service has Restart= set to either always or on-success, which isn't allowed for Type=oneshot services. Refusing.");
658 if (s
->type
== SERVICE_ONESHOT
&& !exit_status_set_is_empty(&s
->restart_force_status
))
659 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Service has RestartForceExitStatus= set, which isn't allowed for Type=oneshot services. Refusing.");
661 if (s
->type
== SERVICE_ONESHOT
&& s
->exit_type
== SERVICE_EXIT_CGROUP
)
662 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Service has ExitType=cgroup set, which isn't allowed for Type=oneshot services. Refusing.");
664 if (s
->type
== SERVICE_DBUS
&& !s
->bus_name
)
665 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Service is of type D-Bus but no D-Bus service name has been specified. Refusing.");
667 if (s
->exec_context
.pam_name
&& !IN_SET(s
->kill_context
.kill_mode
, KILL_CONTROL_GROUP
, KILL_MIXED
))
668 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Service has PAM enabled. Kill mode must be set to 'control-group' or 'mixed'. Refusing.");
670 if (s
->usb_function_descriptors
&& !s
->usb_function_strings
)
671 log_unit_warning(UNIT(s
), "Service has USBFunctionDescriptors= setting, but no USBFunctionStrings=. Ignoring.");
673 if (!s
->usb_function_descriptors
&& s
->usb_function_strings
)
674 log_unit_warning(UNIT(s
), "Service has USBFunctionStrings= setting, but no USBFunctionDescriptors=. Ignoring.");
676 if (s
->runtime_max_usec
!= USEC_INFINITY
&& s
->type
== SERVICE_ONESHOT
)
677 log_unit_warning(UNIT(s
), "RuntimeMaxSec= has no effect in combination with Type=oneshot. Ignoring.");
679 if (s
->runtime_max_usec
== USEC_INFINITY
&& s
->runtime_rand_extra_usec
!= 0)
680 log_unit_warning(UNIT(s
), "Service has RuntimeRandomizedExtraSec= setting, but no RuntimeMaxSec=. Ignoring.");
682 if (s
->exit_type
== SERVICE_EXIT_CGROUP
&& cg_unified() < CGROUP_UNIFIED_SYSTEMD
)
683 log_unit_warning(UNIT(s
), "Service has ExitType=cgroup set, but we are running with legacy cgroups v1, which might not work correctly. Continuing.");
685 if (s
->restart_max_delay_usec
== USEC_INFINITY
&& s
->restart_steps
> 0)
686 log_unit_warning(UNIT(s
), "Service has RestartSteps= but no RestartMaxDelaySec= setting. Ignoring.");
688 if (s
->restart_max_delay_usec
!= USEC_INFINITY
&& s
->restart_steps
== 0)
689 log_unit_warning(UNIT(s
), "Service has RestartMaxDelaySec= but no RestartSteps= setting. Ignoring.");
691 if (s
->restart_max_delay_usec
< s
->restart_usec
) {
692 log_unit_warning(UNIT(s
), "RestartMaxDelaySec= has a value smaller than RestartSec=, resetting RestartSec= to RestartMaxDelaySec=.");
693 s
->restart_usec
= s
->restart_max_delay_usec
;
699 static int service_add_default_dependencies(Service
*s
) {
704 if (!UNIT(s
)->default_dependencies
)
707 /* Add a number of automatic dependencies useful for the
708 * majority of services. */
710 if (MANAGER_IS_SYSTEM(UNIT(s
)->manager
)) {
711 /* First, pull in the really early boot stuff, and
712 * require it, so that we fail if we can't acquire
715 r
= unit_add_two_dependencies_by_name(UNIT(s
), UNIT_AFTER
, UNIT_REQUIRES
, SPECIAL_SYSINIT_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
720 /* In the --user instance there's no sysinit.target,
721 * in that case require basic.target instead. */
723 r
= unit_add_dependency_by_name(UNIT(s
), UNIT_REQUIRES
, SPECIAL_BASIC_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
728 /* Second, if the rest of the base system is in the same
729 * transaction, order us after it, but do not pull it in or
730 * even require it. */
731 r
= unit_add_dependency_by_name(UNIT(s
), UNIT_AFTER
, SPECIAL_BASIC_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
735 /* Third, add us in for normal shutdown. */
736 return unit_add_two_dependencies_by_name(UNIT(s
), UNIT_BEFORE
, UNIT_CONFLICTS
, SPECIAL_SHUTDOWN_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
739 static void service_fix_stdio(Service
*s
) {
742 /* Note that EXEC_INPUT_NULL and EXEC_OUTPUT_INHERIT play a special role here: they are both the
743 * default value that is subject to automatic overriding triggered by other settings and an explicit
744 * choice the user can make. We don't distinguish between these cases currently. */
746 if (s
->exec_context
.std_input
== EXEC_INPUT_NULL
&&
747 s
->exec_context
.stdin_data_size
> 0)
748 s
->exec_context
.std_input
= EXEC_INPUT_DATA
;
750 if (IN_SET(s
->exec_context
.std_input
,
752 EXEC_INPUT_TTY_FORCE
,
755 EXEC_INPUT_NAMED_FD
))
758 /* We assume these listed inputs refer to bidirectional streams, and hence duplicating them from
759 * stdin to stdout/stderr makes sense and hence leaving EXEC_OUTPUT_INHERIT in place makes sense,
760 * too. Outputs such as regular files or sealed data memfds otoh don't really make sense to be
761 * duplicated for both input and output at the same time (since they then would cause a feedback
762 * loop), hence override EXEC_OUTPUT_INHERIT with the default stderr/stdout setting. */
764 if (s
->exec_context
.std_error
== EXEC_OUTPUT_INHERIT
&&
765 s
->exec_context
.std_output
== EXEC_OUTPUT_INHERIT
)
766 s
->exec_context
.std_error
= UNIT(s
)->manager
->defaults
.std_error
;
768 if (s
->exec_context
.std_output
== EXEC_OUTPUT_INHERIT
)
769 s
->exec_context
.std_output
= UNIT(s
)->manager
->defaults
.std_output
;
772 static int service_setup_bus_name(Service
*s
) {
777 /* If s->bus_name is not set, then the unit will be refused by service_verify() later. */
781 if (s
->type
== SERVICE_DBUS
) {
782 r
= unit_add_dependency_by_name(UNIT(s
), UNIT_REQUIRES
, SPECIAL_DBUS_SOCKET
, true, UNIT_DEPENDENCY_FILE
);
784 return log_unit_error_errno(UNIT(s
), r
, "Failed to add dependency on " SPECIAL_DBUS_SOCKET
": %m");
786 /* We always want to be ordered against dbus.socket if both are in the transaction. */
787 r
= unit_add_dependency_by_name(UNIT(s
), UNIT_AFTER
, SPECIAL_DBUS_SOCKET
, true, UNIT_DEPENDENCY_FILE
);
789 return log_unit_error_errno(UNIT(s
), r
, "Failed to add dependency on " SPECIAL_DBUS_SOCKET
": %m");
792 r
= unit_watch_bus_name(UNIT(s
), s
->bus_name
);
794 return log_unit_error_errno(UNIT(s
), r
, "Two services allocated for the same bus name %s, refusing operation.", s
->bus_name
);
796 return log_unit_error_errno(UNIT(s
), r
, "Cannot watch bus name %s: %m", s
->bus_name
);
801 static int service_add_extras(Service
*s
) {
806 if (s
->type
== _SERVICE_TYPE_INVALID
) {
807 /* Figure out a type automatically */
809 s
->type
= SERVICE_DBUS
;
810 else if (s
->exec_command
[SERVICE_EXEC_START
])
811 s
->type
= SERVICE_SIMPLE
;
813 s
->type
= SERVICE_ONESHOT
;
816 /* Oneshot services have disabled start timeout by default */
817 if (s
->type
== SERVICE_ONESHOT
&& !s
->start_timeout_defined
)
818 s
->timeout_start_usec
= USEC_INFINITY
;
820 service_fix_stdio(s
);
822 r
= unit_patch_contexts(UNIT(s
));
826 r
= unit_add_exec_dependencies(UNIT(s
), &s
->exec_context
);
830 r
= unit_set_default_slice(UNIT(s
));
834 /* If the service needs the notify socket, let's enable it automatically. */
835 if (s
->notify_access
== NOTIFY_NONE
&&
836 (IN_SET(s
->type
, SERVICE_NOTIFY
, SERVICE_NOTIFY_RELOAD
) || s
->watchdog_usec
> 0 || s
->n_fd_store_max
> 0))
837 s
->notify_access
= NOTIFY_MAIN
;
839 /* If no OOM policy was explicitly set, then default to the configure default OOM policy. Except when
840 * delegation is on, in that case it we assume the payload knows better what to do and can process
841 * things in a more focused way. */
842 if (s
->oom_policy
< 0)
843 s
->oom_policy
= s
->cgroup_context
.delegate
? OOM_CONTINUE
: UNIT(s
)->manager
->defaults
.oom_policy
;
845 /* Let the kernel do the killing if that's requested. */
846 s
->cgroup_context
.memory_oom_group
= s
->oom_policy
== OOM_KILL
;
848 r
= service_add_default_dependencies(s
);
852 r
= service_setup_bus_name(s
);
859 static int service_load(Unit
*u
) {
860 Service
*s
= SERVICE(u
);
863 r
= unit_load_fragment_and_dropin(u
, true);
867 if (u
->load_state
!= UNIT_LOADED
)
870 /* This is a new unit? Then let's add in some extras */
871 r
= service_add_extras(s
);
875 return service_verify(s
);
878 static void service_dump_fdstore(Service
*s
, FILE *f
, const char *prefix
) {
883 LIST_FOREACH(fd_store
, i
, s
->fd_store
) {
884 _cleanup_free_
char *path
= NULL
;
888 if (fstat(i
->fd
, &st
) < 0) {
889 log_debug_errno(errno
, "Failed to stat fdstore entry: %m");
893 flags
= fcntl(i
->fd
, F_GETFL
);
895 log_debug_errno(errno
, "Failed to get fdstore entry flags: %m");
899 (void) fd_get_path(i
->fd
, &path
);
902 "%s%s '%s' (type=%s; dev=" DEVNUM_FORMAT_STR
"; inode=%" PRIu64
"; rdev=" DEVNUM_FORMAT_STR
"; path=%s; access=%s)\n",
903 prefix
, i
== s
->fd_store
? "File Descriptor Store Entry:" : " ",
905 inode_type_to_string(st
.st_mode
),
906 DEVNUM_FORMAT_VAL(st
.st_dev
),
907 (uint64_t) st
.st_ino
,
908 DEVNUM_FORMAT_VAL(st
.st_rdev
),
910 accmode_to_string(flags
));
914 static void service_dump(Unit
*u
, FILE *f
, const char *prefix
) {
915 Service
*s
= SERVICE(u
);
920 prefix
= strempty(prefix
);
921 prefix2
= strjoina(prefix
, "\t");
924 "%sService State: %s\n"
926 "%sReload Result: %s\n"
927 "%sClean Result: %s\n"
928 "%sPermissionsStartOnly: %s\n"
929 "%sRootDirectoryStartOnly: %s\n"
930 "%sRemainAfterExit: %s\n"
931 "%sGuessMainPID: %s\n"
934 "%sNotifyAccess: %s\n"
935 "%sNotifyState: %s\n"
937 "%sReloadSignal: %s\n",
938 prefix
, service_state_to_string(s
->state
),
939 prefix
, service_result_to_string(s
->result
),
940 prefix
, service_result_to_string(s
->reload_result
),
941 prefix
, service_result_to_string(s
->clean_result
),
942 prefix
, yes_no(s
->permissions_start_only
),
943 prefix
, yes_no(s
->root_directory_start_only
),
944 prefix
, yes_no(s
->remain_after_exit
),
945 prefix
, yes_no(s
->guess_main_pid
),
946 prefix
, service_type_to_string(s
->type
),
947 prefix
, service_restart_to_string(s
->restart
),
948 prefix
, notify_access_to_string(service_get_notify_access(s
)),
949 prefix
, notify_state_to_string(s
->notify_state
),
950 prefix
, oom_policy_to_string(s
->oom_policy
),
951 prefix
, signal_to_string(s
->reload_signal
));
953 if (pidref_is_set(&s
->control_pid
))
955 "%sControl PID: "PID_FMT
"\n",
956 prefix
, s
->control_pid
.pid
);
958 if (pidref_is_set(&s
->main_pid
))
960 "%sMain PID: "PID_FMT
"\n"
961 "%sMain PID Known: %s\n"
962 "%sMain PID Alien: %s\n",
963 prefix
, s
->main_pid
.pid
,
964 prefix
, yes_no(s
->main_pid_known
),
965 prefix
, yes_no(s
->main_pid_alien
));
970 prefix
, s
->pid_file
);
975 "%sBus Name Good: %s\n",
977 prefix
, yes_no(s
->bus_name_good
));
979 if (UNIT_ISSET(s
->accept_socket
))
981 "%sAccept Socket: %s\n",
982 prefix
, UNIT_DEREF(s
->accept_socket
)->id
);
986 "%sRestartSteps: %u\n"
987 "%sRestartMaxDelaySec: %s\n"
988 "%sTimeoutStartSec: %s\n"
989 "%sTimeoutStopSec: %s\n"
990 "%sTimeoutStartFailureMode: %s\n"
991 "%sTimeoutStopFailureMode: %s\n",
992 prefix
, FORMAT_TIMESPAN(s
->restart_usec
, USEC_PER_SEC
),
993 prefix
, s
->restart_steps
,
994 prefix
, FORMAT_TIMESPAN(s
->restart_max_delay_usec
, USEC_PER_SEC
),
995 prefix
, FORMAT_TIMESPAN(s
->timeout_start_usec
, USEC_PER_SEC
),
996 prefix
, FORMAT_TIMESPAN(s
->timeout_stop_usec
, USEC_PER_SEC
),
997 prefix
, service_timeout_failure_mode_to_string(s
->timeout_start_failure_mode
),
998 prefix
, service_timeout_failure_mode_to_string(s
->timeout_stop_failure_mode
));
1000 if (s
->timeout_abort_set
)
1002 "%sTimeoutAbortSec: %s\n",
1003 prefix
, FORMAT_TIMESPAN(s
->timeout_abort_usec
, USEC_PER_SEC
));
1006 "%sRuntimeMaxSec: %s\n"
1007 "%sRuntimeRandomizedExtraSec: %s\n"
1008 "%sWatchdogSec: %s\n",
1009 prefix
, FORMAT_TIMESPAN(s
->runtime_max_usec
, USEC_PER_SEC
),
1010 prefix
, FORMAT_TIMESPAN(s
->runtime_rand_extra_usec
, USEC_PER_SEC
),
1011 prefix
, FORMAT_TIMESPAN(s
->watchdog_usec
, USEC_PER_SEC
));
1013 kill_context_dump(&s
->kill_context
, f
, prefix
);
1014 exec_context_dump(&s
->exec_context
, f
, prefix
);
1016 for (ServiceExecCommand c
= 0; c
< _SERVICE_EXEC_COMMAND_MAX
; c
++) {
1017 if (!s
->exec_command
[c
])
1020 fprintf(f
, "%s-> %s:\n",
1021 prefix
, service_exec_command_to_string(c
));
1023 exec_command_dump_list(s
->exec_command
[c
], f
, prefix2
);
1027 fprintf(f
, "%sStatus Text: %s\n",
1028 prefix
, s
->status_text
);
1030 if (s
->n_fd_store_max
> 0)
1032 "%sFile Descriptor Store Max: %u\n"
1033 "%sFile Descriptor Store Pin: %s\n"
1034 "%sFile Descriptor Store Current: %zu\n",
1035 prefix
, s
->n_fd_store_max
,
1036 prefix
, exec_preserve_mode_to_string(s
->fd_store_preserve_mode
),
1037 prefix
, s
->n_fd_store
);
1039 service_dump_fdstore(s
, f
, prefix
);
1042 LIST_FOREACH(open_files
, of
, s
->open_files
) {
1043 _cleanup_free_
char *ofs
= NULL
;
1046 r
= open_file_to_string(of
, &ofs
);
1049 "Failed to convert OpenFile= setting to string, ignoring: %m");
1053 fprintf(f
, "%sOpen File: %s\n", prefix
, ofs
);
1056 cgroup_context_dump(UNIT(s
), f
, prefix
);
1059 static int service_is_suitable_main_pid(Service
*s
, PidRef
*pid
, int prio
) {
1064 assert(pidref_is_set(pid
));
1066 /* Checks whether the specified PID is suitable as main PID for this service. returns negative if not, 0 if the
1067 * PID is questionnable but should be accepted if the source of configuration is trusted. > 0 if the PID is
1070 if (pidref_is_self(pid
) || pid
->pid
== 1)
1071 return log_unit_full_errno(UNIT(s
), prio
, SYNTHETIC_ERRNO(EPERM
), "New main PID "PID_FMT
" is the manager, refusing.", pid
->pid
);
1073 if (pidref_equal(pid
, &s
->control_pid
))
1074 return log_unit_full_errno(UNIT(s
), prio
, SYNTHETIC_ERRNO(EPERM
), "New main PID "PID_FMT
" is the control process, refusing.", pid
->pid
);
1076 r
= pidref_is_alive(pid
);
1078 return log_unit_full_errno(UNIT(s
), prio
, r
, "Failed to check if main PID "PID_FMT
" exists or is a zombie: %m", pid
->pid
);
1080 return log_unit_full_errno(UNIT(s
), prio
, SYNTHETIC_ERRNO(ESRCH
), "New main PID "PID_FMT
" does not exist or is a zombie.", pid
->pid
);
1082 owner
= manager_get_unit_by_pidref(UNIT(s
)->manager
, pid
);
1083 if (owner
== UNIT(s
)) {
1084 log_unit_debug(UNIT(s
), "New main PID "PID_FMT
" belongs to service, we are happy.", pid
->pid
);
1085 return 1; /* Yay, it's definitely a good PID */
1088 return 0; /* Hmm it's a suspicious PID, let's accept it if configuration source is trusted */
1091 static int service_load_pid_file(Service
*s
, bool may_warn
) {
1092 _cleanup_(pidref_done
) PidRef pidref
= PIDREF_NULL
;
1093 bool questionable_pid_file
= false;
1094 _cleanup_free_
char *k
= NULL
;
1095 _cleanup_close_
int fd
= -EBADF
;
1103 prio
= may_warn
? LOG_INFO
: LOG_DEBUG
;
1105 r
= chase(s
->pid_file
, NULL
, CHASE_SAFE
, NULL
, &fd
);
1106 if (r
== -ENOLINK
) {
1107 log_unit_debug_errno(UNIT(s
), r
,
1108 "Potentially unsafe symlink chain, will now retry with relaxed checks: %s", s
->pid_file
);
1110 questionable_pid_file
= true;
1112 r
= chase(s
->pid_file
, NULL
, 0, NULL
, &fd
);
1115 return log_unit_full_errno(UNIT(s
), prio
, r
,
1116 "Can't open PID file %s (yet?) after %s: %m", s
->pid_file
, service_state_to_string(s
->state
));
1118 /* Let's read the PID file now that we chased it down. But we need to convert the O_PATH fd
1119 * chase() returned us into a proper fd first. */
1120 r
= read_one_line_file(FORMAT_PROC_FD_PATH(fd
), &k
);
1122 return log_unit_error_errno(UNIT(s
), r
,
1123 "Can't convert PID files %s O_PATH file descriptor to proper file descriptor: %m",
1126 r
= pidref_set_pidstr(&pidref
, k
);
1128 return log_unit_full_errno(UNIT(s
), prio
, r
, "Failed to parse PID from file %s: %m", s
->pid_file
);
1130 if (s
->main_pid_known
&& pidref_equal(&pidref
, &s
->main_pid
))
1133 r
= service_is_suitable_main_pid(s
, &pidref
, prio
);
1139 if (questionable_pid_file
)
1140 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(EPERM
),
1141 "Refusing to accept PID outside of service control group, acquired through unsafe symlink chain: %s", s
->pid_file
);
1143 /* Hmm, it's not clear if the new main PID is safe. Let's allow this if the PID file is owned by root */
1145 if (fstat(fd
, &st
) < 0)
1146 return log_unit_error_errno(UNIT(s
), errno
, "Failed to fstat() PID file O_PATH fd: %m");
1149 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(EPERM
),
1150 "New main PID "PID_FMT
" does not belong to service, and PID file is not owned by root. Refusing.", pidref
.pid
);
1152 log_unit_debug(UNIT(s
), "New main PID "PID_FMT
" does not belong to service, but we'll accept it since PID file is owned by root.", pidref
.pid
);
1155 if (s
->main_pid_known
) {
1156 log_unit_debug(UNIT(s
), "Main PID changing: "PID_FMT
" -> "PID_FMT
, s
->main_pid
.pid
, pidref
.pid
);
1158 service_unwatch_main_pid(s
);
1159 s
->main_pid_known
= false;
1161 log_unit_debug(UNIT(s
), "Main PID loaded: "PID_FMT
, pidref
.pid
);
1163 r
= service_set_main_pidref(s
, &pidref
);
1167 r
= unit_watch_pidref(UNIT(s
), &s
->main_pid
, /* exclusive= */ false);
1168 if (r
< 0) /* FIXME: we need to do something here */
1169 return log_unit_warning_errno(UNIT(s
), r
, "Failed to watch PID "PID_FMT
" for service: %m", s
->main_pid
.pid
);
1174 static void service_search_main_pid(Service
*s
) {
1175 _cleanup_(pidref_done
) PidRef pid
= PIDREF_NULL
;
1180 /* If we know it anyway, don't ever fall back to unreliable heuristics */
1181 if (s
->main_pid_known
)
1184 if (!s
->guess_main_pid
)
1187 assert(!pidref_is_set(&s
->main_pid
));
1189 if (unit_search_main_pid(UNIT(s
), &pid
) < 0)
1192 log_unit_debug(UNIT(s
), "Main PID guessed: "PID_FMT
, pid
.pid
);
1193 if (service_set_main_pidref(s
, &pid
) < 0)
1196 r
= unit_watch_pidref(UNIT(s
), &s
->main_pid
, /* exclusive= */ false);
1198 /* FIXME: we need to do something here */
1199 log_unit_warning_errno(UNIT(s
), r
, "Failed to watch PID "PID_FMT
" from: %m", s
->main_pid
.pid
);
1202 static void service_set_state(Service
*s
, ServiceState state
) {
1203 ServiceState old_state
;
1204 const UnitActiveState
*table
;
1208 if (s
->state
!= state
)
1209 bus_unit_send_pending_change_signal(UNIT(s
), false);
1211 table
= s
->type
== SERVICE_IDLE
? state_translation_table_idle
: state_translation_table
;
1213 old_state
= s
->state
;
1216 service_unwatch_pid_file(s
);
1219 SERVICE_CONDITION
, SERVICE_START_PRE
, SERVICE_START
, SERVICE_START_POST
,
1221 SERVICE_RELOAD
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
,
1222 SERVICE_STOP
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
, SERVICE_STOP_POST
,
1223 SERVICE_FINAL_WATCHDOG
, SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
,
1224 SERVICE_AUTO_RESTART
,
1226 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
1229 SERVICE_START
, SERVICE_START_POST
,
1231 SERVICE_RELOAD
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
,
1232 SERVICE_STOP
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
, SERVICE_STOP_POST
,
1233 SERVICE_FINAL_WATCHDOG
, SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
)) {
1234 service_unwatch_main_pid(s
);
1235 s
->main_command
= NULL
;
1239 SERVICE_CONDITION
, SERVICE_START_PRE
, SERVICE_START
, SERVICE_START_POST
,
1240 SERVICE_RELOAD
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
,
1241 SERVICE_STOP
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
, SERVICE_STOP_POST
,
1242 SERVICE_FINAL_WATCHDOG
, SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
,
1243 SERVICE_CLEANING
)) {
1244 service_unwatch_control_pid(s
);
1245 s
->control_command
= NULL
;
1246 s
->control_command_id
= _SERVICE_EXEC_COMMAND_INVALID
;
1250 SERVICE_DEAD
, SERVICE_FAILED
,
1251 SERVICE_DEAD_BEFORE_AUTO_RESTART
, SERVICE_FAILED_BEFORE_AUTO_RESTART
, SERVICE_AUTO_RESTART
, SERVICE_AUTO_RESTART_QUEUED
,
1252 SERVICE_DEAD_RESOURCES_PINNED
)) {
1253 unit_unwatch_all_pids(UNIT(s
));
1254 unit_dequeue_rewatch_pids(UNIT(s
));
1257 if (state
!= SERVICE_START
)
1258 s
->exec_fd_event_source
= sd_event_source_disable_unref(s
->exec_fd_event_source
);
1260 if (!IN_SET(state
, SERVICE_START_POST
, SERVICE_RUNNING
, SERVICE_RELOAD
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
))
1261 service_stop_watchdog(s
);
1263 /* For the inactive states unit_notify() will trim the cgroup,
1264 * but for exit we have to do that ourselves... */
1265 if (state
== SERVICE_EXITED
&& !MANAGER_IS_RELOADING(UNIT(s
)->manager
))
1266 unit_prune_cgroup(UNIT(s
));
1268 if (old_state
!= state
)
1269 log_unit_debug(UNIT(s
), "Changed %s -> %s", service_state_to_string(old_state
), service_state_to_string(state
));
1271 unit_notify(UNIT(s
), table
[old_state
], table
[state
], s
->reload_result
== SERVICE_SUCCESS
);
1274 static usec_t
service_coldplug_timeout(Service
*s
) {
1277 switch (s
->deserialized_state
) {
1279 case SERVICE_CONDITION
:
1280 case SERVICE_START_PRE
:
1282 case SERVICE_START_POST
:
1283 case SERVICE_RELOAD
:
1284 case SERVICE_RELOAD_SIGNAL
:
1285 case SERVICE_RELOAD_NOTIFY
:
1286 return usec_add(UNIT(s
)->state_change_timestamp
.monotonic
, s
->timeout_start_usec
);
1288 case SERVICE_RUNNING
:
1289 return service_running_timeout(s
);
1292 case SERVICE_STOP_SIGTERM
:
1293 case SERVICE_STOP_SIGKILL
:
1294 case SERVICE_STOP_POST
:
1295 case SERVICE_FINAL_SIGTERM
:
1296 case SERVICE_FINAL_SIGKILL
:
1297 return usec_add(UNIT(s
)->state_change_timestamp
.monotonic
, s
->timeout_stop_usec
);
1299 case SERVICE_STOP_WATCHDOG
:
1300 case SERVICE_FINAL_WATCHDOG
:
1301 return usec_add(UNIT(s
)->state_change_timestamp
.monotonic
, service_timeout_abort_usec(s
));
1303 case SERVICE_AUTO_RESTART
:
1304 return usec_add(UNIT(s
)->inactive_enter_timestamp
.monotonic
, service_restart_usec_next(s
));
1306 case SERVICE_CLEANING
:
1307 return usec_add(UNIT(s
)->state_change_timestamp
.monotonic
, s
->exec_context
.timeout_clean_usec
);
1310 return USEC_INFINITY
;
1314 static int service_coldplug(Unit
*u
) {
1315 Service
*s
= SERVICE(u
);
1319 assert(s
->state
== SERVICE_DEAD
);
1321 if (s
->deserialized_state
== s
->state
)
1324 r
= service_arm_timer(s
, /* relative= */ false, service_coldplug_timeout(s
));
1328 if (pidref_is_set(&s
->main_pid
) &&
1329 pidref_is_unwaited(&s
->main_pid
) > 0 &&
1330 (IN_SET(s
->deserialized_state
,
1331 SERVICE_START
, SERVICE_START_POST
,
1333 SERVICE_RELOAD
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
,
1334 SERVICE_STOP
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
, SERVICE_STOP_POST
,
1335 SERVICE_FINAL_WATCHDOG
, SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
))) {
1336 r
= unit_watch_pidref(UNIT(s
), &s
->main_pid
, /* exclusive= */ false);
1341 if (pidref_is_set(&s
->control_pid
) &&
1342 pidref_is_unwaited(&s
->control_pid
) > 0 &&
1343 IN_SET(s
->deserialized_state
,
1344 SERVICE_CONDITION
, SERVICE_START_PRE
, SERVICE_START
, SERVICE_START_POST
,
1345 SERVICE_RELOAD
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
,
1346 SERVICE_STOP
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
, SERVICE_STOP_POST
,
1347 SERVICE_FINAL_WATCHDOG
, SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
,
1348 SERVICE_CLEANING
)) {
1349 r
= unit_watch_pidref(UNIT(s
), &s
->control_pid
, /* exclusive= */ false);
1354 if (!IN_SET(s
->deserialized_state
,
1355 SERVICE_DEAD
, SERVICE_FAILED
,
1356 SERVICE_DEAD_BEFORE_AUTO_RESTART
, SERVICE_FAILED_BEFORE_AUTO_RESTART
, SERVICE_AUTO_RESTART
, SERVICE_AUTO_RESTART_QUEUED
,
1358 SERVICE_DEAD_RESOURCES_PINNED
)) {
1359 (void) unit_enqueue_rewatch_pids(u
);
1360 (void) unit_setup_exec_runtime(u
);
1363 if (IN_SET(s
->deserialized_state
, SERVICE_START_POST
, SERVICE_RUNNING
, SERVICE_RELOAD
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
))
1364 service_start_watchdog(s
);
1366 if (UNIT_ISSET(s
->accept_socket
)) {
1367 Socket
* socket
= SOCKET(UNIT_DEREF(s
->accept_socket
));
1369 if (socket
->max_connections_per_source
> 0) {
1372 /* Make a best-effort attempt at bumping the connection count */
1373 if (socket_acquire_peer(socket
, s
->socket_fd
, &peer
) > 0) {
1374 socket_peer_unref(s
->socket_peer
);
1375 s
->socket_peer
= peer
;
1380 service_set_state(s
, s
->deserialized_state
);
1384 static int service_collect_fds(
1388 size_t *n_socket_fds
,
1389 size_t *n_storage_fds
) {
1391 _cleanup_strv_free_
char **rfd_names
= NULL
;
1392 _cleanup_free_
int *rfds
= NULL
;
1393 size_t rn_socket_fds
= 0, rn_storage_fds
= 0;
1399 assert(n_socket_fds
);
1400 assert(n_storage_fds
);
1402 if (s
->socket_fd
>= 0) {
1404 /* Pass the per-connection socket */
1406 rfds
= newdup(int, &s
->socket_fd
, 1);
1410 rfd_names
= strv_new("connection");
1418 /* Pass all our configured sockets for singleton services */
1420 UNIT_FOREACH_DEPENDENCY(u
, UNIT(s
), UNIT_ATOM_TRIGGERED_BY
) {
1421 _cleanup_free_
int *cfds
= NULL
;
1425 if (u
->type
!= UNIT_SOCKET
)
1430 cn_fds
= socket_collect_fds(sock
, &cfds
);
1438 rfds
= TAKE_PTR(cfds
);
1439 rn_socket_fds
= cn_fds
;
1443 t
= reallocarray(rfds
, rn_socket_fds
+ cn_fds
, sizeof(int));
1447 memcpy(t
+ rn_socket_fds
, cfds
, cn_fds
* sizeof(int));
1450 rn_socket_fds
+= cn_fds
;
1453 r
= strv_extend_n(&rfd_names
, socket_fdname(sock
), cn_fds
);
1459 if (s
->n_fd_store
> 0) {
1464 t
= reallocarray(rfds
, rn_socket_fds
+ s
->n_fd_store
, sizeof(int));
1470 nl
= reallocarray(rfd_names
, rn_socket_fds
+ s
->n_fd_store
+ 1, sizeof(char *));
1475 n_fds
= rn_socket_fds
;
1477 LIST_FOREACH(fd_store
, fs
, s
->fd_store
) {
1478 rfds
[n_fds
] = fs
->fd
;
1479 rfd_names
[n_fds
] = strdup(strempty(fs
->fdname
));
1480 if (!rfd_names
[n_fds
])
1487 rfd_names
[n_fds
] = NULL
;
1490 *fds
= TAKE_PTR(rfds
);
1491 *fd_names
= TAKE_PTR(rfd_names
);
1492 *n_socket_fds
= rn_socket_fds
;
1493 *n_storage_fds
= rn_storage_fds
;
1498 static int service_allocate_exec_fd_event_source(
1501 sd_event_source
**ret_event_source
) {
1503 _cleanup_(sd_event_source_unrefp
) sd_event_source
*source
= NULL
;
1508 assert(ret_event_source
);
1510 r
= sd_event_add_io(UNIT(s
)->manager
->event
, &source
, fd
, 0, service_dispatch_exec_io
, s
);
1512 return log_unit_error_errno(UNIT(s
), r
, "Failed to allocate exec_fd event source: %m");
1514 /* This is a bit lower priority than SIGCHLD, as that carries a lot more interesting failure information */
1516 r
= sd_event_source_set_priority(source
, SD_EVENT_PRIORITY_NORMAL
-3);
1518 return log_unit_error_errno(UNIT(s
), r
, "Failed to adjust priority of exec_fd event source: %m");
1520 (void) sd_event_source_set_description(source
, "service exec_fd");
1522 r
= sd_event_source_set_io_fd_own(source
, true);
1524 return log_unit_error_errno(UNIT(s
), r
, "Failed to pass ownership of fd to event source: %m");
1526 *ret_event_source
= TAKE_PTR(source
);
1530 static int service_allocate_exec_fd(
1532 sd_event_source
**ret_event_source
,
1535 _cleanup_close_pair_
int p
[] = EBADF_PAIR
;
1539 assert(ret_event_source
);
1540 assert(ret_exec_fd
);
1542 if (pipe2(p
, O_CLOEXEC
|O_NONBLOCK
) < 0)
1543 return log_unit_error_errno(UNIT(s
), errno
, "Failed to allocate exec_fd pipe: %m");
1545 r
= service_allocate_exec_fd_event_source(s
, p
[0], ret_event_source
);
1550 *ret_exec_fd
= TAKE_FD(p
[1]);
1555 static bool service_exec_needs_notify_socket(Service
*s
, ExecFlags flags
) {
1558 /* Notifications are accepted depending on the process and
1559 * the access setting of the service:
1560 * process: \ access: NONE MAIN EXEC ALL
1561 * main no yes yes yes
1562 * control no no yes yes
1563 * other (forked) no no no yes */
1565 if (flags
& EXEC_IS_CONTROL
)
1566 /* A control process */
1567 return IN_SET(service_get_notify_access(s
), NOTIFY_EXEC
, NOTIFY_ALL
);
1569 /* We only spawn main processes and control processes, so any
1570 * process that is not a control process is a main process */
1571 return service_get_notify_access(s
) != NOTIFY_NONE
;
1574 static Service
*service_get_triggering_service(Service
*s
) {
1575 Unit
*candidate
= NULL
, *other
;
1579 /* Return the service which triggered service 's', this means dependency
1580 * types which include the UNIT_ATOM_ON_{FAILURE,SUCCESS}_OF atoms.
1582 * N.B. if there are multiple services which could trigger 's' via OnFailure=
1583 * or OnSuccess= then we return NULL. This is since we don't know from which
1584 * one to propagate the exit status. */
1586 UNIT_FOREACH_DEPENDENCY(other
, UNIT(s
), UNIT_ATOM_ON_FAILURE_OF
) {
1592 UNIT_FOREACH_DEPENDENCY(other
, UNIT(s
), UNIT_ATOM_ON_SUCCESS_OF
) {
1598 return SERVICE(candidate
);
1601 log_unit_warning(UNIT(s
), "multiple trigger source candidates for exit status propagation (%s, %s), skipping.",
1602 candidate
->id
, other
->id
);
1606 static int service_spawn_internal(
1614 _cleanup_(exec_params_clear
) ExecParameters exec_params
= EXEC_PARAMETERS_INIT(flags
);
1615 _cleanup_(sd_event_source_unrefp
) sd_event_source
*exec_fd_source
= NULL
;
1616 _cleanup_strv_free_
char **final_env
= NULL
, **our_env
= NULL
;
1617 _cleanup_(pidref_done
) PidRef pidref
= PIDREF_NULL
;
1627 log_unit_debug(UNIT(s
), "Will spawn child (%s): %s", caller
, c
->path
);
1629 r
= unit_prepare_exec(UNIT(s
)); /* This realizes the cgroup, among other things */
1633 assert(!s
->exec_fd_event_source
);
1635 if (flags
& EXEC_IS_CONTROL
) {
1636 /* If this is a control process, mask the permissions/chroot application if this is requested. */
1637 if (s
->permissions_start_only
)
1638 exec_params
.flags
&= ~EXEC_APPLY_SANDBOXING
;
1639 if (s
->root_directory_start_only
)
1640 exec_params
.flags
&= ~EXEC_APPLY_CHROOT
;
1643 if ((flags
& EXEC_PASS_FDS
) ||
1644 s
->exec_context
.std_input
== EXEC_INPUT_SOCKET
||
1645 s
->exec_context
.std_output
== EXEC_OUTPUT_SOCKET
||
1646 s
->exec_context
.std_error
== EXEC_OUTPUT_SOCKET
) {
1648 r
= service_collect_fds(s
,
1650 &exec_params
.fd_names
,
1651 &exec_params
.n_socket_fds
,
1652 &exec_params
.n_storage_fds
);
1656 exec_params
.open_files
= s
->open_files
;
1658 log_unit_debug(UNIT(s
), "Passing %zu fds to service", exec_params
.n_socket_fds
+ exec_params
.n_storage_fds
);
1661 if (!FLAGS_SET(flags
, EXEC_IS_CONTROL
) && s
->type
== SERVICE_EXEC
) {
1662 r
= service_allocate_exec_fd(s
, &exec_fd_source
, &exec_params
.exec_fd
);
1667 r
= service_arm_timer(s
, /* relative= */ true, timeout
);
1671 our_env
= new0(char*, 13);
1675 if (service_exec_needs_notify_socket(s
, flags
)) {
1676 if (asprintf(our_env
+ n_env
++, "NOTIFY_SOCKET=%s", UNIT(s
)->manager
->notify_socket
) < 0)
1679 exec_params
.notify_socket
= UNIT(s
)->manager
->notify_socket
;
1681 if (s
->n_fd_store_max
> 0)
1682 if (asprintf(our_env
+ n_env
++, "FDSTORE=%u", s
->n_fd_store_max
) < 0)
1686 if (pidref_is_set(&s
->main_pid
))
1687 if (asprintf(our_env
+ n_env
++, "MAINPID="PID_FMT
, s
->main_pid
.pid
) < 0)
1690 if (MANAGER_IS_USER(UNIT(s
)->manager
))
1691 if (asprintf(our_env
+ n_env
++, "MANAGERPID="PID_FMT
, getpid_cached()) < 0)
1695 if (asprintf(our_env
+ n_env
++, "PIDFILE=%s", s
->pid_file
) < 0)
1698 if (s
->socket_fd
>= 0) {
1699 union sockaddr_union sa
;
1700 socklen_t salen
= sizeof(sa
);
1702 /* If this is a per-connection service instance, let's set $REMOTE_ADDR and $REMOTE_PORT to something
1703 * useful. Note that we do this only when we are still connected at this point in time, which we might
1704 * very well not be. Hence we ignore all errors when retrieving peer information (as that might result
1705 * in ENOTCONN), and just use whate we can use. */
1707 if (getpeername(s
->socket_fd
, &sa
.sa
, &salen
) >= 0 &&
1708 IN_SET(sa
.sa
.sa_family
, AF_INET
, AF_INET6
, AF_VSOCK
)) {
1709 _cleanup_free_
char *addr
= NULL
;
1713 r
= sockaddr_pretty(&sa
.sa
, salen
, true, false, &addr
);
1717 t
= strjoin("REMOTE_ADDR=", addr
);
1720 our_env
[n_env
++] = t
;
1722 r
= sockaddr_port(&sa
.sa
, &port
);
1726 if (asprintf(&t
, "REMOTE_PORT=%u", port
) < 0)
1728 our_env
[n_env
++] = t
;
1732 Service
*env_source
= NULL
;
1733 const char *monitor_prefix
;
1734 if (flags
& EXEC_SETENV_RESULT
) {
1736 monitor_prefix
= "";
1737 } else if (flags
& EXEC_SETENV_MONITOR_RESULT
) {
1738 env_source
= service_get_triggering_service(s
);
1739 monitor_prefix
= "MONITOR_";
1743 if (asprintf(our_env
+ n_env
++, "%sSERVICE_RESULT=%s", monitor_prefix
, service_result_to_string(env_source
->result
)) < 0)
1746 if (env_source
->main_exec_status
.pid
> 0 &&
1747 dual_timestamp_is_set(&env_source
->main_exec_status
.exit_timestamp
)) {
1748 if (asprintf(our_env
+ n_env
++, "%sEXIT_CODE=%s", monitor_prefix
, sigchld_code_to_string(env_source
->main_exec_status
.code
)) < 0)
1751 if (env_source
->main_exec_status
.code
== CLD_EXITED
)
1752 r
= asprintf(our_env
+ n_env
++, "%sEXIT_STATUS=%i", monitor_prefix
, env_source
->main_exec_status
.status
);
1754 r
= asprintf(our_env
+ n_env
++, "%sEXIT_STATUS=%s", monitor_prefix
, signal_to_string(env_source
->main_exec_status
.status
));
1760 if (env_source
!= s
) {
1761 if (!sd_id128_is_null(UNIT(env_source
)->invocation_id
)) {
1762 r
= asprintf(our_env
+ n_env
++, "%sINVOCATION_ID=" SD_ID128_FORMAT_STR
,
1763 monitor_prefix
, SD_ID128_FORMAT_VAL(UNIT(env_source
)->invocation_id
));
1768 if (asprintf(our_env
+ n_env
++, "%sUNIT=%s", monitor_prefix
, UNIT(env_source
)->id
) < 0)
1773 if (UNIT(s
)->activation_details
) {
1774 r
= activation_details_append_env(UNIT(s
)->activation_details
, &our_env
);
1777 /* The number of env vars added here can vary, rather than keeping the allocation block in
1778 * sync manually, these functions simply use the strv methods to append to it, so we need
1779 * to update n_env when we are done in case of future usage. */
1783 r
= unit_set_exec_params(UNIT(s
), &exec_params
);
1787 final_env
= strv_env_merge(exec_params
.environment
, our_env
);
1791 /* System D-Bus needs nss-systemd disabled, so that we don't deadlock */
1792 SET_FLAG(exec_params
.flags
, EXEC_NSS_DYNAMIC_BYPASS
,
1793 MANAGER_IS_SYSTEM(UNIT(s
)->manager
) && unit_has_name(UNIT(s
), SPECIAL_DBUS_SERVICE
));
1795 strv_free_and_replace(exec_params
.environment
, final_env
);
1796 exec_params
.watchdog_usec
= service_get_watchdog_usec(s
);
1797 exec_params
.selinux_context_net
= s
->socket_fd_selinux_context_net
;
1798 if (s
->type
== SERVICE_IDLE
)
1799 exec_params
.idle_pipe
= UNIT(s
)->manager
->idle_pipe
;
1800 exec_params
.stdin_fd
= s
->stdin_fd
;
1801 exec_params
.stdout_fd
= s
->stdout_fd
;
1802 exec_params
.stderr_fd
= s
->stderr_fd
;
1804 r
= exec_spawn(UNIT(s
),
1814 s
->exec_fd_event_source
= TAKE_PTR(exec_fd_source
);
1815 s
->exec_fd_hot
= false;
1817 r
= pidref_set_pid(&pidref
, pid
);
1821 r
= unit_watch_pidref(UNIT(s
), &pidref
, /* exclusive= */ true);
1825 *ret_pid
= TAKE_PIDREF(pidref
);
1829 static int main_pid_good(Service
*s
) {
1832 /* Returns 0 if the pid is dead, > 0 if it is good, < 0 if we don't know */
1834 /* If we know the pid file, then let's just check if it is still valid */
1835 if (s
->main_pid_known
) {
1837 /* If it's an alien child let's check if it is still alive ... */
1838 if (s
->main_pid_alien
&& pidref_is_set(&s
->main_pid
))
1839 return pidref_is_alive(&s
->main_pid
);
1841 /* .. otherwise assume we'll get a SIGCHLD for it, which we really should wait for to collect
1842 * exit status and code */
1843 return pidref_is_set(&s
->main_pid
);
1846 /* We don't know the pid */
1850 static int control_pid_good(Service
*s
) {
1853 /* Returns 0 if the control PID is dead, > 0 if it is good. We never actually return < 0 here, but in order to
1854 * make this function as similar as possible to main_pid_good() and cgroup_good(), we pretend that < 0 also
1855 * means: we can't figure it out. */
1857 return pidref_is_set(&s
->control_pid
);
1860 static int cgroup_good(Service
*s
) {
1865 /* Returns 0 if the cgroup is empty or doesn't exist, > 0 if it is exists and is populated, < 0 if we can't
1868 if (!UNIT(s
)->cgroup_path
)
1871 r
= cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER
, UNIT(s
)->cgroup_path
);
1878 static bool service_shall_restart(Service
*s
, const char **reason
) {
1881 /* Don't restart after manual stops */
1882 if (s
->forbid_restart
) {
1883 *reason
= "manual stop";
1887 /* Never restart if this is configured as special exception */
1888 if (exit_status_set_test(&s
->restart_prevent_status
, s
->main_exec_status
.code
, s
->main_exec_status
.status
)) {
1889 *reason
= "prevented by exit status";
1893 /* Restart if the exit code/status are configured as restart triggers */
1894 if (exit_status_set_test(&s
->restart_force_status
, s
->main_exec_status
.code
, s
->main_exec_status
.status
)) {
1895 *reason
= "forced by exit status";
1899 *reason
= "restart setting";
1900 switch (s
->restart
) {
1902 case SERVICE_RESTART_NO
:
1905 case SERVICE_RESTART_ALWAYS
:
1906 return s
->result
!= SERVICE_SKIP_CONDITION
;
1908 case SERVICE_RESTART_ON_SUCCESS
:
1909 return s
->result
== SERVICE_SUCCESS
;
1911 case SERVICE_RESTART_ON_FAILURE
:
1912 return !IN_SET(s
->result
, SERVICE_SUCCESS
, SERVICE_SKIP_CONDITION
);
1914 case SERVICE_RESTART_ON_ABNORMAL
:
1915 return !IN_SET(s
->result
, SERVICE_SUCCESS
, SERVICE_FAILURE_EXIT_CODE
, SERVICE_SKIP_CONDITION
);
1917 case SERVICE_RESTART_ON_WATCHDOG
:
1918 return s
->result
== SERVICE_FAILURE_WATCHDOG
;
1920 case SERVICE_RESTART_ON_ABORT
:
1921 return IN_SET(s
->result
, SERVICE_FAILURE_SIGNAL
, SERVICE_FAILURE_CORE_DUMP
);
1924 assert_not_reached();
1928 static bool service_will_restart(Unit
*u
) {
1929 Service
*s
= SERVICE(u
);
1933 if (IN_SET(s
->state
, SERVICE_DEAD_BEFORE_AUTO_RESTART
, SERVICE_FAILED_BEFORE_AUTO_RESTART
, SERVICE_AUTO_RESTART
, SERVICE_AUTO_RESTART_QUEUED
))
1936 return unit_will_restart_default(u
);
1939 static ServiceState
service_determine_dead_state(Service
*s
) {
1942 return s
->fd_store
&& s
->fd_store_preserve_mode
== EXEC_PRESERVE_YES
? SERVICE_DEAD_RESOURCES_PINNED
: SERVICE_DEAD
;
1945 static void service_enter_dead(Service
*s
, ServiceResult f
, bool allow_restart
) {
1946 ServiceState end_state
, restart_state
;
1951 /* If there's a stop job queued before we enter the DEAD state, we shouldn't act on Restart=, in order to not
1952 * undo what has already been enqueued. */
1953 if (unit_stop_pending(UNIT(s
)))
1954 allow_restart
= false;
1956 if (s
->result
== SERVICE_SUCCESS
)
1959 if (s
->result
== SERVICE_SUCCESS
) {
1960 unit_log_success(UNIT(s
));
1961 end_state
= service_determine_dead_state(s
);
1962 restart_state
= SERVICE_DEAD_BEFORE_AUTO_RESTART
;
1963 } else if (s
->result
== SERVICE_SKIP_CONDITION
) {
1964 unit_log_skip(UNIT(s
), service_result_to_string(s
->result
));
1965 end_state
= service_determine_dead_state(s
);
1966 restart_state
= SERVICE_DEAD_BEFORE_AUTO_RESTART
;
1968 unit_log_failure(UNIT(s
), service_result_to_string(s
->result
));
1969 end_state
= SERVICE_FAILED
;
1970 restart_state
= SERVICE_FAILED_BEFORE_AUTO_RESTART
;
1972 unit_warn_leftover_processes(UNIT(s
), unit_log_leftover_process_stop
);
1975 log_unit_debug(UNIT(s
), "Service restart not allowed.");
1979 allow_restart
= service_shall_restart(s
, &reason
);
1980 log_unit_debug(UNIT(s
), "Service will %srestart (%s)",
1981 allow_restart
? "" : "not ",
1985 if (allow_restart
) {
1986 usec_t restart_usec_next
;
1988 /* We make two state changes here: one that maps to the high-level UNIT_INACTIVE/UNIT_FAILED
1989 * state (i.e. a state indicating deactivation), and then one that that maps to the
1990 * high-level UNIT_STARTING state (i.e. a state indicating activation). We do this so that
1991 * external software can watch the state changes and see all service failures, even if they
1992 * are only transitionary and followed by an automatic restart. We have fine-grained
1993 * low-level states for this though so that software can distinguish the permanent UNIT_INACTIVE
1994 * state from this transitionary UNIT_INACTIVE state by looking at the low-level states. */
1995 if (s
->restart_mode
!= SERVICE_RESTART_MODE_DIRECT
)
1996 service_set_state(s
, restart_state
);
1998 restart_usec_next
= service_restart_usec_next(s
);
2000 r
= service_arm_timer(s
, /* relative= */ true, restart_usec_next
);
2002 log_unit_warning_errno(UNIT(s
), r
, "Failed to install restart timer: %m");
2003 service_enter_dead(s
, SERVICE_FAILURE_RESOURCES
, /* allow_restart= */ false);
2007 log_unit_debug(UNIT(s
), "Next restart interval calculated as: %s", FORMAT_TIMESPAN(restart_usec_next
, 0));
2009 service_set_state(s
, SERVICE_AUTO_RESTART
);
2011 service_set_state(s
, end_state
);
2013 /* If we shan't restart, then flush out the restart counter. But don't do that immediately, so that the
2014 * user can still introspect the counter. Do so on the next start. */
2015 s
->flush_n_restarts
= true;
2018 /* The new state is in effect, let's decrease the fd store ref counter again. Let's also re-add us to the GC
2019 * queue, so that the fd store is possibly gc'ed again */
2020 unit_add_to_gc_queue(UNIT(s
));
2022 /* The next restart might not be a manual stop, hence reset the flag indicating manual stops */
2023 s
->forbid_restart
= false;
2025 /* Reset NotifyAccess override */
2026 s
->notify_access_override
= _NOTIFY_ACCESS_INVALID
;
2028 /* We want fresh tmpdirs and ephemeral snapshots in case the service is started again immediately. */
2029 s
->exec_runtime
= exec_runtime_destroy(s
->exec_runtime
);
2031 /* Also, remove the runtime directory */
2032 unit_destroy_runtime_data(UNIT(s
), &s
->exec_context
);
2034 /* Also get rid of the fd store, if that's configured. */
2035 if (s
->fd_store_preserve_mode
== EXEC_PRESERVE_NO
)
2036 service_release_fd_store(s
);
2038 /* Get rid of the IPC bits of the user */
2039 unit_unref_uid_gid(UNIT(s
), true);
2041 /* Try to delete the pid file. At this point it will be
2042 * out-of-date, and some software might be confused by it, so
2043 * let's remove it. */
2045 (void) unlink(s
->pid_file
);
2047 /* Reset TTY ownership if necessary */
2048 exec_context_revert_tty(&s
->exec_context
);
2051 static void service_enter_stop_post(Service
*s
, ServiceResult f
) {
2055 if (s
->result
== SERVICE_SUCCESS
)
2058 service_unwatch_control_pid(s
);
2059 (void) unit_enqueue_rewatch_pids(UNIT(s
));
2061 s
->control_command
= s
->exec_command
[SERVICE_EXEC_STOP_POST
];
2062 if (s
->control_command
) {
2063 s
->control_command_id
= SERVICE_EXEC_STOP_POST
;
2064 pidref_done(&s
->control_pid
);
2066 r
= service_spawn(s
,
2068 s
->timeout_stop_usec
,
2069 EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_APPLY_TTY_STDIN
|EXEC_IS_CONTROL
|EXEC_SETENV_RESULT
|EXEC_CONTROL_CGROUP
,
2072 log_unit_warning_errno(UNIT(s
), r
, "Failed to spawn 'stop-post' task: %m");
2073 service_enter_signal(s
, SERVICE_FINAL_SIGTERM
, SERVICE_FAILURE_RESOURCES
);
2077 service_set_state(s
, SERVICE_STOP_POST
);
2079 service_enter_signal(s
, SERVICE_FINAL_SIGTERM
, SERVICE_SUCCESS
);
2082 static int state_to_kill_operation(Service
*s
, ServiceState state
) {
2085 case SERVICE_STOP_WATCHDOG
:
2086 case SERVICE_FINAL_WATCHDOG
:
2087 return KILL_WATCHDOG
;
2089 case SERVICE_STOP_SIGTERM
:
2090 if (unit_has_job_type(UNIT(s
), JOB_RESTART
))
2091 return KILL_RESTART
;
2094 case SERVICE_FINAL_SIGTERM
:
2095 return KILL_TERMINATE
;
2097 case SERVICE_STOP_SIGKILL
:
2098 case SERVICE_FINAL_SIGKILL
:
2102 return _KILL_OPERATION_INVALID
;
2106 static void service_enter_signal(Service
*s
, ServiceState state
, ServiceResult f
) {
2107 int kill_operation
, r
;
2111 if (s
->result
== SERVICE_SUCCESS
)
2114 /* Before sending any signal, make sure we track all members of this cgroup */
2115 (void) unit_watch_all_pids(UNIT(s
));
2117 /* Also, enqueue a job that we recheck all our PIDs a bit later, given that it's likely some processes have
2119 (void) unit_enqueue_rewatch_pids(UNIT(s
));
2121 kill_operation
= state_to_kill_operation(s
, state
);
2122 r
= unit_kill_context(
2130 log_unit_warning_errno(UNIT(s
), r
, "Failed to kill processes: %m");
2135 r
= service_arm_timer(s
, /* relative= */ true,
2136 kill_operation
== KILL_WATCHDOG
? service_timeout_abort_usec(s
) : s
->timeout_stop_usec
);
2138 log_unit_warning_errno(UNIT(s
), r
, "Failed to install timer: %m");
2142 service_set_state(s
, state
);
2143 } else if (IN_SET(state
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
) && s
->kill_context
.send_sigkill
)
2144 service_enter_signal(s
, SERVICE_STOP_SIGKILL
, SERVICE_SUCCESS
);
2145 else if (IN_SET(state
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
))
2146 service_enter_stop_post(s
, SERVICE_SUCCESS
);
2147 else if (IN_SET(state
, SERVICE_FINAL_WATCHDOG
, SERVICE_FINAL_SIGTERM
) && s
->kill_context
.send_sigkill
)
2148 service_enter_signal(s
, SERVICE_FINAL_SIGKILL
, SERVICE_SUCCESS
);
2150 service_enter_dead(s
, SERVICE_SUCCESS
, /* allow_restart= */ true);
2155 if (IN_SET(state
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
))
2156 service_enter_stop_post(s
, SERVICE_FAILURE_RESOURCES
);
2158 service_enter_dead(s
, SERVICE_FAILURE_RESOURCES
, /* allow_restart= */ true);
2161 static void service_enter_stop_by_notify(Service
*s
) {
2166 (void) unit_enqueue_rewatch_pids(UNIT(s
));
2168 r
= service_arm_timer(s
, /* relative= */ true, s
->timeout_stop_usec
);
2170 log_unit_warning_errno(UNIT(s
), r
, "Failed to install timer: %m");
2171 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_RESOURCES
);
2175 /* The service told us it's stopping, so it's as if we SIGTERM'd it. */
2176 service_set_state(s
, SERVICE_STOP_SIGTERM
);
2179 static void service_enter_stop(Service
*s
, ServiceResult f
) {
2184 if (s
->result
== SERVICE_SUCCESS
)
2187 service_unwatch_control_pid(s
);
2188 (void) unit_enqueue_rewatch_pids(UNIT(s
));
2190 s
->control_command
= s
->exec_command
[SERVICE_EXEC_STOP
];
2191 if (s
->control_command
) {
2192 s
->control_command_id
= SERVICE_EXEC_STOP
;
2193 pidref_done(&s
->control_pid
);
2195 r
= service_spawn(s
,
2197 s
->timeout_stop_usec
,
2198 EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_IS_CONTROL
|EXEC_SETENV_RESULT
|EXEC_CONTROL_CGROUP
,
2201 log_unit_warning_errno(UNIT(s
), r
, "Failed to spawn 'stop' task: %m");
2202 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_RESOURCES
);
2206 service_set_state(s
, SERVICE_STOP
);
2208 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_SUCCESS
);
2211 static bool service_good(Service
*s
) {
2215 if (s
->type
== SERVICE_DBUS
&& !s
->bus_name_good
)
2218 main_pid_ok
= main_pid_good(s
);
2219 if (main_pid_ok
> 0) /* It's alive */
2221 if (main_pid_ok
== 0 && s
->exit_type
== SERVICE_EXIT_MAIN
) /* It's dead */
2224 /* OK, we don't know anything about the main PID, maybe
2225 * because there is none. Let's check the control group
2228 return cgroup_good(s
) != 0;
2231 static void service_enter_running(Service
*s
, ServiceResult f
) {
2236 if (s
->result
== SERVICE_SUCCESS
)
2239 service_unwatch_control_pid(s
);
2241 if (s
->result
!= SERVICE_SUCCESS
)
2242 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
2243 else if (service_good(s
)) {
2245 /* If there are any queued up sd_notify() notifications, process them now */
2246 if (s
->notify_state
== NOTIFY_RELOADING
)
2247 service_enter_reload_by_notify(s
);
2248 else if (s
->notify_state
== NOTIFY_STOPPING
)
2249 service_enter_stop_by_notify(s
);
2251 service_set_state(s
, SERVICE_RUNNING
);
2253 r
= service_arm_timer(s
, /* relative= */ false, service_running_timeout(s
));
2255 log_unit_warning_errno(UNIT(s
), r
, "Failed to install timer: %m");
2256 service_enter_running(s
, SERVICE_FAILURE_RESOURCES
);
2261 } else if (s
->remain_after_exit
)
2262 service_set_state(s
, SERVICE_EXITED
);
2264 service_enter_stop(s
, SERVICE_SUCCESS
);
2267 static void service_enter_start_post(Service
*s
) {
2271 service_unwatch_control_pid(s
);
2272 service_reset_watchdog(s
);
2274 s
->control_command
= s
->exec_command
[SERVICE_EXEC_START_POST
];
2275 if (s
->control_command
) {
2276 s
->control_command_id
= SERVICE_EXEC_START_POST
;
2277 pidref_done(&s
->control_pid
);
2279 r
= service_spawn(s
,
2281 s
->timeout_start_usec
,
2282 EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_IS_CONTROL
|EXEC_CONTROL_CGROUP
,
2285 log_unit_warning_errno(UNIT(s
), r
, "Failed to spawn 'start-post' task: %m");
2286 service_enter_stop(s
, SERVICE_FAILURE_RESOURCES
);
2290 service_set_state(s
, SERVICE_START_POST
);
2292 service_enter_running(s
, SERVICE_SUCCESS
);
2295 static void service_kill_control_process(Service
*s
) {
2300 if (!pidref_is_set(&s
->control_pid
))
2303 r
= pidref_kill_and_sigcont(&s
->control_pid
, SIGKILL
);
2305 _cleanup_free_
char *comm
= NULL
;
2307 (void) pidref_get_comm(&s
->control_pid
, &comm
);
2309 log_unit_debug_errno(UNIT(s
), r
, "Failed to kill control process " PID_FMT
" (%s), ignoring: %m",
2310 s
->control_pid
.pid
, strna(comm
));
2314 static int service_adverse_to_leftover_processes(Service
*s
) {
2317 /* KillMode=mixed and control group are used to indicate that all process should be killed off.
2318 * SendSIGKILL= is used for services that require a clean shutdown. These are typically database
2319 * service where a SigKilled process would result in a lengthy recovery and who's shutdown or startup
2320 * time is quite variable (so Timeout settings aren't of use).
2322 * Here we take these two factors and refuse to start a service if there are existing processes
2323 * within a control group. Databases, while generally having some protection against multiple
2324 * instances running, lets not stress the rigor of these. Also ExecStartPre= parts of the service
2325 * aren't as rigoriously written to protect aganst against multiple use. */
2327 if (unit_warn_leftover_processes(UNIT(s
), unit_log_leftover_process_start
) > 0 &&
2328 IN_SET(s
->kill_context
.kill_mode
, KILL_MIXED
, KILL_CONTROL_GROUP
) &&
2329 !s
->kill_context
.send_sigkill
)
2330 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(EBUSY
),
2331 "Will not start SendSIGKILL=no service of type KillMode=control-group or mixed while processes exist");
2336 static void service_enter_start(Service
*s
) {
2337 _cleanup_(pidref_done
) PidRef pidref
= PIDREF_NULL
;
2344 service_unwatch_control_pid(s
);
2345 service_unwatch_main_pid(s
);
2347 r
= service_adverse_to_leftover_processes(s
);
2351 if (s
->type
== SERVICE_FORKING
) {
2352 s
->control_command_id
= SERVICE_EXEC_START
;
2353 c
= s
->control_command
= s
->exec_command
[SERVICE_EXEC_START
];
2355 s
->main_command
= NULL
;
2357 s
->control_command_id
= _SERVICE_EXEC_COMMAND_INVALID
;
2358 s
->control_command
= NULL
;
2360 c
= s
->main_command
= s
->exec_command
[SERVICE_EXEC_START
];
2364 if (s
->type
!= SERVICE_ONESHOT
) {
2365 /* There's no command line configured for the main command? Hmm, that is strange.
2366 * This can only happen if the configuration changes at runtime. In this case,
2367 * let's enter a failure state. */
2368 r
= log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENXIO
), "There's no 'start' task anymore we could start.");
2372 /* We force a fake state transition here. Otherwise, the unit would go directly from
2373 * SERVICE_DEAD to SERVICE_DEAD without SERVICE_ACTIVATING or SERVICE_ACTIVE
2374 * in between. This way we can later trigger actions that depend on the state
2375 * transition, including SuccessAction=. */
2376 service_set_state(s
, SERVICE_START
);
2378 service_enter_start_post(s
);
2382 if (IN_SET(s
->type
, SERVICE_SIMPLE
, SERVICE_IDLE
))
2383 /* For simple + idle this is the main process. We don't apply any timeout here, but
2384 * service_enter_running() will later apply the .runtime_max_usec timeout. */
2385 timeout
= USEC_INFINITY
;
2387 timeout
= s
->timeout_start_usec
;
2389 r
= service_spawn(s
,
2392 EXEC_PASS_FDS
|EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_APPLY_TTY_STDIN
|EXEC_SET_WATCHDOG
|EXEC_WRITE_CREDENTIALS
|EXEC_SETENV_MONITOR_RESULT
,
2395 log_unit_warning_errno(UNIT(s
), r
, "Failed to spawn 'start' task: %m");
2399 if (IN_SET(s
->type
, SERVICE_SIMPLE
, SERVICE_IDLE
)) {
2400 /* For simple services we immediately start
2401 * the START_POST binaries. */
2403 (void) service_set_main_pidref(s
, &pidref
);
2404 service_enter_start_post(s
);
2406 } else if (s
->type
== SERVICE_FORKING
) {
2408 /* For forking services we wait until the start
2409 * process exited. */
2411 pidref_done(&s
->control_pid
);
2412 s
->control_pid
= TAKE_PIDREF(pidref
);
2413 service_set_state(s
, SERVICE_START
);
2415 } else if (IN_SET(s
->type
, SERVICE_ONESHOT
, SERVICE_DBUS
, SERVICE_NOTIFY
, SERVICE_NOTIFY_RELOAD
, SERVICE_EXEC
)) {
2417 /* For oneshot services we wait until the start process exited, too, but it is our main process. */
2419 /* For D-Bus services we know the main pid right away, but wait for the bus name to appear on the
2420 * bus. 'notify' and 'exec' services are similar. */
2422 (void) service_set_main_pidref(s
, &pidref
);
2423 service_set_state(s
, SERVICE_START
);
2425 assert_not_reached();
2430 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_RESOURCES
);
2433 static void service_enter_start_pre(Service
*s
) {
2438 service_unwatch_control_pid(s
);
2440 s
->control_command
= s
->exec_command
[SERVICE_EXEC_START_PRE
];
2441 if (s
->control_command
) {
2443 r
= service_adverse_to_leftover_processes(s
);
2447 s
->control_command_id
= SERVICE_EXEC_START_PRE
;
2449 r
= service_spawn(s
,
2451 s
->timeout_start_usec
,
2452 EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_IS_CONTROL
|EXEC_APPLY_TTY_STDIN
|EXEC_SETENV_MONITOR_RESULT
|EXEC_WRITE_CREDENTIALS
,
2455 log_unit_warning_errno(UNIT(s
), r
, "Failed to spawn 'start-pre' task: %m");
2459 service_set_state(s
, SERVICE_START_PRE
);
2461 service_enter_start(s
);
2466 service_enter_dead(s
, SERVICE_FAILURE_RESOURCES
, /* allow_restart= */ true);
2469 static void service_enter_condition(Service
*s
) {
2474 service_unwatch_control_pid(s
);
2476 s
->control_command
= s
->exec_command
[SERVICE_EXEC_CONDITION
];
2477 if (s
->control_command
) {
2479 r
= service_adverse_to_leftover_processes(s
);
2483 s
->control_command_id
= SERVICE_EXEC_CONDITION
;
2484 pidref_done(&s
->control_pid
);
2486 r
= service_spawn(s
,
2488 s
->timeout_start_usec
,
2489 EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_IS_CONTROL
|EXEC_APPLY_TTY_STDIN
,
2493 log_unit_warning_errno(UNIT(s
), r
, "Failed to spawn 'exec-condition' task: %m");
2497 service_set_state(s
, SERVICE_CONDITION
);
2499 service_enter_start_pre(s
);
2504 service_enter_dead(s
, SERVICE_FAILURE_RESOURCES
, /* allow_restart= */ true);
2507 static void service_enter_restart(Service
*s
) {
2508 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2513 if (unit_has_job_type(UNIT(s
), JOB_STOP
)) {
2514 /* Don't restart things if we are going down anyway */
2515 log_unit_info(UNIT(s
), "Stop job pending for unit, skipping automatic restart.");
2519 /* Any units that are bound to this service must also be restarted. We use JOB_START for ourselves
2520 * but then set JOB_RESTART_DEPENDENCIES which will enqueue JOB_RESTART for those dependency jobs. */
2521 r
= manager_add_job(UNIT(s
)->manager
, JOB_START
, UNIT(s
), JOB_RESTART_DEPENDENCIES
, NULL
, &error
, NULL
);
2523 log_unit_warning(UNIT(s
), "Failed to schedule restart job: %s", bus_error_message(&error
, r
));
2524 service_enter_dead(s
, SERVICE_FAILURE_RESOURCES
, /* allow_restart= */ false);
2528 /* Count the jobs we enqueue for restarting. This counter is maintained as long as the unit isn't
2529 * fully stopped, i.e. as long as it remains up or remains in auto-start states. The user can reset
2530 * the counter explicitly however via the usual "systemctl reset-failure" logic. */
2532 s
->flush_n_restarts
= false;
2534 s
->notify_access_override
= _NOTIFY_ACCESS_INVALID
;
2536 log_unit_struct(UNIT(s
), LOG_INFO
,
2537 "MESSAGE_ID=" SD_MESSAGE_UNIT_RESTART_SCHEDULED_STR
,
2538 LOG_UNIT_INVOCATION_ID(UNIT(s
)),
2539 LOG_UNIT_MESSAGE(UNIT(s
),
2540 "Scheduled restart job, restart counter is at %u.", s
->n_restarts
),
2541 "N_RESTARTS=%u", s
->n_restarts
);
2543 service_set_state(s
, SERVICE_AUTO_RESTART_QUEUED
);
2545 /* Notify clients about changed restart counter */
2546 unit_add_to_dbus_queue(UNIT(s
));
2549 static void service_enter_reload_by_notify(Service
*s
) {
2550 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2555 r
= service_arm_timer(s
, /* relative= */ true, s
->timeout_start_usec
);
2557 log_unit_warning_errno(UNIT(s
), r
, "Failed to install timer: %m");
2558 s
->reload_result
= SERVICE_FAILURE_RESOURCES
;
2559 service_enter_running(s
, SERVICE_SUCCESS
);
2563 service_set_state(s
, SERVICE_RELOAD_NOTIFY
);
2565 /* service_enter_reload_by_notify is never called during a reload, thus no loops are possible. */
2566 r
= manager_propagate_reload(UNIT(s
)->manager
, UNIT(s
), JOB_FAIL
, &error
);
2568 log_unit_warning(UNIT(s
), "Failed to schedule propagation of reload, ignoring: %s", bus_error_message(&error
, r
));
2571 static void service_enter_reload(Service
*s
) {
2572 bool killed
= false;
2577 service_unwatch_control_pid(s
);
2578 s
->reload_result
= SERVICE_SUCCESS
;
2580 usec_t ts
= now(CLOCK_MONOTONIC
);
2582 if (s
->type
== SERVICE_NOTIFY_RELOAD
&& pidref_is_set(&s
->main_pid
)) {
2583 r
= pidref_kill_and_sigcont(&s
->main_pid
, s
->reload_signal
);
2585 log_unit_warning_errno(UNIT(s
), r
, "Failed to send reload signal: %m");
2592 s
->control_command
= s
->exec_command
[SERVICE_EXEC_RELOAD
];
2593 if (s
->control_command
) {
2594 s
->control_command_id
= SERVICE_EXEC_RELOAD
;
2595 pidref_done(&s
->control_pid
);
2597 r
= service_spawn(s
,
2599 s
->timeout_start_usec
,
2600 EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_IS_CONTROL
|EXEC_CONTROL_CGROUP
,
2603 log_unit_warning_errno(UNIT(s
), r
, "Failed to spawn 'reload' task: %m");
2607 service_set_state(s
, SERVICE_RELOAD
);
2608 } else if (killed
) {
2609 r
= service_arm_timer(s
, /* relative= */ true, s
->timeout_start_usec
);
2611 log_unit_warning_errno(UNIT(s
), r
, "Failed to install timer: %m");
2615 service_set_state(s
, SERVICE_RELOAD_SIGNAL
);
2617 service_enter_running(s
, SERVICE_SUCCESS
);
2621 /* Store the timestamp when we started reloading: when reloading via SIGHUP we won't leave the reload
2622 * state until we received both RELOADING=1 and READY=1 with MONOTONIC_USEC= set to a value above
2623 * this. Thus we know for sure the reload cycle was executed *after* we requested it, and is not one
2624 * that was already in progress before. */
2625 s
->reload_begin_usec
= ts
;
2629 s
->reload_result
= SERVICE_FAILURE_RESOURCES
;
2630 service_enter_running(s
, SERVICE_SUCCESS
);
2633 static void service_run_next_control(Service
*s
) {
2638 assert(s
->control_command
);
2639 assert(s
->control_command
->command_next
);
2641 assert(s
->control_command_id
!= SERVICE_EXEC_START
);
2643 s
->control_command
= s
->control_command
->command_next
;
2644 service_unwatch_control_pid(s
);
2646 if (IN_SET(s
->state
, SERVICE_CONDITION
, SERVICE_START_PRE
, SERVICE_START
, SERVICE_START_POST
, SERVICE_RUNNING
, SERVICE_RELOAD
))
2647 timeout
= s
->timeout_start_usec
;
2649 timeout
= s
->timeout_stop_usec
;
2651 pidref_done(&s
->control_pid
);
2653 r
= service_spawn(s
,
2656 EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_IS_CONTROL
|
2657 (IN_SET(s
->state
, SERVICE_CONDITION
, SERVICE_START_PRE
, SERVICE_START
, SERVICE_START_POST
, SERVICE_RUNNING
, SERVICE_RELOAD
) ? EXEC_WRITE_CREDENTIALS
: 0)|
2658 (IN_SET(s
->control_command_id
, SERVICE_EXEC_CONDITION
, SERVICE_EXEC_START_PRE
, SERVICE_EXEC_STOP_POST
) ? EXEC_APPLY_TTY_STDIN
: 0)|
2659 (IN_SET(s
->control_command_id
, SERVICE_EXEC_STOP
, SERVICE_EXEC_STOP_POST
) ? EXEC_SETENV_RESULT
: 0)|
2660 (IN_SET(s
->control_command_id
, SERVICE_EXEC_START_PRE
, SERVICE_EXEC_START
) ? EXEC_SETENV_MONITOR_RESULT
: 0)|
2661 (IN_SET(s
->control_command_id
, SERVICE_EXEC_START_POST
, SERVICE_EXEC_RELOAD
, SERVICE_EXEC_STOP
, SERVICE_EXEC_STOP_POST
) ? EXEC_CONTROL_CGROUP
: 0),
2664 log_unit_warning_errno(UNIT(s
), r
, "Failed to spawn next control task: %m");
2666 if (IN_SET(s
->state
, SERVICE_CONDITION
, SERVICE_START_PRE
, SERVICE_START_POST
, SERVICE_STOP
))
2667 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_RESOURCES
);
2668 else if (s
->state
== SERVICE_STOP_POST
)
2669 service_enter_dead(s
, SERVICE_FAILURE_RESOURCES
, /* allow_restart= */ true);
2670 else if (s
->state
== SERVICE_RELOAD
) {
2671 s
->reload_result
= SERVICE_FAILURE_RESOURCES
;
2672 service_enter_running(s
, SERVICE_SUCCESS
);
2674 service_enter_stop(s
, SERVICE_FAILURE_RESOURCES
);
2678 static void service_run_next_main(Service
*s
) {
2679 _cleanup_(pidref_done
) PidRef pidref
= PIDREF_NULL
;
2683 assert(s
->main_command
);
2684 assert(s
->main_command
->command_next
);
2685 assert(s
->type
== SERVICE_ONESHOT
);
2687 s
->main_command
= s
->main_command
->command_next
;
2688 service_unwatch_main_pid(s
);
2690 r
= service_spawn(s
,
2692 s
->timeout_start_usec
,
2693 EXEC_PASS_FDS
|EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_APPLY_TTY_STDIN
|EXEC_SET_WATCHDOG
|EXEC_SETENV_MONITOR_RESULT
|EXEC_WRITE_CREDENTIALS
,
2696 log_unit_warning_errno(UNIT(s
), r
, "Failed to spawn next main task: %m");
2697 service_enter_stop(s
, SERVICE_FAILURE_RESOURCES
);
2701 (void) service_set_main_pidref(s
, &pidref
);
2704 static int service_start(Unit
*u
) {
2705 Service
*s
= SERVICE(u
);
2710 /* We cannot fulfill this request right now, try again later
2712 if (IN_SET(s
->state
,
2713 SERVICE_STOP
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
, SERVICE_STOP_POST
,
2714 SERVICE_FINAL_WATCHDOG
, SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
, SERVICE_CLEANING
))
2717 /* Already on it! */
2718 if (IN_SET(s
->state
, SERVICE_CONDITION
, SERVICE_START_PRE
, SERVICE_START
, SERVICE_START_POST
))
2721 /* A service that will be restarted must be stopped first to trigger BindsTo and/or OnFailure
2722 * dependencies. If a user does not want to wait for the holdoff time to elapse, the service should
2723 * be manually restarted, not started. We simply return EAGAIN here, so that any start jobs stay
2724 * queued, and assume that the auto restart timer will eventually trigger the restart. */
2725 if (IN_SET(s
->state
, SERVICE_AUTO_RESTART
, SERVICE_DEAD_BEFORE_AUTO_RESTART
, SERVICE_FAILED_BEFORE_AUTO_RESTART
))
2728 assert(IN_SET(s
->state
, SERVICE_DEAD
, SERVICE_FAILED
, SERVICE_DEAD_RESOURCES_PINNED
, SERVICE_AUTO_RESTART_QUEUED
));
2730 r
= unit_acquire_invocation_id(u
);
2734 s
->result
= SERVICE_SUCCESS
;
2735 s
->reload_result
= SERVICE_SUCCESS
;
2736 s
->main_pid_known
= false;
2737 s
->main_pid_alien
= false;
2738 s
->forbid_restart
= false;
2740 s
->status_text
= mfree(s
->status_text
);
2741 s
->status_errno
= 0;
2743 s
->notify_access_override
= _NOTIFY_ACCESS_INVALID
;
2744 s
->notify_state
= NOTIFY_UNKNOWN
;
2746 s
->watchdog_original_usec
= s
->watchdog_usec
;
2747 s
->watchdog_override_enable
= false;
2748 s
->watchdog_override_usec
= USEC_INFINITY
;
2750 exec_command_reset_status_list_array(s
->exec_command
, _SERVICE_EXEC_COMMAND_MAX
);
2751 exec_status_reset(&s
->main_exec_status
);
2753 /* This is not an automatic restart? Flush the restart counter then */
2754 if (s
->flush_n_restarts
) {
2756 s
->flush_n_restarts
= false;
2759 u
->reset_accounting
= true;
2761 service_enter_condition(s
);
2765 static int service_stop(Unit
*u
) {
2766 Service
*s
= SERVICE(u
);
2770 /* Don't create restart jobs from manual stops. */
2771 s
->forbid_restart
= true;
2776 case SERVICE_STOP_SIGTERM
:
2777 case SERVICE_STOP_SIGKILL
:
2778 case SERVICE_STOP_POST
:
2779 case SERVICE_FINAL_WATCHDOG
:
2780 case SERVICE_FINAL_SIGTERM
:
2781 case SERVICE_FINAL_SIGKILL
:
2785 case SERVICE_AUTO_RESTART
:
2786 case SERVICE_AUTO_RESTART_QUEUED
:
2787 /* Give up on the auto restart */
2788 service_set_state(s
, service_determine_dead_state(s
));
2791 case SERVICE_CONDITION
:
2792 case SERVICE_START_PRE
:
2794 case SERVICE_START_POST
:
2795 case SERVICE_RELOAD
:
2796 case SERVICE_RELOAD_SIGNAL
:
2797 case SERVICE_RELOAD_NOTIFY
:
2798 case SERVICE_STOP_WATCHDOG
:
2799 /* If there's already something running we go directly into kill mode. */
2800 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_SUCCESS
);
2803 case SERVICE_CLEANING
:
2804 /* If we are currently cleaning, then abort it, brutally. */
2805 service_enter_signal(s
, SERVICE_FINAL_SIGKILL
, SERVICE_SUCCESS
);
2808 case SERVICE_RUNNING
:
2809 case SERVICE_EXITED
:
2810 service_enter_stop(s
, SERVICE_SUCCESS
);
2813 case SERVICE_DEAD_BEFORE_AUTO_RESTART
:
2814 case SERVICE_FAILED_BEFORE_AUTO_RESTART
:
2816 case SERVICE_FAILED
:
2817 case SERVICE_DEAD_RESOURCES_PINNED
:
2819 /* Unknown state, or unit_stop() should already have handled these */
2820 assert_not_reached();
2824 static int service_reload(Unit
*u
) {
2825 Service
*s
= SERVICE(u
);
2829 assert(IN_SET(s
->state
, SERVICE_RUNNING
, SERVICE_EXITED
));
2831 service_enter_reload(s
);
2835 static bool service_can_reload(Unit
*u
) {
2836 Service
*s
= SERVICE(u
);
2840 return s
->exec_command
[SERVICE_EXEC_RELOAD
] ||
2841 s
->type
== SERVICE_NOTIFY_RELOAD
;
2844 static unsigned service_exec_command_index(Unit
*u
, ServiceExecCommand id
, const ExecCommand
*current
) {
2845 Service
*s
= SERVICE(u
);
2850 assert(id
< _SERVICE_EXEC_COMMAND_MAX
);
2852 const ExecCommand
*first
= s
->exec_command
[id
];
2854 /* Figure out where we are in the list by walking back to the beginning */
2855 for (const ExecCommand
*c
= current
; c
!= first
; c
= c
->command_prev
)
2861 static int service_serialize_exec_command(Unit
*u
, FILE *f
, const ExecCommand
*command
) {
2862 _cleanup_free_
char *args
= NULL
, *p
= NULL
;
2863 Service
*s
= SERVICE(u
);
2864 const char *type
, *key
;
2865 ServiceExecCommand id
;
2875 if (command
== s
->control_command
) {
2877 id
= s
->control_command_id
;
2880 id
= SERVICE_EXEC_START
;
2883 idx
= service_exec_command_index(u
, id
, command
);
2885 STRV_FOREACH(arg
, command
->argv
) {
2886 _cleanup_free_
char *e
= NULL
;
2894 if (!GREEDY_REALLOC(args
, length
+ 2 + n
+ 2))
2898 args
[length
++] = ' ';
2900 args
[length
++] = '"';
2901 memcpy(args
+ length
, e
, n
);
2903 args
[length
++] = '"';
2906 if (!GREEDY_REALLOC(args
, length
+ 1))
2911 p
= cescape(command
->path
);
2915 key
= strjoina(type
, "-command");
2917 /* We use '+1234' instead of '1234' to mark the last command in a sequence.
2918 * This is used in service_deserialize_exec_command(). */
2919 (void) serialize_item_format(
2922 service_exec_command_to_string(id
),
2923 command
->command_next
? "" : "+",
2930 static int service_serialize(Unit
*u
, FILE *f
, FDSet
*fds
) {
2931 Service
*s
= SERVICE(u
);
2938 (void) serialize_item(f
, "state", service_state_to_string(s
->state
));
2939 (void) serialize_item(f
, "result", service_result_to_string(s
->result
));
2940 (void) serialize_item(f
, "reload-result", service_result_to_string(s
->reload_result
));
2942 (void) serialize_pidref(f
, fds
, "control-pid", &s
->control_pid
);
2943 if (s
->main_pid_known
)
2944 (void) serialize_pidref(f
, fds
, "main-pid", &s
->main_pid
);
2946 (void) serialize_bool(f
, "main-pid-known", s
->main_pid_known
);
2947 (void) serialize_bool(f
, "bus-name-good", s
->bus_name_good
);
2948 (void) serialize_bool(f
, "bus-name-owner", s
->bus_name_owner
);
2950 (void) serialize_item_format(f
, "n-restarts", "%u", s
->n_restarts
);
2951 (void) serialize_bool(f
, "flush-n-restarts", s
->flush_n_restarts
);
2953 r
= serialize_item_escaped(f
, "status-text", s
->status_text
);
2957 service_serialize_exec_command(u
, f
, s
->control_command
);
2958 service_serialize_exec_command(u
, f
, s
->main_command
);
2960 r
= serialize_fd(f
, fds
, "stdin-fd", s
->stdin_fd
);
2963 r
= serialize_fd(f
, fds
, "stdout-fd", s
->stdout_fd
);
2966 r
= serialize_fd(f
, fds
, "stderr-fd", s
->stderr_fd
);
2970 if (s
->exec_fd_event_source
) {
2971 r
= serialize_fd(f
, fds
, "exec-fd", sd_event_source_get_io_fd(s
->exec_fd_event_source
));
2975 (void) serialize_bool(f
, "exec-fd-hot", s
->exec_fd_hot
);
2978 if (UNIT_ISSET(s
->accept_socket
)) {
2979 r
= serialize_item(f
, "accept-socket", UNIT_DEREF(s
->accept_socket
)->id
);
2984 r
= serialize_fd(f
, fds
, "socket-fd", s
->socket_fd
);
2988 LIST_FOREACH(fd_store
, fs
, s
->fd_store
) {
2989 _cleanup_free_
char *c
= NULL
;
2992 copy
= fdset_put_dup(fds
, fs
->fd
);
2994 return log_error_errno(copy
, "Failed to copy file descriptor for serialization: %m");
2996 c
= cescape(fs
->fdname
);
3000 (void) serialize_item_format(f
, "fd-store-fd", "%i \"%s\" %i", copy
, c
, fs
->do_poll
);
3003 if (s
->main_exec_status
.pid
> 0) {
3004 (void) serialize_item_format(f
, "main-exec-status-pid", PID_FMT
, s
->main_exec_status
.pid
);
3005 (void) serialize_dual_timestamp(f
, "main-exec-status-start", &s
->main_exec_status
.start_timestamp
);
3006 (void) serialize_dual_timestamp(f
, "main-exec-status-exit", &s
->main_exec_status
.exit_timestamp
);
3008 if (dual_timestamp_is_set(&s
->main_exec_status
.exit_timestamp
)) {
3009 (void) serialize_item_format(f
, "main-exec-status-code", "%i", s
->main_exec_status
.code
);
3010 (void) serialize_item_format(f
, "main-exec-status-status", "%i", s
->main_exec_status
.status
);
3014 if (s
->notify_access_override
>= 0)
3015 (void) serialize_item(f
, "notify-access-override", notify_access_to_string(s
->notify_access_override
));
3017 (void) serialize_dual_timestamp(f
, "watchdog-timestamp", &s
->watchdog_timestamp
);
3018 (void) serialize_bool(f
, "forbid-restart", s
->forbid_restart
);
3020 if (s
->watchdog_override_enable
)
3021 (void) serialize_item_format(f
, "watchdog-override-usec", USEC_FMT
, s
->watchdog_override_usec
);
3023 if (s
->watchdog_original_usec
!= USEC_INFINITY
)
3024 (void) serialize_item_format(f
, "watchdog-original-usec", USEC_FMT
, s
->watchdog_original_usec
);
3026 if (s
->reload_begin_usec
!= USEC_INFINITY
)
3027 (void) serialize_item_format(f
, "reload-begin-usec", USEC_FMT
, s
->reload_begin_usec
);
3032 int service_deserialize_exec_command(
3035 const char *value
) {
3037 Service
*s
= SERVICE(u
);
3039 unsigned idx
= 0, i
;
3040 bool control
, found
= false, last
= false;
3041 ServiceExecCommand id
= _SERVICE_EXEC_COMMAND_INVALID
;
3042 ExecCommand
*command
= NULL
;
3043 _cleanup_free_
char *path
= NULL
;
3044 _cleanup_strv_free_
char **argv
= NULL
;
3046 enum ExecCommandState
{
3047 STATE_EXEC_COMMAND_TYPE
,
3048 STATE_EXEC_COMMAND_INDEX
,
3049 STATE_EXEC_COMMAND_PATH
,
3050 STATE_EXEC_COMMAND_ARGS
,
3051 _STATE_EXEC_COMMAND_MAX
,
3052 _STATE_EXEC_COMMAND_INVALID
= -EINVAL
,
3059 control
= streq(key
, "control-command");
3061 state
= STATE_EXEC_COMMAND_TYPE
;
3064 _cleanup_free_
char *arg
= NULL
;
3066 r
= extract_first_word(&value
, &arg
, NULL
, EXTRACT_CUNESCAPE
| EXTRACT_UNQUOTE
);
3073 case STATE_EXEC_COMMAND_TYPE
:
3074 id
= service_exec_command_from_string(arg
);
3078 state
= STATE_EXEC_COMMAND_INDEX
;
3080 case STATE_EXEC_COMMAND_INDEX
:
3081 /* PID 1234 is serialized as either '1234' or '+1234'. The second form is used to
3082 * mark the last command in a sequence. We warn if the deserialized command doesn't
3083 * match what we have loaded from the unit, but we don't need to warn if that is the
3086 r
= safe_atou(arg
, &idx
);
3089 last
= arg
[0] == '+';
3091 state
= STATE_EXEC_COMMAND_PATH
;
3093 case STATE_EXEC_COMMAND_PATH
:
3094 path
= TAKE_PTR(arg
);
3095 state
= STATE_EXEC_COMMAND_ARGS
;
3097 case STATE_EXEC_COMMAND_ARGS
:
3098 r
= strv_extend(&argv
, arg
);
3103 assert_not_reached();
3107 if (state
!= STATE_EXEC_COMMAND_ARGS
)
3109 if (strv_isempty(argv
))
3110 return -EINVAL
; /* At least argv[0] must be always present. */
3112 /* Let's check whether exec command on given offset matches data that we just deserialized */
3113 for (command
= s
->exec_command
[id
], i
= 0; command
; command
= command
->command_next
, i
++) {
3117 found
= strv_equal(argv
, command
->argv
) && streq(command
->path
, path
);
3122 /* Command at the index we serialized is different, let's look for command that exactly
3123 * matches but is on different index. If there is no such command we will not resume execution. */
3124 for (command
= s
->exec_command
[id
]; command
; command
= command
->command_next
)
3125 if (strv_equal(command
->argv
, argv
) && streq(command
->path
, path
))
3129 if (command
&& control
) {
3130 s
->control_command
= command
;
3131 s
->control_command_id
= id
;
3133 s
->main_command
= command
;
3135 log_unit_debug(u
, "Current command vanished from the unit file.");
3137 log_unit_warning(u
, "Current command vanished from the unit file, execution of the command list won't be resumed.");
3142 static int service_deserialize_item(Unit
*u
, const char *key
, const char *value
, FDSet
*fds
) {
3143 Service
*s
= SERVICE(u
);
3151 if (streq(key
, "state")) {
3154 state
= service_state_from_string(value
);
3156 log_unit_debug(u
, "Failed to parse state value: %s", value
);
3158 s
->deserialized_state
= state
;
3159 } else if (streq(key
, "result")) {
3162 f
= service_result_from_string(value
);
3164 log_unit_debug(u
, "Failed to parse result value: %s", value
);
3165 else if (f
!= SERVICE_SUCCESS
)
3168 } else if (streq(key
, "reload-result")) {
3171 f
= service_result_from_string(value
);
3173 log_unit_debug(u
, "Failed to parse reload result value: %s", value
);
3174 else if (f
!= SERVICE_SUCCESS
)
3175 s
->reload_result
= f
;
3177 } else if (streq(key
, "control-pid")) {
3178 pidref_done(&s
->control_pid
);
3180 (void) deserialize_pidref(fds
, value
, &s
->control_pid
);
3182 } else if (streq(key
, "main-pid")) {
3183 _cleanup_(pidref_done
) PidRef pidref
= PIDREF_NULL
;
3185 if (deserialize_pidref(fds
, value
, &pidref
) >= 0)
3186 (void) service_set_main_pidref(s
, &pidref
);
3188 } else if (streq(key
, "main-pid-known")) {
3191 b
= parse_boolean(value
);
3193 log_unit_debug(u
, "Failed to parse main-pid-known value: %s", value
);
3195 s
->main_pid_known
= b
;
3196 } else if (streq(key
, "bus-name-good")) {
3199 b
= parse_boolean(value
);
3201 log_unit_debug(u
, "Failed to parse bus-name-good value: %s", value
);
3203 s
->bus_name_good
= b
;
3204 } else if (streq(key
, "bus-name-owner")) {
3205 r
= free_and_strdup(&s
->bus_name_owner
, value
);
3207 log_unit_error_errno(u
, r
, "Unable to deserialize current bus owner %s: %m", value
);
3208 } else if (streq(key
, "status-text")) {
3212 l
= cunescape(value
, 0, &t
);
3214 log_unit_debug_errno(u
, l
, "Failed to unescape status text '%s': %m", value
);
3216 free_and_replace(s
->status_text
, t
);
3218 } else if (streq(key
, "accept-socket")) {
3221 if (u
->type
!= UNIT_SOCKET
) {
3222 log_unit_debug(u
, "Failed to deserialize accept-socket: unit is not a socket");
3226 r
= manager_load_unit(u
->manager
, value
, NULL
, NULL
, &socket
);
3228 log_unit_debug_errno(u
, r
, "Failed to load accept-socket unit '%s': %m", value
);
3230 unit_ref_set(&s
->accept_socket
, u
, socket
);
3231 SOCKET(socket
)->n_connections
++;
3234 } else if (streq(key
, "socket-fd")) {
3235 asynchronous_close(s
->socket_fd
);
3236 s
->socket_fd
= deserialize_fd(fds
, value
);
3238 } else if (streq(key
, "fd-store-fd")) {
3239 _cleanup_free_
char *fdv
= NULL
, *fdn
= NULL
, *fdp
= NULL
;
3240 _cleanup_close_
int fd
= -EBADF
;
3243 r
= extract_first_word(&value
, &fdv
, NULL
, 0);
3245 log_unit_debug(u
, "Failed to parse fd-store-fd value, ignoring: %s", value
);
3249 fd
= deserialize_fd(fds
, fdv
);
3253 r
= extract_first_word(&value
, &fdn
, NULL
, EXTRACT_CUNESCAPE
| EXTRACT_UNQUOTE
);
3255 log_unit_debug(u
, "Failed to parse fd-store-fd value, ignoring: %s", value
);
3259 r
= extract_first_word(&value
, &fdp
, NULL
, 0);
3261 /* If the value is not present, we assume the default */
3263 } else if (r
< 0 || (r
= safe_atoi(fdp
, &do_poll
)) < 0) {
3264 log_unit_debug_errno(u
, r
, "Failed to parse fd-store-fd value \"%s\", ignoring: %m", value
);
3268 r
= service_add_fd_store(s
, fd
, fdn
, do_poll
);
3270 log_unit_debug_errno(u
, r
, "Failed to store deserialized fd %i, ignoring: %m", fd
);
3275 } else if (streq(key
, "main-exec-status-pid")) {
3278 if (parse_pid(value
, &pid
) < 0)
3279 log_unit_debug(u
, "Failed to parse main-exec-status-pid value: %s", value
);
3281 s
->main_exec_status
.pid
= pid
;
3282 } else if (streq(key
, "main-exec-status-code")) {
3285 if (safe_atoi(value
, &i
) < 0)
3286 log_unit_debug(u
, "Failed to parse main-exec-status-code value: %s", value
);
3288 s
->main_exec_status
.code
= i
;
3289 } else if (streq(key
, "main-exec-status-status")) {
3292 if (safe_atoi(value
, &i
) < 0)
3293 log_unit_debug(u
, "Failed to parse main-exec-status-status value: %s", value
);
3295 s
->main_exec_status
.status
= i
;
3296 } else if (streq(key
, "main-exec-status-start"))
3297 deserialize_dual_timestamp(value
, &s
->main_exec_status
.start_timestamp
);
3298 else if (streq(key
, "main-exec-status-exit"))
3299 deserialize_dual_timestamp(value
, &s
->main_exec_status
.exit_timestamp
);
3300 else if (streq(key
, "notify-access-override")) {
3301 NotifyAccess notify_access
;
3303 notify_access
= notify_access_from_string(value
);
3304 if (notify_access
< 0)
3305 log_unit_debug(u
, "Failed to parse notify-access-override value: %s", value
);
3307 s
->notify_access_override
= notify_access
;
3308 } else if (streq(key
, "watchdog-timestamp"))
3309 deserialize_dual_timestamp(value
, &s
->watchdog_timestamp
);
3310 else if (streq(key
, "forbid-restart")) {
3313 b
= parse_boolean(value
);
3315 log_unit_debug(u
, "Failed to parse forbid-restart value: %s", value
);
3317 s
->forbid_restart
= b
;
3318 } else if (streq(key
, "stdin-fd")) {
3320 asynchronous_close(s
->stdin_fd
);
3321 s
->stdin_fd
= deserialize_fd(fds
, value
);
3322 if (s
->stdin_fd
>= 0)
3323 s
->exec_context
.stdio_as_fds
= true;
3325 } else if (streq(key
, "stdout-fd")) {
3327 asynchronous_close(s
->stdout_fd
);
3328 s
->stdout_fd
= deserialize_fd(fds
, value
);
3329 if (s
->stdout_fd
>= 0)
3330 s
->exec_context
.stdio_as_fds
= true;
3332 } else if (streq(key
, "stderr-fd")) {
3334 asynchronous_close(s
->stderr_fd
);
3335 s
->stderr_fd
= deserialize_fd(fds
, value
);
3336 if (s
->stderr_fd
>= 0)
3337 s
->exec_context
.stdio_as_fds
= true;
3339 } else if (streq(key
, "exec-fd")) {
3340 _cleanup_close_
int fd
= -EBADF
;
3342 fd
= deserialize_fd(fds
, value
);
3344 s
->exec_fd_event_source
= sd_event_source_disable_unref(s
->exec_fd_event_source
);
3346 if (service_allocate_exec_fd_event_source(s
, fd
, &s
->exec_fd_event_source
) >= 0)
3350 } else if (streq(key
, "watchdog-override-usec")) {
3351 if (deserialize_usec(value
, &s
->watchdog_override_usec
) < 0)
3352 log_unit_debug(u
, "Failed to parse watchdog_override_usec value: %s", value
);
3354 s
->watchdog_override_enable
= true;
3356 } else if (streq(key
, "watchdog-original-usec")) {
3357 if (deserialize_usec(value
, &s
->watchdog_original_usec
) < 0)
3358 log_unit_debug(u
, "Failed to parse watchdog_original_usec value: %s", value
);
3360 } else if (STR_IN_SET(key
, "main-command", "control-command")) {
3361 r
= service_deserialize_exec_command(u
, key
, value
);
3363 log_unit_debug_errno(u
, r
, "Failed to parse serialized command \"%s\": %m", value
);
3365 } else if (streq(key
, "n-restarts")) {
3366 r
= safe_atou(value
, &s
->n_restarts
);
3368 log_unit_debug_errno(u
, r
, "Failed to parse serialized restart counter '%s': %m", value
);
3370 } else if (streq(key
, "flush-n-restarts")) {
3371 r
= parse_boolean(value
);
3373 log_unit_debug_errno(u
, r
, "Failed to parse serialized flush restart counter setting '%s': %m", value
);
3375 s
->flush_n_restarts
= r
;
3376 } else if (streq(key
, "reload-begin-usec")) {
3377 r
= deserialize_usec(value
, &s
->reload_begin_usec
);
3379 log_unit_debug_errno(u
, r
, "Failed to parse serialized reload begin timestamp '%s', ignoring: %m", value
);
3381 log_unit_debug(u
, "Unknown serialization key: %s", key
);
3386 static UnitActiveState
service_active_state(Unit
*u
) {
3387 const UnitActiveState
*table
;
3391 table
= SERVICE(u
)->type
== SERVICE_IDLE
? state_translation_table_idle
: state_translation_table
;
3393 return table
[SERVICE(u
)->state
];
3396 static const char *service_sub_state_to_string(Unit
*u
) {
3399 return service_state_to_string(SERVICE(u
)->state
);
3402 static bool service_may_gc(Unit
*u
) {
3403 Service
*s
= SERVICE(u
);
3407 /* Never clean up services that still have a process around, even if the service is formally dead. Note that
3408 * unit_may_gc() already checked our cgroup for us, we just check our two additional PIDs, too, in case they
3409 * have moved outside of the cgroup. */
3411 if (main_pid_good(s
) > 0 ||
3412 control_pid_good(s
) > 0)
3415 /* Only allow collection of actually dead services, i.e. not those that are in the transitionary
3416 * SERVICE_DEAD_BEFORE_AUTO_RESTART/SERVICE_FAILED_BEFORE_AUTO_RESTART states. */
3417 if (!IN_SET(s
->state
, SERVICE_DEAD
, SERVICE_FAILED
, SERVICE_DEAD_RESOURCES_PINNED
))
3423 static int service_retry_pid_file(Service
*s
) {
3426 assert(s
->pid_file
);
3427 assert(IN_SET(s
->state
, SERVICE_START
, SERVICE_START_POST
));
3429 r
= service_load_pid_file(s
, false);
3433 service_unwatch_pid_file(s
);
3435 service_enter_running(s
, SERVICE_SUCCESS
);
3439 static int service_watch_pid_file(Service
*s
) {
3442 log_unit_debug(UNIT(s
), "Setting watch for PID file %s", s
->pid_file_pathspec
->path
);
3444 r
= path_spec_watch(s
->pid_file_pathspec
, service_dispatch_inotify_io
);
3446 log_unit_error_errno(UNIT(s
), r
, "Failed to set a watch for PID file %s: %m", s
->pid_file_pathspec
->path
);
3447 service_unwatch_pid_file(s
);
3451 /* the pidfile might have appeared just before we set the watch */
3452 log_unit_debug(UNIT(s
), "Trying to read PID file %s in case it changed", s
->pid_file_pathspec
->path
);
3453 service_retry_pid_file(s
);
3458 static int service_demand_pid_file(Service
*s
) {
3459 _cleanup_free_ PathSpec
*ps
= NULL
;
3461 assert(s
->pid_file
);
3462 assert(!s
->pid_file_pathspec
);
3464 ps
= new(PathSpec
, 1);
3470 .path
= strdup(s
->pid_file
),
3471 /* PATH_CHANGED would not be enough. There are daemons (sendmail) that keep their PID file
3472 * open all the time. */
3473 .type
= PATH_MODIFIED
,
3474 .inotify_fd
= -EBADF
,
3480 path_simplify(ps
->path
);
3482 s
->pid_file_pathspec
= TAKE_PTR(ps
);
3484 return service_watch_pid_file(s
);
3487 static int service_dispatch_inotify_io(sd_event_source
*source
, int fd
, uint32_t events
, void *userdata
) {
3488 PathSpec
*p
= ASSERT_PTR(userdata
);
3491 s
= SERVICE(p
->unit
);
3495 assert(IN_SET(s
->state
, SERVICE_START
, SERVICE_START_POST
));
3496 assert(s
->pid_file_pathspec
);
3497 assert(path_spec_owns_inotify_fd(s
->pid_file_pathspec
, fd
));
3499 log_unit_debug(UNIT(s
), "inotify event");
3501 if (path_spec_fd_event(p
, events
) < 0)
3504 if (service_retry_pid_file(s
) == 0)
3507 if (service_watch_pid_file(s
) < 0)
3513 service_unwatch_pid_file(s
);
3514 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_RESOURCES
);
3518 static int service_dispatch_exec_io(sd_event_source
*source
, int fd
, uint32_t events
, void *userdata
) {
3519 Service
*s
= SERVICE(userdata
);
3523 log_unit_debug(UNIT(s
), "got exec-fd event");
3525 /* If Type=exec is set, we'll consider a service started successfully the instant we invoked execve()
3526 * successfully for it. We implement this through a pipe() towards the child, which the kernel automatically
3527 * closes for us due to O_CLOEXEC on execve() in the child, which then triggers EOF on the pipe in the
3528 * parent. We need to be careful however, as there are other reasons that we might cause the child's side of
3529 * the pipe to be closed (for example, a simple exit()). To deal with that we'll ignore EOFs on the pipe unless
3530 * the child signalled us first that it is about to call the execve(). It does so by sending us a simple
3531 * non-zero byte via the pipe. We also provide the child with a way to inform us in case execve() failed: if it
3532 * sends a zero byte we'll ignore POLLHUP on the fd again. */
3538 n
= read(fd
, &x
, sizeof(x
));
3540 if (errno
== EAGAIN
) /* O_NONBLOCK in effect → everything queued has now been processed. */
3543 return log_unit_error_errno(UNIT(s
), errno
, "Failed to read from exec_fd: %m");
3545 if (n
== 0) { /* EOF → the event we are waiting for */
3547 s
->exec_fd_event_source
= sd_event_source_disable_unref(s
->exec_fd_event_source
);
3549 if (s
->exec_fd_hot
) { /* Did the child tell us to expect EOF now? */
3550 log_unit_debug(UNIT(s
), "Got EOF on exec-fd");
3552 s
->exec_fd_hot
= false;
3554 /* Nice! This is what we have been waiting for. Transition to next state. */
3555 if (s
->type
== SERVICE_EXEC
&& s
->state
== SERVICE_START
)
3556 service_enter_start_post(s
);
3558 log_unit_debug(UNIT(s
), "Got EOF on exec-fd while it was disabled, ignoring.");
3563 /* A byte was read → this turns on/off the exec fd logic */
3564 assert(n
== sizeof(x
));
3571 static void service_notify_cgroup_empty_event(Unit
*u
) {
3572 Service
*s
= SERVICE(u
);
3576 log_unit_debug(u
, "Control group is empty.");
3580 /* Waiting for SIGCHLD is usually more interesting, because it includes return
3581 * codes/signals. Which is why we ignore the cgroup events for most cases, except when we
3582 * don't know pid which to expect the SIGCHLD for. */
3585 if (IN_SET(s
->type
, SERVICE_NOTIFY
, SERVICE_NOTIFY_RELOAD
) &&
3586 main_pid_good(s
) == 0 &&
3587 control_pid_good(s
) == 0) {
3588 /* No chance of getting a ready notification anymore */
3589 service_enter_stop_post(s
, SERVICE_FAILURE_PROTOCOL
);
3593 if (s
->exit_type
== SERVICE_EXIT_CGROUP
&& main_pid_good(s
) <= 0)
3594 service_enter_start_post(s
);
3597 case SERVICE_START_POST
:
3598 if (s
->pid_file_pathspec
&&
3599 main_pid_good(s
) == 0 &&
3600 control_pid_good(s
) == 0) {
3602 /* Give up hoping for the daemon to write its PID file */
3603 log_unit_warning(u
, "Daemon never wrote its PID file. Failing.");
3605 service_unwatch_pid_file(s
);
3606 if (s
->state
== SERVICE_START
)
3607 service_enter_stop_post(s
, SERVICE_FAILURE_PROTOCOL
);
3609 service_enter_stop(s
, SERVICE_FAILURE_PROTOCOL
);
3613 case SERVICE_RUNNING
:
3614 /* service_enter_running() will figure out what to do */
3615 service_enter_running(s
, SERVICE_SUCCESS
);
3618 case SERVICE_STOP_WATCHDOG
:
3619 case SERVICE_STOP_SIGTERM
:
3620 case SERVICE_STOP_SIGKILL
:
3622 if (main_pid_good(s
) <= 0 && control_pid_good(s
) <= 0)
3623 service_enter_stop_post(s
, SERVICE_SUCCESS
);
3627 case SERVICE_STOP_POST
:
3628 case SERVICE_FINAL_WATCHDOG
:
3629 case SERVICE_FINAL_SIGTERM
:
3630 case SERVICE_FINAL_SIGKILL
:
3631 if (main_pid_good(s
) <= 0 && control_pid_good(s
) <= 0)
3632 service_enter_dead(s
, SERVICE_SUCCESS
, true);
3636 /* If the cgroup empty notification comes when the unit is not active, we must have failed to clean
3637 * up the cgroup earlier and should do it now. */
3638 case SERVICE_AUTO_RESTART
:
3639 case SERVICE_AUTO_RESTART_QUEUED
:
3640 unit_prune_cgroup(u
);
3648 static void service_notify_cgroup_oom_event(Unit
*u
, bool managed_oom
) {
3649 Service
*s
= SERVICE(u
);
3652 log_unit_debug(u
, "Process(es) of control group were killed by systemd-oomd.");
3654 log_unit_debug(u
, "Process of control group was killed by the OOM killer.");
3656 if (s
->oom_policy
== OOM_CONTINUE
)
3661 case SERVICE_CONDITION
:
3662 case SERVICE_START_PRE
:
3664 case SERVICE_START_POST
:
3666 if (s
->oom_policy
== OOM_STOP
)
3667 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_OOM_KILL
);
3668 else if (s
->oom_policy
== OOM_KILL
)
3669 service_enter_signal(s
, SERVICE_STOP_SIGKILL
, SERVICE_FAILURE_OOM_KILL
);
3673 case SERVICE_EXITED
:
3674 case SERVICE_RUNNING
:
3675 if (s
->oom_policy
== OOM_STOP
)
3676 service_enter_stop(s
, SERVICE_FAILURE_OOM_KILL
);
3677 else if (s
->oom_policy
== OOM_KILL
)
3678 service_enter_signal(s
, SERVICE_STOP_SIGKILL
, SERVICE_FAILURE_OOM_KILL
);
3682 case SERVICE_STOP_WATCHDOG
:
3683 case SERVICE_STOP_SIGTERM
:
3684 service_enter_signal(s
, SERVICE_STOP_SIGKILL
, SERVICE_FAILURE_OOM_KILL
);
3687 case SERVICE_STOP_SIGKILL
:
3688 case SERVICE_FINAL_SIGKILL
:
3689 if (s
->result
== SERVICE_SUCCESS
)
3690 s
->result
= SERVICE_FAILURE_OOM_KILL
;
3693 case SERVICE_STOP_POST
:
3694 case SERVICE_FINAL_SIGTERM
:
3695 service_enter_signal(s
, SERVICE_FINAL_SIGKILL
, SERVICE_FAILURE_OOM_KILL
);
3703 static void service_sigchld_event(Unit
*u
, pid_t pid
, int code
, int status
) {
3704 bool notify_dbus
= true;
3705 Service
*s
= SERVICE(u
);
3707 ExitClean clean_mode
;
3712 /* Oneshot services and non-SERVICE_EXEC_START commands should not be
3713 * considered daemons as they are typically not long running. */
3714 if (s
->type
== SERVICE_ONESHOT
|| (s
->control_pid
.pid
== pid
&& s
->control_command_id
!= SERVICE_EXEC_START
))
3715 clean_mode
= EXIT_CLEAN_COMMAND
;
3717 clean_mode
= EXIT_CLEAN_DAEMON
;
3719 if (is_clean_exit(code
, status
, clean_mode
, &s
->success_status
))
3720 f
= SERVICE_SUCCESS
;
3721 else if (code
== CLD_EXITED
)
3722 f
= SERVICE_FAILURE_EXIT_CODE
;
3723 else if (code
== CLD_KILLED
)
3724 f
= SERVICE_FAILURE_SIGNAL
;
3725 else if (code
== CLD_DUMPED
)
3726 f
= SERVICE_FAILURE_CORE_DUMP
;
3728 assert_not_reached();
3730 if (s
->main_pid
.pid
== pid
) {
3731 /* Clean up the exec_fd event source. We want to do this here, not later in
3732 * service_set_state(), because service_enter_stop_post() calls service_spawn().
3733 * The source owns its end of the pipe, so this will close that too. */
3734 s
->exec_fd_event_source
= sd_event_source_disable_unref(s
->exec_fd_event_source
);
3736 /* Forking services may occasionally move to a new PID.
3737 * As long as they update the PID file before exiting the old
3738 * PID, they're fine. */
3739 if (service_load_pid_file(s
, false) > 0)
3742 pidref_done(&s
->main_pid
);
3743 exec_status_exit(&s
->main_exec_status
, &s
->exec_context
, pid
, code
, status
);
3745 if (s
->main_command
) {
3746 /* If this is not a forking service than the
3747 * main process got started and hence we copy
3748 * the exit status so that it is recorded both
3749 * as main and as control process exit
3752 s
->main_command
->exec_status
= s
->main_exec_status
;
3754 if (s
->main_command
->flags
& EXEC_COMMAND_IGNORE_FAILURE
)
3755 f
= SERVICE_SUCCESS
;
3756 } else if (s
->exec_command
[SERVICE_EXEC_START
]) {
3758 /* If this is a forked process, then we should
3759 * ignore the return value if this was
3760 * configured for the starter process */
3762 if (s
->exec_command
[SERVICE_EXEC_START
]->flags
& EXEC_COMMAND_IGNORE_FAILURE
)
3763 f
= SERVICE_SUCCESS
;
3766 unit_log_process_exit(
3769 service_exec_command_to_string(SERVICE_EXEC_START
),
3770 f
== SERVICE_SUCCESS
,
3773 if (s
->result
== SERVICE_SUCCESS
)
3776 if (s
->main_command
&&
3777 s
->main_command
->command_next
&&
3778 s
->type
== SERVICE_ONESHOT
&&
3779 f
== SERVICE_SUCCESS
) {
3781 /* There is another command to execute, so let's do that. */
3783 log_unit_debug(u
, "Running next main command for state %s.", service_state_to_string(s
->state
));
3784 service_run_next_main(s
);
3787 s
->main_command
= NULL
;
3789 /* Services with ExitType=cgroup do not act on main PID exiting, unless the cgroup is
3791 if (s
->exit_type
== SERVICE_EXIT_MAIN
|| cgroup_good(s
) <= 0) {
3792 /* The service exited, so the service is officially gone. */
3795 case SERVICE_START_POST
:
3796 case SERVICE_RELOAD
:
3797 case SERVICE_RELOAD_SIGNAL
:
3798 case SERVICE_RELOAD_NOTIFY
:
3799 /* If neither main nor control processes are running then the current
3800 * state can never exit cleanly, hence immediately terminate the
3802 if (control_pid_good(s
) <= 0)
3803 service_enter_stop(s
, f
);
3805 /* Otherwise need to wait until the operation is done. */
3809 /* Need to wait until the operation is done. */
3813 if (s
->type
== SERVICE_ONESHOT
) {
3814 /* This was our main goal, so let's go on */
3815 if (f
== SERVICE_SUCCESS
)
3816 service_enter_start_post(s
);
3818 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
3820 } else if (IN_SET(s
->type
, SERVICE_NOTIFY
, SERVICE_NOTIFY_RELOAD
)) {
3821 /* Only enter running through a notification, so that the
3822 * SERVICE_START state signifies that no ready notification
3823 * has been received */
3824 if (f
!= SERVICE_SUCCESS
)
3825 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
3826 else if (!s
->remain_after_exit
|| service_get_notify_access(s
) == NOTIFY_MAIN
)
3827 /* The service has never been and will never be active */
3828 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_PROTOCOL
);
3833 case SERVICE_RUNNING
:
3834 service_enter_running(s
, f
);
3837 case SERVICE_STOP_WATCHDOG
:
3838 case SERVICE_STOP_SIGTERM
:
3839 case SERVICE_STOP_SIGKILL
:
3841 if (control_pid_good(s
) <= 0)
3842 service_enter_stop_post(s
, f
);
3844 /* If there is still a control process, wait for that first */
3847 case SERVICE_STOP_POST
:
3849 if (control_pid_good(s
) <= 0)
3850 service_enter_signal(s
, SERVICE_FINAL_SIGTERM
, f
);
3854 case SERVICE_FINAL_WATCHDOG
:
3855 case SERVICE_FINAL_SIGTERM
:
3856 case SERVICE_FINAL_SIGKILL
:
3858 if (control_pid_good(s
) <= 0)
3859 service_enter_dead(s
, f
, true);
3863 assert_not_reached();
3865 } else if (s
->exit_type
== SERVICE_EXIT_CGROUP
&& s
->state
== SERVICE_START
)
3866 /* If a main process exits very quickly, this function might be executed
3867 * before service_dispatch_exec_io(). Since this function disabled IO events
3868 * to monitor the main process above, we need to update the state here too.
3869 * Let's consider the process is successfully launched and exited. */
3870 service_enter_start_post(s
);
3873 } else if (s
->control_pid
.pid
== pid
) {
3877 pidref_done(&s
->control_pid
);
3879 if (s
->control_command
) {
3880 exec_status_exit(&s
->control_command
->exec_status
, &s
->exec_context
, pid
, code
, status
);
3882 if (s
->control_command
->flags
& EXEC_COMMAND_IGNORE_FAILURE
)
3883 f
= SERVICE_SUCCESS
;
3886 /* ExecCondition= calls that exit with (0, 254] should invoke skip-like behavior instead of failing */
3887 if (s
->state
== SERVICE_CONDITION
) {
3888 if (f
== SERVICE_FAILURE_EXIT_CODE
&& status
< 255) {
3889 UNIT(s
)->condition_result
= false;
3890 f
= SERVICE_SKIP_CONDITION
;
3892 } else if (f
== SERVICE_SUCCESS
) {
3893 UNIT(s
)->condition_result
= true;
3898 kind
= "Condition check process";
3900 kind
= "Control process";
3901 success
= f
== SERVICE_SUCCESS
;
3904 unit_log_process_exit(
3907 service_exec_command_to_string(s
->control_command_id
),
3911 if (s
->state
!= SERVICE_RELOAD
&& s
->result
== SERVICE_SUCCESS
)
3914 if (s
->control_command
&&
3915 s
->control_command
->command_next
&&
3916 f
== SERVICE_SUCCESS
) {
3918 /* There is another command to * execute, so let's do that. */
3920 log_unit_debug(u
, "Running next control command for state %s.", service_state_to_string(s
->state
));
3921 service_run_next_control(s
);
3924 /* No further commands for this step, so let's figure out what to do next */
3926 s
->control_command
= NULL
;
3927 s
->control_command_id
= _SERVICE_EXEC_COMMAND_INVALID
;
3929 log_unit_debug(u
, "Got final SIGCHLD for state %s.", service_state_to_string(s
->state
));
3933 case SERVICE_CONDITION
:
3934 if (f
== SERVICE_SUCCESS
)
3935 service_enter_start_pre(s
);
3937 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
3940 case SERVICE_START_PRE
:
3941 if (f
== SERVICE_SUCCESS
)
3942 service_enter_start(s
);
3944 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
3948 if (s
->type
!= SERVICE_FORKING
)
3949 /* Maybe spurious event due to a reload that changed the type? */
3952 if (f
!= SERVICE_SUCCESS
) {
3953 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
3958 bool has_start_post
;
3961 /* Let's try to load the pid file here if we can.
3962 * The PID file might actually be created by a START_POST
3963 * script. In that case don't worry if the loading fails. */
3965 has_start_post
= s
->exec_command
[SERVICE_EXEC_START_POST
];
3966 r
= service_load_pid_file(s
, !has_start_post
);
3967 if (!has_start_post
&& r
< 0) {
3968 r
= service_demand_pid_file(s
);
3969 if (r
< 0 || cgroup_good(s
) == 0)
3970 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_PROTOCOL
);
3974 service_search_main_pid(s
);
3976 service_enter_start_post(s
);
3979 case SERVICE_START_POST
:
3980 if (f
!= SERVICE_SUCCESS
) {
3981 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
3988 r
= service_load_pid_file(s
, true);
3990 r
= service_demand_pid_file(s
);
3991 if (r
< 0 || cgroup_good(s
) == 0)
3992 service_enter_stop(s
, SERVICE_FAILURE_PROTOCOL
);
3996 service_search_main_pid(s
);
3998 service_enter_running(s
, SERVICE_SUCCESS
);
4001 case SERVICE_RELOAD
:
4002 case SERVICE_RELOAD_SIGNAL
:
4003 case SERVICE_RELOAD_NOTIFY
:
4004 if (f
== SERVICE_SUCCESS
)
4005 if (service_load_pid_file(s
, true) < 0)
4006 service_search_main_pid(s
);
4008 s
->reload_result
= f
;
4010 /* If the last notification we received from the service process indicates
4011 * we are still reloading, then don't leave reloading state just yet, just
4012 * transition into SERVICE_RELOAD_NOTIFY, to wait for the READY=1 coming,
4014 if (s
->notify_state
== NOTIFY_RELOADING
)
4015 service_set_state(s
, SERVICE_RELOAD_NOTIFY
);
4017 service_enter_running(s
, SERVICE_SUCCESS
);
4021 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
4024 case SERVICE_STOP_WATCHDOG
:
4025 case SERVICE_STOP_SIGTERM
:
4026 case SERVICE_STOP_SIGKILL
:
4027 if (main_pid_good(s
) <= 0)
4028 service_enter_stop_post(s
, f
);
4030 /* If there is still a service process around, wait until
4031 * that one quit, too */
4034 case SERVICE_STOP_POST
:
4035 if (main_pid_good(s
) <= 0)
4036 service_enter_signal(s
, SERVICE_FINAL_SIGTERM
, f
);
4039 case SERVICE_FINAL_WATCHDOG
:
4040 case SERVICE_FINAL_SIGTERM
:
4041 case SERVICE_FINAL_SIGKILL
:
4042 if (main_pid_good(s
) <= 0)
4043 service_enter_dead(s
, f
, true);
4046 case SERVICE_CLEANING
:
4048 if (s
->clean_result
== SERVICE_SUCCESS
)
4049 s
->clean_result
= f
;
4051 service_enter_dead(s
, SERVICE_SUCCESS
, false);
4055 assert_not_reached();
4058 } else /* Neither control nor main PID? If so, don't notify about anything */
4059 notify_dbus
= false;
4061 /* Notify clients about changed exit status */
4063 unit_add_to_dbus_queue(u
);
4065 /* We watch the main/control process otherwise we can't retrieve the unit they
4066 * belong to with cgroupv1. But if they are not our direct child, we won't get a
4067 * SIGCHLD for them. Therefore we need to look for others to watch so we can
4068 * detect when the cgroup becomes empty. Note that the control process is always
4069 * our child so it's pointless to watch all other processes. */
4070 if (!control_pid_good(s
))
4071 if (!s
->main_pid_known
|| s
->main_pid_alien
)
4072 (void) unit_enqueue_rewatch_pids(u
);
4075 static int service_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
) {
4076 Service
*s
= SERVICE(userdata
);
4079 assert(source
== s
->timer_event_source
);
4083 case SERVICE_CONDITION
:
4084 case SERVICE_START_PRE
:
4086 case SERVICE_START_POST
:
4087 switch (s
->timeout_start_failure_mode
) {
4089 case SERVICE_TIMEOUT_TERMINATE
:
4090 log_unit_warning(UNIT(s
), "%s operation timed out. Terminating.", service_state_to_string(s
->state
));
4091 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_TIMEOUT
);
4094 case SERVICE_TIMEOUT_ABORT
:
4095 log_unit_warning(UNIT(s
), "%s operation timed out. Aborting.", service_state_to_string(s
->state
));
4096 service_enter_signal(s
, SERVICE_STOP_WATCHDOG
, SERVICE_FAILURE_TIMEOUT
);
4099 case SERVICE_TIMEOUT_KILL
:
4100 if (s
->kill_context
.send_sigkill
) {
4101 log_unit_warning(UNIT(s
), "%s operation timed out. Killing.", service_state_to_string(s
->state
));
4102 service_enter_signal(s
, SERVICE_STOP_SIGKILL
, SERVICE_FAILURE_TIMEOUT
);
4104 log_unit_warning(UNIT(s
), "%s operation timed out. Skipping SIGKILL.", service_state_to_string(s
->state
));
4105 service_enter_stop_post(s
, SERVICE_FAILURE_TIMEOUT
);
4110 assert_not_reached();
4114 case SERVICE_RUNNING
:
4115 log_unit_warning(UNIT(s
), "Service reached runtime time limit. Stopping.");
4116 service_enter_stop(s
, SERVICE_FAILURE_TIMEOUT
);
4119 case SERVICE_RELOAD
:
4120 case SERVICE_RELOAD_SIGNAL
:
4121 case SERVICE_RELOAD_NOTIFY
:
4122 log_unit_warning(UNIT(s
), "Reload operation timed out. Killing reload process.");
4123 service_kill_control_process(s
);
4124 s
->reload_result
= SERVICE_FAILURE_TIMEOUT
;
4125 service_enter_running(s
, SERVICE_SUCCESS
);
4129 switch (s
->timeout_stop_failure_mode
) {
4131 case SERVICE_TIMEOUT_TERMINATE
:
4132 log_unit_warning(UNIT(s
), "Stopping timed out. Terminating.");
4133 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_TIMEOUT
);
4136 case SERVICE_TIMEOUT_ABORT
:
4137 log_unit_warning(UNIT(s
), "Stopping timed out. Aborting.");
4138 service_enter_signal(s
, SERVICE_STOP_WATCHDOG
, SERVICE_FAILURE_TIMEOUT
);
4141 case SERVICE_TIMEOUT_KILL
:
4142 if (s
->kill_context
.send_sigkill
) {
4143 log_unit_warning(UNIT(s
), "Stopping timed out. Killing.");
4144 service_enter_signal(s
, SERVICE_STOP_SIGKILL
, SERVICE_FAILURE_TIMEOUT
);
4146 log_unit_warning(UNIT(s
), "Stopping timed out. Skipping SIGKILL.");
4147 service_enter_stop_post(s
, SERVICE_FAILURE_TIMEOUT
);
4152 assert_not_reached();
4156 case SERVICE_STOP_WATCHDOG
:
4157 if (s
->kill_context
.send_sigkill
) {
4158 log_unit_warning(UNIT(s
), "State 'stop-watchdog' timed out. Killing.");
4159 service_enter_signal(s
, SERVICE_STOP_SIGKILL
, SERVICE_FAILURE_TIMEOUT
);
4161 log_unit_warning(UNIT(s
), "State 'stop-watchdog' timed out. Skipping SIGKILL.");
4162 service_enter_stop_post(s
, SERVICE_FAILURE_TIMEOUT
);
4166 case SERVICE_STOP_SIGTERM
:
4167 if (s
->timeout_stop_failure_mode
== SERVICE_TIMEOUT_ABORT
) {
4168 log_unit_warning(UNIT(s
), "State 'stop-sigterm' timed out. Aborting.");
4169 service_enter_signal(s
, SERVICE_STOP_WATCHDOG
, SERVICE_FAILURE_TIMEOUT
);
4170 } else if (s
->kill_context
.send_sigkill
) {
4171 log_unit_warning(UNIT(s
), "State 'stop-sigterm' timed out. Killing.");
4172 service_enter_signal(s
, SERVICE_STOP_SIGKILL
, SERVICE_FAILURE_TIMEOUT
);
4174 log_unit_warning(UNIT(s
), "State 'stop-sigterm' timed out. Skipping SIGKILL.");
4175 service_enter_stop_post(s
, SERVICE_FAILURE_TIMEOUT
);
4180 case SERVICE_STOP_SIGKILL
:
4181 /* Uh, we sent a SIGKILL and it is still not gone?
4182 * Must be something we cannot kill, so let's just be
4183 * weirded out and continue */
4185 log_unit_warning(UNIT(s
), "Processes still around after SIGKILL. Ignoring.");
4186 service_enter_stop_post(s
, SERVICE_FAILURE_TIMEOUT
);
4189 case SERVICE_STOP_POST
:
4190 switch (s
->timeout_stop_failure_mode
) {
4192 case SERVICE_TIMEOUT_TERMINATE
:
4193 log_unit_warning(UNIT(s
), "State 'stop-post' timed out. Terminating.");
4194 service_enter_signal(s
, SERVICE_FINAL_SIGTERM
, SERVICE_FAILURE_TIMEOUT
);
4197 case SERVICE_TIMEOUT_ABORT
:
4198 log_unit_warning(UNIT(s
), "State 'stop-post' timed out. Aborting.");
4199 service_enter_signal(s
, SERVICE_FINAL_WATCHDOG
, SERVICE_FAILURE_TIMEOUT
);
4202 case SERVICE_TIMEOUT_KILL
:
4203 if (s
->kill_context
.send_sigkill
) {
4204 log_unit_warning(UNIT(s
), "State 'stop-post' timed out. Killing.");
4205 service_enter_signal(s
, SERVICE_FINAL_SIGKILL
, SERVICE_FAILURE_TIMEOUT
);
4207 log_unit_warning(UNIT(s
), "State 'stop-post' timed out. Skipping SIGKILL. Entering failed mode.");
4208 service_enter_dead(s
, SERVICE_FAILURE_TIMEOUT
, false);
4213 assert_not_reached();
4217 case SERVICE_FINAL_WATCHDOG
:
4218 if (s
->kill_context
.send_sigkill
) {
4219 log_unit_warning(UNIT(s
), "State 'final-watchdog' timed out. Killing.");
4220 service_enter_signal(s
, SERVICE_FINAL_SIGKILL
, SERVICE_FAILURE_TIMEOUT
);
4222 log_unit_warning(UNIT(s
), "State 'final-watchdog' timed out. Skipping SIGKILL. Entering failed mode.");
4223 service_enter_dead(s
, SERVICE_FAILURE_TIMEOUT
, false);
4227 case SERVICE_FINAL_SIGTERM
:
4228 if (s
->timeout_stop_failure_mode
== SERVICE_TIMEOUT_ABORT
) {
4229 log_unit_warning(UNIT(s
), "State 'final-sigterm' timed out. Aborting.");
4230 service_enter_signal(s
, SERVICE_FINAL_WATCHDOG
, SERVICE_FAILURE_TIMEOUT
);
4231 } else if (s
->kill_context
.send_sigkill
) {
4232 log_unit_warning(UNIT(s
), "State 'final-sigterm' timed out. Killing.");
4233 service_enter_signal(s
, SERVICE_FINAL_SIGKILL
, SERVICE_FAILURE_TIMEOUT
);
4235 log_unit_warning(UNIT(s
), "State 'final-sigterm' timed out. Skipping SIGKILL. Entering failed mode.");
4236 service_enter_dead(s
, SERVICE_FAILURE_TIMEOUT
, false);
4241 case SERVICE_FINAL_SIGKILL
:
4242 log_unit_warning(UNIT(s
), "Processes still around after final SIGKILL. Entering failed mode.");
4243 service_enter_dead(s
, SERVICE_FAILURE_TIMEOUT
, true);
4246 case SERVICE_AUTO_RESTART
:
4247 if (s
->restart_usec
> 0)
4248 log_unit_debug(UNIT(s
),
4249 "Service restart interval %s expired, scheduling restart.",
4250 FORMAT_TIMESPAN(service_restart_usec_next(s
), USEC_PER_SEC
));
4252 log_unit_debug(UNIT(s
),
4253 "Service has no hold-off time (RestartSec=0), scheduling restart.");
4255 service_enter_restart(s
);
4258 case SERVICE_CLEANING
:
4259 log_unit_warning(UNIT(s
), "Cleaning timed out. killing.");
4261 if (s
->clean_result
== SERVICE_SUCCESS
)
4262 s
->clean_result
= SERVICE_FAILURE_TIMEOUT
;
4264 service_enter_signal(s
, SERVICE_FINAL_SIGKILL
, 0);
4268 assert_not_reached();
4274 static int service_dispatch_watchdog(sd_event_source
*source
, usec_t usec
, void *userdata
) {
4275 Service
*s
= SERVICE(userdata
);
4276 usec_t watchdog_usec
;
4279 assert(source
== s
->watchdog_event_source
);
4281 watchdog_usec
= service_get_watchdog_usec(s
);
4283 if (UNIT(s
)->manager
->service_watchdogs
) {
4284 log_unit_error(UNIT(s
), "Watchdog timeout (limit %s)!",
4285 FORMAT_TIMESPAN(watchdog_usec
, 1));
4287 service_enter_signal(s
, SERVICE_STOP_WATCHDOG
, SERVICE_FAILURE_WATCHDOG
);
4289 log_unit_warning(UNIT(s
), "Watchdog disabled! Ignoring watchdog timeout (limit %s)!",
4290 FORMAT_TIMESPAN(watchdog_usec
, 1));
4295 static bool service_notify_message_authorized(Service
*s
, pid_t pid
, FDSet
*fds
) {
4298 NotifyAccess notify_access
= service_get_notify_access(s
);
4300 if (notify_access
== NOTIFY_NONE
) {
4301 log_unit_warning(UNIT(s
), "Got notification message from PID "PID_FMT
", but reception is disabled.", pid
);
4305 if (notify_access
== NOTIFY_MAIN
&& pid
!= s
->main_pid
.pid
) {
4306 if (pidref_is_set(&s
->main_pid
))
4307 log_unit_warning(UNIT(s
), "Got notification message from PID "PID_FMT
", but reception only permitted for main PID "PID_FMT
, pid
, s
->main_pid
.pid
);
4309 log_unit_warning(UNIT(s
), "Got notification message from PID "PID_FMT
", but reception only permitted for main PID which is currently not known", pid
);
4314 if (notify_access
== NOTIFY_EXEC
&& pid
!= s
->main_pid
.pid
&& pid
!= s
->control_pid
.pid
) {
4315 if (pidref_is_set(&s
->main_pid
) && pidref_is_set(&s
->control_pid
))
4316 log_unit_warning(UNIT(s
), "Got notification message from PID "PID_FMT
", but reception only permitted for main PID "PID_FMT
" and control PID "PID_FMT
,
4317 pid
, s
->main_pid
.pid
, s
->control_pid
.pid
);
4318 else if (pidref_is_set(&s
->main_pid
))
4319 log_unit_warning(UNIT(s
), "Got notification message from PID "PID_FMT
", but reception only permitted for main PID "PID_FMT
, pid
, s
->main_pid
.pid
);
4320 else if (pidref_is_set(&s
->control_pid
))
4321 log_unit_warning(UNIT(s
), "Got notification message from PID "PID_FMT
", but reception only permitted for control PID "PID_FMT
, pid
, s
->control_pid
.pid
);
4323 log_unit_warning(UNIT(s
), "Got notification message from PID "PID_FMT
", but reception only permitted for main PID and control PID which are currently not known", pid
);
4331 static void service_force_watchdog(Service
*s
) {
4332 if (!UNIT(s
)->manager
->service_watchdogs
)
4335 log_unit_error(UNIT(s
), "Watchdog request (last status: %s)!",
4336 s
->status_text
?: "<unset>");
4338 service_enter_signal(s
, SERVICE_STOP_WATCHDOG
, SERVICE_FAILURE_WATCHDOG
);
4341 static void service_notify_message(
4343 const struct ucred
*ucred
,
4347 Service
*s
= SERVICE(u
);
4348 bool notify_dbus
= false;
4349 usec_t monotonic_usec
= USEC_INFINITY
;
4356 if (!service_notify_message_authorized(s
, ucred
->pid
, fds
))
4359 if (DEBUG_LOGGING
) {
4360 _cleanup_free_
char *cc
= NULL
;
4362 cc
= strv_join(tags
, ", ");
4363 log_unit_debug(u
, "Got notification message from PID "PID_FMT
" (%s)", ucred
->pid
, empty_to_na(cc
));
4366 /* Interpret MAINPID= */
4367 e
= strv_find_startswith(tags
, "MAINPID=");
4368 if (e
&& IN_SET(s
->state
, SERVICE_START
, SERVICE_START_POST
, SERVICE_RUNNING
, SERVICE_RELOAD
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
)) {
4369 _cleanup_(pidref_done
) PidRef new_main_pid
= PIDREF_NULL
;
4371 r
= pidref_set_pidstr(&new_main_pid
, e
);
4373 log_unit_warning_errno(u
, r
, "Failed to parse MAINPID=%s field in notification message, ignoring: %m", e
);
4374 else if (!s
->main_pid_known
|| !pidref_equal(&new_main_pid
, &s
->main_pid
)) {
4376 r
= service_is_suitable_main_pid(s
, &new_main_pid
, LOG_WARNING
);
4378 /* The new main PID is a bit suspicious, which is OK if the sender is privileged. */
4380 if (ucred
->uid
== 0) {
4381 log_unit_debug(u
, "New main PID "PID_FMT
" does not belong to service, but we'll accept it as the request to change it came from a privileged process.", new_main_pid
.pid
);
4384 log_unit_debug(u
, "New main PID "PID_FMT
" does not belong to service, refusing.", new_main_pid
.pid
);
4387 (void) service_set_main_pidref(s
, &new_main_pid
);
4389 r
= unit_watch_pidref(UNIT(s
), &s
->main_pid
, /* exclusive= */ false);
4391 log_unit_warning_errno(UNIT(s
), r
, "Failed to watch new main PID "PID_FMT
" for service: %m", s
->main_pid
.pid
);
4398 /* Parse MONOTONIC_USEC= */
4399 e
= strv_find_startswith(tags
, "MONOTONIC_USEC=");
4401 r
= safe_atou64(e
, &monotonic_usec
);
4403 log_unit_warning_errno(u
, r
, "Failed to parse MONOTONIC_USEC= field in notification message, ignoring: %s", e
);
4406 /* Interpret READY=/STOPPING=/RELOADING=. STOPPING= wins over the others, and READY= over RELOADING= */
4407 if (strv_contains(tags
, "STOPPING=1")) {
4408 s
->notify_state
= NOTIFY_STOPPING
;
4410 if (IN_SET(s
->state
, SERVICE_RUNNING
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
))
4411 service_enter_stop_by_notify(s
);
4415 } else if (strv_contains(tags
, "READY=1")) {
4417 s
->notify_state
= NOTIFY_READY
;
4419 /* Type=notify services inform us about completed initialization with READY=1 */
4420 if (IN_SET(s
->type
, SERVICE_NOTIFY
, SERVICE_NOTIFY_RELOAD
) &&
4421 s
->state
== SERVICE_START
)
4422 service_enter_start_post(s
);
4424 /* Sending READY=1 while we are reloading informs us that the reloading is complete. */
4425 if (s
->state
== SERVICE_RELOAD_NOTIFY
)
4426 service_enter_running(s
, SERVICE_SUCCESS
);
4428 /* Combined RELOADING=1 and READY=1? Then this is indication that the service started and
4429 * immediately finished reloading. */
4430 if (s
->state
== SERVICE_RELOAD_SIGNAL
&&
4431 strv_contains(tags
, "RELOADING=1") &&
4432 monotonic_usec
!= USEC_INFINITY
&&
4433 monotonic_usec
>= s
->reload_begin_usec
) {
4434 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
4436 /* Propagate a reload explicitly */
4437 r
= manager_propagate_reload(UNIT(s
)->manager
, UNIT(s
), JOB_FAIL
, &error
);
4439 log_unit_warning(UNIT(s
), "Failed to schedule propagation of reload, ignoring: %s", bus_error_message(&error
, r
));
4441 service_enter_running(s
, SERVICE_SUCCESS
);
4446 } else if (strv_contains(tags
, "RELOADING=1")) {
4448 s
->notify_state
= NOTIFY_RELOADING
;
4450 /* Sending RELOADING=1 after we send SIGHUP to request a reload will transition
4451 * things to "reload-notify" state, where we'll wait for READY=1 to let us know the
4452 * reload is done. Note that we insist on a timestamp being sent along here, so that
4453 * we know for sure this is a reload cycle initiated *after* we sent the signal */
4454 if (s
->state
== SERVICE_RELOAD_SIGNAL
&&
4455 monotonic_usec
!= USEC_INFINITY
&&
4456 monotonic_usec
>= s
->reload_begin_usec
)
4457 /* Note, we don't call service_enter_reload_by_notify() here, because we
4458 * don't need reload propagation nor do we want to restart the time-out. */
4459 service_set_state(s
, SERVICE_RELOAD_NOTIFY
);
4461 if (s
->state
== SERVICE_RUNNING
)
4462 service_enter_reload_by_notify(s
);
4467 /* Interpret STATUS= */
4468 e
= strv_find_startswith(tags
, "STATUS=");
4470 _cleanup_free_
char *t
= NULL
;
4473 /* Note that this size limit check is mostly paranoia: since the datagram size we are willing
4474 * to process is already limited to NOTIFY_BUFFER_MAX, this limit here should never be hit. */
4475 if (strlen(e
) > STATUS_TEXT_MAX
)
4476 log_unit_warning(u
, "Status message overly long (%zu > %u), ignoring.", strlen(e
), STATUS_TEXT_MAX
);
4477 else if (!utf8_is_valid(e
))
4478 log_unit_warning(u
, "Status message in notification message is not UTF-8 clean, ignoring.");
4486 if (!streq_ptr(s
->status_text
, t
)) {
4487 free_and_replace(s
->status_text
, t
);
4492 /* Interpret NOTIFYACCESS= */
4493 e
= strv_find_startswith(tags
, "NOTIFYACCESS=");
4495 NotifyAccess notify_access
;
4497 notify_access
= notify_access_from_string(e
);
4498 if (notify_access
< 0)
4499 log_unit_warning_errno(u
, notify_access
,
4500 "Failed to parse NOTIFYACCESS= field value '%s' in notification message, ignoring: %m", e
);
4502 /* We don't need to check whether the new access mode is more strict than what is
4503 * already in use, since only the privileged process is allowed to change it
4504 * in the first place. */
4505 if (service_get_notify_access(s
) != notify_access
) {
4506 service_override_notify_access(s
, notify_access
);
4511 /* Interpret ERRNO= */
4512 e
= strv_find_startswith(tags
, "ERRNO=");
4516 status_errno
= parse_errno(e
);
4517 if (status_errno
< 0)
4518 log_unit_warning_errno(u
, status_errno
,
4519 "Failed to parse ERRNO= field value '%s' in notification message: %m", e
);
4520 else if (s
->status_errno
!= status_errno
) {
4521 s
->status_errno
= status_errno
;
4526 /* Interpret EXTEND_TIMEOUT= */
4527 e
= strv_find_startswith(tags
, "EXTEND_TIMEOUT_USEC=");
4529 usec_t extend_timeout_usec
;
4530 if (safe_atou64(e
, &extend_timeout_usec
) < 0)
4531 log_unit_warning(u
, "Failed to parse EXTEND_TIMEOUT_USEC=%s", e
);
4533 service_extend_timeout(s
, extend_timeout_usec
);
4536 /* Interpret WATCHDOG= */
4537 e
= strv_find_startswith(tags
, "WATCHDOG=");
4540 service_reset_watchdog(s
);
4541 else if (streq(e
, "trigger"))
4542 service_force_watchdog(s
);
4544 log_unit_warning(u
, "Passed WATCHDOG= field is invalid, ignoring.");
4547 e
= strv_find_startswith(tags
, "WATCHDOG_USEC=");
4549 usec_t watchdog_override_usec
;
4550 if (safe_atou64(e
, &watchdog_override_usec
) < 0)
4551 log_unit_warning(u
, "Failed to parse WATCHDOG_USEC=%s", e
);
4553 service_override_watchdog_timeout(s
, watchdog_override_usec
);
4556 /* Process FD store messages. Either FDSTOREREMOVE=1 for removal, or FDSTORE=1 for addition. In both cases,
4557 * process FDNAME= for picking the file descriptor name to use. Note that FDNAME= is required when removing
4558 * fds, but optional when pushing in new fds, for compatibility reasons. */
4559 if (strv_contains(tags
, "FDSTOREREMOVE=1")) {
4562 name
= strv_find_startswith(tags
, "FDNAME=");
4563 if (!name
|| !fdname_is_valid(name
))
4564 log_unit_warning(u
, "FDSTOREREMOVE=1 requested, but no valid file descriptor name passed, ignoring.");
4566 service_remove_fd_store(s
, name
);
4568 } else if (strv_contains(tags
, "FDSTORE=1")) {
4571 name
= strv_find_startswith(tags
, "FDNAME=");
4572 if (name
&& !fdname_is_valid(name
)) {
4573 log_unit_warning(u
, "Passed FDNAME= name is invalid, ignoring.");
4577 (void) service_add_fd_store_set(s
, fds
, name
, !strv_contains(tags
, "FDPOLL=0"));
4580 /* Notify clients about changed status or main pid */
4582 unit_add_to_dbus_queue(u
);
4585 static int service_get_timeout(Unit
*u
, usec_t
*timeout
) {
4586 Service
*s
= SERVICE(u
);
4590 if (!s
->timer_event_source
)
4593 r
= sd_event_source_get_time(s
->timer_event_source
, &t
);
4596 if (t
== USEC_INFINITY
)
4603 static usec_t
service_get_timeout_start_usec(Unit
*u
) {
4604 Service
*s
= SERVICE(ASSERT_PTR(u
));
4605 return s
->timeout_start_usec
;
4608 static bool pick_up_pid_from_bus_name(Service
*s
) {
4611 /* If the service is running but we have no main PID yet, get it from the owner of the D-Bus name */
4613 return !pidref_is_set(&s
->main_pid
) &&
4619 SERVICE_RELOAD_SIGNAL
,
4620 SERVICE_RELOAD_NOTIFY
);
4623 static int bus_name_pid_lookup_callback(sd_bus_message
*reply
, void *userdata
, sd_bus_error
*ret_error
) {
4624 _cleanup_(pidref_done
) PidRef pidref
= PIDREF_NULL
;
4625 const sd_bus_error
*e
;
4626 Unit
*u
= ASSERT_PTR(userdata
);
4634 s
->bus_name_pid_lookup_slot
= sd_bus_slot_unref(s
->bus_name_pid_lookup_slot
);
4636 if (!s
->bus_name
|| !pick_up_pid_from_bus_name(s
))
4639 e
= sd_bus_message_get_error(reply
);
4641 r
= sd_bus_error_get_errno(e
);
4642 log_warning_errno(r
, "GetConnectionUnixProcessID() failed: %s", bus_error_message(e
, r
));
4646 r
= sd_bus_message_read(reply
, "u", &pid
);
4648 bus_log_parse_error(r
);
4652 r
= pidref_set_pid(&pidref
, pid
);
4654 log_debug_errno(r
, "GetConnectionUnixProcessID() returned invalid PID: %m");
4658 log_unit_debug(u
, "D-Bus name %s is now owned by process " PID_FMT
, s
->bus_name
, pidref
.pid
);
4660 (void) service_set_main_pidref(s
, &pidref
);
4661 (void) unit_watch_pidref(UNIT(s
), &s
->main_pid
, /* exclusive= */ false);
4665 static void service_bus_name_owner_change(Unit
*u
, const char *new_owner
) {
4667 Service
*s
= SERVICE(u
);
4673 log_unit_debug(u
, "D-Bus name %s now owned by %s", s
->bus_name
, new_owner
);
4675 log_unit_debug(u
, "D-Bus name %s now not owned by anyone.", s
->bus_name
);
4677 s
->bus_name_good
= new_owner
;
4679 /* Track the current owner, so we can reconstruct changes after a daemon reload */
4680 r
= free_and_strdup(&s
->bus_name_owner
, new_owner
);
4682 log_unit_error_errno(u
, r
, "Unable to set new bus name owner %s: %m", new_owner
);
4686 if (s
->type
== SERVICE_DBUS
) {
4688 /* service_enter_running() will figure out what to
4690 if (s
->state
== SERVICE_RUNNING
)
4691 service_enter_running(s
, SERVICE_SUCCESS
);
4692 else if (s
->state
== SERVICE_START
&& new_owner
)
4693 service_enter_start_post(s
);
4695 } else if (new_owner
&& pick_up_pid_from_bus_name(s
)) {
4697 /* Try to acquire PID from bus service */
4699 s
->bus_name_pid_lookup_slot
= sd_bus_slot_unref(s
->bus_name_pid_lookup_slot
);
4701 r
= sd_bus_call_method_async(
4702 u
->manager
->api_bus
,
4703 &s
->bus_name_pid_lookup_slot
,
4704 "org.freedesktop.DBus",
4705 "/org/freedesktop/DBus",
4706 "org.freedesktop.DBus",
4707 "GetConnectionUnixProcessID",
4708 bus_name_pid_lookup_callback
,
4713 log_debug_errno(r
, "Failed to request owner PID of service name, ignoring: %m");
4717 int service_set_socket_fd(
4722 bool selinux_context_net
) {
4724 _cleanup_free_
char *peer_text
= NULL
;
4730 /* This is called by the socket code when instantiating a new service for a stream socket and the socket needs
4731 * to be configured. We take ownership of the passed fd on success. */
4733 if (UNIT(s
)->load_state
!= UNIT_LOADED
)
4736 if (s
->socket_fd
>= 0)
4739 assert(!s
->socket_peer
);
4741 if (!IN_SET(s
->state
, SERVICE_DEAD
, SERVICE_DEAD_RESOURCES_PINNED
))
4744 if (getpeername_pretty(fd
, true, &peer_text
) >= 0) {
4746 if (UNIT(s
)->description
) {
4747 _cleanup_free_
char *a
= NULL
;
4749 a
= strjoin(UNIT(s
)->description
, " (", peer_text
, ")");
4753 r
= unit_set_description(UNIT(s
), a
);
4755 r
= unit_set_description(UNIT(s
), peer_text
);
4760 r
= unit_add_two_dependencies(UNIT(sock
), UNIT_BEFORE
, UNIT_TRIGGERS
, UNIT(s
), false, UNIT_DEPENDENCY_IMPLICIT
);
4765 s
->socket_peer
= socket_peer_ref(peer
);
4766 s
->socket_fd_selinux_context_net
= selinux_context_net
;
4768 unit_ref_set(&s
->accept_socket
, UNIT(s
), UNIT(sock
));
4772 static void service_reset_failed(Unit
*u
) {
4773 Service
*s
= SERVICE(u
);
4777 if (s
->state
== SERVICE_FAILED
)
4778 service_set_state(s
, service_determine_dead_state(s
));
4780 s
->result
= SERVICE_SUCCESS
;
4781 s
->reload_result
= SERVICE_SUCCESS
;
4782 s
->clean_result
= SERVICE_SUCCESS
;
4784 s
->flush_n_restarts
= false;
4787 static PidRef
* service_main_pid(Unit
*u
) {
4788 return &ASSERT_PTR(SERVICE(u
))->main_pid
;
4791 static PidRef
* service_control_pid(Unit
*u
) {
4792 return &ASSERT_PTR(SERVICE(u
))->control_pid
;
4795 static bool service_needs_console(Unit
*u
) {
4796 Service
*s
= SERVICE(u
);
4800 /* We provide our own implementation of this here, instead of relying of the generic implementation
4801 * unit_needs_console() provides, since we want to return false if we are in SERVICE_EXITED state. */
4803 if (!exec_context_may_touch_console(&s
->exec_context
))
4806 return IN_SET(s
->state
,
4813 SERVICE_RELOAD_SIGNAL
,
4814 SERVICE_RELOAD_NOTIFY
,
4816 SERVICE_STOP_WATCHDOG
,
4817 SERVICE_STOP_SIGTERM
,
4818 SERVICE_STOP_SIGKILL
,
4820 SERVICE_FINAL_WATCHDOG
,
4821 SERVICE_FINAL_SIGTERM
,
4822 SERVICE_FINAL_SIGKILL
);
4825 static int service_exit_status(Unit
*u
) {
4826 Service
*s
= SERVICE(u
);
4830 if (s
->main_exec_status
.pid
<= 0 ||
4831 !dual_timestamp_is_set(&s
->main_exec_status
.exit_timestamp
))
4834 if (s
->main_exec_status
.code
!= CLD_EXITED
)
4837 return s
->main_exec_status
.status
;
4840 static const char* service_status_text(Unit
*u
) {
4841 Service
*s
= SERVICE(u
);
4845 return s
->status_text
;
4848 static int service_clean(Unit
*u
, ExecCleanMask mask
) {
4849 _cleanup_strv_free_
char **l
= NULL
;
4850 bool may_clean_fdstore
= false;
4851 Service
*s
= SERVICE(u
);
4857 if (!IN_SET(s
->state
, SERVICE_DEAD
, SERVICE_DEAD_RESOURCES_PINNED
))
4860 /* Determine if there's anything we could potentially clean */
4861 r
= exec_context_get_clean_directories(&s
->exec_context
, u
->manager
->prefix
, mask
, &l
);
4865 if (mask
& EXEC_CLEAN_FDSTORE
)
4866 may_clean_fdstore
= s
->n_fd_store
> 0 || s
->n_fd_store_max
> 0;
4868 if (strv_isempty(l
) && !may_clean_fdstore
)
4869 return -EUNATCH
; /* Nothing to potentially clean */
4871 /* Let's clean the stuff we can clean quickly */
4872 if (may_clean_fdstore
)
4873 service_release_fd_store(s
);
4875 /* If we are done, leave quickly */
4876 if (strv_isempty(l
)) {
4877 if (s
->state
== SERVICE_DEAD_RESOURCES_PINNED
&& !s
->fd_store
)
4878 service_set_state(s
, SERVICE_DEAD
);
4882 /* We need to clean disk stuff. This is slow, hence do it out of process, and change state */
4883 service_unwatch_control_pid(s
);
4884 s
->clean_result
= SERVICE_SUCCESS
;
4885 s
->control_command
= NULL
;
4886 s
->control_command_id
= _SERVICE_EXEC_COMMAND_INVALID
;
4888 r
= service_arm_timer(s
, /* relative= */ true, s
->exec_context
.timeout_clean_usec
);
4890 log_unit_warning_errno(u
, r
, "Failed to install timer: %m");
4894 r
= unit_fork_and_watch_rm_rf(u
, l
, &s
->control_pid
);
4896 log_unit_warning_errno(u
, r
, "Failed to spawn cleaning task: %m");
4900 service_set_state(s
, SERVICE_CLEANING
);
4904 s
->clean_result
= SERVICE_FAILURE_RESOURCES
;
4905 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
4909 static int service_can_clean(Unit
*u
, ExecCleanMask
*ret
) {
4910 Service
*s
= SERVICE(u
);
4911 ExecCleanMask mask
= 0;
4917 r
= exec_context_get_clean_mask(&s
->exec_context
, &mask
);
4921 if (s
->n_fd_store_max
> 0)
4922 mask
|= EXEC_CLEAN_FDSTORE
;
4928 static const char *service_finished_job(Unit
*u
, JobType t
, JobResult result
) {
4929 if (t
== JOB_START
&&
4930 result
== JOB_DONE
&&
4931 SERVICE(u
)->type
== SERVICE_ONESHOT
)
4932 return "Finished %s.";
4934 /* Fall back to generic */
4938 static int service_can_start(Unit
*u
) {
4939 Service
*s
= SERVICE(u
);
4944 /* Make sure we don't enter a busy loop of some kind. */
4945 r
= unit_test_start_limit(u
);
4947 service_enter_dead(s
, SERVICE_FAILURE_START_LIMIT_HIT
, false);
4954 static void service_release_resources(Unit
*u
) {
4955 Service
*s
= SERVICE(ASSERT_PTR(u
));
4957 /* Invoked by the unit state engine, whenever it realizes that unit is dead and there's no job
4958 * anymore for it, and it hence is a good idea to release resources */
4960 /* Don't release resources if this is a transitionary failed/dead state
4961 * (i.e. SERVICE_DEAD_BEFORE_AUTO_RESTART/SERVICE_FAILED_BEFORE_AUTO_RESTART), insist on a permanent
4963 if (!IN_SET(s
->state
, SERVICE_DEAD
, SERVICE_FAILED
, SERVICE_DEAD_RESOURCES_PINNED
))
4966 log_unit_debug(u
, "Releasing resources...");
4968 service_release_socket_fd(s
);
4969 service_release_stdio_fd(s
);
4971 if (s
->fd_store_preserve_mode
!= EXEC_PRESERVE_YES
)
4972 service_release_fd_store(s
);
4974 if (s
->state
== SERVICE_DEAD_RESOURCES_PINNED
&& !s
->fd_store
)
4975 service_set_state(s
, SERVICE_DEAD
);
4978 static const char* const service_restart_table
[_SERVICE_RESTART_MAX
] = {
4979 [SERVICE_RESTART_NO
] = "no",
4980 [SERVICE_RESTART_ON_SUCCESS
] = "on-success",
4981 [SERVICE_RESTART_ON_FAILURE
] = "on-failure",
4982 [SERVICE_RESTART_ON_ABNORMAL
] = "on-abnormal",
4983 [SERVICE_RESTART_ON_WATCHDOG
] = "on-watchdog",
4984 [SERVICE_RESTART_ON_ABORT
] = "on-abort",
4985 [SERVICE_RESTART_ALWAYS
] = "always",
4988 DEFINE_STRING_TABLE_LOOKUP(service_restart
, ServiceRestart
);
4990 static const char* const service_restart_mode_table
[_SERVICE_RESTART_MODE_MAX
] = {
4991 [SERVICE_RESTART_MODE_NORMAL
] = "normal",
4992 [SERVICE_RESTART_MODE_DIRECT
] = "direct",
4995 DEFINE_STRING_TABLE_LOOKUP(service_restart_mode
, ServiceRestartMode
);
4997 static const char* const service_type_table
[_SERVICE_TYPE_MAX
] = {
4998 [SERVICE_SIMPLE
] = "simple",
4999 [SERVICE_FORKING
] = "forking",
5000 [SERVICE_ONESHOT
] = "oneshot",
5001 [SERVICE_DBUS
] = "dbus",
5002 [SERVICE_NOTIFY
] = "notify",
5003 [SERVICE_NOTIFY_RELOAD
] = "notify-reload",
5004 [SERVICE_IDLE
] = "idle",
5005 [SERVICE_EXEC
] = "exec",
5008 DEFINE_STRING_TABLE_LOOKUP(service_type
, ServiceType
);
5010 static const char* const service_exit_type_table
[_SERVICE_EXIT_TYPE_MAX
] = {
5011 [SERVICE_EXIT_MAIN
] = "main",
5012 [SERVICE_EXIT_CGROUP
] = "cgroup",
5015 DEFINE_STRING_TABLE_LOOKUP(service_exit_type
, ServiceExitType
);
5017 static const char* const service_exec_command_table
[_SERVICE_EXEC_COMMAND_MAX
] = {
5018 [SERVICE_EXEC_CONDITION
] = "ExecCondition",
5019 [SERVICE_EXEC_START_PRE
] = "ExecStartPre",
5020 [SERVICE_EXEC_START
] = "ExecStart",
5021 [SERVICE_EXEC_START_POST
] = "ExecStartPost",
5022 [SERVICE_EXEC_RELOAD
] = "ExecReload",
5023 [SERVICE_EXEC_STOP
] = "ExecStop",
5024 [SERVICE_EXEC_STOP_POST
] = "ExecStopPost",
5027 DEFINE_STRING_TABLE_LOOKUP(service_exec_command
, ServiceExecCommand
);
5029 static const char* const service_exec_ex_command_table
[_SERVICE_EXEC_COMMAND_MAX
] = {
5030 [SERVICE_EXEC_CONDITION
] = "ExecConditionEx",
5031 [SERVICE_EXEC_START_PRE
] = "ExecStartPreEx",
5032 [SERVICE_EXEC_START
] = "ExecStartEx",
5033 [SERVICE_EXEC_START_POST
] = "ExecStartPostEx",
5034 [SERVICE_EXEC_RELOAD
] = "ExecReloadEx",
5035 [SERVICE_EXEC_STOP
] = "ExecStopEx",
5036 [SERVICE_EXEC_STOP_POST
] = "ExecStopPostEx",
5039 DEFINE_STRING_TABLE_LOOKUP(service_exec_ex_command
, ServiceExecCommand
);
5041 static const char* const notify_state_table
[_NOTIFY_STATE_MAX
] = {
5042 [NOTIFY_UNKNOWN
] = "unknown",
5043 [NOTIFY_READY
] = "ready",
5044 [NOTIFY_RELOADING
] = "reloading",
5045 [NOTIFY_STOPPING
] = "stopping",
5048 DEFINE_STRING_TABLE_LOOKUP(notify_state
, NotifyState
);
5050 static const char* const service_result_table
[_SERVICE_RESULT_MAX
] = {
5051 [SERVICE_SUCCESS
] = "success",
5052 [SERVICE_FAILURE_RESOURCES
] = "resources",
5053 [SERVICE_FAILURE_PROTOCOL
] = "protocol",
5054 [SERVICE_FAILURE_TIMEOUT
] = "timeout",
5055 [SERVICE_FAILURE_EXIT_CODE
] = "exit-code",
5056 [SERVICE_FAILURE_SIGNAL
] = "signal",
5057 [SERVICE_FAILURE_CORE_DUMP
] = "core-dump",
5058 [SERVICE_FAILURE_WATCHDOG
] = "watchdog",
5059 [SERVICE_FAILURE_START_LIMIT_HIT
] = "start-limit-hit",
5060 [SERVICE_FAILURE_OOM_KILL
] = "oom-kill",
5061 [SERVICE_SKIP_CONDITION
] = "exec-condition",
5064 DEFINE_STRING_TABLE_LOOKUP(service_result
, ServiceResult
);
5066 static const char* const service_timeout_failure_mode_table
[_SERVICE_TIMEOUT_FAILURE_MODE_MAX
] = {
5067 [SERVICE_TIMEOUT_TERMINATE
] = "terminate",
5068 [SERVICE_TIMEOUT_ABORT
] = "abort",
5069 [SERVICE_TIMEOUT_KILL
] = "kill",
5072 DEFINE_STRING_TABLE_LOOKUP(service_timeout_failure_mode
, ServiceTimeoutFailureMode
);
5074 const UnitVTable service_vtable
= {
5075 .object_size
= sizeof(Service
),
5076 .exec_context_offset
= offsetof(Service
, exec_context
),
5077 .cgroup_context_offset
= offsetof(Service
, cgroup_context
),
5078 .kill_context_offset
= offsetof(Service
, kill_context
),
5079 .exec_runtime_offset
= offsetof(Service
, exec_runtime
),
5085 .private_section
= "Service",
5087 .can_transient
= true,
5088 .can_delegate
= true,
5090 .can_set_managed_oom
= true,
5092 .init
= service_init
,
5093 .done
= service_done
,
5094 .load
= service_load
,
5095 .release_resources
= service_release_resources
,
5097 .coldplug
= service_coldplug
,
5099 .dump
= service_dump
,
5101 .start
= service_start
,
5102 .stop
= service_stop
,
5103 .reload
= service_reload
,
5105 .can_reload
= service_can_reload
,
5107 .clean
= service_clean
,
5108 .can_clean
= service_can_clean
,
5110 .freeze
= unit_freeze_vtable_common
,
5111 .thaw
= unit_thaw_vtable_common
,
5113 .serialize
= service_serialize
,
5114 .deserialize_item
= service_deserialize_item
,
5116 .active_state
= service_active_state
,
5117 .sub_state_to_string
= service_sub_state_to_string
,
5119 .will_restart
= service_will_restart
,
5121 .may_gc
= service_may_gc
,
5123 .sigchld_event
= service_sigchld_event
,
5125 .reset_failed
= service_reset_failed
,
5127 .notify_cgroup_empty
= service_notify_cgroup_empty_event
,
5128 .notify_cgroup_oom
= service_notify_cgroup_oom_event
,
5129 .notify_message
= service_notify_message
,
5131 .main_pid
= service_main_pid
,
5132 .control_pid
= service_control_pid
,
5134 .bus_name_owner_change
= service_bus_name_owner_change
,
5136 .bus_set_property
= bus_service_set_property
,
5137 .bus_commit_properties
= bus_service_commit_properties
,
5139 .get_timeout
= service_get_timeout
,
5140 .get_timeout_start_usec
= service_get_timeout_start_usec
,
5141 .needs_console
= service_needs_console
,
5142 .exit_status
= service_exit_status
,
5143 .status_text
= service_status_text
,
5145 .status_message_formats
= {
5146 .finished_start_job
= {
5147 [JOB_FAILED
] = "Failed to start %s.",
5149 .finished_stop_job
= {
5150 [JOB_DONE
] = "Stopped %s.",
5151 [JOB_FAILED
] = "Stopped (with error) %s.",
5153 .finished_job
= service_finished_job
,
5156 .can_start
= service_can_start
,
5158 .notify_plymouth
= true,
5160 .audit_start_message_type
= AUDIT_SERVICE_START
,
5161 .audit_stop_message_type
= AUDIT_SERVICE_STOP
,