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_pid(UNIT(s
), s
->control_pid
.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_pid(UNIT(s
), s
->main_pid
.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
) {
185 /* Takes ownership of the specified pidref on success, but not on failure. */
187 if (!pidref_is_set(pidref
))
190 if (pidref
->pid
<= 1)
193 if (pidref
->pid
== getpid_cached())
196 if (pidref_equal(&s
->main_pid
, pidref
) && s
->main_pid_known
) {
201 if (!pidref_equal(&s
->main_pid
, pidref
)) {
202 service_unwatch_main_pid(s
);
203 exec_status_start(&s
->main_exec_status
, pidref
->pid
);
206 s
->main_pid
= TAKE_PIDREF(*pidref
);
207 s
->main_pid_known
= true;
208 s
->main_pid_alien
= pid_is_my_child(s
->main_pid
.pid
) == 0;
210 if (s
->main_pid_alien
)
211 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
);
216 static int service_set_main_pid(Service
*s
, pid_t pid
) {
217 _cleanup_(pidref_done
) PidRef pidref
= PIDREF_NULL
;
222 r
= pidref_set_pid(&pidref
, pid
);
226 return service_set_main_pidref(s
, &pidref
);
229 void service_release_socket_fd(Service
*s
) {
232 if (s
->socket_fd
< 0 && !UNIT_ISSET(s
->accept_socket
) && !s
->socket_peer
)
235 log_unit_debug(UNIT(s
), "Closing connection socket.");
237 /* Undo the effect of service_set_socket_fd(). */
239 s
->socket_fd
= asynchronous_close(s
->socket_fd
);
241 if (UNIT_ISSET(s
->accept_socket
)) {
242 socket_connection_unref(SOCKET(UNIT_DEREF(s
->accept_socket
)));
243 unit_ref_unset(&s
->accept_socket
);
246 s
->socket_peer
= socket_peer_unref(s
->socket_peer
);
249 static void service_override_notify_access(Service
*s
, NotifyAccess notify_access_override
) {
252 s
->notify_access_override
= notify_access_override
;
254 log_unit_debug(UNIT(s
), "notify_access=%s", notify_access_to_string(s
->notify_access
));
255 log_unit_debug(UNIT(s
), "notify_access_override=%s", notify_access_to_string(s
->notify_access_override
));
258 static void service_stop_watchdog(Service
*s
) {
261 s
->watchdog_event_source
= sd_event_source_disable_unref(s
->watchdog_event_source
);
262 s
->watchdog_timestamp
= DUAL_TIMESTAMP_NULL
;
265 static void service_start_watchdog(Service
*s
) {
266 usec_t watchdog_usec
;
271 watchdog_usec
= service_get_watchdog_usec(s
);
272 if (!timestamp_is_set(watchdog_usec
)) {
273 service_stop_watchdog(s
);
277 if (s
->watchdog_event_source
) {
278 r
= sd_event_source_set_time(s
->watchdog_event_source
, usec_add(s
->watchdog_timestamp
.monotonic
, watchdog_usec
));
280 log_unit_warning_errno(UNIT(s
), r
, "Failed to reset watchdog timer: %m");
284 r
= sd_event_source_set_enabled(s
->watchdog_event_source
, SD_EVENT_ONESHOT
);
286 r
= sd_event_add_time(
287 UNIT(s
)->manager
->event
,
288 &s
->watchdog_event_source
,
290 usec_add(s
->watchdog_timestamp
.monotonic
, watchdog_usec
), 0,
291 service_dispatch_watchdog
, s
);
293 log_unit_warning_errno(UNIT(s
), r
, "Failed to add watchdog timer: %m");
297 (void) sd_event_source_set_description(s
->watchdog_event_source
, "service-watchdog");
299 /* Let's process everything else which might be a sign
300 * of living before we consider a service died. */
301 r
= sd_event_source_set_priority(s
->watchdog_event_source
, SD_EVENT_PRIORITY_IDLE
);
304 log_unit_warning_errno(UNIT(s
), r
, "Failed to install watchdog timer: %m");
307 usec_t
service_restart_usec_next(Service
*s
) {
308 unsigned n_restarts_next
;
312 /* When the service state is in SERVICE_*_BEFORE_AUTO_RESTART or SERVICE_AUTO_RESTART, we still need
313 * to add 1 to s->n_restarts manually, because s->n_restarts is not updated until a restart job is
314 * enqueued, i.e. state has transitioned to SERVICE_AUTO_RESTART_QUEUED. */
315 n_restarts_next
= s
->n_restarts
+ (s
->state
== SERVICE_AUTO_RESTART_QUEUED
? 0 : 1);
317 if (n_restarts_next
<= 1 ||
318 s
->restart_steps
== 0 ||
319 s
->restart_usec
== 0 ||
320 s
->restart_max_delay_usec
== USEC_INFINITY
||
321 s
->restart_usec
>= s
->restart_max_delay_usec
)
322 return s
->restart_usec
;
324 if (n_restarts_next
> s
->restart_steps
)
325 return s
->restart_max_delay_usec
;
327 /* Enforced in service_verify() and above */
328 assert(s
->restart_max_delay_usec
> s
->restart_usec
);
330 /* r_i / r_0 = (r_n / r_0) ^ (i / n)
332 * r_0 : initial restart usec (s->restart_usec),
333 * r_i : i-th restart usec (value),
334 * r_n : maximum restart usec (s->restart_max_delay_usec),
335 * i : index of the next step (n_restarts_next - 1)
336 * n : num maximum steps (s->restart_steps) */
337 return (usec_t
) (s
->restart_usec
* powl((long double) s
->restart_max_delay_usec
/ s
->restart_usec
,
338 (long double) (n_restarts_next
- 1) / s
->restart_steps
));
341 static void service_extend_event_source_timeout(Service
*s
, sd_event_source
*source
, usec_t extended
) {
347 /* Extends the specified event source timer to at least the specified time, unless it is already later
353 r
= sd_event_source_get_time(source
, ¤t
);
356 (void) sd_event_source_get_description(s
->timer_event_source
, &desc
);
357 log_unit_warning_errno(UNIT(s
), r
, "Failed to retrieve timeout time for event source '%s', ignoring: %m", strna(desc
));
361 if (current
>= extended
) /* Current timeout is already longer, ignore this. */
364 r
= sd_event_source_set_time(source
, extended
);
367 (void) sd_event_source_get_description(s
->timer_event_source
, &desc
);
368 log_unit_warning_errno(UNIT(s
), r
, "Failed to set timeout time for event source '%s', ignoring %m", strna(desc
));
372 static void service_extend_timeout(Service
*s
, usec_t extend_timeout_usec
) {
377 if (!timestamp_is_set(extend_timeout_usec
))
380 extended
= usec_add(now(CLOCK_MONOTONIC
), extend_timeout_usec
);
382 service_extend_event_source_timeout(s
, s
->timer_event_source
, extended
);
383 service_extend_event_source_timeout(s
, s
->watchdog_event_source
, extended
);
386 static void service_reset_watchdog(Service
*s
) {
389 dual_timestamp_get(&s
->watchdog_timestamp
);
390 service_start_watchdog(s
);
393 static void service_override_watchdog_timeout(Service
*s
, usec_t watchdog_override_usec
) {
396 s
->watchdog_override_enable
= true;
397 s
->watchdog_override_usec
= watchdog_override_usec
;
398 service_reset_watchdog(s
);
400 log_unit_debug(UNIT(s
), "watchdog_usec="USEC_FMT
, s
->watchdog_usec
);
401 log_unit_debug(UNIT(s
), "watchdog_override_usec="USEC_FMT
, s
->watchdog_override_usec
);
404 static ServiceFDStore
* service_fd_store_unlink(ServiceFDStore
*fs
) {
409 assert(fs
->service
->n_fd_store
> 0);
410 LIST_REMOVE(fd_store
, fs
->service
->fd_store
, fs
);
411 fs
->service
->n_fd_store
--;
414 sd_event_source_disable_unref(fs
->event_source
);
417 asynchronous_close(fs
->fd
);
421 DEFINE_TRIVIAL_CLEANUP_FUNC(ServiceFDStore
*, service_fd_store_unlink
);
423 static void service_release_fd_store(Service
*s
) {
429 log_unit_debug(UNIT(s
), "Releasing all stored fds");
432 service_fd_store_unlink(s
->fd_store
);
434 assert(s
->n_fd_store
== 0);
437 static void service_release_stdio_fd(Service
*s
) {
440 if (s
->stdin_fd
< 0 && s
->stdout_fd
< 0 && s
->stdout_fd
< 0)
443 log_unit_debug(UNIT(s
), "Releasing stdin/stdout/stderr file descriptors.");
445 s
->stdin_fd
= asynchronous_close(s
->stdin_fd
);
446 s
->stdout_fd
= asynchronous_close(s
->stdout_fd
);
447 s
->stderr_fd
= asynchronous_close(s
->stderr_fd
);
449 static void service_done(Unit
*u
) {
450 Service
*s
= SERVICE(u
);
454 open_file_free_many(&s
->open_files
);
456 s
->pid_file
= mfree(s
->pid_file
);
457 s
->status_text
= mfree(s
->status_text
);
459 s
->exec_runtime
= exec_runtime_free(s
->exec_runtime
);
460 exec_command_free_array(s
->exec_command
, _SERVICE_EXEC_COMMAND_MAX
);
461 s
->control_command
= NULL
;
462 s
->main_command
= NULL
;
464 exit_status_set_free(&s
->restart_prevent_status
);
465 exit_status_set_free(&s
->restart_force_status
);
466 exit_status_set_free(&s
->success_status
);
468 /* This will leak a process, but at least no memory or any of our resources */
469 service_unwatch_main_pid(s
);
470 service_unwatch_control_pid(s
);
471 service_unwatch_pid_file(s
);
474 unit_unwatch_bus_name(u
, s
->bus_name
);
475 s
->bus_name
= mfree(s
->bus_name
);
478 s
->bus_name_owner
= mfree(s
->bus_name_owner
);
480 s
->usb_function_descriptors
= mfree(s
->usb_function_descriptors
);
481 s
->usb_function_strings
= mfree(s
->usb_function_strings
);
483 service_stop_watchdog(s
);
485 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
486 s
->exec_fd_event_source
= sd_event_source_disable_unref(s
->exec_fd_event_source
);
488 s
->bus_name_pid_lookup_slot
= sd_bus_slot_unref(s
->bus_name_pid_lookup_slot
);
490 service_release_socket_fd(s
);
491 service_release_stdio_fd(s
);
492 service_release_fd_store(s
);
495 static int on_fd_store_io(sd_event_source
*e
, int fd
, uint32_t revents
, void *userdata
) {
496 ServiceFDStore
*fs
= ASSERT_PTR(userdata
);
500 /* If we get either EPOLLHUP or EPOLLERR, it's time to remove this entry from the fd store */
501 log_unit_debug(UNIT(fs
->service
),
502 "Received %s on stored fd %d (%s), closing.",
503 revents
& EPOLLERR
? "EPOLLERR" : "EPOLLHUP",
504 fs
->fd
, strna(fs
->fdname
));
505 service_fd_store_unlink(fs
);
509 static int service_add_fd_store(Service
*s
, int fd_in
, const char *name
, bool do_poll
) {
510 _cleanup_(service_fd_store_unlinkp
) ServiceFDStore
*fs
= NULL
;
511 _cleanup_(asynchronous_closep
) int fd
= ASSERT_FD(fd_in
);
515 /* fd is always consumed even if the function fails. */
519 if (fstat(fd
, &st
) < 0)
522 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
);
524 if (s
->n_fd_store
>= s
->n_fd_store_max
)
525 /* Our store is full. Use this errno rather than E[NM]FILE to distinguish from the case
526 * where systemd itself hits the file limit. */
527 return log_unit_debug_errno(UNIT(s
), SYNTHETIC_ERRNO(EXFULL
), "Hit fd store limit.");
529 LIST_FOREACH(fd_store
, i
, s
->fd_store
) {
530 r
= same_fd(i
->fd
, fd
);
534 log_unit_debug(UNIT(s
), "Suppressing duplicate fd %i in fd store.", fd
);
535 return 0; /* fd already included */
539 fs
= new(ServiceFDStore
, 1);
543 *fs
= (ServiceFDStore
) {
546 .fdname
= strdup(name
?: "stored"),
553 r
= sd_event_add_io(UNIT(s
)->manager
->event
, &fs
->event_source
, fs
->fd
, 0, on_fd_store_io
, fs
);
554 if (r
< 0 && r
!= -EPERM
) /* EPERM indicates fds that aren't pollable, which is OK */
557 (void) sd_event_source_set_description(fs
->event_source
, "service-fd-store");
561 LIST_PREPEND(fd_store
, s
->fd_store
, fs
);
564 log_unit_debug(UNIT(s
), "Added fd %i (%s) to fd store.", fs
->fd
, fs
->fdname
);
567 return 1; /* fd newly stored */
570 static int service_add_fd_store_set(Service
*s
, FDSet
*fds
, const char *name
, bool do_poll
) {
578 fd
= fdset_steal_first(fds
);
582 r
= service_add_fd_store(s
, fd
, name
, do_poll
);
584 return log_unit_warning_errno(UNIT(s
), r
,
585 "Cannot store more fds than FileDescriptorStoreMax=%u, closing remaining.",
588 return log_unit_error_errno(UNIT(s
), r
, "Failed to add fd to store: %m");
594 static void service_remove_fd_store(Service
*s
, const char *name
) {
598 LIST_FOREACH(fd_store
, fs
, s
->fd_store
) {
599 if (!streq(fs
->fdname
, name
))
602 log_unit_debug(UNIT(s
), "Got explicit request to remove fd %i (%s), closing.", fs
->fd
, name
);
603 service_fd_store_unlink(fs
);
607 static usec_t
service_running_timeout(Service
*s
) {
612 if (s
->runtime_rand_extra_usec
!= 0) {
613 delta
= random_u64_range(s
->runtime_rand_extra_usec
);
614 log_unit_debug(UNIT(s
), "Adding delta of %s sec to timeout", FORMAT_TIMESPAN(delta
, USEC_PER_SEC
));
617 return usec_add(usec_add(UNIT(s
)->active_enter_timestamp
.monotonic
,
618 s
->runtime_max_usec
),
622 static int service_arm_timer(Service
*s
, bool relative
, usec_t usec
) {
627 if (s
->timer_event_source
) {
628 r
= (relative
? sd_event_source_set_time_relative
: sd_event_source_set_time
)(s
->timer_event_source
, usec
);
632 return sd_event_source_set_enabled(s
->timer_event_source
, SD_EVENT_ONESHOT
);
635 if (usec
== USEC_INFINITY
)
638 r
= (relative
? sd_event_add_time_relative
: sd_event_add_time
)(
639 UNIT(s
)->manager
->event
,
640 &s
->timer_event_source
,
643 service_dispatch_timer
, s
);
647 (void) sd_event_source_set_description(s
->timer_event_source
, "service-timer");
652 static int service_verify(Service
*s
) {
654 assert(UNIT(s
)->load_state
== UNIT_LOADED
);
656 for (ServiceExecCommand c
= 0; c
< _SERVICE_EXEC_COMMAND_MAX
; c
++)
657 LIST_FOREACH(command
, command
, s
->exec_command
[c
]) {
658 if (!path_is_absolute(command
->path
) && !filename_is_valid(command
->path
))
659 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
),
660 "Service %s= binary path \"%s\" is neither a valid executable name nor an absolute path. Refusing.",
662 service_exec_command_to_string(c
));
663 if (strv_isempty(command
->argv
))
664 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
),
665 "Service has an empty argv in %s=. Refusing.",
666 service_exec_command_to_string(c
));
669 if (!s
->exec_command
[SERVICE_EXEC_START
] && !s
->exec_command
[SERVICE_EXEC_STOP
] &&
670 UNIT(s
)->success_action
== EMERGENCY_ACTION_NONE
)
671 /* FailureAction= only makes sense if one of the start or stop commands is specified.
672 * SuccessAction= will be executed unconditionally if no commands are specified. Hence,
673 * either a command or SuccessAction= are required. */
675 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Service has no ExecStart=, ExecStop=, or SuccessAction=. Refusing.");
677 if (s
->type
!= SERVICE_ONESHOT
&& !s
->exec_command
[SERVICE_EXEC_START
])
678 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Service has no ExecStart= setting, which is only allowed for Type=oneshot services. Refusing.");
680 if (!s
->remain_after_exit
&& !s
->exec_command
[SERVICE_EXEC_START
] && UNIT(s
)->success_action
== EMERGENCY_ACTION_NONE
)
681 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.");
683 if (s
->type
!= SERVICE_ONESHOT
&& s
->exec_command
[SERVICE_EXEC_START
]->command_next
)
684 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.");
686 if (s
->type
== SERVICE_ONESHOT
&&
687 !IN_SET(s
->restart
, SERVICE_RESTART_NO
, SERVICE_RESTART_ON_FAILURE
, SERVICE_RESTART_ON_ABNORMAL
, SERVICE_RESTART_ON_WATCHDOG
, SERVICE_RESTART_ON_ABORT
))
688 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.");
690 if (s
->type
== SERVICE_ONESHOT
&& !exit_status_set_is_empty(&s
->restart_force_status
))
691 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Service has RestartForceExitStatus= set, which isn't allowed for Type=oneshot services. Refusing.");
693 if (s
->type
== SERVICE_ONESHOT
&& s
->exit_type
== SERVICE_EXIT_CGROUP
)
694 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Service has ExitType=cgroup set, which isn't allowed for Type=oneshot services. Refusing.");
696 if (s
->type
== SERVICE_DBUS
&& !s
->bus_name
)
697 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.");
699 if (s
->exec_context
.pam_name
&& !IN_SET(s
->kill_context
.kill_mode
, KILL_CONTROL_GROUP
, KILL_MIXED
))
700 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.");
702 if (s
->usb_function_descriptors
&& !s
->usb_function_strings
)
703 log_unit_warning(UNIT(s
), "Service has USBFunctionDescriptors= setting, but no USBFunctionStrings=. Ignoring.");
705 if (!s
->usb_function_descriptors
&& s
->usb_function_strings
)
706 log_unit_warning(UNIT(s
), "Service has USBFunctionStrings= setting, but no USBFunctionDescriptors=. Ignoring.");
708 if (s
->runtime_max_usec
!= USEC_INFINITY
&& s
->type
== SERVICE_ONESHOT
)
709 log_unit_warning(UNIT(s
), "RuntimeMaxSec= has no effect in combination with Type=oneshot. Ignoring.");
711 if (s
->runtime_max_usec
== USEC_INFINITY
&& s
->runtime_rand_extra_usec
!= 0)
712 log_unit_warning(UNIT(s
), "Service has RuntimeRandomizedExtraSec= setting, but no RuntimeMaxSec=. Ignoring.");
714 if (s
->exit_type
== SERVICE_EXIT_CGROUP
&& cg_unified() < CGROUP_UNIFIED_SYSTEMD
)
715 log_unit_warning(UNIT(s
), "Service has ExitType=cgroup set, but we are running with legacy cgroups v1, which might not work correctly. Continuing.");
717 if (s
->restart_max_delay_usec
== USEC_INFINITY
&& s
->restart_steps
> 0)
718 log_unit_warning(UNIT(s
), "Service has RestartSteps= but no RestartMaxDelaySec= setting. Ignoring.");
720 if (s
->restart_max_delay_usec
!= USEC_INFINITY
&& s
->restart_steps
== 0)
721 log_unit_warning(UNIT(s
), "Service has RestartMaxDelaySec= but no RestartSteps= setting. Ignoring.");
723 if (s
->restart_max_delay_usec
< s
->restart_usec
) {
724 log_unit_warning(UNIT(s
), "RestartMaxDelaySec= has a value smaller than RestartSec=, resetting RestartSec= to RestartMaxDelaySec=.");
725 s
->restart_usec
= s
->restart_max_delay_usec
;
731 static int service_add_default_dependencies(Service
*s
) {
736 if (!UNIT(s
)->default_dependencies
)
739 /* Add a number of automatic dependencies useful for the
740 * majority of services. */
742 if (MANAGER_IS_SYSTEM(UNIT(s
)->manager
)) {
743 /* First, pull in the really early boot stuff, and
744 * require it, so that we fail if we can't acquire
747 r
= unit_add_two_dependencies_by_name(UNIT(s
), UNIT_AFTER
, UNIT_REQUIRES
, SPECIAL_SYSINIT_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
752 /* In the --user instance there's no sysinit.target,
753 * in that case require basic.target instead. */
755 r
= unit_add_dependency_by_name(UNIT(s
), UNIT_REQUIRES
, SPECIAL_BASIC_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
760 /* Second, if the rest of the base system is in the same
761 * transaction, order us after it, but do not pull it in or
762 * even require it. */
763 r
= unit_add_dependency_by_name(UNIT(s
), UNIT_AFTER
, SPECIAL_BASIC_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
767 /* Third, add us in for normal shutdown. */
768 return unit_add_two_dependencies_by_name(UNIT(s
), UNIT_BEFORE
, UNIT_CONFLICTS
, SPECIAL_SHUTDOWN_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
771 static void service_fix_stdio(Service
*s
) {
774 /* Note that EXEC_INPUT_NULL and EXEC_OUTPUT_INHERIT play a special role here: they are both the
775 * default value that is subject to automatic overriding triggered by other settings and an explicit
776 * choice the user can make. We don't distinguish between these cases currently. */
778 if (s
->exec_context
.std_input
== EXEC_INPUT_NULL
&&
779 s
->exec_context
.stdin_data_size
> 0)
780 s
->exec_context
.std_input
= EXEC_INPUT_DATA
;
782 if (IN_SET(s
->exec_context
.std_input
,
784 EXEC_INPUT_TTY_FORCE
,
787 EXEC_INPUT_NAMED_FD
))
790 /* We assume these listed inputs refer to bidirectional streams, and hence duplicating them from
791 * stdin to stdout/stderr makes sense and hence leaving EXEC_OUTPUT_INHERIT in place makes sense,
792 * too. Outputs such as regular files or sealed data memfds otoh don't really make sense to be
793 * duplicated for both input and output at the same time (since they then would cause a feedback
794 * loop), hence override EXEC_OUTPUT_INHERIT with the default stderr/stdout setting. */
796 if (s
->exec_context
.std_error
== EXEC_OUTPUT_INHERIT
&&
797 s
->exec_context
.std_output
== EXEC_OUTPUT_INHERIT
)
798 s
->exec_context
.std_error
= UNIT(s
)->manager
->defaults
.std_error
;
800 if (s
->exec_context
.std_output
== EXEC_OUTPUT_INHERIT
)
801 s
->exec_context
.std_output
= UNIT(s
)->manager
->defaults
.std_output
;
804 static int service_setup_bus_name(Service
*s
) {
809 /* If s->bus_name is not set, then the unit will be refused by service_verify() later. */
813 if (s
->type
== SERVICE_DBUS
) {
814 r
= unit_add_dependency_by_name(UNIT(s
), UNIT_REQUIRES
, SPECIAL_DBUS_SOCKET
, true, UNIT_DEPENDENCY_FILE
);
816 return log_unit_error_errno(UNIT(s
), r
, "Failed to add dependency on " SPECIAL_DBUS_SOCKET
": %m");
818 /* We always want to be ordered against dbus.socket if both are in the transaction. */
819 r
= unit_add_dependency_by_name(UNIT(s
), UNIT_AFTER
, SPECIAL_DBUS_SOCKET
, true, UNIT_DEPENDENCY_FILE
);
821 return log_unit_error_errno(UNIT(s
), r
, "Failed to add dependency on " SPECIAL_DBUS_SOCKET
": %m");
824 r
= unit_watch_bus_name(UNIT(s
), s
->bus_name
);
826 return log_unit_error_errno(UNIT(s
), r
, "Two services allocated for the same bus name %s, refusing operation.", s
->bus_name
);
828 return log_unit_error_errno(UNIT(s
), r
, "Cannot watch bus name %s: %m", s
->bus_name
);
833 static int service_add_extras(Service
*s
) {
838 if (s
->type
== _SERVICE_TYPE_INVALID
) {
839 /* Figure out a type automatically */
841 s
->type
= SERVICE_DBUS
;
842 else if (s
->exec_command
[SERVICE_EXEC_START
])
843 s
->type
= SERVICE_SIMPLE
;
845 s
->type
= SERVICE_ONESHOT
;
848 /* Oneshot services have disabled start timeout by default */
849 if (s
->type
== SERVICE_ONESHOT
&& !s
->start_timeout_defined
)
850 s
->timeout_start_usec
= USEC_INFINITY
;
852 service_fix_stdio(s
);
854 r
= unit_patch_contexts(UNIT(s
));
858 r
= unit_add_exec_dependencies(UNIT(s
), &s
->exec_context
);
862 r
= unit_set_default_slice(UNIT(s
));
866 /* If the service needs the notify socket, let's enable it automatically. */
867 if (s
->notify_access
== NOTIFY_NONE
&&
868 (IN_SET(s
->type
, SERVICE_NOTIFY
, SERVICE_NOTIFY_RELOAD
) || s
->watchdog_usec
> 0 || s
->n_fd_store_max
> 0))
869 s
->notify_access
= NOTIFY_MAIN
;
871 /* If no OOM policy was explicitly set, then default to the configure default OOM policy. Except when
872 * delegation is on, in that case it we assume the payload knows better what to do and can process
873 * things in a more focused way. */
874 if (s
->oom_policy
< 0)
875 s
->oom_policy
= s
->cgroup_context
.delegate
? OOM_CONTINUE
: UNIT(s
)->manager
->defaults
.oom_policy
;
877 /* Let the kernel do the killing if that's requested. */
878 s
->cgroup_context
.memory_oom_group
= s
->oom_policy
== OOM_KILL
;
880 r
= service_add_default_dependencies(s
);
884 r
= service_setup_bus_name(s
);
891 static int service_load(Unit
*u
) {
892 Service
*s
= SERVICE(u
);
895 r
= unit_load_fragment_and_dropin(u
, true);
899 if (u
->load_state
!= UNIT_LOADED
)
902 /* This is a new unit? Then let's add in some extras */
903 r
= service_add_extras(s
);
907 return service_verify(s
);
910 static void service_dump_fdstore(Service
*s
, FILE *f
, const char *prefix
) {
915 LIST_FOREACH(fd_store
, i
, s
->fd_store
) {
916 _cleanup_free_
char *path
= NULL
;
920 if (fstat(i
->fd
, &st
) < 0) {
921 log_debug_errno(errno
, "Failed to stat fdstore entry: %m");
925 flags
= fcntl(i
->fd
, F_GETFL
);
927 log_debug_errno(errno
, "Failed to get fdstore entry flags: %m");
931 (void) fd_get_path(i
->fd
, &path
);
934 "%s%s '%s' (type=%s; dev=" DEVNUM_FORMAT_STR
"; inode=%" PRIu64
"; rdev=" DEVNUM_FORMAT_STR
"; path=%s; access=%s)\n",
935 prefix
, i
== s
->fd_store
? "File Descriptor Store Entry:" : " ",
937 inode_type_to_string(st
.st_mode
),
938 DEVNUM_FORMAT_VAL(st
.st_dev
),
939 (uint64_t) st
.st_ino
,
940 DEVNUM_FORMAT_VAL(st
.st_rdev
),
942 accmode_to_string(flags
));
946 static void service_dump(Unit
*u
, FILE *f
, const char *prefix
) {
947 Service
*s
= SERVICE(u
);
952 prefix
= strempty(prefix
);
953 prefix2
= strjoina(prefix
, "\t");
956 "%sService State: %s\n"
958 "%sReload Result: %s\n"
959 "%sClean Result: %s\n"
960 "%sPermissionsStartOnly: %s\n"
961 "%sRootDirectoryStartOnly: %s\n"
962 "%sRemainAfterExit: %s\n"
963 "%sGuessMainPID: %s\n"
966 "%sNotifyAccess: %s\n"
967 "%sNotifyState: %s\n"
969 "%sReloadSignal: %s\n",
970 prefix
, service_state_to_string(s
->state
),
971 prefix
, service_result_to_string(s
->result
),
972 prefix
, service_result_to_string(s
->reload_result
),
973 prefix
, service_result_to_string(s
->clean_result
),
974 prefix
, yes_no(s
->permissions_start_only
),
975 prefix
, yes_no(s
->root_directory_start_only
),
976 prefix
, yes_no(s
->remain_after_exit
),
977 prefix
, yes_no(s
->guess_main_pid
),
978 prefix
, service_type_to_string(s
->type
),
979 prefix
, service_restart_to_string(s
->restart
),
980 prefix
, notify_access_to_string(service_get_notify_access(s
)),
981 prefix
, notify_state_to_string(s
->notify_state
),
982 prefix
, oom_policy_to_string(s
->oom_policy
),
983 prefix
, signal_to_string(s
->reload_signal
));
985 if (pidref_is_set(&s
->control_pid
))
987 "%sControl PID: "PID_FMT
"\n",
988 prefix
, s
->control_pid
.pid
);
990 if (pidref_is_set(&s
->main_pid
))
992 "%sMain PID: "PID_FMT
"\n"
993 "%sMain PID Known: %s\n"
994 "%sMain PID Alien: %s\n",
995 prefix
, s
->main_pid
.pid
,
996 prefix
, yes_no(s
->main_pid_known
),
997 prefix
, yes_no(s
->main_pid_alien
));
1002 prefix
, s
->pid_file
);
1007 "%sBus Name Good: %s\n",
1008 prefix
, s
->bus_name
,
1009 prefix
, yes_no(s
->bus_name_good
));
1011 if (UNIT_ISSET(s
->accept_socket
))
1013 "%sAccept Socket: %s\n",
1014 prefix
, UNIT_DEREF(s
->accept_socket
)->id
);
1017 "%sRestartSec: %s\n"
1018 "%sRestartSteps: %u\n"
1019 "%sRestartMaxDelaySec: %s\n"
1020 "%sTimeoutStartSec: %s\n"
1021 "%sTimeoutStopSec: %s\n"
1022 "%sTimeoutStartFailureMode: %s\n"
1023 "%sTimeoutStopFailureMode: %s\n",
1024 prefix
, FORMAT_TIMESPAN(s
->restart_usec
, USEC_PER_SEC
),
1025 prefix
, s
->restart_steps
,
1026 prefix
, FORMAT_TIMESPAN(s
->restart_max_delay_usec
, USEC_PER_SEC
),
1027 prefix
, FORMAT_TIMESPAN(s
->timeout_start_usec
, USEC_PER_SEC
),
1028 prefix
, FORMAT_TIMESPAN(s
->timeout_stop_usec
, USEC_PER_SEC
),
1029 prefix
, service_timeout_failure_mode_to_string(s
->timeout_start_failure_mode
),
1030 prefix
, service_timeout_failure_mode_to_string(s
->timeout_stop_failure_mode
));
1032 if (s
->timeout_abort_set
)
1034 "%sTimeoutAbortSec: %s\n",
1035 prefix
, FORMAT_TIMESPAN(s
->timeout_abort_usec
, USEC_PER_SEC
));
1038 "%sRuntimeMaxSec: %s\n"
1039 "%sRuntimeRandomizedExtraSec: %s\n"
1040 "%sWatchdogSec: %s\n",
1041 prefix
, FORMAT_TIMESPAN(s
->runtime_max_usec
, USEC_PER_SEC
),
1042 prefix
, FORMAT_TIMESPAN(s
->runtime_rand_extra_usec
, USEC_PER_SEC
),
1043 prefix
, FORMAT_TIMESPAN(s
->watchdog_usec
, USEC_PER_SEC
));
1045 kill_context_dump(&s
->kill_context
, f
, prefix
);
1046 exec_context_dump(&s
->exec_context
, f
, prefix
);
1048 for (ServiceExecCommand c
= 0; c
< _SERVICE_EXEC_COMMAND_MAX
; c
++) {
1049 if (!s
->exec_command
[c
])
1052 fprintf(f
, "%s-> %s:\n",
1053 prefix
, service_exec_command_to_string(c
));
1055 exec_command_dump_list(s
->exec_command
[c
], f
, prefix2
);
1059 fprintf(f
, "%sStatus Text: %s\n",
1060 prefix
, s
->status_text
);
1062 if (s
->n_fd_store_max
> 0)
1064 "%sFile Descriptor Store Max: %u\n"
1065 "%sFile Descriptor Store Pin: %s\n"
1066 "%sFile Descriptor Store Current: %zu\n",
1067 prefix
, s
->n_fd_store_max
,
1068 prefix
, exec_preserve_mode_to_string(s
->fd_store_preserve_mode
),
1069 prefix
, s
->n_fd_store
);
1071 service_dump_fdstore(s
, f
, prefix
);
1074 LIST_FOREACH(open_files
, of
, s
->open_files
) {
1075 _cleanup_free_
char *ofs
= NULL
;
1078 r
= open_file_to_string(of
, &ofs
);
1081 "Failed to convert OpenFile= setting to string, ignoring: %m");
1085 fprintf(f
, "%sOpen File: %s\n", prefix
, ofs
);
1088 cgroup_context_dump(UNIT(s
), f
, prefix
);
1091 static int service_is_suitable_main_pid(Service
*s
, pid_t pid
, int prio
) {
1095 assert(pid_is_valid(pid
));
1097 /* Checks whether the specified PID is suitable as main PID for this service. returns negative if not, 0 if the
1098 * PID is questionnable but should be accepted if the source of configuration is trusted. > 0 if the PID is
1101 if (pid
== getpid_cached() || pid
== 1)
1102 return log_unit_full_errno(UNIT(s
), prio
, SYNTHETIC_ERRNO(EPERM
), "New main PID "PID_FMT
" is the manager, refusing.", pid
);
1104 if (pid
== s
->control_pid
.pid
)
1105 return log_unit_full_errno(UNIT(s
), prio
, SYNTHETIC_ERRNO(EPERM
), "New main PID "PID_FMT
" is the control process, refusing.", pid
);
1107 if (!pid_is_alive(pid
))
1108 return log_unit_full_errno(UNIT(s
), prio
, SYNTHETIC_ERRNO(ESRCH
), "New main PID "PID_FMT
" does not exist or is a zombie.", pid
);
1110 owner
= manager_get_unit_by_pid(UNIT(s
)->manager
, pid
);
1111 if (owner
== UNIT(s
)) {
1112 log_unit_debug(UNIT(s
), "New main PID "PID_FMT
" belongs to service, we are happy.", pid
);
1113 return 1; /* Yay, it's definitely a good PID */
1116 return 0; /* Hmm it's a suspicious PID, let's accept it if configuration source is trusted */
1119 static int service_load_pid_file(Service
*s
, bool may_warn
) {
1120 _cleanup_(pidref_done
) PidRef pidref
= PIDREF_NULL
;
1121 bool questionable_pid_file
= false;
1122 _cleanup_free_
char *k
= NULL
;
1123 _cleanup_close_
int fd
= -EBADF
;
1132 prio
= may_warn
? LOG_INFO
: LOG_DEBUG
;
1134 r
= chase(s
->pid_file
, NULL
, CHASE_SAFE
, NULL
, &fd
);
1135 if (r
== -ENOLINK
) {
1136 log_unit_debug_errno(UNIT(s
), r
,
1137 "Potentially unsafe symlink chain, will now retry with relaxed checks: %s", s
->pid_file
);
1139 questionable_pid_file
= true;
1141 r
= chase(s
->pid_file
, NULL
, 0, NULL
, &fd
);
1144 return log_unit_full_errno(UNIT(s
), prio
, r
,
1145 "Can't open PID file %s (yet?) after %s: %m", s
->pid_file
, service_state_to_string(s
->state
));
1147 /* Let's read the PID file now that we chased it down. But we need to convert the O_PATH fd
1148 * chase() returned us into a proper fd first. */
1149 r
= read_one_line_file(FORMAT_PROC_FD_PATH(fd
), &k
);
1151 return log_unit_error_errno(UNIT(s
), r
,
1152 "Can't convert PID files %s O_PATH file descriptor to proper file descriptor: %m",
1155 r
= parse_pid(k
, &pid
);
1157 return log_unit_full_errno(UNIT(s
), prio
, r
, "Failed to parse PID from file %s: %m", s
->pid_file
);
1159 if (s
->main_pid_known
&& pid
== s
->main_pid
.pid
)
1162 r
= pidref_set_pid(&pidref
, pid
);
1164 return log_unit_full_errno(UNIT(s
), prio
, r
, "Failed to pin PID " PID_FMT
": %m", pid
);
1166 r
= service_is_suitable_main_pid(s
, pidref
.pid
, prio
);
1172 if (questionable_pid_file
)
1173 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(EPERM
),
1174 "Refusing to accept PID outside of service control group, acquired through unsafe symlink chain: %s", s
->pid_file
);
1176 /* Hmm, it's not clear if the new main PID is safe. Let's allow this if the PID file is owned by root */
1178 if (fstat(fd
, &st
) < 0)
1179 return log_unit_error_errno(UNIT(s
), errno
, "Failed to fstat() PID file O_PATH fd: %m");
1182 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(EPERM
),
1183 "New main PID "PID_FMT
" does not belong to service, and PID file is not owned by root. Refusing.", pidref
.pid
);
1185 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
);
1188 if (s
->main_pid_known
) {
1189 log_unit_debug(UNIT(s
), "Main PID changing: "PID_FMT
" -> "PID_FMT
, s
->main_pid
.pid
, pidref
.pid
);
1191 service_unwatch_main_pid(s
);
1192 s
->main_pid_known
= false;
1194 log_unit_debug(UNIT(s
), "Main PID loaded: "PID_FMT
, pidref
.pid
);
1196 r
= service_set_main_pidref(s
, &pidref
);
1200 r
= unit_watch_pid(UNIT(s
), s
->main_pid
.pid
, /* exclusive= */ false);
1201 if (r
< 0) /* FIXME: we need to do something here */
1202 return log_unit_warning_errno(UNIT(s
), r
, "Failed to watch PID "PID_FMT
" for service: %m", s
->main_pid
.pid
);
1207 static void service_search_main_pid(Service
*s
) {
1213 /* If we know it anyway, don't ever fall back to unreliable heuristics */
1214 if (s
->main_pid_known
)
1217 if (!s
->guess_main_pid
)
1220 assert(!pidref_is_set(&s
->main_pid
));
1222 if (unit_search_main_pid(UNIT(s
), &pid
) < 0)
1225 log_unit_debug(UNIT(s
), "Main PID guessed: "PID_FMT
, pid
);
1226 if (service_set_main_pid(s
, pid
) < 0)
1229 r
= unit_watch_pid(UNIT(s
), s
->main_pid
.pid
, /* exclusive= */ false);
1231 /* FIXME: we need to do something here */
1232 log_unit_warning_errno(UNIT(s
), r
, "Failed to watch PID "PID_FMT
" from: %m", s
->main_pid
.pid
);
1235 static void service_set_state(Service
*s
, ServiceState state
) {
1236 ServiceState old_state
;
1237 const UnitActiveState
*table
;
1241 if (s
->state
!= state
)
1242 bus_unit_send_pending_change_signal(UNIT(s
), false);
1244 table
= s
->type
== SERVICE_IDLE
? state_translation_table_idle
: state_translation_table
;
1246 old_state
= s
->state
;
1249 service_unwatch_pid_file(s
);
1252 SERVICE_CONDITION
, SERVICE_START_PRE
, SERVICE_START
, SERVICE_START_POST
,
1254 SERVICE_RELOAD
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
,
1255 SERVICE_STOP
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
, SERVICE_STOP_POST
,
1256 SERVICE_FINAL_WATCHDOG
, SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
,
1257 SERVICE_AUTO_RESTART
,
1259 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
1262 SERVICE_START
, SERVICE_START_POST
,
1264 SERVICE_RELOAD
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
,
1265 SERVICE_STOP
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
, SERVICE_STOP_POST
,
1266 SERVICE_FINAL_WATCHDOG
, SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
)) {
1267 service_unwatch_main_pid(s
);
1268 s
->main_command
= NULL
;
1272 SERVICE_CONDITION
, SERVICE_START_PRE
, SERVICE_START
, SERVICE_START_POST
,
1273 SERVICE_RELOAD
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
,
1274 SERVICE_STOP
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
, SERVICE_STOP_POST
,
1275 SERVICE_FINAL_WATCHDOG
, SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
,
1276 SERVICE_CLEANING
)) {
1277 service_unwatch_control_pid(s
);
1278 s
->control_command
= NULL
;
1279 s
->control_command_id
= _SERVICE_EXEC_COMMAND_INVALID
;
1283 SERVICE_DEAD
, SERVICE_FAILED
,
1284 SERVICE_DEAD_BEFORE_AUTO_RESTART
, SERVICE_FAILED_BEFORE_AUTO_RESTART
, SERVICE_AUTO_RESTART
, SERVICE_AUTO_RESTART_QUEUED
,
1285 SERVICE_DEAD_RESOURCES_PINNED
)) {
1286 unit_unwatch_all_pids(UNIT(s
));
1287 unit_dequeue_rewatch_pids(UNIT(s
));
1290 if (state
!= SERVICE_START
)
1291 s
->exec_fd_event_source
= sd_event_source_disable_unref(s
->exec_fd_event_source
);
1293 if (!IN_SET(state
, SERVICE_START_POST
, SERVICE_RUNNING
, SERVICE_RELOAD
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
))
1294 service_stop_watchdog(s
);
1296 /* For the inactive states unit_notify() will trim the cgroup,
1297 * but for exit we have to do that ourselves... */
1298 if (state
== SERVICE_EXITED
&& !MANAGER_IS_RELOADING(UNIT(s
)->manager
))
1299 unit_prune_cgroup(UNIT(s
));
1301 if (old_state
!= state
)
1302 log_unit_debug(UNIT(s
), "Changed %s -> %s", service_state_to_string(old_state
), service_state_to_string(state
));
1304 unit_notify(UNIT(s
), table
[old_state
], table
[state
], s
->reload_result
== SERVICE_SUCCESS
);
1307 static usec_t
service_coldplug_timeout(Service
*s
) {
1310 switch (s
->deserialized_state
) {
1312 case SERVICE_CONDITION
:
1313 case SERVICE_START_PRE
:
1315 case SERVICE_START_POST
:
1316 case SERVICE_RELOAD
:
1317 case SERVICE_RELOAD_SIGNAL
:
1318 case SERVICE_RELOAD_NOTIFY
:
1319 return usec_add(UNIT(s
)->state_change_timestamp
.monotonic
, s
->timeout_start_usec
);
1321 case SERVICE_RUNNING
:
1322 return service_running_timeout(s
);
1325 case SERVICE_STOP_SIGTERM
:
1326 case SERVICE_STOP_SIGKILL
:
1327 case SERVICE_STOP_POST
:
1328 case SERVICE_FINAL_SIGTERM
:
1329 case SERVICE_FINAL_SIGKILL
:
1330 return usec_add(UNIT(s
)->state_change_timestamp
.monotonic
, s
->timeout_stop_usec
);
1332 case SERVICE_STOP_WATCHDOG
:
1333 case SERVICE_FINAL_WATCHDOG
:
1334 return usec_add(UNIT(s
)->state_change_timestamp
.monotonic
, service_timeout_abort_usec(s
));
1336 case SERVICE_AUTO_RESTART
:
1337 return usec_add(UNIT(s
)->inactive_enter_timestamp
.monotonic
, service_restart_usec_next(s
));
1339 case SERVICE_CLEANING
:
1340 return usec_add(UNIT(s
)->state_change_timestamp
.monotonic
, s
->exec_context
.timeout_clean_usec
);
1343 return USEC_INFINITY
;
1347 static int service_coldplug(Unit
*u
) {
1348 Service
*s
= SERVICE(u
);
1352 assert(s
->state
== SERVICE_DEAD
);
1354 if (s
->deserialized_state
== s
->state
)
1357 r
= service_arm_timer(s
, /* relative= */ false, service_coldplug_timeout(s
));
1361 if (pidref_is_set(&s
->main_pid
) &&
1362 pid_is_unwaited(s
->main_pid
.pid
) &&
1363 (IN_SET(s
->deserialized_state
,
1364 SERVICE_START
, SERVICE_START_POST
,
1366 SERVICE_RELOAD
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
,
1367 SERVICE_STOP
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
, SERVICE_STOP_POST
,
1368 SERVICE_FINAL_WATCHDOG
, SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
))) {
1369 r
= unit_watch_pid(UNIT(s
), s
->main_pid
.pid
, /* exclusive= */ false);
1374 if (pidref_is_set(&s
->control_pid
) &&
1375 pid_is_unwaited(s
->control_pid
.pid
) &&
1376 IN_SET(s
->deserialized_state
,
1377 SERVICE_CONDITION
, SERVICE_START_PRE
, SERVICE_START
, SERVICE_START_POST
,
1378 SERVICE_RELOAD
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
,
1379 SERVICE_STOP
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
, SERVICE_STOP_POST
,
1380 SERVICE_FINAL_WATCHDOG
, SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
,
1381 SERVICE_CLEANING
)) {
1382 r
= unit_watch_pid(UNIT(s
), s
->control_pid
.pid
, /* exclusive= */ false);
1387 if (!IN_SET(s
->deserialized_state
,
1388 SERVICE_DEAD
, SERVICE_FAILED
,
1389 SERVICE_DEAD_BEFORE_AUTO_RESTART
, SERVICE_FAILED_BEFORE_AUTO_RESTART
, SERVICE_AUTO_RESTART
, SERVICE_AUTO_RESTART_QUEUED
,
1391 SERVICE_DEAD_RESOURCES_PINNED
)) {
1392 (void) unit_enqueue_rewatch_pids(u
);
1393 (void) unit_setup_exec_runtime(u
);
1396 if (IN_SET(s
->deserialized_state
, SERVICE_START_POST
, SERVICE_RUNNING
, SERVICE_RELOAD
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
))
1397 service_start_watchdog(s
);
1399 if (UNIT_ISSET(s
->accept_socket
)) {
1400 Socket
* socket
= SOCKET(UNIT_DEREF(s
->accept_socket
));
1402 if (socket
->max_connections_per_source
> 0) {
1405 /* Make a best-effort attempt at bumping the connection count */
1406 if (socket_acquire_peer(socket
, s
->socket_fd
, &peer
) > 0) {
1407 socket_peer_unref(s
->socket_peer
);
1408 s
->socket_peer
= peer
;
1413 service_set_state(s
, s
->deserialized_state
);
1417 static int service_collect_fds(
1421 size_t *n_socket_fds
,
1422 size_t *n_storage_fds
) {
1424 _cleanup_strv_free_
char **rfd_names
= NULL
;
1425 _cleanup_free_
int *rfds
= NULL
;
1426 size_t rn_socket_fds
= 0, rn_storage_fds
= 0;
1432 assert(n_socket_fds
);
1433 assert(n_storage_fds
);
1435 if (s
->socket_fd
>= 0) {
1437 /* Pass the per-connection socket */
1439 rfds
= newdup(int, &s
->socket_fd
, 1);
1443 rfd_names
= strv_new("connection");
1451 /* Pass all our configured sockets for singleton services */
1453 UNIT_FOREACH_DEPENDENCY(u
, UNIT(s
), UNIT_ATOM_TRIGGERED_BY
) {
1454 _cleanup_free_
int *cfds
= NULL
;
1458 if (u
->type
!= UNIT_SOCKET
)
1463 cn_fds
= socket_collect_fds(sock
, &cfds
);
1471 rfds
= TAKE_PTR(cfds
);
1472 rn_socket_fds
= cn_fds
;
1476 t
= reallocarray(rfds
, rn_socket_fds
+ cn_fds
, sizeof(int));
1480 memcpy(t
+ rn_socket_fds
, cfds
, cn_fds
* sizeof(int));
1483 rn_socket_fds
+= cn_fds
;
1486 r
= strv_extend_n(&rfd_names
, socket_fdname(sock
), cn_fds
);
1492 if (s
->n_fd_store
> 0) {
1497 t
= reallocarray(rfds
, rn_socket_fds
+ s
->n_fd_store
, sizeof(int));
1503 nl
= reallocarray(rfd_names
, rn_socket_fds
+ s
->n_fd_store
+ 1, sizeof(char *));
1508 n_fds
= rn_socket_fds
;
1510 LIST_FOREACH(fd_store
, fs
, s
->fd_store
) {
1511 rfds
[n_fds
] = fs
->fd
;
1512 rfd_names
[n_fds
] = strdup(strempty(fs
->fdname
));
1513 if (!rfd_names
[n_fds
])
1520 rfd_names
[n_fds
] = NULL
;
1523 *fds
= TAKE_PTR(rfds
);
1524 *fd_names
= TAKE_PTR(rfd_names
);
1525 *n_socket_fds
= rn_socket_fds
;
1526 *n_storage_fds
= rn_storage_fds
;
1531 static int service_allocate_exec_fd_event_source(
1534 sd_event_source
**ret_event_source
) {
1536 _cleanup_(sd_event_source_unrefp
) sd_event_source
*source
= NULL
;
1541 assert(ret_event_source
);
1543 r
= sd_event_add_io(UNIT(s
)->manager
->event
, &source
, fd
, 0, service_dispatch_exec_io
, s
);
1545 return log_unit_error_errno(UNIT(s
), r
, "Failed to allocate exec_fd event source: %m");
1547 /* This is a bit lower priority than SIGCHLD, as that carries a lot more interesting failure information */
1549 r
= sd_event_source_set_priority(source
, SD_EVENT_PRIORITY_NORMAL
-3);
1551 return log_unit_error_errno(UNIT(s
), r
, "Failed to adjust priority of exec_fd event source: %m");
1553 (void) sd_event_source_set_description(source
, "service exec_fd");
1555 r
= sd_event_source_set_io_fd_own(source
, true);
1557 return log_unit_error_errno(UNIT(s
), r
, "Failed to pass ownership of fd to event source: %m");
1559 *ret_event_source
= TAKE_PTR(source
);
1563 static int service_allocate_exec_fd(
1565 sd_event_source
**ret_event_source
,
1568 _cleanup_close_pair_
int p
[] = PIPE_EBADF
;
1572 assert(ret_event_source
);
1573 assert(ret_exec_fd
);
1575 if (pipe2(p
, O_CLOEXEC
|O_NONBLOCK
) < 0)
1576 return log_unit_error_errno(UNIT(s
), errno
, "Failed to allocate exec_fd pipe: %m");
1578 r
= service_allocate_exec_fd_event_source(s
, p
[0], ret_event_source
);
1583 *ret_exec_fd
= TAKE_FD(p
[1]);
1588 static bool service_exec_needs_notify_socket(Service
*s
, ExecFlags flags
) {
1591 /* Notifications are accepted depending on the process and
1592 * the access setting of the service:
1593 * process: \ access: NONE MAIN EXEC ALL
1594 * main no yes yes yes
1595 * control no no yes yes
1596 * other (forked) no no no yes */
1598 if (flags
& EXEC_IS_CONTROL
)
1599 /* A control process */
1600 return IN_SET(service_get_notify_access(s
), NOTIFY_EXEC
, NOTIFY_ALL
);
1602 /* We only spawn main processes and control processes, so any
1603 * process that is not a control process is a main process */
1604 return service_get_notify_access(s
) != NOTIFY_NONE
;
1607 static Service
*service_get_triggering_service(Service
*s
) {
1608 Unit
*candidate
= NULL
, *other
;
1612 /* Return the service which triggered service 's', this means dependency
1613 * types which include the UNIT_ATOM_ON_{FAILURE,SUCCESS}_OF atoms.
1615 * N.B. if there are multiple services which could trigger 's' via OnFailure=
1616 * or OnSuccess= then we return NULL. This is since we don't know from which
1617 * one to propagate the exit status. */
1619 UNIT_FOREACH_DEPENDENCY(other
, UNIT(s
), UNIT_ATOM_ON_FAILURE_OF
) {
1625 UNIT_FOREACH_DEPENDENCY(other
, UNIT(s
), UNIT_ATOM_ON_SUCCESS_OF
) {
1631 return SERVICE(candidate
);
1634 log_unit_warning(UNIT(s
), "multiple trigger source candidates for exit status propagation (%s, %s), skipping.",
1635 candidate
->id
, other
->id
);
1639 static int service_spawn_internal(
1647 _cleanup_(exec_params_clear
) ExecParameters exec_params
= {
1650 .stdout_fd
= -EBADF
,
1651 .stderr_fd
= -EBADF
,
1654 _cleanup_(sd_event_source_unrefp
) sd_event_source
*exec_fd_source
= NULL
;
1655 _cleanup_strv_free_
char **final_env
= NULL
, **our_env
= NULL
;
1656 _cleanup_(pidref_done
) PidRef pidref
= PIDREF_NULL
;
1666 log_unit_debug(UNIT(s
), "Will spawn child (%s): %s", caller
, c
->path
);
1668 r
= unit_prepare_exec(UNIT(s
)); /* This realizes the cgroup, among other things */
1672 assert(!s
->exec_fd_event_source
);
1674 if (flags
& EXEC_IS_CONTROL
) {
1675 /* If this is a control process, mask the permissions/chroot application if this is requested. */
1676 if (s
->permissions_start_only
)
1677 exec_params
.flags
&= ~EXEC_APPLY_SANDBOXING
;
1678 if (s
->root_directory_start_only
)
1679 exec_params
.flags
&= ~EXEC_APPLY_CHROOT
;
1682 if ((flags
& EXEC_PASS_FDS
) ||
1683 s
->exec_context
.std_input
== EXEC_INPUT_SOCKET
||
1684 s
->exec_context
.std_output
== EXEC_OUTPUT_SOCKET
||
1685 s
->exec_context
.std_error
== EXEC_OUTPUT_SOCKET
) {
1687 r
= service_collect_fds(s
,
1689 &exec_params
.fd_names
,
1690 &exec_params
.n_socket_fds
,
1691 &exec_params
.n_storage_fds
);
1695 exec_params
.open_files
= s
->open_files
;
1697 log_unit_debug(UNIT(s
), "Passing %zu fds to service", exec_params
.n_socket_fds
+ exec_params
.n_storage_fds
);
1700 if (!FLAGS_SET(flags
, EXEC_IS_CONTROL
) && s
->type
== SERVICE_EXEC
) {
1701 r
= service_allocate_exec_fd(s
, &exec_fd_source
, &exec_params
.exec_fd
);
1706 r
= service_arm_timer(s
, /* relative= */ true, timeout
);
1710 our_env
= new0(char*, 13);
1714 if (service_exec_needs_notify_socket(s
, flags
)) {
1715 if (asprintf(our_env
+ n_env
++, "NOTIFY_SOCKET=%s", UNIT(s
)->manager
->notify_socket
) < 0)
1718 exec_params
.notify_socket
= UNIT(s
)->manager
->notify_socket
;
1720 if (s
->n_fd_store_max
> 0)
1721 if (asprintf(our_env
+ n_env
++, "FDSTORE=%u", s
->n_fd_store_max
) < 0)
1725 if (pidref_is_set(&s
->main_pid
))
1726 if (asprintf(our_env
+ n_env
++, "MAINPID="PID_FMT
, s
->main_pid
.pid
) < 0)
1729 if (MANAGER_IS_USER(UNIT(s
)->manager
))
1730 if (asprintf(our_env
+ n_env
++, "MANAGERPID="PID_FMT
, getpid_cached()) < 0)
1734 if (asprintf(our_env
+ n_env
++, "PIDFILE=%s", s
->pid_file
) < 0)
1737 if (s
->socket_fd
>= 0) {
1738 union sockaddr_union sa
;
1739 socklen_t salen
= sizeof(sa
);
1741 /* If this is a per-connection service instance, let's set $REMOTE_ADDR and $REMOTE_PORT to something
1742 * useful. Note that we do this only when we are still connected at this point in time, which we might
1743 * very well not be. Hence we ignore all errors when retrieving peer information (as that might result
1744 * in ENOTCONN), and just use whate we can use. */
1746 if (getpeername(s
->socket_fd
, &sa
.sa
, &salen
) >= 0 &&
1747 IN_SET(sa
.sa
.sa_family
, AF_INET
, AF_INET6
, AF_VSOCK
)) {
1748 _cleanup_free_
char *addr
= NULL
;
1752 r
= sockaddr_pretty(&sa
.sa
, salen
, true, false, &addr
);
1756 t
= strjoin("REMOTE_ADDR=", addr
);
1759 our_env
[n_env
++] = t
;
1761 r
= sockaddr_port(&sa
.sa
, &port
);
1765 if (asprintf(&t
, "REMOTE_PORT=%u", port
) < 0)
1767 our_env
[n_env
++] = t
;
1771 Service
*env_source
= NULL
;
1772 const char *monitor_prefix
;
1773 if (flags
& EXEC_SETENV_RESULT
) {
1775 monitor_prefix
= "";
1776 } else if (flags
& EXEC_SETENV_MONITOR_RESULT
) {
1777 env_source
= service_get_triggering_service(s
);
1778 monitor_prefix
= "MONITOR_";
1782 if (asprintf(our_env
+ n_env
++, "%sSERVICE_RESULT=%s", monitor_prefix
, service_result_to_string(env_source
->result
)) < 0)
1785 if (env_source
->main_exec_status
.pid
> 0 &&
1786 dual_timestamp_is_set(&env_source
->main_exec_status
.exit_timestamp
)) {
1787 if (asprintf(our_env
+ n_env
++, "%sEXIT_CODE=%s", monitor_prefix
, sigchld_code_to_string(env_source
->main_exec_status
.code
)) < 0)
1790 if (env_source
->main_exec_status
.code
== CLD_EXITED
)
1791 r
= asprintf(our_env
+ n_env
++, "%sEXIT_STATUS=%i", monitor_prefix
, env_source
->main_exec_status
.status
);
1793 r
= asprintf(our_env
+ n_env
++, "%sEXIT_STATUS=%s", monitor_prefix
, signal_to_string(env_source
->main_exec_status
.status
));
1799 if (env_source
!= s
) {
1800 if (!sd_id128_is_null(UNIT(env_source
)->invocation_id
)) {
1801 r
= asprintf(our_env
+ n_env
++, "%sINVOCATION_ID=" SD_ID128_FORMAT_STR
,
1802 monitor_prefix
, SD_ID128_FORMAT_VAL(UNIT(env_source
)->invocation_id
));
1807 if (asprintf(our_env
+ n_env
++, "%sUNIT=%s", monitor_prefix
, UNIT(env_source
)->id
) < 0)
1812 if (UNIT(s
)->activation_details
) {
1813 r
= activation_details_append_env(UNIT(s
)->activation_details
, &our_env
);
1816 /* The number of env vars added here can vary, rather than keeping the allocation block in
1817 * sync manually, these functions simply use the strv methods to append to it, so we need
1818 * to update n_env when we are done in case of future usage. */
1822 r
= unit_set_exec_params(UNIT(s
), &exec_params
);
1826 final_env
= strv_env_merge(exec_params
.environment
, our_env
);
1830 /* System D-Bus needs nss-systemd disabled, so that we don't deadlock */
1831 SET_FLAG(exec_params
.flags
, EXEC_NSS_DYNAMIC_BYPASS
,
1832 MANAGER_IS_SYSTEM(UNIT(s
)->manager
) && unit_has_name(UNIT(s
), SPECIAL_DBUS_SERVICE
));
1834 strv_free_and_replace(exec_params
.environment
, final_env
);
1835 exec_params
.watchdog_usec
= service_get_watchdog_usec(s
);
1836 exec_params
.selinux_context_net
= s
->socket_fd_selinux_context_net
;
1837 if (s
->type
== SERVICE_IDLE
)
1838 exec_params
.idle_pipe
= UNIT(s
)->manager
->idle_pipe
;
1839 exec_params
.stdin_fd
= s
->stdin_fd
;
1840 exec_params
.stdout_fd
= s
->stdout_fd
;
1841 exec_params
.stderr_fd
= s
->stderr_fd
;
1843 r
= exec_spawn(UNIT(s
),
1853 s
->exec_fd_event_source
= TAKE_PTR(exec_fd_source
);
1854 s
->exec_fd_hot
= false;
1856 r
= pidref_set_pid(&pidref
, pid
);
1860 r
= unit_watch_pid(UNIT(s
), pidref
.pid
, /* exclusive= */ true);
1864 *ret_pid
= TAKE_PIDREF(pidref
);
1868 static int main_pid_good(Service
*s
) {
1871 /* Returns 0 if the pid is dead, > 0 if it is good, < 0 if we don't know */
1873 /* If we know the pid file, then let's just check if it is still valid */
1874 if (s
->main_pid_known
) {
1876 /* If it's an alien child let's check if it is still alive ... */
1877 if (s
->main_pid_alien
&& pidref_is_set(&s
->main_pid
))
1878 return pid_is_alive(s
->main_pid
.pid
);
1880 /* .. otherwise assume we'll get a SIGCHLD for it, which we really should wait for to collect
1881 * exit status and code */
1882 return pidref_is_set(&s
->main_pid
);
1885 /* We don't know the pid */
1889 static int control_pid_good(Service
*s
) {
1892 /* Returns 0 if the control PID is dead, > 0 if it is good. We never actually return < 0 here, but in order to
1893 * make this function as similar as possible to main_pid_good() and cgroup_good(), we pretend that < 0 also
1894 * means: we can't figure it out. */
1896 return pidref_is_set(&s
->control_pid
);
1899 static int cgroup_good(Service
*s
) {
1904 /* Returns 0 if the cgroup is empty or doesn't exist, > 0 if it is exists and is populated, < 0 if we can't
1907 if (!UNIT(s
)->cgroup_path
)
1910 r
= cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER
, UNIT(s
)->cgroup_path
);
1917 static bool service_shall_restart(Service
*s
, const char **reason
) {
1920 /* Don't restart after manual stops */
1921 if (s
->forbid_restart
) {
1922 *reason
= "manual stop";
1926 /* Never restart if this is configured as special exception */
1927 if (exit_status_set_test(&s
->restart_prevent_status
, s
->main_exec_status
.code
, s
->main_exec_status
.status
)) {
1928 *reason
= "prevented by exit status";
1932 /* Restart if the exit code/status are configured as restart triggers */
1933 if (exit_status_set_test(&s
->restart_force_status
, s
->main_exec_status
.code
, s
->main_exec_status
.status
)) {
1934 *reason
= "forced by exit status";
1938 *reason
= "restart setting";
1939 switch (s
->restart
) {
1941 case SERVICE_RESTART_NO
:
1944 case SERVICE_RESTART_ALWAYS
:
1945 return s
->result
!= SERVICE_SKIP_CONDITION
;
1947 case SERVICE_RESTART_ON_SUCCESS
:
1948 return s
->result
== SERVICE_SUCCESS
;
1950 case SERVICE_RESTART_ON_FAILURE
:
1951 return !IN_SET(s
->result
, SERVICE_SUCCESS
, SERVICE_SKIP_CONDITION
);
1953 case SERVICE_RESTART_ON_ABNORMAL
:
1954 return !IN_SET(s
->result
, SERVICE_SUCCESS
, SERVICE_FAILURE_EXIT_CODE
, SERVICE_SKIP_CONDITION
);
1956 case SERVICE_RESTART_ON_WATCHDOG
:
1957 return s
->result
== SERVICE_FAILURE_WATCHDOG
;
1959 case SERVICE_RESTART_ON_ABORT
:
1960 return IN_SET(s
->result
, SERVICE_FAILURE_SIGNAL
, SERVICE_FAILURE_CORE_DUMP
);
1963 assert_not_reached();
1967 static bool service_will_restart(Unit
*u
) {
1968 Service
*s
= SERVICE(u
);
1972 if (IN_SET(s
->state
, SERVICE_DEAD_BEFORE_AUTO_RESTART
, SERVICE_FAILED_BEFORE_AUTO_RESTART
, SERVICE_AUTO_RESTART
, SERVICE_AUTO_RESTART_QUEUED
))
1975 return unit_will_restart_default(u
);
1978 static ServiceState
service_determine_dead_state(Service
*s
) {
1981 return s
->fd_store
&& s
->fd_store_preserve_mode
== EXEC_PRESERVE_YES
? SERVICE_DEAD_RESOURCES_PINNED
: SERVICE_DEAD
;
1984 static void service_enter_dead(Service
*s
, ServiceResult f
, bool allow_restart
) {
1985 ServiceState end_state
, restart_state
;
1990 /* If there's a stop job queued before we enter the DEAD state, we shouldn't act on Restart=, in order to not
1991 * undo what has already been enqueued. */
1992 if (unit_stop_pending(UNIT(s
)))
1993 allow_restart
= false;
1995 if (s
->result
== SERVICE_SUCCESS
)
1998 if (s
->result
== SERVICE_SUCCESS
) {
1999 unit_log_success(UNIT(s
));
2000 end_state
= service_determine_dead_state(s
);
2001 restart_state
= SERVICE_DEAD_BEFORE_AUTO_RESTART
;
2002 } else if (s
->result
== SERVICE_SKIP_CONDITION
) {
2003 unit_log_skip(UNIT(s
), service_result_to_string(s
->result
));
2004 end_state
= service_determine_dead_state(s
);
2005 restart_state
= SERVICE_DEAD_BEFORE_AUTO_RESTART
;
2007 unit_log_failure(UNIT(s
), service_result_to_string(s
->result
));
2008 end_state
= SERVICE_FAILED
;
2009 restart_state
= SERVICE_FAILED_BEFORE_AUTO_RESTART
;
2011 unit_warn_leftover_processes(UNIT(s
), unit_log_leftover_process_stop
);
2014 log_unit_debug(UNIT(s
), "Service restart not allowed.");
2018 allow_restart
= service_shall_restart(s
, &reason
);
2019 log_unit_debug(UNIT(s
), "Service will %srestart (%s)",
2020 allow_restart
? "" : "not ",
2024 if (allow_restart
) {
2025 usec_t restart_usec_next
;
2027 /* We make two state changes here: one that maps to the high-level UNIT_INACTIVE/UNIT_FAILED
2028 * state (i.e. a state indicating deactivation), and then one that that maps to the
2029 * high-level UNIT_STARTING state (i.e. a state indicating activation). We do this so that
2030 * external software can watch the state changes and see all service failures, even if they
2031 * are only transitionary and followed by an automatic restart. We have fine-grained
2032 * low-level states for this though so that software can distinguish the permanent UNIT_INACTIVE
2033 * state from this transitionary UNIT_INACTIVE state by looking at the low-level states. */
2034 if (s
->restart_mode
!= SERVICE_RESTART_MODE_DIRECT
)
2035 service_set_state(s
, restart_state
);
2037 restart_usec_next
= service_restart_usec_next(s
);
2039 r
= service_arm_timer(s
, /* relative= */ true, restart_usec_next
);
2041 log_unit_warning_errno(UNIT(s
), r
, "Failed to install restart timer: %m");
2042 service_enter_dead(s
, SERVICE_FAILURE_RESOURCES
, /* allow_restart= */ false);
2046 log_unit_debug(UNIT(s
), "Next restart interval calculated as: %s", FORMAT_TIMESPAN(restart_usec_next
, 0));
2048 service_set_state(s
, SERVICE_AUTO_RESTART
);
2050 service_set_state(s
, end_state
);
2052 /* If we shan't restart, then flush out the restart counter. But don't do that immediately, so that the
2053 * user can still introspect the counter. Do so on the next start. */
2054 s
->flush_n_restarts
= true;
2057 /* The new state is in effect, let's decrease the fd store ref counter again. Let's also re-add us to the GC
2058 * queue, so that the fd store is possibly gc'ed again */
2059 unit_add_to_gc_queue(UNIT(s
));
2061 /* The next restart might not be a manual stop, hence reset the flag indicating manual stops */
2062 s
->forbid_restart
= false;
2064 /* Reset NotifyAccess override */
2065 s
->notify_access_override
= _NOTIFY_ACCESS_INVALID
;
2067 /* We want fresh tmpdirs and ephemeral snapshots in case the service is started again immediately. */
2068 s
->exec_runtime
= exec_runtime_destroy(s
->exec_runtime
);
2070 /* Also, remove the runtime directory */
2071 unit_destroy_runtime_data(UNIT(s
), &s
->exec_context
);
2073 /* Also get rid of the fd store, if that's configured. */
2074 if (s
->fd_store_preserve_mode
== EXEC_PRESERVE_NO
)
2075 service_release_fd_store(s
);
2077 /* Get rid of the IPC bits of the user */
2078 unit_unref_uid_gid(UNIT(s
), true);
2080 /* Try to delete the pid file. At this point it will be
2081 * out-of-date, and some software might be confused by it, so
2082 * let's remove it. */
2084 (void) unlink(s
->pid_file
);
2086 /* Reset TTY ownership if necessary */
2087 exec_context_revert_tty(&s
->exec_context
);
2090 static void service_enter_stop_post(Service
*s
, ServiceResult f
) {
2094 if (s
->result
== SERVICE_SUCCESS
)
2097 service_unwatch_control_pid(s
);
2098 (void) unit_enqueue_rewatch_pids(UNIT(s
));
2100 s
->control_command
= s
->exec_command
[SERVICE_EXEC_STOP_POST
];
2101 if (s
->control_command
) {
2102 s
->control_command_id
= SERVICE_EXEC_STOP_POST
;
2103 pidref_done(&s
->control_pid
);
2105 r
= service_spawn(s
,
2107 s
->timeout_stop_usec
,
2108 EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_APPLY_TTY_STDIN
|EXEC_IS_CONTROL
|EXEC_SETENV_RESULT
|EXEC_CONTROL_CGROUP
,
2111 log_unit_warning_errno(UNIT(s
), r
, "Failed to spawn 'stop-post' task: %m");
2112 service_enter_signal(s
, SERVICE_FINAL_SIGTERM
, SERVICE_FAILURE_RESOURCES
);
2116 service_set_state(s
, SERVICE_STOP_POST
);
2118 service_enter_signal(s
, SERVICE_FINAL_SIGTERM
, SERVICE_SUCCESS
);
2121 static int state_to_kill_operation(Service
*s
, ServiceState state
) {
2124 case SERVICE_STOP_WATCHDOG
:
2125 case SERVICE_FINAL_WATCHDOG
:
2126 return KILL_WATCHDOG
;
2128 case SERVICE_STOP_SIGTERM
:
2129 if (unit_has_job_type(UNIT(s
), JOB_RESTART
))
2130 return KILL_RESTART
;
2133 case SERVICE_FINAL_SIGTERM
:
2134 return KILL_TERMINATE
;
2136 case SERVICE_STOP_SIGKILL
:
2137 case SERVICE_FINAL_SIGKILL
:
2141 return _KILL_OPERATION_INVALID
;
2145 static void service_enter_signal(Service
*s
, ServiceState state
, ServiceResult f
) {
2146 int kill_operation
, r
;
2150 if (s
->result
== SERVICE_SUCCESS
)
2153 /* Before sending any signal, make sure we track all members of this cgroup */
2154 (void) unit_watch_all_pids(UNIT(s
));
2156 /* Also, enqueue a job that we recheck all our PIDs a bit later, given that it's likely some processes have
2158 (void) unit_enqueue_rewatch_pids(UNIT(s
));
2160 kill_operation
= state_to_kill_operation(s
, state
);
2161 r
= unit_kill_context(
2169 log_unit_warning_errno(UNIT(s
), r
, "Failed to kill processes: %m");
2174 r
= service_arm_timer(s
, /* relative= */ true,
2175 kill_operation
== KILL_WATCHDOG
? service_timeout_abort_usec(s
) : s
->timeout_stop_usec
);
2177 log_unit_warning_errno(UNIT(s
), r
, "Failed to install timer: %m");
2181 service_set_state(s
, state
);
2182 } else if (IN_SET(state
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
) && s
->kill_context
.send_sigkill
)
2183 service_enter_signal(s
, SERVICE_STOP_SIGKILL
, SERVICE_SUCCESS
);
2184 else if (IN_SET(state
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
))
2185 service_enter_stop_post(s
, SERVICE_SUCCESS
);
2186 else if (IN_SET(state
, SERVICE_FINAL_WATCHDOG
, SERVICE_FINAL_SIGTERM
) && s
->kill_context
.send_sigkill
)
2187 service_enter_signal(s
, SERVICE_FINAL_SIGKILL
, SERVICE_SUCCESS
);
2189 service_enter_dead(s
, SERVICE_SUCCESS
, /* allow_restart= */ true);
2194 if (IN_SET(state
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
))
2195 service_enter_stop_post(s
, SERVICE_FAILURE_RESOURCES
);
2197 service_enter_dead(s
, SERVICE_FAILURE_RESOURCES
, /* allow_restart= */ true);
2200 static void service_enter_stop_by_notify(Service
*s
) {
2205 (void) unit_enqueue_rewatch_pids(UNIT(s
));
2207 r
= service_arm_timer(s
, /* relative= */ true, s
->timeout_stop_usec
);
2209 log_unit_warning_errno(UNIT(s
), r
, "Failed to install timer: %m");
2210 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_RESOURCES
);
2214 /* The service told us it's stopping, so it's as if we SIGTERM'd it. */
2215 service_set_state(s
, SERVICE_STOP_SIGTERM
);
2218 static void service_enter_stop(Service
*s
, ServiceResult f
) {
2223 if (s
->result
== SERVICE_SUCCESS
)
2226 service_unwatch_control_pid(s
);
2227 (void) unit_enqueue_rewatch_pids(UNIT(s
));
2229 s
->control_command
= s
->exec_command
[SERVICE_EXEC_STOP
];
2230 if (s
->control_command
) {
2231 s
->control_command_id
= SERVICE_EXEC_STOP
;
2232 pidref_done(&s
->control_pid
);
2234 r
= service_spawn(s
,
2236 s
->timeout_stop_usec
,
2237 EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_IS_CONTROL
|EXEC_SETENV_RESULT
|EXEC_CONTROL_CGROUP
,
2240 log_unit_warning_errno(UNIT(s
), r
, "Failed to spawn 'stop' task: %m");
2241 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_RESOURCES
);
2245 service_set_state(s
, SERVICE_STOP
);
2247 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_SUCCESS
);
2250 static bool service_good(Service
*s
) {
2254 if (s
->type
== SERVICE_DBUS
&& !s
->bus_name_good
)
2257 main_pid_ok
= main_pid_good(s
);
2258 if (main_pid_ok
> 0) /* It's alive */
2260 if (main_pid_ok
== 0 && s
->exit_type
== SERVICE_EXIT_MAIN
) /* It's dead */
2263 /* OK, we don't know anything about the main PID, maybe
2264 * because there is none. Let's check the control group
2267 return cgroup_good(s
) != 0;
2270 static void service_enter_running(Service
*s
, ServiceResult f
) {
2275 if (s
->result
== SERVICE_SUCCESS
)
2278 service_unwatch_control_pid(s
);
2280 if (s
->result
!= SERVICE_SUCCESS
)
2281 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
2282 else if (service_good(s
)) {
2284 /* If there are any queued up sd_notify() notifications, process them now */
2285 if (s
->notify_state
== NOTIFY_RELOADING
)
2286 service_enter_reload_by_notify(s
);
2287 else if (s
->notify_state
== NOTIFY_STOPPING
)
2288 service_enter_stop_by_notify(s
);
2290 service_set_state(s
, SERVICE_RUNNING
);
2292 r
= service_arm_timer(s
, /* relative= */ false, service_running_timeout(s
));
2294 log_unit_warning_errno(UNIT(s
), r
, "Failed to install timer: %m");
2295 service_enter_running(s
, SERVICE_FAILURE_RESOURCES
);
2300 } else if (s
->remain_after_exit
)
2301 service_set_state(s
, SERVICE_EXITED
);
2303 service_enter_stop(s
, SERVICE_SUCCESS
);
2306 static void service_enter_start_post(Service
*s
) {
2310 service_unwatch_control_pid(s
);
2311 service_reset_watchdog(s
);
2313 s
->control_command
= s
->exec_command
[SERVICE_EXEC_START_POST
];
2314 if (s
->control_command
) {
2315 s
->control_command_id
= SERVICE_EXEC_START_POST
;
2316 pidref_done(&s
->control_pid
);
2318 r
= service_spawn(s
,
2320 s
->timeout_start_usec
,
2321 EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_IS_CONTROL
|EXEC_CONTROL_CGROUP
,
2324 log_unit_warning_errno(UNIT(s
), r
, "Failed to spawn 'start-post' task: %m");
2325 service_enter_stop(s
, SERVICE_FAILURE_RESOURCES
);
2329 service_set_state(s
, SERVICE_START_POST
);
2331 service_enter_running(s
, SERVICE_SUCCESS
);
2334 static void service_kill_control_process(Service
*s
) {
2339 if (!pidref_is_set(&s
->control_pid
))
2342 r
= pidref_kill_and_sigcont(&s
->control_pid
, SIGKILL
);
2344 _cleanup_free_
char *comm
= NULL
;
2346 (void) get_process_comm(s
->control_pid
.pid
, &comm
);
2348 log_unit_debug_errno(UNIT(s
), r
, "Failed to kill control process " PID_FMT
" (%s), ignoring: %m",
2349 s
->control_pid
.pid
, strna(comm
));
2353 static int service_adverse_to_leftover_processes(Service
*s
) {
2356 /* KillMode=mixed and control group are used to indicate that all process should be killed off.
2357 * SendSIGKILL= is used for services that require a clean shutdown. These are typically database
2358 * service where a SigKilled process would result in a lengthy recovery and who's shutdown or startup
2359 * time is quite variable (so Timeout settings aren't of use).
2361 * Here we take these two factors and refuse to start a service if there are existing processes
2362 * within a control group. Databases, while generally having some protection against multiple
2363 * instances running, lets not stress the rigor of these. Also ExecStartPre= parts of the service
2364 * aren't as rigoriously written to protect aganst against multiple use. */
2366 if (unit_warn_leftover_processes(UNIT(s
), unit_log_leftover_process_start
) > 0 &&
2367 IN_SET(s
->kill_context
.kill_mode
, KILL_MIXED
, KILL_CONTROL_GROUP
) &&
2368 !s
->kill_context
.send_sigkill
)
2369 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(EBUSY
),
2370 "Will not start SendSIGKILL=no service of type KillMode=control-group or mixed while processes exist");
2375 static void service_enter_start(Service
*s
) {
2376 _cleanup_(pidref_done
) PidRef pidref
= PIDREF_NULL
;
2383 service_unwatch_control_pid(s
);
2384 service_unwatch_main_pid(s
);
2386 r
= service_adverse_to_leftover_processes(s
);
2390 if (s
->type
== SERVICE_FORKING
) {
2391 s
->control_command_id
= SERVICE_EXEC_START
;
2392 c
= s
->control_command
= s
->exec_command
[SERVICE_EXEC_START
];
2394 s
->main_command
= NULL
;
2396 s
->control_command_id
= _SERVICE_EXEC_COMMAND_INVALID
;
2397 s
->control_command
= NULL
;
2399 c
= s
->main_command
= s
->exec_command
[SERVICE_EXEC_START
];
2403 if (s
->type
!= SERVICE_ONESHOT
) {
2404 /* There's no command line configured for the main command? Hmm, that is strange.
2405 * This can only happen if the configuration changes at runtime. In this case,
2406 * let's enter a failure state. */
2407 r
= log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENXIO
), "There's no 'start' task anymore we could start.");
2411 /* We force a fake state transition here. Otherwise, the unit would go directly from
2412 * SERVICE_DEAD to SERVICE_DEAD without SERVICE_ACTIVATING or SERVICE_ACTIVE
2413 * in between. This way we can later trigger actions that depend on the state
2414 * transition, including SuccessAction=. */
2415 service_set_state(s
, SERVICE_START
);
2417 service_enter_start_post(s
);
2421 if (IN_SET(s
->type
, SERVICE_SIMPLE
, SERVICE_IDLE
))
2422 /* For simple + idle this is the main process. We don't apply any timeout here, but
2423 * service_enter_running() will later apply the .runtime_max_usec timeout. */
2424 timeout
= USEC_INFINITY
;
2426 timeout
= s
->timeout_start_usec
;
2428 r
= service_spawn(s
,
2431 EXEC_PASS_FDS
|EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_APPLY_TTY_STDIN
|EXEC_SET_WATCHDOG
|EXEC_WRITE_CREDENTIALS
|EXEC_SETENV_MONITOR_RESULT
,
2434 log_unit_warning_errno(UNIT(s
), r
, "Failed to spawn 'start' task: %m");
2438 if (IN_SET(s
->type
, SERVICE_SIMPLE
, SERVICE_IDLE
)) {
2439 /* For simple services we immediately start
2440 * the START_POST binaries. */
2442 (void) service_set_main_pidref(s
, &pidref
);
2443 service_enter_start_post(s
);
2445 } else if (s
->type
== SERVICE_FORKING
) {
2447 /* For forking services we wait until the start
2448 * process exited. */
2450 pidref_done(&s
->control_pid
);
2451 s
->control_pid
= TAKE_PIDREF(pidref
);
2452 service_set_state(s
, SERVICE_START
);
2454 } else if (IN_SET(s
->type
, SERVICE_ONESHOT
, SERVICE_DBUS
, SERVICE_NOTIFY
, SERVICE_NOTIFY_RELOAD
, SERVICE_EXEC
)) {
2456 /* For oneshot services we wait until the start process exited, too, but it is our main process. */
2458 /* For D-Bus services we know the main pid right away, but wait for the bus name to appear on the
2459 * bus. 'notify' and 'exec' services are similar. */
2461 (void) service_set_main_pidref(s
, &pidref
);
2462 service_set_state(s
, SERVICE_START
);
2464 assert_not_reached();
2469 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_RESOURCES
);
2472 static void service_enter_start_pre(Service
*s
) {
2477 service_unwatch_control_pid(s
);
2479 s
->control_command
= s
->exec_command
[SERVICE_EXEC_START_PRE
];
2480 if (s
->control_command
) {
2482 r
= service_adverse_to_leftover_processes(s
);
2486 s
->control_command_id
= SERVICE_EXEC_START_PRE
;
2488 r
= service_spawn(s
,
2490 s
->timeout_start_usec
,
2491 EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_IS_CONTROL
|EXEC_APPLY_TTY_STDIN
|EXEC_SETENV_MONITOR_RESULT
|EXEC_WRITE_CREDENTIALS
,
2494 log_unit_warning_errno(UNIT(s
), r
, "Failed to spawn 'start-pre' task: %m");
2498 service_set_state(s
, SERVICE_START_PRE
);
2500 service_enter_start(s
);
2505 service_enter_dead(s
, SERVICE_FAILURE_RESOURCES
, /* allow_restart= */ true);
2508 static void service_enter_condition(Service
*s
) {
2513 service_unwatch_control_pid(s
);
2515 s
->control_command
= s
->exec_command
[SERVICE_EXEC_CONDITION
];
2516 if (s
->control_command
) {
2518 r
= service_adverse_to_leftover_processes(s
);
2522 s
->control_command_id
= SERVICE_EXEC_CONDITION
;
2523 pidref_done(&s
->control_pid
);
2525 r
= service_spawn(s
,
2527 s
->timeout_start_usec
,
2528 EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_IS_CONTROL
|EXEC_APPLY_TTY_STDIN
,
2532 log_unit_warning_errno(UNIT(s
), r
, "Failed to spawn 'exec-condition' task: %m");
2536 service_set_state(s
, SERVICE_CONDITION
);
2538 service_enter_start_pre(s
);
2543 service_enter_dead(s
, SERVICE_FAILURE_RESOURCES
, /* allow_restart= */ true);
2546 static void service_enter_restart(Service
*s
) {
2547 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2552 if (unit_has_job_type(UNIT(s
), JOB_STOP
)) {
2553 /* Don't restart things if we are going down anyway */
2554 log_unit_info(UNIT(s
), "Stop job pending for unit, skipping automatic restart.");
2558 /* Any units that are bound to this service must also be restarted. We use JOB_START for ourselves
2559 * but then set JOB_RESTART_DEPENDENCIES which will enqueue JOB_RESTART for those dependency jobs. */
2560 r
= manager_add_job(UNIT(s
)->manager
, JOB_START
, UNIT(s
), JOB_RESTART_DEPENDENCIES
, NULL
, &error
, NULL
);
2562 log_unit_warning(UNIT(s
), "Failed to schedule restart job: %s", bus_error_message(&error
, r
));
2563 service_enter_dead(s
, SERVICE_FAILURE_RESOURCES
, /* allow_restart= */ false);
2567 /* Count the jobs we enqueue for restarting. This counter is maintained as long as the unit isn't
2568 * fully stopped, i.e. as long as it remains up or remains in auto-start states. The user can reset
2569 * the counter explicitly however via the usual "systemctl reset-failure" logic. */
2571 s
->flush_n_restarts
= false;
2573 s
->notify_access_override
= _NOTIFY_ACCESS_INVALID
;
2575 log_unit_struct(UNIT(s
), LOG_INFO
,
2576 "MESSAGE_ID=" SD_MESSAGE_UNIT_RESTART_SCHEDULED_STR
,
2577 LOG_UNIT_INVOCATION_ID(UNIT(s
)),
2578 LOG_UNIT_MESSAGE(UNIT(s
),
2579 "Scheduled restart job, restart counter is at %u.", s
->n_restarts
),
2580 "N_RESTARTS=%u", s
->n_restarts
);
2582 service_set_state(s
, SERVICE_AUTO_RESTART_QUEUED
);
2584 /* Notify clients about changed restart counter */
2585 unit_add_to_dbus_queue(UNIT(s
));
2588 static void service_enter_reload_by_notify(Service
*s
) {
2589 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2594 r
= service_arm_timer(s
, /* relative= */ true, s
->timeout_start_usec
);
2596 log_unit_warning_errno(UNIT(s
), r
, "Failed to install timer: %m");
2597 s
->reload_result
= SERVICE_FAILURE_RESOURCES
;
2598 service_enter_running(s
, SERVICE_SUCCESS
);
2602 service_set_state(s
, SERVICE_RELOAD_NOTIFY
);
2604 /* service_enter_reload_by_notify is never called during a reload, thus no loops are possible. */
2605 r
= manager_propagate_reload(UNIT(s
)->manager
, UNIT(s
), JOB_FAIL
, &error
);
2607 log_unit_warning(UNIT(s
), "Failed to schedule propagation of reload, ignoring: %s", bus_error_message(&error
, r
));
2610 static void service_enter_reload(Service
*s
) {
2611 bool killed
= false;
2616 service_unwatch_control_pid(s
);
2617 s
->reload_result
= SERVICE_SUCCESS
;
2619 usec_t ts
= now(CLOCK_MONOTONIC
);
2621 if (s
->type
== SERVICE_NOTIFY_RELOAD
&& pidref_is_set(&s
->main_pid
)) {
2622 r
= pidref_kill_and_sigcont(&s
->main_pid
, s
->reload_signal
);
2624 log_unit_warning_errno(UNIT(s
), r
, "Failed to send reload signal: %m");
2631 s
->control_command
= s
->exec_command
[SERVICE_EXEC_RELOAD
];
2632 if (s
->control_command
) {
2633 s
->control_command_id
= SERVICE_EXEC_RELOAD
;
2634 pidref_done(&s
->control_pid
);
2636 r
= service_spawn(s
,
2638 s
->timeout_start_usec
,
2639 EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_IS_CONTROL
|EXEC_CONTROL_CGROUP
,
2642 log_unit_warning_errno(UNIT(s
), r
, "Failed to spawn 'reload' task: %m");
2646 service_set_state(s
, SERVICE_RELOAD
);
2647 } else if (killed
) {
2648 r
= service_arm_timer(s
, /* relative= */ true, s
->timeout_start_usec
);
2650 log_unit_warning_errno(UNIT(s
), r
, "Failed to install timer: %m");
2654 service_set_state(s
, SERVICE_RELOAD_SIGNAL
);
2656 service_enter_running(s
, SERVICE_SUCCESS
);
2660 /* Store the timestamp when we started reloading: when reloading via SIGHUP we won't leave the reload
2661 * state until we received both RELOADING=1 and READY=1 with MONOTONIC_USEC= set to a value above
2662 * this. Thus we know for sure the reload cycle was executed *after* we requested it, and is not one
2663 * that was already in progress before. */
2664 s
->reload_begin_usec
= ts
;
2668 s
->reload_result
= SERVICE_FAILURE_RESOURCES
;
2669 service_enter_running(s
, SERVICE_SUCCESS
);
2672 static void service_run_next_control(Service
*s
) {
2677 assert(s
->control_command
);
2678 assert(s
->control_command
->command_next
);
2680 assert(s
->control_command_id
!= SERVICE_EXEC_START
);
2682 s
->control_command
= s
->control_command
->command_next
;
2683 service_unwatch_control_pid(s
);
2685 if (IN_SET(s
->state
, SERVICE_CONDITION
, SERVICE_START_PRE
, SERVICE_START
, SERVICE_START_POST
, SERVICE_RUNNING
, SERVICE_RELOAD
))
2686 timeout
= s
->timeout_start_usec
;
2688 timeout
= s
->timeout_stop_usec
;
2690 pidref_done(&s
->control_pid
);
2692 r
= service_spawn(s
,
2695 EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_IS_CONTROL
|
2696 (IN_SET(s
->state
, SERVICE_CONDITION
, SERVICE_START_PRE
, SERVICE_START
, SERVICE_START_POST
, SERVICE_RUNNING
, SERVICE_RELOAD
) ? EXEC_WRITE_CREDENTIALS
: 0)|
2697 (IN_SET(s
->control_command_id
, SERVICE_EXEC_CONDITION
, SERVICE_EXEC_START_PRE
, SERVICE_EXEC_STOP_POST
) ? EXEC_APPLY_TTY_STDIN
: 0)|
2698 (IN_SET(s
->control_command_id
, SERVICE_EXEC_STOP
, SERVICE_EXEC_STOP_POST
) ? EXEC_SETENV_RESULT
: 0)|
2699 (IN_SET(s
->control_command_id
, SERVICE_EXEC_START_PRE
, SERVICE_EXEC_START
) ? EXEC_SETENV_MONITOR_RESULT
: 0)|
2700 (IN_SET(s
->control_command_id
, SERVICE_EXEC_START_POST
, SERVICE_EXEC_RELOAD
, SERVICE_EXEC_STOP
, SERVICE_EXEC_STOP_POST
) ? EXEC_CONTROL_CGROUP
: 0),
2703 log_unit_warning_errno(UNIT(s
), r
, "Failed to spawn next control task: %m");
2705 if (IN_SET(s
->state
, SERVICE_CONDITION
, SERVICE_START_PRE
, SERVICE_START_POST
, SERVICE_STOP
))
2706 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_RESOURCES
);
2707 else if (s
->state
== SERVICE_STOP_POST
)
2708 service_enter_dead(s
, SERVICE_FAILURE_RESOURCES
, /* allow_restart= */ true);
2709 else if (s
->state
== SERVICE_RELOAD
) {
2710 s
->reload_result
= SERVICE_FAILURE_RESOURCES
;
2711 service_enter_running(s
, SERVICE_SUCCESS
);
2713 service_enter_stop(s
, SERVICE_FAILURE_RESOURCES
);
2717 static void service_run_next_main(Service
*s
) {
2718 _cleanup_(pidref_done
) PidRef pidref
= PIDREF_NULL
;
2722 assert(s
->main_command
);
2723 assert(s
->main_command
->command_next
);
2724 assert(s
->type
== SERVICE_ONESHOT
);
2726 s
->main_command
= s
->main_command
->command_next
;
2727 service_unwatch_main_pid(s
);
2729 r
= service_spawn(s
,
2731 s
->timeout_start_usec
,
2732 EXEC_PASS_FDS
|EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_APPLY_TTY_STDIN
|EXEC_SET_WATCHDOG
|EXEC_SETENV_MONITOR_RESULT
|EXEC_WRITE_CREDENTIALS
,
2735 log_unit_warning_errno(UNIT(s
), r
, "Failed to spawn next main task: %m");
2736 service_enter_stop(s
, SERVICE_FAILURE_RESOURCES
);
2740 (void) service_set_main_pidref(s
, &pidref
);
2743 static int service_start(Unit
*u
) {
2744 Service
*s
= SERVICE(u
);
2749 /* We cannot fulfill this request right now, try again later
2751 if (IN_SET(s
->state
,
2752 SERVICE_STOP
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
, SERVICE_STOP_POST
,
2753 SERVICE_FINAL_WATCHDOG
, SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
, SERVICE_CLEANING
))
2756 /* Already on it! */
2757 if (IN_SET(s
->state
, SERVICE_CONDITION
, SERVICE_START_PRE
, SERVICE_START
, SERVICE_START_POST
))
2760 /* A service that will be restarted must be stopped first to trigger BindsTo and/or OnFailure
2761 * dependencies. If a user does not want to wait for the holdoff time to elapse, the service should
2762 * be manually restarted, not started. We simply return EAGAIN here, so that any start jobs stay
2763 * queued, and assume that the auto restart timer will eventually trigger the restart. */
2764 if (IN_SET(s
->state
, SERVICE_AUTO_RESTART
, SERVICE_DEAD_BEFORE_AUTO_RESTART
, SERVICE_FAILED_BEFORE_AUTO_RESTART
))
2767 assert(IN_SET(s
->state
, SERVICE_DEAD
, SERVICE_FAILED
, SERVICE_DEAD_RESOURCES_PINNED
, SERVICE_AUTO_RESTART_QUEUED
));
2769 r
= unit_acquire_invocation_id(u
);
2773 s
->result
= SERVICE_SUCCESS
;
2774 s
->reload_result
= SERVICE_SUCCESS
;
2775 s
->main_pid_known
= false;
2776 s
->main_pid_alien
= false;
2777 s
->forbid_restart
= false;
2779 s
->status_text
= mfree(s
->status_text
);
2780 s
->status_errno
= 0;
2782 s
->notify_access_override
= _NOTIFY_ACCESS_INVALID
;
2783 s
->notify_state
= NOTIFY_UNKNOWN
;
2785 s
->watchdog_original_usec
= s
->watchdog_usec
;
2786 s
->watchdog_override_enable
= false;
2787 s
->watchdog_override_usec
= USEC_INFINITY
;
2789 exec_command_reset_status_list_array(s
->exec_command
, _SERVICE_EXEC_COMMAND_MAX
);
2790 exec_status_reset(&s
->main_exec_status
);
2792 /* This is not an automatic restart? Flush the restart counter then */
2793 if (s
->flush_n_restarts
) {
2795 s
->flush_n_restarts
= false;
2798 u
->reset_accounting
= true;
2800 service_enter_condition(s
);
2804 static int service_stop(Unit
*u
) {
2805 Service
*s
= SERVICE(u
);
2809 /* Don't create restart jobs from manual stops. */
2810 s
->forbid_restart
= true;
2815 case SERVICE_STOP_SIGTERM
:
2816 case SERVICE_STOP_SIGKILL
:
2817 case SERVICE_STOP_POST
:
2818 case SERVICE_FINAL_WATCHDOG
:
2819 case SERVICE_FINAL_SIGTERM
:
2820 case SERVICE_FINAL_SIGKILL
:
2824 case SERVICE_AUTO_RESTART
:
2825 case SERVICE_AUTO_RESTART_QUEUED
:
2826 /* Give up on the auto restart */
2827 service_set_state(s
, service_determine_dead_state(s
));
2830 case SERVICE_CONDITION
:
2831 case SERVICE_START_PRE
:
2833 case SERVICE_START_POST
:
2834 case SERVICE_RELOAD
:
2835 case SERVICE_RELOAD_SIGNAL
:
2836 case SERVICE_RELOAD_NOTIFY
:
2837 case SERVICE_STOP_WATCHDOG
:
2838 /* If there's already something running we go directly into kill mode. */
2839 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_SUCCESS
);
2842 case SERVICE_CLEANING
:
2843 /* If we are currently cleaning, then abort it, brutally. */
2844 service_enter_signal(s
, SERVICE_FINAL_SIGKILL
, SERVICE_SUCCESS
);
2847 case SERVICE_RUNNING
:
2848 case SERVICE_EXITED
:
2849 service_enter_stop(s
, SERVICE_SUCCESS
);
2852 case SERVICE_DEAD_BEFORE_AUTO_RESTART
:
2853 case SERVICE_FAILED_BEFORE_AUTO_RESTART
:
2855 case SERVICE_FAILED
:
2856 case SERVICE_DEAD_RESOURCES_PINNED
:
2858 /* Unknown state, or unit_stop() should already have handled these */
2859 assert_not_reached();
2863 static int service_reload(Unit
*u
) {
2864 Service
*s
= SERVICE(u
);
2868 assert(IN_SET(s
->state
, SERVICE_RUNNING
, SERVICE_EXITED
));
2870 service_enter_reload(s
);
2874 static bool service_can_reload(Unit
*u
) {
2875 Service
*s
= SERVICE(u
);
2879 return s
->exec_command
[SERVICE_EXEC_RELOAD
] ||
2880 s
->type
== SERVICE_NOTIFY_RELOAD
;
2883 static unsigned service_exec_command_index(Unit
*u
, ServiceExecCommand id
, const ExecCommand
*current
) {
2884 Service
*s
= SERVICE(u
);
2889 assert(id
< _SERVICE_EXEC_COMMAND_MAX
);
2891 const ExecCommand
*first
= s
->exec_command
[id
];
2893 /* Figure out where we are in the list by walking back to the beginning */
2894 for (const ExecCommand
*c
= current
; c
!= first
; c
= c
->command_prev
)
2900 static int service_serialize_exec_command(Unit
*u
, FILE *f
, const ExecCommand
*command
) {
2901 _cleanup_free_
char *args
= NULL
, *p
= NULL
;
2902 Service
*s
= SERVICE(u
);
2903 const char *type
, *key
;
2904 ServiceExecCommand id
;
2914 if (command
== s
->control_command
) {
2916 id
= s
->control_command_id
;
2919 id
= SERVICE_EXEC_START
;
2922 idx
= service_exec_command_index(u
, id
, command
);
2924 STRV_FOREACH(arg
, command
->argv
) {
2925 _cleanup_free_
char *e
= NULL
;
2933 if (!GREEDY_REALLOC(args
, length
+ 2 + n
+ 2))
2937 args
[length
++] = ' ';
2939 args
[length
++] = '"';
2940 memcpy(args
+ length
, e
, n
);
2942 args
[length
++] = '"';
2945 if (!GREEDY_REALLOC(args
, length
+ 1))
2950 p
= cescape(command
->path
);
2954 key
= strjoina(type
, "-command");
2956 /* We use '+1234' instead of '1234' to mark the last command in a sequence.
2957 * This is used in service_deserialize_exec_command(). */
2958 (void) serialize_item_format(
2961 service_exec_command_to_string(id
),
2962 command
->command_next
? "" : "+",
2969 static int service_serialize(Unit
*u
, FILE *f
, FDSet
*fds
) {
2970 Service
*s
= SERVICE(u
);
2977 (void) serialize_item(f
, "state", service_state_to_string(s
->state
));
2978 (void) serialize_item(f
, "result", service_result_to_string(s
->result
));
2979 (void) serialize_item(f
, "reload-result", service_result_to_string(s
->reload_result
));
2981 if (pidref_is_set(&s
->control_pid
))
2982 (void) serialize_item_format(f
, "control-pid", PID_FMT
, s
->control_pid
.pid
);
2984 if (s
->main_pid_known
&& pidref_is_set(&s
->main_pid
))
2985 (void) serialize_item_format(f
, "main-pid", PID_FMT
, s
->main_pid
.pid
);
2987 (void) serialize_bool(f
, "main-pid-known", s
->main_pid_known
);
2988 (void) serialize_bool(f
, "bus-name-good", s
->bus_name_good
);
2989 (void) serialize_bool(f
, "bus-name-owner", s
->bus_name_owner
);
2991 (void) serialize_item_format(f
, "n-restarts", "%u", s
->n_restarts
);
2992 (void) serialize_bool(f
, "flush-n-restarts", s
->flush_n_restarts
);
2994 r
= serialize_item_escaped(f
, "status-text", s
->status_text
);
2998 service_serialize_exec_command(u
, f
, s
->control_command
);
2999 service_serialize_exec_command(u
, f
, s
->main_command
);
3001 r
= serialize_fd(f
, fds
, "stdin-fd", s
->stdin_fd
);
3004 r
= serialize_fd(f
, fds
, "stdout-fd", s
->stdout_fd
);
3007 r
= serialize_fd(f
, fds
, "stderr-fd", s
->stderr_fd
);
3011 if (s
->exec_fd_event_source
) {
3012 r
= serialize_fd(f
, fds
, "exec-fd", sd_event_source_get_io_fd(s
->exec_fd_event_source
));
3016 (void) serialize_bool(f
, "exec-fd-hot", s
->exec_fd_hot
);
3019 if (UNIT_ISSET(s
->accept_socket
)) {
3020 r
= serialize_item(f
, "accept-socket", UNIT_DEREF(s
->accept_socket
)->id
);
3025 r
= serialize_fd(f
, fds
, "socket-fd", s
->socket_fd
);
3029 LIST_FOREACH(fd_store
, fs
, s
->fd_store
) {
3030 _cleanup_free_
char *c
= NULL
;
3033 copy
= fdset_put_dup(fds
, fs
->fd
);
3035 return log_error_errno(copy
, "Failed to copy file descriptor for serialization: %m");
3037 c
= cescape(fs
->fdname
);
3041 (void) serialize_item_format(f
, "fd-store-fd", "%i \"%s\" %i", copy
, c
, fs
->do_poll
);
3044 if (s
->main_exec_status
.pid
> 0) {
3045 (void) serialize_item_format(f
, "main-exec-status-pid", PID_FMT
, s
->main_exec_status
.pid
);
3046 (void) serialize_dual_timestamp(f
, "main-exec-status-start", &s
->main_exec_status
.start_timestamp
);
3047 (void) serialize_dual_timestamp(f
, "main-exec-status-exit", &s
->main_exec_status
.exit_timestamp
);
3049 if (dual_timestamp_is_set(&s
->main_exec_status
.exit_timestamp
)) {
3050 (void) serialize_item_format(f
, "main-exec-status-code", "%i", s
->main_exec_status
.code
);
3051 (void) serialize_item_format(f
, "main-exec-status-status", "%i", s
->main_exec_status
.status
);
3055 if (s
->notify_access_override
>= 0)
3056 (void) serialize_item(f
, "notify-access-override", notify_access_to_string(s
->notify_access_override
));
3058 (void) serialize_dual_timestamp(f
, "watchdog-timestamp", &s
->watchdog_timestamp
);
3059 (void) serialize_bool(f
, "forbid-restart", s
->forbid_restart
);
3061 if (s
->watchdog_override_enable
)
3062 (void) serialize_item_format(f
, "watchdog-override-usec", USEC_FMT
, s
->watchdog_override_usec
);
3064 if (s
->watchdog_original_usec
!= USEC_INFINITY
)
3065 (void) serialize_item_format(f
, "watchdog-original-usec", USEC_FMT
, s
->watchdog_original_usec
);
3067 if (s
->reload_begin_usec
!= USEC_INFINITY
)
3068 (void) serialize_item_format(f
, "reload-begin-usec", USEC_FMT
, s
->reload_begin_usec
);
3073 int service_deserialize_exec_command(
3076 const char *value
) {
3078 Service
*s
= SERVICE(u
);
3080 unsigned idx
= 0, i
;
3081 bool control
, found
= false, last
= false;
3082 ServiceExecCommand id
= _SERVICE_EXEC_COMMAND_INVALID
;
3083 ExecCommand
*command
= NULL
;
3084 _cleanup_free_
char *path
= NULL
;
3085 _cleanup_strv_free_
char **argv
= NULL
;
3087 enum ExecCommandState
{
3088 STATE_EXEC_COMMAND_TYPE
,
3089 STATE_EXEC_COMMAND_INDEX
,
3090 STATE_EXEC_COMMAND_PATH
,
3091 STATE_EXEC_COMMAND_ARGS
,
3092 _STATE_EXEC_COMMAND_MAX
,
3093 _STATE_EXEC_COMMAND_INVALID
= -EINVAL
,
3100 control
= streq(key
, "control-command");
3102 state
= STATE_EXEC_COMMAND_TYPE
;
3105 _cleanup_free_
char *arg
= NULL
;
3107 r
= extract_first_word(&value
, &arg
, NULL
, EXTRACT_CUNESCAPE
| EXTRACT_UNQUOTE
);
3114 case STATE_EXEC_COMMAND_TYPE
:
3115 id
= service_exec_command_from_string(arg
);
3119 state
= STATE_EXEC_COMMAND_INDEX
;
3121 case STATE_EXEC_COMMAND_INDEX
:
3122 /* PID 1234 is serialized as either '1234' or '+1234'. The second form is used to
3123 * mark the last command in a sequence. We warn if the deserialized command doesn't
3124 * match what we have loaded from the unit, but we don't need to warn if that is the
3127 r
= safe_atou(arg
, &idx
);
3130 last
= arg
[0] == '+';
3132 state
= STATE_EXEC_COMMAND_PATH
;
3134 case STATE_EXEC_COMMAND_PATH
:
3135 path
= TAKE_PTR(arg
);
3136 state
= STATE_EXEC_COMMAND_ARGS
;
3138 case STATE_EXEC_COMMAND_ARGS
:
3139 r
= strv_extend(&argv
, arg
);
3144 assert_not_reached();
3148 if (state
!= STATE_EXEC_COMMAND_ARGS
)
3150 if (strv_isempty(argv
))
3151 return -EINVAL
; /* At least argv[0] must be always present. */
3153 /* Let's check whether exec command on given offset matches data that we just deserialized */
3154 for (command
= s
->exec_command
[id
], i
= 0; command
; command
= command
->command_next
, i
++) {
3158 found
= strv_equal(argv
, command
->argv
) && streq(command
->path
, path
);
3163 /* Command at the index we serialized is different, let's look for command that exactly
3164 * matches but is on different index. If there is no such command we will not resume execution. */
3165 for (command
= s
->exec_command
[id
]; command
; command
= command
->command_next
)
3166 if (strv_equal(command
->argv
, argv
) && streq(command
->path
, path
))
3170 if (command
&& control
) {
3171 s
->control_command
= command
;
3172 s
->control_command_id
= id
;
3174 s
->main_command
= command
;
3176 log_unit_debug(u
, "Current command vanished from the unit file.");
3178 log_unit_warning(u
, "Current command vanished from the unit file, execution of the command list won't be resumed.");
3183 static int service_deserialize_item(Unit
*u
, const char *key
, const char *value
, FDSet
*fds
) {
3184 Service
*s
= SERVICE(u
);
3192 if (streq(key
, "state")) {
3195 state
= service_state_from_string(value
);
3197 log_unit_debug(u
, "Failed to parse state value: %s", value
);
3199 s
->deserialized_state
= state
;
3200 } else if (streq(key
, "result")) {
3203 f
= service_result_from_string(value
);
3205 log_unit_debug(u
, "Failed to parse result value: %s", value
);
3206 else if (f
!= SERVICE_SUCCESS
)
3209 } else if (streq(key
, "reload-result")) {
3212 f
= service_result_from_string(value
);
3214 log_unit_debug(u
, "Failed to parse reload result value: %s", value
);
3215 else if (f
!= SERVICE_SUCCESS
)
3216 s
->reload_result
= f
;
3218 } else if (streq(key
, "control-pid")) {
3219 pidref_done(&s
->control_pid
);
3220 r
= pidref_set_pidstr(&s
->control_pid
, value
);
3222 log_unit_debug_errno(u
, r
, "Failed to initialize control PID '%s' from serialization, ignoring.", value
);
3223 } else if (streq(key
, "main-pid")) {
3226 if (parse_pid(value
, &pid
) < 0)
3227 log_unit_debug(u
, "Failed to parse main-pid value: %s", value
);
3229 (void) service_set_main_pid(s
, pid
);
3230 } else if (streq(key
, "main-pid-known")) {
3233 b
= parse_boolean(value
);
3235 log_unit_debug(u
, "Failed to parse main-pid-known value: %s", value
);
3237 s
->main_pid_known
= b
;
3238 } else if (streq(key
, "bus-name-good")) {
3241 b
= parse_boolean(value
);
3243 log_unit_debug(u
, "Failed to parse bus-name-good value: %s", value
);
3245 s
->bus_name_good
= b
;
3246 } else if (streq(key
, "bus-name-owner")) {
3247 r
= free_and_strdup(&s
->bus_name_owner
, value
);
3249 log_unit_error_errno(u
, r
, "Unable to deserialize current bus owner %s: %m", value
);
3250 } else if (streq(key
, "status-text")) {
3254 l
= cunescape(value
, 0, &t
);
3256 log_unit_debug_errno(u
, l
, "Failed to unescape status text '%s': %m", value
);
3258 free_and_replace(s
->status_text
, t
);
3260 } else if (streq(key
, "accept-socket")) {
3263 if (u
->type
!= UNIT_SOCKET
) {
3264 log_unit_debug(u
, "Failed to deserialize accept-socket: unit is not a socket");
3268 r
= manager_load_unit(u
->manager
, value
, NULL
, NULL
, &socket
);
3270 log_unit_debug_errno(u
, r
, "Failed to load accept-socket unit '%s': %m", value
);
3272 unit_ref_set(&s
->accept_socket
, u
, socket
);
3273 SOCKET(socket
)->n_connections
++;
3276 } else if (streq(key
, "socket-fd")) {
3279 if ((fd
= parse_fd(value
)) < 0 || !fdset_contains(fds
, fd
))
3280 log_unit_debug(u
, "Failed to parse socket-fd value: %s", value
);
3282 asynchronous_close(s
->socket_fd
);
3283 s
->socket_fd
= fdset_remove(fds
, fd
);
3285 } else if (streq(key
, "fd-store-fd")) {
3286 _cleanup_free_
char *fdv
= NULL
, *fdn
= NULL
, *fdp
= NULL
;
3289 r
= extract_first_word(&value
, &fdv
, NULL
, 0);
3290 if (r
<= 0 || (fd
= parse_fd(fdv
)) < 0 || !fdset_contains(fds
, fd
)) {
3291 log_unit_debug(u
, "Failed to parse fd-store-fd value: %s", value
);
3295 r
= extract_first_word(&value
, &fdn
, NULL
, EXTRACT_CUNESCAPE
| EXTRACT_UNQUOTE
);
3297 log_unit_debug(u
, "Failed to parse fd-store-fd value: %s", value
);
3301 r
= extract_first_word(&value
, &fdp
, NULL
, 0);
3303 /* If the value is not present, we assume the default */
3305 } else if (r
< 0 || safe_atoi(fdp
, &do_poll
) < 0) {
3306 log_unit_debug_errno(u
, r
, "Failed to parse fd-store-fd value \"%s\": %m", value
);
3310 r
= fdset_remove(fds
, fd
);
3312 log_unit_error_errno(u
, r
, "Could not find deserialized fd %i in fdset: %m", fd
);
3317 r
= service_add_fd_store(s
, fd
, fdn
, do_poll
);
3319 log_unit_error_errno(u
, r
, "Failed to store deserialized fd %i: %m", fd
);
3322 } else if (streq(key
, "main-exec-status-pid")) {
3325 if (parse_pid(value
, &pid
) < 0)
3326 log_unit_debug(u
, "Failed to parse main-exec-status-pid value: %s", value
);
3328 s
->main_exec_status
.pid
= pid
;
3329 } else if (streq(key
, "main-exec-status-code")) {
3332 if (safe_atoi(value
, &i
) < 0)
3333 log_unit_debug(u
, "Failed to parse main-exec-status-code value: %s", value
);
3335 s
->main_exec_status
.code
= i
;
3336 } else if (streq(key
, "main-exec-status-status")) {
3339 if (safe_atoi(value
, &i
) < 0)
3340 log_unit_debug(u
, "Failed to parse main-exec-status-status value: %s", value
);
3342 s
->main_exec_status
.status
= i
;
3343 } else if (streq(key
, "main-exec-status-start"))
3344 deserialize_dual_timestamp(value
, &s
->main_exec_status
.start_timestamp
);
3345 else if (streq(key
, "main-exec-status-exit"))
3346 deserialize_dual_timestamp(value
, &s
->main_exec_status
.exit_timestamp
);
3347 else if (streq(key
, "notify-access-override")) {
3348 NotifyAccess notify_access
;
3350 notify_access
= notify_access_from_string(value
);
3351 if (notify_access
< 0)
3352 log_unit_debug(u
, "Failed to parse notify-access-override value: %s", value
);
3354 s
->notify_access_override
= notify_access
;
3355 } else if (streq(key
, "watchdog-timestamp"))
3356 deserialize_dual_timestamp(value
, &s
->watchdog_timestamp
);
3357 else if (streq(key
, "forbid-restart")) {
3360 b
= parse_boolean(value
);
3362 log_unit_debug(u
, "Failed to parse forbid-restart value: %s", value
);
3364 s
->forbid_restart
= b
;
3365 } else if (streq(key
, "stdin-fd")) {
3368 if ((fd
= parse_fd(value
)) < 0 || !fdset_contains(fds
, fd
))
3369 log_unit_debug(u
, "Failed to parse stdin-fd value: %s", value
);
3371 asynchronous_close(s
->stdin_fd
);
3372 s
->stdin_fd
= fdset_remove(fds
, fd
);
3373 s
->exec_context
.stdio_as_fds
= true;
3375 } else if (streq(key
, "stdout-fd")) {
3378 if ((fd
= parse_fd(value
)) < 0 || !fdset_contains(fds
, fd
))
3379 log_unit_debug(u
, "Failed to parse stdout-fd value: %s", value
);
3381 asynchronous_close(s
->stdout_fd
);
3382 s
->stdout_fd
= fdset_remove(fds
, fd
);
3383 s
->exec_context
.stdio_as_fds
= true;
3385 } else if (streq(key
, "stderr-fd")) {
3388 if ((fd
= parse_fd(value
)) < 0 || !fdset_contains(fds
, fd
))
3389 log_unit_debug(u
, "Failed to parse stderr-fd value: %s", value
);
3391 asynchronous_close(s
->stderr_fd
);
3392 s
->stderr_fd
= fdset_remove(fds
, fd
);
3393 s
->exec_context
.stdio_as_fds
= true;
3395 } else if (streq(key
, "exec-fd")) {
3398 if ((fd
= parse_fd(value
)) < 0 || !fdset_contains(fds
, fd
))
3399 log_unit_debug(u
, "Failed to parse exec-fd value: %s", value
);
3401 s
->exec_fd_event_source
= sd_event_source_disable_unref(s
->exec_fd_event_source
);
3403 fd
= fdset_remove(fds
, fd
);
3404 if (service_allocate_exec_fd_event_source(s
, fd
, &s
->exec_fd_event_source
) < 0)
3407 } else if (streq(key
, "watchdog-override-usec")) {
3408 if (deserialize_usec(value
, &s
->watchdog_override_usec
) < 0)
3409 log_unit_debug(u
, "Failed to parse watchdog_override_usec value: %s", value
);
3411 s
->watchdog_override_enable
= true;
3413 } else if (streq(key
, "watchdog-original-usec")) {
3414 if (deserialize_usec(value
, &s
->watchdog_original_usec
) < 0)
3415 log_unit_debug(u
, "Failed to parse watchdog_original_usec value: %s", value
);
3417 } else if (STR_IN_SET(key
, "main-command", "control-command")) {
3418 r
= service_deserialize_exec_command(u
, key
, value
);
3420 log_unit_debug_errno(u
, r
, "Failed to parse serialized command \"%s\": %m", value
);
3422 } else if (streq(key
, "n-restarts")) {
3423 r
= safe_atou(value
, &s
->n_restarts
);
3425 log_unit_debug_errno(u
, r
, "Failed to parse serialized restart counter '%s': %m", value
);
3427 } else if (streq(key
, "flush-n-restarts")) {
3428 r
= parse_boolean(value
);
3430 log_unit_debug_errno(u
, r
, "Failed to parse serialized flush restart counter setting '%s': %m", value
);
3432 s
->flush_n_restarts
= r
;
3433 } else if (streq(key
, "reload-begin-usec")) {
3434 r
= deserialize_usec(value
, &s
->reload_begin_usec
);
3436 log_unit_debug_errno(u
, r
, "Failed to parse serialized reload begin timestamp '%s', ignoring: %m", value
);
3438 log_unit_debug(u
, "Unknown serialization key: %s", key
);
3443 static UnitActiveState
service_active_state(Unit
*u
) {
3444 const UnitActiveState
*table
;
3448 table
= SERVICE(u
)->type
== SERVICE_IDLE
? state_translation_table_idle
: state_translation_table
;
3450 return table
[SERVICE(u
)->state
];
3453 static const char *service_sub_state_to_string(Unit
*u
) {
3456 return service_state_to_string(SERVICE(u
)->state
);
3459 static bool service_may_gc(Unit
*u
) {
3460 Service
*s
= SERVICE(u
);
3464 /* Never clean up services that still have a process around, even if the service is formally dead. Note that
3465 * unit_may_gc() already checked our cgroup for us, we just check our two additional PIDs, too, in case they
3466 * have moved outside of the cgroup. */
3468 if (main_pid_good(s
) > 0 ||
3469 control_pid_good(s
) > 0)
3472 /* Only allow collection of actually dead services, i.e. not those that are in the transitionary
3473 * SERVICE_DEAD_BEFORE_AUTO_RESTART/SERVICE_FAILED_BEFORE_AUTO_RESTART states. */
3474 if (!IN_SET(s
->state
, SERVICE_DEAD
, SERVICE_FAILED
, SERVICE_DEAD_RESOURCES_PINNED
))
3480 static int service_retry_pid_file(Service
*s
) {
3483 assert(s
->pid_file
);
3484 assert(IN_SET(s
->state
, SERVICE_START
, SERVICE_START_POST
));
3486 r
= service_load_pid_file(s
, false);
3490 service_unwatch_pid_file(s
);
3492 service_enter_running(s
, SERVICE_SUCCESS
);
3496 static int service_watch_pid_file(Service
*s
) {
3499 log_unit_debug(UNIT(s
), "Setting watch for PID file %s", s
->pid_file_pathspec
->path
);
3501 r
= path_spec_watch(s
->pid_file_pathspec
, service_dispatch_inotify_io
);
3503 log_unit_error_errno(UNIT(s
), r
, "Failed to set a watch for PID file %s: %m", s
->pid_file_pathspec
->path
);
3504 service_unwatch_pid_file(s
);
3508 /* the pidfile might have appeared just before we set the watch */
3509 log_unit_debug(UNIT(s
), "Trying to read PID file %s in case it changed", s
->pid_file_pathspec
->path
);
3510 service_retry_pid_file(s
);
3515 static int service_demand_pid_file(Service
*s
) {
3516 _cleanup_free_ PathSpec
*ps
= NULL
;
3518 assert(s
->pid_file
);
3519 assert(!s
->pid_file_pathspec
);
3521 ps
= new(PathSpec
, 1);
3527 .path
= strdup(s
->pid_file
),
3528 /* PATH_CHANGED would not be enough. There are daemons (sendmail) that keep their PID file
3529 * open all the time. */
3530 .type
= PATH_MODIFIED
,
3531 .inotify_fd
= -EBADF
,
3537 path_simplify(ps
->path
);
3539 s
->pid_file_pathspec
= TAKE_PTR(ps
);
3541 return service_watch_pid_file(s
);
3544 static int service_dispatch_inotify_io(sd_event_source
*source
, int fd
, uint32_t events
, void *userdata
) {
3545 PathSpec
*p
= ASSERT_PTR(userdata
);
3548 s
= SERVICE(p
->unit
);
3552 assert(IN_SET(s
->state
, SERVICE_START
, SERVICE_START_POST
));
3553 assert(s
->pid_file_pathspec
);
3554 assert(path_spec_owns_inotify_fd(s
->pid_file_pathspec
, fd
));
3556 log_unit_debug(UNIT(s
), "inotify event");
3558 if (path_spec_fd_event(p
, events
) < 0)
3561 if (service_retry_pid_file(s
) == 0)
3564 if (service_watch_pid_file(s
) < 0)
3570 service_unwatch_pid_file(s
);
3571 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_RESOURCES
);
3575 static int service_dispatch_exec_io(sd_event_source
*source
, int fd
, uint32_t events
, void *userdata
) {
3576 Service
*s
= SERVICE(userdata
);
3580 log_unit_debug(UNIT(s
), "got exec-fd event");
3582 /* If Type=exec is set, we'll consider a service started successfully the instant we invoked execve()
3583 * successfully for it. We implement this through a pipe() towards the child, which the kernel automatically
3584 * closes for us due to O_CLOEXEC on execve() in the child, which then triggers EOF on the pipe in the
3585 * parent. We need to be careful however, as there are other reasons that we might cause the child's side of
3586 * the pipe to be closed (for example, a simple exit()). To deal with that we'll ignore EOFs on the pipe unless
3587 * the child signalled us first that it is about to call the execve(). It does so by sending us a simple
3588 * non-zero byte via the pipe. We also provide the child with a way to inform us in case execve() failed: if it
3589 * sends a zero byte we'll ignore POLLHUP on the fd again. */
3595 n
= read(fd
, &x
, sizeof(x
));
3597 if (errno
== EAGAIN
) /* O_NONBLOCK in effect → everything queued has now been processed. */
3600 return log_unit_error_errno(UNIT(s
), errno
, "Failed to read from exec_fd: %m");
3602 if (n
== 0) { /* EOF → the event we are waiting for */
3604 s
->exec_fd_event_source
= sd_event_source_disable_unref(s
->exec_fd_event_source
);
3606 if (s
->exec_fd_hot
) { /* Did the child tell us to expect EOF now? */
3607 log_unit_debug(UNIT(s
), "Got EOF on exec-fd");
3609 s
->exec_fd_hot
= false;
3611 /* Nice! This is what we have been waiting for. Transition to next state. */
3612 if (s
->type
== SERVICE_EXEC
&& s
->state
== SERVICE_START
)
3613 service_enter_start_post(s
);
3615 log_unit_debug(UNIT(s
), "Got EOF on exec-fd while it was disabled, ignoring.");
3620 /* A byte was read → this turns on/off the exec fd logic */
3621 assert(n
== sizeof(x
));
3628 static void service_notify_cgroup_empty_event(Unit
*u
) {
3629 Service
*s
= SERVICE(u
);
3633 log_unit_debug(u
, "Control group is empty.");
3637 /* Waiting for SIGCHLD is usually more interesting, because it includes return
3638 * codes/signals. Which is why we ignore the cgroup events for most cases, except when we
3639 * don't know pid which to expect the SIGCHLD for. */
3642 if (IN_SET(s
->type
, SERVICE_NOTIFY
, SERVICE_NOTIFY_RELOAD
) &&
3643 main_pid_good(s
) == 0 &&
3644 control_pid_good(s
) == 0) {
3645 /* No chance of getting a ready notification anymore */
3646 service_enter_stop_post(s
, SERVICE_FAILURE_PROTOCOL
);
3650 if (s
->exit_type
== SERVICE_EXIT_CGROUP
&& main_pid_good(s
) <= 0)
3651 service_enter_start_post(s
);
3654 case SERVICE_START_POST
:
3655 if (s
->pid_file_pathspec
&&
3656 main_pid_good(s
) == 0 &&
3657 control_pid_good(s
) == 0) {
3659 /* Give up hoping for the daemon to write its PID file */
3660 log_unit_warning(u
, "Daemon never wrote its PID file. Failing.");
3662 service_unwatch_pid_file(s
);
3663 if (s
->state
== SERVICE_START
)
3664 service_enter_stop_post(s
, SERVICE_FAILURE_PROTOCOL
);
3666 service_enter_stop(s
, SERVICE_FAILURE_PROTOCOL
);
3670 case SERVICE_RUNNING
:
3671 /* service_enter_running() will figure out what to do */
3672 service_enter_running(s
, SERVICE_SUCCESS
);
3675 case SERVICE_STOP_WATCHDOG
:
3676 case SERVICE_STOP_SIGTERM
:
3677 case SERVICE_STOP_SIGKILL
:
3679 if (main_pid_good(s
) <= 0 && control_pid_good(s
) <= 0)
3680 service_enter_stop_post(s
, SERVICE_SUCCESS
);
3684 case SERVICE_STOP_POST
:
3685 case SERVICE_FINAL_WATCHDOG
:
3686 case SERVICE_FINAL_SIGTERM
:
3687 case SERVICE_FINAL_SIGKILL
:
3688 if (main_pid_good(s
) <= 0 && control_pid_good(s
) <= 0)
3689 service_enter_dead(s
, SERVICE_SUCCESS
, true);
3693 /* If the cgroup empty notification comes when the unit is not active, we must have failed to clean
3694 * up the cgroup earlier and should do it now. */
3695 case SERVICE_AUTO_RESTART
:
3696 case SERVICE_AUTO_RESTART_QUEUED
:
3697 unit_prune_cgroup(u
);
3705 static void service_notify_cgroup_oom_event(Unit
*u
, bool managed_oom
) {
3706 Service
*s
= SERVICE(u
);
3709 log_unit_debug(u
, "Process(es) of control group were killed by systemd-oomd.");
3711 log_unit_debug(u
, "Process of control group was killed by the OOM killer.");
3713 if (s
->oom_policy
== OOM_CONTINUE
)
3718 case SERVICE_CONDITION
:
3719 case SERVICE_START_PRE
:
3721 case SERVICE_START_POST
:
3723 if (s
->oom_policy
== OOM_STOP
)
3724 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_OOM_KILL
);
3725 else if (s
->oom_policy
== OOM_KILL
)
3726 service_enter_signal(s
, SERVICE_STOP_SIGKILL
, SERVICE_FAILURE_OOM_KILL
);
3730 case SERVICE_EXITED
:
3731 case SERVICE_RUNNING
:
3732 if (s
->oom_policy
== OOM_STOP
)
3733 service_enter_stop(s
, SERVICE_FAILURE_OOM_KILL
);
3734 else if (s
->oom_policy
== OOM_KILL
)
3735 service_enter_signal(s
, SERVICE_STOP_SIGKILL
, SERVICE_FAILURE_OOM_KILL
);
3739 case SERVICE_STOP_WATCHDOG
:
3740 case SERVICE_STOP_SIGTERM
:
3741 service_enter_signal(s
, SERVICE_STOP_SIGKILL
, SERVICE_FAILURE_OOM_KILL
);
3744 case SERVICE_STOP_SIGKILL
:
3745 case SERVICE_FINAL_SIGKILL
:
3746 if (s
->result
== SERVICE_SUCCESS
)
3747 s
->result
= SERVICE_FAILURE_OOM_KILL
;
3750 case SERVICE_STOP_POST
:
3751 case SERVICE_FINAL_SIGTERM
:
3752 service_enter_signal(s
, SERVICE_FINAL_SIGKILL
, SERVICE_FAILURE_OOM_KILL
);
3760 static void service_sigchld_event(Unit
*u
, pid_t pid
, int code
, int status
) {
3761 bool notify_dbus
= true;
3762 Service
*s
= SERVICE(u
);
3764 ExitClean clean_mode
;
3769 /* Oneshot services and non-SERVICE_EXEC_START commands should not be
3770 * considered daemons as they are typically not long running. */
3771 if (s
->type
== SERVICE_ONESHOT
|| (s
->control_pid
.pid
== pid
&& s
->control_command_id
!= SERVICE_EXEC_START
))
3772 clean_mode
= EXIT_CLEAN_COMMAND
;
3774 clean_mode
= EXIT_CLEAN_DAEMON
;
3776 if (is_clean_exit(code
, status
, clean_mode
, &s
->success_status
))
3777 f
= SERVICE_SUCCESS
;
3778 else if (code
== CLD_EXITED
)
3779 f
= SERVICE_FAILURE_EXIT_CODE
;
3780 else if (code
== CLD_KILLED
)
3781 f
= SERVICE_FAILURE_SIGNAL
;
3782 else if (code
== CLD_DUMPED
)
3783 f
= SERVICE_FAILURE_CORE_DUMP
;
3785 assert_not_reached();
3787 if (s
->main_pid
.pid
== pid
) {
3788 /* Clean up the exec_fd event source. We want to do this here, not later in
3789 * service_set_state(), because service_enter_stop_post() calls service_spawn().
3790 * The source owns its end of the pipe, so this will close that too. */
3791 s
->exec_fd_event_source
= sd_event_source_disable_unref(s
->exec_fd_event_source
);
3793 /* Forking services may occasionally move to a new PID.
3794 * As long as they update the PID file before exiting the old
3795 * PID, they're fine. */
3796 if (service_load_pid_file(s
, false) > 0)
3799 pidref_done(&s
->main_pid
);
3800 exec_status_exit(&s
->main_exec_status
, &s
->exec_context
, pid
, code
, status
);
3802 if (s
->main_command
) {
3803 /* If this is not a forking service than the
3804 * main process got started and hence we copy
3805 * the exit status so that it is recorded both
3806 * as main and as control process exit
3809 s
->main_command
->exec_status
= s
->main_exec_status
;
3811 if (s
->main_command
->flags
& EXEC_COMMAND_IGNORE_FAILURE
)
3812 f
= SERVICE_SUCCESS
;
3813 } else if (s
->exec_command
[SERVICE_EXEC_START
]) {
3815 /* If this is a forked process, then we should
3816 * ignore the return value if this was
3817 * configured for the starter process */
3819 if (s
->exec_command
[SERVICE_EXEC_START
]->flags
& EXEC_COMMAND_IGNORE_FAILURE
)
3820 f
= SERVICE_SUCCESS
;
3823 unit_log_process_exit(
3826 service_exec_command_to_string(SERVICE_EXEC_START
),
3827 f
== SERVICE_SUCCESS
,
3830 if (s
->result
== SERVICE_SUCCESS
)
3833 if (s
->main_command
&&
3834 s
->main_command
->command_next
&&
3835 s
->type
== SERVICE_ONESHOT
&&
3836 f
== SERVICE_SUCCESS
) {
3838 /* There is another command to execute, so let's do that. */
3840 log_unit_debug(u
, "Running next main command for state %s.", service_state_to_string(s
->state
));
3841 service_run_next_main(s
);
3844 s
->main_command
= NULL
;
3846 /* Services with ExitType=cgroup do not act on main PID exiting, unless the cgroup is
3848 if (s
->exit_type
== SERVICE_EXIT_MAIN
|| cgroup_good(s
) <= 0) {
3849 /* The service exited, so the service is officially gone. */
3852 case SERVICE_START_POST
:
3853 case SERVICE_RELOAD
:
3854 case SERVICE_RELOAD_SIGNAL
:
3855 case SERVICE_RELOAD_NOTIFY
:
3856 /* If neither main nor control processes are running then the current
3857 * state can never exit cleanly, hence immediately terminate the
3859 if (control_pid_good(s
) <= 0)
3860 service_enter_stop(s
, f
);
3862 /* Otherwise need to wait until the operation is done. */
3866 /* Need to wait until the operation is done. */
3870 if (s
->type
== SERVICE_ONESHOT
) {
3871 /* This was our main goal, so let's go on */
3872 if (f
== SERVICE_SUCCESS
)
3873 service_enter_start_post(s
);
3875 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
3877 } else if (IN_SET(s
->type
, SERVICE_NOTIFY
, SERVICE_NOTIFY_RELOAD
)) {
3878 /* Only enter running through a notification, so that the
3879 * SERVICE_START state signifies that no ready notification
3880 * has been received */
3881 if (f
!= SERVICE_SUCCESS
)
3882 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
3883 else if (!s
->remain_after_exit
|| service_get_notify_access(s
) == NOTIFY_MAIN
)
3884 /* The service has never been and will never be active */
3885 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_PROTOCOL
);
3890 case SERVICE_RUNNING
:
3891 service_enter_running(s
, f
);
3894 case SERVICE_STOP_WATCHDOG
:
3895 case SERVICE_STOP_SIGTERM
:
3896 case SERVICE_STOP_SIGKILL
:
3898 if (control_pid_good(s
) <= 0)
3899 service_enter_stop_post(s
, f
);
3901 /* If there is still a control process, wait for that first */
3904 case SERVICE_STOP_POST
:
3906 if (control_pid_good(s
) <= 0)
3907 service_enter_signal(s
, SERVICE_FINAL_SIGTERM
, f
);
3911 case SERVICE_FINAL_WATCHDOG
:
3912 case SERVICE_FINAL_SIGTERM
:
3913 case SERVICE_FINAL_SIGKILL
:
3915 if (control_pid_good(s
) <= 0)
3916 service_enter_dead(s
, f
, true);
3920 assert_not_reached();
3922 } else if (s
->exit_type
== SERVICE_EXIT_CGROUP
&& s
->state
== SERVICE_START
)
3923 /* If a main process exits very quickly, this function might be executed
3924 * before service_dispatch_exec_io(). Since this function disabled IO events
3925 * to monitor the main process above, we need to update the state here too.
3926 * Let's consider the process is successfully launched and exited. */
3927 service_enter_start_post(s
);
3930 } else if (s
->control_pid
.pid
== pid
) {
3934 pidref_done(&s
->control_pid
);
3936 if (s
->control_command
) {
3937 exec_status_exit(&s
->control_command
->exec_status
, &s
->exec_context
, pid
, code
, status
);
3939 if (s
->control_command
->flags
& EXEC_COMMAND_IGNORE_FAILURE
)
3940 f
= SERVICE_SUCCESS
;
3943 /* ExecCondition= calls that exit with (0, 254] should invoke skip-like behavior instead of failing */
3944 if (s
->state
== SERVICE_CONDITION
) {
3945 if (f
== SERVICE_FAILURE_EXIT_CODE
&& status
< 255) {
3946 UNIT(s
)->condition_result
= false;
3947 f
= SERVICE_SKIP_CONDITION
;
3949 } else if (f
== SERVICE_SUCCESS
) {
3950 UNIT(s
)->condition_result
= true;
3955 kind
= "Condition check process";
3957 kind
= "Control process";
3958 success
= f
== SERVICE_SUCCESS
;
3961 unit_log_process_exit(
3964 service_exec_command_to_string(s
->control_command_id
),
3968 if (s
->state
!= SERVICE_RELOAD
&& s
->result
== SERVICE_SUCCESS
)
3971 if (s
->control_command
&&
3972 s
->control_command
->command_next
&&
3973 f
== SERVICE_SUCCESS
) {
3975 /* There is another command to * execute, so let's do that. */
3977 log_unit_debug(u
, "Running next control command for state %s.", service_state_to_string(s
->state
));
3978 service_run_next_control(s
);
3981 /* No further commands for this step, so let's figure out what to do next */
3983 s
->control_command
= NULL
;
3984 s
->control_command_id
= _SERVICE_EXEC_COMMAND_INVALID
;
3986 log_unit_debug(u
, "Got final SIGCHLD for state %s.", service_state_to_string(s
->state
));
3990 case SERVICE_CONDITION
:
3991 if (f
== SERVICE_SUCCESS
)
3992 service_enter_start_pre(s
);
3994 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
3997 case SERVICE_START_PRE
:
3998 if (f
== SERVICE_SUCCESS
)
3999 service_enter_start(s
);
4001 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
4005 if (s
->type
!= SERVICE_FORKING
)
4006 /* Maybe spurious event due to a reload that changed the type? */
4009 if (f
!= SERVICE_SUCCESS
) {
4010 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
4015 bool has_start_post
;
4018 /* Let's try to load the pid file here if we can.
4019 * The PID file might actually be created by a START_POST
4020 * script. In that case don't worry if the loading fails. */
4022 has_start_post
= s
->exec_command
[SERVICE_EXEC_START_POST
];
4023 r
= service_load_pid_file(s
, !has_start_post
);
4024 if (!has_start_post
&& r
< 0) {
4025 r
= service_demand_pid_file(s
);
4026 if (r
< 0 || cgroup_good(s
) == 0)
4027 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_PROTOCOL
);
4031 service_search_main_pid(s
);
4033 service_enter_start_post(s
);
4036 case SERVICE_START_POST
:
4037 if (f
!= SERVICE_SUCCESS
) {
4038 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
4045 r
= service_load_pid_file(s
, true);
4047 r
= service_demand_pid_file(s
);
4048 if (r
< 0 || cgroup_good(s
) == 0)
4049 service_enter_stop(s
, SERVICE_FAILURE_PROTOCOL
);
4053 service_search_main_pid(s
);
4055 service_enter_running(s
, SERVICE_SUCCESS
);
4058 case SERVICE_RELOAD
:
4059 case SERVICE_RELOAD_SIGNAL
:
4060 case SERVICE_RELOAD_NOTIFY
:
4061 if (f
== SERVICE_SUCCESS
)
4062 if (service_load_pid_file(s
, true) < 0)
4063 service_search_main_pid(s
);
4065 s
->reload_result
= f
;
4067 /* If the last notification we received from the service process indicates
4068 * we are still reloading, then don't leave reloading state just yet, just
4069 * transition into SERVICE_RELOAD_NOTIFY, to wait for the READY=1 coming,
4071 if (s
->notify_state
== NOTIFY_RELOADING
)
4072 service_set_state(s
, SERVICE_RELOAD_NOTIFY
);
4074 service_enter_running(s
, SERVICE_SUCCESS
);
4078 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
4081 case SERVICE_STOP_WATCHDOG
:
4082 case SERVICE_STOP_SIGTERM
:
4083 case SERVICE_STOP_SIGKILL
:
4084 if (main_pid_good(s
) <= 0)
4085 service_enter_stop_post(s
, f
);
4087 /* If there is still a service process around, wait until
4088 * that one quit, too */
4091 case SERVICE_STOP_POST
:
4092 if (main_pid_good(s
) <= 0)
4093 service_enter_signal(s
, SERVICE_FINAL_SIGTERM
, f
);
4096 case SERVICE_FINAL_WATCHDOG
:
4097 case SERVICE_FINAL_SIGTERM
:
4098 case SERVICE_FINAL_SIGKILL
:
4099 if (main_pid_good(s
) <= 0)
4100 service_enter_dead(s
, f
, true);
4103 case SERVICE_CLEANING
:
4105 if (s
->clean_result
== SERVICE_SUCCESS
)
4106 s
->clean_result
= f
;
4108 service_enter_dead(s
, SERVICE_SUCCESS
, false);
4112 assert_not_reached();
4115 } else /* Neither control nor main PID? If so, don't notify about anything */
4116 notify_dbus
= false;
4118 /* Notify clients about changed exit status */
4120 unit_add_to_dbus_queue(u
);
4122 /* We watch the main/control process otherwise we can't retrieve the unit they
4123 * belong to with cgroupv1. But if they are not our direct child, we won't get a
4124 * SIGCHLD for them. Therefore we need to look for others to watch so we can
4125 * detect when the cgroup becomes empty. Note that the control process is always
4126 * our child so it's pointless to watch all other processes. */
4127 if (!control_pid_good(s
))
4128 if (!s
->main_pid_known
|| s
->main_pid_alien
)
4129 (void) unit_enqueue_rewatch_pids(u
);
4132 static int service_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
) {
4133 Service
*s
= SERVICE(userdata
);
4136 assert(source
== s
->timer_event_source
);
4140 case SERVICE_CONDITION
:
4141 case SERVICE_START_PRE
:
4143 case SERVICE_START_POST
:
4144 switch (s
->timeout_start_failure_mode
) {
4146 case SERVICE_TIMEOUT_TERMINATE
:
4147 log_unit_warning(UNIT(s
), "%s operation timed out. Terminating.", service_state_to_string(s
->state
));
4148 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_TIMEOUT
);
4151 case SERVICE_TIMEOUT_ABORT
:
4152 log_unit_warning(UNIT(s
), "%s operation timed out. Aborting.", service_state_to_string(s
->state
));
4153 service_enter_signal(s
, SERVICE_STOP_WATCHDOG
, SERVICE_FAILURE_TIMEOUT
);
4156 case SERVICE_TIMEOUT_KILL
:
4157 if (s
->kill_context
.send_sigkill
) {
4158 log_unit_warning(UNIT(s
), "%s operation timed out. Killing.", service_state_to_string(s
->state
));
4159 service_enter_signal(s
, SERVICE_STOP_SIGKILL
, SERVICE_FAILURE_TIMEOUT
);
4161 log_unit_warning(UNIT(s
), "%s operation timed out. Skipping SIGKILL.", service_state_to_string(s
->state
));
4162 service_enter_stop_post(s
, SERVICE_FAILURE_TIMEOUT
);
4167 assert_not_reached();
4171 case SERVICE_RUNNING
:
4172 log_unit_warning(UNIT(s
), "Service reached runtime time limit. Stopping.");
4173 service_enter_stop(s
, SERVICE_FAILURE_TIMEOUT
);
4176 case SERVICE_RELOAD
:
4177 case SERVICE_RELOAD_SIGNAL
:
4178 case SERVICE_RELOAD_NOTIFY
:
4179 log_unit_warning(UNIT(s
), "Reload operation timed out. Killing reload process.");
4180 service_kill_control_process(s
);
4181 s
->reload_result
= SERVICE_FAILURE_TIMEOUT
;
4182 service_enter_running(s
, SERVICE_SUCCESS
);
4186 switch (s
->timeout_stop_failure_mode
) {
4188 case SERVICE_TIMEOUT_TERMINATE
:
4189 log_unit_warning(UNIT(s
), "Stopping timed out. Terminating.");
4190 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_TIMEOUT
);
4193 case SERVICE_TIMEOUT_ABORT
:
4194 log_unit_warning(UNIT(s
), "Stopping timed out. Aborting.");
4195 service_enter_signal(s
, SERVICE_STOP_WATCHDOG
, SERVICE_FAILURE_TIMEOUT
);
4198 case SERVICE_TIMEOUT_KILL
:
4199 if (s
->kill_context
.send_sigkill
) {
4200 log_unit_warning(UNIT(s
), "Stopping timed out. Killing.");
4201 service_enter_signal(s
, SERVICE_STOP_SIGKILL
, SERVICE_FAILURE_TIMEOUT
);
4203 log_unit_warning(UNIT(s
), "Stopping timed out. Skipping SIGKILL.");
4204 service_enter_stop_post(s
, SERVICE_FAILURE_TIMEOUT
);
4209 assert_not_reached();
4213 case SERVICE_STOP_WATCHDOG
:
4214 if (s
->kill_context
.send_sigkill
) {
4215 log_unit_warning(UNIT(s
), "State 'stop-watchdog' timed out. Killing.");
4216 service_enter_signal(s
, SERVICE_STOP_SIGKILL
, SERVICE_FAILURE_TIMEOUT
);
4218 log_unit_warning(UNIT(s
), "State 'stop-watchdog' timed out. Skipping SIGKILL.");
4219 service_enter_stop_post(s
, SERVICE_FAILURE_TIMEOUT
);
4223 case SERVICE_STOP_SIGTERM
:
4224 if (s
->timeout_stop_failure_mode
== SERVICE_TIMEOUT_ABORT
) {
4225 log_unit_warning(UNIT(s
), "State 'stop-sigterm' timed out. Aborting.");
4226 service_enter_signal(s
, SERVICE_STOP_WATCHDOG
, SERVICE_FAILURE_TIMEOUT
);
4227 } else if (s
->kill_context
.send_sigkill
) {
4228 log_unit_warning(UNIT(s
), "State 'stop-sigterm' timed out. Killing.");
4229 service_enter_signal(s
, SERVICE_STOP_SIGKILL
, SERVICE_FAILURE_TIMEOUT
);
4231 log_unit_warning(UNIT(s
), "State 'stop-sigterm' timed out. Skipping SIGKILL.");
4232 service_enter_stop_post(s
, SERVICE_FAILURE_TIMEOUT
);
4237 case SERVICE_STOP_SIGKILL
:
4238 /* Uh, we sent a SIGKILL and it is still not gone?
4239 * Must be something we cannot kill, so let's just be
4240 * weirded out and continue */
4242 log_unit_warning(UNIT(s
), "Processes still around after SIGKILL. Ignoring.");
4243 service_enter_stop_post(s
, SERVICE_FAILURE_TIMEOUT
);
4246 case SERVICE_STOP_POST
:
4247 switch (s
->timeout_stop_failure_mode
) {
4249 case SERVICE_TIMEOUT_TERMINATE
:
4250 log_unit_warning(UNIT(s
), "State 'stop-post' timed out. Terminating.");
4251 service_enter_signal(s
, SERVICE_FINAL_SIGTERM
, SERVICE_FAILURE_TIMEOUT
);
4254 case SERVICE_TIMEOUT_ABORT
:
4255 log_unit_warning(UNIT(s
), "State 'stop-post' timed out. Aborting.");
4256 service_enter_signal(s
, SERVICE_FINAL_WATCHDOG
, SERVICE_FAILURE_TIMEOUT
);
4259 case SERVICE_TIMEOUT_KILL
:
4260 if (s
->kill_context
.send_sigkill
) {
4261 log_unit_warning(UNIT(s
), "State 'stop-post' timed out. Killing.");
4262 service_enter_signal(s
, SERVICE_FINAL_SIGKILL
, SERVICE_FAILURE_TIMEOUT
);
4264 log_unit_warning(UNIT(s
), "State 'stop-post' timed out. Skipping SIGKILL. Entering failed mode.");
4265 service_enter_dead(s
, SERVICE_FAILURE_TIMEOUT
, false);
4270 assert_not_reached();
4274 case SERVICE_FINAL_WATCHDOG
:
4275 if (s
->kill_context
.send_sigkill
) {
4276 log_unit_warning(UNIT(s
), "State 'final-watchdog' timed out. Killing.");
4277 service_enter_signal(s
, SERVICE_FINAL_SIGKILL
, SERVICE_FAILURE_TIMEOUT
);
4279 log_unit_warning(UNIT(s
), "State 'final-watchdog' timed out. Skipping SIGKILL. Entering failed mode.");
4280 service_enter_dead(s
, SERVICE_FAILURE_TIMEOUT
, false);
4284 case SERVICE_FINAL_SIGTERM
:
4285 if (s
->timeout_stop_failure_mode
== SERVICE_TIMEOUT_ABORT
) {
4286 log_unit_warning(UNIT(s
), "State 'final-sigterm' timed out. Aborting.");
4287 service_enter_signal(s
, SERVICE_FINAL_WATCHDOG
, SERVICE_FAILURE_TIMEOUT
);
4288 } else if (s
->kill_context
.send_sigkill
) {
4289 log_unit_warning(UNIT(s
), "State 'final-sigterm' timed out. Killing.");
4290 service_enter_signal(s
, SERVICE_FINAL_SIGKILL
, SERVICE_FAILURE_TIMEOUT
);
4292 log_unit_warning(UNIT(s
), "State 'final-sigterm' timed out. Skipping SIGKILL. Entering failed mode.");
4293 service_enter_dead(s
, SERVICE_FAILURE_TIMEOUT
, false);
4298 case SERVICE_FINAL_SIGKILL
:
4299 log_unit_warning(UNIT(s
), "Processes still around after final SIGKILL. Entering failed mode.");
4300 service_enter_dead(s
, SERVICE_FAILURE_TIMEOUT
, true);
4303 case SERVICE_AUTO_RESTART
:
4304 if (s
->restart_usec
> 0)
4305 log_unit_debug(UNIT(s
),
4306 "Service restart interval %s expired, scheduling restart.",
4307 FORMAT_TIMESPAN(service_restart_usec_next(s
), USEC_PER_SEC
));
4309 log_unit_debug(UNIT(s
),
4310 "Service has no hold-off time (RestartSec=0), scheduling restart.");
4312 service_enter_restart(s
);
4315 case SERVICE_CLEANING
:
4316 log_unit_warning(UNIT(s
), "Cleaning timed out. killing.");
4318 if (s
->clean_result
== SERVICE_SUCCESS
)
4319 s
->clean_result
= SERVICE_FAILURE_TIMEOUT
;
4321 service_enter_signal(s
, SERVICE_FINAL_SIGKILL
, 0);
4325 assert_not_reached();
4331 static int service_dispatch_watchdog(sd_event_source
*source
, usec_t usec
, void *userdata
) {
4332 Service
*s
= SERVICE(userdata
);
4333 usec_t watchdog_usec
;
4336 assert(source
== s
->watchdog_event_source
);
4338 watchdog_usec
= service_get_watchdog_usec(s
);
4340 if (UNIT(s
)->manager
->service_watchdogs
) {
4341 log_unit_error(UNIT(s
), "Watchdog timeout (limit %s)!",
4342 FORMAT_TIMESPAN(watchdog_usec
, 1));
4344 service_enter_signal(s
, SERVICE_STOP_WATCHDOG
, SERVICE_FAILURE_WATCHDOG
);
4346 log_unit_warning(UNIT(s
), "Watchdog disabled! Ignoring watchdog timeout (limit %s)!",
4347 FORMAT_TIMESPAN(watchdog_usec
, 1));
4352 static bool service_notify_message_authorized(Service
*s
, pid_t pid
, FDSet
*fds
) {
4355 NotifyAccess notify_access
= service_get_notify_access(s
);
4357 if (notify_access
== NOTIFY_NONE
) {
4358 log_unit_warning(UNIT(s
), "Got notification message from PID "PID_FMT
", but reception is disabled.", pid
);
4362 if (notify_access
== NOTIFY_MAIN
&& pid
!= s
->main_pid
.pid
) {
4363 if (pidref_is_set(&s
->main_pid
))
4364 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
);
4366 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
);
4371 if (notify_access
== NOTIFY_EXEC
&& pid
!= s
->main_pid
.pid
&& pid
!= s
->control_pid
.pid
) {
4372 if (pidref_is_set(&s
->main_pid
) && pidref_is_set(&s
->control_pid
))
4373 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
,
4374 pid
, s
->main_pid
.pid
, s
->control_pid
.pid
);
4375 else if (pidref_is_set(&s
->main_pid
))
4376 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
);
4377 else if (pidref_is_set(&s
->control_pid
))
4378 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
);
4380 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
);
4388 static void service_force_watchdog(Service
*s
) {
4389 if (!UNIT(s
)->manager
->service_watchdogs
)
4392 log_unit_error(UNIT(s
), "Watchdog request (last status: %s)!",
4393 s
->status_text
?: "<unset>");
4395 service_enter_signal(s
, SERVICE_STOP_WATCHDOG
, SERVICE_FAILURE_WATCHDOG
);
4398 static void service_notify_message(
4400 const struct ucred
*ucred
,
4404 Service
*s
= SERVICE(u
);
4405 bool notify_dbus
= false;
4406 usec_t monotonic_usec
= USEC_INFINITY
;
4413 if (!service_notify_message_authorized(s
, ucred
->pid
, fds
))
4416 if (DEBUG_LOGGING
) {
4417 _cleanup_free_
char *cc
= NULL
;
4419 cc
= strv_join(tags
, ", ");
4420 log_unit_debug(u
, "Got notification message from PID "PID_FMT
" (%s)", ucred
->pid
, empty_to_na(cc
));
4423 /* Interpret MAINPID= */
4424 e
= strv_find_startswith(tags
, "MAINPID=");
4425 if (e
&& IN_SET(s
->state
, SERVICE_START
, SERVICE_START_POST
, SERVICE_RUNNING
, SERVICE_RELOAD
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
)) {
4428 if (parse_pid(e
, &new_main_pid
) < 0)
4429 log_unit_warning(u
, "Failed to parse MAINPID= field in notification message, ignoring: %s", e
);
4430 else if (!s
->main_pid_known
|| new_main_pid
!= s
->main_pid
.pid
) {
4432 r
= service_is_suitable_main_pid(s
, new_main_pid
, LOG_WARNING
);
4434 /* The new main PID is a bit suspicious, which is OK if the sender is privileged. */
4436 if (ucred
->uid
== 0) {
4437 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
);
4440 log_unit_debug(u
, "New main PID "PID_FMT
" does not belong to service, refusing.", new_main_pid
);
4443 (void) service_set_main_pid(s
, new_main_pid
);
4445 r
= unit_watch_pid(UNIT(s
), new_main_pid
, /* exclusive= */ false);
4447 log_unit_warning_errno(UNIT(s
), r
, "Failed to watch new main PID "PID_FMT
" for service: %m", new_main_pid
);
4454 /* Parse MONOTONIC_USEC= */
4455 e
= strv_find_startswith(tags
, "MONOTONIC_USEC=");
4457 r
= safe_atou64(e
, &monotonic_usec
);
4459 log_unit_warning_errno(u
, r
, "Failed to parse MONOTONIC_USEC= field in notification message, ignoring: %s", e
);
4462 /* Interpret READY=/STOPPING=/RELOADING=. STOPPING= wins over the others, and READY= over RELOADING= */
4463 if (strv_contains(tags
, "STOPPING=1")) {
4464 s
->notify_state
= NOTIFY_STOPPING
;
4466 if (IN_SET(s
->state
, SERVICE_RUNNING
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
))
4467 service_enter_stop_by_notify(s
);
4471 } else if (strv_contains(tags
, "READY=1")) {
4473 s
->notify_state
= NOTIFY_READY
;
4475 /* Type=notify services inform us about completed initialization with READY=1 */
4476 if (IN_SET(s
->type
, SERVICE_NOTIFY
, SERVICE_NOTIFY_RELOAD
) &&
4477 s
->state
== SERVICE_START
)
4478 service_enter_start_post(s
);
4480 /* Sending READY=1 while we are reloading informs us that the reloading is complete. */
4481 if (s
->state
== SERVICE_RELOAD_NOTIFY
)
4482 service_enter_running(s
, SERVICE_SUCCESS
);
4484 /* Combined RELOADING=1 and READY=1? Then this is indication that the service started and
4485 * immediately finished reloading. */
4486 if (s
->state
== SERVICE_RELOAD_SIGNAL
&&
4487 strv_contains(tags
, "RELOADING=1") &&
4488 monotonic_usec
!= USEC_INFINITY
&&
4489 monotonic_usec
>= s
->reload_begin_usec
) {
4490 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
4492 /* Propagate a reload explicitly */
4493 r
= manager_propagate_reload(UNIT(s
)->manager
, UNIT(s
), JOB_FAIL
, &error
);
4495 log_unit_warning(UNIT(s
), "Failed to schedule propagation of reload, ignoring: %s", bus_error_message(&error
, r
));
4497 service_enter_running(s
, SERVICE_SUCCESS
);
4502 } else if (strv_contains(tags
, "RELOADING=1")) {
4504 s
->notify_state
= NOTIFY_RELOADING
;
4506 /* Sending RELOADING=1 after we send SIGHUP to request a reload will transition
4507 * things to "reload-notify" state, where we'll wait for READY=1 to let us know the
4508 * reload is done. Note that we insist on a timestamp being sent along here, so that
4509 * we know for sure this is a reload cycle initiated *after* we sent the signal */
4510 if (s
->state
== SERVICE_RELOAD_SIGNAL
&&
4511 monotonic_usec
!= USEC_INFINITY
&&
4512 monotonic_usec
>= s
->reload_begin_usec
)
4513 /* Note, we don't call service_enter_reload_by_notify() here, because we
4514 * don't need reload propagation nor do we want to restart the time-out. */
4515 service_set_state(s
, SERVICE_RELOAD_NOTIFY
);
4517 if (s
->state
== SERVICE_RUNNING
)
4518 service_enter_reload_by_notify(s
);
4523 /* Interpret STATUS= */
4524 e
= strv_find_startswith(tags
, "STATUS=");
4526 _cleanup_free_
char *t
= NULL
;
4529 /* Note that this size limit check is mostly paranoia: since the datagram size we are willing
4530 * to process is already limited to NOTIFY_BUFFER_MAX, this limit here should never be hit. */
4531 if (strlen(e
) > STATUS_TEXT_MAX
)
4532 log_unit_warning(u
, "Status message overly long (%zu > %u), ignoring.", strlen(e
), STATUS_TEXT_MAX
);
4533 else if (!utf8_is_valid(e
))
4534 log_unit_warning(u
, "Status message in notification message is not UTF-8 clean, ignoring.");
4542 if (!streq_ptr(s
->status_text
, t
)) {
4543 free_and_replace(s
->status_text
, t
);
4548 /* Interpret NOTIFYACCESS= */
4549 e
= strv_find_startswith(tags
, "NOTIFYACCESS=");
4551 NotifyAccess notify_access
;
4553 notify_access
= notify_access_from_string(e
);
4554 if (notify_access
< 0)
4555 log_unit_warning_errno(u
, notify_access
,
4556 "Failed to parse NOTIFYACCESS= field value '%s' in notification message, ignoring: %m", e
);
4558 /* We don't need to check whether the new access mode is more strict than what is
4559 * already in use, since only the privileged process is allowed to change it
4560 * in the first place. */
4561 if (service_get_notify_access(s
) != notify_access
) {
4562 service_override_notify_access(s
, notify_access
);
4567 /* Interpret ERRNO= */
4568 e
= strv_find_startswith(tags
, "ERRNO=");
4572 status_errno
= parse_errno(e
);
4573 if (status_errno
< 0)
4574 log_unit_warning_errno(u
, status_errno
,
4575 "Failed to parse ERRNO= field value '%s' in notification message: %m", e
);
4576 else if (s
->status_errno
!= status_errno
) {
4577 s
->status_errno
= status_errno
;
4582 /* Interpret EXTEND_TIMEOUT= */
4583 e
= strv_find_startswith(tags
, "EXTEND_TIMEOUT_USEC=");
4585 usec_t extend_timeout_usec
;
4586 if (safe_atou64(e
, &extend_timeout_usec
) < 0)
4587 log_unit_warning(u
, "Failed to parse EXTEND_TIMEOUT_USEC=%s", e
);
4589 service_extend_timeout(s
, extend_timeout_usec
);
4592 /* Interpret WATCHDOG= */
4593 e
= strv_find_startswith(tags
, "WATCHDOG=");
4596 service_reset_watchdog(s
);
4597 else if (streq(e
, "trigger"))
4598 service_force_watchdog(s
);
4600 log_unit_warning(u
, "Passed WATCHDOG= field is invalid, ignoring.");
4603 e
= strv_find_startswith(tags
, "WATCHDOG_USEC=");
4605 usec_t watchdog_override_usec
;
4606 if (safe_atou64(e
, &watchdog_override_usec
) < 0)
4607 log_unit_warning(u
, "Failed to parse WATCHDOG_USEC=%s", e
);
4609 service_override_watchdog_timeout(s
, watchdog_override_usec
);
4612 /* Process FD store messages. Either FDSTOREREMOVE=1 for removal, or FDSTORE=1 for addition. In both cases,
4613 * process FDNAME= for picking the file descriptor name to use. Note that FDNAME= is required when removing
4614 * fds, but optional when pushing in new fds, for compatibility reasons. */
4615 if (strv_contains(tags
, "FDSTOREREMOVE=1")) {
4618 name
= strv_find_startswith(tags
, "FDNAME=");
4619 if (!name
|| !fdname_is_valid(name
))
4620 log_unit_warning(u
, "FDSTOREREMOVE=1 requested, but no valid file descriptor name passed, ignoring.");
4622 service_remove_fd_store(s
, name
);
4624 } else if (strv_contains(tags
, "FDSTORE=1")) {
4627 name
= strv_find_startswith(tags
, "FDNAME=");
4628 if (name
&& !fdname_is_valid(name
)) {
4629 log_unit_warning(u
, "Passed FDNAME= name is invalid, ignoring.");
4633 (void) service_add_fd_store_set(s
, fds
, name
, !strv_contains(tags
, "FDPOLL=0"));
4636 /* Notify clients about changed status or main pid */
4638 unit_add_to_dbus_queue(u
);
4641 static int service_get_timeout(Unit
*u
, usec_t
*timeout
) {
4642 Service
*s
= SERVICE(u
);
4646 if (!s
->timer_event_source
)
4649 r
= sd_event_source_get_time(s
->timer_event_source
, &t
);
4652 if (t
== USEC_INFINITY
)
4659 static usec_t
service_get_timeout_start_usec(Unit
*u
) {
4660 Service
*s
= SERVICE(ASSERT_PTR(u
));
4661 return s
->timeout_start_usec
;
4664 static bool pick_up_pid_from_bus_name(Service
*s
) {
4667 /* If the service is running but we have no main PID yet, get it from the owner of the D-Bus name */
4669 return !pidref_is_set(&s
->main_pid
) &&
4675 SERVICE_RELOAD_SIGNAL
,
4676 SERVICE_RELOAD_NOTIFY
);
4679 static int bus_name_pid_lookup_callback(sd_bus_message
*reply
, void *userdata
, sd_bus_error
*ret_error
) {
4680 const sd_bus_error
*e
;
4681 Unit
*u
= ASSERT_PTR(userdata
);
4689 s
->bus_name_pid_lookup_slot
= sd_bus_slot_unref(s
->bus_name_pid_lookup_slot
);
4691 if (!s
->bus_name
|| !pick_up_pid_from_bus_name(s
))
4694 e
= sd_bus_message_get_error(reply
);
4696 r
= sd_bus_error_get_errno(e
);
4697 log_warning_errno(r
, "GetConnectionUnixProcessID() failed: %s", bus_error_message(e
, r
));
4701 r
= sd_bus_message_read(reply
, "u", &pid
);
4703 bus_log_parse_error(r
);
4707 if (!pid_is_valid(pid
)) {
4708 log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "GetConnectionUnixProcessID() returned invalid PID");
4712 log_unit_debug(u
, "D-Bus name %s is now owned by process " PID_FMT
, s
->bus_name
, (pid_t
) pid
);
4714 (void) service_set_main_pid(s
, pid
);
4715 (void) unit_watch_pid(UNIT(s
), pid
, /* exclusive= */ false);
4719 static void service_bus_name_owner_change(Unit
*u
, const char *new_owner
) {
4721 Service
*s
= SERVICE(u
);
4727 log_unit_debug(u
, "D-Bus name %s now owned by %s", s
->bus_name
, new_owner
);
4729 log_unit_debug(u
, "D-Bus name %s now not owned by anyone.", s
->bus_name
);
4731 s
->bus_name_good
= new_owner
;
4733 /* Track the current owner, so we can reconstruct changes after a daemon reload */
4734 r
= free_and_strdup(&s
->bus_name_owner
, new_owner
);
4736 log_unit_error_errno(u
, r
, "Unable to set new bus name owner %s: %m", new_owner
);
4740 if (s
->type
== SERVICE_DBUS
) {
4742 /* service_enter_running() will figure out what to
4744 if (s
->state
== SERVICE_RUNNING
)
4745 service_enter_running(s
, SERVICE_SUCCESS
);
4746 else if (s
->state
== SERVICE_START
&& new_owner
)
4747 service_enter_start_post(s
);
4749 } else if (new_owner
&& pick_up_pid_from_bus_name(s
)) {
4751 /* Try to acquire PID from bus service */
4753 s
->bus_name_pid_lookup_slot
= sd_bus_slot_unref(s
->bus_name_pid_lookup_slot
);
4755 r
= sd_bus_call_method_async(
4756 u
->manager
->api_bus
,
4757 &s
->bus_name_pid_lookup_slot
,
4758 "org.freedesktop.DBus",
4759 "/org/freedesktop/DBus",
4760 "org.freedesktop.DBus",
4761 "GetConnectionUnixProcessID",
4762 bus_name_pid_lookup_callback
,
4767 log_debug_errno(r
, "Failed to request owner PID of service name, ignoring: %m");
4771 int service_set_socket_fd(
4776 bool selinux_context_net
) {
4778 _cleanup_free_
char *peer_text
= NULL
;
4784 /* This is called by the socket code when instantiating a new service for a stream socket and the socket needs
4785 * to be configured. We take ownership of the passed fd on success. */
4787 if (UNIT(s
)->load_state
!= UNIT_LOADED
)
4790 if (s
->socket_fd
>= 0)
4793 assert(!s
->socket_peer
);
4795 if (!IN_SET(s
->state
, SERVICE_DEAD
, SERVICE_DEAD_RESOURCES_PINNED
))
4798 if (getpeername_pretty(fd
, true, &peer_text
) >= 0) {
4800 if (UNIT(s
)->description
) {
4801 _cleanup_free_
char *a
= NULL
;
4803 a
= strjoin(UNIT(s
)->description
, " (", peer_text
, ")");
4807 r
= unit_set_description(UNIT(s
), a
);
4809 r
= unit_set_description(UNIT(s
), peer_text
);
4814 r
= unit_add_two_dependencies(UNIT(sock
), UNIT_BEFORE
, UNIT_TRIGGERS
, UNIT(s
), false, UNIT_DEPENDENCY_IMPLICIT
);
4819 s
->socket_peer
= socket_peer_ref(peer
);
4820 s
->socket_fd_selinux_context_net
= selinux_context_net
;
4822 unit_ref_set(&s
->accept_socket
, UNIT(s
), UNIT(sock
));
4826 static void service_reset_failed(Unit
*u
) {
4827 Service
*s
= SERVICE(u
);
4831 if (s
->state
== SERVICE_FAILED
)
4832 service_set_state(s
, service_determine_dead_state(s
));
4834 s
->result
= SERVICE_SUCCESS
;
4835 s
->reload_result
= SERVICE_SUCCESS
;
4836 s
->clean_result
= SERVICE_SUCCESS
;
4838 s
->flush_n_restarts
= false;
4841 static PidRef
* service_main_pid(Unit
*u
) {
4842 return &ASSERT_PTR(SERVICE(u
))->main_pid
;
4845 static PidRef
* service_control_pid(Unit
*u
) {
4846 return &ASSERT_PTR(SERVICE(u
))->control_pid
;
4849 static bool service_needs_console(Unit
*u
) {
4850 Service
*s
= SERVICE(u
);
4854 /* We provide our own implementation of this here, instead of relying of the generic implementation
4855 * unit_needs_console() provides, since we want to return false if we are in SERVICE_EXITED state. */
4857 if (!exec_context_may_touch_console(&s
->exec_context
))
4860 return IN_SET(s
->state
,
4867 SERVICE_RELOAD_SIGNAL
,
4868 SERVICE_RELOAD_NOTIFY
,
4870 SERVICE_STOP_WATCHDOG
,
4871 SERVICE_STOP_SIGTERM
,
4872 SERVICE_STOP_SIGKILL
,
4874 SERVICE_FINAL_WATCHDOG
,
4875 SERVICE_FINAL_SIGTERM
,
4876 SERVICE_FINAL_SIGKILL
);
4879 static int service_exit_status(Unit
*u
) {
4880 Service
*s
= SERVICE(u
);
4884 if (s
->main_exec_status
.pid
<= 0 ||
4885 !dual_timestamp_is_set(&s
->main_exec_status
.exit_timestamp
))
4888 if (s
->main_exec_status
.code
!= CLD_EXITED
)
4891 return s
->main_exec_status
.status
;
4894 static const char* service_status_text(Unit
*u
) {
4895 Service
*s
= SERVICE(u
);
4899 return s
->status_text
;
4902 static int service_clean(Unit
*u
, ExecCleanMask mask
) {
4903 _cleanup_strv_free_
char **l
= NULL
;
4904 bool may_clean_fdstore
= false;
4905 Service
*s
= SERVICE(u
);
4911 if (!IN_SET(s
->state
, SERVICE_DEAD
, SERVICE_DEAD_RESOURCES_PINNED
))
4914 /* Determine if there's anything we could potentially clean */
4915 r
= exec_context_get_clean_directories(&s
->exec_context
, u
->manager
->prefix
, mask
, &l
);
4919 if (mask
& EXEC_CLEAN_FDSTORE
)
4920 may_clean_fdstore
= s
->n_fd_store
> 0 || s
->n_fd_store_max
> 0;
4922 if (strv_isempty(l
) && !may_clean_fdstore
)
4923 return -EUNATCH
; /* Nothing to potentially clean */
4925 /* Let's clean the stuff we can clean quickly */
4926 if (may_clean_fdstore
)
4927 service_release_fd_store(s
);
4929 /* If we are done, leave quickly */
4930 if (strv_isempty(l
)) {
4931 if (s
->state
== SERVICE_DEAD_RESOURCES_PINNED
&& !s
->fd_store
)
4932 service_set_state(s
, SERVICE_DEAD
);
4936 /* We need to clean disk stuff. This is slow, hence do it out of process, and change state */
4937 service_unwatch_control_pid(s
);
4938 s
->clean_result
= SERVICE_SUCCESS
;
4939 s
->control_command
= NULL
;
4940 s
->control_command_id
= _SERVICE_EXEC_COMMAND_INVALID
;
4942 r
= service_arm_timer(s
, /* relative= */ true, s
->exec_context
.timeout_clean_usec
);
4944 log_unit_warning_errno(u
, r
, "Failed to install timer: %m");
4948 r
= unit_fork_and_watch_rm_rf(u
, l
, &s
->control_pid
);
4950 log_unit_warning_errno(u
, r
, "Failed to spawn cleaning task: %m");
4954 service_set_state(s
, SERVICE_CLEANING
);
4958 s
->clean_result
= SERVICE_FAILURE_RESOURCES
;
4959 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
4963 static int service_can_clean(Unit
*u
, ExecCleanMask
*ret
) {
4964 Service
*s
= SERVICE(u
);
4965 ExecCleanMask mask
= 0;
4971 r
= exec_context_get_clean_mask(&s
->exec_context
, &mask
);
4975 if (s
->n_fd_store_max
> 0)
4976 mask
|= EXEC_CLEAN_FDSTORE
;
4982 static const char *service_finished_job(Unit
*u
, JobType t
, JobResult result
) {
4983 if (t
== JOB_START
&&
4984 result
== JOB_DONE
&&
4985 SERVICE(u
)->type
== SERVICE_ONESHOT
)
4986 return "Finished %s.";
4988 /* Fall back to generic */
4992 static int service_can_start(Unit
*u
) {
4993 Service
*s
= SERVICE(u
);
4998 /* Make sure we don't enter a busy loop of some kind. */
4999 r
= unit_test_start_limit(u
);
5001 service_enter_dead(s
, SERVICE_FAILURE_START_LIMIT_HIT
, false);
5008 static void service_release_resources(Unit
*u
) {
5009 Service
*s
= SERVICE(ASSERT_PTR(u
));
5011 /* Invoked by the unit state engine, whenever it realizes that unit is dead and there's no job
5012 * anymore for it, and it hence is a good idea to release resources */
5014 /* Don't release resources if this is a transitionary failed/dead state
5015 * (i.e. SERVICE_DEAD_BEFORE_AUTO_RESTART/SERVICE_FAILED_BEFORE_AUTO_RESTART), insist on a permanent
5017 if (!IN_SET(s
->state
, SERVICE_DEAD
, SERVICE_FAILED
, SERVICE_DEAD_RESOURCES_PINNED
))
5020 log_unit_debug(u
, "Releasing resources...");
5022 service_release_socket_fd(s
);
5023 service_release_stdio_fd(s
);
5025 if (s
->fd_store_preserve_mode
!= EXEC_PRESERVE_YES
)
5026 service_release_fd_store(s
);
5028 if (s
->state
== SERVICE_DEAD_RESOURCES_PINNED
&& !s
->fd_store
)
5029 service_set_state(s
, SERVICE_DEAD
);
5032 static const char* const service_restart_table
[_SERVICE_RESTART_MAX
] = {
5033 [SERVICE_RESTART_NO
] = "no",
5034 [SERVICE_RESTART_ON_SUCCESS
] = "on-success",
5035 [SERVICE_RESTART_ON_FAILURE
] = "on-failure",
5036 [SERVICE_RESTART_ON_ABNORMAL
] = "on-abnormal",
5037 [SERVICE_RESTART_ON_WATCHDOG
] = "on-watchdog",
5038 [SERVICE_RESTART_ON_ABORT
] = "on-abort",
5039 [SERVICE_RESTART_ALWAYS
] = "always",
5042 DEFINE_STRING_TABLE_LOOKUP(service_restart
, ServiceRestart
);
5044 static const char* const service_restart_mode_table
[_SERVICE_RESTART_MODE_MAX
] = {
5045 [SERVICE_RESTART_MODE_NORMAL
] = "normal",
5046 [SERVICE_RESTART_MODE_DIRECT
] = "direct",
5049 DEFINE_STRING_TABLE_LOOKUP(service_restart_mode
, ServiceRestartMode
);
5051 static const char* const service_type_table
[_SERVICE_TYPE_MAX
] = {
5052 [SERVICE_SIMPLE
] = "simple",
5053 [SERVICE_FORKING
] = "forking",
5054 [SERVICE_ONESHOT
] = "oneshot",
5055 [SERVICE_DBUS
] = "dbus",
5056 [SERVICE_NOTIFY
] = "notify",
5057 [SERVICE_NOTIFY_RELOAD
] = "notify-reload",
5058 [SERVICE_IDLE
] = "idle",
5059 [SERVICE_EXEC
] = "exec",
5062 DEFINE_STRING_TABLE_LOOKUP(service_type
, ServiceType
);
5064 static const char* const service_exit_type_table
[_SERVICE_EXIT_TYPE_MAX
] = {
5065 [SERVICE_EXIT_MAIN
] = "main",
5066 [SERVICE_EXIT_CGROUP
] = "cgroup",
5069 DEFINE_STRING_TABLE_LOOKUP(service_exit_type
, ServiceExitType
);
5071 static const char* const service_exec_command_table
[_SERVICE_EXEC_COMMAND_MAX
] = {
5072 [SERVICE_EXEC_CONDITION
] = "ExecCondition",
5073 [SERVICE_EXEC_START_PRE
] = "ExecStartPre",
5074 [SERVICE_EXEC_START
] = "ExecStart",
5075 [SERVICE_EXEC_START_POST
] = "ExecStartPost",
5076 [SERVICE_EXEC_RELOAD
] = "ExecReload",
5077 [SERVICE_EXEC_STOP
] = "ExecStop",
5078 [SERVICE_EXEC_STOP_POST
] = "ExecStopPost",
5081 DEFINE_STRING_TABLE_LOOKUP(service_exec_command
, ServiceExecCommand
);
5083 static const char* const service_exec_ex_command_table
[_SERVICE_EXEC_COMMAND_MAX
] = {
5084 [SERVICE_EXEC_CONDITION
] = "ExecConditionEx",
5085 [SERVICE_EXEC_START_PRE
] = "ExecStartPreEx",
5086 [SERVICE_EXEC_START
] = "ExecStartEx",
5087 [SERVICE_EXEC_START_POST
] = "ExecStartPostEx",
5088 [SERVICE_EXEC_RELOAD
] = "ExecReloadEx",
5089 [SERVICE_EXEC_STOP
] = "ExecStopEx",
5090 [SERVICE_EXEC_STOP_POST
] = "ExecStopPostEx",
5093 DEFINE_STRING_TABLE_LOOKUP(service_exec_ex_command
, ServiceExecCommand
);
5095 static const char* const notify_state_table
[_NOTIFY_STATE_MAX
] = {
5096 [NOTIFY_UNKNOWN
] = "unknown",
5097 [NOTIFY_READY
] = "ready",
5098 [NOTIFY_RELOADING
] = "reloading",
5099 [NOTIFY_STOPPING
] = "stopping",
5102 DEFINE_STRING_TABLE_LOOKUP(notify_state
, NotifyState
);
5104 static const char* const service_result_table
[_SERVICE_RESULT_MAX
] = {
5105 [SERVICE_SUCCESS
] = "success",
5106 [SERVICE_FAILURE_RESOURCES
] = "resources",
5107 [SERVICE_FAILURE_PROTOCOL
] = "protocol",
5108 [SERVICE_FAILURE_TIMEOUT
] = "timeout",
5109 [SERVICE_FAILURE_EXIT_CODE
] = "exit-code",
5110 [SERVICE_FAILURE_SIGNAL
] = "signal",
5111 [SERVICE_FAILURE_CORE_DUMP
] = "core-dump",
5112 [SERVICE_FAILURE_WATCHDOG
] = "watchdog",
5113 [SERVICE_FAILURE_START_LIMIT_HIT
] = "start-limit-hit",
5114 [SERVICE_FAILURE_OOM_KILL
] = "oom-kill",
5115 [SERVICE_SKIP_CONDITION
] = "exec-condition",
5118 DEFINE_STRING_TABLE_LOOKUP(service_result
, ServiceResult
);
5120 static const char* const service_timeout_failure_mode_table
[_SERVICE_TIMEOUT_FAILURE_MODE_MAX
] = {
5121 [SERVICE_TIMEOUT_TERMINATE
] = "terminate",
5122 [SERVICE_TIMEOUT_ABORT
] = "abort",
5123 [SERVICE_TIMEOUT_KILL
] = "kill",
5126 DEFINE_STRING_TABLE_LOOKUP(service_timeout_failure_mode
, ServiceTimeoutFailureMode
);
5128 const UnitVTable service_vtable
= {
5129 .object_size
= sizeof(Service
),
5130 .exec_context_offset
= offsetof(Service
, exec_context
),
5131 .cgroup_context_offset
= offsetof(Service
, cgroup_context
),
5132 .kill_context_offset
= offsetof(Service
, kill_context
),
5133 .exec_runtime_offset
= offsetof(Service
, exec_runtime
),
5139 .private_section
= "Service",
5141 .can_transient
= true,
5142 .can_delegate
= true,
5144 .can_set_managed_oom
= true,
5146 .init
= service_init
,
5147 .done
= service_done
,
5148 .load
= service_load
,
5149 .release_resources
= service_release_resources
,
5151 .coldplug
= service_coldplug
,
5153 .dump
= service_dump
,
5155 .start
= service_start
,
5156 .stop
= service_stop
,
5157 .reload
= service_reload
,
5159 .can_reload
= service_can_reload
,
5161 .clean
= service_clean
,
5162 .can_clean
= service_can_clean
,
5164 .freeze
= unit_freeze_vtable_common
,
5165 .thaw
= unit_thaw_vtable_common
,
5167 .serialize
= service_serialize
,
5168 .deserialize_item
= service_deserialize_item
,
5170 .active_state
= service_active_state
,
5171 .sub_state_to_string
= service_sub_state_to_string
,
5173 .will_restart
= service_will_restart
,
5175 .may_gc
= service_may_gc
,
5177 .sigchld_event
= service_sigchld_event
,
5179 .reset_failed
= service_reset_failed
,
5181 .notify_cgroup_empty
= service_notify_cgroup_empty_event
,
5182 .notify_cgroup_oom
= service_notify_cgroup_oom_event
,
5183 .notify_message
= service_notify_message
,
5185 .main_pid
= service_main_pid
,
5186 .control_pid
= service_control_pid
,
5188 .bus_name_owner_change
= service_bus_name_owner_change
,
5190 .bus_set_property
= bus_service_set_property
,
5191 .bus_commit_properties
= bus_service_commit_properties
,
5193 .get_timeout
= service_get_timeout
,
5194 .get_timeout_start_usec
= service_get_timeout_start_usec
,
5195 .needs_console
= service_needs_console
,
5196 .exit_status
= service_exit_status
,
5197 .status_text
= service_status_text
,
5199 .status_message_formats
= {
5200 .finished_start_job
= {
5201 [JOB_FAILED
] = "Failed to start %s.",
5203 .finished_stop_job
= {
5204 [JOB_DONE
] = "Stopped %s.",
5205 [JOB_FAILED
] = "Stopped (with error) %s.",
5207 .finished_job
= service_finished_job
,
5210 .can_start
= service_can_start
,
5212 .notify_plymouth
= true,
5214 .audit_start_message_type
= AUDIT_SERVICE_START
,
5215 .audit_stop_message_type
= AUDIT_SERVICE_STOP
,