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"
15 #include "chase-symlinks.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
->watchdog_original_usec
= USEC_INFINITY
;
130 s
->oom_policy
= _OOM_POLICY_INVALID
;
131 s
->reload_begin_usec
= USEC_INFINITY
;
132 s
->reload_signal
= SIGHUP
;
135 static void service_unwatch_control_pid(Service
*s
) {
138 if (s
->control_pid
<= 0)
141 unit_unwatch_pid(UNIT(s
), TAKE_PID(s
->control_pid
));
144 static void service_unwatch_main_pid(Service
*s
) {
147 if (s
->main_pid
<= 0)
150 unit_unwatch_pid(UNIT(s
), TAKE_PID(s
->main_pid
));
153 static void service_unwatch_pid_file(Service
*s
) {
154 if (!s
->pid_file_pathspec
)
157 log_unit_debug(UNIT(s
), "Stopping watch for PID file %s", s
->pid_file_pathspec
->path
);
158 path_spec_unwatch(s
->pid_file_pathspec
);
159 path_spec_done(s
->pid_file_pathspec
);
160 s
->pid_file_pathspec
= mfree(s
->pid_file_pathspec
);
163 static int service_set_main_pid(Service
*s
, pid_t pid
) {
169 if (pid
== getpid_cached())
172 if (s
->main_pid
== pid
&& s
->main_pid_known
)
175 if (s
->main_pid
!= pid
) {
176 service_unwatch_main_pid(s
);
177 exec_status_start(&s
->main_exec_status
, pid
);
181 s
->main_pid_known
= true;
182 s
->main_pid_alien
= pid_is_my_child(pid
) == 0;
184 if (s
->main_pid_alien
)
185 log_unit_warning(UNIT(s
), "Supervising process "PID_FMT
" which is not our child. We'll most likely not notice when it exits.", pid
);
190 void service_close_socket_fd(Service
*s
) {
193 /* Undo the effect of service_set_socket_fd(). */
195 s
->socket_fd
= asynchronous_close(s
->socket_fd
);
197 if (UNIT_ISSET(s
->accept_socket
)) {
198 socket_connection_unref(SOCKET(UNIT_DEREF(s
->accept_socket
)));
199 unit_ref_unset(&s
->accept_socket
);
202 s
->socket_peer
= socket_peer_unref(s
->socket_peer
);
205 static void service_stop_watchdog(Service
*s
) {
208 s
->watchdog_event_source
= sd_event_source_disable_unref(s
->watchdog_event_source
);
209 s
->watchdog_timestamp
= DUAL_TIMESTAMP_NULL
;
212 static void service_start_watchdog(Service
*s
) {
213 usec_t watchdog_usec
;
218 watchdog_usec
= service_get_watchdog_usec(s
);
219 if (!timestamp_is_set(watchdog_usec
)) {
220 service_stop_watchdog(s
);
224 if (s
->watchdog_event_source
) {
225 r
= sd_event_source_set_time(s
->watchdog_event_source
, usec_add(s
->watchdog_timestamp
.monotonic
, watchdog_usec
));
227 log_unit_warning_errno(UNIT(s
), r
, "Failed to reset watchdog timer: %m");
231 r
= sd_event_source_set_enabled(s
->watchdog_event_source
, SD_EVENT_ONESHOT
);
233 r
= sd_event_add_time(
234 UNIT(s
)->manager
->event
,
235 &s
->watchdog_event_source
,
237 usec_add(s
->watchdog_timestamp
.monotonic
, watchdog_usec
), 0,
238 service_dispatch_watchdog
, s
);
240 log_unit_warning_errno(UNIT(s
), r
, "Failed to add watchdog timer: %m");
244 (void) sd_event_source_set_description(s
->watchdog_event_source
, "service-watchdog");
246 /* Let's process everything else which might be a sign
247 * of living before we consider a service died. */
248 r
= sd_event_source_set_priority(s
->watchdog_event_source
, SD_EVENT_PRIORITY_IDLE
);
251 log_unit_warning_errno(UNIT(s
), r
, "Failed to install watchdog timer: %m");
254 static void service_extend_event_source_timeout(Service
*s
, sd_event_source
*source
, usec_t extended
) {
260 /* Extends the specified event source timer to at least the specified time, unless it is already later
266 r
= sd_event_source_get_time(source
, ¤t
);
269 (void) sd_event_source_get_description(s
->timer_event_source
, &desc
);
270 log_unit_warning_errno(UNIT(s
), r
, "Failed to retrieve timeout time for event source '%s', ignoring: %m", strna(desc
));
274 if (current
>= extended
) /* Current timeout is already longer, ignore this. */
277 r
= sd_event_source_set_time(source
, extended
);
280 (void) sd_event_source_get_description(s
->timer_event_source
, &desc
);
281 log_unit_warning_errno(UNIT(s
), r
, "Failed to set timeout time for event source '%s', ignoring %m", strna(desc
));
285 static void service_extend_timeout(Service
*s
, usec_t extend_timeout_usec
) {
290 if (!timestamp_is_set(extend_timeout_usec
))
293 extended
= usec_add(now(CLOCK_MONOTONIC
), extend_timeout_usec
);
295 service_extend_event_source_timeout(s
, s
->timer_event_source
, extended
);
296 service_extend_event_source_timeout(s
, s
->watchdog_event_source
, extended
);
299 static void service_reset_watchdog(Service
*s
) {
302 dual_timestamp_get(&s
->watchdog_timestamp
);
303 service_start_watchdog(s
);
306 static void service_override_watchdog_timeout(Service
*s
, usec_t watchdog_override_usec
) {
309 s
->watchdog_override_enable
= true;
310 s
->watchdog_override_usec
= watchdog_override_usec
;
311 service_reset_watchdog(s
);
313 log_unit_debug(UNIT(s
), "watchdog_usec="USEC_FMT
, s
->watchdog_usec
);
314 log_unit_debug(UNIT(s
), "watchdog_override_usec="USEC_FMT
, s
->watchdog_override_usec
);
317 static void service_fd_store_unlink(ServiceFDStore
*fs
) {
323 assert(fs
->service
->n_fd_store
> 0);
324 LIST_REMOVE(fd_store
, fs
->service
->fd_store
, fs
);
325 fs
->service
->n_fd_store
--;
328 sd_event_source_disable_unref(fs
->event_source
);
335 static void service_release_fd_store(Service
*s
) {
338 if (s
->n_keep_fd_store
> 0)
341 log_unit_debug(UNIT(s
), "Releasing all stored fds");
343 service_fd_store_unlink(s
->fd_store
);
345 assert(s
->n_fd_store
== 0);
348 static void service_release_resources(Unit
*u
) {
349 Service
*s
= SERVICE(u
);
353 if (!s
->fd_store
&& s
->stdin_fd
< 0 && s
->stdout_fd
< 0 && s
->stderr_fd
< 0)
356 log_unit_debug(u
, "Releasing resources.");
358 s
->stdin_fd
= safe_close(s
->stdin_fd
);
359 s
->stdout_fd
= safe_close(s
->stdout_fd
);
360 s
->stderr_fd
= safe_close(s
->stderr_fd
);
362 service_release_fd_store(s
);
365 static void service_done(Unit
*u
) {
366 Service
*s
= SERVICE(u
);
370 open_file_free_many(&s
->open_files
);
372 s
->pid_file
= mfree(s
->pid_file
);
373 s
->status_text
= mfree(s
->status_text
);
375 s
->exec_runtime
= exec_runtime_unref(s
->exec_runtime
, false);
376 exec_command_free_array(s
->exec_command
, _SERVICE_EXEC_COMMAND_MAX
);
377 s
->control_command
= NULL
;
378 s
->main_command
= NULL
;
380 dynamic_creds_unref(&s
->dynamic_creds
);
382 exit_status_set_free(&s
->restart_prevent_status
);
383 exit_status_set_free(&s
->restart_force_status
);
384 exit_status_set_free(&s
->success_status
);
386 /* This will leak a process, but at least no memory or any of
388 service_unwatch_main_pid(s
);
389 service_unwatch_control_pid(s
);
390 service_unwatch_pid_file(s
);
393 unit_unwatch_bus_name(u
, s
->bus_name
);
394 s
->bus_name
= mfree(s
->bus_name
);
397 s
->bus_name_owner
= mfree(s
->bus_name_owner
);
399 s
->usb_function_descriptors
= mfree(s
->usb_function_descriptors
);
400 s
->usb_function_strings
= mfree(s
->usb_function_strings
);
402 service_close_socket_fd(s
);
404 unit_ref_unset(&s
->accept_socket
);
406 service_stop_watchdog(s
);
408 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
409 s
->exec_fd_event_source
= sd_event_source_disable_unref(s
->exec_fd_event_source
);
411 s
->bus_name_pid_lookup_slot
= sd_bus_slot_unref(s
->bus_name_pid_lookup_slot
);
413 service_release_resources(u
);
416 static int on_fd_store_io(sd_event_source
*e
, int fd
, uint32_t revents
, void *userdata
) {
417 ServiceFDStore
*fs
= ASSERT_PTR(userdata
);
421 /* If we get either EPOLLHUP or EPOLLERR, it's time to remove this entry from the fd store */
422 log_unit_debug(UNIT(fs
->service
),
423 "Received %s on stored fd %d (%s), closing.",
424 revents
& EPOLLERR
? "EPOLLERR" : "EPOLLHUP",
425 fs
->fd
, strna(fs
->fdname
));
426 service_fd_store_unlink(fs
);
430 static int service_add_fd_store(Service
*s
, int fd
, const char *name
, bool do_poll
) {
434 /* fd is always consumed if we return >= 0 */
439 if (s
->n_fd_store
>= s
->n_fd_store_max
)
440 return -EXFULL
; /* Our store is full.
441 * Use this errno rather than E[NM]FILE to distinguish from
442 * the case where systemd itself hits the file limit. */
444 LIST_FOREACH(fd_store
, i
, s
->fd_store
) {
445 r
= same_fd(i
->fd
, fd
);
450 return 0; /* fd already included */
454 fs
= new(ServiceFDStore
, 1);
458 *fs
= (ServiceFDStore
) {
462 .fdname
= strdup(name
?: "stored"),
471 r
= sd_event_add_io(UNIT(s
)->manager
->event
, &fs
->event_source
, fd
, 0, on_fd_store_io
, fs
);
472 if (r
< 0 && r
!= -EPERM
) { /* EPERM indicates fds that aren't pollable, which is OK */
477 (void) sd_event_source_set_description(fs
->event_source
, "service-fd-store");
480 LIST_PREPEND(fd_store
, s
->fd_store
, fs
);
483 return 1; /* fd newly stored */
486 static int service_add_fd_store_set(Service
*s
, FDSet
*fds
, const char *name
, bool do_poll
) {
491 while (fdset_size(fds
) > 0) {
492 _cleanup_close_
int fd
= -EBADF
;
494 fd
= fdset_steal_first(fds
);
498 r
= service_add_fd_store(s
, fd
, name
, do_poll
);
500 return log_unit_warning_errno(UNIT(s
), r
,
501 "Cannot store more fds than FileDescriptorStoreMax=%u, closing remaining.",
504 return log_unit_error_errno(UNIT(s
), r
, "Failed to add fd to store: %m");
506 log_unit_debug(UNIT(s
), "Added fd %i (%s) to fd store.", fd
, strna(name
));
513 static void service_remove_fd_store(Service
*s
, const char *name
) {
517 LIST_FOREACH(fd_store
, fs
, s
->fd_store
) {
518 if (!streq(fs
->fdname
, name
))
521 log_unit_debug(UNIT(s
), "Got explicit request to remove fd %i (%s), closing.", fs
->fd
, name
);
522 service_fd_store_unlink(fs
);
526 static usec_t
service_running_timeout(Service
*s
) {
531 if (s
->runtime_rand_extra_usec
!= 0) {
532 delta
= random_u64_range(s
->runtime_rand_extra_usec
);
533 log_unit_debug(UNIT(s
), "Adding delta of %s sec to timeout", FORMAT_TIMESPAN(delta
, USEC_PER_SEC
));
536 return usec_add(usec_add(UNIT(s
)->active_enter_timestamp
.monotonic
,
537 s
->runtime_max_usec
),
541 static int service_arm_timer(Service
*s
, bool relative
, usec_t usec
) {
546 if (s
->timer_event_source
) {
547 r
= (relative
? sd_event_source_set_time_relative
: sd_event_source_set_time
)(s
->timer_event_source
, usec
);
551 return sd_event_source_set_enabled(s
->timer_event_source
, SD_EVENT_ONESHOT
);
554 if (usec
== USEC_INFINITY
)
557 r
= (relative
? sd_event_add_time_relative
: sd_event_add_time
)(
558 UNIT(s
)->manager
->event
,
559 &s
->timer_event_source
,
562 service_dispatch_timer
, s
);
566 (void) sd_event_source_set_description(s
->timer_event_source
, "service-timer");
571 static int service_verify(Service
*s
) {
573 assert(UNIT(s
)->load_state
== UNIT_LOADED
);
575 for (ServiceExecCommand c
= 0; c
< _SERVICE_EXEC_COMMAND_MAX
; c
++)
576 LIST_FOREACH(command
, command
, s
->exec_command
[c
]) {
577 if (!path_is_absolute(command
->path
) && !filename_is_valid(command
->path
))
578 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
),
579 "Service %s= binary path \"%s\" is neither a valid executable name nor an absolute path. Refusing.",
581 service_exec_command_to_string(c
));
582 if (strv_isempty(command
->argv
))
583 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
),
584 "Service has an empty argv in %s=. Refusing.",
585 service_exec_command_to_string(c
));
588 if (!s
->exec_command
[SERVICE_EXEC_START
] && !s
->exec_command
[SERVICE_EXEC_STOP
] &&
589 UNIT(s
)->success_action
== EMERGENCY_ACTION_NONE
)
590 /* FailureAction= only makes sense if one of the start or stop commands is specified.
591 * SuccessAction= will be executed unconditionally if no commands are specified. Hence,
592 * either a command or SuccessAction= are required. */
594 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Service has no ExecStart=, ExecStop=, or SuccessAction=. Refusing.");
596 if (s
->type
!= SERVICE_ONESHOT
&& !s
->exec_command
[SERVICE_EXEC_START
])
597 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Service has no ExecStart= setting, which is only allowed for Type=oneshot services. Refusing.");
599 if (!s
->remain_after_exit
&& !s
->exec_command
[SERVICE_EXEC_START
] && UNIT(s
)->success_action
== EMERGENCY_ACTION_NONE
)
600 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.");
602 if (s
->type
!= SERVICE_ONESHOT
&& s
->exec_command
[SERVICE_EXEC_START
]->command_next
)
603 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.");
605 if (s
->type
== SERVICE_ONESHOT
&&
606 !IN_SET(s
->restart
, SERVICE_RESTART_NO
, SERVICE_RESTART_ON_FAILURE
, SERVICE_RESTART_ON_ABNORMAL
, SERVICE_RESTART_ON_WATCHDOG
, SERVICE_RESTART_ON_ABORT
))
607 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.");
609 if (s
->type
== SERVICE_ONESHOT
&& !exit_status_set_is_empty(&s
->restart_force_status
))
610 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Service has RestartForceExitStatus= set, which isn't allowed for Type=oneshot services. Refusing.");
612 if (s
->type
== SERVICE_ONESHOT
&& s
->exit_type
== SERVICE_EXIT_CGROUP
)
613 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Service has ExitType=cgroup set, which isn't allowed for Type=oneshot services. Refusing.");
615 if (s
->type
== SERVICE_DBUS
&& !s
->bus_name
)
616 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.");
618 if (s
->exec_context
.pam_name
&& !IN_SET(s
->kill_context
.kill_mode
, KILL_CONTROL_GROUP
, KILL_MIXED
))
619 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.");
621 if (s
->usb_function_descriptors
&& !s
->usb_function_strings
)
622 log_unit_warning(UNIT(s
), "Service has USBFunctionDescriptors= setting, but no USBFunctionStrings=. Ignoring.");
624 if (!s
->usb_function_descriptors
&& s
->usb_function_strings
)
625 log_unit_warning(UNIT(s
), "Service has USBFunctionStrings= setting, but no USBFunctionDescriptors=. Ignoring.");
627 if (s
->runtime_max_usec
!= USEC_INFINITY
&& s
->type
== SERVICE_ONESHOT
)
628 log_unit_warning(UNIT(s
), "RuntimeMaxSec= has no effect in combination with Type=oneshot. Ignoring.");
630 if (s
->runtime_max_usec
== USEC_INFINITY
&& s
->runtime_rand_extra_usec
!= 0)
631 log_unit_warning(UNIT(s
), "Service has RuntimeRandomizedExtraSec= setting, but no RuntimeMaxSec=. Ignoring.");
633 if (s
->exit_type
== SERVICE_EXIT_CGROUP
&& cg_unified() < CGROUP_UNIFIED_SYSTEMD
)
634 log_unit_warning(UNIT(s
), "Service has ExitType=cgroup set, but we are running with legacy cgroups v1, which might not work correctly. Continuing.");
639 static int service_add_default_dependencies(Service
*s
) {
644 if (!UNIT(s
)->default_dependencies
)
647 /* Add a number of automatic dependencies useful for the
648 * majority of services. */
650 if (MANAGER_IS_SYSTEM(UNIT(s
)->manager
)) {
651 /* First, pull in the really early boot stuff, and
652 * require it, so that we fail if we can't acquire
655 r
= unit_add_two_dependencies_by_name(UNIT(s
), UNIT_AFTER
, UNIT_REQUIRES
, SPECIAL_SYSINIT_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
660 /* In the --user instance there's no sysinit.target,
661 * in that case require basic.target instead. */
663 r
= unit_add_dependency_by_name(UNIT(s
), UNIT_REQUIRES
, SPECIAL_BASIC_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
668 /* Second, if the rest of the base system is in the same
669 * transaction, order us after it, but do not pull it in or
670 * even require it. */
671 r
= unit_add_dependency_by_name(UNIT(s
), UNIT_AFTER
, SPECIAL_BASIC_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
675 /* Third, add us in for normal shutdown. */
676 return unit_add_two_dependencies_by_name(UNIT(s
), UNIT_BEFORE
, UNIT_CONFLICTS
, SPECIAL_SHUTDOWN_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
679 static void service_fix_stdio(Service
*s
) {
682 /* Note that EXEC_INPUT_NULL and EXEC_OUTPUT_INHERIT play a special role here: they are both the
683 * default value that is subject to automatic overriding triggered by other settings and an explicit
684 * choice the user can make. We don't distinguish between these cases currently. */
686 if (s
->exec_context
.std_input
== EXEC_INPUT_NULL
&&
687 s
->exec_context
.stdin_data_size
> 0)
688 s
->exec_context
.std_input
= EXEC_INPUT_DATA
;
690 if (IN_SET(s
->exec_context
.std_input
,
692 EXEC_INPUT_TTY_FORCE
,
695 EXEC_INPUT_NAMED_FD
))
698 /* We assume these listed inputs refer to bidirectional streams, and hence duplicating them from
699 * stdin to stdout/stderr makes sense and hence leaving EXEC_OUTPUT_INHERIT in place makes sense,
700 * too. Outputs such as regular files or sealed data memfds otoh don't really make sense to be
701 * duplicated for both input and output at the same time (since they then would cause a feedback
702 * loop), hence override EXEC_OUTPUT_INHERIT with the default stderr/stdout setting. */
704 if (s
->exec_context
.std_error
== EXEC_OUTPUT_INHERIT
&&
705 s
->exec_context
.std_output
== EXEC_OUTPUT_INHERIT
)
706 s
->exec_context
.std_error
= UNIT(s
)->manager
->default_std_error
;
708 if (s
->exec_context
.std_output
== EXEC_OUTPUT_INHERIT
)
709 s
->exec_context
.std_output
= UNIT(s
)->manager
->default_std_output
;
712 static int service_setup_bus_name(Service
*s
) {
717 /* If s->bus_name is not set, then the unit will be refused by service_verify() later. */
721 if (s
->type
== SERVICE_DBUS
) {
722 r
= unit_add_dependency_by_name(UNIT(s
), UNIT_REQUIRES
, SPECIAL_DBUS_SOCKET
, true, UNIT_DEPENDENCY_FILE
);
724 return log_unit_error_errno(UNIT(s
), r
, "Failed to add dependency on " SPECIAL_DBUS_SOCKET
": %m");
726 /* We always want to be ordered against dbus.socket if both are in the transaction. */
727 r
= unit_add_dependency_by_name(UNIT(s
), UNIT_AFTER
, SPECIAL_DBUS_SOCKET
, true, UNIT_DEPENDENCY_FILE
);
729 return log_unit_error_errno(UNIT(s
), r
, "Failed to add dependency on " SPECIAL_DBUS_SOCKET
": %m");
732 r
= unit_watch_bus_name(UNIT(s
), s
->bus_name
);
734 return log_unit_error_errno(UNIT(s
), r
, "Two services allocated for the same bus name %s, refusing operation.", s
->bus_name
);
736 return log_unit_error_errno(UNIT(s
), r
, "Cannot watch bus name %s: %m", s
->bus_name
);
741 static int service_add_extras(Service
*s
) {
746 if (s
->type
== _SERVICE_TYPE_INVALID
) {
747 /* Figure out a type automatically */
749 s
->type
= SERVICE_DBUS
;
750 else if (s
->exec_command
[SERVICE_EXEC_START
])
751 s
->type
= SERVICE_SIMPLE
;
753 s
->type
= SERVICE_ONESHOT
;
756 /* Oneshot services have disabled start timeout by default */
757 if (s
->type
== SERVICE_ONESHOT
&& !s
->start_timeout_defined
)
758 s
->timeout_start_usec
= USEC_INFINITY
;
760 service_fix_stdio(s
);
762 r
= unit_patch_contexts(UNIT(s
));
766 r
= unit_add_exec_dependencies(UNIT(s
), &s
->exec_context
);
770 r
= unit_set_default_slice(UNIT(s
));
774 /* If the service needs the notify socket, let's enable it automatically. */
775 if (s
->notify_access
== NOTIFY_NONE
&&
776 (IN_SET(s
->type
, SERVICE_NOTIFY
, SERVICE_NOTIFY_RELOAD
) || s
->watchdog_usec
> 0 || s
->n_fd_store_max
> 0))
777 s
->notify_access
= NOTIFY_MAIN
;
779 /* If no OOM policy was explicitly set, then default to the configure default OOM policy. Except when
780 * delegation is on, in that case it we assume the payload knows better what to do and can process
781 * things in a more focused way. */
782 if (s
->oom_policy
< 0)
783 s
->oom_policy
= s
->cgroup_context
.delegate
? OOM_CONTINUE
: UNIT(s
)->manager
->default_oom_policy
;
785 /* Let the kernel do the killing if that's requested. */
786 s
->cgroup_context
.memory_oom_group
= s
->oom_policy
== OOM_KILL
;
788 r
= service_add_default_dependencies(s
);
792 r
= service_setup_bus_name(s
);
799 static int service_load(Unit
*u
) {
800 Service
*s
= SERVICE(u
);
803 r
= unit_load_fragment_and_dropin(u
, true);
807 if (u
->load_state
!= UNIT_LOADED
)
810 /* This is a new unit? Then let's add in some extras */
811 r
= service_add_extras(s
);
815 return service_verify(s
);
818 static void service_dump(Unit
*u
, FILE *f
, const char *prefix
) {
819 ServiceExecCommand c
;
820 Service
*s
= SERVICE(u
);
825 prefix
= strempty(prefix
);
826 prefix2
= strjoina(prefix
, "\t");
829 "%sService State: %s\n"
831 "%sReload Result: %s\n"
832 "%sClean Result: %s\n"
833 "%sPermissionsStartOnly: %s\n"
834 "%sRootDirectoryStartOnly: %s\n"
835 "%sRemainAfterExit: %s\n"
836 "%sGuessMainPID: %s\n"
839 "%sNotifyAccess: %s\n"
840 "%sNotifyState: %s\n"
842 "%sReloadSignal: %s\n",
843 prefix
, service_state_to_string(s
->state
),
844 prefix
, service_result_to_string(s
->result
),
845 prefix
, service_result_to_string(s
->reload_result
),
846 prefix
, service_result_to_string(s
->clean_result
),
847 prefix
, yes_no(s
->permissions_start_only
),
848 prefix
, yes_no(s
->root_directory_start_only
),
849 prefix
, yes_no(s
->remain_after_exit
),
850 prefix
, yes_no(s
->guess_main_pid
),
851 prefix
, service_type_to_string(s
->type
),
852 prefix
, service_restart_to_string(s
->restart
),
853 prefix
, notify_access_to_string(s
->notify_access
),
854 prefix
, notify_state_to_string(s
->notify_state
),
855 prefix
, oom_policy_to_string(s
->oom_policy
),
856 prefix
, signal_to_string(s
->reload_signal
));
858 if (s
->control_pid
> 0)
860 "%sControl PID: "PID_FMT
"\n",
861 prefix
, s
->control_pid
);
865 "%sMain PID: "PID_FMT
"\n"
866 "%sMain PID Known: %s\n"
867 "%sMain PID Alien: %s\n",
869 prefix
, yes_no(s
->main_pid_known
),
870 prefix
, yes_no(s
->main_pid_alien
));
875 prefix
, s
->pid_file
);
880 "%sBus Name Good: %s\n",
882 prefix
, yes_no(s
->bus_name_good
));
884 if (UNIT_ISSET(s
->accept_socket
))
886 "%sAccept Socket: %s\n",
887 prefix
, UNIT_DEREF(s
->accept_socket
)->id
);
891 "%sTimeoutStartSec: %s\n"
892 "%sTimeoutStopSec: %s\n"
893 "%sTimeoutStartFailureMode: %s\n"
894 "%sTimeoutStopFailureMode: %s\n",
895 prefix
, FORMAT_TIMESPAN(s
->restart_usec
, USEC_PER_SEC
),
896 prefix
, FORMAT_TIMESPAN(s
->timeout_start_usec
, USEC_PER_SEC
),
897 prefix
, FORMAT_TIMESPAN(s
->timeout_stop_usec
, USEC_PER_SEC
),
898 prefix
, service_timeout_failure_mode_to_string(s
->timeout_start_failure_mode
),
899 prefix
, service_timeout_failure_mode_to_string(s
->timeout_stop_failure_mode
));
901 if (s
->timeout_abort_set
)
903 "%sTimeoutAbortSec: %s\n",
904 prefix
, FORMAT_TIMESPAN(s
->timeout_abort_usec
, USEC_PER_SEC
));
907 "%sRuntimeMaxSec: %s\n"
908 "%sRuntimeRandomizedExtraSec: %s\n"
909 "%sWatchdogSec: %s\n",
910 prefix
, FORMAT_TIMESPAN(s
->runtime_max_usec
, USEC_PER_SEC
),
911 prefix
, FORMAT_TIMESPAN(s
->runtime_rand_extra_usec
, USEC_PER_SEC
),
912 prefix
, FORMAT_TIMESPAN(s
->watchdog_usec
, USEC_PER_SEC
));
914 kill_context_dump(&s
->kill_context
, f
, prefix
);
915 exec_context_dump(&s
->exec_context
, f
, prefix
);
917 for (c
= 0; c
< _SERVICE_EXEC_COMMAND_MAX
; c
++) {
919 if (!s
->exec_command
[c
])
922 fprintf(f
, "%s-> %s:\n",
923 prefix
, service_exec_command_to_string(c
));
925 exec_command_dump_list(s
->exec_command
[c
], f
, prefix2
);
929 fprintf(f
, "%sStatus Text: %s\n",
930 prefix
, s
->status_text
);
932 if (s
->n_fd_store_max
> 0)
934 "%sFile Descriptor Store Max: %u\n"
935 "%sFile Descriptor Store Current: %zu\n",
936 prefix
, s
->n_fd_store_max
,
937 prefix
, s
->n_fd_store
);
940 LIST_FOREACH(open_files
, of
, s
->open_files
) {
941 _cleanup_free_
char *ofs
= NULL
;
944 r
= open_file_to_string(of
, &ofs
);
947 "Failed to convert OpenFile= setting to string, ignoring: %m");
951 fprintf(f
, "%sOpen File: %s\n", prefix
, ofs
);
954 cgroup_context_dump(UNIT(s
), f
, prefix
);
957 static int service_is_suitable_main_pid(Service
*s
, pid_t pid
, int prio
) {
961 assert(pid_is_valid(pid
));
963 /* Checks whether the specified PID is suitable as main PID for this service. returns negative if not, 0 if the
964 * PID is questionnable but should be accepted if the source of configuration is trusted. > 0 if the PID is
967 if (pid
== getpid_cached() || pid
== 1)
968 return log_unit_full_errno(UNIT(s
), prio
, SYNTHETIC_ERRNO(EPERM
), "New main PID "PID_FMT
" is the manager, refusing.", pid
);
970 if (pid
== s
->control_pid
)
971 return log_unit_full_errno(UNIT(s
), prio
, SYNTHETIC_ERRNO(EPERM
), "New main PID "PID_FMT
" is the control process, refusing.", pid
);
973 if (!pid_is_alive(pid
))
974 return log_unit_full_errno(UNIT(s
), prio
, SYNTHETIC_ERRNO(ESRCH
), "New main PID "PID_FMT
" does not exist or is a zombie.", pid
);
976 owner
= manager_get_unit_by_pid(UNIT(s
)->manager
, pid
);
977 if (owner
== UNIT(s
)) {
978 log_unit_debug(UNIT(s
), "New main PID "PID_FMT
" belongs to service, we are happy.", pid
);
979 return 1; /* Yay, it's definitely a good PID */
982 return 0; /* Hmm it's a suspicious PID, let's accept it if configuration source is trusted */
985 static int service_load_pid_file(Service
*s
, bool may_warn
) {
986 bool questionable_pid_file
= false;
987 _cleanup_free_
char *k
= NULL
;
988 _cleanup_close_
int fd
= -EBADF
;
997 prio
= may_warn
? LOG_INFO
: LOG_DEBUG
;
999 r
= chase_symlinks(s
->pid_file
, NULL
, CHASE_SAFE
, NULL
, &fd
);
1000 if (r
== -ENOLINK
) {
1001 log_unit_debug_errno(UNIT(s
), r
,
1002 "Potentially unsafe symlink chain, will now retry with relaxed checks: %s", s
->pid_file
);
1004 questionable_pid_file
= true;
1006 r
= chase_symlinks(s
->pid_file
, NULL
, 0, NULL
, &fd
);
1009 return log_unit_full_errno(UNIT(s
), prio
, fd
,
1010 "Can't open PID file %s (yet?) after %s: %m", s
->pid_file
, service_state_to_string(s
->state
));
1012 /* Let's read the PID file now that we chased it down. But we need to convert the O_PATH fd
1013 * chase_symlinks() returned us into a proper fd first. */
1014 r
= read_one_line_file(FORMAT_PROC_FD_PATH(fd
), &k
);
1016 return log_unit_error_errno(UNIT(s
), r
,
1017 "Can't convert PID files %s O_PATH file descriptor to proper file descriptor: %m",
1020 r
= parse_pid(k
, &pid
);
1022 return log_unit_full_errno(UNIT(s
), prio
, r
, "Failed to parse PID from file %s: %m", s
->pid_file
);
1024 if (s
->main_pid_known
&& pid
== s
->main_pid
)
1027 r
= service_is_suitable_main_pid(s
, pid
, prio
);
1033 if (questionable_pid_file
)
1034 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(EPERM
),
1035 "Refusing to accept PID outside of service control group, acquired through unsafe symlink chain: %s", s
->pid_file
);
1037 /* Hmm, it's not clear if the new main PID is safe. Let's allow this if the PID file is owned by root */
1039 if (fstat(fd
, &st
) < 0)
1040 return log_unit_error_errno(UNIT(s
), errno
, "Failed to fstat() PID file O_PATH fd: %m");
1043 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(EPERM
),
1044 "New main PID "PID_FMT
" does not belong to service, and PID file is not owned by root. Refusing.", pid
);
1046 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
);
1049 if (s
->main_pid_known
) {
1050 log_unit_debug(UNIT(s
), "Main PID changing: "PID_FMT
" -> "PID_FMT
, s
->main_pid
, pid
);
1052 service_unwatch_main_pid(s
);
1053 s
->main_pid_known
= false;
1055 log_unit_debug(UNIT(s
), "Main PID loaded: "PID_FMT
, pid
);
1057 r
= service_set_main_pid(s
, pid
);
1061 r
= unit_watch_pid(UNIT(s
), pid
, false);
1062 if (r
< 0) /* FIXME: we need to do something here */
1063 return log_unit_warning_errno(UNIT(s
), r
, "Failed to watch PID "PID_FMT
" for service: %m", pid
);
1068 static void service_search_main_pid(Service
*s
) {
1074 /* If we know it anyway, don't ever fall back to unreliable
1076 if (s
->main_pid_known
)
1079 if (!s
->guess_main_pid
)
1082 assert(s
->main_pid
<= 0);
1084 if (unit_search_main_pid(UNIT(s
), &pid
) < 0)
1087 log_unit_debug(UNIT(s
), "Main PID guessed: "PID_FMT
, pid
);
1088 if (service_set_main_pid(s
, pid
) < 0)
1091 r
= unit_watch_pid(UNIT(s
), pid
, false);
1093 /* FIXME: we need to do something here */
1094 log_unit_warning_errno(UNIT(s
), r
, "Failed to watch PID "PID_FMT
" from: %m", pid
);
1097 static void service_set_state(Service
*s
, ServiceState state
) {
1098 ServiceState old_state
;
1099 const UnitActiveState
*table
;
1103 if (s
->state
!= state
)
1104 bus_unit_send_pending_change_signal(UNIT(s
), false);
1106 table
= s
->type
== SERVICE_IDLE
? state_translation_table_idle
: state_translation_table
;
1108 old_state
= s
->state
;
1111 service_unwatch_pid_file(s
);
1114 SERVICE_CONDITION
, SERVICE_START_PRE
, SERVICE_START
, SERVICE_START_POST
,
1116 SERVICE_RELOAD
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
,
1117 SERVICE_STOP
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
, SERVICE_STOP_POST
,
1118 SERVICE_FINAL_WATCHDOG
, SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
,
1119 SERVICE_AUTO_RESTART
,
1121 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
1124 SERVICE_START
, SERVICE_START_POST
,
1126 SERVICE_RELOAD
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
,
1127 SERVICE_STOP
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
, SERVICE_STOP_POST
,
1128 SERVICE_FINAL_WATCHDOG
, SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
)) {
1129 service_unwatch_main_pid(s
);
1130 s
->main_command
= NULL
;
1134 SERVICE_CONDITION
, SERVICE_START_PRE
, SERVICE_START
, SERVICE_START_POST
,
1135 SERVICE_RELOAD
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
,
1136 SERVICE_STOP
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
, SERVICE_STOP_POST
,
1137 SERVICE_FINAL_WATCHDOG
, SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
,
1138 SERVICE_CLEANING
)) {
1139 service_unwatch_control_pid(s
);
1140 s
->control_command
= NULL
;
1141 s
->control_command_id
= _SERVICE_EXEC_COMMAND_INVALID
;
1144 if (IN_SET(state
, SERVICE_DEAD
, SERVICE_FAILED
, SERVICE_AUTO_RESTART
)) {
1145 unit_unwatch_all_pids(UNIT(s
));
1146 unit_dequeue_rewatch_pids(UNIT(s
));
1150 SERVICE_CONDITION
, SERVICE_START_PRE
, SERVICE_START
, SERVICE_START_POST
,
1152 SERVICE_RELOAD
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
,
1153 SERVICE_STOP
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
, SERVICE_STOP_POST
,
1154 SERVICE_FINAL_WATCHDOG
, SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
) &&
1155 !(state
== SERVICE_DEAD
&& UNIT(s
)->job
))
1156 service_close_socket_fd(s
);
1158 if (state
!= SERVICE_START
)
1159 s
->exec_fd_event_source
= sd_event_source_disable_unref(s
->exec_fd_event_source
);
1161 if (!IN_SET(state
, SERVICE_START_POST
, SERVICE_RUNNING
, SERVICE_RELOAD
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
))
1162 service_stop_watchdog(s
);
1164 /* For the inactive states unit_notify() will trim the cgroup,
1165 * but for exit we have to do that ourselves... */
1166 if (state
== SERVICE_EXITED
&& !MANAGER_IS_RELOADING(UNIT(s
)->manager
))
1167 unit_prune_cgroup(UNIT(s
));
1169 if (old_state
!= state
)
1170 log_unit_debug(UNIT(s
), "Changed %s -> %s", service_state_to_string(old_state
), service_state_to_string(state
));
1172 unit_notify(UNIT(s
), table
[old_state
], table
[state
],
1173 (s
->reload_result
== SERVICE_SUCCESS
? 0 : UNIT_NOTIFY_RELOAD_FAILURE
) |
1174 (s
->will_auto_restart
? UNIT_NOTIFY_WILL_AUTO_RESTART
: 0));
1177 static usec_t
service_coldplug_timeout(Service
*s
) {
1180 switch (s
->deserialized_state
) {
1182 case SERVICE_CONDITION
:
1183 case SERVICE_START_PRE
:
1185 case SERVICE_START_POST
:
1186 case SERVICE_RELOAD
:
1187 case SERVICE_RELOAD_SIGNAL
:
1188 case SERVICE_RELOAD_NOTIFY
:
1189 return usec_add(UNIT(s
)->state_change_timestamp
.monotonic
, s
->timeout_start_usec
);
1191 case SERVICE_RUNNING
:
1192 return service_running_timeout(s
);
1195 case SERVICE_STOP_SIGTERM
:
1196 case SERVICE_STOP_SIGKILL
:
1197 case SERVICE_STOP_POST
:
1198 case SERVICE_FINAL_SIGTERM
:
1199 case SERVICE_FINAL_SIGKILL
:
1200 return usec_add(UNIT(s
)->state_change_timestamp
.monotonic
, s
->timeout_stop_usec
);
1202 case SERVICE_STOP_WATCHDOG
:
1203 case SERVICE_FINAL_WATCHDOG
:
1204 return usec_add(UNIT(s
)->state_change_timestamp
.monotonic
, service_timeout_abort_usec(s
));
1206 case SERVICE_AUTO_RESTART
:
1207 return usec_add(UNIT(s
)->inactive_enter_timestamp
.monotonic
, s
->restart_usec
);
1209 case SERVICE_CLEANING
:
1210 return usec_add(UNIT(s
)->state_change_timestamp
.monotonic
, s
->exec_context
.timeout_clean_usec
);
1213 return USEC_INFINITY
;
1217 static int service_coldplug(Unit
*u
) {
1218 Service
*s
= SERVICE(u
);
1222 assert(s
->state
== SERVICE_DEAD
);
1224 if (s
->deserialized_state
== s
->state
)
1227 r
= service_arm_timer(s
, /* relative= */ false, service_coldplug_timeout(s
));
1231 if (s
->main_pid
> 0 &&
1232 pid_is_unwaited(s
->main_pid
) &&
1233 (IN_SET(s
->deserialized_state
,
1234 SERVICE_START
, SERVICE_START_POST
,
1236 SERVICE_RELOAD
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
,
1237 SERVICE_STOP
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
, SERVICE_STOP_POST
,
1238 SERVICE_FINAL_WATCHDOG
, SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
))) {
1239 r
= unit_watch_pid(UNIT(s
), s
->main_pid
, false);
1244 if (s
->control_pid
> 0 &&
1245 pid_is_unwaited(s
->control_pid
) &&
1246 IN_SET(s
->deserialized_state
,
1247 SERVICE_CONDITION
, SERVICE_START_PRE
, SERVICE_START
, SERVICE_START_POST
,
1248 SERVICE_RELOAD
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
,
1249 SERVICE_STOP
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
, SERVICE_STOP_POST
,
1250 SERVICE_FINAL_WATCHDOG
, SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
,
1251 SERVICE_CLEANING
)) {
1252 r
= unit_watch_pid(UNIT(s
), s
->control_pid
, false);
1257 if (!IN_SET(s
->deserialized_state
, SERVICE_DEAD
, SERVICE_FAILED
, SERVICE_AUTO_RESTART
, SERVICE_CLEANING
)) {
1258 (void) unit_enqueue_rewatch_pids(u
);
1259 (void) unit_setup_dynamic_creds(u
);
1260 (void) unit_setup_exec_runtime(u
);
1263 if (IN_SET(s
->deserialized_state
, SERVICE_START_POST
, SERVICE_RUNNING
, SERVICE_RELOAD
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
))
1264 service_start_watchdog(s
);
1266 if (UNIT_ISSET(s
->accept_socket
)) {
1267 Socket
* socket
= SOCKET(UNIT_DEREF(s
->accept_socket
));
1269 if (socket
->max_connections_per_source
> 0) {
1272 /* Make a best-effort attempt at bumping the connection count */
1273 if (socket_acquire_peer(socket
, s
->socket_fd
, &peer
) > 0) {
1274 socket_peer_unref(s
->socket_peer
);
1275 s
->socket_peer
= peer
;
1280 service_set_state(s
, s
->deserialized_state
);
1284 static int service_collect_fds(
1288 size_t *n_socket_fds
,
1289 size_t *n_storage_fds
) {
1291 _cleanup_strv_free_
char **rfd_names
= NULL
;
1292 _cleanup_free_
int *rfds
= NULL
;
1293 size_t rn_socket_fds
= 0, rn_storage_fds
= 0;
1299 assert(n_socket_fds
);
1300 assert(n_storage_fds
);
1302 if (s
->socket_fd
>= 0) {
1304 /* Pass the per-connection socket */
1309 rfds
[0] = s
->socket_fd
;
1311 rfd_names
= strv_new("connection");
1319 /* Pass all our configured sockets for singleton services */
1321 UNIT_FOREACH_DEPENDENCY(u
, UNIT(s
), UNIT_ATOM_TRIGGERED_BY
) {
1322 _cleanup_free_
int *cfds
= NULL
;
1326 if (u
->type
!= UNIT_SOCKET
)
1331 cn_fds
= socket_collect_fds(sock
, &cfds
);
1339 rfds
= TAKE_PTR(cfds
);
1340 rn_socket_fds
= cn_fds
;
1344 t
= reallocarray(rfds
, rn_socket_fds
+ cn_fds
, sizeof(int));
1348 memcpy(t
+ rn_socket_fds
, cfds
, cn_fds
* sizeof(int));
1351 rn_socket_fds
+= cn_fds
;
1354 r
= strv_extend_n(&rfd_names
, socket_fdname(sock
), cn_fds
);
1360 if (s
->n_fd_store
> 0) {
1365 t
= reallocarray(rfds
, rn_socket_fds
+ s
->n_fd_store
, sizeof(int));
1371 nl
= reallocarray(rfd_names
, rn_socket_fds
+ s
->n_fd_store
+ 1, sizeof(char *));
1376 n_fds
= rn_socket_fds
;
1378 LIST_FOREACH(fd_store
, fs
, s
->fd_store
) {
1379 rfds
[n_fds
] = fs
->fd
;
1380 rfd_names
[n_fds
] = strdup(strempty(fs
->fdname
));
1381 if (!rfd_names
[n_fds
])
1388 rfd_names
[n_fds
] = NULL
;
1391 *fds
= TAKE_PTR(rfds
);
1392 *fd_names
= TAKE_PTR(rfd_names
);
1393 *n_socket_fds
= rn_socket_fds
;
1394 *n_storage_fds
= rn_storage_fds
;
1399 static int service_allocate_exec_fd_event_source(
1402 sd_event_source
**ret_event_source
) {
1404 _cleanup_(sd_event_source_unrefp
) sd_event_source
*source
= NULL
;
1409 assert(ret_event_source
);
1411 r
= sd_event_add_io(UNIT(s
)->manager
->event
, &source
, fd
, 0, service_dispatch_exec_io
, s
);
1413 return log_unit_error_errno(UNIT(s
), r
, "Failed to allocate exec_fd event source: %m");
1415 /* This is a bit lower priority than SIGCHLD, as that carries a lot more interesting failure information */
1417 r
= sd_event_source_set_priority(source
, SD_EVENT_PRIORITY_NORMAL
-3);
1419 return log_unit_error_errno(UNIT(s
), r
, "Failed to adjust priority of exec_fd event source: %m");
1421 (void) sd_event_source_set_description(source
, "service exec_fd");
1423 r
= sd_event_source_set_io_fd_own(source
, true);
1425 return log_unit_error_errno(UNIT(s
), r
, "Failed to pass ownership of fd to event source: %m");
1427 *ret_event_source
= TAKE_PTR(source
);
1431 static int service_allocate_exec_fd(
1433 sd_event_source
**ret_event_source
,
1436 _cleanup_close_pair_
int p
[] = PIPE_EBADF
;
1440 assert(ret_event_source
);
1441 assert(ret_exec_fd
);
1443 if (pipe2(p
, O_CLOEXEC
|O_NONBLOCK
) < 0)
1444 return log_unit_error_errno(UNIT(s
), errno
, "Failed to allocate exec_fd pipe: %m");
1446 r
= service_allocate_exec_fd_event_source(s
, p
[0], ret_event_source
);
1451 *ret_exec_fd
= TAKE_FD(p
[1]);
1456 static bool service_exec_needs_notify_socket(Service
*s
, ExecFlags flags
) {
1459 /* Notifications are accepted depending on the process and
1460 * the access setting of the service:
1461 * process: \ access: NONE MAIN EXEC ALL
1462 * main no yes yes yes
1463 * control no no yes yes
1464 * other (forked) no no no yes */
1466 if (flags
& EXEC_IS_CONTROL
)
1467 /* A control process */
1468 return IN_SET(s
->notify_access
, NOTIFY_EXEC
, NOTIFY_ALL
);
1470 /* We only spawn main processes and control processes, so any
1471 * process that is not a control process is a main process */
1472 return s
->notify_access
!= NOTIFY_NONE
;
1475 static Service
*service_get_triggering_service(Service
*s
) {
1476 Unit
*candidate
= NULL
, *other
;
1480 /* Return the service which triggered service 's', this means dependency
1481 * types which include the UNIT_ATOM_ON_{FAILURE,SUCCESS}_OF atoms.
1483 * N.B. if there are multiple services which could trigger 's' via OnFailure=
1484 * or OnSuccess= then we return NULL. This is since we don't know from which
1485 * one to propagate the exit status. */
1487 UNIT_FOREACH_DEPENDENCY(other
, UNIT(s
), UNIT_ATOM_ON_FAILURE_OF
) {
1493 UNIT_FOREACH_DEPENDENCY(other
, UNIT(s
), UNIT_ATOM_ON_SUCCESS_OF
) {
1499 return SERVICE(candidate
);
1502 log_unit_warning(UNIT(s
), "multiple trigger source candidates for exit status propagation (%s, %s), skipping.",
1503 candidate
->id
, other
->id
);
1507 static int service_spawn_internal(
1515 _cleanup_(exec_params_clear
) ExecParameters exec_params
= {
1518 .stdout_fd
= -EBADF
,
1519 .stderr_fd
= -EBADF
,
1522 _cleanup_(sd_event_source_unrefp
) sd_event_source
*exec_fd_source
= NULL
;
1523 _cleanup_strv_free_
char **final_env
= NULL
, **our_env
= NULL
;
1533 log_unit_debug(UNIT(s
), "Will spawn child (%s): %s", caller
, c
->path
);
1535 r
= unit_prepare_exec(UNIT(s
)); /* This realizes the cgroup, among other things */
1539 assert(!s
->exec_fd_event_source
);
1541 if (flags
& EXEC_IS_CONTROL
) {
1542 /* If this is a control process, mask the permissions/chroot application if this is requested. */
1543 if (s
->permissions_start_only
)
1544 exec_params
.flags
&= ~EXEC_APPLY_SANDBOXING
;
1545 if (s
->root_directory_start_only
)
1546 exec_params
.flags
&= ~EXEC_APPLY_CHROOT
;
1549 if ((flags
& EXEC_PASS_FDS
) ||
1550 s
->exec_context
.std_input
== EXEC_INPUT_SOCKET
||
1551 s
->exec_context
.std_output
== EXEC_OUTPUT_SOCKET
||
1552 s
->exec_context
.std_error
== EXEC_OUTPUT_SOCKET
) {
1554 r
= service_collect_fds(s
,
1556 &exec_params
.fd_names
,
1557 &exec_params
.n_socket_fds
,
1558 &exec_params
.n_storage_fds
);
1562 exec_params
.open_files
= s
->open_files
;
1564 log_unit_debug(UNIT(s
), "Passing %zu fds to service", exec_params
.n_socket_fds
+ exec_params
.n_storage_fds
);
1567 if (!FLAGS_SET(flags
, EXEC_IS_CONTROL
) && s
->type
== SERVICE_EXEC
) {
1568 r
= service_allocate_exec_fd(s
, &exec_fd_source
, &exec_params
.exec_fd
);
1573 r
= service_arm_timer(s
, /* relative= */ true, timeout
);
1577 our_env
= new0(char*, 12);
1581 if (service_exec_needs_notify_socket(s
, flags
)) {
1582 if (asprintf(our_env
+ n_env
++, "NOTIFY_SOCKET=%s", UNIT(s
)->manager
->notify_socket
) < 0)
1585 exec_params
.notify_socket
= UNIT(s
)->manager
->notify_socket
;
1588 if (s
->main_pid
> 0)
1589 if (asprintf(our_env
+ n_env
++, "MAINPID="PID_FMT
, s
->main_pid
) < 0)
1592 if (MANAGER_IS_USER(UNIT(s
)->manager
))
1593 if (asprintf(our_env
+ n_env
++, "MANAGERPID="PID_FMT
, getpid_cached()) < 0)
1597 if (asprintf(our_env
+ n_env
++, "PIDFILE=%s", s
->pid_file
) < 0)
1600 if (s
->socket_fd
>= 0) {
1601 union sockaddr_union sa
;
1602 socklen_t salen
= sizeof(sa
);
1604 /* If this is a per-connection service instance, let's set $REMOTE_ADDR and $REMOTE_PORT to something
1605 * useful. Note that we do this only when we are still connected at this point in time, which we might
1606 * very well not be. Hence we ignore all errors when retrieving peer information (as that might result
1607 * in ENOTCONN), and just use whate we can use. */
1609 if (getpeername(s
->socket_fd
, &sa
.sa
, &salen
) >= 0 &&
1610 IN_SET(sa
.sa
.sa_family
, AF_INET
, AF_INET6
, AF_VSOCK
)) {
1611 _cleanup_free_
char *addr
= NULL
;
1615 r
= sockaddr_pretty(&sa
.sa
, salen
, true, false, &addr
);
1619 t
= strjoin("REMOTE_ADDR=", addr
);
1622 our_env
[n_env
++] = t
;
1624 r
= sockaddr_port(&sa
.sa
, &port
);
1628 if (asprintf(&t
, "REMOTE_PORT=%u", port
) < 0)
1630 our_env
[n_env
++] = t
;
1634 Service
*env_source
= NULL
;
1635 const char *monitor_prefix
;
1636 if (flags
& EXEC_SETENV_RESULT
) {
1638 monitor_prefix
= "";
1639 } else if (flags
& EXEC_SETENV_MONITOR_RESULT
) {
1640 env_source
= service_get_triggering_service(s
);
1641 monitor_prefix
= "MONITOR_";
1645 if (asprintf(our_env
+ n_env
++, "%sSERVICE_RESULT=%s", monitor_prefix
, service_result_to_string(env_source
->result
)) < 0)
1648 if (env_source
->main_exec_status
.pid
> 0 &&
1649 dual_timestamp_is_set(&env_source
->main_exec_status
.exit_timestamp
)) {
1650 if (asprintf(our_env
+ n_env
++, "%sEXIT_CODE=%s", monitor_prefix
, sigchld_code_to_string(env_source
->main_exec_status
.code
)) < 0)
1653 if (env_source
->main_exec_status
.code
== CLD_EXITED
)
1654 r
= asprintf(our_env
+ n_env
++, "%sEXIT_STATUS=%i", monitor_prefix
, env_source
->main_exec_status
.status
);
1656 r
= asprintf(our_env
+ n_env
++, "%sEXIT_STATUS=%s", monitor_prefix
, signal_to_string(env_source
->main_exec_status
.status
));
1662 if (env_source
!= s
) {
1663 if (!sd_id128_is_null(UNIT(env_source
)->invocation_id
)) {
1664 r
= asprintf(our_env
+ n_env
++, "%sINVOCATION_ID=" SD_ID128_FORMAT_STR
,
1665 monitor_prefix
, SD_ID128_FORMAT_VAL(UNIT(env_source
)->invocation_id
));
1670 if (asprintf(our_env
+ n_env
++, "%sUNIT=%s", monitor_prefix
, UNIT(env_source
)->id
) < 0)
1675 if (UNIT(s
)->activation_details
) {
1676 r
= activation_details_append_env(UNIT(s
)->activation_details
, &our_env
);
1679 /* The number of env vars added here can vary, rather than keeping the allocation block in
1680 * sync manually, these functions simply use the strv methods to append to it, so we need
1681 * to update n_env when we are done in case of future usage. */
1685 r
= unit_set_exec_params(UNIT(s
), &exec_params
);
1689 final_env
= strv_env_merge(exec_params
.environment
, our_env
);
1693 /* System D-Bus needs nss-systemd disabled, so that we don't deadlock */
1694 SET_FLAG(exec_params
.flags
, EXEC_NSS_DYNAMIC_BYPASS
,
1695 MANAGER_IS_SYSTEM(UNIT(s
)->manager
) && unit_has_name(UNIT(s
), SPECIAL_DBUS_SERVICE
));
1697 strv_free_and_replace(exec_params
.environment
, final_env
);
1698 exec_params
.watchdog_usec
= service_get_watchdog_usec(s
);
1699 exec_params
.selinux_context_net
= s
->socket_fd_selinux_context_net
;
1700 if (s
->type
== SERVICE_IDLE
)
1701 exec_params
.idle_pipe
= UNIT(s
)->manager
->idle_pipe
;
1702 exec_params
.stdin_fd
= s
->stdin_fd
;
1703 exec_params
.stdout_fd
= s
->stdout_fd
;
1704 exec_params
.stderr_fd
= s
->stderr_fd
;
1706 r
= exec_spawn(UNIT(s
),
1716 s
->exec_fd_event_source
= TAKE_PTR(exec_fd_source
);
1717 s
->exec_fd_hot
= false;
1719 r
= unit_watch_pid(UNIT(s
), pid
, true);
1728 static int main_pid_good(Service
*s
) {
1731 /* Returns 0 if the pid is dead, > 0 if it is good, < 0 if we don't know */
1733 /* If we know the pid file, then let's just check if it is
1735 if (s
->main_pid_known
) {
1737 /* If it's an alien child let's check if it is still
1739 if (s
->main_pid_alien
&& s
->main_pid
> 0)
1740 return pid_is_alive(s
->main_pid
);
1742 /* .. otherwise assume we'll get a SIGCHLD for it,
1743 * which we really should wait for to collect exit
1744 * status and code */
1745 return s
->main_pid
> 0;
1748 /* We don't know the pid */
1752 static int control_pid_good(Service
*s
) {
1755 /* Returns 0 if the control PID is dead, > 0 if it is good. We never actually return < 0 here, but in order to
1756 * make this function as similar as possible to main_pid_good() and cgroup_good(), we pretend that < 0 also
1757 * means: we can't figure it out. */
1759 return s
->control_pid
> 0;
1762 static int cgroup_good(Service
*s
) {
1767 /* Returns 0 if the cgroup is empty or doesn't exist, > 0 if it is exists and is populated, < 0 if we can't
1770 if (!UNIT(s
)->cgroup_path
)
1773 r
= cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER
, UNIT(s
)->cgroup_path
);
1780 static bool service_shall_restart(Service
*s
, const char **reason
) {
1783 /* Don't restart after manual stops */
1784 if (s
->forbid_restart
) {
1785 *reason
= "manual stop";
1789 /* Never restart if this is configured as special exception */
1790 if (exit_status_set_test(&s
->restart_prevent_status
, s
->main_exec_status
.code
, s
->main_exec_status
.status
)) {
1791 *reason
= "prevented by exit status";
1795 /* Restart if the exit code/status are configured as restart triggers */
1796 if (exit_status_set_test(&s
->restart_force_status
, s
->main_exec_status
.code
, s
->main_exec_status
.status
)) {
1797 *reason
= "forced by exit status";
1801 *reason
= "restart setting";
1802 switch (s
->restart
) {
1804 case SERVICE_RESTART_NO
:
1807 case SERVICE_RESTART_ALWAYS
:
1808 return s
->result
!= SERVICE_SKIP_CONDITION
;
1810 case SERVICE_RESTART_ON_SUCCESS
:
1811 return s
->result
== SERVICE_SUCCESS
;
1813 case SERVICE_RESTART_ON_FAILURE
:
1814 return !IN_SET(s
->result
, SERVICE_SUCCESS
, SERVICE_SKIP_CONDITION
);
1816 case SERVICE_RESTART_ON_ABNORMAL
:
1817 return !IN_SET(s
->result
, SERVICE_SUCCESS
, SERVICE_FAILURE_EXIT_CODE
, SERVICE_SKIP_CONDITION
);
1819 case SERVICE_RESTART_ON_WATCHDOG
:
1820 return s
->result
== SERVICE_FAILURE_WATCHDOG
;
1822 case SERVICE_RESTART_ON_ABORT
:
1823 return IN_SET(s
->result
, SERVICE_FAILURE_SIGNAL
, SERVICE_FAILURE_CORE_DUMP
);
1826 assert_not_reached();
1830 static bool service_will_restart(Unit
*u
) {
1831 Service
*s
= SERVICE(u
);
1835 if (s
->will_auto_restart
)
1837 if (s
->state
== SERVICE_AUTO_RESTART
)
1840 return unit_will_restart_default(u
);
1843 static void service_enter_dead(Service
*s
, ServiceResult f
, bool allow_restart
) {
1844 ServiceState end_state
;
1849 /* If there's a stop job queued before we enter the DEAD state, we shouldn't act on Restart=, in order to not
1850 * undo what has already been enqueued. */
1851 if (unit_stop_pending(UNIT(s
)))
1852 allow_restart
= false;
1854 if (s
->result
== SERVICE_SUCCESS
)
1857 if (s
->result
== SERVICE_SUCCESS
) {
1858 unit_log_success(UNIT(s
));
1859 end_state
= SERVICE_DEAD
;
1860 } else if (s
->result
== SERVICE_SKIP_CONDITION
) {
1861 unit_log_skip(UNIT(s
), service_result_to_string(s
->result
));
1862 end_state
= SERVICE_DEAD
;
1864 unit_log_failure(UNIT(s
), service_result_to_string(s
->result
));
1865 end_state
= SERVICE_FAILED
;
1867 unit_warn_leftover_processes(UNIT(s
), unit_log_leftover_process_stop
);
1870 log_unit_debug(UNIT(s
), "Service restart not allowed.");
1875 shall_restart
= service_shall_restart(s
, &reason
);
1876 log_unit_debug(UNIT(s
), "Service will %srestart (%s)",
1877 shall_restart
? "" : "not ",
1880 s
->will_auto_restart
= true;
1883 /* Make sure service_release_resources() doesn't destroy our FD store, while we are changing through
1884 * SERVICE_FAILED/SERVICE_DEAD before entering into SERVICE_AUTO_RESTART. */
1885 s
->n_keep_fd_store
++;
1887 service_set_state(s
, end_state
);
1889 if (s
->will_auto_restart
) {
1890 s
->will_auto_restart
= false;
1892 r
= service_arm_timer(s
, /* relative= */ true, s
->restart_usec
);
1894 s
->n_keep_fd_store
--;
1898 service_set_state(s
, SERVICE_AUTO_RESTART
);
1900 /* If we shan't restart, then flush out the restart counter. But don't do that immediately, so that the
1901 * user can still introspect the counter. Do so on the next start. */
1902 s
->flush_n_restarts
= true;
1904 /* The new state is in effect, let's decrease the fd store ref counter again. Let's also re-add us to the GC
1905 * queue, so that the fd store is possibly gc'ed again */
1906 s
->n_keep_fd_store
--;
1907 unit_add_to_gc_queue(UNIT(s
));
1909 /* The next restart might not be a manual stop, hence reset the flag indicating manual stops */
1910 s
->forbid_restart
= false;
1912 /* We want fresh tmpdirs in case service is started again immediately */
1913 s
->exec_runtime
= exec_runtime_unref(s
->exec_runtime
, true);
1915 /* Also, remove the runtime directory */
1916 unit_destroy_runtime_data(UNIT(s
), &s
->exec_context
);
1918 /* Get rid of the IPC bits of the user */
1919 unit_unref_uid_gid(UNIT(s
), true);
1921 /* Release the user, and destroy it if we are the only remaining owner */
1922 dynamic_creds_destroy(&s
->dynamic_creds
);
1924 /* Try to delete the pid file. At this point it will be
1925 * out-of-date, and some software might be confused by it, so
1926 * let's remove it. */
1928 (void) unlink(s
->pid_file
);
1930 /* Reset TTY ownership if necessary */
1931 exec_context_revert_tty(&s
->exec_context
);
1936 log_unit_warning_errno(UNIT(s
), r
, "Failed to run install restart timer: %m");
1937 service_enter_dead(s
, SERVICE_FAILURE_RESOURCES
, false);
1940 static void service_enter_stop_post(Service
*s
, ServiceResult f
) {
1944 if (s
->result
== SERVICE_SUCCESS
)
1947 service_unwatch_control_pid(s
);
1948 (void) unit_enqueue_rewatch_pids(UNIT(s
));
1950 s
->control_command
= s
->exec_command
[SERVICE_EXEC_STOP_POST
];
1951 if (s
->control_command
) {
1952 s
->control_command_id
= SERVICE_EXEC_STOP_POST
;
1954 r
= service_spawn(s
,
1956 s
->timeout_stop_usec
,
1957 EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_APPLY_TTY_STDIN
|EXEC_IS_CONTROL
|EXEC_SETENV_RESULT
|EXEC_CONTROL_CGROUP
,
1962 service_set_state(s
, SERVICE_STOP_POST
);
1964 service_enter_signal(s
, SERVICE_FINAL_SIGTERM
, SERVICE_SUCCESS
);
1969 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'stop-post' task: %m");
1970 service_enter_signal(s
, SERVICE_FINAL_SIGTERM
, SERVICE_FAILURE_RESOURCES
);
1973 static int state_to_kill_operation(Service
*s
, ServiceState state
) {
1976 case SERVICE_STOP_WATCHDOG
:
1977 case SERVICE_FINAL_WATCHDOG
:
1978 return KILL_WATCHDOG
;
1980 case SERVICE_STOP_SIGTERM
:
1981 if (unit_has_job_type(UNIT(s
), JOB_RESTART
))
1982 return KILL_RESTART
;
1985 case SERVICE_FINAL_SIGTERM
:
1986 return KILL_TERMINATE
;
1988 case SERVICE_STOP_SIGKILL
:
1989 case SERVICE_FINAL_SIGKILL
:
1993 return _KILL_OPERATION_INVALID
;
1997 static void service_enter_signal(Service
*s
, ServiceState state
, ServiceResult f
) {
1998 int kill_operation
, r
;
2002 if (s
->result
== SERVICE_SUCCESS
)
2005 /* Before sending any signal, make sure we track all members of this cgroup */
2006 (void) unit_watch_all_pids(UNIT(s
));
2008 /* Also, enqueue a job that we recheck all our PIDs a bit later, given that it's likely some processes have
2010 (void) unit_enqueue_rewatch_pids(UNIT(s
));
2012 kill_operation
= state_to_kill_operation(s
, state
);
2013 r
= unit_kill_context(
2024 r
= service_arm_timer(s
, /* relative= */ true,
2025 kill_operation
== KILL_WATCHDOG
? service_timeout_abort_usec(s
) : s
->timeout_stop_usec
);
2029 service_set_state(s
, state
);
2030 } else if (IN_SET(state
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
) && s
->kill_context
.send_sigkill
)
2031 service_enter_signal(s
, SERVICE_STOP_SIGKILL
, SERVICE_SUCCESS
);
2032 else if (IN_SET(state
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
))
2033 service_enter_stop_post(s
, SERVICE_SUCCESS
);
2034 else if (IN_SET(state
, SERVICE_FINAL_WATCHDOG
, SERVICE_FINAL_SIGTERM
) && s
->kill_context
.send_sigkill
)
2035 service_enter_signal(s
, SERVICE_FINAL_SIGKILL
, SERVICE_SUCCESS
);
2037 service_enter_dead(s
, SERVICE_SUCCESS
, true);
2042 log_unit_warning_errno(UNIT(s
), r
, "Failed to kill processes: %m");
2044 if (IN_SET(state
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
))
2045 service_enter_stop_post(s
, SERVICE_FAILURE_RESOURCES
);
2047 service_enter_dead(s
, SERVICE_FAILURE_RESOURCES
, true);
2050 static void service_enter_stop_by_notify(Service
*s
) {
2053 (void) unit_enqueue_rewatch_pids(UNIT(s
));
2055 service_arm_timer(s
, /* relative= */ true, s
->timeout_stop_usec
);
2057 /* The service told us it's stopping, so it's as if we SIGTERM'd it. */
2058 service_set_state(s
, SERVICE_STOP_SIGTERM
);
2061 static void service_enter_stop(Service
*s
, ServiceResult f
) {
2066 if (s
->result
== SERVICE_SUCCESS
)
2069 service_unwatch_control_pid(s
);
2070 (void) unit_enqueue_rewatch_pids(UNIT(s
));
2072 s
->control_command
= s
->exec_command
[SERVICE_EXEC_STOP
];
2073 if (s
->control_command
) {
2074 s
->control_command_id
= SERVICE_EXEC_STOP
;
2076 r
= service_spawn(s
,
2078 s
->timeout_stop_usec
,
2079 EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_IS_CONTROL
|EXEC_SETENV_RESULT
|EXEC_CONTROL_CGROUP
,
2084 service_set_state(s
, SERVICE_STOP
);
2086 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_SUCCESS
);
2091 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'stop' task: %m");
2092 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_RESOURCES
);
2095 static bool service_good(Service
*s
) {
2099 if (s
->type
== SERVICE_DBUS
&& !s
->bus_name_good
)
2102 main_pid_ok
= main_pid_good(s
);
2103 if (main_pid_ok
> 0) /* It's alive */
2105 if (main_pid_ok
== 0) /* It's dead */
2108 /* OK, we don't know anything about the main PID, maybe
2109 * because there is none. Let's check the control group
2112 return cgroup_good(s
) != 0;
2115 static void service_enter_running(Service
*s
, ServiceResult f
) {
2118 if (s
->result
== SERVICE_SUCCESS
)
2121 service_unwatch_control_pid(s
);
2123 if (s
->result
!= SERVICE_SUCCESS
)
2124 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
2125 else if (service_good(s
)) {
2127 /* If there are any queued up sd_notify() notifications, process them now */
2128 if (s
->notify_state
== NOTIFY_RELOADING
)
2129 service_enter_reload_by_notify(s
);
2130 else if (s
->notify_state
== NOTIFY_STOPPING
)
2131 service_enter_stop_by_notify(s
);
2133 service_set_state(s
, SERVICE_RUNNING
);
2134 service_arm_timer(s
, /* relative= */ false, service_running_timeout(s
));
2137 } else if (s
->remain_after_exit
)
2138 service_set_state(s
, SERVICE_EXITED
);
2140 service_enter_stop(s
, SERVICE_SUCCESS
);
2143 static void service_enter_start_post(Service
*s
) {
2147 service_unwatch_control_pid(s
);
2148 service_reset_watchdog(s
);
2150 s
->control_command
= s
->exec_command
[SERVICE_EXEC_START_POST
];
2151 if (s
->control_command
) {
2152 s
->control_command_id
= SERVICE_EXEC_START_POST
;
2154 r
= service_spawn(s
,
2156 s
->timeout_start_usec
,
2157 EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_IS_CONTROL
|EXEC_CONTROL_CGROUP
,
2162 service_set_state(s
, SERVICE_START_POST
);
2164 service_enter_running(s
, SERVICE_SUCCESS
);
2169 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'start-post' task: %m");
2170 service_enter_stop(s
, SERVICE_FAILURE_RESOURCES
);
2173 static void service_kill_control_process(Service
*s
) {
2178 if (s
->control_pid
<= 0)
2181 r
= kill_and_sigcont(s
->control_pid
, SIGKILL
);
2183 _cleanup_free_
char *comm
= NULL
;
2185 (void) get_process_comm(s
->control_pid
, &comm
);
2187 log_unit_debug_errno(UNIT(s
), r
, "Failed to kill control process " PID_FMT
" (%s), ignoring: %m",
2188 s
->control_pid
, strna(comm
));
2192 static int service_adverse_to_leftover_processes(Service
*s
) {
2195 /* KillMode=mixed and control group are used to indicate that all process should be killed off.
2196 * SendSIGKILL= is used for services that require a clean shutdown. These are typically database
2197 * service where a SigKilled process would result in a lengthy recovery and who's shutdown or startup
2198 * time is quite variable (so Timeout settings aren't of use).
2200 * Here we take these two factors and refuse to start a service if there are existing processes
2201 * within a control group. Databases, while generally having some protection against multiple
2202 * instances running, lets not stress the rigor of these. Also ExecStartPre= parts of the service
2203 * aren't as rigoriously written to protect aganst against multiple use. */
2205 if (unit_warn_leftover_processes(UNIT(s
), unit_log_leftover_process_start
) > 0 &&
2206 IN_SET(s
->kill_context
.kill_mode
, KILL_MIXED
, KILL_CONTROL_GROUP
) &&
2207 !s
->kill_context
.send_sigkill
)
2208 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(EBUSY
),
2209 "Will not start SendSIGKILL=no service of type KillMode=control-group or mixed while processes exist");
2214 static void service_enter_start(Service
*s
) {
2222 service_unwatch_control_pid(s
);
2223 service_unwatch_main_pid(s
);
2225 r
= service_adverse_to_leftover_processes(s
);
2229 if (s
->type
== SERVICE_FORKING
) {
2230 s
->control_command_id
= SERVICE_EXEC_START
;
2231 c
= s
->control_command
= s
->exec_command
[SERVICE_EXEC_START
];
2233 s
->main_command
= NULL
;
2235 s
->control_command_id
= _SERVICE_EXEC_COMMAND_INVALID
;
2236 s
->control_command
= NULL
;
2238 c
= s
->main_command
= s
->exec_command
[SERVICE_EXEC_START
];
2242 if (s
->type
!= SERVICE_ONESHOT
) {
2243 /* There's no command line configured for the main command? Hmm, that is strange.
2244 * This can only happen if the configuration changes at runtime. In this case,
2245 * let's enter a failure state. */
2246 r
= log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENXIO
), "There's no 'start' task anymore we could start.");
2250 /* We force a fake state transition here. Otherwise, the unit would go directly from
2251 * SERVICE_DEAD to SERVICE_DEAD without SERVICE_ACTIVATING or SERVICE_ACTIVE
2252 * in between. This way we can later trigger actions that depend on the state
2253 * transition, including SuccessAction=. */
2254 service_set_state(s
, SERVICE_START
);
2256 service_enter_start_post(s
);
2260 if (IN_SET(s
->type
, SERVICE_SIMPLE
, SERVICE_IDLE
))
2261 /* For simple + idle this is the main process. We don't apply any timeout here, but
2262 * service_enter_running() will later apply the .runtime_max_usec timeout. */
2263 timeout
= USEC_INFINITY
;
2265 timeout
= s
->timeout_start_usec
;
2267 r
= service_spawn(s
,
2270 EXEC_PASS_FDS
|EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_APPLY_TTY_STDIN
|EXEC_SET_WATCHDOG
|EXEC_WRITE_CREDENTIALS
|EXEC_SETENV_MONITOR_RESULT
,
2275 if (IN_SET(s
->type
, SERVICE_SIMPLE
, SERVICE_IDLE
)) {
2276 /* For simple services we immediately start
2277 * the START_POST binaries. */
2279 (void) service_set_main_pid(s
, pid
);
2280 service_enter_start_post(s
);
2282 } else if (s
->type
== SERVICE_FORKING
) {
2284 /* For forking services we wait until the start
2285 * process exited. */
2287 s
->control_pid
= pid
;
2288 service_set_state(s
, SERVICE_START
);
2290 } else if (IN_SET(s
->type
, SERVICE_ONESHOT
, SERVICE_DBUS
, SERVICE_NOTIFY
, SERVICE_NOTIFY_RELOAD
, SERVICE_EXEC
)) {
2292 /* For oneshot services we wait until the start process exited, too, but it is our main process. */
2294 /* For D-Bus services we know the main pid right away, but wait for the bus name to appear on the
2295 * bus. 'notify' and 'exec' services are similar. */
2297 (void) service_set_main_pid(s
, pid
);
2298 service_set_state(s
, SERVICE_START
);
2300 assert_not_reached();
2305 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'start' task: %m");
2306 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_RESOURCES
);
2309 static void service_enter_start_pre(Service
*s
) {
2314 service_unwatch_control_pid(s
);
2316 s
->control_command
= s
->exec_command
[SERVICE_EXEC_START_PRE
];
2317 if (s
->control_command
) {
2319 r
= service_adverse_to_leftover_processes(s
);
2323 s
->control_command_id
= SERVICE_EXEC_START_PRE
;
2325 r
= service_spawn(s
,
2327 s
->timeout_start_usec
,
2328 EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_IS_CONTROL
|EXEC_APPLY_TTY_STDIN
|EXEC_SETENV_MONITOR_RESULT
|EXEC_WRITE_CREDENTIALS
,
2333 service_set_state(s
, SERVICE_START_PRE
);
2335 service_enter_start(s
);
2340 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'start-pre' task: %m");
2341 service_enter_dead(s
, SERVICE_FAILURE_RESOURCES
, true);
2344 static void service_enter_condition(Service
*s
) {
2349 service_unwatch_control_pid(s
);
2351 s
->control_command
= s
->exec_command
[SERVICE_EXEC_CONDITION
];
2352 if (s
->control_command
) {
2354 r
= service_adverse_to_leftover_processes(s
);
2358 s
->control_command_id
= SERVICE_EXEC_CONDITION
;
2360 r
= service_spawn(s
,
2362 s
->timeout_start_usec
,
2363 EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_IS_CONTROL
|EXEC_APPLY_TTY_STDIN
,
2369 service_set_state(s
, SERVICE_CONDITION
);
2371 service_enter_start_pre(s
);
2376 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'exec-condition' task: %m");
2377 service_enter_dead(s
, SERVICE_FAILURE_RESOURCES
, true);
2380 static void service_enter_restart(Service
*s
) {
2381 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2386 if (unit_has_job_type(UNIT(s
), JOB_STOP
)) {
2387 /* Don't restart things if we are going down anyway */
2388 log_unit_info(UNIT(s
), "Stop job pending for unit, skipping automatic restart.");
2392 /* Any units that are bound to this service must also be
2393 * restarted. We use JOB_RESTART (instead of the more obvious
2394 * JOB_START) here so that those dependency jobs will be added
2396 r
= manager_add_job(UNIT(s
)->manager
, JOB_RESTART
, UNIT(s
), JOB_REPLACE
, NULL
, &error
, NULL
);
2400 /* Count the jobs we enqueue for restarting. This counter is maintained as long as the unit isn't fully
2401 * stopped, i.e. as long as it remains up or remains in auto-start states. The user can reset the counter
2402 * explicitly however via the usual "systemctl reset-failure" logic. */
2404 s
->flush_n_restarts
= false;
2406 log_unit_struct(UNIT(s
), LOG_INFO
,
2407 "MESSAGE_ID=" SD_MESSAGE_UNIT_RESTART_SCHEDULED_STR
,
2408 LOG_UNIT_INVOCATION_ID(UNIT(s
)),
2409 LOG_UNIT_MESSAGE(UNIT(s
),
2410 "Scheduled restart job, restart counter is at %u.", s
->n_restarts
),
2411 "N_RESTARTS=%u", s
->n_restarts
);
2413 /* Notify clients about changed restart counter */
2414 unit_add_to_dbus_queue(UNIT(s
));
2416 /* Note that we stay in the SERVICE_AUTO_RESTART state here,
2417 * it will be canceled as part of the service_stop() call that
2418 * is executed as part of JOB_RESTART. */
2423 log_unit_warning(UNIT(s
), "Failed to schedule restart job: %s", bus_error_message(&error
, r
));
2424 service_enter_dead(s
, SERVICE_FAILURE_RESOURCES
, false);
2427 static void service_enter_reload_by_notify(Service
*s
) {
2428 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2433 service_arm_timer(s
, /* relative= */ true, s
->timeout_start_usec
);
2434 service_set_state(s
, SERVICE_RELOAD_NOTIFY
);
2436 /* service_enter_reload_by_notify is never called during a reload, thus no loops are possible. */
2437 r
= manager_propagate_reload(UNIT(s
)->manager
, UNIT(s
), JOB_FAIL
, &error
);
2439 log_unit_warning(UNIT(s
), "Failed to schedule propagation of reload: %s", bus_error_message(&error
, r
));
2442 static void service_enter_reload(Service
*s
) {
2443 bool killed
= false;
2448 service_unwatch_control_pid(s
);
2449 s
->reload_result
= SERVICE_SUCCESS
;
2451 usec_t ts
= now(CLOCK_MONOTONIC
);
2453 if (s
->type
== SERVICE_NOTIFY_RELOAD
&& s
->main_pid
> 0) {
2454 r
= kill_and_sigcont(s
->main_pid
, s
->reload_signal
);
2456 log_unit_warning_errno(UNIT(s
), r
, "Failed to send reload signal: %m");
2463 s
->control_command
= s
->exec_command
[SERVICE_EXEC_RELOAD
];
2464 if (s
->control_command
) {
2465 s
->control_command_id
= SERVICE_EXEC_RELOAD
;
2467 r
= service_spawn(s
,
2469 s
->timeout_start_usec
,
2470 EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_IS_CONTROL
|EXEC_CONTROL_CGROUP
,
2473 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'reload' task: %m");
2477 service_set_state(s
, SERVICE_RELOAD
);
2478 } else if (killed
) {
2479 service_arm_timer(s
, /* relative= */ true, s
->timeout_start_usec
);
2480 service_set_state(s
, SERVICE_RELOAD_SIGNAL
);
2482 service_enter_running(s
, SERVICE_SUCCESS
);
2486 /* Store the timestamp when we started reloading: when reloading via SIGHUP we won't leave the reload
2487 * state until we received both RELOADING=1 and READY=1 with MONOTONIC_USEC= set to a value above
2488 * this. Thus we know for sure the reload cycle was executed *after* we requested it, and is not one
2489 * that was already in progress before. */
2490 s
->reload_begin_usec
= ts
;
2494 s
->reload_result
= SERVICE_FAILURE_RESOURCES
;
2495 service_enter_running(s
, SERVICE_SUCCESS
);
2498 static void service_run_next_control(Service
*s
) {
2503 assert(s
->control_command
);
2504 assert(s
->control_command
->command_next
);
2506 assert(s
->control_command_id
!= SERVICE_EXEC_START
);
2508 s
->control_command
= s
->control_command
->command_next
;
2509 service_unwatch_control_pid(s
);
2511 if (IN_SET(s
->state
, SERVICE_CONDITION
, SERVICE_START_PRE
, SERVICE_START
, SERVICE_START_POST
, SERVICE_RUNNING
, SERVICE_RELOAD
))
2512 timeout
= s
->timeout_start_usec
;
2514 timeout
= s
->timeout_stop_usec
;
2516 r
= service_spawn(s
,
2519 EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_IS_CONTROL
|
2520 (IN_SET(s
->control_command_id
, SERVICE_EXEC_CONDITION
, SERVICE_EXEC_START_PRE
, SERVICE_EXEC_STOP_POST
) ? EXEC_APPLY_TTY_STDIN
: 0)|
2521 (IN_SET(s
->control_command_id
, SERVICE_EXEC_STOP
, SERVICE_EXEC_STOP_POST
) ? EXEC_SETENV_RESULT
: 0)|
2522 (IN_SET(s
->control_command_id
, SERVICE_EXEC_START_PRE
, SERVICE_EXEC_START
) ? EXEC_SETENV_MONITOR_RESULT
: 0)|
2523 (IN_SET(s
->control_command_id
, SERVICE_EXEC_START_POST
, SERVICE_EXEC_RELOAD
, SERVICE_EXEC_STOP
, SERVICE_EXEC_STOP_POST
) ? EXEC_CONTROL_CGROUP
: 0),
2531 log_unit_warning_errno(UNIT(s
), r
, "Failed to run next control task: %m");
2533 if (IN_SET(s
->state
, SERVICE_CONDITION
, SERVICE_START_PRE
, SERVICE_START_POST
, SERVICE_STOP
))
2534 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_RESOURCES
);
2535 else if (s
->state
== SERVICE_STOP_POST
)
2536 service_enter_dead(s
, SERVICE_FAILURE_RESOURCES
, true);
2537 else if (s
->state
== SERVICE_RELOAD
) {
2538 s
->reload_result
= SERVICE_FAILURE_RESOURCES
;
2539 service_enter_running(s
, SERVICE_SUCCESS
);
2541 service_enter_stop(s
, SERVICE_FAILURE_RESOURCES
);
2544 static void service_run_next_main(Service
*s
) {
2549 assert(s
->main_command
);
2550 assert(s
->main_command
->command_next
);
2551 assert(s
->type
== SERVICE_ONESHOT
);
2553 s
->main_command
= s
->main_command
->command_next
;
2554 service_unwatch_main_pid(s
);
2556 r
= service_spawn(s
,
2558 s
->timeout_start_usec
,
2559 EXEC_PASS_FDS
|EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_APPLY_TTY_STDIN
|EXEC_SET_WATCHDOG
|EXEC_SETENV_MONITOR_RESULT
,
2564 (void) service_set_main_pid(s
, pid
);
2569 log_unit_warning_errno(UNIT(s
), r
, "Failed to run next main task: %m");
2570 service_enter_stop(s
, SERVICE_FAILURE_RESOURCES
);
2573 static int service_start(Unit
*u
) {
2574 Service
*s
= SERVICE(u
);
2579 /* We cannot fulfill this request right now, try again later
2581 if (IN_SET(s
->state
,
2582 SERVICE_STOP
, SERVICE_STOP_WATCHDOG
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
, SERVICE_STOP_POST
,
2583 SERVICE_FINAL_WATCHDOG
, SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
, SERVICE_CLEANING
))
2586 /* Already on it! */
2587 if (IN_SET(s
->state
, SERVICE_CONDITION
, SERVICE_START_PRE
, SERVICE_START
, SERVICE_START_POST
))
2590 /* A service that will be restarted must be stopped first to
2591 * trigger BindsTo and/or OnFailure dependencies. If a user
2592 * does not want to wait for the holdoff time to elapse, the
2593 * service should be manually restarted, not started. We
2594 * simply return EAGAIN here, so that any start jobs stay
2595 * queued, and assume that the auto restart timer will
2596 * eventually trigger the restart. */
2597 if (s
->state
== SERVICE_AUTO_RESTART
)
2600 assert(IN_SET(s
->state
, SERVICE_DEAD
, SERVICE_FAILED
));
2602 r
= unit_acquire_invocation_id(u
);
2606 s
->result
= SERVICE_SUCCESS
;
2607 s
->reload_result
= SERVICE_SUCCESS
;
2608 s
->main_pid_known
= false;
2609 s
->main_pid_alien
= false;
2610 s
->forbid_restart
= false;
2612 s
->status_text
= mfree(s
->status_text
);
2613 s
->status_errno
= 0;
2615 s
->notify_state
= NOTIFY_UNKNOWN
;
2617 s
->watchdog_original_usec
= s
->watchdog_usec
;
2618 s
->watchdog_override_enable
= false;
2619 s
->watchdog_override_usec
= USEC_INFINITY
;
2621 exec_command_reset_status_list_array(s
->exec_command
, _SERVICE_EXEC_COMMAND_MAX
);
2622 exec_status_reset(&s
->main_exec_status
);
2624 /* This is not an automatic restart? Flush the restart counter then */
2625 if (s
->flush_n_restarts
) {
2627 s
->flush_n_restarts
= false;
2630 u
->reset_accounting
= true;
2632 service_enter_condition(s
);
2636 static int service_stop(Unit
*u
) {
2637 Service
*s
= SERVICE(u
);
2641 /* Don't create restart jobs from manual stops. */
2642 s
->forbid_restart
= true;
2645 if (IN_SET(s
->state
,
2646 SERVICE_STOP
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
, SERVICE_STOP_POST
,
2647 SERVICE_FINAL_WATCHDOG
, SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
))
2650 /* A restart will be scheduled or is in progress. */
2651 if (s
->state
== SERVICE_AUTO_RESTART
) {
2652 service_set_state(s
, SERVICE_DEAD
);
2656 /* If there's already something running we go directly into kill mode. */
2657 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
)) {
2658 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_SUCCESS
);
2662 /* If we are currently cleaning, then abort it, brutally. */
2663 if (s
->state
== SERVICE_CLEANING
) {
2664 service_enter_signal(s
, SERVICE_FINAL_SIGKILL
, SERVICE_SUCCESS
);
2668 assert(IN_SET(s
->state
, SERVICE_RUNNING
, SERVICE_EXITED
));
2670 service_enter_stop(s
, SERVICE_SUCCESS
);
2674 static int service_reload(Unit
*u
) {
2675 Service
*s
= SERVICE(u
);
2679 assert(IN_SET(s
->state
, SERVICE_RUNNING
, SERVICE_EXITED
));
2681 service_enter_reload(s
);
2685 _pure_
static bool service_can_reload(Unit
*u
) {
2686 Service
*s
= SERVICE(u
);
2690 return s
->exec_command
[SERVICE_EXEC_RELOAD
] ||
2691 s
->type
== SERVICE_NOTIFY_RELOAD
;
2694 static unsigned service_exec_command_index(Unit
*u
, ServiceExecCommand id
, ExecCommand
*current
) {
2695 Service
*s
= SERVICE(u
);
2697 ExecCommand
*first
, *c
;
2701 assert(id
< _SERVICE_EXEC_COMMAND_MAX
);
2703 first
= s
->exec_command
[id
];
2705 /* Figure out where we are in the list by walking back to the beginning */
2706 for (c
= current
; c
!= first
; c
= c
->command_prev
)
2712 static int service_serialize_exec_command(Unit
*u
, FILE *f
, ExecCommand
*command
) {
2713 _cleanup_free_
char *args
= NULL
, *p
= NULL
;
2714 Service
*s
= SERVICE(u
);
2715 const char *type
, *key
;
2716 ServiceExecCommand id
;
2726 if (command
== s
->control_command
) {
2728 id
= s
->control_command_id
;
2731 id
= SERVICE_EXEC_START
;
2734 idx
= service_exec_command_index(u
, id
, command
);
2736 STRV_FOREACH(arg
, command
->argv
) {
2737 _cleanup_free_
char *e
= NULL
;
2745 if (!GREEDY_REALLOC(args
, length
+ 2 + n
+ 2))
2749 args
[length
++] = ' ';
2751 args
[length
++] = '"';
2752 memcpy(args
+ length
, e
, n
);
2754 args
[length
++] = '"';
2757 if (!GREEDY_REALLOC(args
, length
+ 1))
2762 p
= cescape(command
->path
);
2766 key
= strjoina(type
, "-command");
2767 (void) serialize_item_format(f
, key
, "%s %u %s %s", service_exec_command_to_string(id
), idx
, p
, args
);
2772 static int service_serialize(Unit
*u
, FILE *f
, FDSet
*fds
) {
2773 Service
*s
= SERVICE(u
);
2780 (void) serialize_item(f
, "state", service_state_to_string(s
->state
));
2781 (void) serialize_item(f
, "result", service_result_to_string(s
->result
));
2782 (void) serialize_item(f
, "reload-result", service_result_to_string(s
->reload_result
));
2784 if (s
->control_pid
> 0)
2785 (void) serialize_item_format(f
, "control-pid", PID_FMT
, s
->control_pid
);
2787 if (s
->main_pid_known
&& s
->main_pid
> 0)
2788 (void) serialize_item_format(f
, "main-pid", PID_FMT
, s
->main_pid
);
2790 (void) serialize_bool(f
, "main-pid-known", s
->main_pid_known
);
2791 (void) serialize_bool(f
, "bus-name-good", s
->bus_name_good
);
2792 (void) serialize_bool(f
, "bus-name-owner", s
->bus_name_owner
);
2794 (void) serialize_item_format(f
, "n-restarts", "%u", s
->n_restarts
);
2795 (void) serialize_bool(f
, "flush-n-restarts", s
->flush_n_restarts
);
2797 r
= serialize_item_escaped(f
, "status-text", s
->status_text
);
2801 service_serialize_exec_command(u
, f
, s
->control_command
);
2802 service_serialize_exec_command(u
, f
, s
->main_command
);
2804 r
= serialize_fd(f
, fds
, "stdin-fd", s
->stdin_fd
);
2807 r
= serialize_fd(f
, fds
, "stdout-fd", s
->stdout_fd
);
2810 r
= serialize_fd(f
, fds
, "stderr-fd", s
->stderr_fd
);
2814 if (s
->exec_fd_event_source
) {
2815 r
= serialize_fd(f
, fds
, "exec-fd", sd_event_source_get_io_fd(s
->exec_fd_event_source
));
2819 (void) serialize_bool(f
, "exec-fd-hot", s
->exec_fd_hot
);
2822 if (UNIT_ISSET(s
->accept_socket
)) {
2823 r
= serialize_item(f
, "accept-socket", UNIT_DEREF(s
->accept_socket
)->id
);
2828 r
= serialize_fd(f
, fds
, "socket-fd", s
->socket_fd
);
2832 LIST_FOREACH(fd_store
, fs
, s
->fd_store
) {
2833 _cleanup_free_
char *c
= NULL
;
2836 copy
= fdset_put_dup(fds
, fs
->fd
);
2838 return log_error_errno(copy
, "Failed to copy file descriptor for serialization: %m");
2840 c
= cescape(fs
->fdname
);
2844 (void) serialize_item_format(f
, "fd-store-fd", "%i \"%s\" %i", copy
, c
, fs
->do_poll
);
2847 if (s
->main_exec_status
.pid
> 0) {
2848 (void) serialize_item_format(f
, "main-exec-status-pid", PID_FMT
, s
->main_exec_status
.pid
);
2849 (void) serialize_dual_timestamp(f
, "main-exec-status-start", &s
->main_exec_status
.start_timestamp
);
2850 (void) serialize_dual_timestamp(f
, "main-exec-status-exit", &s
->main_exec_status
.exit_timestamp
);
2852 if (dual_timestamp_is_set(&s
->main_exec_status
.exit_timestamp
)) {
2853 (void) serialize_item_format(f
, "main-exec-status-code", "%i", s
->main_exec_status
.code
);
2854 (void) serialize_item_format(f
, "main-exec-status-status", "%i", s
->main_exec_status
.status
);
2858 (void) serialize_dual_timestamp(f
, "watchdog-timestamp", &s
->watchdog_timestamp
);
2859 (void) serialize_bool(f
, "forbid-restart", s
->forbid_restart
);
2861 if (s
->watchdog_override_enable
)
2862 (void) serialize_item_format(f
, "watchdog-override-usec", USEC_FMT
, s
->watchdog_override_usec
);
2864 if (s
->watchdog_original_usec
!= USEC_INFINITY
)
2865 (void) serialize_item_format(f
, "watchdog-original-usec", USEC_FMT
, s
->watchdog_original_usec
);
2867 if (s
->reload_begin_usec
!= USEC_INFINITY
)
2868 (void) serialize_item_format(f
, "reload-begin-usec", USEC_FMT
, s
->reload_begin_usec
);
2873 int service_deserialize_exec_command(
2876 const char *value
) {
2878 Service
*s
= SERVICE(u
);
2880 unsigned idx
= 0, i
;
2881 bool control
, found
= false;
2882 ServiceExecCommand id
= _SERVICE_EXEC_COMMAND_INVALID
;
2883 ExecCommand
*command
= NULL
;
2884 _cleanup_free_
char *path
= NULL
;
2885 _cleanup_strv_free_
char **argv
= NULL
;
2887 enum ExecCommandState
{
2888 STATE_EXEC_COMMAND_TYPE
,
2889 STATE_EXEC_COMMAND_INDEX
,
2890 STATE_EXEC_COMMAND_PATH
,
2891 STATE_EXEC_COMMAND_ARGS
,
2892 _STATE_EXEC_COMMAND_MAX
,
2893 _STATE_EXEC_COMMAND_INVALID
= -EINVAL
,
2900 control
= streq(key
, "control-command");
2902 state
= STATE_EXEC_COMMAND_TYPE
;
2905 _cleanup_free_
char *arg
= NULL
;
2907 r
= extract_first_word(&value
, &arg
, NULL
, EXTRACT_CUNESCAPE
| EXTRACT_UNQUOTE
);
2914 case STATE_EXEC_COMMAND_TYPE
:
2915 id
= service_exec_command_from_string(arg
);
2919 state
= STATE_EXEC_COMMAND_INDEX
;
2921 case STATE_EXEC_COMMAND_INDEX
:
2922 r
= safe_atou(arg
, &idx
);
2926 state
= STATE_EXEC_COMMAND_PATH
;
2928 case STATE_EXEC_COMMAND_PATH
:
2929 path
= TAKE_PTR(arg
);
2930 state
= STATE_EXEC_COMMAND_ARGS
;
2932 case STATE_EXEC_COMMAND_ARGS
:
2933 r
= strv_extend(&argv
, arg
);
2938 assert_not_reached();
2942 if (state
!= STATE_EXEC_COMMAND_ARGS
)
2944 if (strv_isempty(argv
))
2945 return -EINVAL
; /* At least argv[0] must be always present. */
2947 /* Let's check whether exec command on given offset matches data that we just deserialized */
2948 for (command
= s
->exec_command
[id
], i
= 0; command
; command
= command
->command_next
, i
++) {
2952 found
= strv_equal(argv
, command
->argv
) && streq(command
->path
, path
);
2957 /* Command at the index we serialized is different, let's look for command that exactly
2958 * matches but is on different index. If there is no such command we will not resume execution. */
2959 for (command
= s
->exec_command
[id
]; command
; command
= command
->command_next
)
2960 if (strv_equal(command
->argv
, argv
) && streq(command
->path
, path
))
2964 if (command
&& control
) {
2965 s
->control_command
= command
;
2966 s
->control_command_id
= id
;
2968 s
->main_command
= command
;
2970 log_unit_warning(u
, "Current command vanished from the unit file, execution of the command list won't be resumed.");
2975 static int service_deserialize_item(Unit
*u
, const char *key
, const char *value
, FDSet
*fds
) {
2976 Service
*s
= SERVICE(u
);
2984 if (streq(key
, "state")) {
2987 state
= service_state_from_string(value
);
2989 log_unit_debug(u
, "Failed to parse state value: %s", value
);
2991 s
->deserialized_state
= state
;
2992 } else if (streq(key
, "result")) {
2995 f
= service_result_from_string(value
);
2997 log_unit_debug(u
, "Failed to parse result value: %s", value
);
2998 else if (f
!= SERVICE_SUCCESS
)
3001 } else if (streq(key
, "reload-result")) {
3004 f
= service_result_from_string(value
);
3006 log_unit_debug(u
, "Failed to parse reload result value: %s", value
);
3007 else if (f
!= SERVICE_SUCCESS
)
3008 s
->reload_result
= f
;
3010 } else if (streq(key
, "control-pid")) {
3013 if (parse_pid(value
, &pid
) < 0)
3014 log_unit_debug(u
, "Failed to parse control-pid value: %s", value
);
3016 s
->control_pid
= pid
;
3017 } else if (streq(key
, "main-pid")) {
3020 if (parse_pid(value
, &pid
) < 0)
3021 log_unit_debug(u
, "Failed to parse main-pid value: %s", value
);
3023 (void) service_set_main_pid(s
, pid
);
3024 } else if (streq(key
, "main-pid-known")) {
3027 b
= parse_boolean(value
);
3029 log_unit_debug(u
, "Failed to parse main-pid-known value: %s", value
);
3031 s
->main_pid_known
= b
;
3032 } else if (streq(key
, "bus-name-good")) {
3035 b
= parse_boolean(value
);
3037 log_unit_debug(u
, "Failed to parse bus-name-good value: %s", value
);
3039 s
->bus_name_good
= b
;
3040 } else if (streq(key
, "bus-name-owner")) {
3041 r
= free_and_strdup(&s
->bus_name_owner
, value
);
3043 log_unit_error_errno(u
, r
, "Unable to deserialize current bus owner %s: %m", value
);
3044 } else if (streq(key
, "status-text")) {
3048 l
= cunescape(value
, 0, &t
);
3050 log_unit_debug_errno(u
, l
, "Failed to unescape status text '%s': %m", value
);
3052 free_and_replace(s
->status_text
, t
);
3054 } else if (streq(key
, "accept-socket")) {
3057 r
= manager_load_unit(u
->manager
, value
, NULL
, NULL
, &socket
);
3059 log_unit_debug_errno(u
, r
, "Failed to load accept-socket unit '%s': %m", value
);
3061 unit_ref_set(&s
->accept_socket
, u
, socket
);
3062 SOCKET(socket
)->n_connections
++;
3065 } else if (streq(key
, "socket-fd")) {
3068 if (safe_atoi(value
, &fd
) < 0 || fd
< 0 || !fdset_contains(fds
, fd
))
3069 log_unit_debug(u
, "Failed to parse socket-fd value: %s", value
);
3071 asynchronous_close(s
->socket_fd
);
3072 s
->socket_fd
= fdset_remove(fds
, fd
);
3074 } else if (streq(key
, "fd-store-fd")) {
3075 _cleanup_free_
char *fdv
= NULL
, *fdn
= NULL
, *fdp
= NULL
;
3079 r
= extract_first_word(&value
, &fdv
, NULL
, 0);
3080 if (r
<= 0 || safe_atoi(fdv
, &fd
) < 0 || fd
< 0 || !fdset_contains(fds
, fd
)) {
3081 log_unit_debug(u
, "Failed to parse fd-store-fd value: %s", value
);
3085 r
= extract_first_word(&value
, &fdn
, NULL
, EXTRACT_CUNESCAPE
| EXTRACT_UNQUOTE
);
3087 log_unit_debug(u
, "Failed to parse fd-store-fd value: %s", value
);
3091 r
= extract_first_word(&value
, &fdp
, NULL
, 0);
3093 /* If the value is not present, we assume the default */
3095 } else if (r
< 0 || safe_atoi(fdp
, &do_poll
) < 0) {
3096 log_unit_debug_errno(u
, r
, "Failed to parse fd-store-fd value \"%s\": %m", value
);
3100 r
= service_add_fd_store(s
, fd
, fdn
, do_poll
);
3102 log_unit_error_errno(u
, r
, "Failed to add fd to store: %m");
3104 fdset_remove(fds
, fd
);
3105 } else if (streq(key
, "main-exec-status-pid")) {
3108 if (parse_pid(value
, &pid
) < 0)
3109 log_unit_debug(u
, "Failed to parse main-exec-status-pid value: %s", value
);
3111 s
->main_exec_status
.pid
= pid
;
3112 } else if (streq(key
, "main-exec-status-code")) {
3115 if (safe_atoi(value
, &i
) < 0)
3116 log_unit_debug(u
, "Failed to parse main-exec-status-code value: %s", value
);
3118 s
->main_exec_status
.code
= i
;
3119 } else if (streq(key
, "main-exec-status-status")) {
3122 if (safe_atoi(value
, &i
) < 0)
3123 log_unit_debug(u
, "Failed to parse main-exec-status-status value: %s", value
);
3125 s
->main_exec_status
.status
= i
;
3126 } else if (streq(key
, "main-exec-status-start"))
3127 deserialize_dual_timestamp(value
, &s
->main_exec_status
.start_timestamp
);
3128 else if (streq(key
, "main-exec-status-exit"))
3129 deserialize_dual_timestamp(value
, &s
->main_exec_status
.exit_timestamp
);
3130 else if (streq(key
, "watchdog-timestamp"))
3131 deserialize_dual_timestamp(value
, &s
->watchdog_timestamp
);
3132 else if (streq(key
, "forbid-restart")) {
3135 b
= parse_boolean(value
);
3137 log_unit_debug(u
, "Failed to parse forbid-restart value: %s", value
);
3139 s
->forbid_restart
= b
;
3140 } else if (streq(key
, "stdin-fd")) {
3143 if (safe_atoi(value
, &fd
) < 0 || fd
< 0 || !fdset_contains(fds
, fd
))
3144 log_unit_debug(u
, "Failed to parse stdin-fd value: %s", value
);
3146 asynchronous_close(s
->stdin_fd
);
3147 s
->stdin_fd
= fdset_remove(fds
, fd
);
3148 s
->exec_context
.stdio_as_fds
= true;
3150 } else if (streq(key
, "stdout-fd")) {
3153 if (safe_atoi(value
, &fd
) < 0 || fd
< 0 || !fdset_contains(fds
, fd
))
3154 log_unit_debug(u
, "Failed to parse stdout-fd value: %s", value
);
3156 asynchronous_close(s
->stdout_fd
);
3157 s
->stdout_fd
= fdset_remove(fds
, fd
);
3158 s
->exec_context
.stdio_as_fds
= true;
3160 } else if (streq(key
, "stderr-fd")) {
3163 if (safe_atoi(value
, &fd
) < 0 || fd
< 0 || !fdset_contains(fds
, fd
))
3164 log_unit_debug(u
, "Failed to parse stderr-fd value: %s", value
);
3166 asynchronous_close(s
->stderr_fd
);
3167 s
->stderr_fd
= fdset_remove(fds
, fd
);
3168 s
->exec_context
.stdio_as_fds
= true;
3170 } else if (streq(key
, "exec-fd")) {
3173 if (safe_atoi(value
, &fd
) < 0 || fd
< 0 || !fdset_contains(fds
, fd
))
3174 log_unit_debug(u
, "Failed to parse exec-fd value: %s", value
);
3176 s
->exec_fd_event_source
= sd_event_source_disable_unref(s
->exec_fd_event_source
);
3178 fd
= fdset_remove(fds
, fd
);
3179 if (service_allocate_exec_fd_event_source(s
, fd
, &s
->exec_fd_event_source
) < 0)
3182 } else if (streq(key
, "watchdog-override-usec")) {
3183 if (deserialize_usec(value
, &s
->watchdog_override_usec
) < 0)
3184 log_unit_debug(u
, "Failed to parse watchdog_override_usec value: %s", value
);
3186 s
->watchdog_override_enable
= true;
3188 } else if (streq(key
, "watchdog-original-usec")) {
3189 if (deserialize_usec(value
, &s
->watchdog_original_usec
) < 0)
3190 log_unit_debug(u
, "Failed to parse watchdog_original_usec value: %s", value
);
3192 } else if (STR_IN_SET(key
, "main-command", "control-command")) {
3193 r
= service_deserialize_exec_command(u
, key
, value
);
3195 log_unit_debug_errno(u
, r
, "Failed to parse serialized command \"%s\": %m", value
);
3197 } else if (streq(key
, "n-restarts")) {
3198 r
= safe_atou(value
, &s
->n_restarts
);
3200 log_unit_debug_errno(u
, r
, "Failed to parse serialized restart counter '%s': %m", value
);
3202 } else if (streq(key
, "flush-n-restarts")) {
3203 r
= parse_boolean(value
);
3205 log_unit_debug_errno(u
, r
, "Failed to parse serialized flush restart counter setting '%s': %m", value
);
3207 s
->flush_n_restarts
= r
;
3208 } else if (streq(key
, "reload-begin-usec")) {
3209 r
= deserialize_usec(value
, &s
->reload_begin_usec
);
3211 log_unit_debug_errno(u
, r
, "Failed to parse serialized reload begin timestamp '%s', ignoring: %m", value
);
3213 log_unit_debug(u
, "Unknown serialization key: %s", key
);
3218 _pure_
static UnitActiveState
service_active_state(Unit
*u
) {
3219 const UnitActiveState
*table
;
3223 table
= SERVICE(u
)->type
== SERVICE_IDLE
? state_translation_table_idle
: state_translation_table
;
3225 return table
[SERVICE(u
)->state
];
3228 static const char *service_sub_state_to_string(Unit
*u
) {
3231 return service_state_to_string(SERVICE(u
)->state
);
3234 static bool service_may_gc(Unit
*u
) {
3235 Service
*s
= SERVICE(u
);
3239 /* Never clean up services that still have a process around, even if the service is formally dead. Note that
3240 * unit_may_gc() already checked our cgroup for us, we just check our two additional PIDs, too, in case they
3241 * have moved outside of the cgroup. */
3243 if (main_pid_good(s
) > 0 ||
3244 control_pid_good(s
) > 0)
3250 static int service_retry_pid_file(Service
*s
) {
3253 assert(s
->pid_file
);
3254 assert(IN_SET(s
->state
, SERVICE_START
, SERVICE_START_POST
));
3256 r
= service_load_pid_file(s
, false);
3260 service_unwatch_pid_file(s
);
3262 service_enter_running(s
, SERVICE_SUCCESS
);
3266 static int service_watch_pid_file(Service
*s
) {
3269 log_unit_debug(UNIT(s
), "Setting watch for PID file %s", s
->pid_file_pathspec
->path
);
3271 r
= path_spec_watch(s
->pid_file_pathspec
, service_dispatch_inotify_io
);
3275 /* the pidfile might have appeared just before we set the watch */
3276 log_unit_debug(UNIT(s
), "Trying to read PID file %s in case it changed", s
->pid_file_pathspec
->path
);
3277 service_retry_pid_file(s
);
3281 log_unit_error_errno(UNIT(s
), r
, "Failed to set a watch for PID file %s: %m", s
->pid_file_pathspec
->path
);
3282 service_unwatch_pid_file(s
);
3286 static int service_demand_pid_file(Service
*s
) {
3289 assert(s
->pid_file
);
3290 assert(!s
->pid_file_pathspec
);
3292 ps
= new0(PathSpec
, 1);
3297 ps
->path
= strdup(s
->pid_file
);
3303 path_simplify(ps
->path
);
3305 /* PATH_CHANGED would not be enough. There are daemons (sendmail) that
3306 * keep their PID file open all the time. */
3307 ps
->type
= PATH_MODIFIED
;
3308 ps
->inotify_fd
= -EBADF
;
3310 s
->pid_file_pathspec
= ps
;
3312 return service_watch_pid_file(s
);
3315 static int service_dispatch_inotify_io(sd_event_source
*source
, int fd
, uint32_t events
, void *userdata
) {
3316 PathSpec
*p
= ASSERT_PTR(userdata
);
3319 s
= SERVICE(p
->unit
);
3323 assert(IN_SET(s
->state
, SERVICE_START
, SERVICE_START_POST
));
3324 assert(s
->pid_file_pathspec
);
3325 assert(path_spec_owns_inotify_fd(s
->pid_file_pathspec
, fd
));
3327 log_unit_debug(UNIT(s
), "inotify event");
3329 if (path_spec_fd_event(p
, events
) < 0)
3332 if (service_retry_pid_file(s
) == 0)
3335 if (service_watch_pid_file(s
) < 0)
3341 service_unwatch_pid_file(s
);
3342 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_RESOURCES
);
3346 static int service_dispatch_exec_io(sd_event_source
*source
, int fd
, uint32_t events
, void *userdata
) {
3347 Service
*s
= SERVICE(userdata
);
3351 log_unit_debug(UNIT(s
), "got exec-fd event");
3353 /* If Type=exec is set, we'll consider a service started successfully the instant we invoked execve()
3354 * successfully for it. We implement this through a pipe() towards the child, which the kernel automatically
3355 * closes for us due to O_CLOEXEC on execve() in the child, which then triggers EOF on the pipe in the
3356 * parent. We need to be careful however, as there are other reasons that we might cause the child's side of
3357 * the pipe to be closed (for example, a simple exit()). To deal with that we'll ignore EOFs on the pipe unless
3358 * the child signalled us first that it is about to call the execve(). It does so by sending us a simple
3359 * non-zero byte via the pipe. We also provide the child with a way to inform us in case execve() failed: if it
3360 * sends a zero byte we'll ignore POLLHUP on the fd again. */
3366 n
= read(fd
, &x
, sizeof(x
));
3368 if (errno
== EAGAIN
) /* O_NONBLOCK in effect → everything queued has now been processed. */
3371 return log_unit_error_errno(UNIT(s
), errno
, "Failed to read from exec_fd: %m");
3373 if (n
== 0) { /* EOF → the event we are waiting for */
3375 s
->exec_fd_event_source
= sd_event_source_disable_unref(s
->exec_fd_event_source
);
3377 if (s
->exec_fd_hot
) { /* Did the child tell us to expect EOF now? */
3378 log_unit_debug(UNIT(s
), "Got EOF on exec-fd");
3380 s
->exec_fd_hot
= false;
3382 /* Nice! This is what we have been waiting for. Transition to next state. */
3383 if (s
->type
== SERVICE_EXEC
&& s
->state
== SERVICE_START
)
3384 service_enter_start_post(s
);
3386 log_unit_debug(UNIT(s
), "Got EOF on exec-fd while it was disabled, ignoring.");
3391 /* A byte was read → this turns on/off the exec fd logic */
3392 assert(n
== sizeof(x
));
3399 static void service_notify_cgroup_empty_event(Unit
*u
) {
3400 Service
*s
= SERVICE(u
);
3404 log_unit_debug(u
, "Control group is empty.");
3408 /* Waiting for SIGCHLD is usually more interesting,
3409 * because it includes return codes/signals. Which is
3410 * why we ignore the cgroup events for most cases,
3411 * except when we don't know pid which to expect the
3415 if (IN_SET(s
->type
, SERVICE_NOTIFY
, SERVICE_NOTIFY_RELOAD
) &&
3416 main_pid_good(s
) == 0 &&
3417 control_pid_good(s
) == 0) {
3418 /* No chance of getting a ready notification anymore */
3419 service_enter_stop_post(s
, SERVICE_FAILURE_PROTOCOL
);
3423 if (s
->exit_type
== SERVICE_EXIT_CGROUP
&& main_pid_good(s
) <= 0)
3424 service_enter_start_post(s
);
3427 case SERVICE_START_POST
:
3428 if (s
->pid_file_pathspec
&&
3429 main_pid_good(s
) == 0 &&
3430 control_pid_good(s
) == 0) {
3432 /* Give up hoping for the daemon to write its PID file */
3433 log_unit_warning(u
, "Daemon never wrote its PID file. Failing.");
3435 service_unwatch_pid_file(s
);
3436 if (s
->state
== SERVICE_START
)
3437 service_enter_stop_post(s
, SERVICE_FAILURE_PROTOCOL
);
3439 service_enter_stop(s
, SERVICE_FAILURE_PROTOCOL
);
3443 case SERVICE_RUNNING
:
3444 /* service_enter_running() will figure out what to do */
3445 service_enter_running(s
, SERVICE_SUCCESS
);
3448 case SERVICE_STOP_WATCHDOG
:
3449 case SERVICE_STOP_SIGTERM
:
3450 case SERVICE_STOP_SIGKILL
:
3452 if (main_pid_good(s
) <= 0 && control_pid_good(s
) <= 0)
3453 service_enter_stop_post(s
, SERVICE_SUCCESS
);
3457 case SERVICE_STOP_POST
:
3458 case SERVICE_FINAL_WATCHDOG
:
3459 case SERVICE_FINAL_SIGTERM
:
3460 case SERVICE_FINAL_SIGKILL
:
3461 if (main_pid_good(s
) <= 0 && control_pid_good(s
) <= 0)
3462 service_enter_dead(s
, SERVICE_SUCCESS
, true);
3466 /* If the cgroup empty notification comes when the unit is not active, we must have failed to clean
3467 * up the cgroup earlier and should do it now. */
3469 case SERVICE_FAILED
:
3470 unit_prune_cgroup(u
);
3478 static void service_notify_cgroup_oom_event(Unit
*u
, bool managed_oom
) {
3479 Service
*s
= SERVICE(u
);
3482 log_unit_debug(u
, "Process(es) of control group were killed by systemd-oomd.");
3484 log_unit_debug(u
, "Process of control group was killed by the OOM killer.");
3486 if (s
->oom_policy
== OOM_CONTINUE
)
3491 case SERVICE_CONDITION
:
3492 case SERVICE_START_PRE
:
3494 case SERVICE_START_POST
:
3496 if (s
->oom_policy
== OOM_STOP
)
3497 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_OOM_KILL
);
3498 else if (s
->oom_policy
== OOM_KILL
)
3499 service_enter_signal(s
, SERVICE_STOP_SIGKILL
, SERVICE_FAILURE_OOM_KILL
);
3503 case SERVICE_EXITED
:
3504 case SERVICE_RUNNING
:
3505 if (s
->oom_policy
== OOM_STOP
)
3506 service_enter_stop(s
, SERVICE_FAILURE_OOM_KILL
);
3507 else if (s
->oom_policy
== OOM_KILL
)
3508 service_enter_signal(s
, SERVICE_STOP_SIGKILL
, SERVICE_FAILURE_OOM_KILL
);
3512 case SERVICE_STOP_WATCHDOG
:
3513 case SERVICE_STOP_SIGTERM
:
3514 service_enter_signal(s
, SERVICE_STOP_SIGKILL
, SERVICE_FAILURE_OOM_KILL
);
3517 case SERVICE_STOP_SIGKILL
:
3518 case SERVICE_FINAL_SIGKILL
:
3519 if (s
->result
== SERVICE_SUCCESS
)
3520 s
->result
= SERVICE_FAILURE_OOM_KILL
;
3523 case SERVICE_STOP_POST
:
3524 case SERVICE_FINAL_SIGTERM
:
3525 service_enter_signal(s
, SERVICE_FINAL_SIGKILL
, SERVICE_FAILURE_OOM_KILL
);
3533 static void service_sigchld_event(Unit
*u
, pid_t pid
, int code
, int status
) {
3534 bool notify_dbus
= true;
3535 Service
*s
= SERVICE(u
);
3537 ExitClean clean_mode
;
3542 /* Oneshot services and non-SERVICE_EXEC_START commands should not be
3543 * considered daemons as they are typically not long running. */
3544 if (s
->type
== SERVICE_ONESHOT
|| (s
->control_pid
== pid
&& s
->control_command_id
!= SERVICE_EXEC_START
))
3545 clean_mode
= EXIT_CLEAN_COMMAND
;
3547 clean_mode
= EXIT_CLEAN_DAEMON
;
3549 if (is_clean_exit(code
, status
, clean_mode
, &s
->success_status
))
3550 f
= SERVICE_SUCCESS
;
3551 else if (code
== CLD_EXITED
)
3552 f
= SERVICE_FAILURE_EXIT_CODE
;
3553 else if (code
== CLD_KILLED
)
3554 f
= SERVICE_FAILURE_SIGNAL
;
3555 else if (code
== CLD_DUMPED
)
3556 f
= SERVICE_FAILURE_CORE_DUMP
;
3558 assert_not_reached();
3560 if (s
->main_pid
== pid
) {
3561 /* Clean up the exec_fd event source. We want to do this here, not later in
3562 * service_set_state(), because service_enter_stop_post() calls service_spawn().
3563 * The source owns its end of the pipe, so this will close that too. */
3564 s
->exec_fd_event_source
= sd_event_source_disable_unref(s
->exec_fd_event_source
);
3566 /* Forking services may occasionally move to a new PID.
3567 * As long as they update the PID file before exiting the old
3568 * PID, they're fine. */
3569 if (service_load_pid_file(s
, false) > 0)
3573 exec_status_exit(&s
->main_exec_status
, &s
->exec_context
, pid
, code
, status
);
3575 if (s
->main_command
) {
3576 /* If this is not a forking service than the
3577 * main process got started and hence we copy
3578 * the exit status so that it is recorded both
3579 * as main and as control process exit
3582 s
->main_command
->exec_status
= s
->main_exec_status
;
3584 if (s
->main_command
->flags
& EXEC_COMMAND_IGNORE_FAILURE
)
3585 f
= SERVICE_SUCCESS
;
3586 } else if (s
->exec_command
[SERVICE_EXEC_START
]) {
3588 /* If this is a forked process, then we should
3589 * ignore the return value if this was
3590 * configured for the starter process */
3592 if (s
->exec_command
[SERVICE_EXEC_START
]->flags
& EXEC_COMMAND_IGNORE_FAILURE
)
3593 f
= SERVICE_SUCCESS
;
3596 unit_log_process_exit(
3599 service_exec_command_to_string(SERVICE_EXEC_START
),
3600 f
== SERVICE_SUCCESS
,
3603 if (s
->result
== SERVICE_SUCCESS
)
3606 if (s
->main_command
&&
3607 s
->main_command
->command_next
&&
3608 s
->type
== SERVICE_ONESHOT
&&
3609 f
== SERVICE_SUCCESS
) {
3611 /* There is another command to execute, so let's do that. */
3613 log_unit_debug(u
, "Running next main command for state %s.", service_state_to_string(s
->state
));
3614 service_run_next_main(s
);
3617 s
->main_command
= NULL
;
3619 /* Services with ExitType=cgroup do not act on main PID exiting, unless the cgroup is
3621 if (s
->exit_type
== SERVICE_EXIT_MAIN
|| cgroup_good(s
) <= 0) {
3622 /* The service exited, so the service is officially gone. */
3625 case SERVICE_START_POST
:
3626 case SERVICE_RELOAD
:
3627 case SERVICE_RELOAD_SIGNAL
:
3628 case SERVICE_RELOAD_NOTIFY
:
3629 /* If neither main nor control processes are running then the current
3630 * state can never exit cleanly, hence immediately terminate the
3632 if (control_pid_good(s
) <= 0)
3633 service_enter_stop(s
, f
);
3635 /* Otherwise need to wait until the operation is done. */
3639 /* Need to wait until the operation is done. */
3643 if (s
->type
== SERVICE_ONESHOT
) {
3644 /* This was our main goal, so let's go on */
3645 if (f
== SERVICE_SUCCESS
)
3646 service_enter_start_post(s
);
3648 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
3650 } else if (IN_SET(s
->type
, SERVICE_NOTIFY
, SERVICE_NOTIFY_RELOAD
)) {
3651 /* Only enter running through a notification, so that the
3652 * SERVICE_START state signifies that no ready notification
3653 * has been received */
3654 if (f
!= SERVICE_SUCCESS
)
3655 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
3656 else if (!s
->remain_after_exit
|| s
->notify_access
== NOTIFY_MAIN
)
3657 /* The service has never been and will never be active */
3658 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_PROTOCOL
);
3663 case SERVICE_RUNNING
:
3664 service_enter_running(s
, f
);
3667 case SERVICE_STOP_WATCHDOG
:
3668 case SERVICE_STOP_SIGTERM
:
3669 case SERVICE_STOP_SIGKILL
:
3671 if (control_pid_good(s
) <= 0)
3672 service_enter_stop_post(s
, f
);
3674 /* If there is still a control process, wait for that first */
3677 case SERVICE_STOP_POST
:
3679 if (control_pid_good(s
) <= 0)
3680 service_enter_signal(s
, SERVICE_FINAL_SIGTERM
, f
);
3684 case SERVICE_FINAL_WATCHDOG
:
3685 case SERVICE_FINAL_SIGTERM
:
3686 case SERVICE_FINAL_SIGKILL
:
3688 if (control_pid_good(s
) <= 0)
3689 service_enter_dead(s
, f
, true);
3693 assert_not_reached();
3698 } else if (s
->control_pid
== pid
) {
3704 if (s
->control_command
) {
3705 exec_status_exit(&s
->control_command
->exec_status
, &s
->exec_context
, pid
, code
, status
);
3707 if (s
->control_command
->flags
& EXEC_COMMAND_IGNORE_FAILURE
)
3708 f
= SERVICE_SUCCESS
;
3711 /* ExecCondition= calls that exit with (0, 254] should invoke skip-like behavior instead of failing */
3712 if (s
->state
== SERVICE_CONDITION
) {
3713 if (f
== SERVICE_FAILURE_EXIT_CODE
&& status
< 255) {
3714 UNIT(s
)->condition_result
= false;
3715 f
= SERVICE_SKIP_CONDITION
;
3717 } else if (f
== SERVICE_SUCCESS
) {
3718 UNIT(s
)->condition_result
= true;
3723 kind
= "Condition check process";
3725 kind
= "Control process";
3726 success
= f
== SERVICE_SUCCESS
;
3729 unit_log_process_exit(
3732 service_exec_command_to_string(s
->control_command_id
),
3736 if (s
->state
!= SERVICE_RELOAD
&& s
->result
== SERVICE_SUCCESS
)
3739 if (s
->control_command
&&
3740 s
->control_command
->command_next
&&
3741 f
== SERVICE_SUCCESS
) {
3743 /* There is another command to * execute, so let's do that. */
3745 log_unit_debug(u
, "Running next control command for state %s.", service_state_to_string(s
->state
));
3746 service_run_next_control(s
);
3749 /* No further commands for this step, so let's figure out what to do next */
3751 s
->control_command
= NULL
;
3752 s
->control_command_id
= _SERVICE_EXEC_COMMAND_INVALID
;
3754 log_unit_debug(u
, "Got final SIGCHLD for state %s.", service_state_to_string(s
->state
));
3758 case SERVICE_CONDITION
:
3759 if (f
== SERVICE_SUCCESS
)
3760 service_enter_start_pre(s
);
3762 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
3765 case SERVICE_START_PRE
:
3766 if (f
== SERVICE_SUCCESS
)
3767 service_enter_start(s
);
3769 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
3773 if (s
->type
!= SERVICE_FORKING
)
3774 /* Maybe spurious event due to a reload that changed the type? */
3777 if (f
!= SERVICE_SUCCESS
) {
3778 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
3783 bool has_start_post
;
3786 /* Let's try to load the pid file here if we can.
3787 * The PID file might actually be created by a START_POST
3788 * script. In that case don't worry if the loading fails. */
3790 has_start_post
= s
->exec_command
[SERVICE_EXEC_START_POST
];
3791 r
= service_load_pid_file(s
, !has_start_post
);
3792 if (!has_start_post
&& r
< 0) {
3793 r
= service_demand_pid_file(s
);
3794 if (r
< 0 || cgroup_good(s
) == 0)
3795 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_PROTOCOL
);
3799 service_search_main_pid(s
);
3801 service_enter_start_post(s
);
3804 case SERVICE_START_POST
:
3805 if (f
!= SERVICE_SUCCESS
) {
3806 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
3813 r
= service_load_pid_file(s
, true);
3815 r
= service_demand_pid_file(s
);
3816 if (r
< 0 || cgroup_good(s
) == 0)
3817 service_enter_stop(s
, SERVICE_FAILURE_PROTOCOL
);
3821 service_search_main_pid(s
);
3823 service_enter_running(s
, SERVICE_SUCCESS
);
3826 case SERVICE_RELOAD
:
3827 case SERVICE_RELOAD_SIGNAL
:
3828 case SERVICE_RELOAD_NOTIFY
:
3829 if (f
== SERVICE_SUCCESS
)
3830 if (service_load_pid_file(s
, true) < 0)
3831 service_search_main_pid(s
);
3833 s
->reload_result
= f
;
3835 /* If the last notification we received from the service process indicates
3836 * we are still reloading, then don't leave reloading state just yet, just
3837 * transition into SERVICE_RELOAD_NOTIFY, to wait for the READY=1 coming,
3839 if (s
->notify_state
== NOTIFY_RELOADING
)
3840 service_set_state(s
, SERVICE_RELOAD_NOTIFY
);
3842 service_enter_running(s
, SERVICE_SUCCESS
);
3846 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
3849 case SERVICE_STOP_WATCHDOG
:
3850 case SERVICE_STOP_SIGTERM
:
3851 case SERVICE_STOP_SIGKILL
:
3852 if (main_pid_good(s
) <= 0)
3853 service_enter_stop_post(s
, f
);
3855 /* If there is still a service process around, wait until
3856 * that one quit, too */
3859 case SERVICE_STOP_POST
:
3860 if (main_pid_good(s
) <= 0)
3861 service_enter_signal(s
, SERVICE_FINAL_SIGTERM
, f
);
3864 case SERVICE_FINAL_WATCHDOG
:
3865 case SERVICE_FINAL_SIGTERM
:
3866 case SERVICE_FINAL_SIGKILL
:
3867 if (main_pid_good(s
) <= 0)
3868 service_enter_dead(s
, f
, true);
3871 case SERVICE_CLEANING
:
3873 if (s
->clean_result
== SERVICE_SUCCESS
)
3874 s
->clean_result
= f
;
3876 service_enter_dead(s
, SERVICE_SUCCESS
, false);
3880 assert_not_reached();
3883 } else /* Neither control nor main PID? If so, don't notify about anything */
3884 notify_dbus
= false;
3886 /* Notify clients about changed exit status */
3888 unit_add_to_dbus_queue(u
);
3890 /* We watch the main/control process otherwise we can't retrieve the unit they
3891 * belong to with cgroupv1. But if they are not our direct child, we won't get a
3892 * SIGCHLD for them. Therefore we need to look for others to watch so we can
3893 * detect when the cgroup becomes empty. Note that the control process is always
3894 * our child so it's pointless to watch all other processes. */
3895 if (!control_pid_good(s
))
3896 if (!s
->main_pid_known
|| s
->main_pid_alien
)
3897 (void) unit_enqueue_rewatch_pids(u
);
3900 static int service_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
) {
3901 Service
*s
= SERVICE(userdata
);
3904 assert(source
== s
->timer_event_source
);
3908 case SERVICE_CONDITION
:
3909 case SERVICE_START_PRE
:
3911 case SERVICE_START_POST
:
3912 switch (s
->timeout_start_failure_mode
) {
3914 case SERVICE_TIMEOUT_TERMINATE
:
3915 log_unit_warning(UNIT(s
), "%s operation timed out. Terminating.", service_state_to_string(s
->state
));
3916 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_TIMEOUT
);
3919 case SERVICE_TIMEOUT_ABORT
:
3920 log_unit_warning(UNIT(s
), "%s operation timed out. Aborting.", service_state_to_string(s
->state
));
3921 service_enter_signal(s
, SERVICE_STOP_WATCHDOG
, SERVICE_FAILURE_TIMEOUT
);
3924 case SERVICE_TIMEOUT_KILL
:
3925 if (s
->kill_context
.send_sigkill
) {
3926 log_unit_warning(UNIT(s
), "%s operation timed out. Killing.", service_state_to_string(s
->state
));
3927 service_enter_signal(s
, SERVICE_STOP_SIGKILL
, SERVICE_FAILURE_TIMEOUT
);
3929 log_unit_warning(UNIT(s
), "%s operation timed out. Skipping SIGKILL.", service_state_to_string(s
->state
));
3930 service_enter_stop_post(s
, SERVICE_FAILURE_TIMEOUT
);
3935 assert_not_reached();
3939 case SERVICE_RUNNING
:
3940 log_unit_warning(UNIT(s
), "Service reached runtime time limit. Stopping.");
3941 service_enter_stop(s
, SERVICE_FAILURE_TIMEOUT
);
3944 case SERVICE_RELOAD
:
3945 case SERVICE_RELOAD_SIGNAL
:
3946 case SERVICE_RELOAD_NOTIFY
:
3947 log_unit_warning(UNIT(s
), "Reload operation timed out. Killing reload process.");
3948 service_kill_control_process(s
);
3949 s
->reload_result
= SERVICE_FAILURE_TIMEOUT
;
3950 service_enter_running(s
, SERVICE_SUCCESS
);
3954 switch (s
->timeout_stop_failure_mode
) {
3956 case SERVICE_TIMEOUT_TERMINATE
:
3957 log_unit_warning(UNIT(s
), "Stopping timed out. Terminating.");
3958 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_TIMEOUT
);
3961 case SERVICE_TIMEOUT_ABORT
:
3962 log_unit_warning(UNIT(s
), "Stopping timed out. Aborting.");
3963 service_enter_signal(s
, SERVICE_STOP_WATCHDOG
, SERVICE_FAILURE_TIMEOUT
);
3966 case SERVICE_TIMEOUT_KILL
:
3967 if (s
->kill_context
.send_sigkill
) {
3968 log_unit_warning(UNIT(s
), "Stopping timed out. Killing.");
3969 service_enter_signal(s
, SERVICE_STOP_SIGKILL
, SERVICE_FAILURE_TIMEOUT
);
3971 log_unit_warning(UNIT(s
), "Stopping timed out. Skipping SIGKILL.");
3972 service_enter_stop_post(s
, SERVICE_FAILURE_TIMEOUT
);
3977 assert_not_reached();
3981 case SERVICE_STOP_WATCHDOG
:
3982 if (s
->kill_context
.send_sigkill
) {
3983 log_unit_warning(UNIT(s
), "State 'stop-watchdog' timed out. Killing.");
3984 service_enter_signal(s
, SERVICE_STOP_SIGKILL
, SERVICE_FAILURE_TIMEOUT
);
3986 log_unit_warning(UNIT(s
), "State 'stop-watchdog' timed out. Skipping SIGKILL.");
3987 service_enter_stop_post(s
, SERVICE_FAILURE_TIMEOUT
);
3991 case SERVICE_STOP_SIGTERM
:
3992 if (s
->timeout_stop_failure_mode
== SERVICE_TIMEOUT_ABORT
) {
3993 log_unit_warning(UNIT(s
), "State 'stop-sigterm' timed out. Aborting.");
3994 service_enter_signal(s
, SERVICE_STOP_WATCHDOG
, SERVICE_FAILURE_TIMEOUT
);
3995 } else if (s
->kill_context
.send_sigkill
) {
3996 log_unit_warning(UNIT(s
), "State 'stop-sigterm' timed out. Killing.");
3997 service_enter_signal(s
, SERVICE_STOP_SIGKILL
, SERVICE_FAILURE_TIMEOUT
);
3999 log_unit_warning(UNIT(s
), "State 'stop-sigterm' timed out. Skipping SIGKILL.");
4000 service_enter_stop_post(s
, SERVICE_FAILURE_TIMEOUT
);
4005 case SERVICE_STOP_SIGKILL
:
4006 /* Uh, we sent a SIGKILL and it is still not gone?
4007 * Must be something we cannot kill, so let's just be
4008 * weirded out and continue */
4010 log_unit_warning(UNIT(s
), "Processes still around after SIGKILL. Ignoring.");
4011 service_enter_stop_post(s
, SERVICE_FAILURE_TIMEOUT
);
4014 case SERVICE_STOP_POST
:
4015 switch (s
->timeout_stop_failure_mode
) {
4017 case SERVICE_TIMEOUT_TERMINATE
:
4018 log_unit_warning(UNIT(s
), "State 'stop-post' timed out. Terminating.");
4019 service_enter_signal(s
, SERVICE_FINAL_SIGTERM
, SERVICE_FAILURE_TIMEOUT
);
4022 case SERVICE_TIMEOUT_ABORT
:
4023 log_unit_warning(UNIT(s
), "State 'stop-post' timed out. Aborting.");
4024 service_enter_signal(s
, SERVICE_FINAL_WATCHDOG
, SERVICE_FAILURE_TIMEOUT
);
4027 case SERVICE_TIMEOUT_KILL
:
4028 if (s
->kill_context
.send_sigkill
) {
4029 log_unit_warning(UNIT(s
), "State 'stop-post' timed out. Killing.");
4030 service_enter_signal(s
, SERVICE_FINAL_SIGKILL
, SERVICE_FAILURE_TIMEOUT
);
4032 log_unit_warning(UNIT(s
), "State 'stop-post' timed out. Skipping SIGKILL. Entering failed mode.");
4033 service_enter_dead(s
, SERVICE_FAILURE_TIMEOUT
, false);
4038 assert_not_reached();
4042 case SERVICE_FINAL_WATCHDOG
:
4043 if (s
->kill_context
.send_sigkill
) {
4044 log_unit_warning(UNIT(s
), "State 'final-watchdog' timed out. Killing.");
4045 service_enter_signal(s
, SERVICE_FINAL_SIGKILL
, SERVICE_FAILURE_TIMEOUT
);
4047 log_unit_warning(UNIT(s
), "State 'final-watchdog' timed out. Skipping SIGKILL. Entering failed mode.");
4048 service_enter_dead(s
, SERVICE_FAILURE_TIMEOUT
, false);
4052 case SERVICE_FINAL_SIGTERM
:
4053 if (s
->timeout_stop_failure_mode
== SERVICE_TIMEOUT_ABORT
) {
4054 log_unit_warning(UNIT(s
), "State 'final-sigterm' timed out. Aborting.");
4055 service_enter_signal(s
, SERVICE_FINAL_WATCHDOG
, SERVICE_FAILURE_TIMEOUT
);
4056 } else if (s
->kill_context
.send_sigkill
) {
4057 log_unit_warning(UNIT(s
), "State 'final-sigterm' timed out. Killing.");
4058 service_enter_signal(s
, SERVICE_FINAL_SIGKILL
, SERVICE_FAILURE_TIMEOUT
);
4060 log_unit_warning(UNIT(s
), "State 'final-sigterm' timed out. Skipping SIGKILL. Entering failed mode.");
4061 service_enter_dead(s
, SERVICE_FAILURE_TIMEOUT
, false);
4066 case SERVICE_FINAL_SIGKILL
:
4067 log_unit_warning(UNIT(s
), "Processes still around after final SIGKILL. Entering failed mode.");
4068 service_enter_dead(s
, SERVICE_FAILURE_TIMEOUT
, true);
4071 case SERVICE_AUTO_RESTART
:
4072 if (s
->restart_usec
> 0)
4073 log_unit_debug(UNIT(s
),
4074 "Service RestartSec=%s expired, scheduling restart.",
4075 FORMAT_TIMESPAN(s
->restart_usec
, USEC_PER_SEC
));
4077 log_unit_debug(UNIT(s
),
4078 "Service has no hold-off time (RestartSec=0), scheduling restart.");
4080 service_enter_restart(s
);
4083 case SERVICE_CLEANING
:
4084 log_unit_warning(UNIT(s
), "Cleaning timed out. killing.");
4086 if (s
->clean_result
== SERVICE_SUCCESS
)
4087 s
->clean_result
= SERVICE_FAILURE_TIMEOUT
;
4089 service_enter_signal(s
, SERVICE_FINAL_SIGKILL
, 0);
4093 assert_not_reached();
4099 static int service_dispatch_watchdog(sd_event_source
*source
, usec_t usec
, void *userdata
) {
4100 Service
*s
= SERVICE(userdata
);
4101 usec_t watchdog_usec
;
4104 assert(source
== s
->watchdog_event_source
);
4106 watchdog_usec
= service_get_watchdog_usec(s
);
4108 if (UNIT(s
)->manager
->service_watchdogs
) {
4109 log_unit_error(UNIT(s
), "Watchdog timeout (limit %s)!",
4110 FORMAT_TIMESPAN(watchdog_usec
, 1));
4112 service_enter_signal(s
, SERVICE_STOP_WATCHDOG
, SERVICE_FAILURE_WATCHDOG
);
4114 log_unit_warning(UNIT(s
), "Watchdog disabled! Ignoring watchdog timeout (limit %s)!",
4115 FORMAT_TIMESPAN(watchdog_usec
, 1));
4120 static bool service_notify_message_authorized(Service
*s
, pid_t pid
, FDSet
*fds
) {
4123 if (s
->notify_access
== NOTIFY_NONE
) {
4124 log_unit_warning(UNIT(s
), "Got notification message from PID "PID_FMT
", but reception is disabled.", pid
);
4128 if (s
->notify_access
== NOTIFY_MAIN
&& pid
!= s
->main_pid
) {
4129 if (s
->main_pid
!= 0)
4130 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
);
4132 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
);
4137 if (s
->notify_access
== NOTIFY_EXEC
&& pid
!= s
->main_pid
&& pid
!= s
->control_pid
) {
4138 if (s
->main_pid
!= 0 && s
->control_pid
!= 0)
4139 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
,
4140 pid
, s
->main_pid
, s
->control_pid
);
4141 else if (s
->main_pid
!= 0)
4142 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
);
4143 else if (s
->control_pid
!= 0)
4144 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
);
4146 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
);
4154 static void service_force_watchdog(Service
*s
) {
4155 if (!UNIT(s
)->manager
->service_watchdogs
)
4158 log_unit_error(UNIT(s
), "Watchdog request (last status: %s)!",
4159 s
->status_text
? s
->status_text
: "<unset>");
4161 service_enter_signal(s
, SERVICE_STOP_WATCHDOG
, SERVICE_FAILURE_WATCHDOG
);
4164 static void service_notify_message(
4166 const struct ucred
*ucred
,
4170 Service
*s
= SERVICE(u
);
4171 bool notify_dbus
= false;
4172 usec_t monotonic_usec
= USEC_INFINITY
;
4179 if (!service_notify_message_authorized(SERVICE(u
), ucred
->pid
, fds
))
4182 if (DEBUG_LOGGING
) {
4183 _cleanup_free_
char *cc
= NULL
;
4185 cc
= strv_join(tags
, ", ");
4186 log_unit_debug(u
, "Got notification message from PID "PID_FMT
" (%s)", ucred
->pid
, isempty(cc
) ? "n/a" : cc
);
4189 /* Interpret MAINPID= */
4190 e
= strv_find_startswith(tags
, "MAINPID=");
4191 if (e
&& IN_SET(s
->state
, SERVICE_START
, SERVICE_START_POST
, SERVICE_RUNNING
, SERVICE_RELOAD
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
)) {
4194 if (parse_pid(e
, &new_main_pid
) < 0)
4195 log_unit_warning(u
, "Failed to parse MAINPID= field in notification message, ignoring: %s", e
);
4196 else if (!s
->main_pid_known
|| new_main_pid
!= s
->main_pid
) {
4198 r
= service_is_suitable_main_pid(s
, new_main_pid
, LOG_WARNING
);
4200 /* The new main PID is a bit suspicious, which is OK if the sender is privileged. */
4202 if (ucred
->uid
== 0) {
4203 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
);
4206 log_unit_debug(u
, "New main PID "PID_FMT
" does not belong to service, refusing.", new_main_pid
);
4209 (void) service_set_main_pid(s
, new_main_pid
);
4211 r
= unit_watch_pid(UNIT(s
), new_main_pid
, false);
4213 log_unit_warning_errno(UNIT(s
), r
, "Failed to watch new main PID "PID_FMT
" for service: %m", new_main_pid
);
4220 /* Parse MONOTONIC_USEC= */
4221 e
= strv_find_startswith(tags
, "MONOTONIC_USEC=");
4223 r
= safe_atou64(e
, &monotonic_usec
);
4225 log_unit_warning_errno(u
, r
, "Failed to parse MONOTONIC_USEC= field in notification message, ignoring: %s", e
);
4228 /* Interpret READY=/STOPPING=/RELOADING=. STOPPING= wins over the others, and READY= over RELOADING= */
4229 if (strv_contains(tags
, "STOPPING=1")) {
4230 s
->notify_state
= NOTIFY_STOPPING
;
4232 if (IN_SET(s
->state
, SERVICE_RUNNING
, SERVICE_RELOAD_SIGNAL
, SERVICE_RELOAD_NOTIFY
))
4233 service_enter_stop_by_notify(s
);
4237 } else if (strv_contains(tags
, "READY=1")) {
4239 s
->notify_state
= NOTIFY_READY
;
4241 /* Type=notify services inform us about completed initialization with READY=1 */
4242 if (IN_SET(s
->type
, SERVICE_NOTIFY
, SERVICE_NOTIFY_RELOAD
) &&
4243 s
->state
== SERVICE_START
)
4244 service_enter_start_post(s
);
4246 /* Sending READY=1 while we are reloading informs us that the reloading is complete. */
4247 if (s
->state
== SERVICE_RELOAD_NOTIFY
)
4248 service_enter_running(s
, SERVICE_SUCCESS
);
4250 /* Combined RELOADING=1 and READY=1? Then this is indication that the service started and
4251 * immediately finished reloading. */
4252 if (s
->state
== SERVICE_RELOAD_SIGNAL
&&
4253 strv_contains(tags
, "RELOADING=1") &&
4254 monotonic_usec
!= USEC_INFINITY
&&
4255 monotonic_usec
>= s
->reload_begin_usec
) {
4256 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
4258 /* Propagate a reload explicitly */
4259 r
= manager_propagate_reload(UNIT(s
)->manager
, UNIT(s
), JOB_FAIL
, &error
);
4261 log_unit_warning(UNIT(s
), "Failed to schedule propagation of reload, ignoring: %s", bus_error_message(&error
, r
));
4263 service_enter_running(s
, SERVICE_SUCCESS
);
4268 } else if (strv_contains(tags
, "RELOADING=1")) {
4270 s
->notify_state
= NOTIFY_RELOADING
;
4272 /* Sending RELOADING=1 after we send SIGHUP to request a reload will transition
4273 * things to "reload-notify" state, where we'll wait for READY=1 to let us know the
4274 * reload is done. Note that we insist on a timestamp being sent along here, so that
4275 * we know for sure this is a reload cycle initiated *after* we sent the signal */
4276 if (s
->state
== SERVICE_RELOAD_SIGNAL
&&
4277 monotonic_usec
!= USEC_INFINITY
&&
4278 monotonic_usec
>= s
->reload_begin_usec
)
4279 /* Note, we don't call service_enter_reload_by_notify() here, because we
4280 * don't need reload propagation nor do we want to restart the time-out. */
4281 service_set_state(s
, SERVICE_RELOAD_NOTIFY
);
4283 if (s
->state
== SERVICE_RUNNING
)
4284 service_enter_reload_by_notify(s
);
4289 /* Interpret STATUS= */
4290 e
= strv_find_startswith(tags
, "STATUS=");
4292 _cleanup_free_
char *t
= NULL
;
4295 /* Note that this size limit check is mostly paranoia: since the datagram size we are willing
4296 * to process is already limited to NOTIFY_BUFFER_MAX, this limit here should never be hit. */
4297 if (strlen(e
) > STATUS_TEXT_MAX
)
4298 log_unit_warning(u
, "Status message overly long (%zu > %u), ignoring.", strlen(e
), STATUS_TEXT_MAX
);
4299 else if (!utf8_is_valid(e
))
4300 log_unit_warning(u
, "Status message in notification message is not UTF-8 clean, ignoring.");
4308 if (!streq_ptr(s
->status_text
, t
)) {
4309 free_and_replace(s
->status_text
, t
);
4314 /* Interpret ERRNO= */
4315 e
= strv_find_startswith(tags
, "ERRNO=");
4319 status_errno
= parse_errno(e
);
4320 if (status_errno
< 0)
4321 log_unit_warning_errno(u
, status_errno
,
4322 "Failed to parse ERRNO= field value '%s' in notification message: %m", e
);
4323 else if (s
->status_errno
!= status_errno
) {
4324 s
->status_errno
= status_errno
;
4329 /* Interpret EXTEND_TIMEOUT= */
4330 e
= strv_find_startswith(tags
, "EXTEND_TIMEOUT_USEC=");
4332 usec_t extend_timeout_usec
;
4333 if (safe_atou64(e
, &extend_timeout_usec
) < 0)
4334 log_unit_warning(u
, "Failed to parse EXTEND_TIMEOUT_USEC=%s", e
);
4336 service_extend_timeout(s
, extend_timeout_usec
);
4339 /* Interpret WATCHDOG= */
4340 e
= strv_find_startswith(tags
, "WATCHDOG=");
4343 service_reset_watchdog(s
);
4344 else if (streq(e
, "trigger"))
4345 service_force_watchdog(s
);
4347 log_unit_warning(u
, "Passed WATCHDOG= field is invalid, ignoring.");
4350 e
= strv_find_startswith(tags
, "WATCHDOG_USEC=");
4352 usec_t watchdog_override_usec
;
4353 if (safe_atou64(e
, &watchdog_override_usec
) < 0)
4354 log_unit_warning(u
, "Failed to parse WATCHDOG_USEC=%s", e
);
4356 service_override_watchdog_timeout(s
, watchdog_override_usec
);
4359 /* Process FD store messages. Either FDSTOREREMOVE=1 for removal, or FDSTORE=1 for addition. In both cases,
4360 * process FDNAME= for picking the file descriptor name to use. Note that FDNAME= is required when removing
4361 * fds, but optional when pushing in new fds, for compatibility reasons. */
4362 if (strv_contains(tags
, "FDSTOREREMOVE=1")) {
4365 name
= strv_find_startswith(tags
, "FDNAME=");
4366 if (!name
|| !fdname_is_valid(name
))
4367 log_unit_warning(u
, "FDSTOREREMOVE=1 requested, but no valid file descriptor name passed, ignoring.");
4369 service_remove_fd_store(s
, name
);
4371 } else if (strv_contains(tags
, "FDSTORE=1")) {
4374 name
= strv_find_startswith(tags
, "FDNAME=");
4375 if (name
&& !fdname_is_valid(name
)) {
4376 log_unit_warning(u
, "Passed FDNAME= name is invalid, ignoring.");
4380 (void) service_add_fd_store_set(s
, fds
, name
, !strv_contains(tags
, "FDPOLL=0"));
4383 /* Notify clients about changed status or main pid */
4385 unit_add_to_dbus_queue(u
);
4388 static int service_get_timeout(Unit
*u
, usec_t
*timeout
) {
4389 Service
*s
= SERVICE(u
);
4393 if (!s
->timer_event_source
)
4396 r
= sd_event_source_get_time(s
->timer_event_source
, &t
);
4399 if (t
== USEC_INFINITY
)
4406 static bool pick_up_pid_from_bus_name(Service
*s
) {
4409 /* If the service is running but we have no main PID yet, get it from the owner of the D-Bus name */
4411 return !pid_is_valid(s
->main_pid
) &&
4417 SERVICE_RELOAD_SIGNAL
,
4418 SERVICE_RELOAD_NOTIFY
);
4421 static int bus_name_pid_lookup_callback(sd_bus_message
*reply
, void *userdata
, sd_bus_error
*ret_error
) {
4422 const sd_bus_error
*e
;
4423 Unit
*u
= ASSERT_PTR(userdata
);
4431 s
->bus_name_pid_lookup_slot
= sd_bus_slot_unref(s
->bus_name_pid_lookup_slot
);
4433 if (!s
->bus_name
|| !pick_up_pid_from_bus_name(s
))
4436 e
= sd_bus_message_get_error(reply
);
4438 r
= sd_bus_error_get_errno(e
);
4439 log_warning_errno(r
, "GetConnectionUnixProcessID() failed: %s", bus_error_message(e
, r
));
4443 r
= sd_bus_message_read(reply
, "u", &pid
);
4445 bus_log_parse_error(r
);
4449 if (!pid_is_valid(pid
)) {
4450 log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "GetConnectionUnixProcessID() returned invalid PID");
4454 log_unit_debug(u
, "D-Bus name %s is now owned by process " PID_FMT
, s
->bus_name
, (pid_t
) pid
);
4456 (void) service_set_main_pid(s
, pid
);
4457 (void) unit_watch_pid(UNIT(s
), pid
, false);
4461 static void service_bus_name_owner_change(Unit
*u
, const char *new_owner
) {
4463 Service
*s
= SERVICE(u
);
4469 log_unit_debug(u
, "D-Bus name %s now owned by %s", s
->bus_name
, new_owner
);
4471 log_unit_debug(u
, "D-Bus name %s now not owned by anyone.", s
->bus_name
);
4473 s
->bus_name_good
= new_owner
;
4475 /* Track the current owner, so we can reconstruct changes after a daemon reload */
4476 r
= free_and_strdup(&s
->bus_name_owner
, new_owner
);
4478 log_unit_error_errno(u
, r
, "Unable to set new bus name owner %s: %m", new_owner
);
4482 if (s
->type
== SERVICE_DBUS
) {
4484 /* service_enter_running() will figure out what to
4486 if (s
->state
== SERVICE_RUNNING
)
4487 service_enter_running(s
, SERVICE_SUCCESS
);
4488 else if (s
->state
== SERVICE_START
&& new_owner
)
4489 service_enter_start_post(s
);
4491 } else if (new_owner
&& pick_up_pid_from_bus_name(s
)) {
4493 /* Try to acquire PID from bus service */
4495 s
->bus_name_pid_lookup_slot
= sd_bus_slot_unref(s
->bus_name_pid_lookup_slot
);
4497 r
= sd_bus_call_method_async(
4498 u
->manager
->api_bus
,
4499 &s
->bus_name_pid_lookup_slot
,
4500 "org.freedesktop.DBus",
4501 "/org/freedesktop/DBus",
4502 "org.freedesktop.DBus",
4503 "GetConnectionUnixProcessID",
4504 bus_name_pid_lookup_callback
,
4509 log_debug_errno(r
, "Failed to request owner PID of service name, ignoring: %m");
4513 int service_set_socket_fd(
4518 bool selinux_context_net
) {
4520 _cleanup_free_
char *peer_text
= NULL
;
4526 /* This is called by the socket code when instantiating a new service for a stream socket and the socket needs
4527 * to be configured. We take ownership of the passed fd on success. */
4529 if (UNIT(s
)->load_state
!= UNIT_LOADED
)
4532 if (s
->socket_fd
>= 0)
4535 assert(!s
->socket_peer
);
4537 if (s
->state
!= SERVICE_DEAD
)
4540 if (getpeername_pretty(fd
, true, &peer_text
) >= 0) {
4542 if (UNIT(s
)->description
) {
4543 _cleanup_free_
char *a
= NULL
;
4545 a
= strjoin(UNIT(s
)->description
, " (", peer_text
, ")");
4549 r
= unit_set_description(UNIT(s
), a
);
4551 r
= unit_set_description(UNIT(s
), peer_text
);
4556 r
= unit_add_two_dependencies(UNIT(sock
), UNIT_BEFORE
, UNIT_TRIGGERS
, UNIT(s
), false, UNIT_DEPENDENCY_IMPLICIT
);
4561 s
->socket_peer
= socket_peer_ref(peer
);
4562 s
->socket_fd_selinux_context_net
= selinux_context_net
;
4564 unit_ref_set(&s
->accept_socket
, UNIT(s
), UNIT(sock
));
4568 static void service_reset_failed(Unit
*u
) {
4569 Service
*s
= SERVICE(u
);
4573 if (s
->state
== SERVICE_FAILED
)
4574 service_set_state(s
, SERVICE_DEAD
);
4576 s
->result
= SERVICE_SUCCESS
;
4577 s
->reload_result
= SERVICE_SUCCESS
;
4578 s
->clean_result
= SERVICE_SUCCESS
;
4580 s
->flush_n_restarts
= false;
4583 static int service_kill(Unit
*u
, KillWho who
, int signo
, sd_bus_error
*error
) {
4584 Service
*s
= SERVICE(u
);
4588 return unit_kill_common(u
, who
, signo
, s
->main_pid
, s
->control_pid
, error
);
4591 static int service_main_pid(Unit
*u
) {
4592 Service
*s
= SERVICE(u
);
4599 static int service_control_pid(Unit
*u
) {
4600 Service
*s
= SERVICE(u
);
4604 return s
->control_pid
;
4607 static bool service_needs_console(Unit
*u
) {
4608 Service
*s
= SERVICE(u
);
4612 /* We provide our own implementation of this here, instead of relying of the generic implementation
4613 * unit_needs_console() provides, since we want to return false if we are in SERVICE_EXITED state. */
4615 if (!exec_context_may_touch_console(&s
->exec_context
))
4618 return IN_SET(s
->state
,
4625 SERVICE_RELOAD_SIGNAL
,
4626 SERVICE_RELOAD_NOTIFY
,
4628 SERVICE_STOP_WATCHDOG
,
4629 SERVICE_STOP_SIGTERM
,
4630 SERVICE_STOP_SIGKILL
,
4632 SERVICE_FINAL_WATCHDOG
,
4633 SERVICE_FINAL_SIGTERM
,
4634 SERVICE_FINAL_SIGKILL
);
4637 static int service_exit_status(Unit
*u
) {
4638 Service
*s
= SERVICE(u
);
4642 if (s
->main_exec_status
.pid
<= 0 ||
4643 !dual_timestamp_is_set(&s
->main_exec_status
.exit_timestamp
))
4646 if (s
->main_exec_status
.code
!= CLD_EXITED
)
4649 return s
->main_exec_status
.status
;
4652 static const char* service_status_text(Unit
*u
) {
4653 Service
*s
= SERVICE(u
);
4657 return s
->status_text
;
4660 static int service_clean(Unit
*u
, ExecCleanMask mask
) {
4661 _cleanup_strv_free_
char **l
= NULL
;
4662 Service
*s
= SERVICE(u
);
4668 if (s
->state
!= SERVICE_DEAD
)
4671 r
= exec_context_get_clean_directories(&s
->exec_context
, u
->manager
->prefix
, mask
, &l
);
4675 if (strv_isempty(l
))
4678 service_unwatch_control_pid(s
);
4679 s
->clean_result
= SERVICE_SUCCESS
;
4680 s
->control_command
= NULL
;
4681 s
->control_command_id
= _SERVICE_EXEC_COMMAND_INVALID
;
4683 r
= service_arm_timer(s
, /* relative= */ true, s
->exec_context
.timeout_clean_usec
);
4687 r
= unit_fork_and_watch_rm_rf(u
, l
, &s
->control_pid
);
4691 service_set_state(s
, SERVICE_CLEANING
);
4696 log_unit_warning_errno(u
, r
, "Failed to initiate cleaning: %m");
4697 s
->clean_result
= SERVICE_FAILURE_RESOURCES
;
4698 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
4702 static int service_can_clean(Unit
*u
, ExecCleanMask
*ret
) {
4703 Service
*s
= SERVICE(u
);
4707 return exec_context_get_clean_mask(&s
->exec_context
, ret
);
4710 static const char *service_finished_job(Unit
*u
, JobType t
, JobResult result
) {
4711 if (t
== JOB_START
&&
4712 result
== JOB_DONE
&&
4713 SERVICE(u
)->type
== SERVICE_ONESHOT
)
4714 return "Finished %s.";
4716 /* Fall back to generic */
4720 static int service_can_start(Unit
*u
) {
4721 Service
*s
= SERVICE(u
);
4726 /* Make sure we don't enter a busy loop of some kind. */
4727 r
= unit_test_start_limit(u
);
4729 service_enter_dead(s
, SERVICE_FAILURE_START_LIMIT_HIT
, false);
4736 static const char* const service_restart_table
[_SERVICE_RESTART_MAX
] = {
4737 [SERVICE_RESTART_NO
] = "no",
4738 [SERVICE_RESTART_ON_SUCCESS
] = "on-success",
4739 [SERVICE_RESTART_ON_FAILURE
] = "on-failure",
4740 [SERVICE_RESTART_ON_ABNORMAL
] = "on-abnormal",
4741 [SERVICE_RESTART_ON_WATCHDOG
] = "on-watchdog",
4742 [SERVICE_RESTART_ON_ABORT
] = "on-abort",
4743 [SERVICE_RESTART_ALWAYS
] = "always",
4746 DEFINE_STRING_TABLE_LOOKUP(service_restart
, ServiceRestart
);
4748 static const char* const service_type_table
[_SERVICE_TYPE_MAX
] = {
4749 [SERVICE_SIMPLE
] = "simple",
4750 [SERVICE_FORKING
] = "forking",
4751 [SERVICE_ONESHOT
] = "oneshot",
4752 [SERVICE_DBUS
] = "dbus",
4753 [SERVICE_NOTIFY
] = "notify",
4754 [SERVICE_NOTIFY_RELOAD
] = "notify-reload",
4755 [SERVICE_IDLE
] = "idle",
4756 [SERVICE_EXEC
] = "exec",
4759 DEFINE_STRING_TABLE_LOOKUP(service_type
, ServiceType
);
4761 static const char* const service_exit_type_table
[_SERVICE_EXIT_TYPE_MAX
] = {
4762 [SERVICE_EXIT_MAIN
] = "main",
4763 [SERVICE_EXIT_CGROUP
] = "cgroup",
4766 DEFINE_STRING_TABLE_LOOKUP(service_exit_type
, ServiceExitType
);
4768 static const char* const service_exec_command_table
[_SERVICE_EXEC_COMMAND_MAX
] = {
4769 [SERVICE_EXEC_CONDITION
] = "ExecCondition",
4770 [SERVICE_EXEC_START_PRE
] = "ExecStartPre",
4771 [SERVICE_EXEC_START
] = "ExecStart",
4772 [SERVICE_EXEC_START_POST
] = "ExecStartPost",
4773 [SERVICE_EXEC_RELOAD
] = "ExecReload",
4774 [SERVICE_EXEC_STOP
] = "ExecStop",
4775 [SERVICE_EXEC_STOP_POST
] = "ExecStopPost",
4778 DEFINE_STRING_TABLE_LOOKUP(service_exec_command
, ServiceExecCommand
);
4780 static const char* const service_exec_ex_command_table
[_SERVICE_EXEC_COMMAND_MAX
] = {
4781 [SERVICE_EXEC_CONDITION
] = "ExecConditionEx",
4782 [SERVICE_EXEC_START_PRE
] = "ExecStartPreEx",
4783 [SERVICE_EXEC_START
] = "ExecStartEx",
4784 [SERVICE_EXEC_START_POST
] = "ExecStartPostEx",
4785 [SERVICE_EXEC_RELOAD
] = "ExecReloadEx",
4786 [SERVICE_EXEC_STOP
] = "ExecStopEx",
4787 [SERVICE_EXEC_STOP_POST
] = "ExecStopPostEx",
4790 DEFINE_STRING_TABLE_LOOKUP(service_exec_ex_command
, ServiceExecCommand
);
4792 static const char* const notify_state_table
[_NOTIFY_STATE_MAX
] = {
4793 [NOTIFY_UNKNOWN
] = "unknown",
4794 [NOTIFY_READY
] = "ready",
4795 [NOTIFY_RELOADING
] = "reloading",
4796 [NOTIFY_STOPPING
] = "stopping",
4799 DEFINE_STRING_TABLE_LOOKUP(notify_state
, NotifyState
);
4801 static const char* const service_result_table
[_SERVICE_RESULT_MAX
] = {
4802 [SERVICE_SUCCESS
] = "success",
4803 [SERVICE_FAILURE_RESOURCES
] = "resources",
4804 [SERVICE_FAILURE_PROTOCOL
] = "protocol",
4805 [SERVICE_FAILURE_TIMEOUT
] = "timeout",
4806 [SERVICE_FAILURE_EXIT_CODE
] = "exit-code",
4807 [SERVICE_FAILURE_SIGNAL
] = "signal",
4808 [SERVICE_FAILURE_CORE_DUMP
] = "core-dump",
4809 [SERVICE_FAILURE_WATCHDOG
] = "watchdog",
4810 [SERVICE_FAILURE_START_LIMIT_HIT
] = "start-limit-hit",
4811 [SERVICE_FAILURE_OOM_KILL
] = "oom-kill",
4812 [SERVICE_SKIP_CONDITION
] = "exec-condition",
4815 DEFINE_STRING_TABLE_LOOKUP(service_result
, ServiceResult
);
4817 static const char* const service_timeout_failure_mode_table
[_SERVICE_TIMEOUT_FAILURE_MODE_MAX
] = {
4818 [SERVICE_TIMEOUT_TERMINATE
] = "terminate",
4819 [SERVICE_TIMEOUT_ABORT
] = "abort",
4820 [SERVICE_TIMEOUT_KILL
] = "kill",
4823 DEFINE_STRING_TABLE_LOOKUP(service_timeout_failure_mode
, ServiceTimeoutFailureMode
);
4825 const UnitVTable service_vtable
= {
4826 .object_size
= sizeof(Service
),
4827 .exec_context_offset
= offsetof(Service
, exec_context
),
4828 .cgroup_context_offset
= offsetof(Service
, cgroup_context
),
4829 .kill_context_offset
= offsetof(Service
, kill_context
),
4830 .exec_runtime_offset
= offsetof(Service
, exec_runtime
),
4831 .dynamic_creds_offset
= offsetof(Service
, dynamic_creds
),
4837 .private_section
= "Service",
4839 .can_transient
= true,
4840 .can_delegate
= true,
4842 .can_set_managed_oom
= true,
4844 .init
= service_init
,
4845 .done
= service_done
,
4846 .load
= service_load
,
4847 .release_resources
= service_release_resources
,
4849 .coldplug
= service_coldplug
,
4851 .dump
= service_dump
,
4853 .start
= service_start
,
4854 .stop
= service_stop
,
4855 .reload
= service_reload
,
4857 .can_reload
= service_can_reload
,
4859 .kill
= service_kill
,
4860 .clean
= service_clean
,
4861 .can_clean
= service_can_clean
,
4863 .freeze
= unit_freeze_vtable_common
,
4864 .thaw
= unit_thaw_vtable_common
,
4866 .serialize
= service_serialize
,
4867 .deserialize_item
= service_deserialize_item
,
4869 .active_state
= service_active_state
,
4870 .sub_state_to_string
= service_sub_state_to_string
,
4872 .will_restart
= service_will_restart
,
4874 .may_gc
= service_may_gc
,
4876 .sigchld_event
= service_sigchld_event
,
4878 .reset_failed
= service_reset_failed
,
4880 .notify_cgroup_empty
= service_notify_cgroup_empty_event
,
4881 .notify_cgroup_oom
= service_notify_cgroup_oom_event
,
4882 .notify_message
= service_notify_message
,
4884 .main_pid
= service_main_pid
,
4885 .control_pid
= service_control_pid
,
4887 .bus_name_owner_change
= service_bus_name_owner_change
,
4889 .bus_set_property
= bus_service_set_property
,
4890 .bus_commit_properties
= bus_service_commit_properties
,
4892 .get_timeout
= service_get_timeout
,
4893 .needs_console
= service_needs_console
,
4894 .exit_status
= service_exit_status
,
4895 .status_text
= service_status_text
,
4897 .status_message_formats
= {
4898 .finished_start_job
= {
4899 [JOB_FAILED
] = "Failed to start %s.",
4901 .finished_stop_job
= {
4902 [JOB_DONE
] = "Stopped %s.",
4903 [JOB_FAILED
] = "Stopped (with error) %s.",
4905 .finished_job
= service_finished_job
,
4908 .can_start
= service_can_start
,