1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
6 #include "alloc-util.h"
7 #include "cgroup-setup.h"
8 #include "dbus-scope.h"
10 #include "exit-status.h"
11 #include "load-dropin.h"
13 #include "process-util.h"
14 #include "random-util.h"
16 #include "serialize.h"
18 #include "string-table.h"
19 #include "string-util.h"
21 #include "unit-name.h"
23 #include "user-util.h"
25 static const UnitActiveState state_translation_table
[_SCOPE_STATE_MAX
] = {
26 [SCOPE_DEAD
] = UNIT_INACTIVE
,
27 [SCOPE_START_CHOWN
] = UNIT_ACTIVATING
,
28 [SCOPE_RUNNING
] = UNIT_ACTIVE
,
29 [SCOPE_ABANDONED
] = UNIT_ACTIVE
,
30 [SCOPE_STOP_SIGTERM
] = UNIT_DEACTIVATING
,
31 [SCOPE_STOP_SIGKILL
] = UNIT_DEACTIVATING
,
32 [SCOPE_FAILED
] = UNIT_FAILED
35 static int scope_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
);
37 static void scope_init(Unit
*u
) {
41 assert(u
->load_state
== UNIT_STUB
);
43 s
->runtime_max_usec
= USEC_INFINITY
;
44 s
->timeout_stop_usec
= u
->manager
->default_timeout_stop_usec
;
45 u
->ignore_on_isolate
= true;
46 s
->user
= s
->group
= NULL
;
47 s
->oom_policy
= _OOM_POLICY_INVALID
;
50 static void scope_done(Unit
*u
) {
55 s
->controller
= mfree(s
->controller
);
56 s
->controller_track
= sd_bus_track_unref(s
->controller_track
);
58 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
60 s
->user
= mfree(s
->user
);
61 s
->group
= mfree(s
->group
);
64 static usec_t
scope_running_timeout(Scope
*s
) {
69 if (s
->runtime_rand_extra_usec
!= 0) {
70 delta
= random_u64_range(s
->runtime_rand_extra_usec
);
71 log_unit_debug(UNIT(s
), "Adding delta of %s sec to timeout", FORMAT_TIMESPAN(delta
, USEC_PER_SEC
));
74 return usec_add(usec_add(UNIT(s
)->active_enter_timestamp
.monotonic
,
79 static int scope_arm_timer(Scope
*s
, usec_t usec
) {
84 if (s
->timer_event_source
) {
85 r
= sd_event_source_set_time(s
->timer_event_source
, usec
);
89 return sd_event_source_set_enabled(s
->timer_event_source
, SD_EVENT_ONESHOT
);
92 if (usec
== USEC_INFINITY
)
95 r
= sd_event_add_time(
96 UNIT(s
)->manager
->event
,
97 &s
->timer_event_source
,
100 scope_dispatch_timer
, s
);
104 (void) sd_event_source_set_description(s
->timer_event_source
, "scope-timer");
109 static void scope_set_state(Scope
*s
, ScopeState state
) {
110 ScopeState old_state
;
113 if (s
->state
!= state
)
114 bus_unit_send_pending_change_signal(UNIT(s
), false);
116 old_state
= s
->state
;
119 if (!IN_SET(state
, SCOPE_STOP_SIGTERM
, SCOPE_STOP_SIGKILL
, SCOPE_START_CHOWN
, SCOPE_RUNNING
))
120 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
122 if (IN_SET(state
, SCOPE_DEAD
, SCOPE_FAILED
)) {
123 unit_unwatch_all_pids(UNIT(s
));
124 unit_dequeue_rewatch_pids(UNIT(s
));
127 if (state
!= old_state
)
128 log_debug("%s changed %s -> %s", UNIT(s
)->id
, scope_state_to_string(old_state
), scope_state_to_string(state
));
130 unit_notify(UNIT(s
), state_translation_table
[old_state
], state_translation_table
[state
], /* reload_success = */ true);
133 static int scope_add_default_dependencies(Scope
*s
) {
136 if (!UNIT(s
)->default_dependencies
)
139 /* Make sure scopes are unloaded on shutdown */
140 if (!UNIT(s
)->ignore_on_soft_reboot
)
141 return unit_add_two_dependencies_by_name(
143 UNIT_BEFORE
, UNIT_CONFLICTS
,
144 SPECIAL_SHUTDOWN_TARGET
, true,
145 UNIT_DEPENDENCY_DEFAULT
);
147 /* Unless we are meant to survive soft reboot, in which case we need to conflict with
148 * non-soft-reboot targets. */
149 return unit_add_dependencies_on_real_shutdown_targets(UNIT(s
));
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
);
633 static void scope_notify_cgroup_oom_event(Unit
*u
, bool managed_oom
) {
637 log_unit_debug(u
, "Process(es) of control group were killed by systemd-oomd.");
639 log_unit_debug(u
, "Process of control group was killed by the OOM killer.");
641 if (s
->oom_policy
== OOM_CONTINUE
)
646 case SCOPE_START_CHOWN
:
648 scope_enter_signal(s
, SCOPE_STOP_SIGTERM
, SCOPE_FAILURE_OOM_KILL
);
651 case SCOPE_STOP_SIGTERM
:
652 scope_enter_signal(s
, SCOPE_STOP_SIGKILL
, SCOPE_FAILURE_OOM_KILL
);
655 case SCOPE_STOP_SIGKILL
:
656 if (s
->result
== SCOPE_SUCCESS
)
657 s
->result
= SCOPE_FAILURE_OOM_KILL
;
659 /* SCOPE_DEAD, SCOPE_ABANDONED, and SCOPE_FAILED end up in default */
665 static void scope_sigchld_event(Unit
*u
, pid_t pid
, int code
, int status
) {
670 if (s
->state
== SCOPE_START_CHOWN
) {
671 if (!is_clean_exit(code
, status
, EXIT_CLEAN_COMMAND
, NULL
))
672 scope_enter_dead(s
, SCOPE_FAILURE_RESOURCES
);
674 scope_enter_running(s
);
678 /* If we get a SIGCHLD event for one of the processes we were interested in, then we look for others to
679 * watch, under the assumption that we'll sooner or later get a SIGCHLD for them, as the original
680 * process we watched was probably the parent of them, and they are hence now our children. */
682 (void) unit_enqueue_rewatch_pids(u
);
685 static int scope_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
) {
686 Scope
*s
= SCOPE(userdata
);
689 assert(s
->timer_event_source
== source
);
694 log_unit_warning(UNIT(s
), "Scope reached runtime time limit. Stopping.");
695 scope_enter_signal(s
, SCOPE_STOP_SIGTERM
, SCOPE_FAILURE_TIMEOUT
);
698 case SCOPE_STOP_SIGTERM
:
699 if (s
->kill_context
.send_sigkill
) {
700 log_unit_warning(UNIT(s
), "Stopping timed out. Killing.");
701 scope_enter_signal(s
, SCOPE_STOP_SIGKILL
, SCOPE_FAILURE_TIMEOUT
);
703 log_unit_warning(UNIT(s
), "Stopping timed out. Skipping SIGKILL.");
704 scope_enter_dead(s
, SCOPE_FAILURE_TIMEOUT
);
709 case SCOPE_STOP_SIGKILL
:
710 log_unit_warning(UNIT(s
), "Still around after SIGKILL. Ignoring.");
711 scope_enter_dead(s
, SCOPE_FAILURE_TIMEOUT
);
714 case SCOPE_START_CHOWN
:
715 log_unit_warning(UNIT(s
), "User lookup timed out. Entering failed state.");
716 scope_enter_dead(s
, SCOPE_FAILURE_TIMEOUT
);
720 assert_not_reached();
726 int scope_abandon(Scope
*s
) {
729 if (unit_has_name(UNIT(s
), SPECIAL_INIT_SCOPE
))
732 if (!IN_SET(s
->state
, SCOPE_RUNNING
, SCOPE_ABANDONED
))
735 s
->was_abandoned
= true;
737 s
->controller
= mfree(s
->controller
);
738 s
->controller_track
= sd_bus_track_unref(s
->controller_track
);
740 scope_set_state(s
, SCOPE_ABANDONED
);
742 /* The client is no longer watching the remaining processes, so let's step in here, under the assumption that
743 * the remaining processes will be sooner or later reassigned to us as parent. */
744 (void) unit_enqueue_rewatch_pids(UNIT(s
));
749 _pure_
static UnitActiveState
scope_active_state(Unit
*u
) {
752 return state_translation_table
[SCOPE(u
)->state
];
755 _pure_
static const char *scope_sub_state_to_string(Unit
*u
) {
758 return scope_state_to_string(SCOPE(u
)->state
);
761 static void scope_enumerate_perpetual(Manager
*m
) {
767 /* Let's unconditionally add the "init.scope" special unit
768 * that encapsulates PID 1. Note that PID 1 already is in the
769 * cgroup for this, we hence just need to allocate the object
770 * for it and that's it. */
772 u
= manager_get_unit(m
, SPECIAL_INIT_SCOPE
);
774 r
= unit_new_for_name(m
, sizeof(Scope
), SPECIAL_INIT_SCOPE
, &u
);
776 log_error_errno(r
, "Failed to allocate the special " SPECIAL_INIT_SCOPE
" unit: %m");
783 SCOPE(u
)->deserialized_state
= SCOPE_RUNNING
;
785 unit_add_to_load_queue(u
);
786 unit_add_to_dbus_queue(u
);
787 /* Enqueue an explicit cgroup realization here. Unlike other cgroups this one already exists and is
788 * populated (by us, after all!) already, even when we are not in a reload cycle. Hence we cannot
789 * apply the settings at creation time anymore, but let's at least apply them asynchronously. */
790 unit_add_to_cgroup_realize_queue(u
);
793 static const char* const scope_result_table
[_SCOPE_RESULT_MAX
] = {
794 [SCOPE_SUCCESS
] = "success",
795 [SCOPE_FAILURE_RESOURCES
] = "resources",
796 [SCOPE_FAILURE_TIMEOUT
] = "timeout",
797 [SCOPE_FAILURE_OOM_KILL
] = "oom-kill",
800 DEFINE_STRING_TABLE_LOOKUP(scope_result
, ScopeResult
);
802 const UnitVTable scope_vtable
= {
803 .object_size
= sizeof(Scope
),
804 .cgroup_context_offset
= offsetof(Scope
, cgroup_context
),
805 .kill_context_offset
= offsetof(Scope
, kill_context
),
811 .private_section
= "Scope",
813 .can_transient
= true,
814 .can_delegate
= true,
817 .can_set_managed_oom
= true,
823 .coldplug
= scope_coldplug
,
827 .start
= scope_start
,
832 .freeze
= unit_freeze_vtable_common
,
833 .thaw
= unit_thaw_vtable_common
,
835 .get_timeout
= scope_get_timeout
,
837 .serialize
= scope_serialize
,
838 .deserialize_item
= scope_deserialize_item
,
840 .active_state
= scope_active_state
,
841 .sub_state_to_string
= scope_sub_state_to_string
,
843 .sigchld_event
= scope_sigchld_event
,
845 .reset_failed
= scope_reset_failed
,
847 .notify_cgroup_empty
= scope_notify_cgroup_empty_event
,
848 .notify_cgroup_oom
= scope_notify_cgroup_oom_event
,
850 .bus_set_property
= bus_scope_set_property
,
851 .bus_commit_properties
= bus_scope_commit_properties
,
853 .enumerate_perpetual
= scope_enumerate_perpetual
,