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
->default_timeout_start_usec
;
124 s
->timeout_stop_usec
= u
->manager
->default_timeout_stop_usec
;
125 s
->timeout_abort_usec
= u
->manager
->default_timeout_abort_usec
;
126 s
->timeout_abort_set
= u
->manager
->default_timeout_abort_set
;
127 s
->restart_usec
= u
->manager
->default_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_pid(Service
*s
, pid_t pid
) {
183 _cleanup_(pidref_done
) PidRef pidref
= PIDREF_NULL
;
191 if (pid
== getpid_cached())
194 if (s
->main_pid
.pid
== pid
&& s
->main_pid_known
)
197 r
= pidref_set_pid(&pidref
, pid
);
201 if (s
->main_pid
.pid
!= pid
) {
202 service_unwatch_main_pid(s
);
203 exec_status_start(&s
->main_exec_status
, pid
);
206 s
->main_pid
= TAKE_PIDREF(pidref
);
207 s
->main_pid_known
= true;
208 s
->main_pid_alien
= pid_is_my_child(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.", pid
);
216 void service_release_socket_fd(Service
*s
) {
219 if (s
->socket_fd
< 0 && !UNIT_ISSET(s
->accept_socket
) && !s
->socket_peer
)
222 log_unit_debug(UNIT(s
), "Closing connection socket.");
224 /* Undo the effect of service_set_socket_fd(). */
226 s
->socket_fd
= asynchronous_close(s
->socket_fd
);
228 if (UNIT_ISSET(s
->accept_socket
)) {
229 socket_connection_unref(SOCKET(UNIT_DEREF(s
->accept_socket
)));
230 unit_ref_unset(&s
->accept_socket
);
233 s
->socket_peer
= socket_peer_unref(s
->socket_peer
);
236 static void service_override_notify_access(Service
*s
, NotifyAccess notify_access_override
) {
239 s
->notify_access_override
= notify_access_override
;
241 log_unit_debug(UNIT(s
), "notify_access=%s", notify_access_to_string(s
->notify_access
));
242 log_unit_debug(UNIT(s
), "notify_access_override=%s", notify_access_to_string(s
->notify_access_override
));
245 static void service_stop_watchdog(Service
*s
) {
248 s
->watchdog_event_source
= sd_event_source_disable_unref(s
->watchdog_event_source
);
249 s
->watchdog_timestamp
= DUAL_TIMESTAMP_NULL
;
252 static void service_start_watchdog(Service
*s
) {
253 usec_t watchdog_usec
;
258 watchdog_usec
= service_get_watchdog_usec(s
);
259 if (!timestamp_is_set(watchdog_usec
)) {
260 service_stop_watchdog(s
);
264 if (s
->watchdog_event_source
) {
265 r
= sd_event_source_set_time(s
->watchdog_event_source
, usec_add(s
->watchdog_timestamp
.monotonic
, watchdog_usec
));
267 log_unit_warning_errno(UNIT(s
), r
, "Failed to reset watchdog timer: %m");
271 r
= sd_event_source_set_enabled(s
->watchdog_event_source
, SD_EVENT_ONESHOT
);
273 r
= sd_event_add_time(
274 UNIT(s
)->manager
->event
,
275 &s
->watchdog_event_source
,
277 usec_add(s
->watchdog_timestamp
.monotonic
, watchdog_usec
), 0,
278 service_dispatch_watchdog
, s
);
280 log_unit_warning_errno(UNIT(s
), r
, "Failed to add watchdog timer: %m");
284 (void) sd_event_source_set_description(s
->watchdog_event_source
, "service-watchdog");
286 /* Let's process everything else which might be a sign
287 * of living before we consider a service died. */
288 r
= sd_event_source_set_priority(s
->watchdog_event_source
, SD_EVENT_PRIORITY_IDLE
);
291 log_unit_warning_errno(UNIT(s
), r
, "Failed to install watchdog timer: %m");
294 usec_t
service_restart_usec_next(Service
*s
) {
295 unsigned n_restarts_next
;
300 /* When the service state is in SERVICE_*_BEFORE_AUTO_RESTART or SERVICE_AUTO_RESTART, we still need
301 * to add 1 to s->n_restarts manually, because s->n_restarts is not updated until a restart job is
302 * enqueued, i.e. state has transitioned to SERVICE_AUTO_RESTART_QUEUED. */
303 n_restarts_next
= s
->n_restarts
+ (s
->state
== SERVICE_AUTO_RESTART_QUEUED
? 0 : 1);
305 if (n_restarts_next
<= 1 ||
306 s
->restart_steps
== 0 ||
307 s
->restart_usec
== 0 ||
308 s
->restart_max_delay_usec
== USEC_INFINITY
||
309 s
->restart_usec
>= s
->restart_max_delay_usec
)
310 value
= s
->restart_usec
;
311 else if (n_restarts_next
> s
->restart_steps
)
312 value
= s
->restart_max_delay_usec
;
314 /* Enforced in service_verify() and above */
315 assert(s
->restart_max_delay_usec
> s
->restart_usec
);
317 /* r_i / r_0 = (r_n / r_0) ^ (i / n)
319 * r_0 : initial restart usec (s->restart_usec),
320 * r_i : i-th restart usec (value),
321 * r_n : maximum restart usec (s->restart_max_delay_usec),
322 * i : index of the next step (n_restarts_next - 1)
323 * n : num maximum steps (s->restart_steps) */
324 value
= (usec_t
) (s
->restart_usec
* powl((long double) s
->restart_max_delay_usec
/ s
->restart_usec
,
325 (long double) (n_restarts_next
- 1) / s
->restart_steps
));
328 log_unit_debug(UNIT(s
), "Next restart interval calculated as: %s", FORMAT_TIMESPAN(value
, 0));
332 static void service_extend_event_source_timeout(Service
*s
, sd_event_source
*source
, usec_t extended
) {
338 /* Extends the specified event source timer to at least the specified time, unless it is already later
344 r
= sd_event_source_get_time(source
, ¤t
);
347 (void) sd_event_source_get_description(s
->timer_event_source
, &desc
);
348 log_unit_warning_errno(UNIT(s
), r
, "Failed to retrieve timeout time for event source '%s', ignoring: %m", strna(desc
));
352 if (current
>= extended
) /* Current timeout is already longer, ignore this. */
355 r
= sd_event_source_set_time(source
, extended
);
358 (void) sd_event_source_get_description(s
->timer_event_source
, &desc
);
359 log_unit_warning_errno(UNIT(s
), r
, "Failed to set timeout time for event source '%s', ignoring %m", strna(desc
));
363 static void service_extend_timeout(Service
*s
, usec_t extend_timeout_usec
) {
368 if (!timestamp_is_set(extend_timeout_usec
))
371 extended
= usec_add(now(CLOCK_MONOTONIC
), extend_timeout_usec
);
373 service_extend_event_source_timeout(s
, s
->timer_event_source
, extended
);
374 service_extend_event_source_timeout(s
, s
->watchdog_event_source
, extended
);
377 static void service_reset_watchdog(Service
*s
) {
380 dual_timestamp_get(&s
->watchdog_timestamp
);
381 service_start_watchdog(s
);
384 static void service_override_watchdog_timeout(Service
*s
, usec_t watchdog_override_usec
) {
387 s
->watchdog_override_enable
= true;
388 s
->watchdog_override_usec
= watchdog_override_usec
;
389 service_reset_watchdog(s
);
391 log_unit_debug(UNIT(s
), "watchdog_usec="USEC_FMT
, s
->watchdog_usec
);
392 log_unit_debug(UNIT(s
), "watchdog_override_usec="USEC_FMT
, s
->watchdog_override_usec
);
395 static ServiceFDStore
* service_fd_store_unlink(ServiceFDStore
*fs
) {
400 assert(fs
->service
->n_fd_store
> 0);
401 LIST_REMOVE(fd_store
, fs
->service
->fd_store
, fs
);
402 fs
->service
->n_fd_store
--;
405 sd_event_source_disable_unref(fs
->event_source
);
408 asynchronous_close(fs
->fd
);
412 DEFINE_TRIVIAL_CLEANUP_FUNC(ServiceFDStore
*, service_fd_store_unlink
);
414 static void service_release_fd_store(Service
*s
) {
420 log_unit_debug(UNIT(s
), "Releasing all stored fds");
423 service_fd_store_unlink(s
->fd_store
);
425 assert(s
->n_fd_store
== 0);
428 static void service_release_stdio_fd(Service
*s
) {
431 if (s
->stdin_fd
< 0 && s
->stdout_fd
< 0 && s
->stdout_fd
< 0)
434 log_unit_debug(UNIT(s
), "Releasing stdin/stdout/stderr file descriptors.");
436 s
->stdin_fd
= asynchronous_close(s
->stdin_fd
);
437 s
->stdout_fd
= asynchronous_close(s
->stdout_fd
);
438 s
->stderr_fd
= asynchronous_close(s
->stderr_fd
);
440 static void service_done(Unit
*u
) {
441 Service
*s
= SERVICE(u
);
445 open_file_free_many(&s
->open_files
);
447 s
->pid_file
= mfree(s
->pid_file
);
448 s
->status_text
= mfree(s
->status_text
);
450 s
->exec_runtime
= exec_runtime_free(s
->exec_runtime
);
451 exec_command_free_array(s
->exec_command
, _SERVICE_EXEC_COMMAND_MAX
);
452 s
->control_command
= NULL
;
453 s
->main_command
= NULL
;
455 exit_status_set_free(&s
->restart_prevent_status
);
456 exit_status_set_free(&s
->restart_force_status
);
457 exit_status_set_free(&s
->success_status
);
459 /* This will leak a process, but at least no memory or any of our resources */
460 service_unwatch_main_pid(s
);
461 service_unwatch_control_pid(s
);
462 service_unwatch_pid_file(s
);
465 unit_unwatch_bus_name(u
, s
->bus_name
);
466 s
->bus_name
= mfree(s
->bus_name
);
469 s
->bus_name_owner
= mfree(s
->bus_name_owner
);
471 s
->usb_function_descriptors
= mfree(s
->usb_function_descriptors
);
472 s
->usb_function_strings
= mfree(s
->usb_function_strings
);
474 service_stop_watchdog(s
);
476 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
477 s
->exec_fd_event_source
= sd_event_source_disable_unref(s
->exec_fd_event_source
);
479 s
->bus_name_pid_lookup_slot
= sd_bus_slot_unref(s
->bus_name_pid_lookup_slot
);
481 service_release_socket_fd(s
);
482 service_release_stdio_fd(s
);
483 service_release_fd_store(s
);
486 static int on_fd_store_io(sd_event_source
*e
, int fd
, uint32_t revents
, void *userdata
) {
487 ServiceFDStore
*fs
= ASSERT_PTR(userdata
);
491 /* If we get either EPOLLHUP or EPOLLERR, it's time to remove this entry from the fd store */
492 log_unit_debug(UNIT(fs
->service
),
493 "Received %s on stored fd %d (%s), closing.",
494 revents
& EPOLLERR
? "EPOLLERR" : "EPOLLHUP",
495 fs
->fd
, strna(fs
->fdname
));
496 service_fd_store_unlink(fs
);
500 static int service_add_fd_store(Service
*s
, int fd_in
, const char *name
, bool do_poll
) {
501 _cleanup_(service_fd_store_unlinkp
) ServiceFDStore
*fs
= NULL
;
502 _cleanup_(asynchronous_closep
) int fd
= ASSERT_FD(fd_in
);
506 /* fd is always consumed even if the function fails. */
510 if (fstat(fd
, &st
) < 0)
513 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
);
515 if (s
->n_fd_store
>= s
->n_fd_store_max
)
516 /* Our store is full. Use this errno rather than E[NM]FILE to distinguish from the case
517 * where systemd itself hits the file limit. */
518 return log_unit_debug_errno(UNIT(s
), SYNTHETIC_ERRNO(EXFULL
), "Hit fd store limit.");
520 LIST_FOREACH(fd_store
, i
, s
->fd_store
) {
521 r
= same_fd(i
->fd
, fd
);
525 log_unit_debug(UNIT(s
), "Suppressing duplicate fd %i in fd store.", fd
);
526 return 0; /* fd already included */
530 fs
= new(ServiceFDStore
, 1);
534 *fs
= (ServiceFDStore
) {
537 .fdname
= strdup(name
?: "stored"),
544 r
= sd_event_add_io(UNIT(s
)->manager
->event
, &fs
->event_source
, fs
->fd
, 0, on_fd_store_io
, fs
);
545 if (r
< 0 && r
!= -EPERM
) /* EPERM indicates fds that aren't pollable, which is OK */
548 (void) sd_event_source_set_description(fs
->event_source
, "service-fd-store");
552 LIST_PREPEND(fd_store
, s
->fd_store
, fs
);
555 log_unit_debug(UNIT(s
), "Added fd %i (%s) to fd store.", fs
->fd
, fs
->fdname
);
558 return 1; /* fd newly stored */
561 static int service_add_fd_store_set(Service
*s
, FDSet
*fds
, const char *name
, bool do_poll
) {
569 fd
= fdset_steal_first(fds
);
573 r
= service_add_fd_store(s
, fd
, name
, do_poll
);
575 return log_unit_warning_errno(UNIT(s
), r
,
576 "Cannot store more fds than FileDescriptorStoreMax=%u, closing remaining.",
579 return log_unit_error_errno(UNIT(s
), r
, "Failed to add fd to store: %m");
585 static void service_remove_fd_store(Service
*s
, const char *name
) {
589 LIST_FOREACH(fd_store
, fs
, s
->fd_store
) {
590 if (!streq(fs
->fdname
, name
))
593 log_unit_debug(UNIT(s
), "Got explicit request to remove fd %i (%s), closing.", fs
->fd
, name
);
594 service_fd_store_unlink(fs
);
598 static usec_t
service_running_timeout(Service
*s
) {
603 if (s
->runtime_rand_extra_usec
!= 0) {
604 delta
= random_u64_range(s
->runtime_rand_extra_usec
);
605 log_unit_debug(UNIT(s
), "Adding delta of %s sec to timeout", FORMAT_TIMESPAN(delta
, USEC_PER_SEC
));
608 return usec_add(usec_add(UNIT(s
)->active_enter_timestamp
.monotonic
,
609 s
->runtime_max_usec
),
613 static int service_arm_timer(Service
*s
, bool relative
, usec_t usec
) {
618 if (s
->timer_event_source
) {
619 r
= (relative
? sd_event_source_set_time_relative
: sd_event_source_set_time
)(s
->timer_event_source
, usec
);
623 return sd_event_source_set_enabled(s
->timer_event_source
, SD_EVENT_ONESHOT
);
626 if (usec
== USEC_INFINITY
)
629 r
= (relative
? sd_event_add_time_relative
: sd_event_add_time
)(
630 UNIT(s
)->manager
->event
,
631 &s
->timer_event_source
,
634 service_dispatch_timer
, s
);
638 (void) sd_event_source_set_description(s
->timer_event_source
, "service-timer");
643 static int service_verify(Service
*s
) {
645 assert(UNIT(s
)->load_state
== UNIT_LOADED
);
647 for (ServiceExecCommand c
= 0; c
< _SERVICE_EXEC_COMMAND_MAX
; c
++)
648 LIST_FOREACH(command
, command
, s
->exec_command
[c
]) {
649 if (!path_is_absolute(command
->path
) && !filename_is_valid(command
->path
))
650 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
),
651 "Service %s= binary path \"%s\" is neither a valid executable name nor an absolute path. Refusing.",
653 service_exec_command_to_string(c
));
654 if (strv_isempty(command
->argv
))
655 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
),
656 "Service has an empty argv in %s=. Refusing.",
657 service_exec_command_to_string(c
));
660 if (!s
->exec_command
[SERVICE_EXEC_START
] && !s
->exec_command
[SERVICE_EXEC_STOP
] &&
661 UNIT(s
)->success_action
== EMERGENCY_ACTION_NONE
)
662 /* FailureAction= only makes sense if one of the start or stop commands is specified.
663 * SuccessAction= will be executed unconditionally if no commands are specified. Hence,
664 * either a command or SuccessAction= are required. */
666 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Service has no ExecStart=, ExecStop=, or SuccessAction=. Refusing.");
668 if (s
->type
!= SERVICE_ONESHOT
&& !s
->exec_command
[SERVICE_EXEC_START
])
669 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Service has no ExecStart= setting, which is only allowed for Type=oneshot services. Refusing.");
671 if (!s
->remain_after_exit
&& !s
->exec_command
[SERVICE_EXEC_START
] && UNIT(s
)->success_action
== EMERGENCY_ACTION_NONE
)
672 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.");
674 if (s
->type
!= SERVICE_ONESHOT
&& s
->exec_command
[SERVICE_EXEC_START
]->command_next
)
675 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.");
677 if (s
->type
== SERVICE_ONESHOT
&&
678 !IN_SET(s
->restart
, SERVICE_RESTART_NO
, SERVICE_RESTART_ON_FAILURE
, SERVICE_RESTART_ON_ABNORMAL
, SERVICE_RESTART_ON_WATCHDOG
, SERVICE_RESTART_ON_ABORT
))
679 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.");
681 if (s
->type
== SERVICE_ONESHOT
&& !exit_status_set_is_empty(&s
->restart_force_status
))
682 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Service has RestartForceExitStatus= set, which isn't allowed for Type=oneshot services. Refusing.");
684 if (s
->type
== SERVICE_ONESHOT
&& s
->exit_type
== SERVICE_EXIT_CGROUP
)
685 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Service has ExitType=cgroup set, which isn't allowed for Type=oneshot services. Refusing.");
687 if (s
->type
== SERVICE_DBUS
&& !s
->bus_name
)
688 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.");
690 if (s
->exec_context
.pam_name
&& !IN_SET(s
->kill_context
.kill_mode
, KILL_CONTROL_GROUP
, KILL_MIXED
))
691 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.");
693 if (s
->usb_function_descriptors
&& !s
->usb_function_strings
)
694 log_unit_warning(UNIT(s
), "Service has USBFunctionDescriptors= setting, but no USBFunctionStrings=. Ignoring.");
696 if (!s
->usb_function_descriptors
&& s
->usb_function_strings
)
697 log_unit_warning(UNIT(s
), "Service has USBFunctionStrings= setting, but no USBFunctionDescriptors=. Ignoring.");
699 if (s
->runtime_max_usec
!= USEC_INFINITY
&& s
->type
== SERVICE_ONESHOT
)
700 log_unit_warning(UNIT(s
), "RuntimeMaxSec= has no effect in combination with Type=oneshot. Ignoring.");
702 if (s
->runtime_max_usec
== USEC_INFINITY
&& s
->runtime_rand_extra_usec
!= 0)
703 log_unit_warning(UNIT(s
), "Service has RuntimeRandomizedExtraSec= setting, but no RuntimeMaxSec=. Ignoring.");
705 if (s
->exit_type
== SERVICE_EXIT_CGROUP
&& cg_unified() < CGROUP_UNIFIED_SYSTEMD
)
706 log_unit_warning(UNIT(s
), "Service has ExitType=cgroup set, but we are running with legacy cgroups v1, which might not work correctly. Continuing.");
708 if (s
->restart_max_delay_usec
== USEC_INFINITY
&& s
->restart_steps
> 0)
709 log_unit_warning(UNIT(s
), "Service has RestartSteps= but no RestartMaxDelaySec= setting. Ignoring.");
711 if (s
->restart_max_delay_usec
!= USEC_INFINITY
&& s
->restart_steps
== 0)
712 log_unit_warning(UNIT(s
), "Service has RestartMaxDelaySec= but no RestartSteps= setting. Ignoring.");
714 if (s
->restart_max_delay_usec
< s
->restart_usec
) {
715 log_unit_warning(UNIT(s
), "RestartMaxDelaySec= has a value smaller than RestartSec=, resetting RestartSec= to RestartMaxDelaySec=.");
716 s
->restart_usec
= s
->restart_max_delay_usec
;
722 static int service_add_default_dependencies(Service
*s
) {
727 if (!UNIT(s
)->default_dependencies
)
730 /* Add a number of automatic dependencies useful for the
731 * majority of services. */
733 if (MANAGER_IS_SYSTEM(UNIT(s
)->manager
)) {
734 /* First, pull in the really early boot stuff, and
735 * require it, so that we fail if we can't acquire
738 r
= unit_add_two_dependencies_by_name(UNIT(s
), UNIT_AFTER
, UNIT_REQUIRES
, SPECIAL_SYSINIT_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
743 /* In the --user instance there's no sysinit.target,
744 * in that case require basic.target instead. */
746 r
= unit_add_dependency_by_name(UNIT(s
), UNIT_REQUIRES
, SPECIAL_BASIC_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
751 /* Second, if the rest of the base system is in the same
752 * transaction, order us after it, but do not pull it in or
753 * even require it. */
754 r
= unit_add_dependency_by_name(UNIT(s
), UNIT_AFTER
, SPECIAL_BASIC_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
758 /* Third, add us in for normal shutdown. */
759 return unit_add_two_dependencies_by_name(UNIT(s
), UNIT_BEFORE
, UNIT_CONFLICTS
, SPECIAL_SHUTDOWN_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
762 static void service_fix_stdio(Service
*s
) {
765 /* Note that EXEC_INPUT_NULL and EXEC_OUTPUT_INHERIT play a special role here: they are both the
766 * default value that is subject to automatic overriding triggered by other settings and an explicit
767 * choice the user can make. We don't distinguish between these cases currently. */
769 if (s
->exec_context
.std_input
== EXEC_INPUT_NULL
&&
770 s
->exec_context
.stdin_data_size
> 0)
771 s
->exec_context
.std_input
= EXEC_INPUT_DATA
;
773 if (IN_SET(s
->exec_context
.std_input
,
775 EXEC_INPUT_TTY_FORCE
,
778 EXEC_INPUT_NAMED_FD
))
781 /* We assume these listed inputs refer to bidirectional streams, and hence duplicating them from
782 * stdin to stdout/stderr makes sense and hence leaving EXEC_OUTPUT_INHERIT in place makes sense,
783 * too. Outputs such as regular files or sealed data memfds otoh don't really make sense to be
784 * duplicated for both input and output at the same time (since they then would cause a feedback
785 * loop), hence override EXEC_OUTPUT_INHERIT with the default stderr/stdout setting. */
787 if (s
->exec_context
.std_error
== EXEC_OUTPUT_INHERIT
&&
788 s
->exec_context
.std_output
== EXEC_OUTPUT_INHERIT
)
789 s
->exec_context
.std_error
= UNIT(s
)->manager
->default_std_error
;
791 if (s
->exec_context
.std_output
== EXEC_OUTPUT_INHERIT
)
792 s
->exec_context
.std_output
= UNIT(s
)->manager
->default_std_output
;
795 static int service_setup_bus_name(Service
*s
) {
800 /* If s->bus_name is not set, then the unit will be refused by service_verify() later. */
804 if (s
->type
== SERVICE_DBUS
) {
805 r
= unit_add_dependency_by_name(UNIT(s
), UNIT_REQUIRES
, SPECIAL_DBUS_SOCKET
, true, UNIT_DEPENDENCY_FILE
);
807 return log_unit_error_errno(UNIT(s
), r
, "Failed to add dependency on " SPECIAL_DBUS_SOCKET
": %m");
809 /* We always want to be ordered against dbus.socket if both are in the transaction. */
810 r
= unit_add_dependency_by_name(UNIT(s
), UNIT_AFTER
, SPECIAL_DBUS_SOCKET
, true, UNIT_DEPENDENCY_FILE
);
812 return log_unit_error_errno(UNIT(s
), r
, "Failed to add dependency on " SPECIAL_DBUS_SOCKET
": %m");
815 r
= unit_watch_bus_name(UNIT(s
), s
->bus_name
);
817 return log_unit_error_errno(UNIT(s
), r
, "Two services allocated for the same bus name %s, refusing operation.", s
->bus_name
);
819 return log_unit_error_errno(UNIT(s
), r
, "Cannot watch bus name %s: %m", s
->bus_name
);
824 static int service_add_extras(Service
*s
) {
829 if (s
->type
== _SERVICE_TYPE_INVALID
) {
830 /* Figure out a type automatically */
832 s
->type
= SERVICE_DBUS
;
833 else if (s
->exec_command
[SERVICE_EXEC_START
])
834 s
->type
= SERVICE_SIMPLE
;
836 s
->type
= SERVICE_ONESHOT
;
839 /* Oneshot services have disabled start timeout by default */
840 if (s
->type
== SERVICE_ONESHOT
&& !s
->start_timeout_defined
)
841 s
->timeout_start_usec
= USEC_INFINITY
;
843 service_fix_stdio(s
);
845 r
= unit_patch_contexts(UNIT(s
));
849 r
= unit_add_exec_dependencies(UNIT(s
), &s
->exec_context
);
853 r
= unit_set_default_slice(UNIT(s
));
857 /* If the service needs the notify socket, let's enable it automatically. */
858 if (s
->notify_access
== NOTIFY_NONE
&&
859 (IN_SET(s
->type
, SERVICE_NOTIFY
, SERVICE_NOTIFY_RELOAD
) || s
->watchdog_usec
> 0 || s
->n_fd_store_max
> 0))
860 s
->notify_access
= NOTIFY_MAIN
;
862 /* If no OOM policy was explicitly set, then default to the configure default OOM policy. Except when
863 * delegation is on, in that case it we assume the payload knows better what to do and can process
864 * things in a more focused way. */
865 if (s
->oom_policy
< 0)
866 s
->oom_policy
= s
->cgroup_context
.delegate
? OOM_CONTINUE
: UNIT(s
)->manager
->default_oom_policy
;
868 /* Let the kernel do the killing if that's requested. */
869 s
->cgroup_context
.memory_oom_group
= s
->oom_policy
== OOM_KILL
;
871 r
= service_add_default_dependencies(s
);
875 r
= service_setup_bus_name(s
);
882 static int service_load(Unit
*u
) {
883 Service
*s
= SERVICE(u
);
886 r
= unit_load_fragment_and_dropin(u
, true);
890 if (u
->load_state
!= UNIT_LOADED
)
893 /* This is a new unit? Then let's add in some extras */
894 r
= service_add_extras(s
);
898 return service_verify(s
);
901 static void service_dump_fdstore(Service
*s
, FILE *f
, const char *prefix
) {
906 LIST_FOREACH(fd_store
, i
, s
->fd_store
) {
907 _cleanup_free_
char *path
= NULL
;
911 if (fstat(i
->fd
, &st
) < 0) {
912 log_debug_errno(errno
, "Failed to stat fdstore entry: %m");
916 flags
= fcntl(i
->fd
, F_GETFL
);
918 log_debug_errno(errno
, "Failed to get fdstore entry flags: %m");
922 (void) fd_get_path(i
->fd
, &path
);
925 "%s%s '%s' (type=%s; dev=" DEVNUM_FORMAT_STR
"; inode=%" PRIu64
"; rdev=" DEVNUM_FORMAT_STR
"; path=%s; access=%s)\n",
926 prefix
, i
== s
->fd_store
? "File Descriptor Store Entry:" : " ",
928 inode_type_to_string(st
.st_mode
),
929 DEVNUM_FORMAT_VAL(st
.st_dev
),
930 (uint64_t) st
.st_ino
,
931 DEVNUM_FORMAT_VAL(st
.st_rdev
),
933 accmode_to_string(flags
));
937 static void service_dump(Unit
*u
, FILE *f
, const char *prefix
) {
938 Service
*s
= SERVICE(u
);
943 prefix
= strempty(prefix
);
944 prefix2
= strjoina(prefix
, "\t");
947 "%sService State: %s\n"
949 "%sReload Result: %s\n"
950 "%sClean Result: %s\n"
951 "%sPermissionsStartOnly: %s\n"
952 "%sRootDirectoryStartOnly: %s\n"
953 "%sRemainAfterExit: %s\n"
954 "%sGuessMainPID: %s\n"
957 "%sNotifyAccess: %s\n"
958 "%sNotifyState: %s\n"
960 "%sReloadSignal: %s\n",
961 prefix
, service_state_to_string(s
->state
),
962 prefix
, service_result_to_string(s
->result
),
963 prefix
, service_result_to_string(s
->reload_result
),
964 prefix
, service_result_to_string(s
->clean_result
),
965 prefix
, yes_no(s
->permissions_start_only
),
966 prefix
, yes_no(s
->root_directory_start_only
),
967 prefix
, yes_no(s
->remain_after_exit
),
968 prefix
, yes_no(s
->guess_main_pid
),
969 prefix
, service_type_to_string(s
->type
),
970 prefix
, service_restart_to_string(s
->restart
),
971 prefix
, notify_access_to_string(service_get_notify_access(s
)),
972 prefix
, notify_state_to_string(s
->notify_state
),
973 prefix
, oom_policy_to_string(s
->oom_policy
),
974 prefix
, signal_to_string(s
->reload_signal
));
976 if (pidref_is_set(&s
->control_pid
))
978 "%sControl PID: "PID_FMT
"\n",
979 prefix
, s
->control_pid
.pid
);
981 if (pidref_is_set(&s
->main_pid
))
983 "%sMain PID: "PID_FMT
"\n"
984 "%sMain PID Known: %s\n"
985 "%sMain PID Alien: %s\n",
986 prefix
, s
->main_pid
.pid
,
987 prefix
, yes_no(s
->main_pid_known
),
988 prefix
, yes_no(s
->main_pid_alien
));
993 prefix
, s
->pid_file
);
998 "%sBus Name Good: %s\n",
1000 prefix
, yes_no(s
->bus_name_good
));
1002 if (UNIT_ISSET(s
->accept_socket
))
1004 "%sAccept Socket: %s\n",
1005 prefix
, UNIT_DEREF(s
->accept_socket
)->id
);
1008 "%sRestartSec: %s\n"
1009 "%sRestartSteps: %u\n"
1010 "%sRestartMaxDelaySec: %s\n"
1011 "%sTimeoutStartSec: %s\n"
1012 "%sTimeoutStopSec: %s\n"
1013 "%sTimeoutStartFailureMode: %s\n"
1014 "%sTimeoutStopFailureMode: %s\n",
1015 prefix
, FORMAT_TIMESPAN(s
->restart_usec
, USEC_PER_SEC
),
1016 prefix
, s
->restart_steps
,
1017 prefix
, FORMAT_TIMESPAN(s
->restart_max_delay_usec
, USEC_PER_SEC
),
1018 prefix
, FORMAT_TIMESPAN(s
->timeout_start_usec
, USEC_PER_SEC
),
1019 prefix
, FORMAT_TIMESPAN(s
->timeout_stop_usec
, USEC_PER_SEC
),
1020 prefix
, service_timeout_failure_mode_to_string(s
->timeout_start_failure_mode
),
1021 prefix
, service_timeout_failure_mode_to_string(s
->timeout_stop_failure_mode
));
1023 if (s
->timeout_abort_set
)
1025 "%sTimeoutAbortSec: %s\n",
1026 prefix
, FORMAT_TIMESPAN(s
->timeout_abort_usec
, USEC_PER_SEC
));
1029 "%sRuntimeMaxSec: %s\n"
1030 "%sRuntimeRandomizedExtraSec: %s\n"
1031 "%sWatchdogSec: %s\n",
1032 prefix
, FORMAT_TIMESPAN(s
->runtime_max_usec
, USEC_PER_SEC
),
1033 prefix
, FORMAT_TIMESPAN(s
->runtime_rand_extra_usec
, USEC_PER_SEC
),
1034 prefix
, FORMAT_TIMESPAN(s
->watchdog_usec
, USEC_PER_SEC
));
1036 kill_context_dump(&s
->kill_context
, f
, prefix
);
1037 exec_context_dump(&s
->exec_context
, f
, prefix
);
1039 for (ServiceExecCommand c
= 0; c
< _SERVICE_EXEC_COMMAND_MAX
; c
++) {
1040 if (!s
->exec_command
[c
])
1043 fprintf(f
, "%s-> %s:\n",
1044 prefix
, service_exec_command_to_string(c
));
1046 exec_command_dump_list(s
->exec_command
[c
], f
, prefix2
);
1050 fprintf(f
, "%sStatus Text: %s\n",
1051 prefix
, s
->status_text
);
1053 if (s
->n_fd_store_max
> 0)
1055 "%sFile Descriptor Store Max: %u\n"
1056 "%sFile Descriptor Store Pin: %s\n"
1057 "%sFile Descriptor Store Current: %zu\n",
1058 prefix
, s
->n_fd_store_max
,
1059 prefix
, exec_preserve_mode_to_string(s
->fd_store_preserve_mode
),
1060 prefix
, s
->n_fd_store
);
1062 service_dump_fdstore(s
, f
, prefix
);
1065 LIST_FOREACH(open_files
, of
, s
->open_files
) {
1066 _cleanup_free_
char *ofs
= NULL
;
1069 r
= open_file_to_string(of
, &ofs
);
1072 "Failed to convert OpenFile= setting to string, ignoring: %m");
1076 fprintf(f
, "%sOpen File: %s\n", prefix
, ofs
);
1079 cgroup_context_dump(UNIT(s
), f
, prefix
);
1082 static int service_is_suitable_main_pid(Service
*s
, pid_t pid
, int prio
) {
1086 assert(pid_is_valid(pid
));
1088 /* Checks whether the specified PID is suitable as main PID for this service. returns negative if not, 0 if the
1089 * PID is questionnable but should be accepted if the source of configuration is trusted. > 0 if the PID is
1092 if (pid
== getpid_cached() || pid
== 1)
1093 return log_unit_full_errno(UNIT(s
), prio
, SYNTHETIC_ERRNO(EPERM
), "New main PID "PID_FMT
" is the manager, refusing.", pid
);
1095 if (pid
== s
->control_pid
.pid
)
1096 return log_unit_full_errno(UNIT(s
), prio
, SYNTHETIC_ERRNO(EPERM
), "New main PID "PID_FMT
" is the control process, refusing.", pid
);
1098 if (!pid_is_alive(pid
))
1099 return log_unit_full_errno(UNIT(s
), prio
, SYNTHETIC_ERRNO(ESRCH
), "New main PID "PID_FMT
" does not exist or is a zombie.", pid
);
1101 owner
= manager_get_unit_by_pid(UNIT(s
)->manager
, pid
);
1102 if (owner
== UNIT(s
)) {
1103 log_unit_debug(UNIT(s
), "New main PID "PID_FMT
" belongs to service, we are happy.", pid
);
1104 return 1; /* Yay, it's definitely a good PID */
1107 return 0; /* Hmm it's a suspicious PID, let's accept it if configuration source is trusted */
1110 static int service_load_pid_file(Service
*s
, bool may_warn
) {
1111 bool questionable_pid_file
= false;
1112 _cleanup_free_
char *k
= NULL
;
1113 _cleanup_close_
int fd
= -EBADF
;
1122 prio
= may_warn
? LOG_INFO
: LOG_DEBUG
;
1124 r
= chase(s
->pid_file
, NULL
, CHASE_SAFE
, NULL
, &fd
);
1125 if (r
== -ENOLINK
) {
1126 log_unit_debug_errno(UNIT(s
), r
,
1127 "Potentially unsafe symlink chain, will now retry with relaxed checks: %s", s
->pid_file
);
1129 questionable_pid_file
= true;
1131 r
= chase(s
->pid_file
, NULL
, 0, NULL
, &fd
);
1134 return log_unit_full_errno(UNIT(s
), prio
, r
,
1135 "Can't open PID file %s (yet?) after %s: %m", s
->pid_file
, service_state_to_string(s
->state
));
1137 /* Let's read the PID file now that we chased it down. But we need to convert the O_PATH fd
1138 * chase() returned us into a proper fd first. */
1139 r
= read_one_line_file(FORMAT_PROC_FD_PATH(fd
), &k
);
1141 return log_unit_error_errno(UNIT(s
), r
,
1142 "Can't convert PID files %s O_PATH file descriptor to proper file descriptor: %m",
1145 r
= parse_pid(k
, &pid
);
1147 return log_unit_full_errno(UNIT(s
), prio
, r
, "Failed to parse PID from file %s: %m", s
->pid_file
);
1149 if (s
->main_pid_known
&& pid
== s
->main_pid
.pid
)
1152 r
= service_is_suitable_main_pid(s
, pid
, prio
);
1158 if (questionable_pid_file
)
1159 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(EPERM
),
1160 "Refusing to accept PID outside of service control group, acquired through unsafe symlink chain: %s", s
->pid_file
);
1162 /* Hmm, it's not clear if the new main PID is safe. Let's allow this if the PID file is owned by root */
1164 if (fstat(fd
, &st
) < 0)
1165 return log_unit_error_errno(UNIT(s
), errno
, "Failed to fstat() PID file O_PATH fd: %m");
1168 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(EPERM
),
1169 "New main PID "PID_FMT
" does not belong to service, and PID file is not owned by root. Refusing.", pid
);
1171 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.", pid
);
1174 if (s
->main_pid_known
) {
1175 log_unit_debug(UNIT(s
), "Main PID changing: "PID_FMT
" -> "PID_FMT
, s
->main_pid
.pid
, pid
);
1177 service_unwatch_main_pid(s
);
1178 s
->main_pid_known
= false;
1180 log_unit_debug(UNIT(s
), "Main PID loaded: "PID_FMT
, pid
);
1182 r
= service_set_main_pid(s
, pid
);
1186 r
= unit_watch_pid(UNIT(s
), pid
, /* exclusive= */ false);
1187 if (r
< 0) /* FIXME: we need to do something here */
1188 return log_unit_warning_errno(UNIT(s
), r
, "Failed to watch PID "PID_FMT
" for service: %m", pid
);
1193 static void service_search_main_pid(Service
*s
) {
1199 /* If we know it anyway, don't ever fall back to unreliable heuristics */
1200 if (s
->main_pid_known
)
1203 if (!s
->guess_main_pid
)
1206 assert(!pidref_is_set(&s
->main_pid
));
1208 if (unit_search_main_pid(UNIT(s
), &pid
) < 0)
1211 log_unit_debug(UNIT(s
), "Main PID guessed: "PID_FMT
, pid
);
1212 if (service_set_main_pid(s
, pid
) < 0)
1215 r
= unit_watch_pid(UNIT(s
), pid
, /* exclusive= */ false);
1217 /* FIXME: we need to do something here */
1218 log_unit_warning_errno(UNIT(s
), r
, "Failed to watch PID "PID_FMT
" from: %m", pid
);
1221 static void service_set_state(Service
*s
, ServiceState state
) {
1222 ServiceState old_state
;
1223 const UnitActiveState
*table
;
1227 if (s
->state
!= state
)
1228 bus_unit_send_pending_change_signal(UNIT(s
), false);
1230 table
= s
->type
== SERVICE_IDLE
? state_translation_table_idle
: state_translation_table
;
1232 old_state
= s
->state
;
1235 service_unwatch_pid_file(s
);
1238 SERVICE_CONDITION
, SERVICE_START_PRE
, SERVICE_START
, SERVICE_START_POST
,
1240 SERVICE_RELOAD
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
,
1241 SERVICE_STOP
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
, SERVICE_STOP_POST
,
1242 SERVICE_FINAL_WATCHDOG
, SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
,
1243 SERVICE_AUTO_RESTART
,
1245 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
1248 SERVICE_START
, SERVICE_START_POST
,
1250 SERVICE_RELOAD
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
,
1251 SERVICE_STOP
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
, SERVICE_STOP_POST
,
1252 SERVICE_FINAL_WATCHDOG
, SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
)) {
1253 service_unwatch_main_pid(s
);
1254 s
->main_command
= NULL
;
1258 SERVICE_CONDITION
, SERVICE_START_PRE
, SERVICE_START
, SERVICE_START_POST
,
1259 SERVICE_RELOAD
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
,
1260 SERVICE_STOP
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
, SERVICE_STOP_POST
,
1261 SERVICE_FINAL_WATCHDOG
, SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
,
1262 SERVICE_CLEANING
)) {
1263 service_unwatch_control_pid(s
);
1264 s
->control_command
= NULL
;
1265 s
->control_command_id
= _SERVICE_EXEC_COMMAND_INVALID
;
1269 SERVICE_DEAD
, SERVICE_FAILED
,
1270 SERVICE_DEAD_BEFORE_AUTO_RESTART
, SERVICE_FAILED_BEFORE_AUTO_RESTART
, SERVICE_AUTO_RESTART
, SERVICE_AUTO_RESTART_QUEUED
,
1271 SERVICE_DEAD_RESOURCES_PINNED
)) {
1272 unit_unwatch_all_pids(UNIT(s
));
1273 unit_dequeue_rewatch_pids(UNIT(s
));
1276 if (state
!= SERVICE_START
)
1277 s
->exec_fd_event_source
= sd_event_source_disable_unref(s
->exec_fd_event_source
);
1279 if (!IN_SET(state
, SERVICE_START_POST
, SERVICE_RUNNING
, SERVICE_RELOAD
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
))
1280 service_stop_watchdog(s
);
1282 /* For the inactive states unit_notify() will trim the cgroup,
1283 * but for exit we have to do that ourselves... */
1284 if (state
== SERVICE_EXITED
&& !MANAGER_IS_RELOADING(UNIT(s
)->manager
))
1285 unit_prune_cgroup(UNIT(s
));
1287 if (old_state
!= state
)
1288 log_unit_debug(UNIT(s
), "Changed %s -> %s", service_state_to_string(old_state
), service_state_to_string(state
));
1290 unit_notify(UNIT(s
), table
[old_state
], table
[state
], s
->reload_result
== SERVICE_SUCCESS
);
1293 static usec_t
service_coldplug_timeout(Service
*s
) {
1296 switch (s
->deserialized_state
) {
1298 case SERVICE_CONDITION
:
1299 case SERVICE_START_PRE
:
1301 case SERVICE_START_POST
:
1302 case SERVICE_RELOAD
:
1303 case SERVICE_RELOAD_SIGNAL
:
1304 case SERVICE_RELOAD_NOTIFY
:
1305 return usec_add(UNIT(s
)->state_change_timestamp
.monotonic
, s
->timeout_start_usec
);
1307 case SERVICE_RUNNING
:
1308 return service_running_timeout(s
);
1311 case SERVICE_STOP_SIGTERM
:
1312 case SERVICE_STOP_SIGKILL
:
1313 case SERVICE_STOP_POST
:
1314 case SERVICE_FINAL_SIGTERM
:
1315 case SERVICE_FINAL_SIGKILL
:
1316 return usec_add(UNIT(s
)->state_change_timestamp
.monotonic
, s
->timeout_stop_usec
);
1318 case SERVICE_STOP_WATCHDOG
:
1319 case SERVICE_FINAL_WATCHDOG
:
1320 return usec_add(UNIT(s
)->state_change_timestamp
.monotonic
, service_timeout_abort_usec(s
));
1322 case SERVICE_AUTO_RESTART
:
1323 return usec_add(UNIT(s
)->inactive_enter_timestamp
.monotonic
, service_restart_usec_next(s
));
1325 case SERVICE_CLEANING
:
1326 return usec_add(UNIT(s
)->state_change_timestamp
.monotonic
, s
->exec_context
.timeout_clean_usec
);
1329 return USEC_INFINITY
;
1333 static int service_coldplug(Unit
*u
) {
1334 Service
*s
= SERVICE(u
);
1338 assert(s
->state
== SERVICE_DEAD
);
1340 if (s
->deserialized_state
== s
->state
)
1343 r
= service_arm_timer(s
, /* relative= */ false, service_coldplug_timeout(s
));
1347 if (pidref_is_set(&s
->main_pid
) &&
1348 pid_is_unwaited(s
->main_pid
.pid
) &&
1349 (IN_SET(s
->deserialized_state
,
1350 SERVICE_START
, SERVICE_START_POST
,
1352 SERVICE_RELOAD
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
,
1353 SERVICE_STOP
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
, SERVICE_STOP_POST
,
1354 SERVICE_FINAL_WATCHDOG
, SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
))) {
1355 r
= unit_watch_pid(UNIT(s
), s
->main_pid
.pid
, /* exclusive= */ false);
1360 if (pidref_is_set(&s
->control_pid
) &&
1361 pid_is_unwaited(s
->control_pid
.pid
) &&
1362 IN_SET(s
->deserialized_state
,
1363 SERVICE_CONDITION
, SERVICE_START_PRE
, SERVICE_START
, SERVICE_START_POST
,
1364 SERVICE_RELOAD
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
,
1365 SERVICE_STOP
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
, SERVICE_STOP_POST
,
1366 SERVICE_FINAL_WATCHDOG
, SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
,
1367 SERVICE_CLEANING
)) {
1368 r
= unit_watch_pid(UNIT(s
), s
->control_pid
.pid
, /* exclusive= */ false);
1373 if (!IN_SET(s
->deserialized_state
,
1374 SERVICE_DEAD
, SERVICE_FAILED
,
1375 SERVICE_DEAD_BEFORE_AUTO_RESTART
, SERVICE_FAILED_BEFORE_AUTO_RESTART
, SERVICE_AUTO_RESTART
, SERVICE_AUTO_RESTART_QUEUED
,
1377 SERVICE_DEAD_RESOURCES_PINNED
)) {
1378 (void) unit_enqueue_rewatch_pids(u
);
1379 (void) unit_setup_exec_runtime(u
);
1382 if (IN_SET(s
->deserialized_state
, SERVICE_START_POST
, SERVICE_RUNNING
, SERVICE_RELOAD
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
))
1383 service_start_watchdog(s
);
1385 if (UNIT_ISSET(s
->accept_socket
)) {
1386 Socket
* socket
= SOCKET(UNIT_DEREF(s
->accept_socket
));
1388 if (socket
->max_connections_per_source
> 0) {
1391 /* Make a best-effort attempt at bumping the connection count */
1392 if (socket_acquire_peer(socket
, s
->socket_fd
, &peer
) > 0) {
1393 socket_peer_unref(s
->socket_peer
);
1394 s
->socket_peer
= peer
;
1399 service_set_state(s
, s
->deserialized_state
);
1403 static int service_collect_fds(
1407 size_t *n_socket_fds
,
1408 size_t *n_storage_fds
) {
1410 _cleanup_strv_free_
char **rfd_names
= NULL
;
1411 _cleanup_free_
int *rfds
= NULL
;
1412 size_t rn_socket_fds
= 0, rn_storage_fds
= 0;
1418 assert(n_socket_fds
);
1419 assert(n_storage_fds
);
1421 if (s
->socket_fd
>= 0) {
1423 /* Pass the per-connection socket */
1425 rfds
= newdup(int, &s
->socket_fd
, 1);
1429 rfd_names
= strv_new("connection");
1437 /* Pass all our configured sockets for singleton services */
1439 UNIT_FOREACH_DEPENDENCY(u
, UNIT(s
), UNIT_ATOM_TRIGGERED_BY
) {
1440 _cleanup_free_
int *cfds
= NULL
;
1444 if (u
->type
!= UNIT_SOCKET
)
1449 cn_fds
= socket_collect_fds(sock
, &cfds
);
1457 rfds
= TAKE_PTR(cfds
);
1458 rn_socket_fds
= cn_fds
;
1462 t
= reallocarray(rfds
, rn_socket_fds
+ cn_fds
, sizeof(int));
1466 memcpy(t
+ rn_socket_fds
, cfds
, cn_fds
* sizeof(int));
1469 rn_socket_fds
+= cn_fds
;
1472 r
= strv_extend_n(&rfd_names
, socket_fdname(sock
), cn_fds
);
1478 if (s
->n_fd_store
> 0) {
1483 t
= reallocarray(rfds
, rn_socket_fds
+ s
->n_fd_store
, sizeof(int));
1489 nl
= reallocarray(rfd_names
, rn_socket_fds
+ s
->n_fd_store
+ 1, sizeof(char *));
1494 n_fds
= rn_socket_fds
;
1496 LIST_FOREACH(fd_store
, fs
, s
->fd_store
) {
1497 rfds
[n_fds
] = fs
->fd
;
1498 rfd_names
[n_fds
] = strdup(strempty(fs
->fdname
));
1499 if (!rfd_names
[n_fds
])
1506 rfd_names
[n_fds
] = NULL
;
1509 *fds
= TAKE_PTR(rfds
);
1510 *fd_names
= TAKE_PTR(rfd_names
);
1511 *n_socket_fds
= rn_socket_fds
;
1512 *n_storage_fds
= rn_storage_fds
;
1517 static int service_allocate_exec_fd_event_source(
1520 sd_event_source
**ret_event_source
) {
1522 _cleanup_(sd_event_source_unrefp
) sd_event_source
*source
= NULL
;
1527 assert(ret_event_source
);
1529 r
= sd_event_add_io(UNIT(s
)->manager
->event
, &source
, fd
, 0, service_dispatch_exec_io
, s
);
1531 return log_unit_error_errno(UNIT(s
), r
, "Failed to allocate exec_fd event source: %m");
1533 /* This is a bit lower priority than SIGCHLD, as that carries a lot more interesting failure information */
1535 r
= sd_event_source_set_priority(source
, SD_EVENT_PRIORITY_NORMAL
-3);
1537 return log_unit_error_errno(UNIT(s
), r
, "Failed to adjust priority of exec_fd event source: %m");
1539 (void) sd_event_source_set_description(source
, "service exec_fd");
1541 r
= sd_event_source_set_io_fd_own(source
, true);
1543 return log_unit_error_errno(UNIT(s
), r
, "Failed to pass ownership of fd to event source: %m");
1545 *ret_event_source
= TAKE_PTR(source
);
1549 static int service_allocate_exec_fd(
1551 sd_event_source
**ret_event_source
,
1554 _cleanup_close_pair_
int p
[] = PIPE_EBADF
;
1558 assert(ret_event_source
);
1559 assert(ret_exec_fd
);
1561 if (pipe2(p
, O_CLOEXEC
|O_NONBLOCK
) < 0)
1562 return log_unit_error_errno(UNIT(s
), errno
, "Failed to allocate exec_fd pipe: %m");
1564 r
= service_allocate_exec_fd_event_source(s
, p
[0], ret_event_source
);
1569 *ret_exec_fd
= TAKE_FD(p
[1]);
1574 static bool service_exec_needs_notify_socket(Service
*s
, ExecFlags flags
) {
1577 /* Notifications are accepted depending on the process and
1578 * the access setting of the service:
1579 * process: \ access: NONE MAIN EXEC ALL
1580 * main no yes yes yes
1581 * control no no yes yes
1582 * other (forked) no no no yes */
1584 if (flags
& EXEC_IS_CONTROL
)
1585 /* A control process */
1586 return IN_SET(service_get_notify_access(s
), NOTIFY_EXEC
, NOTIFY_ALL
);
1588 /* We only spawn main processes and control processes, so any
1589 * process that is not a control process is a main process */
1590 return service_get_notify_access(s
) != NOTIFY_NONE
;
1593 static Service
*service_get_triggering_service(Service
*s
) {
1594 Unit
*candidate
= NULL
, *other
;
1598 /* Return the service which triggered service 's', this means dependency
1599 * types which include the UNIT_ATOM_ON_{FAILURE,SUCCESS}_OF atoms.
1601 * N.B. if there are multiple services which could trigger 's' via OnFailure=
1602 * or OnSuccess= then we return NULL. This is since we don't know from which
1603 * one to propagate the exit status. */
1605 UNIT_FOREACH_DEPENDENCY(other
, UNIT(s
), UNIT_ATOM_ON_FAILURE_OF
) {
1611 UNIT_FOREACH_DEPENDENCY(other
, UNIT(s
), UNIT_ATOM_ON_SUCCESS_OF
) {
1617 return SERVICE(candidate
);
1620 log_unit_warning(UNIT(s
), "multiple trigger source candidates for exit status propagation (%s, %s), skipping.",
1621 candidate
->id
, other
->id
);
1625 static int service_spawn_internal(
1633 _cleanup_(exec_params_clear
) ExecParameters exec_params
= {
1636 .stdout_fd
= -EBADF
,
1637 .stderr_fd
= -EBADF
,
1640 _cleanup_(sd_event_source_unrefp
) sd_event_source
*exec_fd_source
= NULL
;
1641 _cleanup_strv_free_
char **final_env
= NULL
, **our_env
= NULL
;
1642 _cleanup_(pidref_done
) PidRef pidref
= PIDREF_NULL
;
1652 log_unit_debug(UNIT(s
), "Will spawn child (%s): %s", caller
, c
->path
);
1654 r
= unit_prepare_exec(UNIT(s
)); /* This realizes the cgroup, among other things */
1658 assert(!s
->exec_fd_event_source
);
1660 if (flags
& EXEC_IS_CONTROL
) {
1661 /* If this is a control process, mask the permissions/chroot application if this is requested. */
1662 if (s
->permissions_start_only
)
1663 exec_params
.flags
&= ~EXEC_APPLY_SANDBOXING
;
1664 if (s
->root_directory_start_only
)
1665 exec_params
.flags
&= ~EXEC_APPLY_CHROOT
;
1668 if ((flags
& EXEC_PASS_FDS
) ||
1669 s
->exec_context
.std_input
== EXEC_INPUT_SOCKET
||
1670 s
->exec_context
.std_output
== EXEC_OUTPUT_SOCKET
||
1671 s
->exec_context
.std_error
== EXEC_OUTPUT_SOCKET
) {
1673 r
= service_collect_fds(s
,
1675 &exec_params
.fd_names
,
1676 &exec_params
.n_socket_fds
,
1677 &exec_params
.n_storage_fds
);
1681 exec_params
.open_files
= s
->open_files
;
1683 log_unit_debug(UNIT(s
), "Passing %zu fds to service", exec_params
.n_socket_fds
+ exec_params
.n_storage_fds
);
1686 if (!FLAGS_SET(flags
, EXEC_IS_CONTROL
) && s
->type
== SERVICE_EXEC
) {
1687 r
= service_allocate_exec_fd(s
, &exec_fd_source
, &exec_params
.exec_fd
);
1692 r
= service_arm_timer(s
, /* relative= */ true, timeout
);
1696 our_env
= new0(char*, 13);
1700 if (service_exec_needs_notify_socket(s
, flags
)) {
1701 if (asprintf(our_env
+ n_env
++, "NOTIFY_SOCKET=%s", UNIT(s
)->manager
->notify_socket
) < 0)
1704 exec_params
.notify_socket
= UNIT(s
)->manager
->notify_socket
;
1706 if (s
->n_fd_store_max
> 0)
1707 if (asprintf(our_env
+ n_env
++, "FDSTORE=%u", s
->n_fd_store_max
) < 0)
1711 if (pidref_is_set(&s
->main_pid
))
1712 if (asprintf(our_env
+ n_env
++, "MAINPID="PID_FMT
, s
->main_pid
.pid
) < 0)
1715 if (MANAGER_IS_USER(UNIT(s
)->manager
))
1716 if (asprintf(our_env
+ n_env
++, "MANAGERPID="PID_FMT
, getpid_cached()) < 0)
1720 if (asprintf(our_env
+ n_env
++, "PIDFILE=%s", s
->pid_file
) < 0)
1723 if (s
->socket_fd
>= 0) {
1724 union sockaddr_union sa
;
1725 socklen_t salen
= sizeof(sa
);
1727 /* If this is a per-connection service instance, let's set $REMOTE_ADDR and $REMOTE_PORT to something
1728 * useful. Note that we do this only when we are still connected at this point in time, which we might
1729 * very well not be. Hence we ignore all errors when retrieving peer information (as that might result
1730 * in ENOTCONN), and just use whate we can use. */
1732 if (getpeername(s
->socket_fd
, &sa
.sa
, &salen
) >= 0 &&
1733 IN_SET(sa
.sa
.sa_family
, AF_INET
, AF_INET6
, AF_VSOCK
)) {
1734 _cleanup_free_
char *addr
= NULL
;
1738 r
= sockaddr_pretty(&sa
.sa
, salen
, true, false, &addr
);
1742 t
= strjoin("REMOTE_ADDR=", addr
);
1745 our_env
[n_env
++] = t
;
1747 r
= sockaddr_port(&sa
.sa
, &port
);
1751 if (asprintf(&t
, "REMOTE_PORT=%u", port
) < 0)
1753 our_env
[n_env
++] = t
;
1757 Service
*env_source
= NULL
;
1758 const char *monitor_prefix
;
1759 if (flags
& EXEC_SETENV_RESULT
) {
1761 monitor_prefix
= "";
1762 } else if (flags
& EXEC_SETENV_MONITOR_RESULT
) {
1763 env_source
= service_get_triggering_service(s
);
1764 monitor_prefix
= "MONITOR_";
1768 if (asprintf(our_env
+ n_env
++, "%sSERVICE_RESULT=%s", monitor_prefix
, service_result_to_string(env_source
->result
)) < 0)
1771 if (env_source
->main_exec_status
.pid
> 0 &&
1772 dual_timestamp_is_set(&env_source
->main_exec_status
.exit_timestamp
)) {
1773 if (asprintf(our_env
+ n_env
++, "%sEXIT_CODE=%s", monitor_prefix
, sigchld_code_to_string(env_source
->main_exec_status
.code
)) < 0)
1776 if (env_source
->main_exec_status
.code
== CLD_EXITED
)
1777 r
= asprintf(our_env
+ n_env
++, "%sEXIT_STATUS=%i", monitor_prefix
, env_source
->main_exec_status
.status
);
1779 r
= asprintf(our_env
+ n_env
++, "%sEXIT_STATUS=%s", monitor_prefix
, signal_to_string(env_source
->main_exec_status
.status
));
1785 if (env_source
!= s
) {
1786 if (!sd_id128_is_null(UNIT(env_source
)->invocation_id
)) {
1787 r
= asprintf(our_env
+ n_env
++, "%sINVOCATION_ID=" SD_ID128_FORMAT_STR
,
1788 monitor_prefix
, SD_ID128_FORMAT_VAL(UNIT(env_source
)->invocation_id
));
1793 if (asprintf(our_env
+ n_env
++, "%sUNIT=%s", monitor_prefix
, UNIT(env_source
)->id
) < 0)
1798 if (UNIT(s
)->activation_details
) {
1799 r
= activation_details_append_env(UNIT(s
)->activation_details
, &our_env
);
1802 /* The number of env vars added here can vary, rather than keeping the allocation block in
1803 * sync manually, these functions simply use the strv methods to append to it, so we need
1804 * to update n_env when we are done in case of future usage. */
1808 r
= unit_set_exec_params(UNIT(s
), &exec_params
);
1812 final_env
= strv_env_merge(exec_params
.environment
, our_env
);
1816 /* System D-Bus needs nss-systemd disabled, so that we don't deadlock */
1817 SET_FLAG(exec_params
.flags
, EXEC_NSS_DYNAMIC_BYPASS
,
1818 MANAGER_IS_SYSTEM(UNIT(s
)->manager
) && unit_has_name(UNIT(s
), SPECIAL_DBUS_SERVICE
));
1820 strv_free_and_replace(exec_params
.environment
, final_env
);
1821 exec_params
.watchdog_usec
= service_get_watchdog_usec(s
);
1822 exec_params
.selinux_context_net
= s
->socket_fd_selinux_context_net
;
1823 if (s
->type
== SERVICE_IDLE
)
1824 exec_params
.idle_pipe
= UNIT(s
)->manager
->idle_pipe
;
1825 exec_params
.stdin_fd
= s
->stdin_fd
;
1826 exec_params
.stdout_fd
= s
->stdout_fd
;
1827 exec_params
.stderr_fd
= s
->stderr_fd
;
1829 r
= exec_spawn(UNIT(s
),
1839 s
->exec_fd_event_source
= TAKE_PTR(exec_fd_source
);
1840 s
->exec_fd_hot
= false;
1842 r
= pidref_set_pid(&pidref
, pid
);
1846 r
= unit_watch_pid(UNIT(s
), pidref
.pid
, /* exclusive= */ true);
1850 *ret_pid
= TAKE_PIDREF(pidref
);
1854 static int main_pid_good(Service
*s
) {
1857 /* Returns 0 if the pid is dead, > 0 if it is good, < 0 if we don't know */
1859 /* If we know the pid file, then let's just check if it is still valid */
1860 if (s
->main_pid_known
) {
1862 /* If it's an alien child let's check if it is still alive ... */
1863 if (s
->main_pid_alien
&& pidref_is_set(&s
->main_pid
))
1864 return pid_is_alive(s
->main_pid
.pid
);
1866 /* .. otherwise assume we'll get a SIGCHLD for it, which we really should wait for to collect
1867 * exit status and code */
1868 return pidref_is_set(&s
->main_pid
);
1871 /* We don't know the pid */
1875 static int control_pid_good(Service
*s
) {
1878 /* Returns 0 if the control PID is dead, > 0 if it is good. We never actually return < 0 here, but in order to
1879 * make this function as similar as possible to main_pid_good() and cgroup_good(), we pretend that < 0 also
1880 * means: we can't figure it out. */
1882 return pidref_is_set(&s
->control_pid
);
1885 static int cgroup_good(Service
*s
) {
1890 /* Returns 0 if the cgroup is empty or doesn't exist, > 0 if it is exists and is populated, < 0 if we can't
1893 if (!UNIT(s
)->cgroup_path
)
1896 r
= cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER
, UNIT(s
)->cgroup_path
);
1903 static bool service_shall_restart(Service
*s
, const char **reason
) {
1906 /* Don't restart after manual stops */
1907 if (s
->forbid_restart
) {
1908 *reason
= "manual stop";
1912 /* Never restart if this is configured as special exception */
1913 if (exit_status_set_test(&s
->restart_prevent_status
, s
->main_exec_status
.code
, s
->main_exec_status
.status
)) {
1914 *reason
= "prevented by exit status";
1918 /* Restart if the exit code/status are configured as restart triggers */
1919 if (exit_status_set_test(&s
->restart_force_status
, s
->main_exec_status
.code
, s
->main_exec_status
.status
)) {
1920 *reason
= "forced by exit status";
1924 *reason
= "restart setting";
1925 switch (s
->restart
) {
1927 case SERVICE_RESTART_NO
:
1930 case SERVICE_RESTART_ALWAYS
:
1931 return s
->result
!= SERVICE_SKIP_CONDITION
;
1933 case SERVICE_RESTART_ON_SUCCESS
:
1934 return s
->result
== SERVICE_SUCCESS
;
1936 case SERVICE_RESTART_ON_FAILURE
:
1937 return !IN_SET(s
->result
, SERVICE_SUCCESS
, SERVICE_SKIP_CONDITION
);
1939 case SERVICE_RESTART_ON_ABNORMAL
:
1940 return !IN_SET(s
->result
, SERVICE_SUCCESS
, SERVICE_FAILURE_EXIT_CODE
, SERVICE_SKIP_CONDITION
);
1942 case SERVICE_RESTART_ON_WATCHDOG
:
1943 return s
->result
== SERVICE_FAILURE_WATCHDOG
;
1945 case SERVICE_RESTART_ON_ABORT
:
1946 return IN_SET(s
->result
, SERVICE_FAILURE_SIGNAL
, SERVICE_FAILURE_CORE_DUMP
);
1949 assert_not_reached();
1953 static bool service_will_restart(Unit
*u
) {
1954 Service
*s
= SERVICE(u
);
1958 if (IN_SET(s
->state
, SERVICE_DEAD_BEFORE_AUTO_RESTART
, SERVICE_FAILED_BEFORE_AUTO_RESTART
, SERVICE_AUTO_RESTART
, SERVICE_AUTO_RESTART_QUEUED
))
1961 return unit_will_restart_default(u
);
1964 static ServiceState
service_determine_dead_state(Service
*s
) {
1967 return s
->fd_store
&& s
->fd_store_preserve_mode
== EXEC_PRESERVE_YES
? SERVICE_DEAD_RESOURCES_PINNED
: SERVICE_DEAD
;
1970 static void service_enter_dead(Service
*s
, ServiceResult f
, bool allow_restart
) {
1971 ServiceState end_state
, restart_state
;
1976 /* If there's a stop job queued before we enter the DEAD state, we shouldn't act on Restart=, in order to not
1977 * undo what has already been enqueued. */
1978 if (unit_stop_pending(UNIT(s
)))
1979 allow_restart
= false;
1981 if (s
->result
== SERVICE_SUCCESS
)
1984 if (s
->result
== SERVICE_SUCCESS
) {
1985 unit_log_success(UNIT(s
));
1986 end_state
= service_determine_dead_state(s
);
1987 restart_state
= SERVICE_DEAD_BEFORE_AUTO_RESTART
;
1988 } else if (s
->result
== SERVICE_SKIP_CONDITION
) {
1989 unit_log_skip(UNIT(s
), service_result_to_string(s
->result
));
1990 end_state
= service_determine_dead_state(s
);
1991 restart_state
= SERVICE_DEAD_BEFORE_AUTO_RESTART
;
1993 unit_log_failure(UNIT(s
), service_result_to_string(s
->result
));
1994 end_state
= SERVICE_FAILED
;
1995 restart_state
= SERVICE_FAILED_BEFORE_AUTO_RESTART
;
1997 unit_warn_leftover_processes(UNIT(s
), unit_log_leftover_process_stop
);
2000 log_unit_debug(UNIT(s
), "Service restart not allowed.");
2004 allow_restart
= service_shall_restart(s
, &reason
);
2005 log_unit_debug(UNIT(s
), "Service will %srestart (%s)",
2006 allow_restart
? "" : "not ",
2010 if (allow_restart
) {
2011 /* We make two state changes here: one that maps to the high-level UNIT_INACTIVE/UNIT_FAILED
2012 * state (i.e. a state indicating deactivation), and then one that that maps to the
2013 * high-level UNIT_STARTING state (i.e. a state indicating activation). We do this so that
2014 * external software can watch the state changes and see all service failures, even if they
2015 * are only transitionary and followed by an automatic restart. We have fine-grained
2016 * low-level states for this though so that software can distinguish the permanent UNIT_INACTIVE
2017 * state from this transitionary UNIT_INACTIVE state by looking at the low-level states. */
2018 if (s
->restart_mode
!= SERVICE_RESTART_MODE_DIRECT
)
2019 service_set_state(s
, restart_state
);
2021 r
= service_arm_timer(s
, /* relative= */ true, service_restart_usec_next(s
));
2025 service_set_state(s
, SERVICE_AUTO_RESTART
);
2027 service_set_state(s
, end_state
);
2029 /* If we shan't restart, then flush out the restart counter. But don't do that immediately, so that the
2030 * user can still introspect the counter. Do so on the next start. */
2031 s
->flush_n_restarts
= true;
2034 /* The new state is in effect, let's decrease the fd store ref counter again. Let's also re-add us to the GC
2035 * queue, so that the fd store is possibly gc'ed again */
2036 unit_add_to_gc_queue(UNIT(s
));
2038 /* The next restart might not be a manual stop, hence reset the flag indicating manual stops */
2039 s
->forbid_restart
= false;
2041 /* Reset NotifyAccess override */
2042 s
->notify_access_override
= _NOTIFY_ACCESS_INVALID
;
2044 /* We want fresh tmpdirs and ephemeral snapshots in case the service is started again immediately. */
2045 s
->exec_runtime
= exec_runtime_destroy(s
->exec_runtime
);
2047 /* Also, remove the runtime directory */
2048 unit_destroy_runtime_data(UNIT(s
), &s
->exec_context
);
2050 /* Also get rid of the fd store, if that's configured. */
2051 if (s
->fd_store_preserve_mode
== EXEC_PRESERVE_NO
)
2052 service_release_fd_store(s
);
2054 /* Get rid of the IPC bits of the user */
2055 unit_unref_uid_gid(UNIT(s
), true);
2057 /* Try to delete the pid file. At this point it will be
2058 * out-of-date, and some software might be confused by it, so
2059 * let's remove it. */
2061 (void) unlink(s
->pid_file
);
2063 /* Reset TTY ownership if necessary */
2064 exec_context_revert_tty(&s
->exec_context
);
2069 log_unit_warning_errno(UNIT(s
), r
, "Failed to run install restart timer: %m");
2070 service_enter_dead(s
, SERVICE_FAILURE_RESOURCES
, false);
2073 static void service_enter_stop_post(Service
*s
, ServiceResult f
) {
2077 if (s
->result
== SERVICE_SUCCESS
)
2080 service_unwatch_control_pid(s
);
2081 (void) unit_enqueue_rewatch_pids(UNIT(s
));
2083 s
->control_command
= s
->exec_command
[SERVICE_EXEC_STOP_POST
];
2084 if (s
->control_command
) {
2085 s
->control_command_id
= SERVICE_EXEC_STOP_POST
;
2086 pidref_done(&s
->control_pid
);
2088 r
= service_spawn(s
,
2090 s
->timeout_stop_usec
,
2091 EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_APPLY_TTY_STDIN
|EXEC_IS_CONTROL
|EXEC_SETENV_RESULT
|EXEC_CONTROL_CGROUP
,
2096 service_set_state(s
, SERVICE_STOP_POST
);
2098 service_enter_signal(s
, SERVICE_FINAL_SIGTERM
, SERVICE_SUCCESS
);
2103 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'stop-post' task: %m");
2104 service_enter_signal(s
, SERVICE_FINAL_SIGTERM
, SERVICE_FAILURE_RESOURCES
);
2107 static int state_to_kill_operation(Service
*s
, ServiceState state
) {
2110 case SERVICE_STOP_WATCHDOG
:
2111 case SERVICE_FINAL_WATCHDOG
:
2112 return KILL_WATCHDOG
;
2114 case SERVICE_STOP_SIGTERM
:
2115 if (unit_has_job_type(UNIT(s
), JOB_RESTART
))
2116 return KILL_RESTART
;
2119 case SERVICE_FINAL_SIGTERM
:
2120 return KILL_TERMINATE
;
2122 case SERVICE_STOP_SIGKILL
:
2123 case SERVICE_FINAL_SIGKILL
:
2127 return _KILL_OPERATION_INVALID
;
2131 static void service_enter_signal(Service
*s
, ServiceState state
, ServiceResult f
) {
2132 int kill_operation
, r
;
2136 if (s
->result
== SERVICE_SUCCESS
)
2139 /* Before sending any signal, make sure we track all members of this cgroup */
2140 (void) unit_watch_all_pids(UNIT(s
));
2142 /* Also, enqueue a job that we recheck all our PIDs a bit later, given that it's likely some processes have
2144 (void) unit_enqueue_rewatch_pids(UNIT(s
));
2146 kill_operation
= state_to_kill_operation(s
, state
);
2147 r
= unit_kill_context(
2158 r
= service_arm_timer(s
, /* relative= */ true,
2159 kill_operation
== KILL_WATCHDOG
? service_timeout_abort_usec(s
) : s
->timeout_stop_usec
);
2163 service_set_state(s
, state
);
2164 } else if (IN_SET(state
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
) && s
->kill_context
.send_sigkill
)
2165 service_enter_signal(s
, SERVICE_STOP_SIGKILL
, SERVICE_SUCCESS
);
2166 else if (IN_SET(state
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
))
2167 service_enter_stop_post(s
, SERVICE_SUCCESS
);
2168 else if (IN_SET(state
, SERVICE_FINAL_WATCHDOG
, SERVICE_FINAL_SIGTERM
) && s
->kill_context
.send_sigkill
)
2169 service_enter_signal(s
, SERVICE_FINAL_SIGKILL
, SERVICE_SUCCESS
);
2171 service_enter_dead(s
, SERVICE_SUCCESS
, true);
2176 log_unit_warning_errno(UNIT(s
), r
, "Failed to kill processes: %m");
2178 if (IN_SET(state
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
))
2179 service_enter_stop_post(s
, SERVICE_FAILURE_RESOURCES
);
2181 service_enter_dead(s
, SERVICE_FAILURE_RESOURCES
, true);
2184 static void service_enter_stop_by_notify(Service
*s
) {
2187 (void) unit_enqueue_rewatch_pids(UNIT(s
));
2189 service_arm_timer(s
, /* relative= */ true, s
->timeout_stop_usec
);
2191 /* The service told us it's stopping, so it's as if we SIGTERM'd it. */
2192 service_set_state(s
, SERVICE_STOP_SIGTERM
);
2195 static void service_enter_stop(Service
*s
, ServiceResult f
) {
2200 if (s
->result
== SERVICE_SUCCESS
)
2203 service_unwatch_control_pid(s
);
2204 (void) unit_enqueue_rewatch_pids(UNIT(s
));
2206 s
->control_command
= s
->exec_command
[SERVICE_EXEC_STOP
];
2207 if (s
->control_command
) {
2208 s
->control_command_id
= SERVICE_EXEC_STOP
;
2209 pidref_done(&s
->control_pid
);
2211 r
= service_spawn(s
,
2213 s
->timeout_stop_usec
,
2214 EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_IS_CONTROL
|EXEC_SETENV_RESULT
|EXEC_CONTROL_CGROUP
,
2219 service_set_state(s
, SERVICE_STOP
);
2221 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_SUCCESS
);
2226 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'stop' task: %m");
2227 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_RESOURCES
);
2230 static bool service_good(Service
*s
) {
2234 if (s
->type
== SERVICE_DBUS
&& !s
->bus_name_good
)
2237 main_pid_ok
= main_pid_good(s
);
2238 if (main_pid_ok
> 0) /* It's alive */
2240 if (main_pid_ok
== 0 && s
->exit_type
== SERVICE_EXIT_MAIN
) /* It's dead */
2243 /* OK, we don't know anything about the main PID, maybe
2244 * because there is none. Let's check the control group
2247 return cgroup_good(s
) != 0;
2250 static void service_enter_running(Service
*s
, ServiceResult f
) {
2253 if (s
->result
== SERVICE_SUCCESS
)
2256 service_unwatch_control_pid(s
);
2258 if (s
->result
!= SERVICE_SUCCESS
)
2259 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
2260 else if (service_good(s
)) {
2262 /* If there are any queued up sd_notify() notifications, process them now */
2263 if (s
->notify_state
== NOTIFY_RELOADING
)
2264 service_enter_reload_by_notify(s
);
2265 else if (s
->notify_state
== NOTIFY_STOPPING
)
2266 service_enter_stop_by_notify(s
);
2268 service_set_state(s
, SERVICE_RUNNING
);
2269 service_arm_timer(s
, /* relative= */ false, service_running_timeout(s
));
2272 } else if (s
->remain_after_exit
)
2273 service_set_state(s
, SERVICE_EXITED
);
2275 service_enter_stop(s
, SERVICE_SUCCESS
);
2278 static void service_enter_start_post(Service
*s
) {
2282 service_unwatch_control_pid(s
);
2283 service_reset_watchdog(s
);
2285 s
->control_command
= s
->exec_command
[SERVICE_EXEC_START_POST
];
2286 if (s
->control_command
) {
2287 s
->control_command_id
= SERVICE_EXEC_START_POST
;
2288 pidref_done(&s
->control_pid
);
2290 r
= service_spawn(s
,
2292 s
->timeout_start_usec
,
2293 EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_IS_CONTROL
|EXEC_CONTROL_CGROUP
,
2298 service_set_state(s
, SERVICE_START_POST
);
2300 service_enter_running(s
, SERVICE_SUCCESS
);
2305 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'start-post' task: %m");
2306 service_enter_stop(s
, SERVICE_FAILURE_RESOURCES
);
2309 static void service_kill_control_process(Service
*s
) {
2314 if (!pidref_is_set(&s
->control_pid
))
2317 r
= pidref_kill_and_sigcont(&s
->control_pid
, SIGKILL
);
2319 _cleanup_free_
char *comm
= NULL
;
2321 (void) get_process_comm(s
->control_pid
.pid
, &comm
);
2323 log_unit_debug_errno(UNIT(s
), r
, "Failed to kill control process " PID_FMT
" (%s), ignoring: %m",
2324 s
->control_pid
.pid
, strna(comm
));
2328 static int service_adverse_to_leftover_processes(Service
*s
) {
2331 /* KillMode=mixed and control group are used to indicate that all process should be killed off.
2332 * SendSIGKILL= is used for services that require a clean shutdown. These are typically database
2333 * service where a SigKilled process would result in a lengthy recovery and who's shutdown or startup
2334 * time is quite variable (so Timeout settings aren't of use).
2336 * Here we take these two factors and refuse to start a service if there are existing processes
2337 * within a control group. Databases, while generally having some protection against multiple
2338 * instances running, lets not stress the rigor of these. Also ExecStartPre= parts of the service
2339 * aren't as rigoriously written to protect aganst against multiple use. */
2341 if (unit_warn_leftover_processes(UNIT(s
), unit_log_leftover_process_start
) > 0 &&
2342 IN_SET(s
->kill_context
.kill_mode
, KILL_MIXED
, KILL_CONTROL_GROUP
) &&
2343 !s
->kill_context
.send_sigkill
)
2344 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(EBUSY
),
2345 "Will not start SendSIGKILL=no service of type KillMode=control-group or mixed while processes exist");
2350 static void service_enter_start(Service
*s
) {
2351 _cleanup_(pidref_done
) PidRef pidref
= PIDREF_NULL
;
2358 service_unwatch_control_pid(s
);
2359 service_unwatch_main_pid(s
);
2361 r
= service_adverse_to_leftover_processes(s
);
2365 if (s
->type
== SERVICE_FORKING
) {
2366 s
->control_command_id
= SERVICE_EXEC_START
;
2367 c
= s
->control_command
= s
->exec_command
[SERVICE_EXEC_START
];
2369 s
->main_command
= NULL
;
2371 s
->control_command_id
= _SERVICE_EXEC_COMMAND_INVALID
;
2372 s
->control_command
= NULL
;
2374 c
= s
->main_command
= s
->exec_command
[SERVICE_EXEC_START
];
2378 if (s
->type
!= SERVICE_ONESHOT
) {
2379 /* There's no command line configured for the main command? Hmm, that is strange.
2380 * This can only happen if the configuration changes at runtime. In this case,
2381 * let's enter a failure state. */
2382 r
= log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENXIO
), "There's no 'start' task anymore we could start.");
2386 /* We force a fake state transition here. Otherwise, the unit would go directly from
2387 * SERVICE_DEAD to SERVICE_DEAD without SERVICE_ACTIVATING or SERVICE_ACTIVE
2388 * in between. This way we can later trigger actions that depend on the state
2389 * transition, including SuccessAction=. */
2390 service_set_state(s
, SERVICE_START
);
2392 service_enter_start_post(s
);
2396 if (IN_SET(s
->type
, SERVICE_SIMPLE
, SERVICE_IDLE
))
2397 /* For simple + idle this is the main process. We don't apply any timeout here, but
2398 * service_enter_running() will later apply the .runtime_max_usec timeout. */
2399 timeout
= USEC_INFINITY
;
2401 timeout
= s
->timeout_start_usec
;
2403 r
= service_spawn(s
,
2406 EXEC_PASS_FDS
|EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_APPLY_TTY_STDIN
|EXEC_SET_WATCHDOG
|EXEC_WRITE_CREDENTIALS
|EXEC_SETENV_MONITOR_RESULT
,
2411 if (IN_SET(s
->type
, SERVICE_SIMPLE
, SERVICE_IDLE
)) {
2412 /* For simple services we immediately start
2413 * the START_POST binaries. */
2415 (void) service_set_main_pid(s
, pidref
.pid
);
2416 service_enter_start_post(s
);
2418 } else if (s
->type
== SERVICE_FORKING
) {
2420 /* For forking services we wait until the start
2421 * process exited. */
2423 pidref_done(&s
->control_pid
);
2424 s
->control_pid
= TAKE_PIDREF(pidref
);
2425 service_set_state(s
, SERVICE_START
);
2427 } else if (IN_SET(s
->type
, SERVICE_ONESHOT
, SERVICE_DBUS
, SERVICE_NOTIFY
, SERVICE_NOTIFY_RELOAD
, SERVICE_EXEC
)) {
2429 /* For oneshot services we wait until the start process exited, too, but it is our main process. */
2431 /* For D-Bus services we know the main pid right away, but wait for the bus name to appear on the
2432 * bus. 'notify' and 'exec' services are similar. */
2434 (void) service_set_main_pid(s
, pidref
.pid
);
2435 service_set_state(s
, SERVICE_START
);
2437 assert_not_reached();
2442 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'start' task: %m");
2443 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_RESOURCES
);
2446 static void service_enter_start_pre(Service
*s
) {
2451 service_unwatch_control_pid(s
);
2453 s
->control_command
= s
->exec_command
[SERVICE_EXEC_START_PRE
];
2454 if (s
->control_command
) {
2456 r
= service_adverse_to_leftover_processes(s
);
2460 s
->control_command_id
= SERVICE_EXEC_START_PRE
;
2462 r
= service_spawn(s
,
2464 s
->timeout_start_usec
,
2465 EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_IS_CONTROL
|EXEC_APPLY_TTY_STDIN
|EXEC_SETENV_MONITOR_RESULT
|EXEC_WRITE_CREDENTIALS
,
2470 service_set_state(s
, SERVICE_START_PRE
);
2472 service_enter_start(s
);
2477 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'start-pre' task: %m");
2478 service_enter_dead(s
, SERVICE_FAILURE_RESOURCES
, true);
2481 static void service_enter_condition(Service
*s
) {
2486 service_unwatch_control_pid(s
);
2488 s
->control_command
= s
->exec_command
[SERVICE_EXEC_CONDITION
];
2489 if (s
->control_command
) {
2491 r
= service_adverse_to_leftover_processes(s
);
2495 s
->control_command_id
= SERVICE_EXEC_CONDITION
;
2496 pidref_done(&s
->control_pid
);
2498 r
= service_spawn(s
,
2500 s
->timeout_start_usec
,
2501 EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_IS_CONTROL
|EXEC_APPLY_TTY_STDIN
,
2507 service_set_state(s
, SERVICE_CONDITION
);
2509 service_enter_start_pre(s
);
2514 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'exec-condition' task: %m");
2515 service_enter_dead(s
, SERVICE_FAILURE_RESOURCES
, true);
2518 static void service_enter_restart(Service
*s
) {
2519 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2524 if (unit_has_job_type(UNIT(s
), JOB_STOP
)) {
2525 /* Don't restart things if we are going down anyway */
2526 log_unit_info(UNIT(s
), "Stop job pending for unit, skipping automatic restart.");
2530 /* Any units that are bound to this service must also be restarted. We use JOB_START for ourselves
2531 * but then set JOB_RESTART_DEPENDENCIES which will enqueue JOB_RESTART for those dependency jobs. */
2532 r
= manager_add_job(UNIT(s
)->manager
, JOB_START
, UNIT(s
), JOB_RESTART_DEPENDENCIES
, NULL
, &error
, NULL
);
2536 /* Count the jobs we enqueue for restarting. This counter is maintained as long as the unit isn't
2537 * fully stopped, i.e. as long as it remains up or remains in auto-start states. The user can reset
2538 * the counter explicitly however via the usual "systemctl reset-failure" logic. */
2540 s
->flush_n_restarts
= false;
2542 s
->notify_access_override
= _NOTIFY_ACCESS_INVALID
;
2544 log_unit_struct(UNIT(s
), LOG_INFO
,
2545 "MESSAGE_ID=" SD_MESSAGE_UNIT_RESTART_SCHEDULED_STR
,
2546 LOG_UNIT_INVOCATION_ID(UNIT(s
)),
2547 LOG_UNIT_MESSAGE(UNIT(s
),
2548 "Scheduled restart job, restart counter is at %u.", s
->n_restarts
),
2549 "N_RESTARTS=%u", s
->n_restarts
);
2551 service_set_state(s
, SERVICE_AUTO_RESTART_QUEUED
);
2553 /* Notify clients about changed restart counter */
2554 unit_add_to_dbus_queue(UNIT(s
));
2558 log_unit_warning(UNIT(s
), "Failed to schedule restart job: %s", bus_error_message(&error
, r
));
2559 service_enter_dead(s
, SERVICE_FAILURE_RESOURCES
, false);
2562 static void service_enter_reload_by_notify(Service
*s
) {
2563 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2568 service_arm_timer(s
, /* relative= */ true, s
->timeout_start_usec
);
2569 service_set_state(s
, SERVICE_RELOAD_NOTIFY
);
2571 /* service_enter_reload_by_notify is never called during a reload, thus no loops are possible. */
2572 r
= manager_propagate_reload(UNIT(s
)->manager
, UNIT(s
), JOB_FAIL
, &error
);
2574 log_unit_warning(UNIT(s
), "Failed to schedule propagation of reload: %s", bus_error_message(&error
, r
));
2577 static void service_enter_reload(Service
*s
) {
2578 bool killed
= false;
2583 service_unwatch_control_pid(s
);
2584 s
->reload_result
= SERVICE_SUCCESS
;
2586 usec_t ts
= now(CLOCK_MONOTONIC
);
2588 if (s
->type
== SERVICE_NOTIFY_RELOAD
&& pidref_is_set(&s
->main_pid
)) {
2589 r
= pidref_kill_and_sigcont(&s
->main_pid
, s
->reload_signal
);
2591 log_unit_warning_errno(UNIT(s
), r
, "Failed to send reload signal: %m");
2598 s
->control_command
= s
->exec_command
[SERVICE_EXEC_RELOAD
];
2599 if (s
->control_command
) {
2600 s
->control_command_id
= SERVICE_EXEC_RELOAD
;
2601 pidref_done(&s
->control_pid
);
2603 r
= service_spawn(s
,
2605 s
->timeout_start_usec
,
2606 EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_IS_CONTROL
|EXEC_CONTROL_CGROUP
,
2609 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'reload' task: %m");
2613 service_set_state(s
, SERVICE_RELOAD
);
2614 } else if (killed
) {
2615 service_arm_timer(s
, /* relative= */ true, s
->timeout_start_usec
);
2616 service_set_state(s
, SERVICE_RELOAD_SIGNAL
);
2618 service_enter_running(s
, SERVICE_SUCCESS
);
2622 /* Store the timestamp when we started reloading: when reloading via SIGHUP we won't leave the reload
2623 * state until we received both RELOADING=1 and READY=1 with MONOTONIC_USEC= set to a value above
2624 * this. Thus we know for sure the reload cycle was executed *after* we requested it, and is not one
2625 * that was already in progress before. */
2626 s
->reload_begin_usec
= ts
;
2630 s
->reload_result
= SERVICE_FAILURE_RESOURCES
;
2631 service_enter_running(s
, SERVICE_SUCCESS
);
2634 static void service_run_next_control(Service
*s
) {
2639 assert(s
->control_command
);
2640 assert(s
->control_command
->command_next
);
2642 assert(s
->control_command_id
!= SERVICE_EXEC_START
);
2644 s
->control_command
= s
->control_command
->command_next
;
2645 service_unwatch_control_pid(s
);
2647 if (IN_SET(s
->state
, SERVICE_CONDITION
, SERVICE_START_PRE
, SERVICE_START
, SERVICE_START_POST
, SERVICE_RUNNING
, SERVICE_RELOAD
))
2648 timeout
= s
->timeout_start_usec
;
2650 timeout
= s
->timeout_stop_usec
;
2652 pidref_done(&s
->control_pid
);
2654 r
= service_spawn(s
,
2657 EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_IS_CONTROL
|
2658 (IN_SET(s
->state
, SERVICE_CONDITION
, SERVICE_START_PRE
, SERVICE_START
, SERVICE_START_POST
, SERVICE_RUNNING
, SERVICE_RELOAD
) ? EXEC_WRITE_CREDENTIALS
: 0)|
2659 (IN_SET(s
->control_command_id
, SERVICE_EXEC_CONDITION
, SERVICE_EXEC_START_PRE
, SERVICE_EXEC_STOP_POST
) ? EXEC_APPLY_TTY_STDIN
: 0)|
2660 (IN_SET(s
->control_command_id
, SERVICE_EXEC_STOP
, SERVICE_EXEC_STOP_POST
) ? EXEC_SETENV_RESULT
: 0)|
2661 (IN_SET(s
->control_command_id
, SERVICE_EXEC_START_PRE
, SERVICE_EXEC_START
) ? EXEC_SETENV_MONITOR_RESULT
: 0)|
2662 (IN_SET(s
->control_command_id
, SERVICE_EXEC_START_POST
, SERVICE_EXEC_RELOAD
, SERVICE_EXEC_STOP
, SERVICE_EXEC_STOP_POST
) ? EXEC_CONTROL_CGROUP
: 0),
2670 log_unit_warning_errno(UNIT(s
), r
, "Failed to run next control task: %m");
2672 if (IN_SET(s
->state
, SERVICE_CONDITION
, SERVICE_START_PRE
, SERVICE_START_POST
, SERVICE_STOP
))
2673 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_RESOURCES
);
2674 else if (s
->state
== SERVICE_STOP_POST
)
2675 service_enter_dead(s
, SERVICE_FAILURE_RESOURCES
, true);
2676 else if (s
->state
== SERVICE_RELOAD
) {
2677 s
->reload_result
= SERVICE_FAILURE_RESOURCES
;
2678 service_enter_running(s
, SERVICE_SUCCESS
);
2680 service_enter_stop(s
, SERVICE_FAILURE_RESOURCES
);
2683 static void service_run_next_main(Service
*s
) {
2684 _cleanup_(pidref_done
) PidRef pidref
= PIDREF_NULL
;
2688 assert(s
->main_command
);
2689 assert(s
->main_command
->command_next
);
2690 assert(s
->type
== SERVICE_ONESHOT
);
2692 s
->main_command
= s
->main_command
->command_next
;
2693 service_unwatch_main_pid(s
);
2695 r
= service_spawn(s
,
2697 s
->timeout_start_usec
,
2698 EXEC_PASS_FDS
|EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_APPLY_TTY_STDIN
|EXEC_SET_WATCHDOG
|EXEC_SETENV_MONITOR_RESULT
|EXEC_WRITE_CREDENTIALS
,
2703 (void) service_set_main_pid(s
, pidref
.pid
);
2708 log_unit_warning_errno(UNIT(s
), r
, "Failed to run next main task: %m");
2709 service_enter_stop(s
, SERVICE_FAILURE_RESOURCES
);
2712 static int service_start(Unit
*u
) {
2713 Service
*s
= SERVICE(u
);
2718 /* We cannot fulfill this request right now, try again later
2720 if (IN_SET(s
->state
,
2721 SERVICE_STOP
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
, SERVICE_STOP_POST
,
2722 SERVICE_FINAL_WATCHDOG
, SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
, SERVICE_CLEANING
))
2725 /* Already on it! */
2726 if (IN_SET(s
->state
, SERVICE_CONDITION
, SERVICE_START_PRE
, SERVICE_START
, SERVICE_START_POST
))
2729 /* A service that will be restarted must be stopped first to trigger BindsTo and/or OnFailure
2730 * dependencies. If a user does not want to wait for the holdoff time to elapse, the service should
2731 * be manually restarted, not started. We simply return EAGAIN here, so that any start jobs stay
2732 * queued, and assume that the auto restart timer will eventually trigger the restart. */
2733 if (IN_SET(s
->state
, SERVICE_AUTO_RESTART
, SERVICE_DEAD_BEFORE_AUTO_RESTART
, SERVICE_FAILED_BEFORE_AUTO_RESTART
))
2736 assert(IN_SET(s
->state
, SERVICE_DEAD
, SERVICE_FAILED
, SERVICE_DEAD_RESOURCES_PINNED
, SERVICE_AUTO_RESTART_QUEUED
));
2738 r
= unit_acquire_invocation_id(u
);
2742 s
->result
= SERVICE_SUCCESS
;
2743 s
->reload_result
= SERVICE_SUCCESS
;
2744 s
->main_pid_known
= false;
2745 s
->main_pid_alien
= false;
2746 s
->forbid_restart
= false;
2748 s
->status_text
= mfree(s
->status_text
);
2749 s
->status_errno
= 0;
2751 s
->notify_access_override
= _NOTIFY_ACCESS_INVALID
;
2752 s
->notify_state
= NOTIFY_UNKNOWN
;
2754 s
->watchdog_original_usec
= s
->watchdog_usec
;
2755 s
->watchdog_override_enable
= false;
2756 s
->watchdog_override_usec
= USEC_INFINITY
;
2758 exec_command_reset_status_list_array(s
->exec_command
, _SERVICE_EXEC_COMMAND_MAX
);
2759 exec_status_reset(&s
->main_exec_status
);
2761 /* This is not an automatic restart? Flush the restart counter then */
2762 if (s
->flush_n_restarts
) {
2764 s
->flush_n_restarts
= false;
2767 u
->reset_accounting
= true;
2769 service_enter_condition(s
);
2773 static int service_stop(Unit
*u
) {
2774 Service
*s
= SERVICE(u
);
2778 /* Don't create restart jobs from manual stops. */
2779 s
->forbid_restart
= true;
2784 case SERVICE_STOP_SIGTERM
:
2785 case SERVICE_STOP_SIGKILL
:
2786 case SERVICE_STOP_POST
:
2787 case SERVICE_FINAL_WATCHDOG
:
2788 case SERVICE_FINAL_SIGTERM
:
2789 case SERVICE_FINAL_SIGKILL
:
2793 case SERVICE_AUTO_RESTART
:
2794 case SERVICE_AUTO_RESTART_QUEUED
:
2795 /* Give up on the auto restart */
2796 service_set_state(s
, service_determine_dead_state(s
));
2799 case SERVICE_CONDITION
:
2800 case SERVICE_START_PRE
:
2802 case SERVICE_START_POST
:
2803 case SERVICE_RELOAD
:
2804 case SERVICE_RELOAD_SIGNAL
:
2805 case SERVICE_RELOAD_NOTIFY
:
2806 case SERVICE_STOP_WATCHDOG
:
2807 /* If there's already something running we go directly into kill mode. */
2808 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_SUCCESS
);
2811 case SERVICE_CLEANING
:
2812 /* If we are currently cleaning, then abort it, brutally. */
2813 service_enter_signal(s
, SERVICE_FINAL_SIGKILL
, SERVICE_SUCCESS
);
2816 case SERVICE_RUNNING
:
2817 case SERVICE_EXITED
:
2818 service_enter_stop(s
, SERVICE_SUCCESS
);
2821 case SERVICE_DEAD_BEFORE_AUTO_RESTART
:
2822 case SERVICE_FAILED_BEFORE_AUTO_RESTART
:
2824 case SERVICE_FAILED
:
2825 case SERVICE_DEAD_RESOURCES_PINNED
:
2827 /* Unknown state, or unit_stop() should already have handled these */
2828 assert_not_reached();
2832 static int service_reload(Unit
*u
) {
2833 Service
*s
= SERVICE(u
);
2837 assert(IN_SET(s
->state
, SERVICE_RUNNING
, SERVICE_EXITED
));
2839 service_enter_reload(s
);
2843 static bool service_can_reload(Unit
*u
) {
2844 Service
*s
= SERVICE(u
);
2848 return s
->exec_command
[SERVICE_EXEC_RELOAD
] ||
2849 s
->type
== SERVICE_NOTIFY_RELOAD
;
2852 static unsigned service_exec_command_index(Unit
*u
, ServiceExecCommand id
, const ExecCommand
*current
) {
2853 Service
*s
= SERVICE(u
);
2858 assert(id
< _SERVICE_EXEC_COMMAND_MAX
);
2860 const ExecCommand
*first
= s
->exec_command
[id
];
2862 /* Figure out where we are in the list by walking back to the beginning */
2863 for (const ExecCommand
*c
= current
; c
!= first
; c
= c
->command_prev
)
2869 static int service_serialize_exec_command(Unit
*u
, FILE *f
, const ExecCommand
*command
) {
2870 _cleanup_free_
char *args
= NULL
, *p
= NULL
;
2871 Service
*s
= SERVICE(u
);
2872 const char *type
, *key
;
2873 ServiceExecCommand id
;
2883 if (command
== s
->control_command
) {
2885 id
= s
->control_command_id
;
2888 id
= SERVICE_EXEC_START
;
2891 idx
= service_exec_command_index(u
, id
, command
);
2893 STRV_FOREACH(arg
, command
->argv
) {
2894 _cleanup_free_
char *e
= NULL
;
2902 if (!GREEDY_REALLOC(args
, length
+ 2 + n
+ 2))
2906 args
[length
++] = ' ';
2908 args
[length
++] = '"';
2909 memcpy(args
+ length
, e
, n
);
2911 args
[length
++] = '"';
2914 if (!GREEDY_REALLOC(args
, length
+ 1))
2919 p
= cescape(command
->path
);
2923 key
= strjoina(type
, "-command");
2925 /* We use '+1234' instead of '1234' to mark the last command in a sequence.
2926 * This is used in service_deserialize_exec_command(). */
2927 (void) serialize_item_format(
2930 service_exec_command_to_string(id
),
2931 command
->command_next
? "" : "+",
2938 static int service_serialize(Unit
*u
, FILE *f
, FDSet
*fds
) {
2939 Service
*s
= SERVICE(u
);
2946 (void) serialize_item(f
, "state", service_state_to_string(s
->state
));
2947 (void) serialize_item(f
, "result", service_result_to_string(s
->result
));
2948 (void) serialize_item(f
, "reload-result", service_result_to_string(s
->reload_result
));
2950 if (pidref_is_set(&s
->control_pid
))
2951 (void) serialize_item_format(f
, "control-pid", PID_FMT
, s
->control_pid
.pid
);
2953 if (s
->main_pid_known
&& pidref_is_set(&s
->main_pid
))
2954 (void) serialize_item_format(f
, "main-pid", PID_FMT
, s
->main_pid
.pid
);
2956 (void) serialize_bool(f
, "main-pid-known", s
->main_pid_known
);
2957 (void) serialize_bool(f
, "bus-name-good", s
->bus_name_good
);
2958 (void) serialize_bool(f
, "bus-name-owner", s
->bus_name_owner
);
2960 (void) serialize_item_format(f
, "n-restarts", "%u", s
->n_restarts
);
2961 (void) serialize_bool(f
, "flush-n-restarts", s
->flush_n_restarts
);
2963 r
= serialize_item_escaped(f
, "status-text", s
->status_text
);
2967 service_serialize_exec_command(u
, f
, s
->control_command
);
2968 service_serialize_exec_command(u
, f
, s
->main_command
);
2970 r
= serialize_fd(f
, fds
, "stdin-fd", s
->stdin_fd
);
2973 r
= serialize_fd(f
, fds
, "stdout-fd", s
->stdout_fd
);
2976 r
= serialize_fd(f
, fds
, "stderr-fd", s
->stderr_fd
);
2980 if (s
->exec_fd_event_source
) {
2981 r
= serialize_fd(f
, fds
, "exec-fd", sd_event_source_get_io_fd(s
->exec_fd_event_source
));
2985 (void) serialize_bool(f
, "exec-fd-hot", s
->exec_fd_hot
);
2988 if (UNIT_ISSET(s
->accept_socket
)) {
2989 r
= serialize_item(f
, "accept-socket", UNIT_DEREF(s
->accept_socket
)->id
);
2994 r
= serialize_fd(f
, fds
, "socket-fd", s
->socket_fd
);
2998 LIST_FOREACH(fd_store
, fs
, s
->fd_store
) {
2999 _cleanup_free_
char *c
= NULL
;
3002 copy
= fdset_put_dup(fds
, fs
->fd
);
3004 return log_error_errno(copy
, "Failed to copy file descriptor for serialization: %m");
3006 c
= cescape(fs
->fdname
);
3010 (void) serialize_item_format(f
, "fd-store-fd", "%i \"%s\" %i", copy
, c
, fs
->do_poll
);
3013 if (s
->main_exec_status
.pid
> 0) {
3014 (void) serialize_item_format(f
, "main-exec-status-pid", PID_FMT
, s
->main_exec_status
.pid
);
3015 (void) serialize_dual_timestamp(f
, "main-exec-status-start", &s
->main_exec_status
.start_timestamp
);
3016 (void) serialize_dual_timestamp(f
, "main-exec-status-exit", &s
->main_exec_status
.exit_timestamp
);
3018 if (dual_timestamp_is_set(&s
->main_exec_status
.exit_timestamp
)) {
3019 (void) serialize_item_format(f
, "main-exec-status-code", "%i", s
->main_exec_status
.code
);
3020 (void) serialize_item_format(f
, "main-exec-status-status", "%i", s
->main_exec_status
.status
);
3024 if (s
->notify_access_override
>= 0)
3025 (void) serialize_item(f
, "notify-access-override", notify_access_to_string(s
->notify_access_override
));
3027 (void) serialize_dual_timestamp(f
, "watchdog-timestamp", &s
->watchdog_timestamp
);
3028 (void) serialize_bool(f
, "forbid-restart", s
->forbid_restart
);
3030 if (s
->watchdog_override_enable
)
3031 (void) serialize_item_format(f
, "watchdog-override-usec", USEC_FMT
, s
->watchdog_override_usec
);
3033 if (s
->watchdog_original_usec
!= USEC_INFINITY
)
3034 (void) serialize_item_format(f
, "watchdog-original-usec", USEC_FMT
, s
->watchdog_original_usec
);
3036 if (s
->reload_begin_usec
!= USEC_INFINITY
)
3037 (void) serialize_item_format(f
, "reload-begin-usec", USEC_FMT
, s
->reload_begin_usec
);
3042 int service_deserialize_exec_command(
3045 const char *value
) {
3047 Service
*s
= SERVICE(u
);
3049 unsigned idx
= 0, i
;
3050 bool control
, found
= false, last
= false;
3051 ServiceExecCommand id
= _SERVICE_EXEC_COMMAND_INVALID
;
3052 ExecCommand
*command
= NULL
;
3053 _cleanup_free_
char *path
= NULL
;
3054 _cleanup_strv_free_
char **argv
= NULL
;
3056 enum ExecCommandState
{
3057 STATE_EXEC_COMMAND_TYPE
,
3058 STATE_EXEC_COMMAND_INDEX
,
3059 STATE_EXEC_COMMAND_PATH
,
3060 STATE_EXEC_COMMAND_ARGS
,
3061 _STATE_EXEC_COMMAND_MAX
,
3062 _STATE_EXEC_COMMAND_INVALID
= -EINVAL
,
3069 control
= streq(key
, "control-command");
3071 state
= STATE_EXEC_COMMAND_TYPE
;
3074 _cleanup_free_
char *arg
= NULL
;
3076 r
= extract_first_word(&value
, &arg
, NULL
, EXTRACT_CUNESCAPE
| EXTRACT_UNQUOTE
);
3083 case STATE_EXEC_COMMAND_TYPE
:
3084 id
= service_exec_command_from_string(arg
);
3088 state
= STATE_EXEC_COMMAND_INDEX
;
3090 case STATE_EXEC_COMMAND_INDEX
:
3091 /* PID 1234 is serialized as either '1234' or '+1234'. The second form is used to
3092 * mark the last command in a sequence. We warn if the deserialized command doesn't
3093 * match what we have loaded from the unit, but we don't need to warn if that is the
3096 r
= safe_atou(arg
, &idx
);
3099 last
= arg
[0] == '+';
3101 state
= STATE_EXEC_COMMAND_PATH
;
3103 case STATE_EXEC_COMMAND_PATH
:
3104 path
= TAKE_PTR(arg
);
3105 state
= STATE_EXEC_COMMAND_ARGS
;
3107 case STATE_EXEC_COMMAND_ARGS
:
3108 r
= strv_extend(&argv
, arg
);
3113 assert_not_reached();
3117 if (state
!= STATE_EXEC_COMMAND_ARGS
)
3119 if (strv_isempty(argv
))
3120 return -EINVAL
; /* At least argv[0] must be always present. */
3122 /* Let's check whether exec command on given offset matches data that we just deserialized */
3123 for (command
= s
->exec_command
[id
], i
= 0; command
; command
= command
->command_next
, i
++) {
3127 found
= strv_equal(argv
, command
->argv
) && streq(command
->path
, path
);
3132 /* Command at the index we serialized is different, let's look for command that exactly
3133 * matches but is on different index. If there is no such command we will not resume execution. */
3134 for (command
= s
->exec_command
[id
]; command
; command
= command
->command_next
)
3135 if (strv_equal(command
->argv
, argv
) && streq(command
->path
, path
))
3139 if (command
&& control
) {
3140 s
->control_command
= command
;
3141 s
->control_command_id
= id
;
3143 s
->main_command
= command
;
3145 log_unit_debug(u
, "Current command vanished from the unit file.");
3147 log_unit_warning(u
, "Current command vanished from the unit file, execution of the command list won't be resumed.");
3152 static int service_deserialize_item(Unit
*u
, const char *key
, const char *value
, FDSet
*fds
) {
3153 Service
*s
= SERVICE(u
);
3161 if (streq(key
, "state")) {
3164 state
= service_state_from_string(value
);
3166 log_unit_debug(u
, "Failed to parse state value: %s", value
);
3168 s
->deserialized_state
= state
;
3169 } else if (streq(key
, "result")) {
3172 f
= service_result_from_string(value
);
3174 log_unit_debug(u
, "Failed to parse result value: %s", value
);
3175 else if (f
!= SERVICE_SUCCESS
)
3178 } else if (streq(key
, "reload-result")) {
3181 f
= service_result_from_string(value
);
3183 log_unit_debug(u
, "Failed to parse reload result value: %s", value
);
3184 else if (f
!= SERVICE_SUCCESS
)
3185 s
->reload_result
= f
;
3187 } else if (streq(key
, "control-pid")) {
3188 pidref_done(&s
->control_pid
);
3189 r
= pidref_set_pidstr(&s
->control_pid
, value
);
3191 log_unit_debug_errno(u
, r
, "Failed to initialize control PID '%s' from serialization, ignoring.", value
);
3192 } else if (streq(key
, "main-pid")) {
3195 if (parse_pid(value
, &pid
) < 0)
3196 log_unit_debug(u
, "Failed to parse main-pid value: %s", value
);
3198 (void) service_set_main_pid(s
, pid
);
3199 } else if (streq(key
, "main-pid-known")) {
3202 b
= parse_boolean(value
);
3204 log_unit_debug(u
, "Failed to parse main-pid-known value: %s", value
);
3206 s
->main_pid_known
= b
;
3207 } else if (streq(key
, "bus-name-good")) {
3210 b
= parse_boolean(value
);
3212 log_unit_debug(u
, "Failed to parse bus-name-good value: %s", value
);
3214 s
->bus_name_good
= b
;
3215 } else if (streq(key
, "bus-name-owner")) {
3216 r
= free_and_strdup(&s
->bus_name_owner
, value
);
3218 log_unit_error_errno(u
, r
, "Unable to deserialize current bus owner %s: %m", value
);
3219 } else if (streq(key
, "status-text")) {
3223 l
= cunescape(value
, 0, &t
);
3225 log_unit_debug_errno(u
, l
, "Failed to unescape status text '%s': %m", value
);
3227 free_and_replace(s
->status_text
, t
);
3229 } else if (streq(key
, "accept-socket")) {
3232 if (u
->type
!= UNIT_SOCKET
) {
3233 log_unit_debug(u
, "Failed to deserialize accept-socket: unit is not a socket");
3237 r
= manager_load_unit(u
->manager
, value
, NULL
, NULL
, &socket
);
3239 log_unit_debug_errno(u
, r
, "Failed to load accept-socket unit '%s': %m", value
);
3241 unit_ref_set(&s
->accept_socket
, u
, socket
);
3242 SOCKET(socket
)->n_connections
++;
3245 } else if (streq(key
, "socket-fd")) {
3248 if ((fd
= parse_fd(value
)) < 0 || !fdset_contains(fds
, fd
))
3249 log_unit_debug(u
, "Failed to parse socket-fd value: %s", value
);
3251 asynchronous_close(s
->socket_fd
);
3252 s
->socket_fd
= fdset_remove(fds
, fd
);
3254 } else if (streq(key
, "fd-store-fd")) {
3255 _cleanup_free_
char *fdv
= NULL
, *fdn
= NULL
, *fdp
= NULL
;
3258 r
= extract_first_word(&value
, &fdv
, NULL
, 0);
3259 if (r
<= 0 || (fd
= parse_fd(fdv
)) < 0 || !fdset_contains(fds
, fd
)) {
3260 log_unit_debug(u
, "Failed to parse fd-store-fd value: %s", value
);
3264 r
= extract_first_word(&value
, &fdn
, NULL
, EXTRACT_CUNESCAPE
| EXTRACT_UNQUOTE
);
3266 log_unit_debug(u
, "Failed to parse fd-store-fd value: %s", value
);
3270 r
= extract_first_word(&value
, &fdp
, NULL
, 0);
3272 /* If the value is not present, we assume the default */
3274 } else if (r
< 0 || safe_atoi(fdp
, &do_poll
) < 0) {
3275 log_unit_debug_errno(u
, r
, "Failed to parse fd-store-fd value \"%s\": %m", value
);
3279 r
= fdset_remove(fds
, fd
);
3281 log_unit_error_errno(u
, r
, "Could not find deserialized fd %i in fdset: %m", fd
);
3286 r
= service_add_fd_store(s
, fd
, fdn
, do_poll
);
3288 log_unit_error_errno(u
, r
, "Failed to store deserialized fd %i: %m", fd
);
3291 } else if (streq(key
, "main-exec-status-pid")) {
3294 if (parse_pid(value
, &pid
) < 0)
3295 log_unit_debug(u
, "Failed to parse main-exec-status-pid value: %s", value
);
3297 s
->main_exec_status
.pid
= pid
;
3298 } else if (streq(key
, "main-exec-status-code")) {
3301 if (safe_atoi(value
, &i
) < 0)
3302 log_unit_debug(u
, "Failed to parse main-exec-status-code value: %s", value
);
3304 s
->main_exec_status
.code
= i
;
3305 } else if (streq(key
, "main-exec-status-status")) {
3308 if (safe_atoi(value
, &i
) < 0)
3309 log_unit_debug(u
, "Failed to parse main-exec-status-status value: %s", value
);
3311 s
->main_exec_status
.status
= i
;
3312 } else if (streq(key
, "main-exec-status-start"))
3313 deserialize_dual_timestamp(value
, &s
->main_exec_status
.start_timestamp
);
3314 else if (streq(key
, "main-exec-status-exit"))
3315 deserialize_dual_timestamp(value
, &s
->main_exec_status
.exit_timestamp
);
3316 else if (streq(key
, "notify-access-override")) {
3317 NotifyAccess notify_access
;
3319 notify_access
= notify_access_from_string(value
);
3320 if (notify_access
< 0)
3321 log_unit_debug(u
, "Failed to parse notify-access-override value: %s", value
);
3323 s
->notify_access_override
= notify_access
;
3324 } else if (streq(key
, "watchdog-timestamp"))
3325 deserialize_dual_timestamp(value
, &s
->watchdog_timestamp
);
3326 else if (streq(key
, "forbid-restart")) {
3329 b
= parse_boolean(value
);
3331 log_unit_debug(u
, "Failed to parse forbid-restart value: %s", value
);
3333 s
->forbid_restart
= b
;
3334 } else if (streq(key
, "stdin-fd")) {
3337 if ((fd
= parse_fd(value
)) < 0 || !fdset_contains(fds
, fd
))
3338 log_unit_debug(u
, "Failed to parse stdin-fd value: %s", value
);
3340 asynchronous_close(s
->stdin_fd
);
3341 s
->stdin_fd
= fdset_remove(fds
, fd
);
3342 s
->exec_context
.stdio_as_fds
= true;
3344 } else if (streq(key
, "stdout-fd")) {
3347 if ((fd
= parse_fd(value
)) < 0 || !fdset_contains(fds
, fd
))
3348 log_unit_debug(u
, "Failed to parse stdout-fd value: %s", value
);
3350 asynchronous_close(s
->stdout_fd
);
3351 s
->stdout_fd
= fdset_remove(fds
, fd
);
3352 s
->exec_context
.stdio_as_fds
= true;
3354 } else if (streq(key
, "stderr-fd")) {
3357 if ((fd
= parse_fd(value
)) < 0 || !fdset_contains(fds
, fd
))
3358 log_unit_debug(u
, "Failed to parse stderr-fd value: %s", value
);
3360 asynchronous_close(s
->stderr_fd
);
3361 s
->stderr_fd
= fdset_remove(fds
, fd
);
3362 s
->exec_context
.stdio_as_fds
= true;
3364 } else if (streq(key
, "exec-fd")) {
3367 if ((fd
= parse_fd(value
)) < 0 || !fdset_contains(fds
, fd
))
3368 log_unit_debug(u
, "Failed to parse exec-fd value: %s", value
);
3370 s
->exec_fd_event_source
= sd_event_source_disable_unref(s
->exec_fd_event_source
);
3372 fd
= fdset_remove(fds
, fd
);
3373 if (service_allocate_exec_fd_event_source(s
, fd
, &s
->exec_fd_event_source
) < 0)
3376 } else if (streq(key
, "watchdog-override-usec")) {
3377 if (deserialize_usec(value
, &s
->watchdog_override_usec
) < 0)
3378 log_unit_debug(u
, "Failed to parse watchdog_override_usec value: %s", value
);
3380 s
->watchdog_override_enable
= true;
3382 } else if (streq(key
, "watchdog-original-usec")) {
3383 if (deserialize_usec(value
, &s
->watchdog_original_usec
) < 0)
3384 log_unit_debug(u
, "Failed to parse watchdog_original_usec value: %s", value
);
3386 } else if (STR_IN_SET(key
, "main-command", "control-command")) {
3387 r
= service_deserialize_exec_command(u
, key
, value
);
3389 log_unit_debug_errno(u
, r
, "Failed to parse serialized command \"%s\": %m", value
);
3391 } else if (streq(key
, "n-restarts")) {
3392 r
= safe_atou(value
, &s
->n_restarts
);
3394 log_unit_debug_errno(u
, r
, "Failed to parse serialized restart counter '%s': %m", value
);
3396 } else if (streq(key
, "flush-n-restarts")) {
3397 r
= parse_boolean(value
);
3399 log_unit_debug_errno(u
, r
, "Failed to parse serialized flush restart counter setting '%s': %m", value
);
3401 s
->flush_n_restarts
= r
;
3402 } else if (streq(key
, "reload-begin-usec")) {
3403 r
= deserialize_usec(value
, &s
->reload_begin_usec
);
3405 log_unit_debug_errno(u
, r
, "Failed to parse serialized reload begin timestamp '%s', ignoring: %m", value
);
3407 log_unit_debug(u
, "Unknown serialization key: %s", key
);
3412 static UnitActiveState
service_active_state(Unit
*u
) {
3413 const UnitActiveState
*table
;
3417 table
= SERVICE(u
)->type
== SERVICE_IDLE
? state_translation_table_idle
: state_translation_table
;
3419 return table
[SERVICE(u
)->state
];
3422 static const char *service_sub_state_to_string(Unit
*u
) {
3425 return service_state_to_string(SERVICE(u
)->state
);
3428 static bool service_may_gc(Unit
*u
) {
3429 Service
*s
= SERVICE(u
);
3433 /* Never clean up services that still have a process around, even if the service is formally dead. Note that
3434 * unit_may_gc() already checked our cgroup for us, we just check our two additional PIDs, too, in case they
3435 * have moved outside of the cgroup. */
3437 if (main_pid_good(s
) > 0 ||
3438 control_pid_good(s
) > 0)
3441 /* Only allow collection of actually dead services, i.e. not those that are in the transitionary
3442 * SERVICE_DEAD_BEFORE_AUTO_RESTART/SERVICE_FAILED_BEFORE_AUTO_RESTART states. */
3443 if (!IN_SET(s
->state
, SERVICE_DEAD
, SERVICE_FAILED
, SERVICE_DEAD_RESOURCES_PINNED
))
3449 static int service_retry_pid_file(Service
*s
) {
3452 assert(s
->pid_file
);
3453 assert(IN_SET(s
->state
, SERVICE_START
, SERVICE_START_POST
));
3455 r
= service_load_pid_file(s
, false);
3459 service_unwatch_pid_file(s
);
3461 service_enter_running(s
, SERVICE_SUCCESS
);
3465 static int service_watch_pid_file(Service
*s
) {
3468 log_unit_debug(UNIT(s
), "Setting watch for PID file %s", s
->pid_file_pathspec
->path
);
3470 r
= path_spec_watch(s
->pid_file_pathspec
, service_dispatch_inotify_io
);
3474 /* the pidfile might have appeared just before we set the watch */
3475 log_unit_debug(UNIT(s
), "Trying to read PID file %s in case it changed", s
->pid_file_pathspec
->path
);
3476 service_retry_pid_file(s
);
3480 log_unit_error_errno(UNIT(s
), r
, "Failed to set a watch for PID file %s: %m", s
->pid_file_pathspec
->path
);
3481 service_unwatch_pid_file(s
);
3485 static int service_demand_pid_file(Service
*s
) {
3486 _cleanup_free_ PathSpec
*ps
= NULL
;
3488 assert(s
->pid_file
);
3489 assert(!s
->pid_file_pathspec
);
3491 ps
= new(PathSpec
, 1);
3497 .path
= strdup(s
->pid_file
),
3498 /* PATH_CHANGED would not be enough. There are daemons (sendmail) that keep their PID file
3499 * open all the time. */
3500 .type
= PATH_MODIFIED
,
3501 .inotify_fd
= -EBADF
,
3507 path_simplify(ps
->path
);
3509 s
->pid_file_pathspec
= TAKE_PTR(ps
);
3511 return service_watch_pid_file(s
);
3514 static int service_dispatch_inotify_io(sd_event_source
*source
, int fd
, uint32_t events
, void *userdata
) {
3515 PathSpec
*p
= ASSERT_PTR(userdata
);
3518 s
= SERVICE(p
->unit
);
3522 assert(IN_SET(s
->state
, SERVICE_START
, SERVICE_START_POST
));
3523 assert(s
->pid_file_pathspec
);
3524 assert(path_spec_owns_inotify_fd(s
->pid_file_pathspec
, fd
));
3526 log_unit_debug(UNIT(s
), "inotify event");
3528 if (path_spec_fd_event(p
, events
) < 0)
3531 if (service_retry_pid_file(s
) == 0)
3534 if (service_watch_pid_file(s
) < 0)
3540 service_unwatch_pid_file(s
);
3541 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_RESOURCES
);
3545 static int service_dispatch_exec_io(sd_event_source
*source
, int fd
, uint32_t events
, void *userdata
) {
3546 Service
*s
= SERVICE(userdata
);
3550 log_unit_debug(UNIT(s
), "got exec-fd event");
3552 /* If Type=exec is set, we'll consider a service started successfully the instant we invoked execve()
3553 * successfully for it. We implement this through a pipe() towards the child, which the kernel automatically
3554 * closes for us due to O_CLOEXEC on execve() in the child, which then triggers EOF on the pipe in the
3555 * parent. We need to be careful however, as there are other reasons that we might cause the child's side of
3556 * the pipe to be closed (for example, a simple exit()). To deal with that we'll ignore EOFs on the pipe unless
3557 * the child signalled us first that it is about to call the execve(). It does so by sending us a simple
3558 * non-zero byte via the pipe. We also provide the child with a way to inform us in case execve() failed: if it
3559 * sends a zero byte we'll ignore POLLHUP on the fd again. */
3565 n
= read(fd
, &x
, sizeof(x
));
3567 if (errno
== EAGAIN
) /* O_NONBLOCK in effect → everything queued has now been processed. */
3570 return log_unit_error_errno(UNIT(s
), errno
, "Failed to read from exec_fd: %m");
3572 if (n
== 0) { /* EOF → the event we are waiting for */
3574 s
->exec_fd_event_source
= sd_event_source_disable_unref(s
->exec_fd_event_source
);
3576 if (s
->exec_fd_hot
) { /* Did the child tell us to expect EOF now? */
3577 log_unit_debug(UNIT(s
), "Got EOF on exec-fd");
3579 s
->exec_fd_hot
= false;
3581 /* Nice! This is what we have been waiting for. Transition to next state. */
3582 if (s
->type
== SERVICE_EXEC
&& s
->state
== SERVICE_START
)
3583 service_enter_start_post(s
);
3585 log_unit_debug(UNIT(s
), "Got EOF on exec-fd while it was disabled, ignoring.");
3590 /* A byte was read → this turns on/off the exec fd logic */
3591 assert(n
== sizeof(x
));
3598 static void service_notify_cgroup_empty_event(Unit
*u
) {
3599 Service
*s
= SERVICE(u
);
3603 log_unit_debug(u
, "Control group is empty.");
3607 /* Waiting for SIGCHLD is usually more interesting, because it includes return
3608 * codes/signals. Which is why we ignore the cgroup events for most cases, except when we
3609 * don't know pid which to expect the SIGCHLD for. */
3612 if (IN_SET(s
->type
, SERVICE_NOTIFY
, SERVICE_NOTIFY_RELOAD
) &&
3613 main_pid_good(s
) == 0 &&
3614 control_pid_good(s
) == 0) {
3615 /* No chance of getting a ready notification anymore */
3616 service_enter_stop_post(s
, SERVICE_FAILURE_PROTOCOL
);
3620 if (s
->exit_type
== SERVICE_EXIT_CGROUP
&& main_pid_good(s
) <= 0)
3621 service_enter_start_post(s
);
3624 case SERVICE_START_POST
:
3625 if (s
->pid_file_pathspec
&&
3626 main_pid_good(s
) == 0 &&
3627 control_pid_good(s
) == 0) {
3629 /* Give up hoping for the daemon to write its PID file */
3630 log_unit_warning(u
, "Daemon never wrote its PID file. Failing.");
3632 service_unwatch_pid_file(s
);
3633 if (s
->state
== SERVICE_START
)
3634 service_enter_stop_post(s
, SERVICE_FAILURE_PROTOCOL
);
3636 service_enter_stop(s
, SERVICE_FAILURE_PROTOCOL
);
3640 case SERVICE_RUNNING
:
3641 /* service_enter_running() will figure out what to do */
3642 service_enter_running(s
, SERVICE_SUCCESS
);
3645 case SERVICE_STOP_WATCHDOG
:
3646 case SERVICE_STOP_SIGTERM
:
3647 case SERVICE_STOP_SIGKILL
:
3649 if (main_pid_good(s
) <= 0 && control_pid_good(s
) <= 0)
3650 service_enter_stop_post(s
, SERVICE_SUCCESS
);
3654 case SERVICE_STOP_POST
:
3655 case SERVICE_FINAL_WATCHDOG
:
3656 case SERVICE_FINAL_SIGTERM
:
3657 case SERVICE_FINAL_SIGKILL
:
3658 if (main_pid_good(s
) <= 0 && control_pid_good(s
) <= 0)
3659 service_enter_dead(s
, SERVICE_SUCCESS
, true);
3663 /* If the cgroup empty notification comes when the unit is not active, we must have failed to clean
3664 * up the cgroup earlier and should do it now. */
3665 case SERVICE_AUTO_RESTART
:
3666 case SERVICE_AUTO_RESTART_QUEUED
:
3667 unit_prune_cgroup(u
);
3675 static void service_notify_cgroup_oom_event(Unit
*u
, bool managed_oom
) {
3676 Service
*s
= SERVICE(u
);
3679 log_unit_debug(u
, "Process(es) of control group were killed by systemd-oomd.");
3681 log_unit_debug(u
, "Process of control group was killed by the OOM killer.");
3683 if (s
->oom_policy
== OOM_CONTINUE
)
3688 case SERVICE_CONDITION
:
3689 case SERVICE_START_PRE
:
3691 case SERVICE_START_POST
:
3693 if (s
->oom_policy
== OOM_STOP
)
3694 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_OOM_KILL
);
3695 else if (s
->oom_policy
== OOM_KILL
)
3696 service_enter_signal(s
, SERVICE_STOP_SIGKILL
, SERVICE_FAILURE_OOM_KILL
);
3700 case SERVICE_EXITED
:
3701 case SERVICE_RUNNING
:
3702 if (s
->oom_policy
== OOM_STOP
)
3703 service_enter_stop(s
, SERVICE_FAILURE_OOM_KILL
);
3704 else if (s
->oom_policy
== OOM_KILL
)
3705 service_enter_signal(s
, SERVICE_STOP_SIGKILL
, SERVICE_FAILURE_OOM_KILL
);
3709 case SERVICE_STOP_WATCHDOG
:
3710 case SERVICE_STOP_SIGTERM
:
3711 service_enter_signal(s
, SERVICE_STOP_SIGKILL
, SERVICE_FAILURE_OOM_KILL
);
3714 case SERVICE_STOP_SIGKILL
:
3715 case SERVICE_FINAL_SIGKILL
:
3716 if (s
->result
== SERVICE_SUCCESS
)
3717 s
->result
= SERVICE_FAILURE_OOM_KILL
;
3720 case SERVICE_STOP_POST
:
3721 case SERVICE_FINAL_SIGTERM
:
3722 service_enter_signal(s
, SERVICE_FINAL_SIGKILL
, SERVICE_FAILURE_OOM_KILL
);
3730 static void service_sigchld_event(Unit
*u
, pid_t pid
, int code
, int status
) {
3731 bool notify_dbus
= true;
3732 Service
*s
= SERVICE(u
);
3734 ExitClean clean_mode
;
3739 /* Oneshot services and non-SERVICE_EXEC_START commands should not be
3740 * considered daemons as they are typically not long running. */
3741 if (s
->type
== SERVICE_ONESHOT
|| (s
->control_pid
.pid
== pid
&& s
->control_command_id
!= SERVICE_EXEC_START
))
3742 clean_mode
= EXIT_CLEAN_COMMAND
;
3744 clean_mode
= EXIT_CLEAN_DAEMON
;
3746 if (is_clean_exit(code
, status
, clean_mode
, &s
->success_status
))
3747 f
= SERVICE_SUCCESS
;
3748 else if (code
== CLD_EXITED
)
3749 f
= SERVICE_FAILURE_EXIT_CODE
;
3750 else if (code
== CLD_KILLED
)
3751 f
= SERVICE_FAILURE_SIGNAL
;
3752 else if (code
== CLD_DUMPED
)
3753 f
= SERVICE_FAILURE_CORE_DUMP
;
3755 assert_not_reached();
3757 if (s
->main_pid
.pid
== pid
) {
3758 /* Clean up the exec_fd event source. We want to do this here, not later in
3759 * service_set_state(), because service_enter_stop_post() calls service_spawn().
3760 * The source owns its end of the pipe, so this will close that too. */
3761 s
->exec_fd_event_source
= sd_event_source_disable_unref(s
->exec_fd_event_source
);
3763 /* Forking services may occasionally move to a new PID.
3764 * As long as they update the PID file before exiting the old
3765 * PID, they're fine. */
3766 if (service_load_pid_file(s
, false) > 0)
3769 pidref_done(&s
->main_pid
);
3770 exec_status_exit(&s
->main_exec_status
, &s
->exec_context
, pid
, code
, status
);
3772 if (s
->main_command
) {
3773 /* If this is not a forking service than the
3774 * main process got started and hence we copy
3775 * the exit status so that it is recorded both
3776 * as main and as control process exit
3779 s
->main_command
->exec_status
= s
->main_exec_status
;
3781 if (s
->main_command
->flags
& EXEC_COMMAND_IGNORE_FAILURE
)
3782 f
= SERVICE_SUCCESS
;
3783 } else if (s
->exec_command
[SERVICE_EXEC_START
]) {
3785 /* If this is a forked process, then we should
3786 * ignore the return value if this was
3787 * configured for the starter process */
3789 if (s
->exec_command
[SERVICE_EXEC_START
]->flags
& EXEC_COMMAND_IGNORE_FAILURE
)
3790 f
= SERVICE_SUCCESS
;
3793 unit_log_process_exit(
3796 service_exec_command_to_string(SERVICE_EXEC_START
),
3797 f
== SERVICE_SUCCESS
,
3800 if (s
->result
== SERVICE_SUCCESS
)
3803 if (s
->main_command
&&
3804 s
->main_command
->command_next
&&
3805 s
->type
== SERVICE_ONESHOT
&&
3806 f
== SERVICE_SUCCESS
) {
3808 /* There is another command to execute, so let's do that. */
3810 log_unit_debug(u
, "Running next main command for state %s.", service_state_to_string(s
->state
));
3811 service_run_next_main(s
);
3814 s
->main_command
= NULL
;
3816 /* Services with ExitType=cgroup do not act on main PID exiting, unless the cgroup is
3818 if (s
->exit_type
== SERVICE_EXIT_MAIN
|| cgroup_good(s
) <= 0) {
3819 /* The service exited, so the service is officially gone. */
3822 case SERVICE_START_POST
:
3823 case SERVICE_RELOAD
:
3824 case SERVICE_RELOAD_SIGNAL
:
3825 case SERVICE_RELOAD_NOTIFY
:
3826 /* If neither main nor control processes are running then the current
3827 * state can never exit cleanly, hence immediately terminate the
3829 if (control_pid_good(s
) <= 0)
3830 service_enter_stop(s
, f
);
3832 /* Otherwise need to wait until the operation is done. */
3836 /* Need to wait until the operation is done. */
3840 if (s
->type
== SERVICE_ONESHOT
) {
3841 /* This was our main goal, so let's go on */
3842 if (f
== SERVICE_SUCCESS
)
3843 service_enter_start_post(s
);
3845 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
3847 } else if (IN_SET(s
->type
, SERVICE_NOTIFY
, SERVICE_NOTIFY_RELOAD
)) {
3848 /* Only enter running through a notification, so that the
3849 * SERVICE_START state signifies that no ready notification
3850 * has been received */
3851 if (f
!= SERVICE_SUCCESS
)
3852 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
3853 else if (!s
->remain_after_exit
|| service_get_notify_access(s
) == NOTIFY_MAIN
)
3854 /* The service has never been and will never be active */
3855 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_PROTOCOL
);
3860 case SERVICE_RUNNING
:
3861 service_enter_running(s
, f
);
3864 case SERVICE_STOP_WATCHDOG
:
3865 case SERVICE_STOP_SIGTERM
:
3866 case SERVICE_STOP_SIGKILL
:
3868 if (control_pid_good(s
) <= 0)
3869 service_enter_stop_post(s
, f
);
3871 /* If there is still a control process, wait for that first */
3874 case SERVICE_STOP_POST
:
3876 if (control_pid_good(s
) <= 0)
3877 service_enter_signal(s
, SERVICE_FINAL_SIGTERM
, f
);
3881 case SERVICE_FINAL_WATCHDOG
:
3882 case SERVICE_FINAL_SIGTERM
:
3883 case SERVICE_FINAL_SIGKILL
:
3885 if (control_pid_good(s
) <= 0)
3886 service_enter_dead(s
, f
, true);
3890 assert_not_reached();
3892 } else if (s
->exit_type
== SERVICE_EXIT_CGROUP
&& s
->state
== SERVICE_START
)
3893 /* If a main process exits very quickly, this function might be executed
3894 * before service_dispatch_exec_io(). Since this function disabled IO events
3895 * to monitor the main process above, we need to update the state here too.
3896 * Let's consider the process is successfully launched and exited. */
3897 service_enter_start_post(s
);
3900 } else if (s
->control_pid
.pid
== pid
) {
3904 pidref_done(&s
->control_pid
);
3906 if (s
->control_command
) {
3907 exec_status_exit(&s
->control_command
->exec_status
, &s
->exec_context
, pid
, code
, status
);
3909 if (s
->control_command
->flags
& EXEC_COMMAND_IGNORE_FAILURE
)
3910 f
= SERVICE_SUCCESS
;
3913 /* ExecCondition= calls that exit with (0, 254] should invoke skip-like behavior instead of failing */
3914 if (s
->state
== SERVICE_CONDITION
) {
3915 if (f
== SERVICE_FAILURE_EXIT_CODE
&& status
< 255) {
3916 UNIT(s
)->condition_result
= false;
3917 f
= SERVICE_SKIP_CONDITION
;
3919 } else if (f
== SERVICE_SUCCESS
) {
3920 UNIT(s
)->condition_result
= true;
3925 kind
= "Condition check process";
3927 kind
= "Control process";
3928 success
= f
== SERVICE_SUCCESS
;
3931 unit_log_process_exit(
3934 service_exec_command_to_string(s
->control_command_id
),
3938 if (s
->state
!= SERVICE_RELOAD
&& s
->result
== SERVICE_SUCCESS
)
3941 if (s
->control_command
&&
3942 s
->control_command
->command_next
&&
3943 f
== SERVICE_SUCCESS
) {
3945 /* There is another command to * execute, so let's do that. */
3947 log_unit_debug(u
, "Running next control command for state %s.", service_state_to_string(s
->state
));
3948 service_run_next_control(s
);
3951 /* No further commands for this step, so let's figure out what to do next */
3953 s
->control_command
= NULL
;
3954 s
->control_command_id
= _SERVICE_EXEC_COMMAND_INVALID
;
3956 log_unit_debug(u
, "Got final SIGCHLD for state %s.", service_state_to_string(s
->state
));
3960 case SERVICE_CONDITION
:
3961 if (f
== SERVICE_SUCCESS
)
3962 service_enter_start_pre(s
);
3964 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
3967 case SERVICE_START_PRE
:
3968 if (f
== SERVICE_SUCCESS
)
3969 service_enter_start(s
);
3971 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
3975 if (s
->type
!= SERVICE_FORKING
)
3976 /* Maybe spurious event due to a reload that changed the type? */
3979 if (f
!= SERVICE_SUCCESS
) {
3980 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
3985 bool has_start_post
;
3988 /* Let's try to load the pid file here if we can.
3989 * The PID file might actually be created by a START_POST
3990 * script. In that case don't worry if the loading fails. */
3992 has_start_post
= s
->exec_command
[SERVICE_EXEC_START_POST
];
3993 r
= service_load_pid_file(s
, !has_start_post
);
3994 if (!has_start_post
&& r
< 0) {
3995 r
= service_demand_pid_file(s
);
3996 if (r
< 0 || cgroup_good(s
) == 0)
3997 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_PROTOCOL
);
4001 service_search_main_pid(s
);
4003 service_enter_start_post(s
);
4006 case SERVICE_START_POST
:
4007 if (f
!= SERVICE_SUCCESS
) {
4008 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
4015 r
= service_load_pid_file(s
, true);
4017 r
= service_demand_pid_file(s
);
4018 if (r
< 0 || cgroup_good(s
) == 0)
4019 service_enter_stop(s
, SERVICE_FAILURE_PROTOCOL
);
4023 service_search_main_pid(s
);
4025 service_enter_running(s
, SERVICE_SUCCESS
);
4028 case SERVICE_RELOAD
:
4029 case SERVICE_RELOAD_SIGNAL
:
4030 case SERVICE_RELOAD_NOTIFY
:
4031 if (f
== SERVICE_SUCCESS
)
4032 if (service_load_pid_file(s
, true) < 0)
4033 service_search_main_pid(s
);
4035 s
->reload_result
= f
;
4037 /* If the last notification we received from the service process indicates
4038 * we are still reloading, then don't leave reloading state just yet, just
4039 * transition into SERVICE_RELOAD_NOTIFY, to wait for the READY=1 coming,
4041 if (s
->notify_state
== NOTIFY_RELOADING
)
4042 service_set_state(s
, SERVICE_RELOAD_NOTIFY
);
4044 service_enter_running(s
, SERVICE_SUCCESS
);
4048 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
4051 case SERVICE_STOP_WATCHDOG
:
4052 case SERVICE_STOP_SIGTERM
:
4053 case SERVICE_STOP_SIGKILL
:
4054 if (main_pid_good(s
) <= 0)
4055 service_enter_stop_post(s
, f
);
4057 /* If there is still a service process around, wait until
4058 * that one quit, too */
4061 case SERVICE_STOP_POST
:
4062 if (main_pid_good(s
) <= 0)
4063 service_enter_signal(s
, SERVICE_FINAL_SIGTERM
, f
);
4066 case SERVICE_FINAL_WATCHDOG
:
4067 case SERVICE_FINAL_SIGTERM
:
4068 case SERVICE_FINAL_SIGKILL
:
4069 if (main_pid_good(s
) <= 0)
4070 service_enter_dead(s
, f
, true);
4073 case SERVICE_CLEANING
:
4075 if (s
->clean_result
== SERVICE_SUCCESS
)
4076 s
->clean_result
= f
;
4078 service_enter_dead(s
, SERVICE_SUCCESS
, false);
4082 assert_not_reached();
4085 } else /* Neither control nor main PID? If so, don't notify about anything */
4086 notify_dbus
= false;
4088 /* Notify clients about changed exit status */
4090 unit_add_to_dbus_queue(u
);
4092 /* We watch the main/control process otherwise we can't retrieve the unit they
4093 * belong to with cgroupv1. But if they are not our direct child, we won't get a
4094 * SIGCHLD for them. Therefore we need to look for others to watch so we can
4095 * detect when the cgroup becomes empty. Note that the control process is always
4096 * our child so it's pointless to watch all other processes. */
4097 if (!control_pid_good(s
))
4098 if (!s
->main_pid_known
|| s
->main_pid_alien
)
4099 (void) unit_enqueue_rewatch_pids(u
);
4102 static int service_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
) {
4103 Service
*s
= SERVICE(userdata
);
4106 assert(source
== s
->timer_event_source
);
4110 case SERVICE_CONDITION
:
4111 case SERVICE_START_PRE
:
4113 case SERVICE_START_POST
:
4114 switch (s
->timeout_start_failure_mode
) {
4116 case SERVICE_TIMEOUT_TERMINATE
:
4117 log_unit_warning(UNIT(s
), "%s operation timed out. Terminating.", service_state_to_string(s
->state
));
4118 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_TIMEOUT
);
4121 case SERVICE_TIMEOUT_ABORT
:
4122 log_unit_warning(UNIT(s
), "%s operation timed out. Aborting.", service_state_to_string(s
->state
));
4123 service_enter_signal(s
, SERVICE_STOP_WATCHDOG
, SERVICE_FAILURE_TIMEOUT
);
4126 case SERVICE_TIMEOUT_KILL
:
4127 if (s
->kill_context
.send_sigkill
) {
4128 log_unit_warning(UNIT(s
), "%s operation timed out. Killing.", service_state_to_string(s
->state
));
4129 service_enter_signal(s
, SERVICE_STOP_SIGKILL
, SERVICE_FAILURE_TIMEOUT
);
4131 log_unit_warning(UNIT(s
), "%s operation timed out. Skipping SIGKILL.", service_state_to_string(s
->state
));
4132 service_enter_stop_post(s
, SERVICE_FAILURE_TIMEOUT
);
4137 assert_not_reached();
4141 case SERVICE_RUNNING
:
4142 log_unit_warning(UNIT(s
), "Service reached runtime time limit. Stopping.");
4143 service_enter_stop(s
, SERVICE_FAILURE_TIMEOUT
);
4146 case SERVICE_RELOAD
:
4147 case SERVICE_RELOAD_SIGNAL
:
4148 case SERVICE_RELOAD_NOTIFY
:
4149 log_unit_warning(UNIT(s
), "Reload operation timed out. Killing reload process.");
4150 service_kill_control_process(s
);
4151 s
->reload_result
= SERVICE_FAILURE_TIMEOUT
;
4152 service_enter_running(s
, SERVICE_SUCCESS
);
4156 switch (s
->timeout_stop_failure_mode
) {
4158 case SERVICE_TIMEOUT_TERMINATE
:
4159 log_unit_warning(UNIT(s
), "Stopping timed out. Terminating.");
4160 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_TIMEOUT
);
4163 case SERVICE_TIMEOUT_ABORT
:
4164 log_unit_warning(UNIT(s
), "Stopping timed out. Aborting.");
4165 service_enter_signal(s
, SERVICE_STOP_WATCHDOG
, SERVICE_FAILURE_TIMEOUT
);
4168 case SERVICE_TIMEOUT_KILL
:
4169 if (s
->kill_context
.send_sigkill
) {
4170 log_unit_warning(UNIT(s
), "Stopping timed out. Killing.");
4171 service_enter_signal(s
, SERVICE_STOP_SIGKILL
, SERVICE_FAILURE_TIMEOUT
);
4173 log_unit_warning(UNIT(s
), "Stopping timed out. Skipping SIGKILL.");
4174 service_enter_stop_post(s
, SERVICE_FAILURE_TIMEOUT
);
4179 assert_not_reached();
4183 case SERVICE_STOP_WATCHDOG
:
4184 if (s
->kill_context
.send_sigkill
) {
4185 log_unit_warning(UNIT(s
), "State 'stop-watchdog' timed out. Killing.");
4186 service_enter_signal(s
, SERVICE_STOP_SIGKILL
, SERVICE_FAILURE_TIMEOUT
);
4188 log_unit_warning(UNIT(s
), "State 'stop-watchdog' timed out. Skipping SIGKILL.");
4189 service_enter_stop_post(s
, SERVICE_FAILURE_TIMEOUT
);
4193 case SERVICE_STOP_SIGTERM
:
4194 if (s
->timeout_stop_failure_mode
== SERVICE_TIMEOUT_ABORT
) {
4195 log_unit_warning(UNIT(s
), "State 'stop-sigterm' timed out. Aborting.");
4196 service_enter_signal(s
, SERVICE_STOP_WATCHDOG
, SERVICE_FAILURE_TIMEOUT
);
4197 } else if (s
->kill_context
.send_sigkill
) {
4198 log_unit_warning(UNIT(s
), "State 'stop-sigterm' timed out. Killing.");
4199 service_enter_signal(s
, SERVICE_STOP_SIGKILL
, SERVICE_FAILURE_TIMEOUT
);
4201 log_unit_warning(UNIT(s
), "State 'stop-sigterm' timed out. Skipping SIGKILL.");
4202 service_enter_stop_post(s
, SERVICE_FAILURE_TIMEOUT
);
4207 case SERVICE_STOP_SIGKILL
:
4208 /* Uh, we sent a SIGKILL and it is still not gone?
4209 * Must be something we cannot kill, so let's just be
4210 * weirded out and continue */
4212 log_unit_warning(UNIT(s
), "Processes still around after SIGKILL. Ignoring.");
4213 service_enter_stop_post(s
, SERVICE_FAILURE_TIMEOUT
);
4216 case SERVICE_STOP_POST
:
4217 switch (s
->timeout_stop_failure_mode
) {
4219 case SERVICE_TIMEOUT_TERMINATE
:
4220 log_unit_warning(UNIT(s
), "State 'stop-post' timed out. Terminating.");
4221 service_enter_signal(s
, SERVICE_FINAL_SIGTERM
, SERVICE_FAILURE_TIMEOUT
);
4224 case SERVICE_TIMEOUT_ABORT
:
4225 log_unit_warning(UNIT(s
), "State 'stop-post' timed out. Aborting.");
4226 service_enter_signal(s
, SERVICE_FINAL_WATCHDOG
, SERVICE_FAILURE_TIMEOUT
);
4229 case SERVICE_TIMEOUT_KILL
:
4230 if (s
->kill_context
.send_sigkill
) {
4231 log_unit_warning(UNIT(s
), "State 'stop-post' timed out. Killing.");
4232 service_enter_signal(s
, SERVICE_FINAL_SIGKILL
, SERVICE_FAILURE_TIMEOUT
);
4234 log_unit_warning(UNIT(s
), "State 'stop-post' timed out. Skipping SIGKILL. Entering failed mode.");
4235 service_enter_dead(s
, SERVICE_FAILURE_TIMEOUT
, false);
4240 assert_not_reached();
4244 case SERVICE_FINAL_WATCHDOG
:
4245 if (s
->kill_context
.send_sigkill
) {
4246 log_unit_warning(UNIT(s
), "State 'final-watchdog' timed out. Killing.");
4247 service_enter_signal(s
, SERVICE_FINAL_SIGKILL
, SERVICE_FAILURE_TIMEOUT
);
4249 log_unit_warning(UNIT(s
), "State 'final-watchdog' timed out. Skipping SIGKILL. Entering failed mode.");
4250 service_enter_dead(s
, SERVICE_FAILURE_TIMEOUT
, false);
4254 case SERVICE_FINAL_SIGTERM
:
4255 if (s
->timeout_stop_failure_mode
== SERVICE_TIMEOUT_ABORT
) {
4256 log_unit_warning(UNIT(s
), "State 'final-sigterm' timed out. Aborting.");
4257 service_enter_signal(s
, SERVICE_FINAL_WATCHDOG
, SERVICE_FAILURE_TIMEOUT
);
4258 } else if (s
->kill_context
.send_sigkill
) {
4259 log_unit_warning(UNIT(s
), "State 'final-sigterm' timed out. Killing.");
4260 service_enter_signal(s
, SERVICE_FINAL_SIGKILL
, SERVICE_FAILURE_TIMEOUT
);
4262 log_unit_warning(UNIT(s
), "State 'final-sigterm' timed out. Skipping SIGKILL. Entering failed mode.");
4263 service_enter_dead(s
, SERVICE_FAILURE_TIMEOUT
, false);
4268 case SERVICE_FINAL_SIGKILL
:
4269 log_unit_warning(UNIT(s
), "Processes still around after final SIGKILL. Entering failed mode.");
4270 service_enter_dead(s
, SERVICE_FAILURE_TIMEOUT
, true);
4273 case SERVICE_AUTO_RESTART
:
4274 if (s
->restart_usec
> 0)
4275 log_unit_debug(UNIT(s
),
4276 "Service restart interval %s expired, scheduling restart.",
4277 FORMAT_TIMESPAN(service_restart_usec_next(s
), USEC_PER_SEC
));
4279 log_unit_debug(UNIT(s
),
4280 "Service has no hold-off time (RestartSec=0), scheduling restart.");
4282 service_enter_restart(s
);
4285 case SERVICE_CLEANING
:
4286 log_unit_warning(UNIT(s
), "Cleaning timed out. killing.");
4288 if (s
->clean_result
== SERVICE_SUCCESS
)
4289 s
->clean_result
= SERVICE_FAILURE_TIMEOUT
;
4291 service_enter_signal(s
, SERVICE_FINAL_SIGKILL
, 0);
4295 assert_not_reached();
4301 static int service_dispatch_watchdog(sd_event_source
*source
, usec_t usec
, void *userdata
) {
4302 Service
*s
= SERVICE(userdata
);
4303 usec_t watchdog_usec
;
4306 assert(source
== s
->watchdog_event_source
);
4308 watchdog_usec
= service_get_watchdog_usec(s
);
4310 if (UNIT(s
)->manager
->service_watchdogs
) {
4311 log_unit_error(UNIT(s
), "Watchdog timeout (limit %s)!",
4312 FORMAT_TIMESPAN(watchdog_usec
, 1));
4314 service_enter_signal(s
, SERVICE_STOP_WATCHDOG
, SERVICE_FAILURE_WATCHDOG
);
4316 log_unit_warning(UNIT(s
), "Watchdog disabled! Ignoring watchdog timeout (limit %s)!",
4317 FORMAT_TIMESPAN(watchdog_usec
, 1));
4322 static bool service_notify_message_authorized(Service
*s
, pid_t pid
, FDSet
*fds
) {
4325 NotifyAccess notify_access
= service_get_notify_access(s
);
4327 if (notify_access
== NOTIFY_NONE
) {
4328 log_unit_warning(UNIT(s
), "Got notification message from PID "PID_FMT
", but reception is disabled.", pid
);
4332 if (notify_access
== NOTIFY_MAIN
&& pid
!= s
->main_pid
.pid
) {
4333 if (pidref_is_set(&s
->main_pid
))
4334 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
);
4336 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
);
4341 if (notify_access
== NOTIFY_EXEC
&& pid
!= s
->main_pid
.pid
&& pid
!= s
->control_pid
.pid
) {
4342 if (pidref_is_set(&s
->main_pid
) && pidref_is_set(&s
->control_pid
))
4343 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
,
4344 pid
, s
->main_pid
.pid
, s
->control_pid
.pid
);
4345 else if (pidref_is_set(&s
->main_pid
))
4346 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
);
4347 else if (pidref_is_set(&s
->control_pid
))
4348 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
);
4350 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
);
4358 static void service_force_watchdog(Service
*s
) {
4359 if (!UNIT(s
)->manager
->service_watchdogs
)
4362 log_unit_error(UNIT(s
), "Watchdog request (last status: %s)!",
4363 s
->status_text
?: "<unset>");
4365 service_enter_signal(s
, SERVICE_STOP_WATCHDOG
, SERVICE_FAILURE_WATCHDOG
);
4368 static void service_notify_message(
4370 const struct ucred
*ucred
,
4374 Service
*s
= SERVICE(u
);
4375 bool notify_dbus
= false;
4376 usec_t monotonic_usec
= USEC_INFINITY
;
4383 if (!service_notify_message_authorized(s
, ucred
->pid
, fds
))
4386 if (DEBUG_LOGGING
) {
4387 _cleanup_free_
char *cc
= NULL
;
4389 cc
= strv_join(tags
, ", ");
4390 log_unit_debug(u
, "Got notification message from PID "PID_FMT
" (%s)", ucred
->pid
, isempty(cc
) ? "n/a" : cc
);
4393 /* Interpret MAINPID= */
4394 e
= strv_find_startswith(tags
, "MAINPID=");
4395 if (e
&& IN_SET(s
->state
, SERVICE_START
, SERVICE_START_POST
, SERVICE_RUNNING
, SERVICE_RELOAD
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
)) {
4398 if (parse_pid(e
, &new_main_pid
) < 0)
4399 log_unit_warning(u
, "Failed to parse MAINPID= field in notification message, ignoring: %s", e
);
4400 else if (!s
->main_pid_known
|| new_main_pid
!= s
->main_pid
.pid
) {
4402 r
= service_is_suitable_main_pid(s
, new_main_pid
, LOG_WARNING
);
4404 /* The new main PID is a bit suspicious, which is OK if the sender is privileged. */
4406 if (ucred
->uid
== 0) {
4407 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
);
4410 log_unit_debug(u
, "New main PID "PID_FMT
" does not belong to service, refusing.", new_main_pid
);
4413 (void) service_set_main_pid(s
, new_main_pid
);
4415 r
= unit_watch_pid(UNIT(s
), new_main_pid
, /* exclusive= */ false);
4417 log_unit_warning_errno(UNIT(s
), r
, "Failed to watch new main PID "PID_FMT
" for service: %m", new_main_pid
);
4424 /* Parse MONOTONIC_USEC= */
4425 e
= strv_find_startswith(tags
, "MONOTONIC_USEC=");
4427 r
= safe_atou64(e
, &monotonic_usec
);
4429 log_unit_warning_errno(u
, r
, "Failed to parse MONOTONIC_USEC= field in notification message, ignoring: %s", e
);
4432 /* Interpret READY=/STOPPING=/RELOADING=. STOPPING= wins over the others, and READY= over RELOADING= */
4433 if (strv_contains(tags
, "STOPPING=1")) {
4434 s
->notify_state
= NOTIFY_STOPPING
;
4436 if (IN_SET(s
->state
, SERVICE_RUNNING
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
))
4437 service_enter_stop_by_notify(s
);
4441 } else if (strv_contains(tags
, "READY=1")) {
4443 s
->notify_state
= NOTIFY_READY
;
4445 /* Type=notify services inform us about completed initialization with READY=1 */
4446 if (IN_SET(s
->type
, SERVICE_NOTIFY
, SERVICE_NOTIFY_RELOAD
) &&
4447 s
->state
== SERVICE_START
)
4448 service_enter_start_post(s
);
4450 /* Sending READY=1 while we are reloading informs us that the reloading is complete. */
4451 if (s
->state
== SERVICE_RELOAD_NOTIFY
)
4452 service_enter_running(s
, SERVICE_SUCCESS
);
4454 /* Combined RELOADING=1 and READY=1? Then this is indication that the service started and
4455 * immediately finished reloading. */
4456 if (s
->state
== SERVICE_RELOAD_SIGNAL
&&
4457 strv_contains(tags
, "RELOADING=1") &&
4458 monotonic_usec
!= USEC_INFINITY
&&
4459 monotonic_usec
>= s
->reload_begin_usec
) {
4460 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
4462 /* Propagate a reload explicitly */
4463 r
= manager_propagate_reload(UNIT(s
)->manager
, UNIT(s
), JOB_FAIL
, &error
);
4465 log_unit_warning(UNIT(s
), "Failed to schedule propagation of reload, ignoring: %s", bus_error_message(&error
, r
));
4467 service_enter_running(s
, SERVICE_SUCCESS
);
4472 } else if (strv_contains(tags
, "RELOADING=1")) {
4474 s
->notify_state
= NOTIFY_RELOADING
;
4476 /* Sending RELOADING=1 after we send SIGHUP to request a reload will transition
4477 * things to "reload-notify" state, where we'll wait for READY=1 to let us know the
4478 * reload is done. Note that we insist on a timestamp being sent along here, so that
4479 * we know for sure this is a reload cycle initiated *after* we sent the signal */
4480 if (s
->state
== SERVICE_RELOAD_SIGNAL
&&
4481 monotonic_usec
!= USEC_INFINITY
&&
4482 monotonic_usec
>= s
->reload_begin_usec
)
4483 /* Note, we don't call service_enter_reload_by_notify() here, because we
4484 * don't need reload propagation nor do we want to restart the time-out. */
4485 service_set_state(s
, SERVICE_RELOAD_NOTIFY
);
4487 if (s
->state
== SERVICE_RUNNING
)
4488 service_enter_reload_by_notify(s
);
4493 /* Interpret STATUS= */
4494 e
= strv_find_startswith(tags
, "STATUS=");
4496 _cleanup_free_
char *t
= NULL
;
4499 /* Note that this size limit check is mostly paranoia: since the datagram size we are willing
4500 * to process is already limited to NOTIFY_BUFFER_MAX, this limit here should never be hit. */
4501 if (strlen(e
) > STATUS_TEXT_MAX
)
4502 log_unit_warning(u
, "Status message overly long (%zu > %u), ignoring.", strlen(e
), STATUS_TEXT_MAX
);
4503 else if (!utf8_is_valid(e
))
4504 log_unit_warning(u
, "Status message in notification message is not UTF-8 clean, ignoring.");
4512 if (!streq_ptr(s
->status_text
, t
)) {
4513 free_and_replace(s
->status_text
, t
);
4518 /* Interpret NOTIFYACCESS= */
4519 e
= strv_find_startswith(tags
, "NOTIFYACCESS=");
4521 NotifyAccess notify_access
;
4523 notify_access
= notify_access_from_string(e
);
4524 if (notify_access
< 0)
4525 log_unit_warning_errno(u
, notify_access
,
4526 "Failed to parse NOTIFYACCESS= field value '%s' in notification message, ignoring: %m", e
);
4528 /* We don't need to check whether the new access mode is more strict than what is
4529 * already in use, since only the privileged process is allowed to change it
4530 * in the first place. */
4531 if (service_get_notify_access(s
) != notify_access
) {
4532 service_override_notify_access(s
, notify_access
);
4537 /* Interpret ERRNO= */
4538 e
= strv_find_startswith(tags
, "ERRNO=");
4542 status_errno
= parse_errno(e
);
4543 if (status_errno
< 0)
4544 log_unit_warning_errno(u
, status_errno
,
4545 "Failed to parse ERRNO= field value '%s' in notification message: %m", e
);
4546 else if (s
->status_errno
!= status_errno
) {
4547 s
->status_errno
= status_errno
;
4552 /* Interpret EXTEND_TIMEOUT= */
4553 e
= strv_find_startswith(tags
, "EXTEND_TIMEOUT_USEC=");
4555 usec_t extend_timeout_usec
;
4556 if (safe_atou64(e
, &extend_timeout_usec
) < 0)
4557 log_unit_warning(u
, "Failed to parse EXTEND_TIMEOUT_USEC=%s", e
);
4559 service_extend_timeout(s
, extend_timeout_usec
);
4562 /* Interpret WATCHDOG= */
4563 e
= strv_find_startswith(tags
, "WATCHDOG=");
4566 service_reset_watchdog(s
);
4567 else if (streq(e
, "trigger"))
4568 service_force_watchdog(s
);
4570 log_unit_warning(u
, "Passed WATCHDOG= field is invalid, ignoring.");
4573 e
= strv_find_startswith(tags
, "WATCHDOG_USEC=");
4575 usec_t watchdog_override_usec
;
4576 if (safe_atou64(e
, &watchdog_override_usec
) < 0)
4577 log_unit_warning(u
, "Failed to parse WATCHDOG_USEC=%s", e
);
4579 service_override_watchdog_timeout(s
, watchdog_override_usec
);
4582 /* Process FD store messages. Either FDSTOREREMOVE=1 for removal, or FDSTORE=1 for addition. In both cases,
4583 * process FDNAME= for picking the file descriptor name to use. Note that FDNAME= is required when removing
4584 * fds, but optional when pushing in new fds, for compatibility reasons. */
4585 if (strv_contains(tags
, "FDSTOREREMOVE=1")) {
4588 name
= strv_find_startswith(tags
, "FDNAME=");
4589 if (!name
|| !fdname_is_valid(name
))
4590 log_unit_warning(u
, "FDSTOREREMOVE=1 requested, but no valid file descriptor name passed, ignoring.");
4592 service_remove_fd_store(s
, name
);
4594 } else if (strv_contains(tags
, "FDSTORE=1")) {
4597 name
= strv_find_startswith(tags
, "FDNAME=");
4598 if (name
&& !fdname_is_valid(name
)) {
4599 log_unit_warning(u
, "Passed FDNAME= name is invalid, ignoring.");
4603 (void) service_add_fd_store_set(s
, fds
, name
, !strv_contains(tags
, "FDPOLL=0"));
4606 /* Notify clients about changed status or main pid */
4608 unit_add_to_dbus_queue(u
);
4611 static int service_get_timeout(Unit
*u
, usec_t
*timeout
) {
4612 Service
*s
= SERVICE(u
);
4616 if (!s
->timer_event_source
)
4619 r
= sd_event_source_get_time(s
->timer_event_source
, &t
);
4622 if (t
== USEC_INFINITY
)
4629 static usec_t
service_get_timeout_start_usec(Unit
*u
) {
4630 Service
*s
= SERVICE(ASSERT_PTR(u
));
4631 return s
->timeout_start_usec
;
4634 static bool pick_up_pid_from_bus_name(Service
*s
) {
4637 /* If the service is running but we have no main PID yet, get it from the owner of the D-Bus name */
4639 return !pidref_is_set(&s
->main_pid
) &&
4645 SERVICE_RELOAD_SIGNAL
,
4646 SERVICE_RELOAD_NOTIFY
);
4649 static int bus_name_pid_lookup_callback(sd_bus_message
*reply
, void *userdata
, sd_bus_error
*ret_error
) {
4650 const sd_bus_error
*e
;
4651 Unit
*u
= ASSERT_PTR(userdata
);
4659 s
->bus_name_pid_lookup_slot
= sd_bus_slot_unref(s
->bus_name_pid_lookup_slot
);
4661 if (!s
->bus_name
|| !pick_up_pid_from_bus_name(s
))
4664 e
= sd_bus_message_get_error(reply
);
4666 r
= sd_bus_error_get_errno(e
);
4667 log_warning_errno(r
, "GetConnectionUnixProcessID() failed: %s", bus_error_message(e
, r
));
4671 r
= sd_bus_message_read(reply
, "u", &pid
);
4673 bus_log_parse_error(r
);
4677 if (!pid_is_valid(pid
)) {
4678 log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "GetConnectionUnixProcessID() returned invalid PID");
4682 log_unit_debug(u
, "D-Bus name %s is now owned by process " PID_FMT
, s
->bus_name
, (pid_t
) pid
);
4684 (void) service_set_main_pid(s
, pid
);
4685 (void) unit_watch_pid(UNIT(s
), pid
, /* exclusive= */ false);
4689 static void service_bus_name_owner_change(Unit
*u
, const char *new_owner
) {
4691 Service
*s
= SERVICE(u
);
4697 log_unit_debug(u
, "D-Bus name %s now owned by %s", s
->bus_name
, new_owner
);
4699 log_unit_debug(u
, "D-Bus name %s now not owned by anyone.", s
->bus_name
);
4701 s
->bus_name_good
= new_owner
;
4703 /* Track the current owner, so we can reconstruct changes after a daemon reload */
4704 r
= free_and_strdup(&s
->bus_name_owner
, new_owner
);
4706 log_unit_error_errno(u
, r
, "Unable to set new bus name owner %s: %m", new_owner
);
4710 if (s
->type
== SERVICE_DBUS
) {
4712 /* service_enter_running() will figure out what to
4714 if (s
->state
== SERVICE_RUNNING
)
4715 service_enter_running(s
, SERVICE_SUCCESS
);
4716 else if (s
->state
== SERVICE_START
&& new_owner
)
4717 service_enter_start_post(s
);
4719 } else if (new_owner
&& pick_up_pid_from_bus_name(s
)) {
4721 /* Try to acquire PID from bus service */
4723 s
->bus_name_pid_lookup_slot
= sd_bus_slot_unref(s
->bus_name_pid_lookup_slot
);
4725 r
= sd_bus_call_method_async(
4726 u
->manager
->api_bus
,
4727 &s
->bus_name_pid_lookup_slot
,
4728 "org.freedesktop.DBus",
4729 "/org/freedesktop/DBus",
4730 "org.freedesktop.DBus",
4731 "GetConnectionUnixProcessID",
4732 bus_name_pid_lookup_callback
,
4737 log_debug_errno(r
, "Failed to request owner PID of service name, ignoring: %m");
4741 int service_set_socket_fd(
4746 bool selinux_context_net
) {
4748 _cleanup_free_
char *peer_text
= NULL
;
4754 /* This is called by the socket code when instantiating a new service for a stream socket and the socket needs
4755 * to be configured. We take ownership of the passed fd on success. */
4757 if (UNIT(s
)->load_state
!= UNIT_LOADED
)
4760 if (s
->socket_fd
>= 0)
4763 assert(!s
->socket_peer
);
4765 if (!IN_SET(s
->state
, SERVICE_DEAD
, SERVICE_DEAD_RESOURCES_PINNED
))
4768 if (getpeername_pretty(fd
, true, &peer_text
) >= 0) {
4770 if (UNIT(s
)->description
) {
4771 _cleanup_free_
char *a
= NULL
;
4773 a
= strjoin(UNIT(s
)->description
, " (", peer_text
, ")");
4777 r
= unit_set_description(UNIT(s
), a
);
4779 r
= unit_set_description(UNIT(s
), peer_text
);
4784 r
= unit_add_two_dependencies(UNIT(sock
), UNIT_BEFORE
, UNIT_TRIGGERS
, UNIT(s
), false, UNIT_DEPENDENCY_IMPLICIT
);
4789 s
->socket_peer
= socket_peer_ref(peer
);
4790 s
->socket_fd_selinux_context_net
= selinux_context_net
;
4792 unit_ref_set(&s
->accept_socket
, UNIT(s
), UNIT(sock
));
4796 static void service_reset_failed(Unit
*u
) {
4797 Service
*s
= SERVICE(u
);
4801 if (s
->state
== SERVICE_FAILED
)
4802 service_set_state(s
, service_determine_dead_state(s
));
4804 s
->result
= SERVICE_SUCCESS
;
4805 s
->reload_result
= SERVICE_SUCCESS
;
4806 s
->clean_result
= SERVICE_SUCCESS
;
4808 s
->flush_n_restarts
= false;
4811 static int service_kill(Unit
*u
, KillWho who
, int signo
, int code
, int value
, sd_bus_error
*error
) {
4812 Service
*s
= SERVICE(u
);
4816 return unit_kill_common(u
, who
, signo
, code
, value
, s
->main_pid
.pid
, s
->control_pid
.pid
, error
);
4819 static int service_main_pid(Unit
*u
) {
4820 Service
*s
= SERVICE(u
);
4824 return s
->main_pid
.pid
;
4827 static int service_control_pid(Unit
*u
) {
4828 Service
*s
= SERVICE(u
);
4832 return s
->control_pid
.pid
;
4835 static bool service_needs_console(Unit
*u
) {
4836 Service
*s
= SERVICE(u
);
4840 /* We provide our own implementation of this here, instead of relying of the generic implementation
4841 * unit_needs_console() provides, since we want to return false if we are in SERVICE_EXITED state. */
4843 if (!exec_context_may_touch_console(&s
->exec_context
))
4846 return IN_SET(s
->state
,
4853 SERVICE_RELOAD_SIGNAL
,
4854 SERVICE_RELOAD_NOTIFY
,
4856 SERVICE_STOP_WATCHDOG
,
4857 SERVICE_STOP_SIGTERM
,
4858 SERVICE_STOP_SIGKILL
,
4860 SERVICE_FINAL_WATCHDOG
,
4861 SERVICE_FINAL_SIGTERM
,
4862 SERVICE_FINAL_SIGKILL
);
4865 static int service_exit_status(Unit
*u
) {
4866 Service
*s
= SERVICE(u
);
4870 if (s
->main_exec_status
.pid
<= 0 ||
4871 !dual_timestamp_is_set(&s
->main_exec_status
.exit_timestamp
))
4874 if (s
->main_exec_status
.code
!= CLD_EXITED
)
4877 return s
->main_exec_status
.status
;
4880 static const char* service_status_text(Unit
*u
) {
4881 Service
*s
= SERVICE(u
);
4885 return s
->status_text
;
4888 static int service_clean(Unit
*u
, ExecCleanMask mask
) {
4889 _cleanup_strv_free_
char **l
= NULL
;
4890 bool may_clean_fdstore
= false;
4891 Service
*s
= SERVICE(u
);
4898 if (!IN_SET(s
->state
, SERVICE_DEAD
, SERVICE_DEAD_RESOURCES_PINNED
))
4901 /* Determine if there's anything we could potentially clean */
4902 r
= exec_context_get_clean_directories(&s
->exec_context
, u
->manager
->prefix
, mask
, &l
);
4906 if (mask
& EXEC_CLEAN_FDSTORE
)
4907 may_clean_fdstore
= s
->n_fd_store
> 0 || s
->n_fd_store_max
> 0;
4909 if (strv_isempty(l
) && !may_clean_fdstore
)
4910 return -EUNATCH
; /* Nothing to potentially clean */
4912 /* Let's clean the stuff we can clean quickly */
4913 if (may_clean_fdstore
)
4914 service_release_fd_store(s
);
4916 /* If we are done, leave quickly */
4917 if (strv_isempty(l
)) {
4918 if (s
->state
== SERVICE_DEAD_RESOURCES_PINNED
&& !s
->fd_store
)
4919 service_set_state(s
, SERVICE_DEAD
);
4923 /* We need to clean disk stuff. This is slow, hence do it out of process, and change state */
4924 service_unwatch_control_pid(s
);
4925 s
->clean_result
= SERVICE_SUCCESS
;
4926 s
->control_command
= NULL
;
4927 s
->control_command_id
= _SERVICE_EXEC_COMMAND_INVALID
;
4929 r
= service_arm_timer(s
, /* relative= */ true, s
->exec_context
.timeout_clean_usec
);
4933 r
= unit_fork_and_watch_rm_rf(u
, l
, &pid
);
4937 r
= pidref_set_pid(&s
->control_pid
, pid
);
4941 service_set_state(s
, SERVICE_CLEANING
);
4945 log_unit_warning_errno(u
, r
, "Failed to initiate cleaning: %m");
4946 s
->clean_result
= SERVICE_FAILURE_RESOURCES
;
4947 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
4951 static int service_can_clean(Unit
*u
, ExecCleanMask
*ret
) {
4952 Service
*s
= SERVICE(u
);
4953 ExecCleanMask mask
= 0;
4959 r
= exec_context_get_clean_mask(&s
->exec_context
, &mask
);
4963 if (s
->n_fd_store_max
> 0)
4964 mask
|= EXEC_CLEAN_FDSTORE
;
4970 static const char *service_finished_job(Unit
*u
, JobType t
, JobResult result
) {
4971 if (t
== JOB_START
&&
4972 result
== JOB_DONE
&&
4973 SERVICE(u
)->type
== SERVICE_ONESHOT
)
4974 return "Finished %s.";
4976 /* Fall back to generic */
4980 static int service_can_start(Unit
*u
) {
4981 Service
*s
= SERVICE(u
);
4986 /* Make sure we don't enter a busy loop of some kind. */
4987 r
= unit_test_start_limit(u
);
4989 service_enter_dead(s
, SERVICE_FAILURE_START_LIMIT_HIT
, false);
4996 static void service_release_resources(Unit
*u
) {
4997 Service
*s
= SERVICE(ASSERT_PTR(u
));
4999 /* Invoked by the unit state engine, whenever it realizes that unit is dead and there's no job
5000 * anymore for it, and it hence is a good idea to release resources */
5002 /* Don't release resources if this is a transitionary failed/dead state
5003 * (i.e. SERVICE_DEAD_BEFORE_AUTO_RESTART/SERVICE_FAILED_BEFORE_AUTO_RESTART), insist on a permanent
5005 if (!IN_SET(s
->state
, SERVICE_DEAD
, SERVICE_FAILED
, SERVICE_DEAD_RESOURCES_PINNED
))
5008 log_unit_debug(u
, "Releasing resources...");
5010 service_release_socket_fd(s
);
5011 service_release_stdio_fd(s
);
5013 if (s
->fd_store_preserve_mode
!= EXEC_PRESERVE_YES
)
5014 service_release_fd_store(s
);
5016 if (s
->state
== SERVICE_DEAD_RESOURCES_PINNED
&& !s
->fd_store
)
5017 service_set_state(s
, SERVICE_DEAD
);
5020 static const char* const service_restart_table
[_SERVICE_RESTART_MAX
] = {
5021 [SERVICE_RESTART_NO
] = "no",
5022 [SERVICE_RESTART_ON_SUCCESS
] = "on-success",
5023 [SERVICE_RESTART_ON_FAILURE
] = "on-failure",
5024 [SERVICE_RESTART_ON_ABNORMAL
] = "on-abnormal",
5025 [SERVICE_RESTART_ON_WATCHDOG
] = "on-watchdog",
5026 [SERVICE_RESTART_ON_ABORT
] = "on-abort",
5027 [SERVICE_RESTART_ALWAYS
] = "always",
5030 DEFINE_STRING_TABLE_LOOKUP(service_restart
, ServiceRestart
);
5032 static const char* const service_restart_mode_table
[_SERVICE_RESTART_MODE_MAX
] = {
5033 [SERVICE_RESTART_MODE_NORMAL
] = "normal",
5034 [SERVICE_RESTART_MODE_DIRECT
] = "direct",
5037 DEFINE_STRING_TABLE_LOOKUP(service_restart_mode
, ServiceRestartMode
);
5039 static const char* const service_type_table
[_SERVICE_TYPE_MAX
] = {
5040 [SERVICE_SIMPLE
] = "simple",
5041 [SERVICE_FORKING
] = "forking",
5042 [SERVICE_ONESHOT
] = "oneshot",
5043 [SERVICE_DBUS
] = "dbus",
5044 [SERVICE_NOTIFY
] = "notify",
5045 [SERVICE_NOTIFY_RELOAD
] = "notify-reload",
5046 [SERVICE_IDLE
] = "idle",
5047 [SERVICE_EXEC
] = "exec",
5050 DEFINE_STRING_TABLE_LOOKUP(service_type
, ServiceType
);
5052 static const char* const service_exit_type_table
[_SERVICE_EXIT_TYPE_MAX
] = {
5053 [SERVICE_EXIT_MAIN
] = "main",
5054 [SERVICE_EXIT_CGROUP
] = "cgroup",
5057 DEFINE_STRING_TABLE_LOOKUP(service_exit_type
, ServiceExitType
);
5059 static const char* const service_exec_command_table
[_SERVICE_EXEC_COMMAND_MAX
] = {
5060 [SERVICE_EXEC_CONDITION
] = "ExecCondition",
5061 [SERVICE_EXEC_START_PRE
] = "ExecStartPre",
5062 [SERVICE_EXEC_START
] = "ExecStart",
5063 [SERVICE_EXEC_START_POST
] = "ExecStartPost",
5064 [SERVICE_EXEC_RELOAD
] = "ExecReload",
5065 [SERVICE_EXEC_STOP
] = "ExecStop",
5066 [SERVICE_EXEC_STOP_POST
] = "ExecStopPost",
5069 DEFINE_STRING_TABLE_LOOKUP(service_exec_command
, ServiceExecCommand
);
5071 static const char* const service_exec_ex_command_table
[_SERVICE_EXEC_COMMAND_MAX
] = {
5072 [SERVICE_EXEC_CONDITION
] = "ExecConditionEx",
5073 [SERVICE_EXEC_START_PRE
] = "ExecStartPreEx",
5074 [SERVICE_EXEC_START
] = "ExecStartEx",
5075 [SERVICE_EXEC_START_POST
] = "ExecStartPostEx",
5076 [SERVICE_EXEC_RELOAD
] = "ExecReloadEx",
5077 [SERVICE_EXEC_STOP
] = "ExecStopEx",
5078 [SERVICE_EXEC_STOP_POST
] = "ExecStopPostEx",
5081 DEFINE_STRING_TABLE_LOOKUP(service_exec_ex_command
, ServiceExecCommand
);
5083 static const char* const notify_state_table
[_NOTIFY_STATE_MAX
] = {
5084 [NOTIFY_UNKNOWN
] = "unknown",
5085 [NOTIFY_READY
] = "ready",
5086 [NOTIFY_RELOADING
] = "reloading",
5087 [NOTIFY_STOPPING
] = "stopping",
5090 DEFINE_STRING_TABLE_LOOKUP(notify_state
, NotifyState
);
5092 static const char* const service_result_table
[_SERVICE_RESULT_MAX
] = {
5093 [SERVICE_SUCCESS
] = "success",
5094 [SERVICE_FAILURE_RESOURCES
] = "resources",
5095 [SERVICE_FAILURE_PROTOCOL
] = "protocol",
5096 [SERVICE_FAILURE_TIMEOUT
] = "timeout",
5097 [SERVICE_FAILURE_EXIT_CODE
] = "exit-code",
5098 [SERVICE_FAILURE_SIGNAL
] = "signal",
5099 [SERVICE_FAILURE_CORE_DUMP
] = "core-dump",
5100 [SERVICE_FAILURE_WATCHDOG
] = "watchdog",
5101 [SERVICE_FAILURE_START_LIMIT_HIT
] = "start-limit-hit",
5102 [SERVICE_FAILURE_OOM_KILL
] = "oom-kill",
5103 [SERVICE_SKIP_CONDITION
] = "exec-condition",
5106 DEFINE_STRING_TABLE_LOOKUP(service_result
, ServiceResult
);
5108 static const char* const service_timeout_failure_mode_table
[_SERVICE_TIMEOUT_FAILURE_MODE_MAX
] = {
5109 [SERVICE_TIMEOUT_TERMINATE
] = "terminate",
5110 [SERVICE_TIMEOUT_ABORT
] = "abort",
5111 [SERVICE_TIMEOUT_KILL
] = "kill",
5114 DEFINE_STRING_TABLE_LOOKUP(service_timeout_failure_mode
, ServiceTimeoutFailureMode
);
5116 const UnitVTable service_vtable
= {
5117 .object_size
= sizeof(Service
),
5118 .exec_context_offset
= offsetof(Service
, exec_context
),
5119 .cgroup_context_offset
= offsetof(Service
, cgroup_context
),
5120 .kill_context_offset
= offsetof(Service
, kill_context
),
5121 .exec_runtime_offset
= offsetof(Service
, exec_runtime
),
5127 .private_section
= "Service",
5129 .can_transient
= true,
5130 .can_delegate
= true,
5132 .can_set_managed_oom
= true,
5134 .init
= service_init
,
5135 .done
= service_done
,
5136 .load
= service_load
,
5137 .release_resources
= service_release_resources
,
5139 .coldplug
= service_coldplug
,
5141 .dump
= service_dump
,
5143 .start
= service_start
,
5144 .stop
= service_stop
,
5145 .reload
= service_reload
,
5147 .can_reload
= service_can_reload
,
5149 .kill
= service_kill
,
5150 .clean
= service_clean
,
5151 .can_clean
= service_can_clean
,
5153 .freeze
= unit_freeze_vtable_common
,
5154 .thaw
= unit_thaw_vtable_common
,
5156 .serialize
= service_serialize
,
5157 .deserialize_item
= service_deserialize_item
,
5159 .active_state
= service_active_state
,
5160 .sub_state_to_string
= service_sub_state_to_string
,
5162 .will_restart
= service_will_restart
,
5164 .may_gc
= service_may_gc
,
5166 .sigchld_event
= service_sigchld_event
,
5168 .reset_failed
= service_reset_failed
,
5170 .notify_cgroup_empty
= service_notify_cgroup_empty_event
,
5171 .notify_cgroup_oom
= service_notify_cgroup_oom_event
,
5172 .notify_message
= service_notify_message
,
5174 .main_pid
= service_main_pid
,
5175 .control_pid
= service_control_pid
,
5177 .bus_name_owner_change
= service_bus_name_owner_change
,
5179 .bus_set_property
= bus_service_set_property
,
5180 .bus_commit_properties
= bus_service_commit_properties
,
5182 .get_timeout
= service_get_timeout
,
5183 .get_timeout_start_usec
= service_get_timeout_start_usec
,
5184 .needs_console
= service_needs_console
,
5185 .exit_status
= service_exit_status
,
5186 .status_text
= service_status_text
,
5188 .status_message_formats
= {
5189 .finished_start_job
= {
5190 [JOB_FAILED
] = "Failed to start %s.",
5192 .finished_stop_job
= {
5193 [JOB_DONE
] = "Stopped %s.",
5194 [JOB_FAILED
] = "Stopped (with error) %s.",
5196 .finished_job
= service_finished_job
,
5199 .can_start
= service_can_start
,
5201 .notify_plymouth
= true,
5203 .audit_start_message_type
= AUDIT_SERVICE_START
,
5204 .audit_stop_message_type
= AUDIT_SERVICE_STOP
,