1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
6 #include "alloc-util.h"
7 #include "dbus-scope.h"
9 #include "exit-status.h"
10 #include "load-dropin.h"
12 #include "process-util.h"
13 #include "random-util.h"
15 #include "serialize.h"
17 #include "string-table.h"
18 #include "string-util.h"
20 #include "unit-name.h"
22 #include "user-util.h"
24 static const UnitActiveState state_translation_table
[_SCOPE_STATE_MAX
] = {
25 [SCOPE_DEAD
] = UNIT_INACTIVE
,
26 [SCOPE_START_CHOWN
] = UNIT_ACTIVATING
,
27 [SCOPE_RUNNING
] = UNIT_ACTIVE
,
28 [SCOPE_ABANDONED
] = UNIT_ACTIVE
,
29 [SCOPE_STOP_SIGTERM
] = UNIT_DEACTIVATING
,
30 [SCOPE_STOP_SIGKILL
] = UNIT_DEACTIVATING
,
31 [SCOPE_FAILED
] = UNIT_FAILED
34 static int scope_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
);
36 static void scope_init(Unit
*u
) {
40 assert(u
->load_state
== UNIT_STUB
);
42 s
->runtime_max_usec
= USEC_INFINITY
;
43 s
->timeout_stop_usec
= u
->manager
->default_timeout_stop_usec
;
44 u
->ignore_on_isolate
= true;
45 s
->user
= s
->group
= NULL
;
48 static void scope_done(Unit
*u
) {
53 s
->controller
= mfree(s
->controller
);
54 s
->controller_track
= sd_bus_track_unref(s
->controller_track
);
56 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
58 s
->user
= mfree(s
->user
);
59 s
->group
= mfree(s
->group
);
62 static usec_t
scope_running_timeout(Scope
*s
) {
67 if (s
->runtime_rand_extra_usec
!= 0) {
68 delta
= random_u64_range(s
->runtime_rand_extra_usec
);
69 log_unit_debug(UNIT(s
), "Adding delta of %s sec to timeout", FORMAT_TIMESPAN(delta
, USEC_PER_SEC
));
72 return usec_add(usec_add(UNIT(s
)->active_enter_timestamp
.monotonic
,
77 static int scope_arm_timer(Scope
*s
, usec_t usec
) {
82 if (s
->timer_event_source
) {
83 r
= sd_event_source_set_time(s
->timer_event_source
, usec
);
87 return sd_event_source_set_enabled(s
->timer_event_source
, SD_EVENT_ONESHOT
);
90 if (usec
== USEC_INFINITY
)
93 r
= sd_event_add_time(
94 UNIT(s
)->manager
->event
,
95 &s
->timer_event_source
,
98 scope_dispatch_timer
, s
);
102 (void) sd_event_source_set_description(s
->timer_event_source
, "scope-timer");
107 static void scope_set_state(Scope
*s
, ScopeState state
) {
108 ScopeState old_state
;
111 if (s
->state
!= state
)
112 bus_unit_send_pending_change_signal(UNIT(s
), false);
114 old_state
= s
->state
;
117 if (!IN_SET(state
, SCOPE_STOP_SIGTERM
, SCOPE_STOP_SIGKILL
, SCOPE_START_CHOWN
))
118 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
120 if (IN_SET(state
, SCOPE_DEAD
, SCOPE_FAILED
)) {
121 unit_unwatch_all_pids(UNIT(s
));
122 unit_dequeue_rewatch_pids(UNIT(s
));
125 if (state
!= old_state
)
126 log_debug("%s changed %s -> %s", UNIT(s
)->id
, scope_state_to_string(old_state
), scope_state_to_string(state
));
128 unit_notify(UNIT(s
), state_translation_table
[old_state
], state_translation_table
[state
], 0);
131 static int scope_add_default_dependencies(Scope
*s
) {
136 if (!UNIT(s
)->default_dependencies
)
139 /* Make sure scopes are unloaded on shutdown */
140 r
= unit_add_two_dependencies_by_name(
142 UNIT_BEFORE
, UNIT_CONFLICTS
,
143 SPECIAL_SHUTDOWN_TARGET
, true,
144 UNIT_DEPENDENCY_DEFAULT
);
151 static int scope_verify(Scope
*s
) {
153 assert(UNIT(s
)->load_state
== UNIT_LOADED
);
155 if (set_isempty(UNIT(s
)->pids
) &&
156 !MANAGER_IS_RELOADING(UNIT(s
)->manager
) &&
157 !unit_has_name(UNIT(s
), SPECIAL_INIT_SCOPE
))
158 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOENT
), "Scope has no PIDs. Refusing.");
163 static int scope_load_init_scope(Unit
*u
) {
166 if (!unit_has_name(u
, SPECIAL_INIT_SCOPE
))
172 /* init.scope is a bit special, as it has to stick around forever. Because of its special semantics we
173 * synthesize it here, instead of relying on the unit file on disk. */
175 u
->default_dependencies
= false;
177 /* Prettify things, if we can. */
179 u
->description
= strdup("System and Service Manager");
180 if (!u
->documentation
)
181 (void) strv_extend(&u
->documentation
, "man:systemd(1)");
186 static int scope_add_extras(Scope
*s
) {
189 r
= unit_patch_contexts(UNIT(s
));
193 r
= unit_set_default_slice(UNIT(s
));
197 return scope_add_default_dependencies(s
);
200 static int scope_load(Unit
*u
) {
205 assert(u
->load_state
== UNIT_STUB
);
207 if (!u
->transient
&& !MANAGER_IS_RELOADING(u
->manager
))
208 /* Refuse to load non-transient scope units, but allow them while reloading. */
211 r
= scope_load_init_scope(u
);
215 r
= unit_load_fragment_and_dropin(u
, false);
219 if (u
->load_state
!= UNIT_LOADED
)
222 r
= scope_add_extras(s
);
226 return scope_verify(s
);
229 static usec_t
scope_coldplug_timeout(Scope
*s
) {
232 switch (s
->deserialized_state
) {
235 return scope_running_timeout(s
);
237 case SCOPE_STOP_SIGKILL
:
238 case SCOPE_STOP_SIGTERM
:
239 return usec_add(UNIT(s
)->state_change_timestamp
.monotonic
, s
->timeout_stop_usec
);
242 return USEC_INFINITY
;
246 static int scope_coldplug(Unit
*u
) {
251 assert(s
->state
== SCOPE_DEAD
);
253 if (s
->deserialized_state
== s
->state
)
256 r
= scope_arm_timer(s
, scope_coldplug_timeout(s
));
260 if (!IN_SET(s
->deserialized_state
, SCOPE_DEAD
, SCOPE_FAILED
)) {
264 SET_FOREACH(pidp
, u
->pids
) {
265 r
= unit_watch_pid(u
, PTR_TO_PID(pidp
), false);
266 if (r
< 0 && r
!= -EEXIST
)
270 (void) unit_enqueue_rewatch_pids(u
);
273 bus_scope_track_controller(s
);
275 scope_set_state(s
, s
->deserialized_state
);
279 static void scope_dump(Unit
*u
, FILE *f
, const char *prefix
) {
286 "%sScope State: %s\n"
288 "%sRuntimeMaxSec: %s\n"
289 "%sRuntimeRandomizedExtraSec: %s\n",
290 prefix
, scope_state_to_string(s
->state
),
291 prefix
, scope_result_to_string(s
->result
),
292 prefix
, FORMAT_TIMESPAN(s
->runtime_max_usec
, USEC_PER_SEC
),
293 prefix
, FORMAT_TIMESPAN(s
->runtime_rand_extra_usec
, USEC_PER_SEC
));
295 cgroup_context_dump(UNIT(s
), f
, prefix
);
296 kill_context_dump(&s
->kill_context
, f
, prefix
);
299 static void scope_enter_dead(Scope
*s
, ScopeResult f
) {
302 if (s
->result
== SCOPE_SUCCESS
)
305 unit_log_result(UNIT(s
), s
->result
== SCOPE_SUCCESS
, scope_result_to_string(s
->result
));
306 scope_set_state(s
, s
->result
!= SCOPE_SUCCESS
? SCOPE_FAILED
: SCOPE_DEAD
);
309 static void scope_enter_signal(Scope
*s
, ScopeState state
, ScopeResult f
) {
310 bool skip_signal
= false;
315 if (s
->result
== SCOPE_SUCCESS
)
318 /* Before sending any signal, make sure we track all members of this cgroup */
319 (void) unit_watch_all_pids(UNIT(s
));
321 /* Also, enqueue a job that we recheck all our PIDs a bit later, given that it's likely some processes have
323 (void) unit_enqueue_rewatch_pids(UNIT(s
));
325 /* If we have a controller set let's ask the controller nicely to terminate the scope, instead of us going
326 * directly into SIGTERM berserk mode */
327 if (state
== SCOPE_STOP_SIGTERM
)
328 skip_signal
= bus_scope_send_request_stop(s
) > 0;
333 r
= unit_kill_context(
336 state
!= SCOPE_STOP_SIGTERM
? KILL_KILL
:
337 s
->was_abandoned
? KILL_TERMINATE_AND_LOG
:
345 r
= scope_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_stop_usec
));
349 scope_set_state(s
, state
);
350 } else if (state
== SCOPE_STOP_SIGTERM
)
351 scope_enter_signal(s
, SCOPE_STOP_SIGKILL
, SCOPE_SUCCESS
);
353 scope_enter_dead(s
, SCOPE_SUCCESS
);
358 log_unit_warning_errno(UNIT(s
), r
, "Failed to kill processes: %m");
360 scope_enter_dead(s
, SCOPE_FAILURE_RESOURCES
);
363 static int scope_enter_start_chown(Scope
*s
) {
371 r
= scope_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), u
->manager
->default_timeout_start_usec
));
375 r
= unit_fork_helper_process(u
, "(sd-chown-cgroup)", &pid
);
380 uid_t uid
= UID_INVALID
;
381 gid_t gid
= GID_INVALID
;
383 if (!isempty(s
->user
)) {
384 const char *user
= s
->user
;
386 r
= get_user_creds(&user
, &uid
, &gid
, NULL
, NULL
, 0);
388 log_unit_error_errno(UNIT(s
), r
, "Failed to resolve user \"%s\": %m", user
);
393 if (!isempty(s
->group
)) {
394 const char *group
= s
->group
;
396 r
= get_group_creds(&group
, &gid
, 0);
398 log_unit_error_errno(UNIT(s
), r
, "Failed to resolve group \"%s\": %m", group
);
403 r
= cg_set_access(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
, uid
, gid
);
405 log_unit_error_errno(UNIT(s
), r
, "Failed to adjust control group access: %m");
412 r
= unit_watch_pid(UNIT(s
), pid
, true);
416 scope_set_state(s
, SCOPE_START_CHOWN
);
420 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
424 static int scope_enter_running(Scope
*s
) {
430 (void) bus_scope_track_controller(s
);
432 r
= unit_acquire_invocation_id(u
);
436 unit_export_state_files(u
);
438 r
= unit_attach_pids_to_cgroup(u
, u
->pids
, NULL
);
440 log_unit_warning_errno(u
, r
, "Failed to add PIDs to scope's control group: %m");
441 scope_enter_dead(s
, SCOPE_FAILURE_RESOURCES
);
445 log_unit_warning(u
, "No PIDs left to attach to the scope's control group, refusing.");
446 scope_enter_dead(s
, SCOPE_FAILURE_RESOURCES
);
449 log_unit_debug(u
, "%i %s added to scope's control group.", r
, r
== 1 ? "process" : "processes");
451 s
->result
= SCOPE_SUCCESS
;
453 scope_set_state(s
, SCOPE_RUNNING
);
455 /* Set the maximum runtime timeout. */
456 scope_arm_timer(s
, scope_running_timeout(s
));
458 /* On unified we use proper notifications hence we can unwatch the PIDs
459 * we just attached to the scope. This can also be done on legacy as
460 * we're going to update the list of the processes we watch with the
461 * PIDs currently in the scope anyway. */
462 unit_unwatch_all_pids(u
);
464 /* Start watching the PIDs currently in the scope (legacy hierarchy only) */
465 (void) unit_enqueue_rewatch_pids(u
);
469 static int scope_start(Unit
*u
) {
474 if (unit_has_name(u
, SPECIAL_INIT_SCOPE
))
477 if (s
->state
== SCOPE_FAILED
)
480 /* We can't fulfill this right now, please try again later */
481 if (IN_SET(s
->state
, SCOPE_STOP_SIGTERM
, SCOPE_STOP_SIGKILL
))
484 assert(s
->state
== SCOPE_DEAD
);
486 if (!u
->transient
&& !MANAGER_IS_RELOADING(u
->manager
))
489 (void) unit_realize_cgroup(u
);
490 (void) unit_reset_accounting(u
);
492 /* We check only for User= option to keep behavior consistent with logic for service units,
493 * i.e. having 'Delegate=true Group=foo' w/o specifing User= has no effect. */
494 if (s
->user
&& unit_cgroup_delegate(u
))
495 return scope_enter_start_chown(s
);
497 return scope_enter_running(s
);
500 static int scope_stop(Unit
*u
) {
505 if (IN_SET(s
->state
, SCOPE_STOP_SIGTERM
, SCOPE_STOP_SIGKILL
))
508 assert(IN_SET(s
->state
, SCOPE_RUNNING
, SCOPE_ABANDONED
));
510 scope_enter_signal(s
, SCOPE_STOP_SIGTERM
, SCOPE_SUCCESS
);
514 static void scope_reset_failed(Unit
*u
) {
519 if (s
->state
== SCOPE_FAILED
)
520 scope_set_state(s
, SCOPE_DEAD
);
522 s
->result
= SCOPE_SUCCESS
;
525 static int scope_kill(Unit
*u
, KillWho who
, int signo
, sd_bus_error
*error
) {
526 return unit_kill_common(u
, who
, signo
, -1, -1, error
);
529 static int scope_get_timeout(Unit
*u
, usec_t
*timeout
) {
534 if (!s
->timer_event_source
)
537 r
= sd_event_source_get_time(s
->timer_event_source
, &t
);
540 if (t
== USEC_INFINITY
)
547 static int scope_serialize(Unit
*u
, FILE *f
, FDSet
*fds
) {
555 (void) serialize_item(f
, "state", scope_state_to_string(s
->state
));
556 (void) serialize_bool(f
, "was-abandoned", s
->was_abandoned
);
559 (void) serialize_item(f
, "controller", s
->controller
);
561 SET_FOREACH(pidp
, u
->pids
)
562 serialize_item_format(f
, "pids", PID_FMT
, PTR_TO_PID(pidp
));
567 static int scope_deserialize_item(Unit
*u
, const char *key
, const char *value
, FDSet
*fds
) {
576 if (streq(key
, "state")) {
579 state
= scope_state_from_string(value
);
581 log_unit_debug(u
, "Failed to parse state value: %s", value
);
583 s
->deserialized_state
= state
;
585 } else if (streq(key
, "was-abandoned")) {
588 k
= parse_boolean(value
);
590 log_unit_debug(u
, "Failed to parse boolean value: %s", value
);
592 s
->was_abandoned
= k
;
593 } else if (streq(key
, "controller")) {
595 r
= free_and_strdup(&s
->controller
, value
);
599 } else if (streq(key
, "pids")) {
602 if (parse_pid(value
, &pid
) < 0)
603 log_unit_debug(u
, "Failed to parse pids value: %s", value
);
605 r
= set_ensure_put(&u
->pids
, NULL
, PID_TO_PTR(pid
));
610 log_unit_debug(u
, "Unknown serialization key: %s", key
);
615 static void scope_notify_cgroup_empty_event(Unit
*u
) {
619 log_unit_debug(u
, "cgroup is empty");
621 if (IN_SET(s
->state
, SCOPE_RUNNING
, SCOPE_ABANDONED
, SCOPE_STOP_SIGTERM
, SCOPE_STOP_SIGKILL
))
622 scope_enter_dead(s
, SCOPE_SUCCESS
);
624 /* If the cgroup empty notification comes when the unit is not active, we must have failed to clean
625 * up the cgroup earlier and should do it now. */
626 if (IN_SET(s
->state
, SCOPE_DEAD
, SCOPE_FAILED
))
627 unit_prune_cgroup(u
);
630 static void scope_sigchld_event(Unit
*u
, pid_t pid
, int code
, int status
) {
635 if (s
->state
== SCOPE_START_CHOWN
) {
636 if (!is_clean_exit(code
, status
, EXIT_CLEAN_COMMAND
, NULL
))
637 scope_enter_dead(s
, SCOPE_FAILURE_RESOURCES
);
639 scope_enter_running(s
);
643 /* If we get a SIGCHLD event for one of the processes we were interested in, then we look for others to
644 * watch, under the assumption that we'll sooner or later get a SIGCHLD for them, as the original
645 * process we watched was probably the parent of them, and they are hence now our children. */
647 (void) unit_enqueue_rewatch_pids(u
);
650 static int scope_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
) {
651 Scope
*s
= SCOPE(userdata
);
654 assert(s
->timer_event_source
== source
);
659 log_unit_warning(UNIT(s
), "Scope reached runtime time limit. Stopping.");
660 scope_enter_signal(s
, SCOPE_STOP_SIGTERM
, SCOPE_FAILURE_TIMEOUT
);
663 case SCOPE_STOP_SIGTERM
:
664 if (s
->kill_context
.send_sigkill
) {
665 log_unit_warning(UNIT(s
), "Stopping timed out. Killing.");
666 scope_enter_signal(s
, SCOPE_STOP_SIGKILL
, SCOPE_FAILURE_TIMEOUT
);
668 log_unit_warning(UNIT(s
), "Stopping timed out. Skipping SIGKILL.");
669 scope_enter_dead(s
, SCOPE_FAILURE_TIMEOUT
);
674 case SCOPE_STOP_SIGKILL
:
675 log_unit_warning(UNIT(s
), "Still around after SIGKILL. Ignoring.");
676 scope_enter_dead(s
, SCOPE_FAILURE_TIMEOUT
);
679 case SCOPE_START_CHOWN
:
680 log_unit_warning(UNIT(s
), "User lookup timed out. Entering failed state.");
681 scope_enter_dead(s
, SCOPE_FAILURE_TIMEOUT
);
685 assert_not_reached();
691 int scope_abandon(Scope
*s
) {
694 if (unit_has_name(UNIT(s
), SPECIAL_INIT_SCOPE
))
697 if (!IN_SET(s
->state
, SCOPE_RUNNING
, SCOPE_ABANDONED
))
700 s
->was_abandoned
= true;
702 s
->controller
= mfree(s
->controller
);
703 s
->controller_track
= sd_bus_track_unref(s
->controller_track
);
705 scope_set_state(s
, SCOPE_ABANDONED
);
707 /* The client is no longer watching the remaining processes, so let's step in here, under the assumption that
708 * the remaining processes will be sooner or later reassigned to us as parent. */
709 (void) unit_enqueue_rewatch_pids(UNIT(s
));
714 _pure_
static UnitActiveState
scope_active_state(Unit
*u
) {
717 return state_translation_table
[SCOPE(u
)->state
];
720 _pure_
static const char *scope_sub_state_to_string(Unit
*u
) {
723 return scope_state_to_string(SCOPE(u
)->state
);
726 static void scope_enumerate_perpetual(Manager
*m
) {
732 /* Let's unconditionally add the "init.scope" special unit
733 * that encapsulates PID 1. Note that PID 1 already is in the
734 * cgroup for this, we hence just need to allocate the object
735 * for it and that's it. */
737 u
= manager_get_unit(m
, SPECIAL_INIT_SCOPE
);
739 r
= unit_new_for_name(m
, sizeof(Scope
), SPECIAL_INIT_SCOPE
, &u
);
741 log_error_errno(r
, "Failed to allocate the special " SPECIAL_INIT_SCOPE
" unit: %m");
748 SCOPE(u
)->deserialized_state
= SCOPE_RUNNING
;
750 unit_add_to_load_queue(u
);
751 unit_add_to_dbus_queue(u
);
754 static const char* const scope_result_table
[_SCOPE_RESULT_MAX
] = {
755 [SCOPE_SUCCESS
] = "success",
756 [SCOPE_FAILURE_RESOURCES
] = "resources",
757 [SCOPE_FAILURE_TIMEOUT
] = "timeout",
760 DEFINE_STRING_TABLE_LOOKUP(scope_result
, ScopeResult
);
762 const UnitVTable scope_vtable
= {
763 .object_size
= sizeof(Scope
),
764 .cgroup_context_offset
= offsetof(Scope
, cgroup_context
),
765 .kill_context_offset
= offsetof(Scope
, kill_context
),
771 .private_section
= "Scope",
773 .can_transient
= true,
774 .can_delegate
= true,
777 .can_set_managed_oom
= true,
783 .coldplug
= scope_coldplug
,
787 .start
= scope_start
,
792 .freeze
= unit_freeze_vtable_common
,
793 .thaw
= unit_thaw_vtable_common
,
795 .get_timeout
= scope_get_timeout
,
797 .serialize
= scope_serialize
,
798 .deserialize_item
= scope_deserialize_item
,
800 .active_state
= scope_active_state
,
801 .sub_state_to_string
= scope_sub_state_to_string
,
803 .sigchld_event
= scope_sigchld_event
,
805 .reset_failed
= scope_reset_failed
,
807 .notify_cgroup_empty
= scope_notify_cgroup_empty_event
,
809 .bus_set_property
= bus_scope_set_property
,
810 .bus_commit_properties
= bus_scope_commit_properties
,
812 .enumerate_perpetual
= scope_enumerate_perpetual
,