1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
8 #include "sd-messages.h"
10 #include "alloc-util.h"
12 #include "bus-error.h"
13 #include "bus-kernel.h"
16 #include "constants.h"
17 #include "dbus-service.h"
18 #include "dbus-unit.h"
21 #include "exit-status.h"
24 #include "format-util.h"
25 #include "load-dropin.h"
26 #include "load-fragment.h"
29 #include "open-file.h"
30 #include "parse-util.h"
31 #include "path-util.h"
32 #include "process-util.h"
33 #include "random-util.h"
34 #include "serialize.h"
36 #include "signal-util.h"
38 #include "stdio-util.h"
39 #include "string-table.h"
40 #include "string-util.h"
42 #include "unit-name.h"
46 #define service_spawn(...) service_spawn_internal(__func__, __VA_ARGS__)
48 static const UnitActiveState state_translation_table
[_SERVICE_STATE_MAX
] = {
49 [SERVICE_DEAD
] = UNIT_INACTIVE
,
50 [SERVICE_CONDITION
] = UNIT_ACTIVATING
,
51 [SERVICE_START_PRE
] = UNIT_ACTIVATING
,
52 [SERVICE_START
] = UNIT_ACTIVATING
,
53 [SERVICE_START_POST
] = UNIT_ACTIVATING
,
54 [SERVICE_RUNNING
] = UNIT_ACTIVE
,
55 [SERVICE_EXITED
] = UNIT_ACTIVE
,
56 [SERVICE_RELOAD
] = UNIT_RELOADING
,
57 [SERVICE_RELOAD_SIGNAL
] = UNIT_RELOADING
,
58 [SERVICE_RELOAD_NOTIFY
] = UNIT_RELOADING
,
59 [SERVICE_STOP
] = UNIT_DEACTIVATING
,
60 [SERVICE_STOP_WATCHDOG
] = UNIT_DEACTIVATING
,
61 [SERVICE_STOP_SIGTERM
] = UNIT_DEACTIVATING
,
62 [SERVICE_STOP_SIGKILL
] = UNIT_DEACTIVATING
,
63 [SERVICE_STOP_POST
] = UNIT_DEACTIVATING
,
64 [SERVICE_FINAL_WATCHDOG
] = UNIT_DEACTIVATING
,
65 [SERVICE_FINAL_SIGTERM
] = UNIT_DEACTIVATING
,
66 [SERVICE_FINAL_SIGKILL
] = UNIT_DEACTIVATING
,
67 [SERVICE_FAILED
] = UNIT_FAILED
,
68 [SERVICE_AUTO_RESTART
] = UNIT_ACTIVATING
,
69 [SERVICE_CLEANING
] = UNIT_MAINTENANCE
,
72 /* For Type=idle we never want to delay any other jobs, hence we
73 * consider idle jobs active as soon as we start working on them */
74 static const UnitActiveState state_translation_table_idle
[_SERVICE_STATE_MAX
] = {
75 [SERVICE_DEAD
] = UNIT_INACTIVE
,
76 [SERVICE_CONDITION
] = UNIT_ACTIVE
,
77 [SERVICE_START_PRE
] = UNIT_ACTIVE
,
78 [SERVICE_START
] = UNIT_ACTIVE
,
79 [SERVICE_START_POST
] = UNIT_ACTIVE
,
80 [SERVICE_RUNNING
] = UNIT_ACTIVE
,
81 [SERVICE_EXITED
] = UNIT_ACTIVE
,
82 [SERVICE_RELOAD
] = UNIT_RELOADING
,
83 [SERVICE_RELOAD_SIGNAL
] = UNIT_RELOADING
,
84 [SERVICE_RELOAD_NOTIFY
] = UNIT_RELOADING
,
85 [SERVICE_STOP
] = UNIT_DEACTIVATING
,
86 [SERVICE_STOP_WATCHDOG
] = UNIT_DEACTIVATING
,
87 [SERVICE_STOP_SIGTERM
] = UNIT_DEACTIVATING
,
88 [SERVICE_STOP_SIGKILL
] = UNIT_DEACTIVATING
,
89 [SERVICE_STOP_POST
] = UNIT_DEACTIVATING
,
90 [SERVICE_FINAL_WATCHDOG
] = UNIT_DEACTIVATING
,
91 [SERVICE_FINAL_SIGTERM
] = UNIT_DEACTIVATING
,
92 [SERVICE_FINAL_SIGKILL
] = UNIT_DEACTIVATING
,
93 [SERVICE_FAILED
] = UNIT_FAILED
,
94 [SERVICE_AUTO_RESTART
] = UNIT_ACTIVATING
,
95 [SERVICE_CLEANING
] = UNIT_MAINTENANCE
,
98 static int service_dispatch_inotify_io(sd_event_source
*source
, int fd
, uint32_t events
, void *userdata
);
99 static int service_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
);
100 static int service_dispatch_watchdog(sd_event_source
*source
, usec_t usec
, void *userdata
);
101 static int service_dispatch_exec_io(sd_event_source
*source
, int fd
, uint32_t events
, void *userdata
);
103 static void service_enter_signal(Service
*s
, ServiceState state
, ServiceResult f
);
104 static void service_enter_reload_by_notify(Service
*s
);
106 static void service_init(Unit
*u
) {
107 Service
*s
= SERVICE(u
);
110 assert(u
->load_state
== UNIT_STUB
);
112 s
->timeout_start_usec
= u
->manager
->default_timeout_start_usec
;
113 s
->timeout_stop_usec
= u
->manager
->default_timeout_stop_usec
;
114 s
->timeout_abort_usec
= u
->manager
->default_timeout_abort_usec
;
115 s
->timeout_abort_set
= u
->manager
->default_timeout_abort_set
;
116 s
->restart_usec
= u
->manager
->default_restart_usec
;
117 s
->runtime_max_usec
= USEC_INFINITY
;
118 s
->type
= _SERVICE_TYPE_INVALID
;
119 s
->socket_fd
= -EBADF
;
120 s
->stdin_fd
= s
->stdout_fd
= s
->stderr_fd
= -EBADF
;
121 s
->guess_main_pid
= true;
123 s
->control_command_id
= _SERVICE_EXEC_COMMAND_INVALID
;
125 s
->exec_context
.keyring_mode
= MANAGER_IS_SYSTEM(u
->manager
) ?
126 EXEC_KEYRING_PRIVATE
: EXEC_KEYRING_INHERIT
;
128 s
->notify_access_override
= _NOTIFY_ACCESS_INVALID
;
130 s
->watchdog_original_usec
= USEC_INFINITY
;
132 s
->oom_policy
= _OOM_POLICY_INVALID
;
133 s
->reload_begin_usec
= USEC_INFINITY
;
134 s
->reload_signal
= SIGHUP
;
137 static void service_unwatch_control_pid(Service
*s
) {
140 if (s
->control_pid
<= 0)
143 unit_unwatch_pid(UNIT(s
), TAKE_PID(s
->control_pid
));
146 static void service_unwatch_main_pid(Service
*s
) {
149 if (s
->main_pid
<= 0)
152 unit_unwatch_pid(UNIT(s
), TAKE_PID(s
->main_pid
));
155 static void service_unwatch_pid_file(Service
*s
) {
156 if (!s
->pid_file_pathspec
)
159 log_unit_debug(UNIT(s
), "Stopping watch for PID file %s", s
->pid_file_pathspec
->path
);
160 path_spec_unwatch(s
->pid_file_pathspec
);
161 path_spec_done(s
->pid_file_pathspec
);
162 s
->pid_file_pathspec
= mfree(s
->pid_file_pathspec
);
165 static int service_set_main_pid(Service
*s
, pid_t pid
) {
171 if (pid
== getpid_cached())
174 if (s
->main_pid
== pid
&& s
->main_pid_known
)
177 if (s
->main_pid
!= pid
) {
178 service_unwatch_main_pid(s
);
179 exec_status_start(&s
->main_exec_status
, pid
);
183 s
->main_pid_known
= true;
184 s
->main_pid_alien
= pid_is_my_child(pid
) == 0;
186 if (s
->main_pid_alien
)
187 log_unit_warning(UNIT(s
), "Supervising process "PID_FMT
" which is not our child. We'll most likely not notice when it exits.", pid
);
192 void service_close_socket_fd(Service
*s
) {
195 /* Undo the effect of service_set_socket_fd(). */
197 s
->socket_fd
= asynchronous_close(s
->socket_fd
);
199 if (UNIT_ISSET(s
->accept_socket
)) {
200 socket_connection_unref(SOCKET(UNIT_DEREF(s
->accept_socket
)));
201 unit_ref_unset(&s
->accept_socket
);
204 s
->socket_peer
= socket_peer_unref(s
->socket_peer
);
207 static void service_override_notify_access(Service
*s
, NotifyAccess notify_access_override
) {
210 s
->notify_access_override
= notify_access_override
;
212 log_unit_debug(UNIT(s
), "notify_access=%s", notify_access_to_string(s
->notify_access
));
213 log_unit_debug(UNIT(s
), "notify_access_override=%s", notify_access_to_string(s
->notify_access_override
));
216 static void service_stop_watchdog(Service
*s
) {
219 s
->watchdog_event_source
= sd_event_source_disable_unref(s
->watchdog_event_source
);
220 s
->watchdog_timestamp
= DUAL_TIMESTAMP_NULL
;
223 static void service_start_watchdog(Service
*s
) {
224 usec_t watchdog_usec
;
229 watchdog_usec
= service_get_watchdog_usec(s
);
230 if (!timestamp_is_set(watchdog_usec
)) {
231 service_stop_watchdog(s
);
235 if (s
->watchdog_event_source
) {
236 r
= sd_event_source_set_time(s
->watchdog_event_source
, usec_add(s
->watchdog_timestamp
.monotonic
, watchdog_usec
));
238 log_unit_warning_errno(UNIT(s
), r
, "Failed to reset watchdog timer: %m");
242 r
= sd_event_source_set_enabled(s
->watchdog_event_source
, SD_EVENT_ONESHOT
);
244 r
= sd_event_add_time(
245 UNIT(s
)->manager
->event
,
246 &s
->watchdog_event_source
,
248 usec_add(s
->watchdog_timestamp
.monotonic
, watchdog_usec
), 0,
249 service_dispatch_watchdog
, s
);
251 log_unit_warning_errno(UNIT(s
), r
, "Failed to add watchdog timer: %m");
255 (void) sd_event_source_set_description(s
->watchdog_event_source
, "service-watchdog");
257 /* Let's process everything else which might be a sign
258 * of living before we consider a service died. */
259 r
= sd_event_source_set_priority(s
->watchdog_event_source
, SD_EVENT_PRIORITY_IDLE
);
262 log_unit_warning_errno(UNIT(s
), r
, "Failed to install watchdog timer: %m");
265 static void service_extend_event_source_timeout(Service
*s
, sd_event_source
*source
, usec_t extended
) {
271 /* Extends the specified event source timer to at least the specified time, unless it is already later
277 r
= sd_event_source_get_time(source
, ¤t
);
280 (void) sd_event_source_get_description(s
->timer_event_source
, &desc
);
281 log_unit_warning_errno(UNIT(s
), r
, "Failed to retrieve timeout time for event source '%s', ignoring: %m", strna(desc
));
285 if (current
>= extended
) /* Current timeout is already longer, ignore this. */
288 r
= sd_event_source_set_time(source
, extended
);
291 (void) sd_event_source_get_description(s
->timer_event_source
, &desc
);
292 log_unit_warning_errno(UNIT(s
), r
, "Failed to set timeout time for event source '%s', ignoring %m", strna(desc
));
296 static void service_extend_timeout(Service
*s
, usec_t extend_timeout_usec
) {
301 if (!timestamp_is_set(extend_timeout_usec
))
304 extended
= usec_add(now(CLOCK_MONOTONIC
), extend_timeout_usec
);
306 service_extend_event_source_timeout(s
, s
->timer_event_source
, extended
);
307 service_extend_event_source_timeout(s
, s
->watchdog_event_source
, extended
);
310 static void service_reset_watchdog(Service
*s
) {
313 dual_timestamp_get(&s
->watchdog_timestamp
);
314 service_start_watchdog(s
);
317 static void service_override_watchdog_timeout(Service
*s
, usec_t watchdog_override_usec
) {
320 s
->watchdog_override_enable
= true;
321 s
->watchdog_override_usec
= watchdog_override_usec
;
322 service_reset_watchdog(s
);
324 log_unit_debug(UNIT(s
), "watchdog_usec="USEC_FMT
, s
->watchdog_usec
);
325 log_unit_debug(UNIT(s
), "watchdog_override_usec="USEC_FMT
, s
->watchdog_override_usec
);
328 static void service_fd_store_unlink(ServiceFDStore
*fs
) {
334 assert(fs
->service
->n_fd_store
> 0);
335 LIST_REMOVE(fd_store
, fs
->service
->fd_store
, fs
);
336 fs
->service
->n_fd_store
--;
339 sd_event_source_disable_unref(fs
->event_source
);
346 static void service_release_fd_store(Service
*s
) {
349 if (s
->n_keep_fd_store
> 0)
352 log_unit_debug(UNIT(s
), "Releasing all stored fds");
354 service_fd_store_unlink(s
->fd_store
);
356 assert(s
->n_fd_store
== 0);
359 static void service_release_resources(Unit
*u
) {
360 Service
*s
= SERVICE(u
);
364 if (!s
->fd_store
&& s
->stdin_fd
< 0 && s
->stdout_fd
< 0 && s
->stderr_fd
< 0)
367 log_unit_debug(u
, "Releasing resources.");
369 s
->stdin_fd
= safe_close(s
->stdin_fd
);
370 s
->stdout_fd
= safe_close(s
->stdout_fd
);
371 s
->stderr_fd
= safe_close(s
->stderr_fd
);
373 service_release_fd_store(s
);
376 static void service_done(Unit
*u
) {
377 Service
*s
= SERVICE(u
);
381 open_file_free_many(&s
->open_files
);
383 s
->pid_file
= mfree(s
->pid_file
);
384 s
->status_text
= mfree(s
->status_text
);
386 s
->exec_runtime
= exec_shared_runtime_unref(s
->exec_runtime
, false);
387 exec_command_free_array(s
->exec_command
, _SERVICE_EXEC_COMMAND_MAX
);
388 s
->control_command
= NULL
;
389 s
->main_command
= NULL
;
391 dynamic_creds_unref(&s
->dynamic_creds
);
393 exit_status_set_free(&s
->restart_prevent_status
);
394 exit_status_set_free(&s
->restart_force_status
);
395 exit_status_set_free(&s
->success_status
);
397 /* This will leak a process, but at least no memory or any of
399 service_unwatch_main_pid(s
);
400 service_unwatch_control_pid(s
);
401 service_unwatch_pid_file(s
);
404 unit_unwatch_bus_name(u
, s
->bus_name
);
405 s
->bus_name
= mfree(s
->bus_name
);
408 s
->bus_name_owner
= mfree(s
->bus_name_owner
);
410 s
->usb_function_descriptors
= mfree(s
->usb_function_descriptors
);
411 s
->usb_function_strings
= mfree(s
->usb_function_strings
);
413 service_close_socket_fd(s
);
415 unit_ref_unset(&s
->accept_socket
);
417 service_stop_watchdog(s
);
419 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
420 s
->exec_fd_event_source
= sd_event_source_disable_unref(s
->exec_fd_event_source
);
422 s
->bus_name_pid_lookup_slot
= sd_bus_slot_unref(s
->bus_name_pid_lookup_slot
);
424 service_release_resources(u
);
427 static int on_fd_store_io(sd_event_source
*e
, int fd
, uint32_t revents
, void *userdata
) {
428 ServiceFDStore
*fs
= ASSERT_PTR(userdata
);
432 /* If we get either EPOLLHUP or EPOLLERR, it's time to remove this entry from the fd store */
433 log_unit_debug(UNIT(fs
->service
),
434 "Received %s on stored fd %d (%s), closing.",
435 revents
& EPOLLERR
? "EPOLLERR" : "EPOLLHUP",
436 fs
->fd
, strna(fs
->fdname
));
437 service_fd_store_unlink(fs
);
441 static int service_add_fd_store(Service
*s
, int fd
, const char *name
, bool do_poll
) {
445 /* fd is always consumed if we return >= 0 */
450 if (s
->n_fd_store
>= s
->n_fd_store_max
)
451 return -EXFULL
; /* Our store is full.
452 * Use this errno rather than E[NM]FILE to distinguish from
453 * the case where systemd itself hits the file limit. */
455 LIST_FOREACH(fd_store
, i
, s
->fd_store
) {
456 r
= same_fd(i
->fd
, fd
);
461 return 0; /* fd already included */
465 fs
= new(ServiceFDStore
, 1);
469 *fs
= (ServiceFDStore
) {
473 .fdname
= strdup(name
?: "stored"),
482 r
= sd_event_add_io(UNIT(s
)->manager
->event
, &fs
->event_source
, fd
, 0, on_fd_store_io
, fs
);
483 if (r
< 0 && r
!= -EPERM
) { /* EPERM indicates fds that aren't pollable, which is OK */
488 (void) sd_event_source_set_description(fs
->event_source
, "service-fd-store");
491 LIST_PREPEND(fd_store
, s
->fd_store
, fs
);
494 return 1; /* fd newly stored */
497 static int service_add_fd_store_set(Service
*s
, FDSet
*fds
, const char *name
, bool do_poll
) {
502 while (fdset_size(fds
) > 0) {
503 _cleanup_close_
int fd
= -EBADF
;
505 fd
= fdset_steal_first(fds
);
509 r
= service_add_fd_store(s
, fd
, name
, do_poll
);
511 return log_unit_warning_errno(UNIT(s
), r
,
512 "Cannot store more fds than FileDescriptorStoreMax=%u, closing remaining.",
515 return log_unit_error_errno(UNIT(s
), r
, "Failed to add fd to store: %m");
517 log_unit_debug(UNIT(s
), "Added fd %i (%s) to fd store.", fd
, strna(name
));
524 static void service_remove_fd_store(Service
*s
, const char *name
) {
528 LIST_FOREACH(fd_store
, fs
, s
->fd_store
) {
529 if (!streq(fs
->fdname
, name
))
532 log_unit_debug(UNIT(s
), "Got explicit request to remove fd %i (%s), closing.", fs
->fd
, name
);
533 service_fd_store_unlink(fs
);
537 static usec_t
service_running_timeout(Service
*s
) {
542 if (s
->runtime_rand_extra_usec
!= 0) {
543 delta
= random_u64_range(s
->runtime_rand_extra_usec
);
544 log_unit_debug(UNIT(s
), "Adding delta of %s sec to timeout", FORMAT_TIMESPAN(delta
, USEC_PER_SEC
));
547 return usec_add(usec_add(UNIT(s
)->active_enter_timestamp
.monotonic
,
548 s
->runtime_max_usec
),
552 static int service_arm_timer(Service
*s
, bool relative
, usec_t usec
) {
557 if (s
->timer_event_source
) {
558 r
= (relative
? sd_event_source_set_time_relative
: sd_event_source_set_time
)(s
->timer_event_source
, usec
);
562 return sd_event_source_set_enabled(s
->timer_event_source
, SD_EVENT_ONESHOT
);
565 if (usec
== USEC_INFINITY
)
568 r
= (relative
? sd_event_add_time_relative
: sd_event_add_time
)(
569 UNIT(s
)->manager
->event
,
570 &s
->timer_event_source
,
573 service_dispatch_timer
, s
);
577 (void) sd_event_source_set_description(s
->timer_event_source
, "service-timer");
582 static int service_verify(Service
*s
) {
584 assert(UNIT(s
)->load_state
== UNIT_LOADED
);
586 for (ServiceExecCommand c
= 0; c
< _SERVICE_EXEC_COMMAND_MAX
; c
++)
587 LIST_FOREACH(command
, command
, s
->exec_command
[c
]) {
588 if (!path_is_absolute(command
->path
) && !filename_is_valid(command
->path
))
589 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
),
590 "Service %s= binary path \"%s\" is neither a valid executable name nor an absolute path. Refusing.",
592 service_exec_command_to_string(c
));
593 if (strv_isempty(command
->argv
))
594 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
),
595 "Service has an empty argv in %s=. Refusing.",
596 service_exec_command_to_string(c
));
599 if (!s
->exec_command
[SERVICE_EXEC_START
] && !s
->exec_command
[SERVICE_EXEC_STOP
] &&
600 UNIT(s
)->success_action
== EMERGENCY_ACTION_NONE
)
601 /* FailureAction= only makes sense if one of the start or stop commands is specified.
602 * SuccessAction= will be executed unconditionally if no commands are specified. Hence,
603 * either a command or SuccessAction= are required. */
605 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Service has no ExecStart=, ExecStop=, or SuccessAction=. Refusing.");
607 if (s
->type
!= SERVICE_ONESHOT
&& !s
->exec_command
[SERVICE_EXEC_START
])
608 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Service has no ExecStart= setting, which is only allowed for Type=oneshot services. Refusing.");
610 if (!s
->remain_after_exit
&& !s
->exec_command
[SERVICE_EXEC_START
] && UNIT(s
)->success_action
== EMERGENCY_ACTION_NONE
)
611 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.");
613 if (s
->type
!= SERVICE_ONESHOT
&& s
->exec_command
[SERVICE_EXEC_START
]->command_next
)
614 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.");
616 if (s
->type
== SERVICE_ONESHOT
&&
617 !IN_SET(s
->restart
, SERVICE_RESTART_NO
, SERVICE_RESTART_ON_FAILURE
, SERVICE_RESTART_ON_ABNORMAL
, SERVICE_RESTART_ON_WATCHDOG
, SERVICE_RESTART_ON_ABORT
))
618 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.");
620 if (s
->type
== SERVICE_ONESHOT
&& !exit_status_set_is_empty(&s
->restart_force_status
))
621 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Service has RestartForceExitStatus= set, which isn't allowed for Type=oneshot services. Refusing.");
623 if (s
->type
== SERVICE_ONESHOT
&& s
->exit_type
== SERVICE_EXIT_CGROUP
)
624 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Service has ExitType=cgroup set, which isn't allowed for Type=oneshot services. Refusing.");
626 if (s
->type
== SERVICE_DBUS
&& !s
->bus_name
)
627 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.");
629 if (s
->exec_context
.pam_name
&& !IN_SET(s
->kill_context
.kill_mode
, KILL_CONTROL_GROUP
, KILL_MIXED
))
630 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.");
632 if (s
->usb_function_descriptors
&& !s
->usb_function_strings
)
633 log_unit_warning(UNIT(s
), "Service has USBFunctionDescriptors= setting, but no USBFunctionStrings=. Ignoring.");
635 if (!s
->usb_function_descriptors
&& s
->usb_function_strings
)
636 log_unit_warning(UNIT(s
), "Service has USBFunctionStrings= setting, but no USBFunctionDescriptors=. Ignoring.");
638 if (s
->runtime_max_usec
!= USEC_INFINITY
&& s
->type
== SERVICE_ONESHOT
)
639 log_unit_warning(UNIT(s
), "RuntimeMaxSec= has no effect in combination with Type=oneshot. Ignoring.");
641 if (s
->runtime_max_usec
== USEC_INFINITY
&& s
->runtime_rand_extra_usec
!= 0)
642 log_unit_warning(UNIT(s
), "Service has RuntimeRandomizedExtraSec= setting, but no RuntimeMaxSec=. Ignoring.");
644 if (s
->exit_type
== SERVICE_EXIT_CGROUP
&& cg_unified() < CGROUP_UNIFIED_SYSTEMD
)
645 log_unit_warning(UNIT(s
), "Service has ExitType=cgroup set, but we are running with legacy cgroups v1, which might not work correctly. Continuing.");
650 static int service_add_default_dependencies(Service
*s
) {
655 if (!UNIT(s
)->default_dependencies
)
658 /* Add a number of automatic dependencies useful for the
659 * majority of services. */
661 if (MANAGER_IS_SYSTEM(UNIT(s
)->manager
)) {
662 /* First, pull in the really early boot stuff, and
663 * require it, so that we fail if we can't acquire
666 r
= unit_add_two_dependencies_by_name(UNIT(s
), UNIT_AFTER
, UNIT_REQUIRES
, SPECIAL_SYSINIT_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
671 /* In the --user instance there's no sysinit.target,
672 * in that case require basic.target instead. */
674 r
= unit_add_dependency_by_name(UNIT(s
), UNIT_REQUIRES
, SPECIAL_BASIC_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
679 /* Second, if the rest of the base system is in the same
680 * transaction, order us after it, but do not pull it in or
681 * even require it. */
682 r
= unit_add_dependency_by_name(UNIT(s
), UNIT_AFTER
, SPECIAL_BASIC_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
686 /* Third, add us in for normal shutdown. */
687 return unit_add_two_dependencies_by_name(UNIT(s
), UNIT_BEFORE
, UNIT_CONFLICTS
, SPECIAL_SHUTDOWN_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
690 static void service_fix_stdio(Service
*s
) {
693 /* Note that EXEC_INPUT_NULL and EXEC_OUTPUT_INHERIT play a special role here: they are both the
694 * default value that is subject to automatic overriding triggered by other settings and an explicit
695 * choice the user can make. We don't distinguish between these cases currently. */
697 if (s
->exec_context
.std_input
== EXEC_INPUT_NULL
&&
698 s
->exec_context
.stdin_data_size
> 0)
699 s
->exec_context
.std_input
= EXEC_INPUT_DATA
;
701 if (IN_SET(s
->exec_context
.std_input
,
703 EXEC_INPUT_TTY_FORCE
,
706 EXEC_INPUT_NAMED_FD
))
709 /* We assume these listed inputs refer to bidirectional streams, and hence duplicating them from
710 * stdin to stdout/stderr makes sense and hence leaving EXEC_OUTPUT_INHERIT in place makes sense,
711 * too. Outputs such as regular files or sealed data memfds otoh don't really make sense to be
712 * duplicated for both input and output at the same time (since they then would cause a feedback
713 * loop), hence override EXEC_OUTPUT_INHERIT with the default stderr/stdout setting. */
715 if (s
->exec_context
.std_error
== EXEC_OUTPUT_INHERIT
&&
716 s
->exec_context
.std_output
== EXEC_OUTPUT_INHERIT
)
717 s
->exec_context
.std_error
= UNIT(s
)->manager
->default_std_error
;
719 if (s
->exec_context
.std_output
== EXEC_OUTPUT_INHERIT
)
720 s
->exec_context
.std_output
= UNIT(s
)->manager
->default_std_output
;
723 static int service_setup_bus_name(Service
*s
) {
728 /* If s->bus_name is not set, then the unit will be refused by service_verify() later. */
732 if (s
->type
== SERVICE_DBUS
) {
733 r
= unit_add_dependency_by_name(UNIT(s
), UNIT_REQUIRES
, SPECIAL_DBUS_SOCKET
, true, UNIT_DEPENDENCY_FILE
);
735 return log_unit_error_errno(UNIT(s
), r
, "Failed to add dependency on " SPECIAL_DBUS_SOCKET
": %m");
737 /* We always want to be ordered against dbus.socket if both are in the transaction. */
738 r
= unit_add_dependency_by_name(UNIT(s
), UNIT_AFTER
, SPECIAL_DBUS_SOCKET
, true, UNIT_DEPENDENCY_FILE
);
740 return log_unit_error_errno(UNIT(s
), r
, "Failed to add dependency on " SPECIAL_DBUS_SOCKET
": %m");
743 r
= unit_watch_bus_name(UNIT(s
), s
->bus_name
);
745 return log_unit_error_errno(UNIT(s
), r
, "Two services allocated for the same bus name %s, refusing operation.", s
->bus_name
);
747 return log_unit_error_errno(UNIT(s
), r
, "Cannot watch bus name %s: %m", s
->bus_name
);
752 static int service_add_extras(Service
*s
) {
757 if (s
->type
== _SERVICE_TYPE_INVALID
) {
758 /* Figure out a type automatically */
760 s
->type
= SERVICE_DBUS
;
761 else if (s
->exec_command
[SERVICE_EXEC_START
])
762 s
->type
= SERVICE_SIMPLE
;
764 s
->type
= SERVICE_ONESHOT
;
767 /* Oneshot services have disabled start timeout by default */
768 if (s
->type
== SERVICE_ONESHOT
&& !s
->start_timeout_defined
)
769 s
->timeout_start_usec
= USEC_INFINITY
;
771 service_fix_stdio(s
);
773 r
= unit_patch_contexts(UNIT(s
));
777 r
= unit_add_exec_dependencies(UNIT(s
), &s
->exec_context
);
781 r
= unit_set_default_slice(UNIT(s
));
785 /* If the service needs the notify socket, let's enable it automatically. */
786 if (s
->notify_access
== NOTIFY_NONE
&&
787 (IN_SET(s
->type
, SERVICE_NOTIFY
, SERVICE_NOTIFY_RELOAD
) || s
->watchdog_usec
> 0 || s
->n_fd_store_max
> 0))
788 s
->notify_access
= NOTIFY_MAIN
;
790 /* If no OOM policy was explicitly set, then default to the configure default OOM policy. Except when
791 * delegation is on, in that case it we assume the payload knows better what to do and can process
792 * things in a more focused way. */
793 if (s
->oom_policy
< 0)
794 s
->oom_policy
= s
->cgroup_context
.delegate
? OOM_CONTINUE
: UNIT(s
)->manager
->default_oom_policy
;
796 /* Let the kernel do the killing if that's requested. */
797 s
->cgroup_context
.memory_oom_group
= s
->oom_policy
== OOM_KILL
;
799 r
= service_add_default_dependencies(s
);
803 r
= service_setup_bus_name(s
);
810 static int service_load(Unit
*u
) {
811 Service
*s
= SERVICE(u
);
814 r
= unit_load_fragment_and_dropin(u
, true);
818 if (u
->load_state
!= UNIT_LOADED
)
821 /* This is a new unit? Then let's add in some extras */
822 r
= service_add_extras(s
);
826 return service_verify(s
);
829 static void service_dump(Unit
*u
, FILE *f
, const char *prefix
) {
830 ServiceExecCommand c
;
831 Service
*s
= SERVICE(u
);
836 prefix
= strempty(prefix
);
837 prefix2
= strjoina(prefix
, "\t");
840 "%sService State: %s\n"
842 "%sReload Result: %s\n"
843 "%sClean Result: %s\n"
844 "%sPermissionsStartOnly: %s\n"
845 "%sRootDirectoryStartOnly: %s\n"
846 "%sRemainAfterExit: %s\n"
847 "%sGuessMainPID: %s\n"
850 "%sNotifyAccess: %s\n"
851 "%sNotifyState: %s\n"
853 "%sReloadSignal: %s\n",
854 prefix
, service_state_to_string(s
->state
),
855 prefix
, service_result_to_string(s
->result
),
856 prefix
, service_result_to_string(s
->reload_result
),
857 prefix
, service_result_to_string(s
->clean_result
),
858 prefix
, yes_no(s
->permissions_start_only
),
859 prefix
, yes_no(s
->root_directory_start_only
),
860 prefix
, yes_no(s
->remain_after_exit
),
861 prefix
, yes_no(s
->guess_main_pid
),
862 prefix
, service_type_to_string(s
->type
),
863 prefix
, service_restart_to_string(s
->restart
),
864 prefix
, notify_access_to_string(service_get_notify_access(s
)),
865 prefix
, notify_state_to_string(s
->notify_state
),
866 prefix
, oom_policy_to_string(s
->oom_policy
),
867 prefix
, signal_to_string(s
->reload_signal
));
869 if (s
->control_pid
> 0)
871 "%sControl PID: "PID_FMT
"\n",
872 prefix
, s
->control_pid
);
876 "%sMain PID: "PID_FMT
"\n"
877 "%sMain PID Known: %s\n"
878 "%sMain PID Alien: %s\n",
880 prefix
, yes_no(s
->main_pid_known
),
881 prefix
, yes_no(s
->main_pid_alien
));
886 prefix
, s
->pid_file
);
891 "%sBus Name Good: %s\n",
893 prefix
, yes_no(s
->bus_name_good
));
895 if (UNIT_ISSET(s
->accept_socket
))
897 "%sAccept Socket: %s\n",
898 prefix
, UNIT_DEREF(s
->accept_socket
)->id
);
902 "%sTimeoutStartSec: %s\n"
903 "%sTimeoutStopSec: %s\n"
904 "%sTimeoutStartFailureMode: %s\n"
905 "%sTimeoutStopFailureMode: %s\n",
906 prefix
, FORMAT_TIMESPAN(s
->restart_usec
, USEC_PER_SEC
),
907 prefix
, FORMAT_TIMESPAN(s
->timeout_start_usec
, USEC_PER_SEC
),
908 prefix
, FORMAT_TIMESPAN(s
->timeout_stop_usec
, USEC_PER_SEC
),
909 prefix
, service_timeout_failure_mode_to_string(s
->timeout_start_failure_mode
),
910 prefix
, service_timeout_failure_mode_to_string(s
->timeout_stop_failure_mode
));
912 if (s
->timeout_abort_set
)
914 "%sTimeoutAbortSec: %s\n",
915 prefix
, FORMAT_TIMESPAN(s
->timeout_abort_usec
, USEC_PER_SEC
));
918 "%sRuntimeMaxSec: %s\n"
919 "%sRuntimeRandomizedExtraSec: %s\n"
920 "%sWatchdogSec: %s\n",
921 prefix
, FORMAT_TIMESPAN(s
->runtime_max_usec
, USEC_PER_SEC
),
922 prefix
, FORMAT_TIMESPAN(s
->runtime_rand_extra_usec
, USEC_PER_SEC
),
923 prefix
, FORMAT_TIMESPAN(s
->watchdog_usec
, USEC_PER_SEC
));
925 kill_context_dump(&s
->kill_context
, f
, prefix
);
926 exec_context_dump(&s
->exec_context
, f
, prefix
);
928 for (c
= 0; c
< _SERVICE_EXEC_COMMAND_MAX
; c
++) {
930 if (!s
->exec_command
[c
])
933 fprintf(f
, "%s-> %s:\n",
934 prefix
, service_exec_command_to_string(c
));
936 exec_command_dump_list(s
->exec_command
[c
], f
, prefix2
);
940 fprintf(f
, "%sStatus Text: %s\n",
941 prefix
, s
->status_text
);
943 if (s
->n_fd_store_max
> 0)
945 "%sFile Descriptor Store Max: %u\n"
946 "%sFile Descriptor Store Current: %zu\n",
947 prefix
, s
->n_fd_store_max
,
948 prefix
, s
->n_fd_store
);
951 LIST_FOREACH(open_files
, of
, s
->open_files
) {
952 _cleanup_free_
char *ofs
= NULL
;
955 r
= open_file_to_string(of
, &ofs
);
958 "Failed to convert OpenFile= setting to string, ignoring: %m");
962 fprintf(f
, "%sOpen File: %s\n", prefix
, ofs
);
965 cgroup_context_dump(UNIT(s
), f
, prefix
);
968 static int service_is_suitable_main_pid(Service
*s
, pid_t pid
, int prio
) {
972 assert(pid_is_valid(pid
));
974 /* Checks whether the specified PID is suitable as main PID for this service. returns negative if not, 0 if the
975 * PID is questionnable but should be accepted if the source of configuration is trusted. > 0 if the PID is
978 if (pid
== getpid_cached() || pid
== 1)
979 return log_unit_full_errno(UNIT(s
), prio
, SYNTHETIC_ERRNO(EPERM
), "New main PID "PID_FMT
" is the manager, refusing.", pid
);
981 if (pid
== s
->control_pid
)
982 return log_unit_full_errno(UNIT(s
), prio
, SYNTHETIC_ERRNO(EPERM
), "New main PID "PID_FMT
" is the control process, refusing.", pid
);
984 if (!pid_is_alive(pid
))
985 return log_unit_full_errno(UNIT(s
), prio
, SYNTHETIC_ERRNO(ESRCH
), "New main PID "PID_FMT
" does not exist or is a zombie.", pid
);
987 owner
= manager_get_unit_by_pid(UNIT(s
)->manager
, pid
);
988 if (owner
== UNIT(s
)) {
989 log_unit_debug(UNIT(s
), "New main PID "PID_FMT
" belongs to service, we are happy.", pid
);
990 return 1; /* Yay, it's definitely a good PID */
993 return 0; /* Hmm it's a suspicious PID, let's accept it if configuration source is trusted */
996 static int service_load_pid_file(Service
*s
, bool may_warn
) {
997 bool questionable_pid_file
= false;
998 _cleanup_free_
char *k
= NULL
;
999 _cleanup_close_
int fd
= -EBADF
;
1008 prio
= may_warn
? LOG_INFO
: LOG_DEBUG
;
1010 r
= chase(s
->pid_file
, NULL
, CHASE_SAFE
, NULL
, &fd
);
1011 if (r
== -ENOLINK
) {
1012 log_unit_debug_errno(UNIT(s
), r
,
1013 "Potentially unsafe symlink chain, will now retry with relaxed checks: %s", s
->pid_file
);
1015 questionable_pid_file
= true;
1017 r
= chase(s
->pid_file
, NULL
, 0, NULL
, &fd
);
1020 return log_unit_full_errno(UNIT(s
), prio
, fd
,
1021 "Can't open PID file %s (yet?) after %s: %m", s
->pid_file
, service_state_to_string(s
->state
));
1023 /* Let's read the PID file now that we chased it down. But we need to convert the O_PATH fd
1024 * chase() returned us into a proper fd first. */
1025 r
= read_one_line_file(FORMAT_PROC_FD_PATH(fd
), &k
);
1027 return log_unit_error_errno(UNIT(s
), r
,
1028 "Can't convert PID files %s O_PATH file descriptor to proper file descriptor: %m",
1031 r
= parse_pid(k
, &pid
);
1033 return log_unit_full_errno(UNIT(s
), prio
, r
, "Failed to parse PID from file %s: %m", s
->pid_file
);
1035 if (s
->main_pid_known
&& pid
== s
->main_pid
)
1038 r
= service_is_suitable_main_pid(s
, pid
, prio
);
1044 if (questionable_pid_file
)
1045 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(EPERM
),
1046 "Refusing to accept PID outside of service control group, acquired through unsafe symlink chain: %s", s
->pid_file
);
1048 /* Hmm, it's not clear if the new main PID is safe. Let's allow this if the PID file is owned by root */
1050 if (fstat(fd
, &st
) < 0)
1051 return log_unit_error_errno(UNIT(s
), errno
, "Failed to fstat() PID file O_PATH fd: %m");
1054 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(EPERM
),
1055 "New main PID "PID_FMT
" does not belong to service, and PID file is not owned by root. Refusing.", pid
);
1057 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
);
1060 if (s
->main_pid_known
) {
1061 log_unit_debug(UNIT(s
), "Main PID changing: "PID_FMT
" -> "PID_FMT
, s
->main_pid
, pid
);
1063 service_unwatch_main_pid(s
);
1064 s
->main_pid_known
= false;
1066 log_unit_debug(UNIT(s
), "Main PID loaded: "PID_FMT
, pid
);
1068 r
= service_set_main_pid(s
, pid
);
1072 r
= unit_watch_pid(UNIT(s
), pid
, false);
1073 if (r
< 0) /* FIXME: we need to do something here */
1074 return log_unit_warning_errno(UNIT(s
), r
, "Failed to watch PID "PID_FMT
" for service: %m", pid
);
1079 static void service_search_main_pid(Service
*s
) {
1085 /* If we know it anyway, don't ever fall back to unreliable
1087 if (s
->main_pid_known
)
1090 if (!s
->guess_main_pid
)
1093 assert(s
->main_pid
<= 0);
1095 if (unit_search_main_pid(UNIT(s
), &pid
) < 0)
1098 log_unit_debug(UNIT(s
), "Main PID guessed: "PID_FMT
, pid
);
1099 if (service_set_main_pid(s
, pid
) < 0)
1102 r
= unit_watch_pid(UNIT(s
), pid
, false);
1104 /* FIXME: we need to do something here */
1105 log_unit_warning_errno(UNIT(s
), r
, "Failed to watch PID "PID_FMT
" from: %m", pid
);
1108 static void service_set_state(Service
*s
, ServiceState state
) {
1109 ServiceState old_state
;
1110 const UnitActiveState
*table
;
1114 if (s
->state
!= state
)
1115 bus_unit_send_pending_change_signal(UNIT(s
), false);
1117 table
= s
->type
== SERVICE_IDLE
? state_translation_table_idle
: state_translation_table
;
1119 old_state
= s
->state
;
1122 service_unwatch_pid_file(s
);
1125 SERVICE_CONDITION
, SERVICE_START_PRE
, SERVICE_START
, SERVICE_START_POST
,
1127 SERVICE_RELOAD
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
,
1128 SERVICE_STOP
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
, SERVICE_STOP_POST
,
1129 SERVICE_FINAL_WATCHDOG
, SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
,
1130 SERVICE_AUTO_RESTART
,
1132 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
1135 SERVICE_START
, SERVICE_START_POST
,
1137 SERVICE_RELOAD
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
,
1138 SERVICE_STOP
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
, SERVICE_STOP_POST
,
1139 SERVICE_FINAL_WATCHDOG
, SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
)) {
1140 service_unwatch_main_pid(s
);
1141 s
->main_command
= NULL
;
1145 SERVICE_CONDITION
, SERVICE_START_PRE
, SERVICE_START
, SERVICE_START_POST
,
1146 SERVICE_RELOAD
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
,
1147 SERVICE_STOP
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
, SERVICE_STOP_POST
,
1148 SERVICE_FINAL_WATCHDOG
, SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
,
1149 SERVICE_CLEANING
)) {
1150 service_unwatch_control_pid(s
);
1151 s
->control_command
= NULL
;
1152 s
->control_command_id
= _SERVICE_EXEC_COMMAND_INVALID
;
1155 if (IN_SET(state
, SERVICE_DEAD
, SERVICE_FAILED
, SERVICE_AUTO_RESTART
)) {
1156 unit_unwatch_all_pids(UNIT(s
));
1157 unit_dequeue_rewatch_pids(UNIT(s
));
1161 SERVICE_CONDITION
, SERVICE_START_PRE
, SERVICE_START
, SERVICE_START_POST
,
1163 SERVICE_RELOAD
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
,
1164 SERVICE_STOP
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
, SERVICE_STOP_POST
,
1165 SERVICE_FINAL_WATCHDOG
, SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
) &&
1166 !(state
== SERVICE_DEAD
&& UNIT(s
)->job
))
1167 service_close_socket_fd(s
);
1169 if (state
!= SERVICE_START
)
1170 s
->exec_fd_event_source
= sd_event_source_disable_unref(s
->exec_fd_event_source
);
1172 if (!IN_SET(state
, SERVICE_START_POST
, SERVICE_RUNNING
, SERVICE_RELOAD
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
))
1173 service_stop_watchdog(s
);
1175 /* For the inactive states unit_notify() will trim the cgroup,
1176 * but for exit we have to do that ourselves... */
1177 if (state
== SERVICE_EXITED
&& !MANAGER_IS_RELOADING(UNIT(s
)->manager
))
1178 unit_prune_cgroup(UNIT(s
));
1180 if (old_state
!= state
)
1181 log_unit_debug(UNIT(s
), "Changed %s -> %s", service_state_to_string(old_state
), service_state_to_string(state
));
1183 unit_notify(UNIT(s
), table
[old_state
], table
[state
],
1184 (s
->reload_result
== SERVICE_SUCCESS
? 0 : UNIT_NOTIFY_RELOAD_FAILURE
) |
1185 (s
->will_auto_restart
? UNIT_NOTIFY_WILL_AUTO_RESTART
: 0));
1188 static usec_t
service_coldplug_timeout(Service
*s
) {
1191 switch (s
->deserialized_state
) {
1193 case SERVICE_CONDITION
:
1194 case SERVICE_START_PRE
:
1196 case SERVICE_START_POST
:
1197 case SERVICE_RELOAD
:
1198 case SERVICE_RELOAD_SIGNAL
:
1199 case SERVICE_RELOAD_NOTIFY
:
1200 return usec_add(UNIT(s
)->state_change_timestamp
.monotonic
, s
->timeout_start_usec
);
1202 case SERVICE_RUNNING
:
1203 return service_running_timeout(s
);
1206 case SERVICE_STOP_SIGTERM
:
1207 case SERVICE_STOP_SIGKILL
:
1208 case SERVICE_STOP_POST
:
1209 case SERVICE_FINAL_SIGTERM
:
1210 case SERVICE_FINAL_SIGKILL
:
1211 return usec_add(UNIT(s
)->state_change_timestamp
.monotonic
, s
->timeout_stop_usec
);
1213 case SERVICE_STOP_WATCHDOG
:
1214 case SERVICE_FINAL_WATCHDOG
:
1215 return usec_add(UNIT(s
)->state_change_timestamp
.monotonic
, service_timeout_abort_usec(s
));
1217 case SERVICE_AUTO_RESTART
:
1218 return usec_add(UNIT(s
)->inactive_enter_timestamp
.monotonic
, s
->restart_usec
);
1220 case SERVICE_CLEANING
:
1221 return usec_add(UNIT(s
)->state_change_timestamp
.monotonic
, s
->exec_context
.timeout_clean_usec
);
1224 return USEC_INFINITY
;
1228 static int service_coldplug(Unit
*u
) {
1229 Service
*s
= SERVICE(u
);
1233 assert(s
->state
== SERVICE_DEAD
);
1235 if (s
->deserialized_state
== s
->state
)
1238 r
= service_arm_timer(s
, /* relative= */ false, service_coldplug_timeout(s
));
1242 if (s
->main_pid
> 0 &&
1243 pid_is_unwaited(s
->main_pid
) &&
1244 (IN_SET(s
->deserialized_state
,
1245 SERVICE_START
, SERVICE_START_POST
,
1247 SERVICE_RELOAD
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
,
1248 SERVICE_STOP
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
, SERVICE_STOP_POST
,
1249 SERVICE_FINAL_WATCHDOG
, SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
))) {
1250 r
= unit_watch_pid(UNIT(s
), s
->main_pid
, false);
1255 if (s
->control_pid
> 0 &&
1256 pid_is_unwaited(s
->control_pid
) &&
1257 IN_SET(s
->deserialized_state
,
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 r
= unit_watch_pid(UNIT(s
), s
->control_pid
, false);
1268 if (!IN_SET(s
->deserialized_state
, SERVICE_DEAD
, SERVICE_FAILED
, SERVICE_AUTO_RESTART
, SERVICE_CLEANING
)) {
1269 (void) unit_enqueue_rewatch_pids(u
);
1270 (void) unit_setup_dynamic_creds(u
);
1271 (void) unit_setup_exec_runtime(u
);
1274 if (IN_SET(s
->deserialized_state
, SERVICE_START_POST
, SERVICE_RUNNING
, SERVICE_RELOAD
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
))
1275 service_start_watchdog(s
);
1277 if (UNIT_ISSET(s
->accept_socket
)) {
1278 Socket
* socket
= SOCKET(UNIT_DEREF(s
->accept_socket
));
1280 if (socket
->max_connections_per_source
> 0) {
1283 /* Make a best-effort attempt at bumping the connection count */
1284 if (socket_acquire_peer(socket
, s
->socket_fd
, &peer
) > 0) {
1285 socket_peer_unref(s
->socket_peer
);
1286 s
->socket_peer
= peer
;
1291 service_set_state(s
, s
->deserialized_state
);
1295 static int service_collect_fds(
1299 size_t *n_socket_fds
,
1300 size_t *n_storage_fds
) {
1302 _cleanup_strv_free_
char **rfd_names
= NULL
;
1303 _cleanup_free_
int *rfds
= NULL
;
1304 size_t rn_socket_fds
= 0, rn_storage_fds
= 0;
1310 assert(n_socket_fds
);
1311 assert(n_storage_fds
);
1313 if (s
->socket_fd
>= 0) {
1315 /* Pass the per-connection socket */
1320 rfds
[0] = s
->socket_fd
;
1322 rfd_names
= strv_new("connection");
1330 /* Pass all our configured sockets for singleton services */
1332 UNIT_FOREACH_DEPENDENCY(u
, UNIT(s
), UNIT_ATOM_TRIGGERED_BY
) {
1333 _cleanup_free_
int *cfds
= NULL
;
1337 if (u
->type
!= UNIT_SOCKET
)
1342 cn_fds
= socket_collect_fds(sock
, &cfds
);
1350 rfds
= TAKE_PTR(cfds
);
1351 rn_socket_fds
= cn_fds
;
1355 t
= reallocarray(rfds
, rn_socket_fds
+ cn_fds
, sizeof(int));
1359 memcpy(t
+ rn_socket_fds
, cfds
, cn_fds
* sizeof(int));
1362 rn_socket_fds
+= cn_fds
;
1365 r
= strv_extend_n(&rfd_names
, socket_fdname(sock
), cn_fds
);
1371 if (s
->n_fd_store
> 0) {
1376 t
= reallocarray(rfds
, rn_socket_fds
+ s
->n_fd_store
, sizeof(int));
1382 nl
= reallocarray(rfd_names
, rn_socket_fds
+ s
->n_fd_store
+ 1, sizeof(char *));
1387 n_fds
= rn_socket_fds
;
1389 LIST_FOREACH(fd_store
, fs
, s
->fd_store
) {
1390 rfds
[n_fds
] = fs
->fd
;
1391 rfd_names
[n_fds
] = strdup(strempty(fs
->fdname
));
1392 if (!rfd_names
[n_fds
])
1399 rfd_names
[n_fds
] = NULL
;
1402 *fds
= TAKE_PTR(rfds
);
1403 *fd_names
= TAKE_PTR(rfd_names
);
1404 *n_socket_fds
= rn_socket_fds
;
1405 *n_storage_fds
= rn_storage_fds
;
1410 static int service_allocate_exec_fd_event_source(
1413 sd_event_source
**ret_event_source
) {
1415 _cleanup_(sd_event_source_unrefp
) sd_event_source
*source
= NULL
;
1420 assert(ret_event_source
);
1422 r
= sd_event_add_io(UNIT(s
)->manager
->event
, &source
, fd
, 0, service_dispatch_exec_io
, s
);
1424 return log_unit_error_errno(UNIT(s
), r
, "Failed to allocate exec_fd event source: %m");
1426 /* This is a bit lower priority than SIGCHLD, as that carries a lot more interesting failure information */
1428 r
= sd_event_source_set_priority(source
, SD_EVENT_PRIORITY_NORMAL
-3);
1430 return log_unit_error_errno(UNIT(s
), r
, "Failed to adjust priority of exec_fd event source: %m");
1432 (void) sd_event_source_set_description(source
, "service exec_fd");
1434 r
= sd_event_source_set_io_fd_own(source
, true);
1436 return log_unit_error_errno(UNIT(s
), r
, "Failed to pass ownership of fd to event source: %m");
1438 *ret_event_source
= TAKE_PTR(source
);
1442 static int service_allocate_exec_fd(
1444 sd_event_source
**ret_event_source
,
1447 _cleanup_close_pair_
int p
[] = PIPE_EBADF
;
1451 assert(ret_event_source
);
1452 assert(ret_exec_fd
);
1454 if (pipe2(p
, O_CLOEXEC
|O_NONBLOCK
) < 0)
1455 return log_unit_error_errno(UNIT(s
), errno
, "Failed to allocate exec_fd pipe: %m");
1457 r
= service_allocate_exec_fd_event_source(s
, p
[0], ret_event_source
);
1462 *ret_exec_fd
= TAKE_FD(p
[1]);
1467 static bool service_exec_needs_notify_socket(Service
*s
, ExecFlags flags
) {
1470 /* Notifications are accepted depending on the process and
1471 * the access setting of the service:
1472 * process: \ access: NONE MAIN EXEC ALL
1473 * main no yes yes yes
1474 * control no no yes yes
1475 * other (forked) no no no yes */
1477 if (flags
& EXEC_IS_CONTROL
)
1478 /* A control process */
1479 return IN_SET(service_get_notify_access(s
), NOTIFY_EXEC
, NOTIFY_ALL
);
1481 /* We only spawn main processes and control processes, so any
1482 * process that is not a control process is a main process */
1483 return service_get_notify_access(s
) != NOTIFY_NONE
;
1486 static Service
*service_get_triggering_service(Service
*s
) {
1487 Unit
*candidate
= NULL
, *other
;
1491 /* Return the service which triggered service 's', this means dependency
1492 * types which include the UNIT_ATOM_ON_{FAILURE,SUCCESS}_OF atoms.
1494 * N.B. if there are multiple services which could trigger 's' via OnFailure=
1495 * or OnSuccess= then we return NULL. This is since we don't know from which
1496 * one to propagate the exit status. */
1498 UNIT_FOREACH_DEPENDENCY(other
, UNIT(s
), UNIT_ATOM_ON_FAILURE_OF
) {
1504 UNIT_FOREACH_DEPENDENCY(other
, UNIT(s
), UNIT_ATOM_ON_SUCCESS_OF
) {
1510 return SERVICE(candidate
);
1513 log_unit_warning(UNIT(s
), "multiple trigger source candidates for exit status propagation (%s, %s), skipping.",
1514 candidate
->id
, other
->id
);
1518 static int service_spawn_internal(
1526 _cleanup_(exec_params_clear
) ExecParameters exec_params
= {
1529 .stdout_fd
= -EBADF
,
1530 .stderr_fd
= -EBADF
,
1533 _cleanup_(sd_event_source_unrefp
) sd_event_source
*exec_fd_source
= NULL
;
1534 _cleanup_strv_free_
char **final_env
= NULL
, **our_env
= NULL
;
1544 log_unit_debug(UNIT(s
), "Will spawn child (%s): %s", caller
, c
->path
);
1546 r
= unit_prepare_exec(UNIT(s
)); /* This realizes the cgroup, among other things */
1550 assert(!s
->exec_fd_event_source
);
1552 if (flags
& EXEC_IS_CONTROL
) {
1553 /* If this is a control process, mask the permissions/chroot application if this is requested. */
1554 if (s
->permissions_start_only
)
1555 exec_params
.flags
&= ~EXEC_APPLY_SANDBOXING
;
1556 if (s
->root_directory_start_only
)
1557 exec_params
.flags
&= ~EXEC_APPLY_CHROOT
;
1560 if ((flags
& EXEC_PASS_FDS
) ||
1561 s
->exec_context
.std_input
== EXEC_INPUT_SOCKET
||
1562 s
->exec_context
.std_output
== EXEC_OUTPUT_SOCKET
||
1563 s
->exec_context
.std_error
== EXEC_OUTPUT_SOCKET
) {
1565 r
= service_collect_fds(s
,
1567 &exec_params
.fd_names
,
1568 &exec_params
.n_socket_fds
,
1569 &exec_params
.n_storage_fds
);
1573 exec_params
.open_files
= s
->open_files
;
1575 log_unit_debug(UNIT(s
), "Passing %zu fds to service", exec_params
.n_socket_fds
+ exec_params
.n_storage_fds
);
1578 if (!FLAGS_SET(flags
, EXEC_IS_CONTROL
) && s
->type
== SERVICE_EXEC
) {
1579 r
= service_allocate_exec_fd(s
, &exec_fd_source
, &exec_params
.exec_fd
);
1584 r
= service_arm_timer(s
, /* relative= */ true, timeout
);
1588 our_env
= new0(char*, 12);
1592 if (service_exec_needs_notify_socket(s
, flags
)) {
1593 if (asprintf(our_env
+ n_env
++, "NOTIFY_SOCKET=%s", UNIT(s
)->manager
->notify_socket
) < 0)
1596 exec_params
.notify_socket
= UNIT(s
)->manager
->notify_socket
;
1599 if (s
->main_pid
> 0)
1600 if (asprintf(our_env
+ n_env
++, "MAINPID="PID_FMT
, s
->main_pid
) < 0)
1603 if (MANAGER_IS_USER(UNIT(s
)->manager
))
1604 if (asprintf(our_env
+ n_env
++, "MANAGERPID="PID_FMT
, getpid_cached()) < 0)
1608 if (asprintf(our_env
+ n_env
++, "PIDFILE=%s", s
->pid_file
) < 0)
1611 if (s
->socket_fd
>= 0) {
1612 union sockaddr_union sa
;
1613 socklen_t salen
= sizeof(sa
);
1615 /* If this is a per-connection service instance, let's set $REMOTE_ADDR and $REMOTE_PORT to something
1616 * useful. Note that we do this only when we are still connected at this point in time, which we might
1617 * very well not be. Hence we ignore all errors when retrieving peer information (as that might result
1618 * in ENOTCONN), and just use whate we can use. */
1620 if (getpeername(s
->socket_fd
, &sa
.sa
, &salen
) >= 0 &&
1621 IN_SET(sa
.sa
.sa_family
, AF_INET
, AF_INET6
, AF_VSOCK
)) {
1622 _cleanup_free_
char *addr
= NULL
;
1626 r
= sockaddr_pretty(&sa
.sa
, salen
, true, false, &addr
);
1630 t
= strjoin("REMOTE_ADDR=", addr
);
1633 our_env
[n_env
++] = t
;
1635 r
= sockaddr_port(&sa
.sa
, &port
);
1639 if (asprintf(&t
, "REMOTE_PORT=%u", port
) < 0)
1641 our_env
[n_env
++] = t
;
1645 Service
*env_source
= NULL
;
1646 const char *monitor_prefix
;
1647 if (flags
& EXEC_SETENV_RESULT
) {
1649 monitor_prefix
= "";
1650 } else if (flags
& EXEC_SETENV_MONITOR_RESULT
) {
1651 env_source
= service_get_triggering_service(s
);
1652 monitor_prefix
= "MONITOR_";
1656 if (asprintf(our_env
+ n_env
++, "%sSERVICE_RESULT=%s", monitor_prefix
, service_result_to_string(env_source
->result
)) < 0)
1659 if (env_source
->main_exec_status
.pid
> 0 &&
1660 dual_timestamp_is_set(&env_source
->main_exec_status
.exit_timestamp
)) {
1661 if (asprintf(our_env
+ n_env
++, "%sEXIT_CODE=%s", monitor_prefix
, sigchld_code_to_string(env_source
->main_exec_status
.code
)) < 0)
1664 if (env_source
->main_exec_status
.code
== CLD_EXITED
)
1665 r
= asprintf(our_env
+ n_env
++, "%sEXIT_STATUS=%i", monitor_prefix
, env_source
->main_exec_status
.status
);
1667 r
= asprintf(our_env
+ n_env
++, "%sEXIT_STATUS=%s", monitor_prefix
, signal_to_string(env_source
->main_exec_status
.status
));
1673 if (env_source
!= s
) {
1674 if (!sd_id128_is_null(UNIT(env_source
)->invocation_id
)) {
1675 r
= asprintf(our_env
+ n_env
++, "%sINVOCATION_ID=" SD_ID128_FORMAT_STR
,
1676 monitor_prefix
, SD_ID128_FORMAT_VAL(UNIT(env_source
)->invocation_id
));
1681 if (asprintf(our_env
+ n_env
++, "%sUNIT=%s", monitor_prefix
, UNIT(env_source
)->id
) < 0)
1686 if (UNIT(s
)->activation_details
) {
1687 r
= activation_details_append_env(UNIT(s
)->activation_details
, &our_env
);
1690 /* The number of env vars added here can vary, rather than keeping the allocation block in
1691 * sync manually, these functions simply use the strv methods to append to it, so we need
1692 * to update n_env when we are done in case of future usage. */
1696 r
= unit_set_exec_params(UNIT(s
), &exec_params
);
1700 final_env
= strv_env_merge(exec_params
.environment
, our_env
);
1704 /* System D-Bus needs nss-systemd disabled, so that we don't deadlock */
1705 SET_FLAG(exec_params
.flags
, EXEC_NSS_DYNAMIC_BYPASS
,
1706 MANAGER_IS_SYSTEM(UNIT(s
)->manager
) && unit_has_name(UNIT(s
), SPECIAL_DBUS_SERVICE
));
1708 strv_free_and_replace(exec_params
.environment
, final_env
);
1709 exec_params
.watchdog_usec
= service_get_watchdog_usec(s
);
1710 exec_params
.selinux_context_net
= s
->socket_fd_selinux_context_net
;
1711 if (s
->type
== SERVICE_IDLE
)
1712 exec_params
.idle_pipe
= UNIT(s
)->manager
->idle_pipe
;
1713 exec_params
.stdin_fd
= s
->stdin_fd
;
1714 exec_params
.stdout_fd
= s
->stdout_fd
;
1715 exec_params
.stderr_fd
= s
->stderr_fd
;
1717 r
= exec_spawn(UNIT(s
),
1728 s
->exec_fd_event_source
= TAKE_PTR(exec_fd_source
);
1729 s
->exec_fd_hot
= false;
1731 r
= unit_watch_pid(UNIT(s
), pid
, true);
1740 static int main_pid_good(Service
*s
) {
1743 /* Returns 0 if the pid is dead, > 0 if it is good, < 0 if we don't know */
1745 /* If we know the pid file, then let's just check if it is
1747 if (s
->main_pid_known
) {
1749 /* If it's an alien child let's check if it is still
1751 if (s
->main_pid_alien
&& s
->main_pid
> 0)
1752 return pid_is_alive(s
->main_pid
);
1754 /* .. otherwise assume we'll get a SIGCHLD for it,
1755 * which we really should wait for to collect exit
1756 * status and code */
1757 return s
->main_pid
> 0;
1760 /* We don't know the pid */
1764 static int control_pid_good(Service
*s
) {
1767 /* Returns 0 if the control PID is dead, > 0 if it is good. We never actually return < 0 here, but in order to
1768 * make this function as similar as possible to main_pid_good() and cgroup_good(), we pretend that < 0 also
1769 * means: we can't figure it out. */
1771 return s
->control_pid
> 0;
1774 static int cgroup_good(Service
*s
) {
1779 /* Returns 0 if the cgroup is empty or doesn't exist, > 0 if it is exists and is populated, < 0 if we can't
1782 if (!UNIT(s
)->cgroup_path
)
1785 r
= cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER
, UNIT(s
)->cgroup_path
);
1792 static bool service_shall_restart(Service
*s
, const char **reason
) {
1795 /* Don't restart after manual stops */
1796 if (s
->forbid_restart
) {
1797 *reason
= "manual stop";
1801 /* Never restart if this is configured as special exception */
1802 if (exit_status_set_test(&s
->restart_prevent_status
, s
->main_exec_status
.code
, s
->main_exec_status
.status
)) {
1803 *reason
= "prevented by exit status";
1807 /* Restart if the exit code/status are configured as restart triggers */
1808 if (exit_status_set_test(&s
->restart_force_status
, s
->main_exec_status
.code
, s
->main_exec_status
.status
)) {
1809 *reason
= "forced by exit status";
1813 *reason
= "restart setting";
1814 switch (s
->restart
) {
1816 case SERVICE_RESTART_NO
:
1819 case SERVICE_RESTART_ALWAYS
:
1820 return s
->result
!= SERVICE_SKIP_CONDITION
;
1822 case SERVICE_RESTART_ON_SUCCESS
:
1823 return s
->result
== SERVICE_SUCCESS
;
1825 case SERVICE_RESTART_ON_FAILURE
:
1826 return !IN_SET(s
->result
, SERVICE_SUCCESS
, SERVICE_SKIP_CONDITION
);
1828 case SERVICE_RESTART_ON_ABNORMAL
:
1829 return !IN_SET(s
->result
, SERVICE_SUCCESS
, SERVICE_FAILURE_EXIT_CODE
, SERVICE_SKIP_CONDITION
);
1831 case SERVICE_RESTART_ON_WATCHDOG
:
1832 return s
->result
== SERVICE_FAILURE_WATCHDOG
;
1834 case SERVICE_RESTART_ON_ABORT
:
1835 return IN_SET(s
->result
, SERVICE_FAILURE_SIGNAL
, SERVICE_FAILURE_CORE_DUMP
);
1838 assert_not_reached();
1842 static bool service_will_restart(Unit
*u
) {
1843 Service
*s
= SERVICE(u
);
1847 if (s
->will_auto_restart
)
1849 if (s
->state
== SERVICE_AUTO_RESTART
)
1852 return unit_will_restart_default(u
);
1855 static void service_enter_dead(Service
*s
, ServiceResult f
, bool allow_restart
) {
1856 ServiceState end_state
;
1861 /* If there's a stop job queued before we enter the DEAD state, we shouldn't act on Restart=, in order to not
1862 * undo what has already been enqueued. */
1863 if (unit_stop_pending(UNIT(s
)))
1864 allow_restart
= false;
1866 if (s
->result
== SERVICE_SUCCESS
)
1869 if (s
->result
== SERVICE_SUCCESS
) {
1870 unit_log_success(UNIT(s
));
1871 end_state
= SERVICE_DEAD
;
1872 } else if (s
->result
== SERVICE_SKIP_CONDITION
) {
1873 unit_log_skip(UNIT(s
), service_result_to_string(s
->result
));
1874 end_state
= SERVICE_DEAD
;
1876 unit_log_failure(UNIT(s
), service_result_to_string(s
->result
));
1877 end_state
= SERVICE_FAILED
;
1879 unit_warn_leftover_processes(UNIT(s
), unit_log_leftover_process_stop
);
1882 log_unit_debug(UNIT(s
), "Service restart not allowed.");
1887 shall_restart
= service_shall_restart(s
, &reason
);
1888 log_unit_debug(UNIT(s
), "Service will %srestart (%s)",
1889 shall_restart
? "" : "not ",
1892 s
->will_auto_restart
= true;
1895 /* Make sure service_release_resources() doesn't destroy our FD store, while we are changing through
1896 * SERVICE_FAILED/SERVICE_DEAD before entering into SERVICE_AUTO_RESTART. */
1897 s
->n_keep_fd_store
++;
1899 service_set_state(s
, end_state
);
1901 if (s
->will_auto_restart
) {
1902 s
->will_auto_restart
= false;
1904 r
= service_arm_timer(s
, /* relative= */ true, s
->restart_usec
);
1906 s
->n_keep_fd_store
--;
1910 service_set_state(s
, SERVICE_AUTO_RESTART
);
1912 /* If we shan't restart, then flush out the restart counter. But don't do that immediately, so that the
1913 * user can still introspect the counter. Do so on the next start. */
1914 s
->flush_n_restarts
= true;
1916 /* The new state is in effect, let's decrease the fd store ref counter again. Let's also re-add us to the GC
1917 * queue, so that the fd store is possibly gc'ed again */
1918 s
->n_keep_fd_store
--;
1919 unit_add_to_gc_queue(UNIT(s
));
1921 /* The next restart might not be a manual stop, hence reset the flag indicating manual stops */
1922 s
->forbid_restart
= false;
1924 /* Reset NotifyAccess override */
1925 s
->notify_access_override
= _NOTIFY_ACCESS_INVALID
;
1927 /* We want fresh tmpdirs in case service is started again immediately */
1928 s
->exec_runtime
= exec_shared_runtime_unref(s
->exec_runtime
, true);
1930 /* Also, remove the runtime directory */
1931 unit_destroy_runtime_data(UNIT(s
), &s
->exec_context
);
1933 /* Get rid of the IPC bits of the user */
1934 unit_unref_uid_gid(UNIT(s
), true);
1936 /* Release the user, and destroy it if we are the only remaining owner */
1937 dynamic_creds_destroy(&s
->dynamic_creds
);
1939 /* Try to delete the pid file. At this point it will be
1940 * out-of-date, and some software might be confused by it, so
1941 * let's remove it. */
1943 (void) unlink(s
->pid_file
);
1945 /* Reset TTY ownership if necessary */
1946 exec_context_revert_tty(&s
->exec_context
);
1951 log_unit_warning_errno(UNIT(s
), r
, "Failed to run install restart timer: %m");
1952 service_enter_dead(s
, SERVICE_FAILURE_RESOURCES
, false);
1955 static void service_enter_stop_post(Service
*s
, ServiceResult f
) {
1959 if (s
->result
== SERVICE_SUCCESS
)
1962 service_unwatch_control_pid(s
);
1963 (void) unit_enqueue_rewatch_pids(UNIT(s
));
1965 s
->control_command
= s
->exec_command
[SERVICE_EXEC_STOP_POST
];
1966 if (s
->control_command
) {
1967 s
->control_command_id
= SERVICE_EXEC_STOP_POST
;
1969 r
= service_spawn(s
,
1971 s
->timeout_stop_usec
,
1972 EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_APPLY_TTY_STDIN
|EXEC_IS_CONTROL
|EXEC_SETENV_RESULT
|EXEC_CONTROL_CGROUP
,
1977 service_set_state(s
, SERVICE_STOP_POST
);
1979 service_enter_signal(s
, SERVICE_FINAL_SIGTERM
, SERVICE_SUCCESS
);
1984 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'stop-post' task: %m");
1985 service_enter_signal(s
, SERVICE_FINAL_SIGTERM
, SERVICE_FAILURE_RESOURCES
);
1988 static int state_to_kill_operation(Service
*s
, ServiceState state
) {
1991 case SERVICE_STOP_WATCHDOG
:
1992 case SERVICE_FINAL_WATCHDOG
:
1993 return KILL_WATCHDOG
;
1995 case SERVICE_STOP_SIGTERM
:
1996 if (unit_has_job_type(UNIT(s
), JOB_RESTART
))
1997 return KILL_RESTART
;
2000 case SERVICE_FINAL_SIGTERM
:
2001 return KILL_TERMINATE
;
2003 case SERVICE_STOP_SIGKILL
:
2004 case SERVICE_FINAL_SIGKILL
:
2008 return _KILL_OPERATION_INVALID
;
2012 static void service_enter_signal(Service
*s
, ServiceState state
, ServiceResult f
) {
2013 int kill_operation
, r
;
2017 if (s
->result
== SERVICE_SUCCESS
)
2020 /* Before sending any signal, make sure we track all members of this cgroup */
2021 (void) unit_watch_all_pids(UNIT(s
));
2023 /* Also, enqueue a job that we recheck all our PIDs a bit later, given that it's likely some processes have
2025 (void) unit_enqueue_rewatch_pids(UNIT(s
));
2027 kill_operation
= state_to_kill_operation(s
, state
);
2028 r
= unit_kill_context(
2039 r
= service_arm_timer(s
, /* relative= */ true,
2040 kill_operation
== KILL_WATCHDOG
? service_timeout_abort_usec(s
) : s
->timeout_stop_usec
);
2044 service_set_state(s
, state
);
2045 } else if (IN_SET(state
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
) && s
->kill_context
.send_sigkill
)
2046 service_enter_signal(s
, SERVICE_STOP_SIGKILL
, SERVICE_SUCCESS
);
2047 else if (IN_SET(state
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
))
2048 service_enter_stop_post(s
, SERVICE_SUCCESS
);
2049 else if (IN_SET(state
, SERVICE_FINAL_WATCHDOG
, SERVICE_FINAL_SIGTERM
) && s
->kill_context
.send_sigkill
)
2050 service_enter_signal(s
, SERVICE_FINAL_SIGKILL
, SERVICE_SUCCESS
);
2052 service_enter_dead(s
, SERVICE_SUCCESS
, true);
2057 log_unit_warning_errno(UNIT(s
), r
, "Failed to kill processes: %m");
2059 if (IN_SET(state
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
))
2060 service_enter_stop_post(s
, SERVICE_FAILURE_RESOURCES
);
2062 service_enter_dead(s
, SERVICE_FAILURE_RESOURCES
, true);
2065 static void service_enter_stop_by_notify(Service
*s
) {
2068 (void) unit_enqueue_rewatch_pids(UNIT(s
));
2070 service_arm_timer(s
, /* relative= */ true, s
->timeout_stop_usec
);
2072 /* The service told us it's stopping, so it's as if we SIGTERM'd it. */
2073 service_set_state(s
, SERVICE_STOP_SIGTERM
);
2076 static void service_enter_stop(Service
*s
, ServiceResult f
) {
2081 if (s
->result
== SERVICE_SUCCESS
)
2084 service_unwatch_control_pid(s
);
2085 (void) unit_enqueue_rewatch_pids(UNIT(s
));
2087 s
->control_command
= s
->exec_command
[SERVICE_EXEC_STOP
];
2088 if (s
->control_command
) {
2089 s
->control_command_id
= SERVICE_EXEC_STOP
;
2091 r
= service_spawn(s
,
2093 s
->timeout_stop_usec
,
2094 EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_IS_CONTROL
|EXEC_SETENV_RESULT
|EXEC_CONTROL_CGROUP
,
2099 service_set_state(s
, SERVICE_STOP
);
2101 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_SUCCESS
);
2106 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'stop' task: %m");
2107 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_RESOURCES
);
2110 static bool service_good(Service
*s
) {
2114 if (s
->type
== SERVICE_DBUS
&& !s
->bus_name_good
)
2117 main_pid_ok
= main_pid_good(s
);
2118 if (main_pid_ok
> 0) /* It's alive */
2120 if (main_pid_ok
== 0) /* It's dead */
2123 /* OK, we don't know anything about the main PID, maybe
2124 * because there is none. Let's check the control group
2127 return cgroup_good(s
) != 0;
2130 static void service_enter_running(Service
*s
, ServiceResult f
) {
2133 if (s
->result
== SERVICE_SUCCESS
)
2136 service_unwatch_control_pid(s
);
2138 if (s
->result
!= SERVICE_SUCCESS
)
2139 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
2140 else if (service_good(s
)) {
2142 /* If there are any queued up sd_notify() notifications, process them now */
2143 if (s
->notify_state
== NOTIFY_RELOADING
)
2144 service_enter_reload_by_notify(s
);
2145 else if (s
->notify_state
== NOTIFY_STOPPING
)
2146 service_enter_stop_by_notify(s
);
2148 service_set_state(s
, SERVICE_RUNNING
);
2149 service_arm_timer(s
, /* relative= */ false, service_running_timeout(s
));
2152 } else if (s
->remain_after_exit
)
2153 service_set_state(s
, SERVICE_EXITED
);
2155 service_enter_stop(s
, SERVICE_SUCCESS
);
2158 static void service_enter_start_post(Service
*s
) {
2162 service_unwatch_control_pid(s
);
2163 service_reset_watchdog(s
);
2165 s
->control_command
= s
->exec_command
[SERVICE_EXEC_START_POST
];
2166 if (s
->control_command
) {
2167 s
->control_command_id
= SERVICE_EXEC_START_POST
;
2169 r
= service_spawn(s
,
2171 s
->timeout_start_usec
,
2172 EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_IS_CONTROL
|EXEC_CONTROL_CGROUP
,
2177 service_set_state(s
, SERVICE_START_POST
);
2179 service_enter_running(s
, SERVICE_SUCCESS
);
2184 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'start-post' task: %m");
2185 service_enter_stop(s
, SERVICE_FAILURE_RESOURCES
);
2188 static void service_kill_control_process(Service
*s
) {
2193 if (s
->control_pid
<= 0)
2196 r
= kill_and_sigcont(s
->control_pid
, SIGKILL
);
2198 _cleanup_free_
char *comm
= NULL
;
2200 (void) get_process_comm(s
->control_pid
, &comm
);
2202 log_unit_debug_errno(UNIT(s
), r
, "Failed to kill control process " PID_FMT
" (%s), ignoring: %m",
2203 s
->control_pid
, strna(comm
));
2207 static int service_adverse_to_leftover_processes(Service
*s
) {
2210 /* KillMode=mixed and control group are used to indicate that all process should be killed off.
2211 * SendSIGKILL= is used for services that require a clean shutdown. These are typically database
2212 * service where a SigKilled process would result in a lengthy recovery and who's shutdown or startup
2213 * time is quite variable (so Timeout settings aren't of use).
2215 * Here we take these two factors and refuse to start a service if there are existing processes
2216 * within a control group. Databases, while generally having some protection against multiple
2217 * instances running, lets not stress the rigor of these. Also ExecStartPre= parts of the service
2218 * aren't as rigoriously written to protect aganst against multiple use. */
2220 if (unit_warn_leftover_processes(UNIT(s
), unit_log_leftover_process_start
) > 0 &&
2221 IN_SET(s
->kill_context
.kill_mode
, KILL_MIXED
, KILL_CONTROL_GROUP
) &&
2222 !s
->kill_context
.send_sigkill
)
2223 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(EBUSY
),
2224 "Will not start SendSIGKILL=no service of type KillMode=control-group or mixed while processes exist");
2229 static void service_enter_start(Service
*s
) {
2237 service_unwatch_control_pid(s
);
2238 service_unwatch_main_pid(s
);
2240 r
= service_adverse_to_leftover_processes(s
);
2244 if (s
->type
== SERVICE_FORKING
) {
2245 s
->control_command_id
= SERVICE_EXEC_START
;
2246 c
= s
->control_command
= s
->exec_command
[SERVICE_EXEC_START
];
2248 s
->main_command
= NULL
;
2250 s
->control_command_id
= _SERVICE_EXEC_COMMAND_INVALID
;
2251 s
->control_command
= NULL
;
2253 c
= s
->main_command
= s
->exec_command
[SERVICE_EXEC_START
];
2257 if (s
->type
!= SERVICE_ONESHOT
) {
2258 /* There's no command line configured for the main command? Hmm, that is strange.
2259 * This can only happen if the configuration changes at runtime. In this case,
2260 * let's enter a failure state. */
2261 r
= log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENXIO
), "There's no 'start' task anymore we could start.");
2265 /* We force a fake state transition here. Otherwise, the unit would go directly from
2266 * SERVICE_DEAD to SERVICE_DEAD without SERVICE_ACTIVATING or SERVICE_ACTIVE
2267 * in between. This way we can later trigger actions that depend on the state
2268 * transition, including SuccessAction=. */
2269 service_set_state(s
, SERVICE_START
);
2271 service_enter_start_post(s
);
2275 if (IN_SET(s
->type
, SERVICE_SIMPLE
, SERVICE_IDLE
))
2276 /* For simple + idle this is the main process. We don't apply any timeout here, but
2277 * service_enter_running() will later apply the .runtime_max_usec timeout. */
2278 timeout
= USEC_INFINITY
;
2280 timeout
= s
->timeout_start_usec
;
2282 r
= service_spawn(s
,
2285 EXEC_PASS_FDS
|EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_APPLY_TTY_STDIN
|EXEC_SET_WATCHDOG
|EXEC_WRITE_CREDENTIALS
|EXEC_SETENV_MONITOR_RESULT
,
2290 if (IN_SET(s
->type
, SERVICE_SIMPLE
, SERVICE_IDLE
)) {
2291 /* For simple services we immediately start
2292 * the START_POST binaries. */
2294 (void) service_set_main_pid(s
, pid
);
2295 service_enter_start_post(s
);
2297 } else if (s
->type
== SERVICE_FORKING
) {
2299 /* For forking services we wait until the start
2300 * process exited. */
2302 s
->control_pid
= pid
;
2303 service_set_state(s
, SERVICE_START
);
2305 } else if (IN_SET(s
->type
, SERVICE_ONESHOT
, SERVICE_DBUS
, SERVICE_NOTIFY
, SERVICE_NOTIFY_RELOAD
, SERVICE_EXEC
)) {
2307 /* For oneshot services we wait until the start process exited, too, but it is our main process. */
2309 /* For D-Bus services we know the main pid right away, but wait for the bus name to appear on the
2310 * bus. 'notify' and 'exec' services are similar. */
2312 (void) service_set_main_pid(s
, pid
);
2313 service_set_state(s
, SERVICE_START
);
2315 assert_not_reached();
2320 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'start' task: %m");
2321 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_RESOURCES
);
2324 static void service_enter_start_pre(Service
*s
) {
2329 service_unwatch_control_pid(s
);
2331 s
->control_command
= s
->exec_command
[SERVICE_EXEC_START_PRE
];
2332 if (s
->control_command
) {
2334 r
= service_adverse_to_leftover_processes(s
);
2338 s
->control_command_id
= SERVICE_EXEC_START_PRE
;
2340 r
= service_spawn(s
,
2342 s
->timeout_start_usec
,
2343 EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_IS_CONTROL
|EXEC_APPLY_TTY_STDIN
|EXEC_SETENV_MONITOR_RESULT
|EXEC_WRITE_CREDENTIALS
,
2348 service_set_state(s
, SERVICE_START_PRE
);
2350 service_enter_start(s
);
2355 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'start-pre' task: %m");
2356 service_enter_dead(s
, SERVICE_FAILURE_RESOURCES
, true);
2359 static void service_enter_condition(Service
*s
) {
2364 service_unwatch_control_pid(s
);
2366 s
->control_command
= s
->exec_command
[SERVICE_EXEC_CONDITION
];
2367 if (s
->control_command
) {
2369 r
= service_adverse_to_leftover_processes(s
);
2373 s
->control_command_id
= SERVICE_EXEC_CONDITION
;
2375 r
= service_spawn(s
,
2377 s
->timeout_start_usec
,
2378 EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_IS_CONTROL
|EXEC_APPLY_TTY_STDIN
,
2384 service_set_state(s
, SERVICE_CONDITION
);
2386 service_enter_start_pre(s
);
2391 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'exec-condition' task: %m");
2392 service_enter_dead(s
, SERVICE_FAILURE_RESOURCES
, true);
2395 static void service_enter_restart(Service
*s
) {
2396 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2401 if (unit_has_job_type(UNIT(s
), JOB_STOP
)) {
2402 /* Don't restart things if we are going down anyway */
2403 log_unit_info(UNIT(s
), "Stop job pending for unit, skipping automatic restart.");
2407 /* Any units that are bound to this service must also be
2408 * restarted. We use JOB_RESTART (instead of the more obvious
2409 * JOB_START) here so that those dependency jobs will be added
2411 r
= manager_add_job(UNIT(s
)->manager
, JOB_RESTART
, UNIT(s
), JOB_REPLACE
, NULL
, &error
, NULL
);
2415 /* Count the jobs we enqueue for restarting. This counter is maintained as long as the unit isn't fully
2416 * stopped, i.e. as long as it remains up or remains in auto-start states. The user can reset the counter
2417 * explicitly however via the usual "systemctl reset-failure" logic. */
2419 s
->flush_n_restarts
= false;
2421 s
->notify_access_override
= _NOTIFY_ACCESS_INVALID
;
2423 log_unit_struct(UNIT(s
), LOG_INFO
,
2424 "MESSAGE_ID=" SD_MESSAGE_UNIT_RESTART_SCHEDULED_STR
,
2425 LOG_UNIT_INVOCATION_ID(UNIT(s
)),
2426 LOG_UNIT_MESSAGE(UNIT(s
),
2427 "Scheduled restart job, restart counter is at %u.", s
->n_restarts
),
2428 "N_RESTARTS=%u", s
->n_restarts
);
2430 /* Notify clients about changed restart counter */
2431 unit_add_to_dbus_queue(UNIT(s
));
2433 /* Note that we stay in the SERVICE_AUTO_RESTART state here,
2434 * it will be canceled as part of the service_stop() call that
2435 * is executed as part of JOB_RESTART. */
2440 log_unit_warning(UNIT(s
), "Failed to schedule restart job: %s", bus_error_message(&error
, r
));
2441 service_enter_dead(s
, SERVICE_FAILURE_RESOURCES
, false);
2444 static void service_enter_reload_by_notify(Service
*s
) {
2445 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2450 service_arm_timer(s
, /* relative= */ true, s
->timeout_start_usec
);
2451 service_set_state(s
, SERVICE_RELOAD_NOTIFY
);
2453 /* service_enter_reload_by_notify is never called during a reload, thus no loops are possible. */
2454 r
= manager_propagate_reload(UNIT(s
)->manager
, UNIT(s
), JOB_FAIL
, &error
);
2456 log_unit_warning(UNIT(s
), "Failed to schedule propagation of reload: %s", bus_error_message(&error
, r
));
2459 static void service_enter_reload(Service
*s
) {
2460 bool killed
= false;
2465 service_unwatch_control_pid(s
);
2466 s
->reload_result
= SERVICE_SUCCESS
;
2468 usec_t ts
= now(CLOCK_MONOTONIC
);
2470 if (s
->type
== SERVICE_NOTIFY_RELOAD
&& s
->main_pid
> 0) {
2471 r
= kill_and_sigcont(s
->main_pid
, s
->reload_signal
);
2473 log_unit_warning_errno(UNIT(s
), r
, "Failed to send reload signal: %m");
2480 s
->control_command
= s
->exec_command
[SERVICE_EXEC_RELOAD
];
2481 if (s
->control_command
) {
2482 s
->control_command_id
= SERVICE_EXEC_RELOAD
;
2484 r
= service_spawn(s
,
2486 s
->timeout_start_usec
,
2487 EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_IS_CONTROL
|EXEC_CONTROL_CGROUP
,
2490 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'reload' task: %m");
2494 service_set_state(s
, SERVICE_RELOAD
);
2495 } else if (killed
) {
2496 service_arm_timer(s
, /* relative= */ true, s
->timeout_start_usec
);
2497 service_set_state(s
, SERVICE_RELOAD_SIGNAL
);
2499 service_enter_running(s
, SERVICE_SUCCESS
);
2503 /* Store the timestamp when we started reloading: when reloading via SIGHUP we won't leave the reload
2504 * state until we received both RELOADING=1 and READY=1 with MONOTONIC_USEC= set to a value above
2505 * this. Thus we know for sure the reload cycle was executed *after* we requested it, and is not one
2506 * that was already in progress before. */
2507 s
->reload_begin_usec
= ts
;
2511 s
->reload_result
= SERVICE_FAILURE_RESOURCES
;
2512 service_enter_running(s
, SERVICE_SUCCESS
);
2515 static void service_run_next_control(Service
*s
) {
2520 assert(s
->control_command
);
2521 assert(s
->control_command
->command_next
);
2523 assert(s
->control_command_id
!= SERVICE_EXEC_START
);
2525 s
->control_command
= s
->control_command
->command_next
;
2526 service_unwatch_control_pid(s
);
2528 if (IN_SET(s
->state
, SERVICE_CONDITION
, SERVICE_START_PRE
, SERVICE_START
, SERVICE_START_POST
, SERVICE_RUNNING
, SERVICE_RELOAD
))
2529 timeout
= s
->timeout_start_usec
;
2531 timeout
= s
->timeout_stop_usec
;
2533 r
= service_spawn(s
,
2536 EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_IS_CONTROL
|
2537 (IN_SET(s
->control_command_id
, SERVICE_EXEC_CONDITION
, SERVICE_EXEC_START_PRE
, SERVICE_EXEC_STOP_POST
) ? EXEC_APPLY_TTY_STDIN
: 0)|
2538 (IN_SET(s
->control_command_id
, SERVICE_EXEC_STOP
, SERVICE_EXEC_STOP_POST
) ? EXEC_SETENV_RESULT
: 0)|
2539 (IN_SET(s
->control_command_id
, SERVICE_EXEC_START_PRE
, SERVICE_EXEC_START
) ? EXEC_SETENV_MONITOR_RESULT
: 0)|
2540 (IN_SET(s
->control_command_id
, SERVICE_EXEC_START_POST
, SERVICE_EXEC_RELOAD
, SERVICE_EXEC_STOP
, SERVICE_EXEC_STOP_POST
) ? EXEC_CONTROL_CGROUP
: 0),
2548 log_unit_warning_errno(UNIT(s
), r
, "Failed to run next control task: %m");
2550 if (IN_SET(s
->state
, SERVICE_CONDITION
, SERVICE_START_PRE
, SERVICE_START_POST
, SERVICE_STOP
))
2551 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_RESOURCES
);
2552 else if (s
->state
== SERVICE_STOP_POST
)
2553 service_enter_dead(s
, SERVICE_FAILURE_RESOURCES
, true);
2554 else if (s
->state
== SERVICE_RELOAD
) {
2555 s
->reload_result
= SERVICE_FAILURE_RESOURCES
;
2556 service_enter_running(s
, SERVICE_SUCCESS
);
2558 service_enter_stop(s
, SERVICE_FAILURE_RESOURCES
);
2561 static void service_run_next_main(Service
*s
) {
2566 assert(s
->main_command
);
2567 assert(s
->main_command
->command_next
);
2568 assert(s
->type
== SERVICE_ONESHOT
);
2570 s
->main_command
= s
->main_command
->command_next
;
2571 service_unwatch_main_pid(s
);
2573 r
= service_spawn(s
,
2575 s
->timeout_start_usec
,
2576 EXEC_PASS_FDS
|EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_APPLY_TTY_STDIN
|EXEC_SET_WATCHDOG
|EXEC_SETENV_MONITOR_RESULT
,
2581 (void) service_set_main_pid(s
, pid
);
2586 log_unit_warning_errno(UNIT(s
), r
, "Failed to run next main task: %m");
2587 service_enter_stop(s
, SERVICE_FAILURE_RESOURCES
);
2590 static int service_start(Unit
*u
) {
2591 Service
*s
= SERVICE(u
);
2596 /* We cannot fulfill this request right now, try again later
2598 if (IN_SET(s
->state
,
2599 SERVICE_STOP
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
, SERVICE_STOP_POST
,
2600 SERVICE_FINAL_WATCHDOG
, SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
, SERVICE_CLEANING
))
2603 /* Already on it! */
2604 if (IN_SET(s
->state
, SERVICE_CONDITION
, SERVICE_START_PRE
, SERVICE_START
, SERVICE_START_POST
))
2607 /* A service that will be restarted must be stopped first to
2608 * trigger BindsTo and/or OnFailure dependencies. If a user
2609 * does not want to wait for the holdoff time to elapse, the
2610 * service should be manually restarted, not started. We
2611 * simply return EAGAIN here, so that any start jobs stay
2612 * queued, and assume that the auto restart timer will
2613 * eventually trigger the restart. */
2614 if (s
->state
== SERVICE_AUTO_RESTART
)
2617 assert(IN_SET(s
->state
, SERVICE_DEAD
, SERVICE_FAILED
));
2619 r
= unit_acquire_invocation_id(u
);
2623 s
->result
= SERVICE_SUCCESS
;
2624 s
->reload_result
= SERVICE_SUCCESS
;
2625 s
->main_pid_known
= false;
2626 s
->main_pid_alien
= false;
2627 s
->forbid_restart
= false;
2629 s
->status_text
= mfree(s
->status_text
);
2630 s
->status_errno
= 0;
2632 s
->notify_access_override
= _NOTIFY_ACCESS_INVALID
;
2633 s
->notify_state
= NOTIFY_UNKNOWN
;
2635 s
->watchdog_original_usec
= s
->watchdog_usec
;
2636 s
->watchdog_override_enable
= false;
2637 s
->watchdog_override_usec
= USEC_INFINITY
;
2639 exec_command_reset_status_list_array(s
->exec_command
, _SERVICE_EXEC_COMMAND_MAX
);
2640 exec_status_reset(&s
->main_exec_status
);
2642 /* This is not an automatic restart? Flush the restart counter then */
2643 if (s
->flush_n_restarts
) {
2645 s
->flush_n_restarts
= false;
2648 u
->reset_accounting
= true;
2650 service_enter_condition(s
);
2654 static int service_stop(Unit
*u
) {
2655 Service
*s
= SERVICE(u
);
2659 /* Don't create restart jobs from manual stops. */
2660 s
->forbid_restart
= true;
2663 if (IN_SET(s
->state
,
2664 SERVICE_STOP
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
, SERVICE_STOP_POST
,
2665 SERVICE_FINAL_WATCHDOG
, SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
))
2668 /* A restart will be scheduled or is in progress. */
2669 if (s
->state
== SERVICE_AUTO_RESTART
) {
2670 service_set_state(s
, SERVICE_DEAD
);
2674 /* If there's already something running we go directly into kill mode. */
2675 if (IN_SET(s
->state
, SERVICE_CONDITION
, SERVICE_START_PRE
, SERVICE_START
, SERVICE_START_POST
, SERVICE_RELOAD
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
, SERVICE_STOP_WATCHDOG
)) {
2676 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_SUCCESS
);
2680 /* If we are currently cleaning, then abort it, brutally. */
2681 if (s
->state
== SERVICE_CLEANING
) {
2682 service_enter_signal(s
, SERVICE_FINAL_SIGKILL
, SERVICE_SUCCESS
);
2686 assert(IN_SET(s
->state
, SERVICE_RUNNING
, SERVICE_EXITED
));
2688 service_enter_stop(s
, SERVICE_SUCCESS
);
2692 static int service_reload(Unit
*u
) {
2693 Service
*s
= SERVICE(u
);
2697 assert(IN_SET(s
->state
, SERVICE_RUNNING
, SERVICE_EXITED
));
2699 service_enter_reload(s
);
2703 _pure_
static bool service_can_reload(Unit
*u
) {
2704 Service
*s
= SERVICE(u
);
2708 return s
->exec_command
[SERVICE_EXEC_RELOAD
] ||
2709 s
->type
== SERVICE_NOTIFY_RELOAD
;
2712 static unsigned service_exec_command_index(Unit
*u
, ServiceExecCommand id
, const ExecCommand
*current
) {
2713 Service
*s
= SERVICE(u
);
2718 assert(id
< _SERVICE_EXEC_COMMAND_MAX
);
2720 const ExecCommand
*first
= s
->exec_command
[id
];
2722 /* Figure out where we are in the list by walking back to the beginning */
2723 for (const ExecCommand
*c
= current
; c
!= first
; c
= c
->command_prev
)
2729 static int service_serialize_exec_command(Unit
*u
, FILE *f
, const ExecCommand
*command
) {
2730 _cleanup_free_
char *args
= NULL
, *p
= NULL
;
2731 Service
*s
= SERVICE(u
);
2732 const char *type
, *key
;
2733 ServiceExecCommand id
;
2743 if (command
== s
->control_command
) {
2745 id
= s
->control_command_id
;
2748 id
= SERVICE_EXEC_START
;
2751 idx
= service_exec_command_index(u
, id
, command
);
2753 STRV_FOREACH(arg
, command
->argv
) {
2754 _cleanup_free_
char *e
= NULL
;
2762 if (!GREEDY_REALLOC(args
, length
+ 2 + n
+ 2))
2766 args
[length
++] = ' ';
2768 args
[length
++] = '"';
2769 memcpy(args
+ length
, e
, n
);
2771 args
[length
++] = '"';
2774 if (!GREEDY_REALLOC(args
, length
+ 1))
2779 p
= cescape(command
->path
);
2783 key
= strjoina(type
, "-command");
2785 /* We use '+1234' instead of '1234' to mark the last command in a sequence.
2786 * This is used in service_deserialize_exec_command(). */
2787 (void) serialize_item_format(
2790 service_exec_command_to_string(id
),
2791 command
->command_next
? "" : "+",
2798 static int service_serialize(Unit
*u
, FILE *f
, FDSet
*fds
) {
2799 Service
*s
= SERVICE(u
);
2806 (void) serialize_item(f
, "state", service_state_to_string(s
->state
));
2807 (void) serialize_item(f
, "result", service_result_to_string(s
->result
));
2808 (void) serialize_item(f
, "reload-result", service_result_to_string(s
->reload_result
));
2810 if (s
->control_pid
> 0)
2811 (void) serialize_item_format(f
, "control-pid", PID_FMT
, s
->control_pid
);
2813 if (s
->main_pid_known
&& s
->main_pid
> 0)
2814 (void) serialize_item_format(f
, "main-pid", PID_FMT
, s
->main_pid
);
2816 (void) serialize_bool(f
, "main-pid-known", s
->main_pid_known
);
2817 (void) serialize_bool(f
, "bus-name-good", s
->bus_name_good
);
2818 (void) serialize_bool(f
, "bus-name-owner", s
->bus_name_owner
);
2820 (void) serialize_item_format(f
, "n-restarts", "%u", s
->n_restarts
);
2821 (void) serialize_bool(f
, "flush-n-restarts", s
->flush_n_restarts
);
2823 r
= serialize_item_escaped(f
, "status-text", s
->status_text
);
2827 service_serialize_exec_command(u
, f
, s
->control_command
);
2828 service_serialize_exec_command(u
, f
, s
->main_command
);
2830 r
= serialize_fd(f
, fds
, "stdin-fd", s
->stdin_fd
);
2833 r
= serialize_fd(f
, fds
, "stdout-fd", s
->stdout_fd
);
2836 r
= serialize_fd(f
, fds
, "stderr-fd", s
->stderr_fd
);
2840 if (s
->exec_fd_event_source
) {
2841 r
= serialize_fd(f
, fds
, "exec-fd", sd_event_source_get_io_fd(s
->exec_fd_event_source
));
2845 (void) serialize_bool(f
, "exec-fd-hot", s
->exec_fd_hot
);
2848 if (UNIT_ISSET(s
->accept_socket
)) {
2849 r
= serialize_item(f
, "accept-socket", UNIT_DEREF(s
->accept_socket
)->id
);
2854 r
= serialize_fd(f
, fds
, "socket-fd", s
->socket_fd
);
2858 LIST_FOREACH(fd_store
, fs
, s
->fd_store
) {
2859 _cleanup_free_
char *c
= NULL
;
2862 copy
= fdset_put_dup(fds
, fs
->fd
);
2864 return log_error_errno(copy
, "Failed to copy file descriptor for serialization: %m");
2866 c
= cescape(fs
->fdname
);
2870 (void) serialize_item_format(f
, "fd-store-fd", "%i \"%s\" %i", copy
, c
, fs
->do_poll
);
2873 if (s
->main_exec_status
.pid
> 0) {
2874 (void) serialize_item_format(f
, "main-exec-status-pid", PID_FMT
, s
->main_exec_status
.pid
);
2875 (void) serialize_dual_timestamp(f
, "main-exec-status-start", &s
->main_exec_status
.start_timestamp
);
2876 (void) serialize_dual_timestamp(f
, "main-exec-status-exit", &s
->main_exec_status
.exit_timestamp
);
2878 if (dual_timestamp_is_set(&s
->main_exec_status
.exit_timestamp
)) {
2879 (void) serialize_item_format(f
, "main-exec-status-code", "%i", s
->main_exec_status
.code
);
2880 (void) serialize_item_format(f
, "main-exec-status-status", "%i", s
->main_exec_status
.status
);
2884 if (s
->notify_access_override
>= 0)
2885 (void) serialize_item(f
, "notify-access-override", notify_access_to_string(s
->notify_access_override
));
2887 (void) serialize_dual_timestamp(f
, "watchdog-timestamp", &s
->watchdog_timestamp
);
2888 (void) serialize_bool(f
, "forbid-restart", s
->forbid_restart
);
2890 if (s
->watchdog_override_enable
)
2891 (void) serialize_item_format(f
, "watchdog-override-usec", USEC_FMT
, s
->watchdog_override_usec
);
2893 if (s
->watchdog_original_usec
!= USEC_INFINITY
)
2894 (void) serialize_item_format(f
, "watchdog-original-usec", USEC_FMT
, s
->watchdog_original_usec
);
2896 if (s
->reload_begin_usec
!= USEC_INFINITY
)
2897 (void) serialize_item_format(f
, "reload-begin-usec", USEC_FMT
, s
->reload_begin_usec
);
2902 int service_deserialize_exec_command(
2905 const char *value
) {
2907 Service
*s
= SERVICE(u
);
2909 unsigned idx
= 0, i
;
2910 bool control
, found
= false, last
= false;
2911 ServiceExecCommand id
= _SERVICE_EXEC_COMMAND_INVALID
;
2912 ExecCommand
*command
= NULL
;
2913 _cleanup_free_
char *path
= NULL
;
2914 _cleanup_strv_free_
char **argv
= NULL
;
2916 enum ExecCommandState
{
2917 STATE_EXEC_COMMAND_TYPE
,
2918 STATE_EXEC_COMMAND_INDEX
,
2919 STATE_EXEC_COMMAND_PATH
,
2920 STATE_EXEC_COMMAND_ARGS
,
2921 _STATE_EXEC_COMMAND_MAX
,
2922 _STATE_EXEC_COMMAND_INVALID
= -EINVAL
,
2929 control
= streq(key
, "control-command");
2931 state
= STATE_EXEC_COMMAND_TYPE
;
2934 _cleanup_free_
char *arg
= NULL
;
2936 r
= extract_first_word(&value
, &arg
, NULL
, EXTRACT_CUNESCAPE
| EXTRACT_UNQUOTE
);
2943 case STATE_EXEC_COMMAND_TYPE
:
2944 id
= service_exec_command_from_string(arg
);
2948 state
= STATE_EXEC_COMMAND_INDEX
;
2950 case STATE_EXEC_COMMAND_INDEX
:
2951 /* PID 1234 is serialized as either '1234' or '+1234'. The second form is used to
2952 * mark the last command in a sequence. We warn if the deserialized command doesn't
2953 * match what we have loaded from the unit, but we don't need to warn if that is the
2956 r
= safe_atou(arg
, &idx
);
2959 last
= arg
[0] == '+';
2961 state
= STATE_EXEC_COMMAND_PATH
;
2963 case STATE_EXEC_COMMAND_PATH
:
2964 path
= TAKE_PTR(arg
);
2965 state
= STATE_EXEC_COMMAND_ARGS
;
2967 case STATE_EXEC_COMMAND_ARGS
:
2968 r
= strv_extend(&argv
, arg
);
2973 assert_not_reached();
2977 if (state
!= STATE_EXEC_COMMAND_ARGS
)
2979 if (strv_isempty(argv
))
2980 return -EINVAL
; /* At least argv[0] must be always present. */
2982 /* Let's check whether exec command on given offset matches data that we just deserialized */
2983 for (command
= s
->exec_command
[id
], i
= 0; command
; command
= command
->command_next
, i
++) {
2987 found
= strv_equal(argv
, command
->argv
) && streq(command
->path
, path
);
2992 /* Command at the index we serialized is different, let's look for command that exactly
2993 * matches but is on different index. If there is no such command we will not resume execution. */
2994 for (command
= s
->exec_command
[id
]; command
; command
= command
->command_next
)
2995 if (strv_equal(command
->argv
, argv
) && streq(command
->path
, path
))
2999 if (command
&& control
) {
3000 s
->control_command
= command
;
3001 s
->control_command_id
= id
;
3003 s
->main_command
= command
;
3005 log_unit_debug(u
, "Current command vanished from the unit file.");
3007 log_unit_warning(u
, "Current command vanished from the unit file, execution of the command list won't be resumed.");
3012 static int service_deserialize_item(Unit
*u
, const char *key
, const char *value
, FDSet
*fds
) {
3013 Service
*s
= SERVICE(u
);
3021 if (streq(key
, "state")) {
3024 state
= service_state_from_string(value
);
3026 log_unit_debug(u
, "Failed to parse state value: %s", value
);
3028 s
->deserialized_state
= state
;
3029 } else if (streq(key
, "result")) {
3032 f
= service_result_from_string(value
);
3034 log_unit_debug(u
, "Failed to parse result value: %s", value
);
3035 else if (f
!= SERVICE_SUCCESS
)
3038 } else if (streq(key
, "reload-result")) {
3041 f
= service_result_from_string(value
);
3043 log_unit_debug(u
, "Failed to parse reload result value: %s", value
);
3044 else if (f
!= SERVICE_SUCCESS
)
3045 s
->reload_result
= f
;
3047 } else if (streq(key
, "control-pid")) {
3050 if (parse_pid(value
, &pid
) < 0)
3051 log_unit_debug(u
, "Failed to parse control-pid value: %s", value
);
3053 s
->control_pid
= pid
;
3054 } else if (streq(key
, "main-pid")) {
3057 if (parse_pid(value
, &pid
) < 0)
3058 log_unit_debug(u
, "Failed to parse main-pid value: %s", value
);
3060 (void) service_set_main_pid(s
, pid
);
3061 } else if (streq(key
, "main-pid-known")) {
3064 b
= parse_boolean(value
);
3066 log_unit_debug(u
, "Failed to parse main-pid-known value: %s", value
);
3068 s
->main_pid_known
= b
;
3069 } else if (streq(key
, "bus-name-good")) {
3072 b
= parse_boolean(value
);
3074 log_unit_debug(u
, "Failed to parse bus-name-good value: %s", value
);
3076 s
->bus_name_good
= b
;
3077 } else if (streq(key
, "bus-name-owner")) {
3078 r
= free_and_strdup(&s
->bus_name_owner
, value
);
3080 log_unit_error_errno(u
, r
, "Unable to deserialize current bus owner %s: %m", value
);
3081 } else if (streq(key
, "status-text")) {
3085 l
= cunescape(value
, 0, &t
);
3087 log_unit_debug_errno(u
, l
, "Failed to unescape status text '%s': %m", value
);
3089 free_and_replace(s
->status_text
, t
);
3091 } else if (streq(key
, "accept-socket")) {
3094 r
= manager_load_unit(u
->manager
, value
, NULL
, NULL
, &socket
);
3096 log_unit_debug_errno(u
, r
, "Failed to load accept-socket unit '%s': %m", value
);
3098 unit_ref_set(&s
->accept_socket
, u
, socket
);
3099 SOCKET(socket
)->n_connections
++;
3102 } else if (streq(key
, "socket-fd")) {
3105 if (safe_atoi(value
, &fd
) < 0 || fd
< 0 || !fdset_contains(fds
, fd
))
3106 log_unit_debug(u
, "Failed to parse socket-fd value: %s", value
);
3108 asynchronous_close(s
->socket_fd
);
3109 s
->socket_fd
= fdset_remove(fds
, fd
);
3111 } else if (streq(key
, "fd-store-fd")) {
3112 _cleanup_free_
char *fdv
= NULL
, *fdn
= NULL
, *fdp
= NULL
;
3116 r
= extract_first_word(&value
, &fdv
, NULL
, 0);
3117 if (r
<= 0 || safe_atoi(fdv
, &fd
) < 0 || fd
< 0 || !fdset_contains(fds
, fd
)) {
3118 log_unit_debug(u
, "Failed to parse fd-store-fd value: %s", value
);
3122 r
= extract_first_word(&value
, &fdn
, NULL
, EXTRACT_CUNESCAPE
| EXTRACT_UNQUOTE
);
3124 log_unit_debug(u
, "Failed to parse fd-store-fd value: %s", value
);
3128 r
= extract_first_word(&value
, &fdp
, NULL
, 0);
3130 /* If the value is not present, we assume the default */
3132 } else if (r
< 0 || safe_atoi(fdp
, &do_poll
) < 0) {
3133 log_unit_debug_errno(u
, r
, "Failed to parse fd-store-fd value \"%s\": %m", value
);
3137 r
= service_add_fd_store(s
, fd
, fdn
, do_poll
);
3139 log_unit_error_errno(u
, r
, "Failed to add fd to store: %m");
3141 fdset_remove(fds
, fd
);
3142 } else if (streq(key
, "main-exec-status-pid")) {
3145 if (parse_pid(value
, &pid
) < 0)
3146 log_unit_debug(u
, "Failed to parse main-exec-status-pid value: %s", value
);
3148 s
->main_exec_status
.pid
= pid
;
3149 } else if (streq(key
, "main-exec-status-code")) {
3152 if (safe_atoi(value
, &i
) < 0)
3153 log_unit_debug(u
, "Failed to parse main-exec-status-code value: %s", value
);
3155 s
->main_exec_status
.code
= i
;
3156 } else if (streq(key
, "main-exec-status-status")) {
3159 if (safe_atoi(value
, &i
) < 0)
3160 log_unit_debug(u
, "Failed to parse main-exec-status-status value: %s", value
);
3162 s
->main_exec_status
.status
= i
;
3163 } else if (streq(key
, "main-exec-status-start"))
3164 deserialize_dual_timestamp(value
, &s
->main_exec_status
.start_timestamp
);
3165 else if (streq(key
, "main-exec-status-exit"))
3166 deserialize_dual_timestamp(value
, &s
->main_exec_status
.exit_timestamp
);
3167 else if (streq(key
, "notify-access-override")) {
3168 NotifyAccess notify_access
;
3170 notify_access
= notify_access_from_string(value
);
3171 if (notify_access
< 0)
3172 log_unit_debug(u
, "Failed to parse notify-access-override value: %s", value
);
3174 s
->notify_access_override
= notify_access
;
3175 } else if (streq(key
, "watchdog-timestamp"))
3176 deserialize_dual_timestamp(value
, &s
->watchdog_timestamp
);
3177 else if (streq(key
, "forbid-restart")) {
3180 b
= parse_boolean(value
);
3182 log_unit_debug(u
, "Failed to parse forbid-restart value: %s", value
);
3184 s
->forbid_restart
= b
;
3185 } else if (streq(key
, "stdin-fd")) {
3188 if (safe_atoi(value
, &fd
) < 0 || fd
< 0 || !fdset_contains(fds
, fd
))
3189 log_unit_debug(u
, "Failed to parse stdin-fd value: %s", value
);
3191 asynchronous_close(s
->stdin_fd
);
3192 s
->stdin_fd
= fdset_remove(fds
, fd
);
3193 s
->exec_context
.stdio_as_fds
= true;
3195 } else if (streq(key
, "stdout-fd")) {
3198 if (safe_atoi(value
, &fd
) < 0 || fd
< 0 || !fdset_contains(fds
, fd
))
3199 log_unit_debug(u
, "Failed to parse stdout-fd value: %s", value
);
3201 asynchronous_close(s
->stdout_fd
);
3202 s
->stdout_fd
= fdset_remove(fds
, fd
);
3203 s
->exec_context
.stdio_as_fds
= true;
3205 } else if (streq(key
, "stderr-fd")) {
3208 if (safe_atoi(value
, &fd
) < 0 || fd
< 0 || !fdset_contains(fds
, fd
))
3209 log_unit_debug(u
, "Failed to parse stderr-fd value: %s", value
);
3211 asynchronous_close(s
->stderr_fd
);
3212 s
->stderr_fd
= fdset_remove(fds
, fd
);
3213 s
->exec_context
.stdio_as_fds
= true;
3215 } else if (streq(key
, "exec-fd")) {
3218 if (safe_atoi(value
, &fd
) < 0 || fd
< 0 || !fdset_contains(fds
, fd
))
3219 log_unit_debug(u
, "Failed to parse exec-fd value: %s", value
);
3221 s
->exec_fd_event_source
= sd_event_source_disable_unref(s
->exec_fd_event_source
);
3223 fd
= fdset_remove(fds
, fd
);
3224 if (service_allocate_exec_fd_event_source(s
, fd
, &s
->exec_fd_event_source
) < 0)
3227 } else if (streq(key
, "watchdog-override-usec")) {
3228 if (deserialize_usec(value
, &s
->watchdog_override_usec
) < 0)
3229 log_unit_debug(u
, "Failed to parse watchdog_override_usec value: %s", value
);
3231 s
->watchdog_override_enable
= true;
3233 } else if (streq(key
, "watchdog-original-usec")) {
3234 if (deserialize_usec(value
, &s
->watchdog_original_usec
) < 0)
3235 log_unit_debug(u
, "Failed to parse watchdog_original_usec value: %s", value
);
3237 } else if (STR_IN_SET(key
, "main-command", "control-command")) {
3238 r
= service_deserialize_exec_command(u
, key
, value
);
3240 log_unit_debug_errno(u
, r
, "Failed to parse serialized command \"%s\": %m", value
);
3242 } else if (streq(key
, "n-restarts")) {
3243 r
= safe_atou(value
, &s
->n_restarts
);
3245 log_unit_debug_errno(u
, r
, "Failed to parse serialized restart counter '%s': %m", value
);
3247 } else if (streq(key
, "flush-n-restarts")) {
3248 r
= parse_boolean(value
);
3250 log_unit_debug_errno(u
, r
, "Failed to parse serialized flush restart counter setting '%s': %m", value
);
3252 s
->flush_n_restarts
= r
;
3253 } else if (streq(key
, "reload-begin-usec")) {
3254 r
= deserialize_usec(value
, &s
->reload_begin_usec
);
3256 log_unit_debug_errno(u
, r
, "Failed to parse serialized reload begin timestamp '%s', ignoring: %m", value
);
3258 log_unit_debug(u
, "Unknown serialization key: %s", key
);
3263 _pure_
static UnitActiveState
service_active_state(Unit
*u
) {
3264 const UnitActiveState
*table
;
3268 table
= SERVICE(u
)->type
== SERVICE_IDLE
? state_translation_table_idle
: state_translation_table
;
3270 return table
[SERVICE(u
)->state
];
3273 static const char *service_sub_state_to_string(Unit
*u
) {
3276 return service_state_to_string(SERVICE(u
)->state
);
3279 static bool service_may_gc(Unit
*u
) {
3280 Service
*s
= SERVICE(u
);
3284 /* Never clean up services that still have a process around, even if the service is formally dead. Note that
3285 * unit_may_gc() already checked our cgroup for us, we just check our two additional PIDs, too, in case they
3286 * have moved outside of the cgroup. */
3288 if (main_pid_good(s
) > 0 ||
3289 control_pid_good(s
) > 0)
3295 static int service_retry_pid_file(Service
*s
) {
3298 assert(s
->pid_file
);
3299 assert(IN_SET(s
->state
, SERVICE_START
, SERVICE_START_POST
));
3301 r
= service_load_pid_file(s
, false);
3305 service_unwatch_pid_file(s
);
3307 service_enter_running(s
, SERVICE_SUCCESS
);
3311 static int service_watch_pid_file(Service
*s
) {
3314 log_unit_debug(UNIT(s
), "Setting watch for PID file %s", s
->pid_file_pathspec
->path
);
3316 r
= path_spec_watch(s
->pid_file_pathspec
, service_dispatch_inotify_io
);
3320 /* the pidfile might have appeared just before we set the watch */
3321 log_unit_debug(UNIT(s
), "Trying to read PID file %s in case it changed", s
->pid_file_pathspec
->path
);
3322 service_retry_pid_file(s
);
3326 log_unit_error_errno(UNIT(s
), r
, "Failed to set a watch for PID file %s: %m", s
->pid_file_pathspec
->path
);
3327 service_unwatch_pid_file(s
);
3331 static int service_demand_pid_file(Service
*s
) {
3334 assert(s
->pid_file
);
3335 assert(!s
->pid_file_pathspec
);
3337 ps
= new0(PathSpec
, 1);
3342 ps
->path
= strdup(s
->pid_file
);
3348 path_simplify(ps
->path
);
3350 /* PATH_CHANGED would not be enough. There are daemons (sendmail) that
3351 * keep their PID file open all the time. */
3352 ps
->type
= PATH_MODIFIED
;
3353 ps
->inotify_fd
= -EBADF
;
3355 s
->pid_file_pathspec
= ps
;
3357 return service_watch_pid_file(s
);
3360 static int service_dispatch_inotify_io(sd_event_source
*source
, int fd
, uint32_t events
, void *userdata
) {
3361 PathSpec
*p
= ASSERT_PTR(userdata
);
3364 s
= SERVICE(p
->unit
);
3368 assert(IN_SET(s
->state
, SERVICE_START
, SERVICE_START_POST
));
3369 assert(s
->pid_file_pathspec
);
3370 assert(path_spec_owns_inotify_fd(s
->pid_file_pathspec
, fd
));
3372 log_unit_debug(UNIT(s
), "inotify event");
3374 if (path_spec_fd_event(p
, events
) < 0)
3377 if (service_retry_pid_file(s
) == 0)
3380 if (service_watch_pid_file(s
) < 0)
3386 service_unwatch_pid_file(s
);
3387 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_RESOURCES
);
3391 static int service_dispatch_exec_io(sd_event_source
*source
, int fd
, uint32_t events
, void *userdata
) {
3392 Service
*s
= SERVICE(userdata
);
3396 log_unit_debug(UNIT(s
), "got exec-fd event");
3398 /* If Type=exec is set, we'll consider a service started successfully the instant we invoked execve()
3399 * successfully for it. We implement this through a pipe() towards the child, which the kernel automatically
3400 * closes for us due to O_CLOEXEC on execve() in the child, which then triggers EOF on the pipe in the
3401 * parent. We need to be careful however, as there are other reasons that we might cause the child's side of
3402 * the pipe to be closed (for example, a simple exit()). To deal with that we'll ignore EOFs on the pipe unless
3403 * the child signalled us first that it is about to call the execve(). It does so by sending us a simple
3404 * non-zero byte via the pipe. We also provide the child with a way to inform us in case execve() failed: if it
3405 * sends a zero byte we'll ignore POLLHUP on the fd again. */
3411 n
= read(fd
, &x
, sizeof(x
));
3413 if (errno
== EAGAIN
) /* O_NONBLOCK in effect → everything queued has now been processed. */
3416 return log_unit_error_errno(UNIT(s
), errno
, "Failed to read from exec_fd: %m");
3418 if (n
== 0) { /* EOF → the event we are waiting for */
3420 s
->exec_fd_event_source
= sd_event_source_disable_unref(s
->exec_fd_event_source
);
3422 if (s
->exec_fd_hot
) { /* Did the child tell us to expect EOF now? */
3423 log_unit_debug(UNIT(s
), "Got EOF on exec-fd");
3425 s
->exec_fd_hot
= false;
3427 /* Nice! This is what we have been waiting for. Transition to next state. */
3428 if (s
->type
== SERVICE_EXEC
&& s
->state
== SERVICE_START
)
3429 service_enter_start_post(s
);
3431 log_unit_debug(UNIT(s
), "Got EOF on exec-fd while it was disabled, ignoring.");
3436 /* A byte was read → this turns on/off the exec fd logic */
3437 assert(n
== sizeof(x
));
3444 static void service_notify_cgroup_empty_event(Unit
*u
) {
3445 Service
*s
= SERVICE(u
);
3449 log_unit_debug(u
, "Control group is empty.");
3453 /* Waiting for SIGCHLD is usually more interesting,
3454 * because it includes return codes/signals. Which is
3455 * why we ignore the cgroup events for most cases,
3456 * except when we don't know pid which to expect the
3460 if (IN_SET(s
->type
, SERVICE_NOTIFY
, SERVICE_NOTIFY_RELOAD
) &&
3461 main_pid_good(s
) == 0 &&
3462 control_pid_good(s
) == 0) {
3463 /* No chance of getting a ready notification anymore */
3464 service_enter_stop_post(s
, SERVICE_FAILURE_PROTOCOL
);
3468 if (s
->exit_type
== SERVICE_EXIT_CGROUP
&& main_pid_good(s
) <= 0)
3469 service_enter_start_post(s
);
3472 case SERVICE_START_POST
:
3473 if (s
->pid_file_pathspec
&&
3474 main_pid_good(s
) == 0 &&
3475 control_pid_good(s
) == 0) {
3477 /* Give up hoping for the daemon to write its PID file */
3478 log_unit_warning(u
, "Daemon never wrote its PID file. Failing.");
3480 service_unwatch_pid_file(s
);
3481 if (s
->state
== SERVICE_START
)
3482 service_enter_stop_post(s
, SERVICE_FAILURE_PROTOCOL
);
3484 service_enter_stop(s
, SERVICE_FAILURE_PROTOCOL
);
3488 case SERVICE_RUNNING
:
3489 /* service_enter_running() will figure out what to do */
3490 service_enter_running(s
, SERVICE_SUCCESS
);
3493 case SERVICE_STOP_WATCHDOG
:
3494 case SERVICE_STOP_SIGTERM
:
3495 case SERVICE_STOP_SIGKILL
:
3497 if (main_pid_good(s
) <= 0 && control_pid_good(s
) <= 0)
3498 service_enter_stop_post(s
, SERVICE_SUCCESS
);
3502 case SERVICE_STOP_POST
:
3503 case SERVICE_FINAL_WATCHDOG
:
3504 case SERVICE_FINAL_SIGTERM
:
3505 case SERVICE_FINAL_SIGKILL
:
3506 if (main_pid_good(s
) <= 0 && control_pid_good(s
) <= 0)
3507 service_enter_dead(s
, SERVICE_SUCCESS
, true);
3511 /* If the cgroup empty notification comes when the unit is not active, we must have failed to clean
3512 * up the cgroup earlier and should do it now. */
3514 case SERVICE_FAILED
:
3515 unit_prune_cgroup(u
);
3523 static void service_notify_cgroup_oom_event(Unit
*u
, bool managed_oom
) {
3524 Service
*s
= SERVICE(u
);
3527 log_unit_debug(u
, "Process(es) of control group were killed by systemd-oomd.");
3529 log_unit_debug(u
, "Process of control group was killed by the OOM killer.");
3531 if (s
->oom_policy
== OOM_CONTINUE
)
3536 case SERVICE_CONDITION
:
3537 case SERVICE_START_PRE
:
3539 case SERVICE_START_POST
:
3541 if (s
->oom_policy
== OOM_STOP
)
3542 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_OOM_KILL
);
3543 else if (s
->oom_policy
== OOM_KILL
)
3544 service_enter_signal(s
, SERVICE_STOP_SIGKILL
, SERVICE_FAILURE_OOM_KILL
);
3548 case SERVICE_EXITED
:
3549 case SERVICE_RUNNING
:
3550 if (s
->oom_policy
== OOM_STOP
)
3551 service_enter_stop(s
, SERVICE_FAILURE_OOM_KILL
);
3552 else if (s
->oom_policy
== OOM_KILL
)
3553 service_enter_signal(s
, SERVICE_STOP_SIGKILL
, SERVICE_FAILURE_OOM_KILL
);
3557 case SERVICE_STOP_WATCHDOG
:
3558 case SERVICE_STOP_SIGTERM
:
3559 service_enter_signal(s
, SERVICE_STOP_SIGKILL
, SERVICE_FAILURE_OOM_KILL
);
3562 case SERVICE_STOP_SIGKILL
:
3563 case SERVICE_FINAL_SIGKILL
:
3564 if (s
->result
== SERVICE_SUCCESS
)
3565 s
->result
= SERVICE_FAILURE_OOM_KILL
;
3568 case SERVICE_STOP_POST
:
3569 case SERVICE_FINAL_SIGTERM
:
3570 service_enter_signal(s
, SERVICE_FINAL_SIGKILL
, SERVICE_FAILURE_OOM_KILL
);
3578 static void service_sigchld_event(Unit
*u
, pid_t pid
, int code
, int status
) {
3579 bool notify_dbus
= true;
3580 Service
*s
= SERVICE(u
);
3582 ExitClean clean_mode
;
3587 /* Oneshot services and non-SERVICE_EXEC_START commands should not be
3588 * considered daemons as they are typically not long running. */
3589 if (s
->type
== SERVICE_ONESHOT
|| (s
->control_pid
== pid
&& s
->control_command_id
!= SERVICE_EXEC_START
))
3590 clean_mode
= EXIT_CLEAN_COMMAND
;
3592 clean_mode
= EXIT_CLEAN_DAEMON
;
3594 if (is_clean_exit(code
, status
, clean_mode
, &s
->success_status
))
3595 f
= SERVICE_SUCCESS
;
3596 else if (code
== CLD_EXITED
)
3597 f
= SERVICE_FAILURE_EXIT_CODE
;
3598 else if (code
== CLD_KILLED
)
3599 f
= SERVICE_FAILURE_SIGNAL
;
3600 else if (code
== CLD_DUMPED
)
3601 f
= SERVICE_FAILURE_CORE_DUMP
;
3603 assert_not_reached();
3605 if (s
->main_pid
== pid
) {
3606 /* Clean up the exec_fd event source. We want to do this here, not later in
3607 * service_set_state(), because service_enter_stop_post() calls service_spawn().
3608 * The source owns its end of the pipe, so this will close that too. */
3609 s
->exec_fd_event_source
= sd_event_source_disable_unref(s
->exec_fd_event_source
);
3611 /* Forking services may occasionally move to a new PID.
3612 * As long as they update the PID file before exiting the old
3613 * PID, they're fine. */
3614 if (service_load_pid_file(s
, false) > 0)
3618 exec_status_exit(&s
->main_exec_status
, &s
->exec_context
, pid
, code
, status
);
3620 if (s
->main_command
) {
3621 /* If this is not a forking service than the
3622 * main process got started and hence we copy
3623 * the exit status so that it is recorded both
3624 * as main and as control process exit
3627 s
->main_command
->exec_status
= s
->main_exec_status
;
3629 if (s
->main_command
->flags
& EXEC_COMMAND_IGNORE_FAILURE
)
3630 f
= SERVICE_SUCCESS
;
3631 } else if (s
->exec_command
[SERVICE_EXEC_START
]) {
3633 /* If this is a forked process, then we should
3634 * ignore the return value if this was
3635 * configured for the starter process */
3637 if (s
->exec_command
[SERVICE_EXEC_START
]->flags
& EXEC_COMMAND_IGNORE_FAILURE
)
3638 f
= SERVICE_SUCCESS
;
3641 unit_log_process_exit(
3644 service_exec_command_to_string(SERVICE_EXEC_START
),
3645 f
== SERVICE_SUCCESS
,
3648 if (s
->result
== SERVICE_SUCCESS
)
3651 if (s
->main_command
&&
3652 s
->main_command
->command_next
&&
3653 s
->type
== SERVICE_ONESHOT
&&
3654 f
== SERVICE_SUCCESS
) {
3656 /* There is another command to execute, so let's do that. */
3658 log_unit_debug(u
, "Running next main command for state %s.", service_state_to_string(s
->state
));
3659 service_run_next_main(s
);
3662 s
->main_command
= NULL
;
3664 /* Services with ExitType=cgroup do not act on main PID exiting, unless the cgroup is
3666 if (s
->exit_type
== SERVICE_EXIT_MAIN
|| cgroup_good(s
) <= 0) {
3667 /* The service exited, so the service is officially gone. */
3670 case SERVICE_START_POST
:
3671 case SERVICE_RELOAD
:
3672 case SERVICE_RELOAD_SIGNAL
:
3673 case SERVICE_RELOAD_NOTIFY
:
3674 /* If neither main nor control processes are running then the current
3675 * state can never exit cleanly, hence immediately terminate the
3677 if (control_pid_good(s
) <= 0)
3678 service_enter_stop(s
, f
);
3680 /* Otherwise need to wait until the operation is done. */
3684 /* Need to wait until the operation is done. */
3688 if (s
->type
== SERVICE_ONESHOT
) {
3689 /* This was our main goal, so let's go on */
3690 if (f
== SERVICE_SUCCESS
)
3691 service_enter_start_post(s
);
3693 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
3695 } else if (IN_SET(s
->type
, SERVICE_NOTIFY
, SERVICE_NOTIFY_RELOAD
)) {
3696 /* Only enter running through a notification, so that the
3697 * SERVICE_START state signifies that no ready notification
3698 * has been received */
3699 if (f
!= SERVICE_SUCCESS
)
3700 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
3701 else if (!s
->remain_after_exit
|| service_get_notify_access(s
) == NOTIFY_MAIN
)
3702 /* The service has never been and will never be active */
3703 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_PROTOCOL
);
3708 case SERVICE_RUNNING
:
3709 service_enter_running(s
, f
);
3712 case SERVICE_STOP_WATCHDOG
:
3713 case SERVICE_STOP_SIGTERM
:
3714 case SERVICE_STOP_SIGKILL
:
3716 if (control_pid_good(s
) <= 0)
3717 service_enter_stop_post(s
, f
);
3719 /* If there is still a control process, wait for that first */
3722 case SERVICE_STOP_POST
:
3724 if (control_pid_good(s
) <= 0)
3725 service_enter_signal(s
, SERVICE_FINAL_SIGTERM
, f
);
3729 case SERVICE_FINAL_WATCHDOG
:
3730 case SERVICE_FINAL_SIGTERM
:
3731 case SERVICE_FINAL_SIGKILL
:
3733 if (control_pid_good(s
) <= 0)
3734 service_enter_dead(s
, f
, true);
3738 assert_not_reached();
3743 } else if (s
->control_pid
== pid
) {
3749 if (s
->control_command
) {
3750 exec_status_exit(&s
->control_command
->exec_status
, &s
->exec_context
, pid
, code
, status
);
3752 if (s
->control_command
->flags
& EXEC_COMMAND_IGNORE_FAILURE
)
3753 f
= SERVICE_SUCCESS
;
3756 /* ExecCondition= calls that exit with (0, 254] should invoke skip-like behavior instead of failing */
3757 if (s
->state
== SERVICE_CONDITION
) {
3758 if (f
== SERVICE_FAILURE_EXIT_CODE
&& status
< 255) {
3759 UNIT(s
)->condition_result
= false;
3760 f
= SERVICE_SKIP_CONDITION
;
3762 } else if (f
== SERVICE_SUCCESS
) {
3763 UNIT(s
)->condition_result
= true;
3768 kind
= "Condition check process";
3770 kind
= "Control process";
3771 success
= f
== SERVICE_SUCCESS
;
3774 unit_log_process_exit(
3777 service_exec_command_to_string(s
->control_command_id
),
3781 if (s
->state
!= SERVICE_RELOAD
&& s
->result
== SERVICE_SUCCESS
)
3784 if (s
->control_command
&&
3785 s
->control_command
->command_next
&&
3786 f
== SERVICE_SUCCESS
) {
3788 /* There is another command to * execute, so let's do that. */
3790 log_unit_debug(u
, "Running next control command for state %s.", service_state_to_string(s
->state
));
3791 service_run_next_control(s
);
3794 /* No further commands for this step, so let's figure out what to do next */
3796 s
->control_command
= NULL
;
3797 s
->control_command_id
= _SERVICE_EXEC_COMMAND_INVALID
;
3799 log_unit_debug(u
, "Got final SIGCHLD for state %s.", service_state_to_string(s
->state
));
3803 case SERVICE_CONDITION
:
3804 if (f
== SERVICE_SUCCESS
)
3805 service_enter_start_pre(s
);
3807 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
3810 case SERVICE_START_PRE
:
3811 if (f
== SERVICE_SUCCESS
)
3812 service_enter_start(s
);
3814 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
3818 if (s
->type
!= SERVICE_FORKING
)
3819 /* Maybe spurious event due to a reload that changed the type? */
3822 if (f
!= SERVICE_SUCCESS
) {
3823 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
3828 bool has_start_post
;
3831 /* Let's try to load the pid file here if we can.
3832 * The PID file might actually be created by a START_POST
3833 * script. In that case don't worry if the loading fails. */
3835 has_start_post
= s
->exec_command
[SERVICE_EXEC_START_POST
];
3836 r
= service_load_pid_file(s
, !has_start_post
);
3837 if (!has_start_post
&& r
< 0) {
3838 r
= service_demand_pid_file(s
);
3839 if (r
< 0 || cgroup_good(s
) == 0)
3840 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_PROTOCOL
);
3844 service_search_main_pid(s
);
3846 service_enter_start_post(s
);
3849 case SERVICE_START_POST
:
3850 if (f
!= SERVICE_SUCCESS
) {
3851 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
3858 r
= service_load_pid_file(s
, true);
3860 r
= service_demand_pid_file(s
);
3861 if (r
< 0 || cgroup_good(s
) == 0)
3862 service_enter_stop(s
, SERVICE_FAILURE_PROTOCOL
);
3866 service_search_main_pid(s
);
3868 service_enter_running(s
, SERVICE_SUCCESS
);
3871 case SERVICE_RELOAD
:
3872 case SERVICE_RELOAD_SIGNAL
:
3873 case SERVICE_RELOAD_NOTIFY
:
3874 if (f
== SERVICE_SUCCESS
)
3875 if (service_load_pid_file(s
, true) < 0)
3876 service_search_main_pid(s
);
3878 s
->reload_result
= f
;
3880 /* If the last notification we received from the service process indicates
3881 * we are still reloading, then don't leave reloading state just yet, just
3882 * transition into SERVICE_RELOAD_NOTIFY, to wait for the READY=1 coming,
3884 if (s
->notify_state
== NOTIFY_RELOADING
)
3885 service_set_state(s
, SERVICE_RELOAD_NOTIFY
);
3887 service_enter_running(s
, SERVICE_SUCCESS
);
3891 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
3894 case SERVICE_STOP_WATCHDOG
:
3895 case SERVICE_STOP_SIGTERM
:
3896 case SERVICE_STOP_SIGKILL
:
3897 if (main_pid_good(s
) <= 0)
3898 service_enter_stop_post(s
, f
);
3900 /* If there is still a service process around, wait until
3901 * that one quit, too */
3904 case SERVICE_STOP_POST
:
3905 if (main_pid_good(s
) <= 0)
3906 service_enter_signal(s
, SERVICE_FINAL_SIGTERM
, f
);
3909 case SERVICE_FINAL_WATCHDOG
:
3910 case SERVICE_FINAL_SIGTERM
:
3911 case SERVICE_FINAL_SIGKILL
:
3912 if (main_pid_good(s
) <= 0)
3913 service_enter_dead(s
, f
, true);
3916 case SERVICE_CLEANING
:
3918 if (s
->clean_result
== SERVICE_SUCCESS
)
3919 s
->clean_result
= f
;
3921 service_enter_dead(s
, SERVICE_SUCCESS
, false);
3925 assert_not_reached();
3928 } else /* Neither control nor main PID? If so, don't notify about anything */
3929 notify_dbus
= false;
3931 /* Notify clients about changed exit status */
3933 unit_add_to_dbus_queue(u
);
3935 /* We watch the main/control process otherwise we can't retrieve the unit they
3936 * belong to with cgroupv1. But if they are not our direct child, we won't get a
3937 * SIGCHLD for them. Therefore we need to look for others to watch so we can
3938 * detect when the cgroup becomes empty. Note that the control process is always
3939 * our child so it's pointless to watch all other processes. */
3940 if (!control_pid_good(s
))
3941 if (!s
->main_pid_known
|| s
->main_pid_alien
)
3942 (void) unit_enqueue_rewatch_pids(u
);
3945 static int service_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
) {
3946 Service
*s
= SERVICE(userdata
);
3949 assert(source
== s
->timer_event_source
);
3953 case SERVICE_CONDITION
:
3954 case SERVICE_START_PRE
:
3956 case SERVICE_START_POST
:
3957 switch (s
->timeout_start_failure_mode
) {
3959 case SERVICE_TIMEOUT_TERMINATE
:
3960 log_unit_warning(UNIT(s
), "%s operation timed out. Terminating.", service_state_to_string(s
->state
));
3961 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_TIMEOUT
);
3964 case SERVICE_TIMEOUT_ABORT
:
3965 log_unit_warning(UNIT(s
), "%s operation timed out. Aborting.", service_state_to_string(s
->state
));
3966 service_enter_signal(s
, SERVICE_STOP_WATCHDOG
, SERVICE_FAILURE_TIMEOUT
);
3969 case SERVICE_TIMEOUT_KILL
:
3970 if (s
->kill_context
.send_sigkill
) {
3971 log_unit_warning(UNIT(s
), "%s operation timed out. Killing.", service_state_to_string(s
->state
));
3972 service_enter_signal(s
, SERVICE_STOP_SIGKILL
, SERVICE_FAILURE_TIMEOUT
);
3974 log_unit_warning(UNIT(s
), "%s operation timed out. Skipping SIGKILL.", service_state_to_string(s
->state
));
3975 service_enter_stop_post(s
, SERVICE_FAILURE_TIMEOUT
);
3980 assert_not_reached();
3984 case SERVICE_RUNNING
:
3985 log_unit_warning(UNIT(s
), "Service reached runtime time limit. Stopping.");
3986 service_enter_stop(s
, SERVICE_FAILURE_TIMEOUT
);
3989 case SERVICE_RELOAD
:
3990 case SERVICE_RELOAD_SIGNAL
:
3991 case SERVICE_RELOAD_NOTIFY
:
3992 log_unit_warning(UNIT(s
), "Reload operation timed out. Killing reload process.");
3993 service_kill_control_process(s
);
3994 s
->reload_result
= SERVICE_FAILURE_TIMEOUT
;
3995 service_enter_running(s
, SERVICE_SUCCESS
);
3999 switch (s
->timeout_stop_failure_mode
) {
4001 case SERVICE_TIMEOUT_TERMINATE
:
4002 log_unit_warning(UNIT(s
), "Stopping timed out. Terminating.");
4003 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_TIMEOUT
);
4006 case SERVICE_TIMEOUT_ABORT
:
4007 log_unit_warning(UNIT(s
), "Stopping timed out. Aborting.");
4008 service_enter_signal(s
, SERVICE_STOP_WATCHDOG
, SERVICE_FAILURE_TIMEOUT
);
4011 case SERVICE_TIMEOUT_KILL
:
4012 if (s
->kill_context
.send_sigkill
) {
4013 log_unit_warning(UNIT(s
), "Stopping timed out. Killing.");
4014 service_enter_signal(s
, SERVICE_STOP_SIGKILL
, SERVICE_FAILURE_TIMEOUT
);
4016 log_unit_warning(UNIT(s
), "Stopping timed out. Skipping SIGKILL.");
4017 service_enter_stop_post(s
, SERVICE_FAILURE_TIMEOUT
);
4022 assert_not_reached();
4026 case SERVICE_STOP_WATCHDOG
:
4027 if (s
->kill_context
.send_sigkill
) {
4028 log_unit_warning(UNIT(s
), "State 'stop-watchdog' timed out. Killing.");
4029 service_enter_signal(s
, SERVICE_STOP_SIGKILL
, SERVICE_FAILURE_TIMEOUT
);
4031 log_unit_warning(UNIT(s
), "State 'stop-watchdog' timed out. Skipping SIGKILL.");
4032 service_enter_stop_post(s
, SERVICE_FAILURE_TIMEOUT
);
4036 case SERVICE_STOP_SIGTERM
:
4037 if (s
->timeout_stop_failure_mode
== SERVICE_TIMEOUT_ABORT
) {
4038 log_unit_warning(UNIT(s
), "State 'stop-sigterm' timed out. Aborting.");
4039 service_enter_signal(s
, SERVICE_STOP_WATCHDOG
, SERVICE_FAILURE_TIMEOUT
);
4040 } else if (s
->kill_context
.send_sigkill
) {
4041 log_unit_warning(UNIT(s
), "State 'stop-sigterm' timed out. Killing.");
4042 service_enter_signal(s
, SERVICE_STOP_SIGKILL
, SERVICE_FAILURE_TIMEOUT
);
4044 log_unit_warning(UNIT(s
), "State 'stop-sigterm' timed out. Skipping SIGKILL.");
4045 service_enter_stop_post(s
, SERVICE_FAILURE_TIMEOUT
);
4050 case SERVICE_STOP_SIGKILL
:
4051 /* Uh, we sent a SIGKILL and it is still not gone?
4052 * Must be something we cannot kill, so let's just be
4053 * weirded out and continue */
4055 log_unit_warning(UNIT(s
), "Processes still around after SIGKILL. Ignoring.");
4056 service_enter_stop_post(s
, SERVICE_FAILURE_TIMEOUT
);
4059 case SERVICE_STOP_POST
:
4060 switch (s
->timeout_stop_failure_mode
) {
4062 case SERVICE_TIMEOUT_TERMINATE
:
4063 log_unit_warning(UNIT(s
), "State 'stop-post' timed out. Terminating.");
4064 service_enter_signal(s
, SERVICE_FINAL_SIGTERM
, SERVICE_FAILURE_TIMEOUT
);
4067 case SERVICE_TIMEOUT_ABORT
:
4068 log_unit_warning(UNIT(s
), "State 'stop-post' timed out. Aborting.");
4069 service_enter_signal(s
, SERVICE_FINAL_WATCHDOG
, SERVICE_FAILURE_TIMEOUT
);
4072 case SERVICE_TIMEOUT_KILL
:
4073 if (s
->kill_context
.send_sigkill
) {
4074 log_unit_warning(UNIT(s
), "State 'stop-post' timed out. Killing.");
4075 service_enter_signal(s
, SERVICE_FINAL_SIGKILL
, SERVICE_FAILURE_TIMEOUT
);
4077 log_unit_warning(UNIT(s
), "State 'stop-post' timed out. Skipping SIGKILL. Entering failed mode.");
4078 service_enter_dead(s
, SERVICE_FAILURE_TIMEOUT
, false);
4083 assert_not_reached();
4087 case SERVICE_FINAL_WATCHDOG
:
4088 if (s
->kill_context
.send_sigkill
) {
4089 log_unit_warning(UNIT(s
), "State 'final-watchdog' timed out. Killing.");
4090 service_enter_signal(s
, SERVICE_FINAL_SIGKILL
, SERVICE_FAILURE_TIMEOUT
);
4092 log_unit_warning(UNIT(s
), "State 'final-watchdog' timed out. Skipping SIGKILL. Entering failed mode.");
4093 service_enter_dead(s
, SERVICE_FAILURE_TIMEOUT
, false);
4097 case SERVICE_FINAL_SIGTERM
:
4098 if (s
->timeout_stop_failure_mode
== SERVICE_TIMEOUT_ABORT
) {
4099 log_unit_warning(UNIT(s
), "State 'final-sigterm' timed out. Aborting.");
4100 service_enter_signal(s
, SERVICE_FINAL_WATCHDOG
, SERVICE_FAILURE_TIMEOUT
);
4101 } else if (s
->kill_context
.send_sigkill
) {
4102 log_unit_warning(UNIT(s
), "State 'final-sigterm' timed out. Killing.");
4103 service_enter_signal(s
, SERVICE_FINAL_SIGKILL
, SERVICE_FAILURE_TIMEOUT
);
4105 log_unit_warning(UNIT(s
), "State 'final-sigterm' timed out. Skipping SIGKILL. Entering failed mode.");
4106 service_enter_dead(s
, SERVICE_FAILURE_TIMEOUT
, false);
4111 case SERVICE_FINAL_SIGKILL
:
4112 log_unit_warning(UNIT(s
), "Processes still around after final SIGKILL. Entering failed mode.");
4113 service_enter_dead(s
, SERVICE_FAILURE_TIMEOUT
, true);
4116 case SERVICE_AUTO_RESTART
:
4117 if (s
->restart_usec
> 0)
4118 log_unit_debug(UNIT(s
),
4119 "Service RestartSec=%s expired, scheduling restart.",
4120 FORMAT_TIMESPAN(s
->restart_usec
, USEC_PER_SEC
));
4122 log_unit_debug(UNIT(s
),
4123 "Service has no hold-off time (RestartSec=0), scheduling restart.");
4125 service_enter_restart(s
);
4128 case SERVICE_CLEANING
:
4129 log_unit_warning(UNIT(s
), "Cleaning timed out. killing.");
4131 if (s
->clean_result
== SERVICE_SUCCESS
)
4132 s
->clean_result
= SERVICE_FAILURE_TIMEOUT
;
4134 service_enter_signal(s
, SERVICE_FINAL_SIGKILL
, 0);
4138 assert_not_reached();
4144 static int service_dispatch_watchdog(sd_event_source
*source
, usec_t usec
, void *userdata
) {
4145 Service
*s
= SERVICE(userdata
);
4146 usec_t watchdog_usec
;
4149 assert(source
== s
->watchdog_event_source
);
4151 watchdog_usec
= service_get_watchdog_usec(s
);
4153 if (UNIT(s
)->manager
->service_watchdogs
) {
4154 log_unit_error(UNIT(s
), "Watchdog timeout (limit %s)!",
4155 FORMAT_TIMESPAN(watchdog_usec
, 1));
4157 service_enter_signal(s
, SERVICE_STOP_WATCHDOG
, SERVICE_FAILURE_WATCHDOG
);
4159 log_unit_warning(UNIT(s
), "Watchdog disabled! Ignoring watchdog timeout (limit %s)!",
4160 FORMAT_TIMESPAN(watchdog_usec
, 1));
4165 static bool service_notify_message_authorized(Service
*s
, pid_t pid
, FDSet
*fds
) {
4168 NotifyAccess notify_access
= service_get_notify_access(s
);
4170 if (notify_access
== NOTIFY_NONE
) {
4171 log_unit_warning(UNIT(s
), "Got notification message from PID "PID_FMT
", but reception is disabled.", pid
);
4175 if (notify_access
== NOTIFY_MAIN
&& pid
!= s
->main_pid
) {
4176 if (s
->main_pid
!= 0)
4177 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
);
4179 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
);
4184 if (notify_access
== NOTIFY_EXEC
&& pid
!= s
->main_pid
&& pid
!= s
->control_pid
) {
4185 if (s
->main_pid
!= 0 && s
->control_pid
!= 0)
4186 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
,
4187 pid
, s
->main_pid
, s
->control_pid
);
4188 else if (s
->main_pid
!= 0)
4189 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
);
4190 else if (s
->control_pid
!= 0)
4191 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
);
4193 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
);
4201 static void service_force_watchdog(Service
*s
) {
4202 if (!UNIT(s
)->manager
->service_watchdogs
)
4205 log_unit_error(UNIT(s
), "Watchdog request (last status: %s)!",
4206 s
->status_text
?: "<unset>");
4208 service_enter_signal(s
, SERVICE_STOP_WATCHDOG
, SERVICE_FAILURE_WATCHDOG
);
4211 static void service_notify_message(
4213 const struct ucred
*ucred
,
4217 Service
*s
= SERVICE(u
);
4218 bool notify_dbus
= false;
4219 usec_t monotonic_usec
= USEC_INFINITY
;
4226 if (!service_notify_message_authorized(s
, ucred
->pid
, fds
))
4229 if (DEBUG_LOGGING
) {
4230 _cleanup_free_
char *cc
= NULL
;
4232 cc
= strv_join(tags
, ", ");
4233 log_unit_debug(u
, "Got notification message from PID "PID_FMT
" (%s)", ucred
->pid
, isempty(cc
) ? "n/a" : cc
);
4236 /* Interpret MAINPID= */
4237 e
= strv_find_startswith(tags
, "MAINPID=");
4238 if (e
&& IN_SET(s
->state
, SERVICE_START
, SERVICE_START_POST
, SERVICE_RUNNING
, SERVICE_RELOAD
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
)) {
4241 if (parse_pid(e
, &new_main_pid
) < 0)
4242 log_unit_warning(u
, "Failed to parse MAINPID= field in notification message, ignoring: %s", e
);
4243 else if (!s
->main_pid_known
|| new_main_pid
!= s
->main_pid
) {
4245 r
= service_is_suitable_main_pid(s
, new_main_pid
, LOG_WARNING
);
4247 /* The new main PID is a bit suspicious, which is OK if the sender is privileged. */
4249 if (ucred
->uid
== 0) {
4250 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
);
4253 log_unit_debug(u
, "New main PID "PID_FMT
" does not belong to service, refusing.", new_main_pid
);
4256 (void) service_set_main_pid(s
, new_main_pid
);
4258 r
= unit_watch_pid(UNIT(s
), new_main_pid
, false);
4260 log_unit_warning_errno(UNIT(s
), r
, "Failed to watch new main PID "PID_FMT
" for service: %m", new_main_pid
);
4267 /* Parse MONOTONIC_USEC= */
4268 e
= strv_find_startswith(tags
, "MONOTONIC_USEC=");
4270 r
= safe_atou64(e
, &monotonic_usec
);
4272 log_unit_warning_errno(u
, r
, "Failed to parse MONOTONIC_USEC= field in notification message, ignoring: %s", e
);
4275 /* Interpret READY=/STOPPING=/RELOADING=. STOPPING= wins over the others, and READY= over RELOADING= */
4276 if (strv_contains(tags
, "STOPPING=1")) {
4277 s
->notify_state
= NOTIFY_STOPPING
;
4279 if (IN_SET(s
->state
, SERVICE_RUNNING
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
))
4280 service_enter_stop_by_notify(s
);
4284 } else if (strv_contains(tags
, "READY=1")) {
4286 s
->notify_state
= NOTIFY_READY
;
4288 /* Type=notify services inform us about completed initialization with READY=1 */
4289 if (IN_SET(s
->type
, SERVICE_NOTIFY
, SERVICE_NOTIFY_RELOAD
) &&
4290 s
->state
== SERVICE_START
)
4291 service_enter_start_post(s
);
4293 /* Sending READY=1 while we are reloading informs us that the reloading is complete. */
4294 if (s
->state
== SERVICE_RELOAD_NOTIFY
)
4295 service_enter_running(s
, SERVICE_SUCCESS
);
4297 /* Combined RELOADING=1 and READY=1? Then this is indication that the service started and
4298 * immediately finished reloading. */
4299 if (s
->state
== SERVICE_RELOAD_SIGNAL
&&
4300 strv_contains(tags
, "RELOADING=1") &&
4301 monotonic_usec
!= USEC_INFINITY
&&
4302 monotonic_usec
>= s
->reload_begin_usec
) {
4303 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
4305 /* Propagate a reload explicitly */
4306 r
= manager_propagate_reload(UNIT(s
)->manager
, UNIT(s
), JOB_FAIL
, &error
);
4308 log_unit_warning(UNIT(s
), "Failed to schedule propagation of reload, ignoring: %s", bus_error_message(&error
, r
));
4310 service_enter_running(s
, SERVICE_SUCCESS
);
4315 } else if (strv_contains(tags
, "RELOADING=1")) {
4317 s
->notify_state
= NOTIFY_RELOADING
;
4319 /* Sending RELOADING=1 after we send SIGHUP to request a reload will transition
4320 * things to "reload-notify" state, where we'll wait for READY=1 to let us know the
4321 * reload is done. Note that we insist on a timestamp being sent along here, so that
4322 * we know for sure this is a reload cycle initiated *after* we sent the signal */
4323 if (s
->state
== SERVICE_RELOAD_SIGNAL
&&
4324 monotonic_usec
!= USEC_INFINITY
&&
4325 monotonic_usec
>= s
->reload_begin_usec
)
4326 /* Note, we don't call service_enter_reload_by_notify() here, because we
4327 * don't need reload propagation nor do we want to restart the time-out. */
4328 service_set_state(s
, SERVICE_RELOAD_NOTIFY
);
4330 if (s
->state
== SERVICE_RUNNING
)
4331 service_enter_reload_by_notify(s
);
4336 /* Interpret STATUS= */
4337 e
= strv_find_startswith(tags
, "STATUS=");
4339 _cleanup_free_
char *t
= NULL
;
4342 /* Note that this size limit check is mostly paranoia: since the datagram size we are willing
4343 * to process is already limited to NOTIFY_BUFFER_MAX, this limit here should never be hit. */
4344 if (strlen(e
) > STATUS_TEXT_MAX
)
4345 log_unit_warning(u
, "Status message overly long (%zu > %u), ignoring.", strlen(e
), STATUS_TEXT_MAX
);
4346 else if (!utf8_is_valid(e
))
4347 log_unit_warning(u
, "Status message in notification message is not UTF-8 clean, ignoring.");
4355 if (!streq_ptr(s
->status_text
, t
)) {
4356 free_and_replace(s
->status_text
, t
);
4361 /* Interpret NOTIFYACCESS= */
4362 e
= strv_find_startswith(tags
, "NOTIFYACCESS=");
4364 NotifyAccess notify_access
;
4366 notify_access
= notify_access_from_string(e
);
4367 if (notify_access
< 0)
4368 log_unit_warning_errno(u
, notify_access
,
4369 "Failed to parse NOTIFYACCESS= field value '%s' in notification message, ignoring: %m", e
);
4371 /* We don't need to check whether the new access mode is more strict than what is
4372 * already in use, since only the privileged process is allowed to change it
4373 * in the first place. */
4374 if (service_get_notify_access(s
) != notify_access
) {
4375 service_override_notify_access(s
, notify_access
);
4380 /* Interpret ERRNO= */
4381 e
= strv_find_startswith(tags
, "ERRNO=");
4385 status_errno
= parse_errno(e
);
4386 if (status_errno
< 0)
4387 log_unit_warning_errno(u
, status_errno
,
4388 "Failed to parse ERRNO= field value '%s' in notification message: %m", e
);
4389 else if (s
->status_errno
!= status_errno
) {
4390 s
->status_errno
= status_errno
;
4395 /* Interpret EXTEND_TIMEOUT= */
4396 e
= strv_find_startswith(tags
, "EXTEND_TIMEOUT_USEC=");
4398 usec_t extend_timeout_usec
;
4399 if (safe_atou64(e
, &extend_timeout_usec
) < 0)
4400 log_unit_warning(u
, "Failed to parse EXTEND_TIMEOUT_USEC=%s", e
);
4402 service_extend_timeout(s
, extend_timeout_usec
);
4405 /* Interpret WATCHDOG= */
4406 e
= strv_find_startswith(tags
, "WATCHDOG=");
4409 service_reset_watchdog(s
);
4410 else if (streq(e
, "trigger"))
4411 service_force_watchdog(s
);
4413 log_unit_warning(u
, "Passed WATCHDOG= field is invalid, ignoring.");
4416 e
= strv_find_startswith(tags
, "WATCHDOG_USEC=");
4418 usec_t watchdog_override_usec
;
4419 if (safe_atou64(e
, &watchdog_override_usec
) < 0)
4420 log_unit_warning(u
, "Failed to parse WATCHDOG_USEC=%s", e
);
4422 service_override_watchdog_timeout(s
, watchdog_override_usec
);
4425 /* Process FD store messages. Either FDSTOREREMOVE=1 for removal, or FDSTORE=1 for addition. In both cases,
4426 * process FDNAME= for picking the file descriptor name to use. Note that FDNAME= is required when removing
4427 * fds, but optional when pushing in new fds, for compatibility reasons. */
4428 if (strv_contains(tags
, "FDSTOREREMOVE=1")) {
4431 name
= strv_find_startswith(tags
, "FDNAME=");
4432 if (!name
|| !fdname_is_valid(name
))
4433 log_unit_warning(u
, "FDSTOREREMOVE=1 requested, but no valid file descriptor name passed, ignoring.");
4435 service_remove_fd_store(s
, name
);
4437 } else if (strv_contains(tags
, "FDSTORE=1")) {
4440 name
= strv_find_startswith(tags
, "FDNAME=");
4441 if (name
&& !fdname_is_valid(name
)) {
4442 log_unit_warning(u
, "Passed FDNAME= name is invalid, ignoring.");
4446 (void) service_add_fd_store_set(s
, fds
, name
, !strv_contains(tags
, "FDPOLL=0"));
4449 /* Notify clients about changed status or main pid */
4451 unit_add_to_dbus_queue(u
);
4454 static int service_get_timeout(Unit
*u
, usec_t
*timeout
) {
4455 Service
*s
= SERVICE(u
);
4459 if (!s
->timer_event_source
)
4462 r
= sd_event_source_get_time(s
->timer_event_source
, &t
);
4465 if (t
== USEC_INFINITY
)
4472 static bool pick_up_pid_from_bus_name(Service
*s
) {
4475 /* If the service is running but we have no main PID yet, get it from the owner of the D-Bus name */
4477 return !pid_is_valid(s
->main_pid
) &&
4483 SERVICE_RELOAD_SIGNAL
,
4484 SERVICE_RELOAD_NOTIFY
);
4487 static int bus_name_pid_lookup_callback(sd_bus_message
*reply
, void *userdata
, sd_bus_error
*ret_error
) {
4488 const sd_bus_error
*e
;
4489 Unit
*u
= ASSERT_PTR(userdata
);
4497 s
->bus_name_pid_lookup_slot
= sd_bus_slot_unref(s
->bus_name_pid_lookup_slot
);
4499 if (!s
->bus_name
|| !pick_up_pid_from_bus_name(s
))
4502 e
= sd_bus_message_get_error(reply
);
4504 r
= sd_bus_error_get_errno(e
);
4505 log_warning_errno(r
, "GetConnectionUnixProcessID() failed: %s", bus_error_message(e
, r
));
4509 r
= sd_bus_message_read(reply
, "u", &pid
);
4511 bus_log_parse_error(r
);
4515 if (!pid_is_valid(pid
)) {
4516 log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "GetConnectionUnixProcessID() returned invalid PID");
4520 log_unit_debug(u
, "D-Bus name %s is now owned by process " PID_FMT
, s
->bus_name
, (pid_t
) pid
);
4522 (void) service_set_main_pid(s
, pid
);
4523 (void) unit_watch_pid(UNIT(s
), pid
, false);
4527 static void service_bus_name_owner_change(Unit
*u
, const char *new_owner
) {
4529 Service
*s
= SERVICE(u
);
4535 log_unit_debug(u
, "D-Bus name %s now owned by %s", s
->bus_name
, new_owner
);
4537 log_unit_debug(u
, "D-Bus name %s now not owned by anyone.", s
->bus_name
);
4539 s
->bus_name_good
= new_owner
;
4541 /* Track the current owner, so we can reconstruct changes after a daemon reload */
4542 r
= free_and_strdup(&s
->bus_name_owner
, new_owner
);
4544 log_unit_error_errno(u
, r
, "Unable to set new bus name owner %s: %m", new_owner
);
4548 if (s
->type
== SERVICE_DBUS
) {
4550 /* service_enter_running() will figure out what to
4552 if (s
->state
== SERVICE_RUNNING
)
4553 service_enter_running(s
, SERVICE_SUCCESS
);
4554 else if (s
->state
== SERVICE_START
&& new_owner
)
4555 service_enter_start_post(s
);
4557 } else if (new_owner
&& pick_up_pid_from_bus_name(s
)) {
4559 /* Try to acquire PID from bus service */
4561 s
->bus_name_pid_lookup_slot
= sd_bus_slot_unref(s
->bus_name_pid_lookup_slot
);
4563 r
= sd_bus_call_method_async(
4564 u
->manager
->api_bus
,
4565 &s
->bus_name_pid_lookup_slot
,
4566 "org.freedesktop.DBus",
4567 "/org/freedesktop/DBus",
4568 "org.freedesktop.DBus",
4569 "GetConnectionUnixProcessID",
4570 bus_name_pid_lookup_callback
,
4575 log_debug_errno(r
, "Failed to request owner PID of service name, ignoring: %m");
4579 int service_set_socket_fd(
4584 bool selinux_context_net
) {
4586 _cleanup_free_
char *peer_text
= NULL
;
4592 /* This is called by the socket code when instantiating a new service for a stream socket and the socket needs
4593 * to be configured. We take ownership of the passed fd on success. */
4595 if (UNIT(s
)->load_state
!= UNIT_LOADED
)
4598 if (s
->socket_fd
>= 0)
4601 assert(!s
->socket_peer
);
4603 if (s
->state
!= SERVICE_DEAD
)
4606 if (getpeername_pretty(fd
, true, &peer_text
) >= 0) {
4608 if (UNIT(s
)->description
) {
4609 _cleanup_free_
char *a
= NULL
;
4611 a
= strjoin(UNIT(s
)->description
, " (", peer_text
, ")");
4615 r
= unit_set_description(UNIT(s
), a
);
4617 r
= unit_set_description(UNIT(s
), peer_text
);
4622 r
= unit_add_two_dependencies(UNIT(sock
), UNIT_BEFORE
, UNIT_TRIGGERS
, UNIT(s
), false, UNIT_DEPENDENCY_IMPLICIT
);
4627 s
->socket_peer
= socket_peer_ref(peer
);
4628 s
->socket_fd_selinux_context_net
= selinux_context_net
;
4630 unit_ref_set(&s
->accept_socket
, UNIT(s
), UNIT(sock
));
4634 static void service_reset_failed(Unit
*u
) {
4635 Service
*s
= SERVICE(u
);
4639 if (s
->state
== SERVICE_FAILED
)
4640 service_set_state(s
, SERVICE_DEAD
);
4642 s
->result
= SERVICE_SUCCESS
;
4643 s
->reload_result
= SERVICE_SUCCESS
;
4644 s
->clean_result
= SERVICE_SUCCESS
;
4646 s
->flush_n_restarts
= false;
4649 static int service_kill(Unit
*u
, KillWho who
, int signo
, int code
, int value
, sd_bus_error
*error
) {
4650 Service
*s
= SERVICE(u
);
4654 return unit_kill_common(u
, who
, signo
, code
, value
, s
->main_pid
, s
->control_pid
, error
);
4657 static int service_main_pid(Unit
*u
) {
4658 Service
*s
= SERVICE(u
);
4665 static int service_control_pid(Unit
*u
) {
4666 Service
*s
= SERVICE(u
);
4670 return s
->control_pid
;
4673 static bool service_needs_console(Unit
*u
) {
4674 Service
*s
= SERVICE(u
);
4678 /* We provide our own implementation of this here, instead of relying of the generic implementation
4679 * unit_needs_console() provides, since we want to return false if we are in SERVICE_EXITED state. */
4681 if (!exec_context_may_touch_console(&s
->exec_context
))
4684 return IN_SET(s
->state
,
4691 SERVICE_RELOAD_SIGNAL
,
4692 SERVICE_RELOAD_NOTIFY
,
4694 SERVICE_STOP_WATCHDOG
,
4695 SERVICE_STOP_SIGTERM
,
4696 SERVICE_STOP_SIGKILL
,
4698 SERVICE_FINAL_WATCHDOG
,
4699 SERVICE_FINAL_SIGTERM
,
4700 SERVICE_FINAL_SIGKILL
);
4703 static int service_exit_status(Unit
*u
) {
4704 Service
*s
= SERVICE(u
);
4708 if (s
->main_exec_status
.pid
<= 0 ||
4709 !dual_timestamp_is_set(&s
->main_exec_status
.exit_timestamp
))
4712 if (s
->main_exec_status
.code
!= CLD_EXITED
)
4715 return s
->main_exec_status
.status
;
4718 static const char* service_status_text(Unit
*u
) {
4719 Service
*s
= SERVICE(u
);
4723 return s
->status_text
;
4726 static int service_clean(Unit
*u
, ExecCleanMask mask
) {
4727 _cleanup_strv_free_
char **l
= NULL
;
4728 Service
*s
= SERVICE(u
);
4734 if (s
->state
!= SERVICE_DEAD
)
4737 r
= exec_context_get_clean_directories(&s
->exec_context
, u
->manager
->prefix
, mask
, &l
);
4741 if (strv_isempty(l
))
4744 service_unwatch_control_pid(s
);
4745 s
->clean_result
= SERVICE_SUCCESS
;
4746 s
->control_command
= NULL
;
4747 s
->control_command_id
= _SERVICE_EXEC_COMMAND_INVALID
;
4749 r
= service_arm_timer(s
, /* relative= */ true, s
->exec_context
.timeout_clean_usec
);
4753 r
= unit_fork_and_watch_rm_rf(u
, l
, &s
->control_pid
);
4757 service_set_state(s
, SERVICE_CLEANING
);
4762 log_unit_warning_errno(u
, r
, "Failed to initiate cleaning: %m");
4763 s
->clean_result
= SERVICE_FAILURE_RESOURCES
;
4764 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
4768 static int service_can_clean(Unit
*u
, ExecCleanMask
*ret
) {
4769 Service
*s
= SERVICE(u
);
4773 return exec_context_get_clean_mask(&s
->exec_context
, ret
);
4776 static const char *service_finished_job(Unit
*u
, JobType t
, JobResult result
) {
4777 if (t
== JOB_START
&&
4778 result
== JOB_DONE
&&
4779 SERVICE(u
)->type
== SERVICE_ONESHOT
)
4780 return "Finished %s.";
4782 /* Fall back to generic */
4786 static int service_can_start(Unit
*u
) {
4787 Service
*s
= SERVICE(u
);
4792 /* Make sure we don't enter a busy loop of some kind. */
4793 r
= unit_test_start_limit(u
);
4795 service_enter_dead(s
, SERVICE_FAILURE_START_LIMIT_HIT
, false);
4802 static const char* const service_restart_table
[_SERVICE_RESTART_MAX
] = {
4803 [SERVICE_RESTART_NO
] = "no",
4804 [SERVICE_RESTART_ON_SUCCESS
] = "on-success",
4805 [SERVICE_RESTART_ON_FAILURE
] = "on-failure",
4806 [SERVICE_RESTART_ON_ABNORMAL
] = "on-abnormal",
4807 [SERVICE_RESTART_ON_WATCHDOG
] = "on-watchdog",
4808 [SERVICE_RESTART_ON_ABORT
] = "on-abort",
4809 [SERVICE_RESTART_ALWAYS
] = "always",
4812 DEFINE_STRING_TABLE_LOOKUP(service_restart
, ServiceRestart
);
4814 static const char* const service_type_table
[_SERVICE_TYPE_MAX
] = {
4815 [SERVICE_SIMPLE
] = "simple",
4816 [SERVICE_FORKING
] = "forking",
4817 [SERVICE_ONESHOT
] = "oneshot",
4818 [SERVICE_DBUS
] = "dbus",
4819 [SERVICE_NOTIFY
] = "notify",
4820 [SERVICE_NOTIFY_RELOAD
] = "notify-reload",
4821 [SERVICE_IDLE
] = "idle",
4822 [SERVICE_EXEC
] = "exec",
4825 DEFINE_STRING_TABLE_LOOKUP(service_type
, ServiceType
);
4827 static const char* const service_exit_type_table
[_SERVICE_EXIT_TYPE_MAX
] = {
4828 [SERVICE_EXIT_MAIN
] = "main",
4829 [SERVICE_EXIT_CGROUP
] = "cgroup",
4832 DEFINE_STRING_TABLE_LOOKUP(service_exit_type
, ServiceExitType
);
4834 static const char* const service_exec_command_table
[_SERVICE_EXEC_COMMAND_MAX
] = {
4835 [SERVICE_EXEC_CONDITION
] = "ExecCondition",
4836 [SERVICE_EXEC_START_PRE
] = "ExecStartPre",
4837 [SERVICE_EXEC_START
] = "ExecStart",
4838 [SERVICE_EXEC_START_POST
] = "ExecStartPost",
4839 [SERVICE_EXEC_RELOAD
] = "ExecReload",
4840 [SERVICE_EXEC_STOP
] = "ExecStop",
4841 [SERVICE_EXEC_STOP_POST
] = "ExecStopPost",
4844 DEFINE_STRING_TABLE_LOOKUP(service_exec_command
, ServiceExecCommand
);
4846 static const char* const service_exec_ex_command_table
[_SERVICE_EXEC_COMMAND_MAX
] = {
4847 [SERVICE_EXEC_CONDITION
] = "ExecConditionEx",
4848 [SERVICE_EXEC_START_PRE
] = "ExecStartPreEx",
4849 [SERVICE_EXEC_START
] = "ExecStartEx",
4850 [SERVICE_EXEC_START_POST
] = "ExecStartPostEx",
4851 [SERVICE_EXEC_RELOAD
] = "ExecReloadEx",
4852 [SERVICE_EXEC_STOP
] = "ExecStopEx",
4853 [SERVICE_EXEC_STOP_POST
] = "ExecStopPostEx",
4856 DEFINE_STRING_TABLE_LOOKUP(service_exec_ex_command
, ServiceExecCommand
);
4858 static const char* const notify_state_table
[_NOTIFY_STATE_MAX
] = {
4859 [NOTIFY_UNKNOWN
] = "unknown",
4860 [NOTIFY_READY
] = "ready",
4861 [NOTIFY_RELOADING
] = "reloading",
4862 [NOTIFY_STOPPING
] = "stopping",
4865 DEFINE_STRING_TABLE_LOOKUP(notify_state
, NotifyState
);
4867 static const char* const service_result_table
[_SERVICE_RESULT_MAX
] = {
4868 [SERVICE_SUCCESS
] = "success",
4869 [SERVICE_FAILURE_RESOURCES
] = "resources",
4870 [SERVICE_FAILURE_PROTOCOL
] = "protocol",
4871 [SERVICE_FAILURE_TIMEOUT
] = "timeout",
4872 [SERVICE_FAILURE_EXIT_CODE
] = "exit-code",
4873 [SERVICE_FAILURE_SIGNAL
] = "signal",
4874 [SERVICE_FAILURE_CORE_DUMP
] = "core-dump",
4875 [SERVICE_FAILURE_WATCHDOG
] = "watchdog",
4876 [SERVICE_FAILURE_START_LIMIT_HIT
] = "start-limit-hit",
4877 [SERVICE_FAILURE_OOM_KILL
] = "oom-kill",
4878 [SERVICE_SKIP_CONDITION
] = "exec-condition",
4881 DEFINE_STRING_TABLE_LOOKUP(service_result
, ServiceResult
);
4883 static const char* const service_timeout_failure_mode_table
[_SERVICE_TIMEOUT_FAILURE_MODE_MAX
] = {
4884 [SERVICE_TIMEOUT_TERMINATE
] = "terminate",
4885 [SERVICE_TIMEOUT_ABORT
] = "abort",
4886 [SERVICE_TIMEOUT_KILL
] = "kill",
4889 DEFINE_STRING_TABLE_LOOKUP(service_timeout_failure_mode
, ServiceTimeoutFailureMode
);
4891 const UnitVTable service_vtable
= {
4892 .object_size
= sizeof(Service
),
4893 .exec_context_offset
= offsetof(Service
, exec_context
),
4894 .cgroup_context_offset
= offsetof(Service
, cgroup_context
),
4895 .kill_context_offset
= offsetof(Service
, kill_context
),
4896 .exec_runtime_offset
= offsetof(Service
, exec_runtime
),
4897 .dynamic_creds_offset
= offsetof(Service
, dynamic_creds
),
4903 .private_section
= "Service",
4905 .can_transient
= true,
4906 .can_delegate
= true,
4908 .can_set_managed_oom
= true,
4910 .init
= service_init
,
4911 .done
= service_done
,
4912 .load
= service_load
,
4913 .release_resources
= service_release_resources
,
4915 .coldplug
= service_coldplug
,
4917 .dump
= service_dump
,
4919 .start
= service_start
,
4920 .stop
= service_stop
,
4921 .reload
= service_reload
,
4923 .can_reload
= service_can_reload
,
4925 .kill
= service_kill
,
4926 .clean
= service_clean
,
4927 .can_clean
= service_can_clean
,
4929 .freeze
= unit_freeze_vtable_common
,
4930 .thaw
= unit_thaw_vtable_common
,
4932 .serialize
= service_serialize
,
4933 .deserialize_item
= service_deserialize_item
,
4935 .active_state
= service_active_state
,
4936 .sub_state_to_string
= service_sub_state_to_string
,
4938 .will_restart
= service_will_restart
,
4940 .may_gc
= service_may_gc
,
4942 .sigchld_event
= service_sigchld_event
,
4944 .reset_failed
= service_reset_failed
,
4946 .notify_cgroup_empty
= service_notify_cgroup_empty_event
,
4947 .notify_cgroup_oom
= service_notify_cgroup_oom_event
,
4948 .notify_message
= service_notify_message
,
4950 .main_pid
= service_main_pid
,
4951 .control_pid
= service_control_pid
,
4953 .bus_name_owner_change
= service_bus_name_owner_change
,
4955 .bus_set_property
= bus_service_set_property
,
4956 .bus_commit_properties
= bus_service_commit_properties
,
4958 .get_timeout
= service_get_timeout
,
4959 .needs_console
= service_needs_console
,
4960 .exit_status
= service_exit_status
,
4961 .status_text
= service_status_text
,
4963 .status_message_formats
= {
4964 .finished_start_job
= {
4965 [JOB_FAILED
] = "Failed to start %s.",
4967 .finished_stop_job
= {
4968 [JOB_DONE
] = "Stopped %s.",
4969 [JOB_FAILED
] = "Stopped (with error) %s.",
4971 .finished_job
= service_finished_job
,
4974 .can_start
= service_can_start
,