2 This file is part of systemd.
4 Copyright 2010 Lennart Poettering
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
24 #include "alloc-util.h"
26 #include "bus-error.h"
27 #include "bus-kernel.h"
29 #include "dbus-service.h"
33 #include "exit-status.h"
36 #include "format-util.h"
38 #include "load-dropin.h"
39 #include "load-fragment.h"
42 #include "parse-util.h"
43 #include "path-util.h"
44 #include "process-util.h"
46 #include "signal-util.h"
48 #include "stdio-util.h"
49 #include "string-table.h"
50 #include "string-util.h"
52 #include "unit-name.h"
57 static const UnitActiveState state_translation_table
[_SERVICE_STATE_MAX
] = {
58 [SERVICE_DEAD
] = UNIT_INACTIVE
,
59 [SERVICE_START_PRE
] = UNIT_ACTIVATING
,
60 [SERVICE_START
] = UNIT_ACTIVATING
,
61 [SERVICE_START_POST
] = UNIT_ACTIVATING
,
62 [SERVICE_RUNNING
] = UNIT_ACTIVE
,
63 [SERVICE_EXITED
] = UNIT_ACTIVE
,
64 [SERVICE_RELOAD
] = UNIT_RELOADING
,
65 [SERVICE_STOP
] = UNIT_DEACTIVATING
,
66 [SERVICE_STOP_SIGABRT
] = UNIT_DEACTIVATING
,
67 [SERVICE_STOP_SIGTERM
] = UNIT_DEACTIVATING
,
68 [SERVICE_STOP_SIGKILL
] = UNIT_DEACTIVATING
,
69 [SERVICE_STOP_POST
] = UNIT_DEACTIVATING
,
70 [SERVICE_FINAL_SIGTERM
] = UNIT_DEACTIVATING
,
71 [SERVICE_FINAL_SIGKILL
] = UNIT_DEACTIVATING
,
72 [SERVICE_FAILED
] = UNIT_FAILED
,
73 [SERVICE_AUTO_RESTART
] = UNIT_ACTIVATING
76 /* For Type=idle we never want to delay any other jobs, hence we
77 * consider idle jobs active as soon as we start working on them */
78 static const UnitActiveState state_translation_table_idle
[_SERVICE_STATE_MAX
] = {
79 [SERVICE_DEAD
] = UNIT_INACTIVE
,
80 [SERVICE_START_PRE
] = UNIT_ACTIVE
,
81 [SERVICE_START
] = UNIT_ACTIVE
,
82 [SERVICE_START_POST
] = UNIT_ACTIVE
,
83 [SERVICE_RUNNING
] = UNIT_ACTIVE
,
84 [SERVICE_EXITED
] = UNIT_ACTIVE
,
85 [SERVICE_RELOAD
] = UNIT_RELOADING
,
86 [SERVICE_STOP
] = UNIT_DEACTIVATING
,
87 [SERVICE_STOP_SIGABRT
] = UNIT_DEACTIVATING
,
88 [SERVICE_STOP_SIGTERM
] = UNIT_DEACTIVATING
,
89 [SERVICE_STOP_SIGKILL
] = UNIT_DEACTIVATING
,
90 [SERVICE_STOP_POST
] = 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
97 static int service_dispatch_io(sd_event_source
*source
, int fd
, uint32_t events
, void *userdata
);
98 static int service_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
);
99 static int service_dispatch_watchdog(sd_event_source
*source
, usec_t usec
, void *userdata
);
101 static void service_enter_signal(Service
*s
, ServiceState state
, ServiceResult f
);
102 static void service_enter_reload_by_notify(Service
*s
);
104 static void service_init(Unit
*u
) {
105 Service
*s
= SERVICE(u
);
108 assert(u
->load_state
== UNIT_STUB
);
110 s
->timeout_start_usec
= u
->manager
->default_timeout_start_usec
;
111 s
->timeout_stop_usec
= u
->manager
->default_timeout_stop_usec
;
112 s
->restart_usec
= u
->manager
->default_restart_usec
;
113 s
->runtime_max_usec
= USEC_INFINITY
;
114 s
->type
= _SERVICE_TYPE_INVALID
;
116 s
->stdin_fd
= s
->stdout_fd
= s
->stderr_fd
= -1;
117 s
->guess_main_pid
= true;
119 s
->control_command_id
= _SERVICE_EXEC_COMMAND_INVALID
;
122 static void service_unwatch_control_pid(Service
*s
) {
125 if (s
->control_pid
<= 0)
128 unit_unwatch_pid(UNIT(s
), s
->control_pid
);
132 static void service_unwatch_main_pid(Service
*s
) {
135 if (s
->main_pid
<= 0)
138 unit_unwatch_pid(UNIT(s
), s
->main_pid
);
142 static void service_unwatch_pid_file(Service
*s
) {
143 if (!s
->pid_file_pathspec
)
146 log_unit_debug(UNIT(s
), "Stopping watch for PID file %s", s
->pid_file_pathspec
->path
);
147 path_spec_unwatch(s
->pid_file_pathspec
);
148 path_spec_done(s
->pid_file_pathspec
);
149 s
->pid_file_pathspec
= mfree(s
->pid_file_pathspec
);
152 static int service_set_main_pid(Service
*s
, pid_t pid
) {
163 if (s
->main_pid
== pid
&& s
->main_pid_known
)
166 if (s
->main_pid
!= pid
) {
167 service_unwatch_main_pid(s
);
168 exec_status_start(&s
->main_exec_status
, pid
);
172 s
->main_pid_known
= true;
174 if (get_process_ppid(pid
, &ppid
) >= 0 && ppid
!= getpid()) {
175 log_unit_warning(UNIT(s
), "Supervising process "PID_FMT
" which is not our child. We'll most likely not notice when it exits.", pid
);
176 s
->main_pid_alien
= true;
178 s
->main_pid_alien
= false;
183 void service_close_socket_fd(Service
*s
) {
186 /* Undo the effect of service_set_socket_fd(). */
188 s
->socket_fd
= asynchronous_close(s
->socket_fd
);
190 if (UNIT_ISSET(s
->accept_socket
)) {
191 socket_connection_unref(SOCKET(UNIT_DEREF(s
->accept_socket
)));
192 unit_ref_unset(&s
->accept_socket
);
196 static void service_stop_watchdog(Service
*s
) {
199 s
->watchdog_event_source
= sd_event_source_unref(s
->watchdog_event_source
);
200 s
->watchdog_timestamp
= DUAL_TIMESTAMP_NULL
;
203 static usec_t
service_get_watchdog_usec(Service
*s
) {
206 if (s
->watchdog_override_enable
)
207 return s
->watchdog_override_usec
;
209 return s
->watchdog_usec
;
212 static void service_start_watchdog(Service
*s
) {
214 usec_t watchdog_usec
;
218 watchdog_usec
= service_get_watchdog_usec(s
);
219 if (watchdog_usec
== 0 || watchdog_usec
== USEC_INFINITY
)
222 if (s
->watchdog_event_source
) {
223 r
= sd_event_source_set_time(s
->watchdog_event_source
, usec_add(s
->watchdog_timestamp
.monotonic
, watchdog_usec
));
225 log_unit_warning_errno(UNIT(s
), r
, "Failed to reset watchdog timer: %m");
229 r
= sd_event_source_set_enabled(s
->watchdog_event_source
, SD_EVENT_ONESHOT
);
231 r
= sd_event_add_time(
232 UNIT(s
)->manager
->event
,
233 &s
->watchdog_event_source
,
235 usec_add(s
->watchdog_timestamp
.monotonic
, watchdog_usec
), 0,
236 service_dispatch_watchdog
, s
);
238 log_unit_warning_errno(UNIT(s
), r
, "Failed to add watchdog timer: %m");
242 (void) sd_event_source_set_description(s
->watchdog_event_source
, "service-watchdog");
244 /* Let's process everything else which might be a sign
245 * of living before we consider a service died. */
246 r
= sd_event_source_set_priority(s
->watchdog_event_source
, SD_EVENT_PRIORITY_IDLE
);
250 log_unit_warning_errno(UNIT(s
), r
, "Failed to install watchdog timer: %m");
253 static void service_reset_watchdog(Service
*s
) {
256 dual_timestamp_get(&s
->watchdog_timestamp
);
257 service_start_watchdog(s
);
260 static void service_reset_watchdog_timeout(Service
*s
, usec_t watchdog_override_usec
) {
263 s
->watchdog_override_enable
= true;
264 s
->watchdog_override_usec
= watchdog_override_usec
;
265 service_reset_watchdog(s
);
267 log_unit_debug(UNIT(s
), "watchdog_usec="USEC_FMT
, s
->watchdog_usec
);
268 log_unit_debug(UNIT(s
), "watchdog_override_usec="USEC_FMT
, s
->watchdog_override_usec
);
271 static void service_fd_store_unlink(ServiceFDStore
*fs
) {
277 assert(fs
->service
->n_fd_store
> 0);
278 LIST_REMOVE(fd_store
, fs
->service
->fd_store
, fs
);
279 fs
->service
->n_fd_store
--;
282 if (fs
->event_source
) {
283 sd_event_source_set_enabled(fs
->event_source
, SD_EVENT_OFF
);
284 sd_event_source_unref(fs
->event_source
);
292 static void service_release_fd_store(Service
*s
) {
295 log_unit_debug(UNIT(s
), "Releasing all stored fds");
297 service_fd_store_unlink(s
->fd_store
);
299 assert(s
->n_fd_store
== 0);
302 static void service_release_resources(Unit
*u
, bool inactive
) {
303 Service
*s
= SERVICE(u
);
307 if (!s
->fd_store
&& s
->stdin_fd
< 0 && s
->stdout_fd
< 0 && s
->stderr_fd
< 0)
310 log_unit_debug(u
, "Releasing resources.");
312 s
->stdin_fd
= safe_close(s
->stdin_fd
);
313 s
->stdout_fd
= safe_close(s
->stdout_fd
);
314 s
->stderr_fd
= safe_close(s
->stderr_fd
);
317 service_release_fd_store(s
);
320 static void service_done(Unit
*u
) {
321 Service
*s
= SERVICE(u
);
325 s
->pid_file
= mfree(s
->pid_file
);
326 s
->status_text
= mfree(s
->status_text
);
328 s
->exec_runtime
= exec_runtime_unref(s
->exec_runtime
);
329 exec_command_free_array(s
->exec_command
, _SERVICE_EXEC_COMMAND_MAX
);
330 s
->control_command
= NULL
;
331 s
->main_command
= NULL
;
333 dynamic_creds_unref(&s
->dynamic_creds
);
335 exit_status_set_free(&s
->restart_prevent_status
);
336 exit_status_set_free(&s
->restart_force_status
);
337 exit_status_set_free(&s
->success_status
);
339 /* This will leak a process, but at least no memory or any of
341 service_unwatch_main_pid(s
);
342 service_unwatch_control_pid(s
);
343 service_unwatch_pid_file(s
);
346 unit_unwatch_bus_name(u
, s
->bus_name
);
347 s
->bus_name
= mfree(s
->bus_name
);
350 s
->bus_name_owner
= mfree(s
->bus_name_owner
);
352 service_close_socket_fd(s
);
353 s
->peer
= socket_peer_unref(s
->peer
);
355 unit_ref_unset(&s
->accept_socket
);
357 service_stop_watchdog(s
);
359 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
361 service_release_resources(u
, true);
364 static int on_fd_store_io(sd_event_source
*e
, int fd
, uint32_t revents
, void *userdata
) {
365 ServiceFDStore
*fs
= userdata
;
370 /* If we get either EPOLLHUP or EPOLLERR, it's time to remove this entry from the fd store */
371 log_unit_debug(UNIT(fs
->service
),
372 "Received %s on stored fd %d (%s), closing.",
373 revents
& EPOLLERR
? "EPOLLERR" : "EPOLLHUP",
374 fs
->fd
, strna(fs
->fdname
));
375 service_fd_store_unlink(fs
);
379 static int service_add_fd_store(Service
*s
, int fd
, const char *name
) {
383 /* fd is always consumed if we return >= 0 */
388 if (s
->n_fd_store
>= s
->n_fd_store_max
)
389 return -EXFULL
; /* Our store is full.
390 * Use this errno rather than E[NM]FILE to distinguish from
391 * the case where systemd itself hits the file limit. */
393 LIST_FOREACH(fd_store
, fs
, s
->fd_store
) {
394 r
= same_fd(fs
->fd
, fd
);
399 return 0; /* fd already included */
403 fs
= new0(ServiceFDStore
, 1);
409 fs
->fdname
= strdup(name
?: "stored");
415 r
= sd_event_add_io(UNIT(s
)->manager
->event
, &fs
->event_source
, fd
, 0, on_fd_store_io
, fs
);
416 if (r
< 0 && r
!= -EPERM
) { /* EPERM indicates fds that aren't pollable, which is OK */
421 (void) sd_event_source_set_description(fs
->event_source
, "service-fd-store");
423 LIST_PREPEND(fd_store
, s
->fd_store
, fs
);
426 return 1; /* fd newly stored */
429 static int service_add_fd_store_set(Service
*s
, FDSet
*fds
, const char *name
) {
434 while (fdset_size(fds
) > 0) {
435 _cleanup_close_
int fd
= -1;
437 fd
= fdset_steal_first(fds
);
441 r
= service_add_fd_store(s
, fd
, name
);
443 return log_unit_warning_errno(UNIT(s
), r
,
444 "Cannot store more fds than FileDescriptorStoreMax=%u, closing remaining.",
447 return log_unit_error_errno(UNIT(s
), r
, "Failed to add fd to store: %m");
449 log_unit_debug(UNIT(s
), "Added fd %u (%s) to fd store.", fd
, strna(name
));
456 static int service_arm_timer(Service
*s
, usec_t usec
) {
461 if (s
->timer_event_source
) {
462 r
= sd_event_source_set_time(s
->timer_event_source
, usec
);
466 return sd_event_source_set_enabled(s
->timer_event_source
, SD_EVENT_ONESHOT
);
469 if (usec
== USEC_INFINITY
)
472 r
= sd_event_add_time(
473 UNIT(s
)->manager
->event
,
474 &s
->timer_event_source
,
477 service_dispatch_timer
, s
);
481 (void) sd_event_source_set_description(s
->timer_event_source
, "service-timer");
486 static int service_verify(Service
*s
) {
489 if (UNIT(s
)->load_state
!= UNIT_LOADED
)
492 if (!s
->exec_command
[SERVICE_EXEC_START
] && !s
->exec_command
[SERVICE_EXEC_STOP
]) {
493 log_unit_error(UNIT(s
), "Service lacks both ExecStart= and ExecStop= setting. Refusing.");
497 if (s
->type
!= SERVICE_ONESHOT
&& !s
->exec_command
[SERVICE_EXEC_START
]) {
498 log_unit_error(UNIT(s
), "Service has no ExecStart= setting, which is only allowed for Type=oneshot services. Refusing.");
502 if (!s
->remain_after_exit
&& !s
->exec_command
[SERVICE_EXEC_START
]) {
503 log_unit_error(UNIT(s
), "Service has no ExecStart= setting, which is only allowed for RemainAfterExit=yes services. Refusing.");
507 if (s
->type
!= SERVICE_ONESHOT
&& s
->exec_command
[SERVICE_EXEC_START
]->command_next
) {
508 log_unit_error(UNIT(s
), "Service has more than one ExecStart= setting, which is only allowed for Type=oneshot services. Refusing.");
512 if (s
->type
== SERVICE_ONESHOT
&& s
->restart
!= SERVICE_RESTART_NO
) {
513 log_unit_error(UNIT(s
), "Service has Restart= setting other than no, which isn't allowed for Type=oneshot services. Refusing.");
517 if (s
->type
== SERVICE_ONESHOT
&& !exit_status_set_is_empty(&s
->restart_force_status
)) {
518 log_unit_error(UNIT(s
), "Service has RestartForceStatus= set, which isn't allowed for Type=oneshot services. Refusing.");
522 if (s
->type
== SERVICE_DBUS
&& !s
->bus_name
) {
523 log_unit_error(UNIT(s
), "Service is of type D-Bus but no D-Bus service name has been specified. Refusing.");
527 if (s
->bus_name
&& s
->type
!= SERVICE_DBUS
)
528 log_unit_warning(UNIT(s
), "Service has a D-Bus service name specified, but is not of type dbus. Ignoring.");
530 if (s
->exec_context
.pam_name
&& !(s
->kill_context
.kill_mode
== KILL_CONTROL_GROUP
|| s
->kill_context
.kill_mode
== KILL_MIXED
)) {
531 log_unit_error(UNIT(s
), "Service has PAM enabled. Kill mode must be set to 'control-group' or 'mixed'. Refusing.");
535 if (s
->usb_function_descriptors
&& !s
->usb_function_strings
)
536 log_unit_warning(UNIT(s
), "Service has USBFunctionDescriptors= setting, but no USBFunctionStrings=. Ignoring.");
538 if (!s
->usb_function_descriptors
&& s
->usb_function_strings
)
539 log_unit_warning(UNIT(s
), "Service has USBFunctionStrings= setting, but no USBFunctionDescriptors=. Ignoring.");
541 if (s
->runtime_max_usec
!= USEC_INFINITY
&& s
->type
== SERVICE_ONESHOT
)
542 log_unit_warning(UNIT(s
), "MaxRuntimeSec= has no effect in combination with Type=oneshot. Ignoring.");
547 static int service_add_default_dependencies(Service
*s
) {
552 if (!UNIT(s
)->default_dependencies
)
555 /* Add a number of automatic dependencies useful for the
556 * majority of services. */
558 if (MANAGER_IS_SYSTEM(UNIT(s
)->manager
)) {
559 /* First, pull in the really early boot stuff, and
560 * require it, so that we fail if we can't acquire
563 r
= unit_add_two_dependencies_by_name(UNIT(s
), UNIT_AFTER
, UNIT_REQUIRES
, SPECIAL_SYSINIT_TARGET
, NULL
, true);
568 /* In the --user instance there's no sysinit.target,
569 * in that case require basic.target instead. */
571 r
= unit_add_dependency_by_name(UNIT(s
), UNIT_REQUIRES
, SPECIAL_BASIC_TARGET
, NULL
, true);
576 /* Second, if the rest of the base system is in the same
577 * transaction, order us after it, but do not pull it in or
578 * even require it. */
579 r
= unit_add_dependency_by_name(UNIT(s
), UNIT_AFTER
, SPECIAL_BASIC_TARGET
, NULL
, true);
583 /* Third, add us in for normal shutdown. */
584 return unit_add_two_dependencies_by_name(UNIT(s
), UNIT_BEFORE
, UNIT_CONFLICTS
, SPECIAL_SHUTDOWN_TARGET
, NULL
, true);
587 static void service_fix_output(Service
*s
) {
590 /* If nothing has been explicitly configured, patch default
591 * output in. If input is socket/tty we avoid this however,
592 * since in that case we want output to default to the same
593 * place as we read input from. */
595 if (s
->exec_context
.std_error
== EXEC_OUTPUT_INHERIT
&&
596 s
->exec_context
.std_output
== EXEC_OUTPUT_INHERIT
&&
597 s
->exec_context
.std_input
== EXEC_INPUT_NULL
)
598 s
->exec_context
.std_error
= UNIT(s
)->manager
->default_std_error
;
600 if (s
->exec_context
.std_output
== EXEC_OUTPUT_INHERIT
&&
601 s
->exec_context
.std_input
== EXEC_INPUT_NULL
)
602 s
->exec_context
.std_output
= UNIT(s
)->manager
->default_std_output
;
605 static int service_setup_bus_name(Service
*s
) {
613 r
= unit_add_dependency_by_name(UNIT(s
), UNIT_REQUIRES
, SPECIAL_DBUS_SOCKET
, NULL
, true);
615 return log_unit_error_errno(UNIT(s
), r
, "Failed to add dependency on " SPECIAL_DBUS_SOCKET
": %m");
617 /* Regardless if kdbus is used or not, we always want to be ordered against dbus.socket if both are in the transaction. */
618 r
= unit_add_dependency_by_name(UNIT(s
), UNIT_AFTER
, SPECIAL_DBUS_SOCKET
, NULL
, true);
620 return log_unit_error_errno(UNIT(s
), r
, "Failed to add dependency on " SPECIAL_DBUS_SOCKET
": %m");
622 r
= unit_watch_bus_name(UNIT(s
), s
->bus_name
);
624 return log_unit_error_errno(UNIT(s
), r
, "Two services allocated for the same bus name %s, refusing operation.", s
->bus_name
);
626 return log_unit_error_errno(UNIT(s
), r
, "Cannot watch bus name %s: %m", s
->bus_name
);
631 static int service_add_extras(Service
*s
) {
636 if (s
->type
== _SERVICE_TYPE_INVALID
) {
637 /* Figure out a type automatically */
639 s
->type
= SERVICE_DBUS
;
640 else if (s
->exec_command
[SERVICE_EXEC_START
])
641 s
->type
= SERVICE_SIMPLE
;
643 s
->type
= SERVICE_ONESHOT
;
646 /* Oneshot services have disabled start timeout by default */
647 if (s
->type
== SERVICE_ONESHOT
&& !s
->start_timeout_defined
)
648 s
->timeout_start_usec
= USEC_INFINITY
;
650 service_fix_output(s
);
652 r
= unit_patch_contexts(UNIT(s
));
656 r
= unit_add_exec_dependencies(UNIT(s
), &s
->exec_context
);
660 r
= unit_set_default_slice(UNIT(s
));
664 if (s
->type
== SERVICE_NOTIFY
&& s
->notify_access
== NOTIFY_NONE
)
665 s
->notify_access
= NOTIFY_MAIN
;
667 if (s
->watchdog_usec
> 0 && s
->notify_access
== NOTIFY_NONE
)
668 s
->notify_access
= NOTIFY_MAIN
;
670 r
= service_add_default_dependencies(s
);
674 r
= service_setup_bus_name(s
);
681 static int service_load(Unit
*u
) {
682 Service
*s
= SERVICE(u
);
687 /* Load a .service file */
688 r
= unit_load_fragment(u
);
692 /* Still nothing found? Then let's give up */
693 if (u
->load_state
== UNIT_STUB
)
696 /* This is a new unit? Then let's add in some extras */
697 if (u
->load_state
== UNIT_LOADED
) {
699 /* We were able to load something, then let's add in
700 * the dropin directories. */
701 r
= unit_load_dropin(u
);
705 /* This is a new unit? Then let's add in some
707 r
= service_add_extras(s
);
712 return service_verify(s
);
715 static void service_dump(Unit
*u
, FILE *f
, const char *prefix
) {
716 ServiceExecCommand c
;
717 Service
*s
= SERVICE(u
);
722 prefix
= strempty(prefix
);
723 prefix2
= strjoina(prefix
, "\t");
726 "%sService State: %s\n"
728 "%sReload Result: %s\n"
729 "%sPermissionsStartOnly: %s\n"
730 "%sRootDirectoryStartOnly: %s\n"
731 "%sRemainAfterExit: %s\n"
732 "%sGuessMainPID: %s\n"
735 "%sNotifyAccess: %s\n"
736 "%sNotifyState: %s\n",
737 prefix
, service_state_to_string(s
->state
),
738 prefix
, service_result_to_string(s
->result
),
739 prefix
, service_result_to_string(s
->reload_result
),
740 prefix
, yes_no(s
->permissions_start_only
),
741 prefix
, yes_no(s
->root_directory_start_only
),
742 prefix
, yes_no(s
->remain_after_exit
),
743 prefix
, yes_no(s
->guess_main_pid
),
744 prefix
, service_type_to_string(s
->type
),
745 prefix
, service_restart_to_string(s
->restart
),
746 prefix
, notify_access_to_string(s
->notify_access
),
747 prefix
, notify_state_to_string(s
->notify_state
));
749 if (s
->control_pid
> 0)
751 "%sControl PID: "PID_FMT
"\n",
752 prefix
, s
->control_pid
);
756 "%sMain PID: "PID_FMT
"\n"
757 "%sMain PID Known: %s\n"
758 "%sMain PID Alien: %s\n",
760 prefix
, yes_no(s
->main_pid_known
),
761 prefix
, yes_no(s
->main_pid_alien
));
766 prefix
, s
->pid_file
);
771 "%sBus Name Good: %s\n",
773 prefix
, yes_no(s
->bus_name_good
));
775 if (UNIT_ISSET(s
->accept_socket
))
777 "%sAccept Socket: %s\n",
778 prefix
, UNIT_DEREF(s
->accept_socket
)->id
);
780 kill_context_dump(&s
->kill_context
, f
, prefix
);
781 exec_context_dump(&s
->exec_context
, f
, prefix
);
783 for (c
= 0; c
< _SERVICE_EXEC_COMMAND_MAX
; c
++) {
785 if (!s
->exec_command
[c
])
788 fprintf(f
, "%s-> %s:\n",
789 prefix
, service_exec_command_to_string(c
));
791 exec_command_dump_list(s
->exec_command
[c
], f
, prefix2
);
795 fprintf(f
, "%sStatus Text: %s\n",
796 prefix
, s
->status_text
);
798 if (s
->n_fd_store_max
> 0)
800 "%sFile Descriptor Store Max: %u\n"
801 "%sFile Descriptor Store Current: %u\n",
802 prefix
, s
->n_fd_store_max
,
803 prefix
, s
->n_fd_store
);
806 static int service_load_pid_file(Service
*s
, bool may_warn
) {
807 _cleanup_free_
char *k
= NULL
;
816 r
= read_one_line_file(s
->pid_file
, &k
);
819 log_unit_info_errno(UNIT(s
), r
, "PID file %s not readable (yet?) after %s: %m", s
->pid_file
, service_state_to_string(s
->state
));
823 r
= parse_pid(k
, &pid
);
826 log_unit_info_errno(UNIT(s
), r
, "Failed to read PID from file %s: %m", s
->pid_file
);
830 if (!pid_is_alive(pid
)) {
832 log_unit_info(UNIT(s
), "PID "PID_FMT
" read from file %s does not exist or is a zombie.", pid
, s
->pid_file
);
836 if (s
->main_pid_known
) {
837 if (pid
== s
->main_pid
)
840 log_unit_debug(UNIT(s
), "Main PID changing: "PID_FMT
" -> "PID_FMT
, s
->main_pid
, pid
);
842 service_unwatch_main_pid(s
);
843 s
->main_pid_known
= false;
845 log_unit_debug(UNIT(s
), "Main PID loaded: "PID_FMT
, pid
);
847 r
= service_set_main_pid(s
, pid
);
851 r
= unit_watch_pid(UNIT(s
), pid
);
852 if (r
< 0) /* FIXME: we need to do something here */
853 return log_unit_warning_errno(UNIT(s
), r
, "Failed to watch PID "PID_FMT
" for service: %m", pid
);
858 static void service_search_main_pid(Service
*s
) {
864 /* If we know it anyway, don't ever fallback to unreliable
866 if (s
->main_pid_known
)
869 if (!s
->guess_main_pid
)
872 assert(s
->main_pid
<= 0);
874 if (unit_search_main_pid(UNIT(s
), &pid
) < 0)
877 log_unit_debug(UNIT(s
), "Main PID guessed: "PID_FMT
, pid
);
878 if (service_set_main_pid(s
, pid
) < 0)
881 r
= unit_watch_pid(UNIT(s
), pid
);
883 /* FIXME: we need to do something here */
884 log_unit_warning_errno(UNIT(s
), r
, "Failed to watch PID "PID_FMT
" from: %m", pid
);
887 static void service_set_state(Service
*s
, ServiceState state
) {
888 ServiceState old_state
;
889 const UnitActiveState
*table
;
893 table
= s
->type
== SERVICE_IDLE
? state_translation_table_idle
: state_translation_table
;
895 old_state
= s
->state
;
898 service_unwatch_pid_file(s
);
901 SERVICE_START_PRE
, SERVICE_START
, SERVICE_START_POST
,
904 SERVICE_STOP
, SERVICE_STOP_SIGABRT
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
, SERVICE_STOP_POST
,
905 SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
,
906 SERVICE_AUTO_RESTART
))
907 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
910 SERVICE_START
, SERVICE_START_POST
,
911 SERVICE_RUNNING
, SERVICE_RELOAD
,
912 SERVICE_STOP
, SERVICE_STOP_SIGABRT
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
, SERVICE_STOP_POST
,
913 SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
)) {
914 service_unwatch_main_pid(s
);
915 s
->main_command
= NULL
;
919 SERVICE_START_PRE
, SERVICE_START
, SERVICE_START_POST
,
921 SERVICE_STOP
, SERVICE_STOP_SIGABRT
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
, SERVICE_STOP_POST
,
922 SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
)) {
923 service_unwatch_control_pid(s
);
924 s
->control_command
= NULL
;
925 s
->control_command_id
= _SERVICE_EXEC_COMMAND_INVALID
;
928 if (IN_SET(state
, SERVICE_DEAD
, SERVICE_FAILED
, SERVICE_AUTO_RESTART
))
929 unit_unwatch_all_pids(UNIT(s
));
932 SERVICE_START_PRE
, SERVICE_START
, SERVICE_START_POST
,
933 SERVICE_RUNNING
, SERVICE_RELOAD
,
934 SERVICE_STOP
, SERVICE_STOP_SIGABRT
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
, SERVICE_STOP_POST
,
935 SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
) &&
936 !(state
== SERVICE_DEAD
&& UNIT(s
)->job
))
937 service_close_socket_fd(s
);
939 if (!IN_SET(state
, SERVICE_START_POST
, SERVICE_RUNNING
, SERVICE_RELOAD
))
940 service_stop_watchdog(s
);
942 /* For the inactive states unit_notify() will trim the cgroup,
943 * but for exit we have to do that ourselves... */
944 if (state
== SERVICE_EXITED
&& !MANAGER_IS_RELOADING(UNIT(s
)->manager
))
945 unit_prune_cgroup(UNIT(s
));
947 /* For remain_after_exit services, let's see if we can "release" the
948 * hold on the console, since unit_notify() only does that in case of
950 if (state
== SERVICE_EXITED
&&
951 s
->remain_after_exit
&&
952 UNIT(s
)->manager
->n_on_console
> 0) {
956 ec
= unit_get_exec_context(UNIT(s
));
957 if (ec
&& exec_context_may_touch_console(ec
)) {
958 Manager
*m
= UNIT(s
)->manager
;
961 if (m
->n_on_console
== 0)
962 /* unset no_console_output flag, since the console is free */
963 m
->no_console_output
= false;
967 if (old_state
!= state
)
968 log_unit_debug(UNIT(s
), "Changed %s -> %s", service_state_to_string(old_state
), service_state_to_string(state
));
970 unit_notify(UNIT(s
), table
[old_state
], table
[state
], s
->reload_result
== SERVICE_SUCCESS
);
973 static usec_t
service_coldplug_timeout(Service
*s
) {
976 switch (s
->deserialized_state
) {
978 case SERVICE_START_PRE
:
980 case SERVICE_START_POST
:
982 return usec_add(UNIT(s
)->state_change_timestamp
.monotonic
, s
->timeout_start_usec
);
984 case SERVICE_RUNNING
:
985 return usec_add(UNIT(s
)->active_enter_timestamp
.monotonic
, s
->runtime_max_usec
);
988 case SERVICE_STOP_SIGABRT
:
989 case SERVICE_STOP_SIGTERM
:
990 case SERVICE_STOP_SIGKILL
:
991 case SERVICE_STOP_POST
:
992 case SERVICE_FINAL_SIGTERM
:
993 case SERVICE_FINAL_SIGKILL
:
994 return usec_add(UNIT(s
)->state_change_timestamp
.monotonic
, s
->timeout_stop_usec
);
996 case SERVICE_AUTO_RESTART
:
997 return usec_add(UNIT(s
)->inactive_enter_timestamp
.monotonic
, s
->restart_usec
);
1000 return USEC_INFINITY
;
1004 static int service_coldplug(Unit
*u
) {
1005 Service
*s
= SERVICE(u
);
1009 assert(s
->state
== SERVICE_DEAD
);
1011 if (s
->deserialized_state
== s
->state
)
1014 r
= service_arm_timer(s
, service_coldplug_timeout(s
));
1018 if (s
->main_pid
> 0 &&
1019 pid_is_unwaited(s
->main_pid
) &&
1020 ((s
->deserialized_state
== SERVICE_START
&& IN_SET(s
->type
, SERVICE_FORKING
, SERVICE_DBUS
, SERVICE_ONESHOT
, SERVICE_NOTIFY
)) ||
1021 IN_SET(s
->deserialized_state
,
1022 SERVICE_START
, SERVICE_START_POST
,
1023 SERVICE_RUNNING
, SERVICE_RELOAD
,
1024 SERVICE_STOP
, SERVICE_STOP_SIGABRT
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
, SERVICE_STOP_POST
,
1025 SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
))) {
1026 r
= unit_watch_pid(UNIT(s
), s
->main_pid
);
1031 if (s
->control_pid
> 0 &&
1032 pid_is_unwaited(s
->control_pid
) &&
1033 IN_SET(s
->deserialized_state
,
1034 SERVICE_START_PRE
, SERVICE_START
, SERVICE_START_POST
,
1036 SERVICE_STOP
, SERVICE_STOP_SIGABRT
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
, SERVICE_STOP_POST
,
1037 SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
)) {
1038 r
= unit_watch_pid(UNIT(s
), s
->control_pid
);
1043 if (!IN_SET(s
->deserialized_state
, SERVICE_DEAD
, SERVICE_FAILED
, SERVICE_AUTO_RESTART
))
1044 unit_watch_all_pids(UNIT(s
));
1046 if (IN_SET(s
->deserialized_state
, SERVICE_START_POST
, SERVICE_RUNNING
, SERVICE_RELOAD
))
1047 service_start_watchdog(s
);
1049 if (!IN_SET(s
->deserialized_state
, SERVICE_DEAD
, SERVICE_FAILED
, SERVICE_AUTO_RESTART
))
1050 (void) unit_setup_dynamic_creds(u
);
1052 if (UNIT_ISSET(s
->accept_socket
)) {
1053 Socket
* socket
= SOCKET(UNIT_DEREF(s
->accept_socket
));
1055 if (socket
->max_connections_per_source
> 0) {
1058 /* Make a best-effort attempt at bumping the connection count */
1059 if (socket_acquire_peer(socket
, s
->socket_fd
, &peer
) > 0) {
1060 socket_peer_unref(s
->peer
);
1066 service_set_state(s
, s
->deserialized_state
);
1070 static int service_collect_fds(Service
*s
,
1073 unsigned *n_storage_fds
,
1074 unsigned *n_socket_fds
) {
1076 _cleanup_strv_free_
char **rfd_names
= NULL
;
1077 _cleanup_free_
int *rfds
= NULL
;
1078 unsigned rn_socket_fds
= 0, rn_storage_fds
= 0;
1084 assert(n_socket_fds
);
1086 if (s
->socket_fd
>= 0) {
1088 /* Pass the per-connection socket */
1093 rfds
[0] = s
->socket_fd
;
1095 rfd_names
= strv_new("connection", NULL
);
1104 /* Pass all our configured sockets for singleton services */
1106 SET_FOREACH(u
, UNIT(s
)->dependencies
[UNIT_TRIGGERED_BY
], i
) {
1107 _cleanup_free_
int *cfds
= NULL
;
1111 if (u
->type
!= UNIT_SOCKET
)
1116 cn_fds
= socket_collect_fds(sock
, &cfds
);
1125 rn_socket_fds
= cn_fds
;
1131 t
= realloc(rfds
, (rn_socket_fds
+ cn_fds
) * sizeof(int));
1135 memcpy(t
+ rn_socket_fds
, cfds
, cn_fds
* sizeof(int));
1138 rn_socket_fds
+= cn_fds
;
1141 r
= strv_extend_n(&rfd_names
, socket_fdname(sock
), cn_fds
);
1147 if (s
->n_fd_store
> 0) {
1153 t
= realloc(rfds
, (rn_socket_fds
+ s
->n_fd_store
) * sizeof(int));
1159 nl
= realloc(rfd_names
, (rn_socket_fds
+ s
->n_fd_store
+ 1) * sizeof(char*));
1164 n_fds
= rn_socket_fds
;
1166 LIST_FOREACH(fd_store
, fs
, s
->fd_store
) {
1167 rfds
[n_fds
] = fs
->fd
;
1168 rfd_names
[n_fds
] = strdup(strempty(fs
->fdname
));
1169 if (!rfd_names
[n_fds
])
1176 rfd_names
[n_fds
] = NULL
;
1180 *fd_names
= rfd_names
;
1181 *n_socket_fds
= rn_socket_fds
;
1182 *n_storage_fds
= rn_storage_fds
;
1190 static bool service_exec_needs_notify_socket(Service
*s
, ExecFlags flags
) {
1193 /* Notifications are accepted depending on the process and
1194 * the access setting of the service:
1195 * process: \ access: NONE MAIN EXEC ALL
1196 * main no yes yes yes
1197 * control no no yes yes
1198 * other (forked) no no no yes */
1200 if (flags
& EXEC_IS_CONTROL
)
1201 /* A control process */
1202 return IN_SET(s
->notify_access
, NOTIFY_EXEC
, NOTIFY_ALL
);
1204 /* We only spawn main processes and control processes, so any
1205 * process that is not a control process is a main process */
1206 return s
->notify_access
!= NOTIFY_NONE
;
1209 static int service_spawn(
1216 _cleanup_strv_free_
char **final_env
= NULL
, **our_env
= NULL
, **fd_names
= NULL
;
1217 _cleanup_free_
int *fds
= NULL
;
1218 unsigned n_storage_fds
= 0, n_socket_fds
= 0, n_env
= 0;
1222 ExecParameters exec_params
= {
1235 if (flags
& EXEC_IS_CONTROL
) {
1236 /* If this is a control process, mask the permissions/chroot application if this is requested. */
1237 if (s
->permissions_start_only
)
1238 exec_params
.flags
&= ~EXEC_APPLY_PERMISSIONS
;
1239 if (s
->root_directory_start_only
)
1240 exec_params
.flags
&= ~EXEC_APPLY_CHROOT
;
1243 (void) unit_realize_cgroup(UNIT(s
));
1244 if (s
->reset_cpu_usage
) {
1245 (void) unit_reset_cpu_usage(UNIT(s
));
1246 s
->reset_cpu_usage
= false;
1249 r
= unit_setup_exec_runtime(UNIT(s
));
1253 r
= unit_setup_dynamic_creds(UNIT(s
));
1257 if ((flags
& EXEC_PASS_FDS
) ||
1258 s
->exec_context
.std_input
== EXEC_INPUT_SOCKET
||
1259 s
->exec_context
.std_output
== EXEC_OUTPUT_SOCKET
||
1260 s
->exec_context
.std_error
== EXEC_OUTPUT_SOCKET
) {
1262 r
= service_collect_fds(s
, &fds
, &fd_names
, &n_storage_fds
, &n_socket_fds
);
1266 log_unit_debug(UNIT(s
), "Passing %i fds to service", n_storage_fds
+ n_socket_fds
);
1269 r
= service_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), timeout
));
1273 our_env
= new0(char*, 9);
1277 if (service_exec_needs_notify_socket(s
, flags
))
1278 if (asprintf(our_env
+ n_env
++, "NOTIFY_SOCKET=%s", UNIT(s
)->manager
->notify_socket
) < 0)
1281 if (s
->main_pid
> 0)
1282 if (asprintf(our_env
+ n_env
++, "MAINPID="PID_FMT
, s
->main_pid
) < 0)
1285 if (MANAGER_IS_USER(UNIT(s
)->manager
))
1286 if (asprintf(our_env
+ n_env
++, "MANAGERPID="PID_FMT
, getpid()) < 0)
1289 if (s
->socket_fd
>= 0) {
1290 union sockaddr_union sa
;
1291 socklen_t salen
= sizeof(sa
);
1293 r
= getpeername(s
->socket_fd
, &sa
.sa
, &salen
);
1297 /* ENOTCONN is legitimate if the endpoint disappeared on shutdown.
1298 * This connection is over, but the socket unit lives on. */
1299 if (r
!= -ENOTCONN
|| !IN_SET(s
->control_command_id
, SERVICE_EXEC_STOP
, SERVICE_EXEC_STOP_POST
))
1303 if (r
== 0 && IN_SET(sa
.sa
.sa_family
, AF_INET
, AF_INET6
, AF_VSOCK
)) {
1304 _cleanup_free_
char *addr
= NULL
;
1308 r
= sockaddr_pretty(&sa
.sa
, salen
, true, false, &addr
);
1312 t
= strappend("REMOTE_ADDR=", addr
);
1315 our_env
[n_env
++] = t
;
1317 r
= sockaddr_port(&sa
.sa
, &port
);
1321 if (asprintf(&t
, "REMOTE_PORT=%u", port
) < 0)
1323 our_env
[n_env
++] = t
;
1327 if (flags
& EXEC_SETENV_RESULT
) {
1328 if (asprintf(our_env
+ n_env
++, "SERVICE_RESULT=%s", service_result_to_string(s
->result
)) < 0)
1331 if (s
->main_exec_status
.pid
> 0 &&
1332 dual_timestamp_is_set(&s
->main_exec_status
.exit_timestamp
)) {
1333 if (asprintf(our_env
+ n_env
++, "EXIT_CODE=%s", sigchld_code_to_string(s
->main_exec_status
.code
)) < 0)
1336 if (s
->main_exec_status
.code
== CLD_EXITED
)
1337 r
= asprintf(our_env
+ n_env
++, "EXIT_STATUS=%i", s
->main_exec_status
.status
);
1339 r
= asprintf(our_env
+ n_env
++, "EXIT_STATUS=%s", signal_to_string(s
->main_exec_status
.status
));
1345 final_env
= strv_env_merge(2, UNIT(s
)->manager
->environment
, our_env
, NULL
);
1349 if ((flags
& EXEC_IS_CONTROL
) && UNIT(s
)->cgroup_path
) {
1350 path
= strjoina(UNIT(s
)->cgroup_path
, "/control");
1351 (void) cg_create(SYSTEMD_CGROUP_CONTROLLER
, path
);
1353 path
= UNIT(s
)->cgroup_path
;
1355 exec_params
.flags
|= MANAGER_IS_SYSTEM(UNIT(s
)->manager
) ? EXEC_NEW_KEYRING
: 0;
1356 exec_params
.argv
= c
->argv
;
1357 exec_params
.environment
= final_env
;
1358 exec_params
.fds
= fds
;
1359 exec_params
.fd_names
= fd_names
;
1360 exec_params
.n_storage_fds
= n_storage_fds
;
1361 exec_params
.n_socket_fds
= n_socket_fds
;
1362 exec_params
.confirm_spawn
= manager_get_confirm_spawn(UNIT(s
)->manager
);
1363 exec_params
.cgroup_supported
= UNIT(s
)->manager
->cgroup_supported
;
1364 exec_params
.cgroup_path
= path
;
1365 exec_params
.cgroup_delegate
= s
->cgroup_context
.delegate
;
1366 exec_params
.runtime_prefix
= manager_get_runtime_prefix(UNIT(s
)->manager
);
1367 exec_params
.watchdog_usec
= s
->watchdog_usec
;
1368 exec_params
.selinux_context_net
= s
->socket_fd_selinux_context_net
;
1369 if (s
->type
== SERVICE_IDLE
)
1370 exec_params
.idle_pipe
= UNIT(s
)->manager
->idle_pipe
;
1371 exec_params
.stdin_fd
= s
->stdin_fd
;
1372 exec_params
.stdout_fd
= s
->stdout_fd
;
1373 exec_params
.stderr_fd
= s
->stderr_fd
;
1375 r
= exec_spawn(UNIT(s
),
1385 r
= unit_watch_pid(UNIT(s
), pid
);
1386 if (r
< 0) /* FIXME: we need to do something here */
1394 static int main_pid_good(Service
*s
) {
1397 /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1400 /* If we know the pid file, then let's just check if it is
1402 if (s
->main_pid_known
) {
1404 /* If it's an alien child let's check if it is still
1406 if (s
->main_pid_alien
&& s
->main_pid
> 0)
1407 return pid_is_alive(s
->main_pid
);
1409 /* .. otherwise assume we'll get a SIGCHLD for it,
1410 * which we really should wait for to collect exit
1411 * status and code */
1412 return s
->main_pid
> 0;
1415 /* We don't know the pid */
1419 _pure_
static int control_pid_good(Service
*s
) {
1422 return s
->control_pid
> 0;
1425 static int cgroup_good(Service
*s
) {
1430 if (!UNIT(s
)->cgroup_path
)
1433 r
= cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER
, UNIT(s
)->cgroup_path
);
1440 static bool service_shall_restart(Service
*s
) {
1443 /* Don't restart after manual stops */
1444 if (s
->forbid_restart
)
1447 /* Never restart if this is configured as special exception */
1448 if (exit_status_set_test(&s
->restart_prevent_status
, s
->main_exec_status
.code
, s
->main_exec_status
.status
))
1451 /* Restart if the exit code/status are configured as restart triggers */
1452 if (exit_status_set_test(&s
->restart_force_status
, s
->main_exec_status
.code
, s
->main_exec_status
.status
))
1455 switch (s
->restart
) {
1457 case SERVICE_RESTART_NO
:
1460 case SERVICE_RESTART_ALWAYS
:
1463 case SERVICE_RESTART_ON_SUCCESS
:
1464 return s
->result
== SERVICE_SUCCESS
;
1466 case SERVICE_RESTART_ON_FAILURE
:
1467 return s
->result
!= SERVICE_SUCCESS
;
1469 case SERVICE_RESTART_ON_ABNORMAL
:
1470 return !IN_SET(s
->result
, SERVICE_SUCCESS
, SERVICE_FAILURE_EXIT_CODE
);
1472 case SERVICE_RESTART_ON_WATCHDOG
:
1473 return s
->result
== SERVICE_FAILURE_WATCHDOG
;
1475 case SERVICE_RESTART_ON_ABORT
:
1476 return IN_SET(s
->result
, SERVICE_FAILURE_SIGNAL
, SERVICE_FAILURE_CORE_DUMP
);
1479 assert_not_reached("unknown restart setting");
1483 static bool service_will_restart(Service
*s
) {
1486 if (s
->state
== SERVICE_AUTO_RESTART
)
1490 if (UNIT(s
)->job
->type
== JOB_START
)
1495 static void service_enter_dead(Service
*s
, ServiceResult f
, bool allow_restart
) {
1499 if (s
->result
== SERVICE_SUCCESS
)
1502 service_set_state(s
, s
->result
!= SERVICE_SUCCESS
? SERVICE_FAILED
: SERVICE_DEAD
);
1504 if (s
->result
!= SERVICE_SUCCESS
) {
1505 log_unit_warning(UNIT(s
), "Failed with result '%s'.", service_result_to_string(s
->result
));
1506 emergency_action(UNIT(s
)->manager
, s
->emergency_action
, UNIT(s
)->reboot_arg
, "service failed");
1509 if (allow_restart
&& service_shall_restart(s
)) {
1511 r
= service_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->restart_usec
));
1515 service_set_state(s
, SERVICE_AUTO_RESTART
);
1518 /* The next restart might not be a manual stop, hence reset the flag indicating manual stops */
1519 s
->forbid_restart
= false;
1521 /* We want fresh tmpdirs in case service is started again immediately */
1522 exec_runtime_destroy(s
->exec_runtime
);
1523 s
->exec_runtime
= exec_runtime_unref(s
->exec_runtime
);
1525 if (s
->exec_context
.runtime_directory_preserve_mode
== EXEC_PRESERVE_NO
||
1526 (s
->exec_context
.runtime_directory_preserve_mode
== EXEC_PRESERVE_RESTART
&& !service_will_restart(s
)))
1527 /* Also, remove the runtime directory */
1528 exec_context_destroy_runtime_directory(&s
->exec_context
, manager_get_runtime_prefix(UNIT(s
)->manager
));
1530 /* Get rid of the IPC bits of the user */
1531 unit_unref_uid_gid(UNIT(s
), true);
1533 /* Release the user, and destroy it if we are the only remaining owner */
1534 dynamic_creds_destroy(&s
->dynamic_creds
);
1536 /* Try to delete the pid file. At this point it will be
1537 * out-of-date, and some software might be confused by it, so
1538 * let's remove it. */
1540 (void) unlink(s
->pid_file
);
1545 log_unit_warning_errno(UNIT(s
), r
, "Failed to run install restart timer: %m");
1546 service_enter_dead(s
, SERVICE_FAILURE_RESOURCES
, false);
1549 static void service_enter_stop_post(Service
*s
, ServiceResult f
) {
1553 if (s
->result
== SERVICE_SUCCESS
)
1556 service_unwatch_control_pid(s
);
1557 unit_watch_all_pids(UNIT(s
));
1559 s
->control_command
= s
->exec_command
[SERVICE_EXEC_STOP_POST
];
1560 if (s
->control_command
) {
1561 s
->control_command_id
= SERVICE_EXEC_STOP_POST
;
1563 r
= service_spawn(s
,
1565 s
->timeout_stop_usec
,
1566 EXEC_APPLY_PERMISSIONS
|EXEC_APPLY_CHROOT
|EXEC_APPLY_TTY_STDIN
|EXEC_IS_CONTROL
|EXEC_SETENV_RESULT
,
1571 service_set_state(s
, SERVICE_STOP_POST
);
1573 service_enter_signal(s
, SERVICE_FINAL_SIGTERM
, SERVICE_SUCCESS
);
1578 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'stop-post' task: %m");
1579 service_enter_signal(s
, SERVICE_FINAL_SIGTERM
, SERVICE_FAILURE_RESOURCES
);
1582 static int state_to_kill_operation(ServiceState state
) {
1585 case SERVICE_STOP_SIGABRT
:
1588 case SERVICE_STOP_SIGTERM
:
1589 case SERVICE_FINAL_SIGTERM
:
1590 return KILL_TERMINATE
;
1592 case SERVICE_STOP_SIGKILL
:
1593 case SERVICE_FINAL_SIGKILL
:
1597 return _KILL_OPERATION_INVALID
;
1601 static void service_enter_signal(Service
*s
, ServiceState state
, ServiceResult f
) {
1606 if (s
->result
== SERVICE_SUCCESS
)
1609 unit_watch_all_pids(UNIT(s
));
1611 r
= unit_kill_context(
1614 state_to_kill_operation(state
),
1623 r
= service_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_stop_usec
));
1627 service_set_state(s
, state
);
1628 } else if (IN_SET(state
, SERVICE_STOP_SIGABRT
, SERVICE_STOP_SIGTERM
) && s
->kill_context
.send_sigkill
)
1629 service_enter_signal(s
, SERVICE_STOP_SIGKILL
, SERVICE_SUCCESS
);
1630 else if (IN_SET(state
, SERVICE_STOP_SIGABRT
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
))
1631 service_enter_stop_post(s
, SERVICE_SUCCESS
);
1632 else if (state
== SERVICE_FINAL_SIGTERM
&& s
->kill_context
.send_sigkill
)
1633 service_enter_signal(s
, SERVICE_FINAL_SIGKILL
, SERVICE_SUCCESS
);
1635 service_enter_dead(s
, SERVICE_SUCCESS
, true);
1640 log_unit_warning_errno(UNIT(s
), r
, "Failed to kill processes: %m");
1642 if (IN_SET(state
, SERVICE_STOP_SIGABRT
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
))
1643 service_enter_stop_post(s
, SERVICE_FAILURE_RESOURCES
);
1645 service_enter_dead(s
, SERVICE_FAILURE_RESOURCES
, true);
1648 static void service_enter_stop_by_notify(Service
*s
) {
1651 unit_watch_all_pids(UNIT(s
));
1653 service_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_stop_usec
));
1655 /* The service told us it's stopping, so it's as if we SIGTERM'd it. */
1656 service_set_state(s
, SERVICE_STOP_SIGTERM
);
1659 static void service_enter_stop(Service
*s
, ServiceResult f
) {
1664 if (s
->result
== SERVICE_SUCCESS
)
1667 service_unwatch_control_pid(s
);
1668 unit_watch_all_pids(UNIT(s
));
1670 s
->control_command
= s
->exec_command
[SERVICE_EXEC_STOP
];
1671 if (s
->control_command
) {
1672 s
->control_command_id
= SERVICE_EXEC_STOP
;
1674 r
= service_spawn(s
,
1676 s
->timeout_stop_usec
,
1677 EXEC_APPLY_PERMISSIONS
|EXEC_APPLY_CHROOT
|EXEC_IS_CONTROL
|EXEC_SETENV_RESULT
,
1682 service_set_state(s
, SERVICE_STOP
);
1684 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_SUCCESS
);
1689 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'stop' task: %m");
1690 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_RESOURCES
);
1693 static bool service_good(Service
*s
) {
1697 if (s
->type
== SERVICE_DBUS
&& !s
->bus_name_good
)
1700 main_pid_ok
= main_pid_good(s
);
1701 if (main_pid_ok
> 0) /* It's alive */
1703 if (main_pid_ok
== 0) /* It's dead */
1706 /* OK, we don't know anything about the main PID, maybe
1707 * because there is none. Let's check the control group
1710 return cgroup_good(s
) != 0;
1713 static void service_enter_running(Service
*s
, ServiceResult f
) {
1716 if (s
->result
== SERVICE_SUCCESS
)
1719 service_unwatch_control_pid(s
);
1721 if (service_good(s
)) {
1723 /* If there are any queued up sd_notify()
1724 * notifications, process them now */
1725 if (s
->notify_state
== NOTIFY_RELOADING
)
1726 service_enter_reload_by_notify(s
);
1727 else if (s
->notify_state
== NOTIFY_STOPPING
)
1728 service_enter_stop_by_notify(s
);
1730 service_set_state(s
, SERVICE_RUNNING
);
1731 service_arm_timer(s
, usec_add(UNIT(s
)->active_enter_timestamp
.monotonic
, s
->runtime_max_usec
));
1734 } else if (f
!= SERVICE_SUCCESS
)
1735 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
1736 else if (s
->remain_after_exit
)
1737 service_set_state(s
, SERVICE_EXITED
);
1739 service_enter_stop(s
, SERVICE_SUCCESS
);
1742 static void service_enter_start_post(Service
*s
) {
1746 service_unwatch_control_pid(s
);
1747 service_reset_watchdog(s
);
1749 s
->control_command
= s
->exec_command
[SERVICE_EXEC_START_POST
];
1750 if (s
->control_command
) {
1751 s
->control_command_id
= SERVICE_EXEC_START_POST
;
1753 r
= service_spawn(s
,
1755 s
->timeout_start_usec
,
1756 EXEC_APPLY_PERMISSIONS
|EXEC_APPLY_CHROOT
|EXEC_IS_CONTROL
,
1761 service_set_state(s
, SERVICE_START_POST
);
1763 service_enter_running(s
, SERVICE_SUCCESS
);
1768 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'start-post' task: %m");
1769 service_enter_stop(s
, SERVICE_FAILURE_RESOURCES
);
1772 static void service_kill_control_processes(Service
*s
) {
1775 if (!UNIT(s
)->cgroup_path
)
1778 p
= strjoina(UNIT(s
)->cgroup_path
, "/control");
1779 cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER
, p
, SIGKILL
, CGROUP_SIGCONT
|CGROUP_IGNORE_SELF
|CGROUP_REMOVE
, NULL
, NULL
, NULL
);
1782 static void service_enter_start(Service
*s
) {
1790 service_unwatch_control_pid(s
);
1791 service_unwatch_main_pid(s
);
1793 /* We want to ensure that nobody leaks processes from
1794 * START_PRE here, so let's go on a killing spree, People
1795 * should not spawn long running processes from START_PRE. */
1796 service_kill_control_processes(s
);
1798 if (s
->type
== SERVICE_FORKING
) {
1799 s
->control_command_id
= SERVICE_EXEC_START
;
1800 c
= s
->control_command
= s
->exec_command
[SERVICE_EXEC_START
];
1802 s
->main_command
= NULL
;
1804 s
->control_command_id
= _SERVICE_EXEC_COMMAND_INVALID
;
1805 s
->control_command
= NULL
;
1807 c
= s
->main_command
= s
->exec_command
[SERVICE_EXEC_START
];
1811 if (s
->type
!= SERVICE_ONESHOT
) {
1812 /* There's no command line configured for the main command? Hmm, that is strange. This can only
1813 * happen if the configuration changes at runtime. In this case, let's enter a failure
1815 log_unit_error(UNIT(s
), "There's no 'start' task anymore we could start: %m");
1820 service_enter_start_post(s
);
1824 if (IN_SET(s
->type
, SERVICE_SIMPLE
, SERVICE_IDLE
))
1825 /* For simple + idle this is the main process. We don't apply any timeout here, but
1826 * service_enter_running() will later apply the .runtime_max_usec timeout. */
1827 timeout
= USEC_INFINITY
;
1829 timeout
= s
->timeout_start_usec
;
1831 r
= service_spawn(s
,
1834 EXEC_PASS_FDS
|EXEC_APPLY_PERMISSIONS
|EXEC_APPLY_CHROOT
|EXEC_APPLY_TTY_STDIN
|EXEC_SET_WATCHDOG
,
1839 if (IN_SET(s
->type
, SERVICE_SIMPLE
, SERVICE_IDLE
)) {
1840 /* For simple services we immediately start
1841 * the START_POST binaries. */
1843 service_set_main_pid(s
, pid
);
1844 service_enter_start_post(s
);
1846 } else if (s
->type
== SERVICE_FORKING
) {
1848 /* For forking services we wait until the start
1849 * process exited. */
1851 s
->control_pid
= pid
;
1852 service_set_state(s
, SERVICE_START
);
1854 } else if (IN_SET(s
->type
, SERVICE_ONESHOT
, SERVICE_DBUS
, SERVICE_NOTIFY
)) {
1856 /* For oneshot services we wait until the start
1857 * process exited, too, but it is our main process. */
1859 /* For D-Bus services we know the main pid right away,
1860 * but wait for the bus name to appear on the
1861 * bus. Notify services are similar. */
1863 service_set_main_pid(s
, pid
);
1864 service_set_state(s
, SERVICE_START
);
1866 assert_not_reached("Unknown service type");
1871 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'start' task: %m");
1872 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_RESOURCES
);
1875 static void service_enter_start_pre(Service
*s
) {
1880 service_unwatch_control_pid(s
);
1882 s
->control_command
= s
->exec_command
[SERVICE_EXEC_START_PRE
];
1883 if (s
->control_command
) {
1884 /* Before we start anything, let's clear up what might
1885 * be left from previous runs. */
1886 service_kill_control_processes(s
);
1888 s
->control_command_id
= SERVICE_EXEC_START_PRE
;
1890 r
= service_spawn(s
,
1892 s
->timeout_start_usec
,
1893 EXEC_APPLY_PERMISSIONS
|EXEC_APPLY_CHROOT
|EXEC_IS_CONTROL
|EXEC_APPLY_TTY_STDIN
,
1898 service_set_state(s
, SERVICE_START_PRE
);
1900 service_enter_start(s
);
1905 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'start-pre' task: %m");
1906 service_enter_dead(s
, SERVICE_FAILURE_RESOURCES
, true);
1909 static void service_enter_restart(Service
*s
) {
1910 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1915 if (UNIT(s
)->job
&& UNIT(s
)->job
->type
== JOB_STOP
) {
1916 /* Don't restart things if we are going down anyway */
1917 log_unit_info(UNIT(s
), "Stop job pending for unit, delaying automatic restart.");
1919 r
= service_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->restart_usec
));
1926 /* Any units that are bound to this service must also be
1927 * restarted. We use JOB_RESTART (instead of the more obvious
1928 * JOB_START) here so that those dependency jobs will be added
1930 r
= manager_add_job(UNIT(s
)->manager
, JOB_RESTART
, UNIT(s
), JOB_FAIL
, &error
, NULL
);
1934 /* Note that we stay in the SERVICE_AUTO_RESTART state here,
1935 * it will be canceled as part of the service_stop() call that
1936 * is executed as part of JOB_RESTART. */
1938 log_unit_debug(UNIT(s
), "Scheduled restart job.");
1942 log_unit_warning(UNIT(s
), "Failed to schedule restart job: %s", bus_error_message(&error
, -r
));
1943 service_enter_dead(s
, SERVICE_FAILURE_RESOURCES
, false);
1946 static void service_enter_reload_by_notify(Service
*s
) {
1949 service_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_start_usec
));
1950 service_set_state(s
, SERVICE_RELOAD
);
1953 static void service_enter_reload(Service
*s
) {
1958 service_unwatch_control_pid(s
);
1959 s
->reload_result
= SERVICE_SUCCESS
;
1961 s
->control_command
= s
->exec_command
[SERVICE_EXEC_RELOAD
];
1962 if (s
->control_command
) {
1963 s
->control_command_id
= SERVICE_EXEC_RELOAD
;
1965 r
= service_spawn(s
,
1967 s
->timeout_start_usec
,
1968 EXEC_APPLY_PERMISSIONS
|EXEC_APPLY_CHROOT
|EXEC_IS_CONTROL
,
1973 service_set_state(s
, SERVICE_RELOAD
);
1975 service_enter_running(s
, SERVICE_SUCCESS
);
1980 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'reload' task: %m");
1981 s
->reload_result
= SERVICE_FAILURE_RESOURCES
;
1982 service_enter_running(s
, SERVICE_SUCCESS
);
1985 static void service_run_next_control(Service
*s
) {
1990 assert(s
->control_command
);
1991 assert(s
->control_command
->command_next
);
1993 assert(s
->control_command_id
!= SERVICE_EXEC_START
);
1995 s
->control_command
= s
->control_command
->command_next
;
1996 service_unwatch_control_pid(s
);
1998 if (IN_SET(s
->state
, SERVICE_START_PRE
, SERVICE_START
, SERVICE_START_POST
, SERVICE_RUNNING
, SERVICE_RELOAD
))
1999 timeout
= s
->timeout_start_usec
;
2001 timeout
= s
->timeout_stop_usec
;
2003 r
= service_spawn(s
,
2006 EXEC_APPLY_PERMISSIONS
|EXEC_APPLY_CHROOT
|EXEC_IS_CONTROL
|
2007 (IN_SET(s
->control_command_id
, SERVICE_EXEC_START_PRE
, SERVICE_EXEC_STOP_POST
) ? EXEC_APPLY_TTY_STDIN
: 0)|
2008 (IN_SET(s
->control_command_id
, SERVICE_EXEC_STOP
, SERVICE_EXEC_STOP_POST
) ? EXEC_SETENV_RESULT
: 0),
2016 log_unit_warning_errno(UNIT(s
), r
, "Failed to run next control task: %m");
2018 if (IN_SET(s
->state
, SERVICE_START_PRE
, SERVICE_STOP
))
2019 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_RESOURCES
);
2020 else if (s
->state
== SERVICE_STOP_POST
)
2021 service_enter_dead(s
, SERVICE_FAILURE_RESOURCES
, true);
2022 else if (s
->state
== SERVICE_RELOAD
) {
2023 s
->reload_result
= SERVICE_FAILURE_RESOURCES
;
2024 service_enter_running(s
, SERVICE_SUCCESS
);
2026 service_enter_stop(s
, SERVICE_FAILURE_RESOURCES
);
2029 static void service_run_next_main(Service
*s
) {
2034 assert(s
->main_command
);
2035 assert(s
->main_command
->command_next
);
2036 assert(s
->type
== SERVICE_ONESHOT
);
2038 s
->main_command
= s
->main_command
->command_next
;
2039 service_unwatch_main_pid(s
);
2041 r
= service_spawn(s
,
2043 s
->timeout_start_usec
,
2044 EXEC_PASS_FDS
|EXEC_APPLY_PERMISSIONS
|EXEC_APPLY_CHROOT
|EXEC_APPLY_TTY_STDIN
|EXEC_SET_WATCHDOG
,
2049 service_set_main_pid(s
, pid
);
2054 log_unit_warning_errno(UNIT(s
), r
, "Failed to run next main task: %m");
2055 service_enter_stop(s
, SERVICE_FAILURE_RESOURCES
);
2058 static int service_start(Unit
*u
) {
2059 Service
*s
= SERVICE(u
);
2064 /* We cannot fulfill this request right now, try again later
2066 if (IN_SET(s
->state
,
2067 SERVICE_STOP
, SERVICE_STOP_SIGABRT
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
, SERVICE_STOP_POST
,
2068 SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
))
2071 /* Already on it! */
2072 if (IN_SET(s
->state
, SERVICE_START_PRE
, SERVICE_START
, SERVICE_START_POST
))
2075 /* A service that will be restarted must be stopped first to
2076 * trigger BindsTo and/or OnFailure dependencies. If a user
2077 * does not want to wait for the holdoff time to elapse, the
2078 * service should be manually restarted, not started. We
2079 * simply return EAGAIN here, so that any start jobs stay
2080 * queued, and assume that the auto restart timer will
2081 * eventually trigger the restart. */
2082 if (s
->state
== SERVICE_AUTO_RESTART
)
2085 assert(IN_SET(s
->state
, SERVICE_DEAD
, SERVICE_FAILED
));
2087 /* Make sure we don't enter a busy loop of some kind. */
2088 r
= unit_start_limit_test(u
);
2090 service_enter_dead(s
, SERVICE_FAILURE_START_LIMIT_HIT
, false);
2094 r
= unit_acquire_invocation_id(u
);
2098 s
->result
= SERVICE_SUCCESS
;
2099 s
->reload_result
= SERVICE_SUCCESS
;
2100 s
->main_pid_known
= false;
2101 s
->main_pid_alien
= false;
2102 s
->forbid_restart
= false;
2103 s
->reset_cpu_usage
= true;
2105 s
->status_text
= mfree(s
->status_text
);
2106 s
->status_errno
= 0;
2108 s
->notify_state
= NOTIFY_UNKNOWN
;
2110 s
->watchdog_override_enable
= false;
2111 s
->watchdog_override_usec
= 0;
2113 service_enter_start_pre(s
);
2117 static int service_stop(Unit
*u
) {
2118 Service
*s
= SERVICE(u
);
2122 /* Don't create restart jobs from manual stops. */
2123 s
->forbid_restart
= true;
2126 if (IN_SET(s
->state
,
2127 SERVICE_STOP
, SERVICE_STOP_SIGABRT
, SERVICE_STOP_SIGTERM
, SERVICE_STOP_SIGKILL
, SERVICE_STOP_POST
,
2128 SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
))
2131 /* A restart will be scheduled or is in progress. */
2132 if (s
->state
== SERVICE_AUTO_RESTART
) {
2133 service_set_state(s
, SERVICE_DEAD
);
2137 /* If there's already something running we go directly into
2139 if (IN_SET(s
->state
, SERVICE_START_PRE
, SERVICE_START
, SERVICE_START_POST
, SERVICE_RELOAD
)) {
2140 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_SUCCESS
);
2144 assert(IN_SET(s
->state
, SERVICE_RUNNING
, SERVICE_EXITED
));
2146 service_enter_stop(s
, SERVICE_SUCCESS
);
2150 static int service_reload(Unit
*u
) {
2151 Service
*s
= SERVICE(u
);
2155 assert(s
->state
== SERVICE_RUNNING
|| s
->state
== SERVICE_EXITED
);
2157 service_enter_reload(s
);
2161 _pure_
static bool service_can_reload(Unit
*u
) {
2162 Service
*s
= SERVICE(u
);
2166 return !!s
->exec_command
[SERVICE_EXEC_RELOAD
];
2169 static unsigned service_exec_command_index(Unit
*u
, ServiceExecCommand id
, ExecCommand
*current
) {
2170 Service
*s
= SERVICE(u
);
2172 ExecCommand
*first
, *c
;
2176 first
= s
->exec_command
[id
];
2178 /* Figure out where we are in the list by walking back to the beginning */
2179 for (c
= current
; c
!= first
; c
= c
->command_prev
)
2185 static int service_serialize_exec_command(Unit
*u
, FILE *f
, ExecCommand
*command
) {
2186 Service
*s
= SERVICE(u
);
2187 ServiceExecCommand id
;
2191 _cleanup_free_
char *args
= NULL
, *p
= NULL
;
2192 size_t allocated
= 0, length
= 0;
2200 if (command
== s
->control_command
) {
2202 id
= s
->control_command_id
;
2205 id
= SERVICE_EXEC_START
;
2208 idx
= service_exec_command_index(u
, id
, command
);
2210 STRV_FOREACH(arg
, command
->argv
) {
2212 _cleanup_free_
char *e
= NULL
;
2214 e
= xescape(*arg
, WHITESPACE
);
2219 if (!GREEDY_REALLOC(args
, allocated
, length
+ 1 + n
+ 1))
2223 args
[length
++] = ' ';
2225 memcpy(args
+ length
, e
, n
);
2229 if (!GREEDY_REALLOC(args
, allocated
, length
+ 1))
2233 p
= xescape(command
->path
, WHITESPACE
);
2237 fprintf(f
, "%s-command=%s %u %s %s\n", type
, service_exec_command_to_string(id
), idx
, p
, args
);
2242 static int service_serialize(Unit
*u
, FILE *f
, FDSet
*fds
) {
2243 Service
*s
= SERVICE(u
);
2251 unit_serialize_item(u
, f
, "state", service_state_to_string(s
->state
));
2252 unit_serialize_item(u
, f
, "result", service_result_to_string(s
->result
));
2253 unit_serialize_item(u
, f
, "reload-result", service_result_to_string(s
->reload_result
));
2255 if (s
->control_pid
> 0)
2256 unit_serialize_item_format(u
, f
, "control-pid", PID_FMT
, s
->control_pid
);
2258 if (s
->main_pid_known
&& s
->main_pid
> 0)
2259 unit_serialize_item_format(u
, f
, "main-pid", PID_FMT
, s
->main_pid
);
2261 unit_serialize_item(u
, f
, "main-pid-known", yes_no(s
->main_pid_known
));
2262 unit_serialize_item(u
, f
, "bus-name-good", yes_no(s
->bus_name_good
));
2263 unit_serialize_item(u
, f
, "bus-name-owner", s
->bus_name_owner
);
2265 r
= unit_serialize_item_escaped(u
, f
, "status-text", s
->status_text
);
2269 service_serialize_exec_command(u
, f
, s
->control_command
);
2270 service_serialize_exec_command(u
, f
, s
->main_command
);
2272 r
= unit_serialize_item_fd(u
, f
, fds
, "stdin-fd", s
->stdin_fd
);
2275 r
= unit_serialize_item_fd(u
, f
, fds
, "stdout-fd", s
->stdout_fd
);
2278 r
= unit_serialize_item_fd(u
, f
, fds
, "stderr-fd", s
->stderr_fd
);
2282 if (UNIT_ISSET(s
->accept_socket
)) {
2283 r
= unit_serialize_item(u
, f
, "accept-socket", UNIT_DEREF(s
->accept_socket
)->id
);
2288 r
= unit_serialize_item_fd(u
, f
, fds
, "socket-fd", s
->socket_fd
);
2292 LIST_FOREACH(fd_store
, fs
, s
->fd_store
) {
2293 _cleanup_free_
char *c
= NULL
;
2296 copy
= fdset_put_dup(fds
, fs
->fd
);
2300 c
= cescape(fs
->fdname
);
2302 unit_serialize_item_format(u
, f
, "fd-store-fd", "%i %s", copy
, strempty(c
));
2305 if (s
->main_exec_status
.pid
> 0) {
2306 unit_serialize_item_format(u
, f
, "main-exec-status-pid", PID_FMT
, s
->main_exec_status
.pid
);
2307 dual_timestamp_serialize(f
, "main-exec-status-start", &s
->main_exec_status
.start_timestamp
);
2308 dual_timestamp_serialize(f
, "main-exec-status-exit", &s
->main_exec_status
.exit_timestamp
);
2310 if (dual_timestamp_is_set(&s
->main_exec_status
.exit_timestamp
)) {
2311 unit_serialize_item_format(u
, f
, "main-exec-status-code", "%i", s
->main_exec_status
.code
);
2312 unit_serialize_item_format(u
, f
, "main-exec-status-status", "%i", s
->main_exec_status
.status
);
2316 dual_timestamp_serialize(f
, "watchdog-timestamp", &s
->watchdog_timestamp
);
2318 unit_serialize_item(u
, f
, "forbid-restart", yes_no(s
->forbid_restart
));
2320 if (s
->watchdog_override_enable
)
2321 unit_serialize_item_format(u
, f
, "watchdog-override-usec", USEC_FMT
, s
->watchdog_override_usec
);
2326 static int service_deserialize_exec_command(Unit
*u
, const char *key
, const char *value
) {
2327 Service
*s
= SERVICE(u
);
2329 unsigned idx
= 0, i
;
2330 bool control
, found
= false;
2331 ServiceExecCommand id
= _SERVICE_EXEC_COMMAND_INVALID
;
2332 ExecCommand
*command
= NULL
;
2333 _cleanup_free_
char *path
= NULL
;
2334 _cleanup_strv_free_
char **argv
= NULL
;
2336 enum ExecCommandState
{
2337 STATE_EXEC_COMMAND_TYPE
,
2338 STATE_EXEC_COMMAND_INDEX
,
2339 STATE_EXEC_COMMAND_PATH
,
2340 STATE_EXEC_COMMAND_ARGS
,
2341 _STATE_EXEC_COMMAND_MAX
,
2342 _STATE_EXEC_COMMAND_INVALID
= -1,
2349 control
= streq(key
, "control-command");
2351 state
= STATE_EXEC_COMMAND_TYPE
;
2354 _cleanup_free_
char *arg
= NULL
;
2356 r
= extract_first_word(&value
, &arg
, NULL
, EXTRACT_CUNESCAPE
);
2363 case STATE_EXEC_COMMAND_TYPE
:
2364 id
= service_exec_command_from_string(arg
);
2368 state
= STATE_EXEC_COMMAND_INDEX
;
2370 case STATE_EXEC_COMMAND_INDEX
:
2371 r
= safe_atou(arg
, &idx
);
2375 state
= STATE_EXEC_COMMAND_PATH
;
2377 case STATE_EXEC_COMMAND_PATH
:
2380 state
= STATE_EXEC_COMMAND_ARGS
;
2382 if (!path_is_absolute(path
))
2385 case STATE_EXEC_COMMAND_ARGS
:
2386 r
= strv_extend(&argv
, arg
);
2391 assert_not_reached("Unknown error at deserialization of exec command");
2396 if (state
!= STATE_EXEC_COMMAND_ARGS
)
2399 /* Let's check whether exec command on given offset matches data that we just deserialized */
2400 for (command
= s
->exec_command
[id
], i
= 0; command
; command
= command
->command_next
, i
++) {
2404 found
= strv_equal(argv
, command
->argv
) && streq(command
->path
, path
);
2409 /* Command at the index we serialized is different, let's look for command that exactly
2410 * matches but is on different index. If there is no such command we will not resume execution. */
2411 for (command
= s
->exec_command
[id
]; command
; command
= command
->command_next
)
2412 if (strv_equal(command
->argv
, argv
) && streq(command
->path
, path
))
2416 if (command
&& control
)
2417 s
->control_command
= command
;
2419 s
->main_command
= command
;
2421 log_unit_warning(u
, "Current command vanished from the unit file, execution of the command list won't be resumed.");
2426 static int service_deserialize_item(Unit
*u
, const char *key
, const char *value
, FDSet
*fds
) {
2427 Service
*s
= SERVICE(u
);
2435 if (streq(key
, "state")) {
2438 state
= service_state_from_string(value
);
2440 log_unit_debug(u
, "Failed to parse state value: %s", value
);
2442 s
->deserialized_state
= state
;
2443 } else if (streq(key
, "result")) {
2446 f
= service_result_from_string(value
);
2448 log_unit_debug(u
, "Failed to parse result value: %s", value
);
2449 else if (f
!= SERVICE_SUCCESS
)
2452 } else if (streq(key
, "reload-result")) {
2455 f
= service_result_from_string(value
);
2457 log_unit_debug(u
, "Failed to parse reload result value: %s", value
);
2458 else if (f
!= SERVICE_SUCCESS
)
2459 s
->reload_result
= f
;
2461 } else if (streq(key
, "control-pid")) {
2464 if (parse_pid(value
, &pid
) < 0)
2465 log_unit_debug(u
, "Failed to parse control-pid value: %s", value
);
2467 s
->control_pid
= pid
;
2468 } else if (streq(key
, "main-pid")) {
2471 if (parse_pid(value
, &pid
) < 0)
2472 log_unit_debug(u
, "Failed to parse main-pid value: %s", value
);
2474 service_set_main_pid(s
, pid
);
2475 unit_watch_pid(UNIT(s
), pid
);
2477 } else if (streq(key
, "main-pid-known")) {
2480 b
= parse_boolean(value
);
2482 log_unit_debug(u
, "Failed to parse main-pid-known value: %s", value
);
2484 s
->main_pid_known
= b
;
2485 } else if (streq(key
, "bus-name-good")) {
2488 b
= parse_boolean(value
);
2490 log_unit_debug(u
, "Failed to parse bus-name-good value: %s", value
);
2492 s
->bus_name_good
= b
;
2493 } else if (streq(key
, "bus-name-owner")) {
2494 r
= free_and_strdup(&s
->bus_name_owner
, value
);
2496 log_unit_error_errno(u
, r
, "Unable to deserialize current bus owner %s: %m", value
);
2497 } else if (streq(key
, "status-text")) {
2500 r
= cunescape(value
, 0, &t
);
2502 log_unit_debug_errno(u
, r
, "Failed to unescape status text: %s", value
);
2504 free(s
->status_text
);
2508 } else if (streq(key
, "accept-socket")) {
2511 r
= manager_load_unit(u
->manager
, value
, NULL
, NULL
, &socket
);
2513 log_unit_debug_errno(u
, r
, "Failed to load accept-socket unit: %s", value
);
2515 unit_ref_set(&s
->accept_socket
, socket
);
2516 SOCKET(socket
)->n_connections
++;
2519 } else if (streq(key
, "socket-fd")) {
2522 if (safe_atoi(value
, &fd
) < 0 || fd
< 0 || !fdset_contains(fds
, fd
))
2523 log_unit_debug(u
, "Failed to parse socket-fd value: %s", value
);
2525 asynchronous_close(s
->socket_fd
);
2526 s
->socket_fd
= fdset_remove(fds
, fd
);
2528 } else if (streq(key
, "fd-store-fd")) {
2533 pf
= strcspn(value
, WHITESPACE
);
2534 fdv
= strndupa(value
, pf
);
2536 if (safe_atoi(fdv
, &fd
) < 0 || fd
< 0 || !fdset_contains(fds
, fd
))
2537 log_unit_debug(u
, "Failed to parse fd-store-fd value: %s", value
);
2539 _cleanup_free_
char *t
= NULL
;
2543 fdn
+= strspn(fdn
, WHITESPACE
);
2544 (void) cunescape(fdn
, 0, &t
);
2546 r
= service_add_fd_store(s
, fd
, t
);
2548 log_unit_error_errno(u
, r
, "Failed to add fd to store: %m");
2550 fdset_remove(fds
, fd
);
2553 } else if (streq(key
, "main-exec-status-pid")) {
2556 if (parse_pid(value
, &pid
) < 0)
2557 log_unit_debug(u
, "Failed to parse main-exec-status-pid value: %s", value
);
2559 s
->main_exec_status
.pid
= pid
;
2560 } else if (streq(key
, "main-exec-status-code")) {
2563 if (safe_atoi(value
, &i
) < 0)
2564 log_unit_debug(u
, "Failed to parse main-exec-status-code value: %s", value
);
2566 s
->main_exec_status
.code
= i
;
2567 } else if (streq(key
, "main-exec-status-status")) {
2570 if (safe_atoi(value
, &i
) < 0)
2571 log_unit_debug(u
, "Failed to parse main-exec-status-status value: %s", value
);
2573 s
->main_exec_status
.status
= i
;
2574 } else if (streq(key
, "main-exec-status-start"))
2575 dual_timestamp_deserialize(value
, &s
->main_exec_status
.start_timestamp
);
2576 else if (streq(key
, "main-exec-status-exit"))
2577 dual_timestamp_deserialize(value
, &s
->main_exec_status
.exit_timestamp
);
2578 else if (streq(key
, "watchdog-timestamp"))
2579 dual_timestamp_deserialize(value
, &s
->watchdog_timestamp
);
2580 else if (streq(key
, "forbid-restart")) {
2583 b
= parse_boolean(value
);
2585 log_unit_debug(u
, "Failed to parse forbid-restart value: %s", value
);
2587 s
->forbid_restart
= b
;
2588 } else if (streq(key
, "stdin-fd")) {
2591 if (safe_atoi(value
, &fd
) < 0 || fd
< 0 || !fdset_contains(fds
, fd
))
2592 log_unit_debug(u
, "Failed to parse stdin-fd value: %s", value
);
2594 asynchronous_close(s
->stdin_fd
);
2595 s
->stdin_fd
= fdset_remove(fds
, fd
);
2596 s
->exec_context
.stdio_as_fds
= true;
2598 } else if (streq(key
, "stdout-fd")) {
2601 if (safe_atoi(value
, &fd
) < 0 || fd
< 0 || !fdset_contains(fds
, fd
))
2602 log_unit_debug(u
, "Failed to parse stdout-fd value: %s", value
);
2604 asynchronous_close(s
->stdout_fd
);
2605 s
->stdout_fd
= fdset_remove(fds
, fd
);
2606 s
->exec_context
.stdio_as_fds
= true;
2608 } else if (streq(key
, "stderr-fd")) {
2611 if (safe_atoi(value
, &fd
) < 0 || fd
< 0 || !fdset_contains(fds
, fd
))
2612 log_unit_debug(u
, "Failed to parse stderr-fd value: %s", value
);
2614 asynchronous_close(s
->stderr_fd
);
2615 s
->stderr_fd
= fdset_remove(fds
, fd
);
2616 s
->exec_context
.stdio_as_fds
= true;
2618 } else if (streq(key
, "watchdog-override-usec")) {
2619 usec_t watchdog_override_usec
;
2620 if (timestamp_deserialize(value
, &watchdog_override_usec
) < 0)
2621 log_unit_debug(u
, "Failed to parse watchdog_override_usec value: %s", value
);
2623 s
->watchdog_override_enable
= true;
2624 s
->watchdog_override_usec
= watchdog_override_usec
;
2626 } else if (STR_IN_SET(key
, "main-command", "control-command")) {
2627 r
= service_deserialize_exec_command(u
, key
, value
);
2629 log_unit_debug_errno(u
, r
, "Failed to parse serialized command \"%s\": %m", value
);
2631 log_unit_debug(u
, "Unknown serialization key: %s", key
);
2636 _pure_
static UnitActiveState
service_active_state(Unit
*u
) {
2637 const UnitActiveState
*table
;
2641 table
= SERVICE(u
)->type
== SERVICE_IDLE
? state_translation_table_idle
: state_translation_table
;
2643 return table
[SERVICE(u
)->state
];
2646 static const char *service_sub_state_to_string(Unit
*u
) {
2649 return service_state_to_string(SERVICE(u
)->state
);
2652 static bool service_check_gc(Unit
*u
) {
2653 Service
*s
= SERVICE(u
);
2657 /* Never clean up services that still have a process around,
2658 * even if the service is formally dead. */
2659 if (cgroup_good(s
) > 0 ||
2660 main_pid_good(s
) > 0 ||
2661 control_pid_good(s
) > 0)
2667 static int service_retry_pid_file(Service
*s
) {
2670 assert(s
->pid_file
);
2671 assert(s
->state
== SERVICE_START
|| s
->state
== SERVICE_START_POST
);
2673 r
= service_load_pid_file(s
, false);
2677 service_unwatch_pid_file(s
);
2679 service_enter_running(s
, SERVICE_SUCCESS
);
2683 static int service_watch_pid_file(Service
*s
) {
2686 log_unit_debug(UNIT(s
), "Setting watch for PID file %s", s
->pid_file_pathspec
->path
);
2688 r
= path_spec_watch(s
->pid_file_pathspec
, service_dispatch_io
);
2692 /* the pidfile might have appeared just before we set the watch */
2693 log_unit_debug(UNIT(s
), "Trying to read PID file %s in case it changed", s
->pid_file_pathspec
->path
);
2694 service_retry_pid_file(s
);
2698 log_unit_error_errno(UNIT(s
), r
, "Failed to set a watch for PID file %s: %m", s
->pid_file_pathspec
->path
);
2699 service_unwatch_pid_file(s
);
2703 static int service_demand_pid_file(Service
*s
) {
2706 assert(s
->pid_file
);
2707 assert(!s
->pid_file_pathspec
);
2709 ps
= new0(PathSpec
, 1);
2714 ps
->path
= strdup(s
->pid_file
);
2720 path_kill_slashes(ps
->path
);
2722 /* PATH_CHANGED would not be enough. There are daemons (sendmail) that
2723 * keep their PID file open all the time. */
2724 ps
->type
= PATH_MODIFIED
;
2725 ps
->inotify_fd
= -1;
2727 s
->pid_file_pathspec
= ps
;
2729 return service_watch_pid_file(s
);
2732 static int service_dispatch_io(sd_event_source
*source
, int fd
, uint32_t events
, void *userdata
) {
2733 PathSpec
*p
= userdata
;
2738 s
= SERVICE(p
->unit
);
2742 assert(s
->state
== SERVICE_START
|| s
->state
== SERVICE_START_POST
);
2743 assert(s
->pid_file_pathspec
);
2744 assert(path_spec_owns_inotify_fd(s
->pid_file_pathspec
, fd
));
2746 log_unit_debug(UNIT(s
), "inotify event");
2748 if (path_spec_fd_event(p
, events
) < 0)
2751 if (service_retry_pid_file(s
) == 0)
2754 if (service_watch_pid_file(s
) < 0)
2760 service_unwatch_pid_file(s
);
2761 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_RESOURCES
);
2765 static void service_notify_cgroup_empty_event(Unit
*u
) {
2766 Service
*s
= SERVICE(u
);
2770 log_unit_debug(u
, "cgroup is empty");
2774 /* Waiting for SIGCHLD is usually more interesting,
2775 * because it includes return codes/signals. Which is
2776 * why we ignore the cgroup events for most cases,
2777 * except when we don't know pid which to expect the
2781 if (s
->type
== SERVICE_NOTIFY
) {
2782 /* No chance of getting a ready notification anymore */
2783 service_enter_stop_post(s
, SERVICE_FAILURE_PROTOCOL
);
2789 case SERVICE_START_POST
:
2790 if (s
->pid_file_pathspec
) {
2791 /* Give up hoping for the daemon to write its PID file */
2792 log_unit_warning(u
, "Daemon never wrote its PID file. Failing.");
2794 service_unwatch_pid_file(s
);
2795 if (s
->state
== SERVICE_START
)
2796 service_enter_stop_post(s
, SERVICE_FAILURE_PROTOCOL
);
2798 service_enter_stop(s
, SERVICE_FAILURE_PROTOCOL
);
2802 case SERVICE_RUNNING
:
2803 /* service_enter_running() will figure out what to do */
2804 service_enter_running(s
, SERVICE_SUCCESS
);
2807 case SERVICE_STOP_SIGABRT
:
2808 case SERVICE_STOP_SIGTERM
:
2809 case SERVICE_STOP_SIGKILL
:
2811 if (main_pid_good(s
) <= 0 && !control_pid_good(s
))
2812 service_enter_stop_post(s
, SERVICE_SUCCESS
);
2816 case SERVICE_STOP_POST
:
2817 case SERVICE_FINAL_SIGTERM
:
2818 case SERVICE_FINAL_SIGKILL
:
2819 if (main_pid_good(s
) <= 0 && !control_pid_good(s
))
2820 service_enter_dead(s
, SERVICE_SUCCESS
, true);
2829 static void service_sigchld_event(Unit
*u
, pid_t pid
, int code
, int status
) {
2830 Service
*s
= SERVICE(u
);
2836 if (is_clean_exit(code
, status
, s
->type
== SERVICE_ONESHOT
? EXIT_CLEAN_COMMAND
: EXIT_CLEAN_DAEMON
, &s
->success_status
))
2837 f
= SERVICE_SUCCESS
;
2838 else if (code
== CLD_EXITED
)
2839 f
= SERVICE_FAILURE_EXIT_CODE
;
2840 else if (code
== CLD_KILLED
)
2841 f
= SERVICE_FAILURE_SIGNAL
;
2842 else if (code
== CLD_DUMPED
)
2843 f
= SERVICE_FAILURE_CORE_DUMP
;
2845 assert_not_reached("Unknown code");
2847 if (s
->main_pid
== pid
) {
2848 /* Forking services may occasionally move to a new PID.
2849 * As long as they update the PID file before exiting the old
2850 * PID, they're fine. */
2851 if (service_load_pid_file(s
, false) == 0)
2855 exec_status_exit(&s
->main_exec_status
, &s
->exec_context
, pid
, code
, status
);
2857 if (s
->main_command
) {
2858 /* If this is not a forking service than the
2859 * main process got started and hence we copy
2860 * the exit status so that it is recorded both
2861 * as main and as control process exit
2864 s
->main_command
->exec_status
= s
->main_exec_status
;
2866 if (s
->main_command
->ignore
)
2867 f
= SERVICE_SUCCESS
;
2868 } else if (s
->exec_command
[SERVICE_EXEC_START
]) {
2870 /* If this is a forked process, then we should
2871 * ignore the return value if this was
2872 * configured for the starter process */
2874 if (s
->exec_command
[SERVICE_EXEC_START
]->ignore
)
2875 f
= SERVICE_SUCCESS
;
2878 /* When this is a successful exit, let's log about the exit code on DEBUG level. If this is a failure
2879 * and the process exited on its own via exit(), then let's make this a NOTICE, under the assumption
2880 * that the service already logged the reason at a higher log level on its own. However, if the service
2881 * died due to a signal, then it most likely didn't say anything about any reason, hence let's raise
2882 * our log level to WARNING then. */
2884 log_struct(f
== SERVICE_SUCCESS
? LOG_DEBUG
:
2885 (code
== CLD_EXITED
? LOG_NOTICE
: LOG_WARNING
),
2886 LOG_UNIT_MESSAGE(u
, "Main process exited, code=%s, status=%i/%s",
2887 sigchld_code_to_string(code
), status
,
2888 strna(code
== CLD_EXITED
2889 ? exit_status_to_string(status
, EXIT_STATUS_FULL
)
2890 : signal_to_string(status
))),
2891 "EXIT_CODE=%s", sigchld_code_to_string(code
),
2892 "EXIT_STATUS=%i", status
,
2896 if (s
->result
== SERVICE_SUCCESS
)
2899 if (s
->main_command
&&
2900 s
->main_command
->command_next
&&
2901 f
== SERVICE_SUCCESS
) {
2903 /* There is another command to *
2904 * execute, so let's do that. */
2906 log_unit_debug(u
, "Running next main command for state %s.", service_state_to_string(s
->state
));
2907 service_run_next_main(s
);
2911 /* The service exited, so the service is officially
2913 s
->main_command
= NULL
;
2917 case SERVICE_START_POST
:
2918 case SERVICE_RELOAD
:
2920 /* Need to wait until the operation is
2925 if (s
->type
== SERVICE_ONESHOT
) {
2926 /* This was our main goal, so let's go on */
2927 if (f
== SERVICE_SUCCESS
)
2928 service_enter_start_post(s
);
2930 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
2932 } else if (s
->type
== SERVICE_NOTIFY
) {
2933 /* Only enter running through a notification, so that the
2934 * SERVICE_START state signifies that no ready notification
2935 * has been received */
2936 if (f
!= SERVICE_SUCCESS
)
2937 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
2938 else if (!s
->remain_after_exit
)
2939 /* The service has never been active */
2940 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_PROTOCOL
);
2946 case SERVICE_RUNNING
:
2947 service_enter_running(s
, f
);
2950 case SERVICE_STOP_SIGABRT
:
2951 case SERVICE_STOP_SIGTERM
:
2952 case SERVICE_STOP_SIGKILL
:
2954 if (!control_pid_good(s
))
2955 service_enter_stop_post(s
, f
);
2957 /* If there is still a control process, wait for that first */
2960 case SERVICE_STOP_POST
:
2961 case SERVICE_FINAL_SIGTERM
:
2962 case SERVICE_FINAL_SIGKILL
:
2964 if (!control_pid_good(s
))
2965 service_enter_dead(s
, f
, true);
2969 assert_not_reached("Uh, main process died at wrong time.");
2973 } else if (s
->control_pid
== pid
) {
2976 if (s
->control_command
) {
2977 exec_status_exit(&s
->control_command
->exec_status
, &s
->exec_context
, pid
, code
, status
);
2979 if (s
->control_command
->ignore
)
2980 f
= SERVICE_SUCCESS
;
2983 log_unit_full(u
, f
== SERVICE_SUCCESS
? LOG_DEBUG
: LOG_NOTICE
, 0,
2984 "Control process exited, code=%s status=%i",
2985 sigchld_code_to_string(code
), status
);
2987 if (s
->result
== SERVICE_SUCCESS
)
2990 /* Immediately get rid of the cgroup, so that the
2991 * kernel doesn't delay the cgroup empty messages for
2992 * the service cgroup any longer than necessary */
2993 service_kill_control_processes(s
);
2995 if (s
->control_command
&&
2996 s
->control_command
->command_next
&&
2997 f
== SERVICE_SUCCESS
) {
2999 /* There is another command to *
3000 * execute, so let's do that. */
3002 log_unit_debug(u
, "Running next control command for state %s.", service_state_to_string(s
->state
));
3003 service_run_next_control(s
);
3006 /* No further commands for this step, so let's
3007 * figure out what to do next */
3009 s
->control_command
= NULL
;
3010 s
->control_command_id
= _SERVICE_EXEC_COMMAND_INVALID
;
3012 log_unit_debug(u
, "Got final SIGCHLD for state %s.", service_state_to_string(s
->state
));
3016 case SERVICE_START_PRE
:
3017 if (f
== SERVICE_SUCCESS
)
3018 service_enter_start(s
);
3020 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
3024 if (s
->type
!= SERVICE_FORKING
)
3025 /* Maybe spurious event due to a reload that changed the type? */
3028 if (f
!= SERVICE_SUCCESS
) {
3029 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
3034 bool has_start_post
;
3037 /* Let's try to load the pid file here if we can.
3038 * The PID file might actually be created by a START_POST
3039 * script. In that case don't worry if the loading fails. */
3041 has_start_post
= !!s
->exec_command
[SERVICE_EXEC_START_POST
];
3042 r
= service_load_pid_file(s
, !has_start_post
);
3043 if (!has_start_post
&& r
< 0) {
3044 r
= service_demand_pid_file(s
);
3045 if (r
< 0 || !cgroup_good(s
))
3046 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_PROTOCOL
);
3050 service_search_main_pid(s
);
3052 service_enter_start_post(s
);
3055 case SERVICE_START_POST
:
3056 if (f
!= SERVICE_SUCCESS
) {
3057 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
3064 r
= service_load_pid_file(s
, true);
3066 r
= service_demand_pid_file(s
);
3067 if (r
< 0 || !cgroup_good(s
))
3068 service_enter_stop(s
, SERVICE_FAILURE_PROTOCOL
);
3072 service_search_main_pid(s
);
3074 service_enter_running(s
, SERVICE_SUCCESS
);
3077 case SERVICE_RELOAD
:
3078 if (f
== SERVICE_SUCCESS
)
3079 if (service_load_pid_file(s
, true) < 0)
3080 service_search_main_pid(s
);
3082 s
->reload_result
= f
;
3083 service_enter_running(s
, SERVICE_SUCCESS
);
3087 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, f
);
3090 case SERVICE_STOP_SIGABRT
:
3091 case SERVICE_STOP_SIGTERM
:
3092 case SERVICE_STOP_SIGKILL
:
3093 if (main_pid_good(s
) <= 0)
3094 service_enter_stop_post(s
, f
);
3096 /* If there is still a service
3097 * process around, wait until
3098 * that one quit, too */
3101 case SERVICE_STOP_POST
:
3102 case SERVICE_FINAL_SIGTERM
:
3103 case SERVICE_FINAL_SIGKILL
:
3104 if (main_pid_good(s
) <= 0)
3105 service_enter_dead(s
, f
, true);
3109 assert_not_reached("Uh, control process died at wrong time.");
3114 /* Notify clients about changed exit status */
3115 unit_add_to_dbus_queue(u
);
3117 /* We got one SIGCHLD for the service, let's watch all
3118 * processes that are now running of the service, and watch
3119 * that. Among the PIDs we then watch will be children
3120 * reassigned to us, which hopefully allows us to identify
3121 * when all children are gone */
3122 unit_tidy_watch_pids(u
, s
->main_pid
, s
->control_pid
);
3123 unit_watch_all_pids(u
);
3125 /* If the PID set is empty now, then let's finish this off
3126 (On unified we use proper notifications) */
3127 if (cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER
) == 0 && set_isempty(u
->pids
))
3128 service_notify_cgroup_empty_event(u
);
3131 static int service_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
) {
3132 Service
*s
= SERVICE(userdata
);
3135 assert(source
== s
->timer_event_source
);
3139 case SERVICE_START_PRE
:
3141 log_unit_warning(UNIT(s
), "%s operation timed out. Terminating.", s
->state
== SERVICE_START
? "Start" : "Start-pre");
3142 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_TIMEOUT
);
3145 case SERVICE_START_POST
:
3146 log_unit_warning(UNIT(s
), "Start-post operation timed out. Stopping.");
3147 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_TIMEOUT
);
3150 case SERVICE_RUNNING
:
3151 log_unit_warning(UNIT(s
), "Service reached runtime time limit. Stopping.");
3152 service_enter_stop(s
, SERVICE_FAILURE_TIMEOUT
);
3155 case SERVICE_RELOAD
:
3156 log_unit_warning(UNIT(s
), "Reload operation timed out. Killing reload process.");
3157 service_kill_control_processes(s
);
3158 s
->reload_result
= SERVICE_FAILURE_TIMEOUT
;
3159 service_enter_running(s
, SERVICE_SUCCESS
);
3163 log_unit_warning(UNIT(s
), "Stopping timed out. Terminating.");
3164 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_TIMEOUT
);
3167 case SERVICE_STOP_SIGABRT
:
3168 log_unit_warning(UNIT(s
), "State 'stop-sigabrt' timed out. Terminating.");
3169 service_enter_signal(s
, SERVICE_STOP_SIGTERM
, SERVICE_FAILURE_TIMEOUT
);
3172 case SERVICE_STOP_SIGTERM
:
3173 if (s
->kill_context
.send_sigkill
) {
3174 log_unit_warning(UNIT(s
), "State 'stop-sigterm' timed out. Killing.");
3175 service_enter_signal(s
, SERVICE_STOP_SIGKILL
, SERVICE_FAILURE_TIMEOUT
);
3177 log_unit_warning(UNIT(s
), "State 'stop-sigterm' timed out. Skipping SIGKILL.");
3178 service_enter_stop_post(s
, SERVICE_FAILURE_TIMEOUT
);
3183 case SERVICE_STOP_SIGKILL
:
3184 /* Uh, we sent a SIGKILL and it is still not gone?
3185 * Must be something we cannot kill, so let's just be
3186 * weirded out and continue */
3188 log_unit_warning(UNIT(s
), "Processes still around after SIGKILL. Ignoring.");
3189 service_enter_stop_post(s
, SERVICE_FAILURE_TIMEOUT
);
3192 case SERVICE_STOP_POST
:
3193 log_unit_warning(UNIT(s
), "State 'stop-post' timed out. Terminating.");
3194 service_enter_signal(s
, SERVICE_FINAL_SIGTERM
, SERVICE_FAILURE_TIMEOUT
);
3197 case SERVICE_FINAL_SIGTERM
:
3198 if (s
->kill_context
.send_sigkill
) {
3199 log_unit_warning(UNIT(s
), "State 'stop-final-sigterm' timed out. Killing.");
3200 service_enter_signal(s
, SERVICE_FINAL_SIGKILL
, SERVICE_FAILURE_TIMEOUT
);
3202 log_unit_warning(UNIT(s
), "State 'stop-final-sigterm' timed out. Skipping SIGKILL. Entering failed mode.");
3203 service_enter_dead(s
, SERVICE_FAILURE_TIMEOUT
, false);
3208 case SERVICE_FINAL_SIGKILL
:
3209 log_unit_warning(UNIT(s
), "Processes still around after final SIGKILL. Entering failed mode.");
3210 service_enter_dead(s
, SERVICE_FAILURE_TIMEOUT
, true);
3213 case SERVICE_AUTO_RESTART
:
3214 log_unit_info(UNIT(s
),
3215 s
->restart_usec
> 0 ?
3216 "Service hold-off time over, scheduling restart." :
3217 "Service has no hold-off time, scheduling restart.");
3218 service_enter_restart(s
);
3222 assert_not_reached("Timeout at wrong time.");
3228 static int service_dispatch_watchdog(sd_event_source
*source
, usec_t usec
, void *userdata
) {
3229 Service
*s
= SERVICE(userdata
);
3230 char t
[FORMAT_TIMESPAN_MAX
];
3231 usec_t watchdog_usec
;
3234 assert(source
== s
->watchdog_event_source
);
3236 watchdog_usec
= service_get_watchdog_usec(s
);
3238 log_unit_error(UNIT(s
), "Watchdog timeout (limit %s)!",
3239 format_timespan(t
, sizeof(t
), watchdog_usec
, 1));
3241 service_enter_signal(s
, SERVICE_STOP_SIGABRT
, SERVICE_FAILURE_WATCHDOG
);
3246 static void service_notify_message(Unit
*u
, pid_t pid
, char **tags
, FDSet
*fds
) {
3247 Service
*s
= SERVICE(u
);
3248 _cleanup_free_
char *cc
= NULL
;
3249 bool notify_dbus
= false;
3254 cc
= strv_join(tags
, ", ");
3256 if (s
->notify_access
== NOTIFY_NONE
) {
3257 log_unit_warning(u
, "Got notification message from PID "PID_FMT
", but reception is disabled.", pid
);
3259 } else if (s
->notify_access
== NOTIFY_MAIN
&& pid
!= s
->main_pid
) {
3260 if (s
->main_pid
!= 0)
3261 log_unit_warning(u
, "Got notification message from PID "PID_FMT
", but reception only permitted for main PID "PID_FMT
, pid
, s
->main_pid
);
3263 log_unit_warning(u
, "Got notification message from PID "PID_FMT
", but reception only permitted for main PID which is currently not known", pid
);
3265 } else if (s
->notify_access
== NOTIFY_EXEC
&& pid
!= s
->main_pid
&& pid
!= s
->control_pid
) {
3266 if (s
->main_pid
!= 0 && s
->control_pid
!= 0)
3267 log_unit_warning(u
, "Got notification message from PID "PID_FMT
", but reception only permitted for main PID "PID_FMT
" and control PID "PID_FMT
,
3268 pid
, s
->main_pid
, s
->control_pid
);
3269 else if (s
->main_pid
!= 0)
3270 log_unit_warning(u
, "Got notification message from PID "PID_FMT
", but reception only permitted for main PID "PID_FMT
, pid
, s
->main_pid
);
3271 else if (s
->control_pid
!= 0)
3272 log_unit_warning(u
, "Got notification message from PID "PID_FMT
", but reception only permitted for control PID "PID_FMT
, pid
, s
->control_pid
);
3274 log_unit_warning(u
, "Got notification message from PID "PID_FMT
", but reception only permitted for main PID and control PID which are currently not known", pid
);
3277 log_unit_debug(u
, "Got notification message from PID "PID_FMT
" (%s)", pid
, isempty(cc
) ? "n/a" : cc
);
3279 /* Interpret MAINPID= */
3280 e
= strv_find_startswith(tags
, "MAINPID=");
3281 if (e
&& IN_SET(s
->state
, SERVICE_START
, SERVICE_START_POST
, SERVICE_RUNNING
, SERVICE_RELOAD
)) {
3282 if (parse_pid(e
, &pid
) < 0)
3283 log_unit_warning(u
, "Failed to parse MAINPID= field in notification message: %s", e
);
3284 else if (pid
== s
->control_pid
)
3285 log_unit_warning(u
, "A control process cannot also be the main process");
3286 else if (pid
== getpid() || pid
== 1)
3287 log_unit_warning(u
, "Service manager can't be main process, ignoring sd_notify() MAINPID= field");
3289 service_set_main_pid(s
, pid
);
3290 unit_watch_pid(UNIT(s
), pid
);
3295 /* Interpret RELOADING= */
3296 if (strv_find(tags
, "RELOADING=1")) {
3298 s
->notify_state
= NOTIFY_RELOADING
;
3300 if (s
->state
== SERVICE_RUNNING
)
3301 service_enter_reload_by_notify(s
);
3306 /* Interpret READY= */
3307 if (strv_find(tags
, "READY=1")) {
3309 s
->notify_state
= NOTIFY_READY
;
3311 /* Type=notify services inform us about completed
3312 * initialization with READY=1 */
3313 if (s
->type
== SERVICE_NOTIFY
&& s
->state
== SERVICE_START
)
3314 service_enter_start_post(s
);
3316 /* Sending READY=1 while we are reloading informs us
3317 * that the reloading is complete */
3318 if (s
->state
== SERVICE_RELOAD
&& s
->control_pid
== 0)
3319 service_enter_running(s
, SERVICE_SUCCESS
);
3324 /* Interpret STOPPING= */
3325 if (strv_find(tags
, "STOPPING=1")) {
3327 s
->notify_state
= NOTIFY_STOPPING
;
3329 if (s
->state
== SERVICE_RUNNING
)
3330 service_enter_stop_by_notify(s
);
3335 /* Interpret STATUS= */
3336 e
= strv_find_startswith(tags
, "STATUS=");
3338 _cleanup_free_
char *t
= NULL
;
3341 if (!utf8_is_valid(e
))
3342 log_unit_warning(u
, "Status message in notification message is not UTF-8 clean.");
3350 if (!streq_ptr(s
->status_text
, t
)) {
3352 free_and_replace(s
->status_text
, t
);
3358 /* Interpret ERRNO= */
3359 e
= strv_find_startswith(tags
, "ERRNO=");
3363 if (safe_atoi(e
, &status_errno
) < 0 || status_errno
< 0)
3364 log_unit_warning(u
, "Failed to parse ERRNO= field in notification message: %s", e
);
3366 if (s
->status_errno
!= status_errno
) {
3367 s
->status_errno
= status_errno
;
3373 /* Interpret WATCHDOG= */
3374 if (strv_find(tags
, "WATCHDOG=1"))
3375 service_reset_watchdog(s
);
3377 if (strv_find(tags
, "FDSTORE=1")) {
3380 name
= strv_find_startswith(tags
, "FDNAME=");
3381 if (name
&& !fdname_is_valid(name
)) {
3382 log_unit_warning(u
, "Passed FDNAME= name is invalid, ignoring.");
3386 service_add_fd_store_set(s
, fds
, name
);
3389 e
= strv_find_startswith(tags
, "WATCHDOG_USEC=");
3391 usec_t watchdog_override_usec
;
3392 if (safe_atou64(e
, &watchdog_override_usec
) < 0)
3393 log_unit_warning(u
, "Failed to parse WATCHDOG_USEC=%s", e
);
3395 service_reset_watchdog_timeout(s
, watchdog_override_usec
);
3398 /* Notify clients about changed status or main pid */
3400 unit_add_to_dbus_queue(u
);
3403 static int service_get_timeout(Unit
*u
, usec_t
*timeout
) {
3404 Service
*s
= SERVICE(u
);
3408 if (!s
->timer_event_source
)
3411 r
= sd_event_source_get_time(s
->timer_event_source
, &t
);
3414 if (t
== USEC_INFINITY
)
3421 static void service_bus_name_owner_change(
3424 const char *old_owner
,
3425 const char *new_owner
) {
3427 Service
*s
= SERVICE(u
);
3433 assert(streq(s
->bus_name
, name
));
3434 assert(old_owner
|| new_owner
);
3436 if (old_owner
&& new_owner
)
3437 log_unit_debug(u
, "D-Bus name %s changed owner from %s to %s", name
, old_owner
, new_owner
);
3439 log_unit_debug(u
, "D-Bus name %s no longer registered by %s", name
, old_owner
);
3441 log_unit_debug(u
, "D-Bus name %s now registered by %s", name
, new_owner
);
3443 s
->bus_name_good
= !!new_owner
;
3445 /* Track the current owner, so we can reconstruct changes after a daemon reload */
3446 r
= free_and_strdup(&s
->bus_name_owner
, new_owner
);
3448 log_unit_error_errno(u
, r
, "Unable to set new bus name owner %s: %m", new_owner
);
3452 if (s
->type
== SERVICE_DBUS
) {
3454 /* service_enter_running() will figure out what to
3456 if (s
->state
== SERVICE_RUNNING
)
3457 service_enter_running(s
, SERVICE_SUCCESS
);
3458 else if (s
->state
== SERVICE_START
&& new_owner
)
3459 service_enter_start_post(s
);
3461 } else if (new_owner
&&
3463 (s
->state
== SERVICE_START
||
3464 s
->state
== SERVICE_START_POST
||
3465 s
->state
== SERVICE_RUNNING
||
3466 s
->state
== SERVICE_RELOAD
)) {
3468 _cleanup_(sd_bus_creds_unrefp
) sd_bus_creds
*creds
= NULL
;
3471 /* Try to acquire PID from bus service */
3473 r
= sd_bus_get_name_creds(u
->manager
->api_bus
, name
, SD_BUS_CREDS_PID
, &creds
);
3475 r
= sd_bus_creds_get_pid(creds
, &pid
);
3477 log_unit_debug(u
, "D-Bus name %s is now owned by process " PID_FMT
, name
, pid
);
3479 service_set_main_pid(s
, pid
);
3480 unit_watch_pid(UNIT(s
), pid
);
3485 int service_set_socket_fd(Service
*s
, int fd
, Socket
*sock
, bool selinux_context_net
) {
3486 _cleanup_free_
char *peer
= NULL
;
3492 /* This is called by the socket code when instantiating a new service for a stream socket and the socket needs
3493 * to be configured. We take ownership of the passed fd on success. */
3495 if (UNIT(s
)->load_state
!= UNIT_LOADED
)
3498 if (s
->socket_fd
>= 0)
3501 if (s
->state
!= SERVICE_DEAD
)
3504 if (getpeername_pretty(fd
, true, &peer
) >= 0) {
3506 if (UNIT(s
)->description
) {
3507 _cleanup_free_
char *a
;
3509 a
= strjoin(UNIT(s
)->description
, " (", peer
, ")");
3513 r
= unit_set_description(UNIT(s
), a
);
3515 r
= unit_set_description(UNIT(s
), peer
);
3521 r
= unit_add_two_dependencies(UNIT(sock
), UNIT_BEFORE
, UNIT_TRIGGERS
, UNIT(s
), false);
3526 s
->socket_fd_selinux_context_net
= selinux_context_net
;
3528 unit_ref_set(&s
->accept_socket
, UNIT(sock
));
3532 static void service_reset_failed(Unit
*u
) {
3533 Service
*s
= SERVICE(u
);
3537 if (s
->state
== SERVICE_FAILED
)
3538 service_set_state(s
, SERVICE_DEAD
);
3540 s
->result
= SERVICE_SUCCESS
;
3541 s
->reload_result
= SERVICE_SUCCESS
;
3544 static int service_kill(Unit
*u
, KillWho who
, int signo
, sd_bus_error
*error
) {
3545 Service
*s
= SERVICE(u
);
3547 return unit_kill_common(u
, who
, signo
, s
->main_pid
, s
->control_pid
, error
);
3550 static int service_main_pid(Unit
*u
) {
3551 Service
*s
= SERVICE(u
);
3558 static int service_control_pid(Unit
*u
) {
3559 Service
*s
= SERVICE(u
);
3563 return s
->control_pid
;
3566 static const char* const service_restart_table
[_SERVICE_RESTART_MAX
] = {
3567 [SERVICE_RESTART_NO
] = "no",
3568 [SERVICE_RESTART_ON_SUCCESS
] = "on-success",
3569 [SERVICE_RESTART_ON_FAILURE
] = "on-failure",
3570 [SERVICE_RESTART_ON_ABNORMAL
] = "on-abnormal",
3571 [SERVICE_RESTART_ON_WATCHDOG
] = "on-watchdog",
3572 [SERVICE_RESTART_ON_ABORT
] = "on-abort",
3573 [SERVICE_RESTART_ALWAYS
] = "always",
3576 DEFINE_STRING_TABLE_LOOKUP(service_restart
, ServiceRestart
);
3578 static const char* const service_type_table
[_SERVICE_TYPE_MAX
] = {
3579 [SERVICE_SIMPLE
] = "simple",
3580 [SERVICE_FORKING
] = "forking",
3581 [SERVICE_ONESHOT
] = "oneshot",
3582 [SERVICE_DBUS
] = "dbus",
3583 [SERVICE_NOTIFY
] = "notify",
3584 [SERVICE_IDLE
] = "idle"
3587 DEFINE_STRING_TABLE_LOOKUP(service_type
, ServiceType
);
3589 static const char* const service_exec_command_table
[_SERVICE_EXEC_COMMAND_MAX
] = {
3590 [SERVICE_EXEC_START_PRE
] = "ExecStartPre",
3591 [SERVICE_EXEC_START
] = "ExecStart",
3592 [SERVICE_EXEC_START_POST
] = "ExecStartPost",
3593 [SERVICE_EXEC_RELOAD
] = "ExecReload",
3594 [SERVICE_EXEC_STOP
] = "ExecStop",
3595 [SERVICE_EXEC_STOP_POST
] = "ExecStopPost",
3598 DEFINE_STRING_TABLE_LOOKUP(service_exec_command
, ServiceExecCommand
);
3600 static const char* const notify_state_table
[_NOTIFY_STATE_MAX
] = {
3601 [NOTIFY_UNKNOWN
] = "unknown",
3602 [NOTIFY_READY
] = "ready",
3603 [NOTIFY_RELOADING
] = "reloading",
3604 [NOTIFY_STOPPING
] = "stopping",
3607 DEFINE_STRING_TABLE_LOOKUP(notify_state
, NotifyState
);
3609 static const char* const service_result_table
[_SERVICE_RESULT_MAX
] = {
3610 [SERVICE_SUCCESS
] = "success",
3611 [SERVICE_FAILURE_RESOURCES
] = "resources",
3612 [SERVICE_FAILURE_PROTOCOL
] = "protocol",
3613 [SERVICE_FAILURE_TIMEOUT
] = "timeout",
3614 [SERVICE_FAILURE_EXIT_CODE
] = "exit-code",
3615 [SERVICE_FAILURE_SIGNAL
] = "signal",
3616 [SERVICE_FAILURE_CORE_DUMP
] = "core-dump",
3617 [SERVICE_FAILURE_WATCHDOG
] = "watchdog",
3618 [SERVICE_FAILURE_START_LIMIT_HIT
] = "start-limit-hit",
3621 DEFINE_STRING_TABLE_LOOKUP(service_result
, ServiceResult
);
3623 const UnitVTable service_vtable
= {
3624 .object_size
= sizeof(Service
),
3625 .exec_context_offset
= offsetof(Service
, exec_context
),
3626 .cgroup_context_offset
= offsetof(Service
, cgroup_context
),
3627 .kill_context_offset
= offsetof(Service
, kill_context
),
3628 .exec_runtime_offset
= offsetof(Service
, exec_runtime
),
3629 .dynamic_creds_offset
= offsetof(Service
, dynamic_creds
),
3635 .private_section
= "Service",
3637 .init
= service_init
,
3638 .done
= service_done
,
3639 .load
= service_load
,
3640 .release_resources
= service_release_resources
,
3642 .coldplug
= service_coldplug
,
3644 .dump
= service_dump
,
3646 .start
= service_start
,
3647 .stop
= service_stop
,
3648 .reload
= service_reload
,
3650 .can_reload
= service_can_reload
,
3652 .kill
= service_kill
,
3654 .serialize
= service_serialize
,
3655 .deserialize_item
= service_deserialize_item
,
3657 .active_state
= service_active_state
,
3658 .sub_state_to_string
= service_sub_state_to_string
,
3660 .check_gc
= service_check_gc
,
3662 .sigchld_event
= service_sigchld_event
,
3664 .reset_failed
= service_reset_failed
,
3666 .notify_cgroup_empty
= service_notify_cgroup_empty_event
,
3667 .notify_message
= service_notify_message
,
3669 .main_pid
= service_main_pid
,
3670 .control_pid
= service_control_pid
,
3672 .bus_name_owner_change
= service_bus_name_owner_change
,
3674 .bus_vtable
= bus_service_vtable
,
3675 .bus_set_property
= bus_service_set_property
,
3676 .bus_commit_properties
= bus_service_commit_properties
,
3678 .get_timeout
= service_get_timeout
,
3679 .can_transient
= true,
3681 .status_message_formats
= {
3682 .starting_stopping
= {
3683 [0] = "Starting %s...",
3684 [1] = "Stopping %s...",
3686 .finished_start_job
= {
3687 [JOB_DONE
] = "Started %s.",
3688 [JOB_FAILED
] = "Failed to start %s.",
3690 .finished_stop_job
= {
3691 [JOB_DONE
] = "Stopped %s.",
3692 [JOB_FAILED
] = "Stopped (with error) %s.",