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
;
46 s
->oom_policy
= _OOM_POLICY_INVALID
;
49 static void scope_done(Unit
*u
) {
54 s
->controller
= mfree(s
->controller
);
55 s
->controller_track
= sd_bus_track_unref(s
->controller_track
);
57 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
59 s
->user
= mfree(s
->user
);
60 s
->group
= mfree(s
->group
);
63 static usec_t
scope_running_timeout(Scope
*s
) {
68 if (s
->runtime_rand_extra_usec
!= 0) {
69 delta
= random_u64_range(s
->runtime_rand_extra_usec
);
70 log_unit_debug(UNIT(s
), "Adding delta of %s sec to timeout", FORMAT_TIMESPAN(delta
, USEC_PER_SEC
));
73 return usec_add(usec_add(UNIT(s
)->active_enter_timestamp
.monotonic
,
78 static int scope_arm_timer(Scope
*s
, usec_t usec
) {
83 if (s
->timer_event_source
) {
84 r
= sd_event_source_set_time(s
->timer_event_source
, usec
);
88 return sd_event_source_set_enabled(s
->timer_event_source
, SD_EVENT_ONESHOT
);
91 if (usec
== USEC_INFINITY
)
94 r
= sd_event_add_time(
95 UNIT(s
)->manager
->event
,
96 &s
->timer_event_source
,
99 scope_dispatch_timer
, s
);
103 (void) sd_event_source_set_description(s
->timer_event_source
, "scope-timer");
108 static void scope_set_state(Scope
*s
, ScopeState state
) {
109 ScopeState old_state
;
112 if (s
->state
!= state
)
113 bus_unit_send_pending_change_signal(UNIT(s
), false);
115 old_state
= s
->state
;
118 if (!IN_SET(state
, SCOPE_STOP_SIGTERM
, SCOPE_STOP_SIGKILL
, SCOPE_START_CHOWN
))
119 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
121 if (IN_SET(state
, SCOPE_DEAD
, SCOPE_FAILED
)) {
122 unit_unwatch_all_pids(UNIT(s
));
123 unit_dequeue_rewatch_pids(UNIT(s
));
126 if (state
!= old_state
)
127 log_debug("%s changed %s -> %s", UNIT(s
)->id
, scope_state_to_string(old_state
), scope_state_to_string(state
));
129 unit_notify(UNIT(s
), state_translation_table
[old_state
], state_translation_table
[state
], 0);
132 static int scope_add_default_dependencies(Scope
*s
) {
137 if (!UNIT(s
)->default_dependencies
)
140 /* Make sure scopes are unloaded on shutdown */
141 r
= unit_add_two_dependencies_by_name(
143 UNIT_BEFORE
, UNIT_CONFLICTS
,
144 SPECIAL_SHUTDOWN_TARGET
, true,
145 UNIT_DEPENDENCY_DEFAULT
);
152 static int scope_verify(Scope
*s
) {
154 assert(UNIT(s
)->load_state
== UNIT_LOADED
);
156 if (set_isempty(UNIT(s
)->pids
) &&
157 !MANAGER_IS_RELOADING(UNIT(s
)->manager
) &&
158 !unit_has_name(UNIT(s
), SPECIAL_INIT_SCOPE
))
159 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOENT
), "Scope has no PIDs. Refusing.");
164 static int scope_load_init_scope(Unit
*u
) {
167 if (!unit_has_name(u
, SPECIAL_INIT_SCOPE
))
173 /* init.scope is a bit special, as it has to stick around forever. Because of its special semantics we
174 * synthesize it here, instead of relying on the unit file on disk. */
176 u
->default_dependencies
= false;
178 /* Prettify things, if we can. */
180 u
->description
= strdup("System and Service Manager");
181 if (!u
->documentation
)
182 (void) strv_extend(&u
->documentation
, "man:systemd(1)");
187 static int scope_add_extras(Scope
*s
) {
190 r
= unit_patch_contexts(UNIT(s
));
194 r
= unit_set_default_slice(UNIT(s
));
198 if (s
->oom_policy
< 0)
199 s
->oom_policy
= s
->cgroup_context
.delegate
? OOM_CONTINUE
: UNIT(s
)->manager
->default_oom_policy
;
201 s
->cgroup_context
.memory_oom_group
= s
->oom_policy
== OOM_KILL
;
203 return scope_add_default_dependencies(s
);
206 static int scope_load(Unit
*u
) {
211 assert(u
->load_state
== UNIT_STUB
);
213 if (!u
->transient
&& !MANAGER_IS_RELOADING(u
->manager
))
214 /* Refuse to load non-transient scope units, but allow them while reloading. */
217 r
= scope_load_init_scope(u
);
221 r
= unit_load_fragment_and_dropin(u
, false);
225 if (u
->load_state
!= UNIT_LOADED
)
228 r
= scope_add_extras(s
);
232 return scope_verify(s
);
235 static usec_t
scope_coldplug_timeout(Scope
*s
) {
238 switch (s
->deserialized_state
) {
241 return scope_running_timeout(s
);
243 case SCOPE_STOP_SIGKILL
:
244 case SCOPE_STOP_SIGTERM
:
245 return usec_add(UNIT(s
)->state_change_timestamp
.monotonic
, s
->timeout_stop_usec
);
248 return USEC_INFINITY
;
252 static int scope_coldplug(Unit
*u
) {
257 assert(s
->state
== SCOPE_DEAD
);
259 if (s
->deserialized_state
== s
->state
)
262 r
= scope_arm_timer(s
, scope_coldplug_timeout(s
));
266 if (!IN_SET(s
->deserialized_state
, SCOPE_DEAD
, SCOPE_FAILED
)) {
270 SET_FOREACH(pidp
, u
->pids
) {
271 r
= unit_watch_pid(u
, PTR_TO_PID(pidp
), false);
272 if (r
< 0 && r
!= -EEXIST
)
276 (void) unit_enqueue_rewatch_pids(u
);
279 bus_scope_track_controller(s
);
281 scope_set_state(s
, s
->deserialized_state
);
285 static void scope_dump(Unit
*u
, FILE *f
, const char *prefix
) {
292 "%sScope State: %s\n"
294 "%sRuntimeMaxSec: %s\n"
295 "%sRuntimeRandomizedExtraSec: %s\n"
297 prefix
, scope_state_to_string(s
->state
),
298 prefix
, scope_result_to_string(s
->result
),
299 prefix
, FORMAT_TIMESPAN(s
->runtime_max_usec
, USEC_PER_SEC
),
300 prefix
, FORMAT_TIMESPAN(s
->runtime_rand_extra_usec
, USEC_PER_SEC
),
301 prefix
, oom_policy_to_string(s
->oom_policy
));
303 cgroup_context_dump(UNIT(s
), f
, prefix
);
304 kill_context_dump(&s
->kill_context
, f
, prefix
);
307 static void scope_enter_dead(Scope
*s
, ScopeResult f
) {
310 if (s
->result
== SCOPE_SUCCESS
)
313 unit_log_result(UNIT(s
), s
->result
== SCOPE_SUCCESS
, scope_result_to_string(s
->result
));
314 scope_set_state(s
, s
->result
!= SCOPE_SUCCESS
? SCOPE_FAILED
: SCOPE_DEAD
);
317 static void scope_enter_signal(Scope
*s
, ScopeState state
, ScopeResult f
) {
318 bool skip_signal
= false;
323 if (s
->result
== SCOPE_SUCCESS
)
326 /* Before sending any signal, make sure we track all members of this cgroup */
327 (void) unit_watch_all_pids(UNIT(s
));
329 /* Also, enqueue a job that we recheck all our PIDs a bit later, given that it's likely some processes have
331 (void) unit_enqueue_rewatch_pids(UNIT(s
));
333 /* If we have a controller set let's ask the controller nicely to terminate the scope, instead of us going
334 * directly into SIGTERM berserk mode */
335 if (state
== SCOPE_STOP_SIGTERM
)
336 skip_signal
= bus_scope_send_request_stop(s
) > 0;
341 r
= unit_kill_context(
344 state
!= SCOPE_STOP_SIGTERM
? KILL_KILL
:
345 s
->was_abandoned
? KILL_TERMINATE_AND_LOG
:
353 r
= scope_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_stop_usec
));
357 scope_set_state(s
, state
);
358 } else if (state
== SCOPE_STOP_SIGTERM
)
359 scope_enter_signal(s
, SCOPE_STOP_SIGKILL
, SCOPE_SUCCESS
);
361 scope_enter_dead(s
, SCOPE_SUCCESS
);
366 log_unit_warning_errno(UNIT(s
), r
, "Failed to kill processes: %m");
368 scope_enter_dead(s
, SCOPE_FAILURE_RESOURCES
);
371 static int scope_enter_start_chown(Scope
*s
) {
379 r
= scope_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), u
->manager
->default_timeout_start_usec
));
383 r
= unit_fork_helper_process(u
, "(sd-chown-cgroup)", &pid
);
388 uid_t uid
= UID_INVALID
;
389 gid_t gid
= GID_INVALID
;
391 if (!isempty(s
->user
)) {
392 const char *user
= s
->user
;
394 r
= get_user_creds(&user
, &uid
, &gid
, NULL
, NULL
, 0);
396 log_unit_error_errno(UNIT(s
), r
, "Failed to resolve user \"%s\": %m", user
);
401 if (!isempty(s
->group
)) {
402 const char *group
= s
->group
;
404 r
= get_group_creds(&group
, &gid
, 0);
406 log_unit_error_errno(UNIT(s
), r
, "Failed to resolve group \"%s\": %m", group
);
411 r
= cg_set_access(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
, uid
, gid
);
413 log_unit_error_errno(UNIT(s
), r
, "Failed to adjust control group access: %m");
420 r
= unit_watch_pid(UNIT(s
), pid
, true);
424 scope_set_state(s
, SCOPE_START_CHOWN
);
428 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
432 static int scope_enter_running(Scope
*s
) {
438 (void) bus_scope_track_controller(s
);
440 r
= unit_acquire_invocation_id(u
);
444 unit_export_state_files(u
);
446 r
= unit_attach_pids_to_cgroup(u
, u
->pids
, NULL
);
448 log_unit_warning_errno(u
, r
, "Failed to add PIDs to scope's control group: %m");
449 scope_enter_dead(s
, SCOPE_FAILURE_RESOURCES
);
453 log_unit_warning(u
, "No PIDs left to attach to the scope's control group, refusing.");
454 scope_enter_dead(s
, SCOPE_FAILURE_RESOURCES
);
457 log_unit_debug(u
, "%i %s added to scope's control group.", r
, r
== 1 ? "process" : "processes");
459 s
->result
= SCOPE_SUCCESS
;
461 scope_set_state(s
, SCOPE_RUNNING
);
463 /* Set the maximum runtime timeout. */
464 scope_arm_timer(s
, scope_running_timeout(s
));
466 /* On unified we use proper notifications hence we can unwatch the PIDs
467 * we just attached to the scope. This can also be done on legacy as
468 * we're going to update the list of the processes we watch with the
469 * PIDs currently in the scope anyway. */
470 unit_unwatch_all_pids(u
);
472 /* Start watching the PIDs currently in the scope (legacy hierarchy only) */
473 (void) unit_enqueue_rewatch_pids(u
);
477 static int scope_start(Unit
*u
) {
482 if (unit_has_name(u
, SPECIAL_INIT_SCOPE
))
485 if (s
->state
== SCOPE_FAILED
)
488 /* We can't fulfill this right now, please try again later */
489 if (IN_SET(s
->state
, SCOPE_STOP_SIGTERM
, SCOPE_STOP_SIGKILL
))
492 assert(s
->state
== SCOPE_DEAD
);
494 if (!u
->transient
&& !MANAGER_IS_RELOADING(u
->manager
))
497 (void) unit_realize_cgroup(u
);
498 (void) unit_reset_accounting(u
);
500 /* We check only for User= option to keep behavior consistent with logic for service units,
501 * i.e. having 'Delegate=true Group=foo' w/o specifying User= has no effect. */
502 if (s
->user
&& unit_cgroup_delegate(u
))
503 return scope_enter_start_chown(s
);
505 return scope_enter_running(s
);
508 static int scope_stop(Unit
*u
) {
513 if (IN_SET(s
->state
, SCOPE_STOP_SIGTERM
, SCOPE_STOP_SIGKILL
))
516 assert(IN_SET(s
->state
, SCOPE_RUNNING
, SCOPE_ABANDONED
));
518 scope_enter_signal(s
, SCOPE_STOP_SIGTERM
, SCOPE_SUCCESS
);
522 static void scope_reset_failed(Unit
*u
) {
527 if (s
->state
== SCOPE_FAILED
)
528 scope_set_state(s
, SCOPE_DEAD
);
530 s
->result
= SCOPE_SUCCESS
;
533 static int scope_kill(Unit
*u
, KillWho who
, int signo
, int code
, int value
, sd_bus_error
*error
) {
534 return unit_kill_common(u
, who
, signo
, code
, value
, -1, -1, error
);
537 static int scope_get_timeout(Unit
*u
, usec_t
*timeout
) {
542 if (!s
->timer_event_source
)
545 r
= sd_event_source_get_time(s
->timer_event_source
, &t
);
548 if (t
== USEC_INFINITY
)
555 static int scope_serialize(Unit
*u
, FILE *f
, FDSet
*fds
) {
563 (void) serialize_item(f
, "state", scope_state_to_string(s
->state
));
564 (void) serialize_bool(f
, "was-abandoned", s
->was_abandoned
);
567 (void) serialize_item(f
, "controller", s
->controller
);
569 SET_FOREACH(pidp
, u
->pids
)
570 serialize_item_format(f
, "pids", PID_FMT
, PTR_TO_PID(pidp
));
575 static int scope_deserialize_item(Unit
*u
, const char *key
, const char *value
, FDSet
*fds
) {
584 if (streq(key
, "state")) {
587 state
= scope_state_from_string(value
);
589 log_unit_debug(u
, "Failed to parse state value: %s", value
);
591 s
->deserialized_state
= state
;
593 } else if (streq(key
, "was-abandoned")) {
596 k
= parse_boolean(value
);
598 log_unit_debug(u
, "Failed to parse boolean value: %s", value
);
600 s
->was_abandoned
= k
;
601 } else if (streq(key
, "controller")) {
603 r
= free_and_strdup(&s
->controller
, value
);
607 } else if (streq(key
, "pids")) {
610 if (parse_pid(value
, &pid
) < 0)
611 log_unit_debug(u
, "Failed to parse pids value: %s", value
);
613 r
= set_ensure_put(&u
->pids
, NULL
, PID_TO_PTR(pid
));
618 log_unit_debug(u
, "Unknown serialization key: %s", key
);
623 static void scope_notify_cgroup_empty_event(Unit
*u
) {
627 log_unit_debug(u
, "cgroup is empty");
629 if (IN_SET(s
->state
, SCOPE_RUNNING
, SCOPE_ABANDONED
, SCOPE_STOP_SIGTERM
, SCOPE_STOP_SIGKILL
))
630 scope_enter_dead(s
, SCOPE_SUCCESS
);
632 /* If the cgroup empty notification comes when the unit is not active, we must have failed to clean
633 * up the cgroup earlier and should do it now. */
634 if (IN_SET(s
->state
, SCOPE_DEAD
, SCOPE_FAILED
))
635 unit_prune_cgroup(u
);
638 static void scope_notify_cgroup_oom_event(Unit
*u
, bool managed_oom
) {
642 log_unit_debug(u
, "Process(es) of control group were killed by systemd-oomd.");
644 log_unit_debug(u
, "Process of control group was killed by the OOM killer.");
646 if (s
->oom_policy
== OOM_CONTINUE
)
651 case SCOPE_START_CHOWN
:
653 scope_enter_signal(s
, SCOPE_STOP_SIGTERM
, SCOPE_FAILURE_OOM_KILL
);
656 case SCOPE_STOP_SIGTERM
:
657 scope_enter_signal(s
, SCOPE_STOP_SIGKILL
, SCOPE_FAILURE_OOM_KILL
);
660 case SCOPE_STOP_SIGKILL
:
661 if (s
->result
== SCOPE_SUCCESS
)
662 s
->result
= SCOPE_FAILURE_OOM_KILL
;
664 /* SCOPE_DEAD, SCOPE_ABANDONED, and SCOPE_FAILED end up in default */
670 static void scope_sigchld_event(Unit
*u
, pid_t pid
, int code
, int status
) {
675 if (s
->state
== SCOPE_START_CHOWN
) {
676 if (!is_clean_exit(code
, status
, EXIT_CLEAN_COMMAND
, NULL
))
677 scope_enter_dead(s
, SCOPE_FAILURE_RESOURCES
);
679 scope_enter_running(s
);
683 /* If we get a SIGCHLD event for one of the processes we were interested in, then we look for others to
684 * watch, under the assumption that we'll sooner or later get a SIGCHLD for them, as the original
685 * process we watched was probably the parent of them, and they are hence now our children. */
687 (void) unit_enqueue_rewatch_pids(u
);
690 static int scope_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
) {
691 Scope
*s
= SCOPE(userdata
);
694 assert(s
->timer_event_source
== source
);
699 log_unit_warning(UNIT(s
), "Scope reached runtime time limit. Stopping.");
700 scope_enter_signal(s
, SCOPE_STOP_SIGTERM
, SCOPE_FAILURE_TIMEOUT
);
703 case SCOPE_STOP_SIGTERM
:
704 if (s
->kill_context
.send_sigkill
) {
705 log_unit_warning(UNIT(s
), "Stopping timed out. Killing.");
706 scope_enter_signal(s
, SCOPE_STOP_SIGKILL
, SCOPE_FAILURE_TIMEOUT
);
708 log_unit_warning(UNIT(s
), "Stopping timed out. Skipping SIGKILL.");
709 scope_enter_dead(s
, SCOPE_FAILURE_TIMEOUT
);
714 case SCOPE_STOP_SIGKILL
:
715 log_unit_warning(UNIT(s
), "Still around after SIGKILL. Ignoring.");
716 scope_enter_dead(s
, SCOPE_FAILURE_TIMEOUT
);
719 case SCOPE_START_CHOWN
:
720 log_unit_warning(UNIT(s
), "User lookup timed out. Entering failed state.");
721 scope_enter_dead(s
, SCOPE_FAILURE_TIMEOUT
);
725 assert_not_reached();
731 int scope_abandon(Scope
*s
) {
734 if (unit_has_name(UNIT(s
), SPECIAL_INIT_SCOPE
))
737 if (!IN_SET(s
->state
, SCOPE_RUNNING
, SCOPE_ABANDONED
))
740 s
->was_abandoned
= true;
742 s
->controller
= mfree(s
->controller
);
743 s
->controller_track
= sd_bus_track_unref(s
->controller_track
);
745 scope_set_state(s
, SCOPE_ABANDONED
);
747 /* The client is no longer watching the remaining processes, so let's step in here, under the assumption that
748 * the remaining processes will be sooner or later reassigned to us as parent. */
749 (void) unit_enqueue_rewatch_pids(UNIT(s
));
754 _pure_
static UnitActiveState
scope_active_state(Unit
*u
) {
757 return state_translation_table
[SCOPE(u
)->state
];
760 _pure_
static const char *scope_sub_state_to_string(Unit
*u
) {
763 return scope_state_to_string(SCOPE(u
)->state
);
766 static void scope_enumerate_perpetual(Manager
*m
) {
772 /* Let's unconditionally add the "init.scope" special unit
773 * that encapsulates PID 1. Note that PID 1 already is in the
774 * cgroup for this, we hence just need to allocate the object
775 * for it and that's it. */
777 u
= manager_get_unit(m
, SPECIAL_INIT_SCOPE
);
779 r
= unit_new_for_name(m
, sizeof(Scope
), SPECIAL_INIT_SCOPE
, &u
);
781 log_error_errno(r
, "Failed to allocate the special " SPECIAL_INIT_SCOPE
" unit: %m");
788 SCOPE(u
)->deserialized_state
= SCOPE_RUNNING
;
790 unit_add_to_load_queue(u
);
791 unit_add_to_dbus_queue(u
);
792 /* Enqueue an explicit cgroup realization here. Unlike other cgroups this one already exists and is
793 * populated (by us, after all!) already, even when we are not in a reload cycle. Hence we cannot
794 * apply the settings at creation time anymore, but let's at least apply them asynchronously. */
795 unit_add_to_cgroup_realize_queue(u
);
798 static const char* const scope_result_table
[_SCOPE_RESULT_MAX
] = {
799 [SCOPE_SUCCESS
] = "success",
800 [SCOPE_FAILURE_RESOURCES
] = "resources",
801 [SCOPE_FAILURE_TIMEOUT
] = "timeout",
802 [SCOPE_FAILURE_OOM_KILL
] = "oom-kill",
805 DEFINE_STRING_TABLE_LOOKUP(scope_result
, ScopeResult
);
807 const UnitVTable scope_vtable
= {
808 .object_size
= sizeof(Scope
),
809 .cgroup_context_offset
= offsetof(Scope
, cgroup_context
),
810 .kill_context_offset
= offsetof(Scope
, kill_context
),
816 .private_section
= "Scope",
818 .can_transient
= true,
819 .can_delegate
= true,
822 .can_set_managed_oom
= true,
828 .coldplug
= scope_coldplug
,
832 .start
= scope_start
,
837 .freeze
= unit_freeze_vtable_common
,
838 .thaw
= unit_thaw_vtable_common
,
840 .get_timeout
= scope_get_timeout
,
842 .serialize
= scope_serialize
,
843 .deserialize_item
= scope_deserialize_item
,
845 .active_state
= scope_active_state
,
846 .sub_state_to_string
= scope_sub_state_to_string
,
848 .sigchld_event
= scope_sigchld_event
,
850 .reset_failed
= scope_reset_failed
,
852 .notify_cgroup_empty
= scope_notify_cgroup_empty_event
,
853 .notify_cgroup_oom
= scope_notify_cgroup_oom_event
,
855 .bus_set_property
= bus_scope_set_property
,
856 .bus_commit_properties
= bus_scope_commit_properties
,
858 .enumerate_perpetual
= scope_enumerate_perpetual
,