]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/core/scope.c
Merge pull request #17399 from afq984/udev-escaped-string
[thirdparty/systemd.git] / src / core / scope.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <errno.h>
4 #include <unistd.h>
5
6 #include "alloc-util.h"
7 #include "dbus-scope.h"
8 #include "dbus-unit.h"
9 #include "load-dropin.h"
10 #include "log.h"
11 #include "scope.h"
12 #include "serialize.h"
13 #include "special.h"
14 #include "string-table.h"
15 #include "string-util.h"
16 #include "strv.h"
17 #include "unit-name.h"
18 #include "unit.h"
19
20 static const UnitActiveState state_translation_table[_SCOPE_STATE_MAX] = {
21 [SCOPE_DEAD] = UNIT_INACTIVE,
22 [SCOPE_RUNNING] = UNIT_ACTIVE,
23 [SCOPE_ABANDONED] = UNIT_ACTIVE,
24 [SCOPE_STOP_SIGTERM] = UNIT_DEACTIVATING,
25 [SCOPE_STOP_SIGKILL] = UNIT_DEACTIVATING,
26 [SCOPE_FAILED] = UNIT_FAILED
27 };
28
29 static int scope_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata);
30
31 static void scope_init(Unit *u) {
32 Scope *s = SCOPE(u);
33
34 assert(u);
35 assert(u->load_state == UNIT_STUB);
36
37 s->runtime_max_usec = USEC_INFINITY;
38 s->timeout_stop_usec = u->manager->default_timeout_stop_usec;
39 u->ignore_on_isolate = true;
40 }
41
42 static void scope_done(Unit *u) {
43 Scope *s = SCOPE(u);
44
45 assert(u);
46
47 s->controller = mfree(s->controller);
48 s->controller_track = sd_bus_track_unref(s->controller_track);
49
50 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
51 }
52
53 static int scope_arm_timer(Scope *s, usec_t usec) {
54 int r;
55
56 assert(s);
57
58 if (s->timer_event_source) {
59 r = sd_event_source_set_time(s->timer_event_source, usec);
60 if (r < 0)
61 return r;
62
63 return sd_event_source_set_enabled(s->timer_event_source, SD_EVENT_ONESHOT);
64 }
65
66 if (usec == USEC_INFINITY)
67 return 0;
68
69 r = sd_event_add_time(
70 UNIT(s)->manager->event,
71 &s->timer_event_source,
72 CLOCK_MONOTONIC,
73 usec, 0,
74 scope_dispatch_timer, s);
75 if (r < 0)
76 return r;
77
78 (void) sd_event_source_set_description(s->timer_event_source, "scope-timer");
79
80 return 0;
81 }
82
83 static void scope_set_state(Scope *s, ScopeState state) {
84 ScopeState old_state;
85 assert(s);
86
87 if (s->state != state)
88 bus_unit_send_pending_change_signal(UNIT(s), false);
89
90 old_state = s->state;
91 s->state = state;
92
93 if (!IN_SET(state, SCOPE_STOP_SIGTERM, SCOPE_STOP_SIGKILL))
94 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
95
96 if (IN_SET(state, SCOPE_DEAD, SCOPE_FAILED)) {
97 unit_unwatch_all_pids(UNIT(s));
98 unit_dequeue_rewatch_pids(UNIT(s));
99 }
100
101 if (state != old_state)
102 log_debug("%s changed %s -> %s", UNIT(s)->id, scope_state_to_string(old_state), scope_state_to_string(state));
103
104 unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state], 0);
105 }
106
107 static int scope_add_default_dependencies(Scope *s) {
108 int r;
109
110 assert(s);
111
112 if (!UNIT(s)->default_dependencies)
113 return 0;
114
115 /* Make sure scopes are unloaded on shutdown */
116 r = unit_add_two_dependencies_by_name(
117 UNIT(s),
118 UNIT_BEFORE, UNIT_CONFLICTS,
119 SPECIAL_SHUTDOWN_TARGET, true,
120 UNIT_DEPENDENCY_DEFAULT);
121 if (r < 0)
122 return r;
123
124 return 0;
125 }
126
127 static int scope_verify(Scope *s) {
128 assert(s);
129 assert(UNIT(s)->load_state == UNIT_LOADED);
130
131 if (set_isempty(UNIT(s)->pids) &&
132 !MANAGER_IS_RELOADING(UNIT(s)->manager) &&
133 !unit_has_name(UNIT(s), SPECIAL_INIT_SCOPE)) {
134 log_unit_error(UNIT(s), "Scope has no PIDs. Refusing.");
135 return -ENOENT;
136 }
137
138 return 0;
139 }
140
141 static int scope_load_init_scope(Unit *u) {
142 assert(u);
143
144 if (!unit_has_name(u, SPECIAL_INIT_SCOPE))
145 return 0;
146
147 u->transient = true;
148 u->perpetual = true;
149
150 /* init.scope is a bit special, as it has to stick around forever. Because of its special semantics we
151 * synthesize it here, instead of relying on the unit file on disk. */
152
153 u->default_dependencies = false;
154
155 /* Prettify things, if we can. */
156 if (!u->description)
157 u->description = strdup("System and Service Manager");
158 if (!u->documentation)
159 (void) strv_extend(&u->documentation, "man:systemd(1)");
160
161 return 1;
162 }
163
164 static int scope_add_extras(Scope *s) {
165 int r;
166
167 r = unit_patch_contexts(UNIT(s));
168 if (r < 0)
169 return r;
170
171 r = unit_set_default_slice(UNIT(s));
172 if (r < 0)
173 return r;
174
175 return scope_add_default_dependencies(s);
176 }
177
178 static int scope_load(Unit *u) {
179 Scope *s = SCOPE(u);
180 int r;
181
182 assert(s);
183 assert(u->load_state == UNIT_STUB);
184
185 if (!u->transient && !MANAGER_IS_RELOADING(u->manager))
186 /* Refuse to load non-transient scope units, but allow them while reloading. */
187 return -ENOENT;
188
189 r = scope_load_init_scope(u);
190 if (r < 0)
191 return r;
192
193 r = unit_load_fragment_and_dropin(u, false);
194 if (r < 0)
195 return r;
196
197 if (u->load_state != UNIT_LOADED)
198 return 0;
199
200 r = scope_add_extras(s);
201 if (r < 0)
202 return r;
203
204 return scope_verify(s);
205 }
206
207 static usec_t scope_coldplug_timeout(Scope *s) {
208 assert(s);
209
210 switch (s->deserialized_state) {
211
212 case SCOPE_RUNNING:
213 return usec_add(UNIT(s)->active_enter_timestamp.monotonic, s->runtime_max_usec);
214
215 case SCOPE_STOP_SIGKILL:
216 case SCOPE_STOP_SIGTERM:
217 return usec_add(UNIT(s)->state_change_timestamp.monotonic, s->timeout_stop_usec);
218
219 default:
220 return USEC_INFINITY;
221 }
222 }
223
224 static int scope_coldplug(Unit *u) {
225 Scope *s = SCOPE(u);
226 int r;
227
228 assert(s);
229 assert(s->state == SCOPE_DEAD);
230
231 if (s->deserialized_state == s->state)
232 return 0;
233
234 r = scope_arm_timer(s, scope_coldplug_timeout(s));
235 if (r < 0)
236 return r;
237
238 if (!IN_SET(s->deserialized_state, SCOPE_DEAD, SCOPE_FAILED))
239 (void) unit_enqueue_rewatch_pids(u);
240
241 bus_scope_track_controller(s);
242
243 scope_set_state(s, s->deserialized_state);
244 return 0;
245 }
246
247 static void scope_dump(Unit *u, FILE *f, const char *prefix) {
248 Scope *s = SCOPE(u);
249 char buf_runtime[FORMAT_TIMESPAN_MAX];
250
251 assert(s);
252 assert(f);
253
254 fprintf(f,
255 "%sScope State: %s\n"
256 "%sResult: %s\n"
257 "%sRuntimeMaxSec: %s\n",
258 prefix, scope_state_to_string(s->state),
259 prefix, scope_result_to_string(s->result),
260 prefix, format_timespan(buf_runtime, sizeof(buf_runtime), s->runtime_max_usec, USEC_PER_SEC));
261
262 cgroup_context_dump(UNIT(s), f, prefix);
263 kill_context_dump(&s->kill_context, f, prefix);
264 }
265
266 static void scope_enter_dead(Scope *s, ScopeResult f) {
267 assert(s);
268
269 if (s->result == SCOPE_SUCCESS)
270 s->result = f;
271
272 unit_log_result(UNIT(s), s->result == SCOPE_SUCCESS, scope_result_to_string(s->result));
273 scope_set_state(s, s->result != SCOPE_SUCCESS ? SCOPE_FAILED : SCOPE_DEAD);
274 }
275
276 static void scope_enter_signal(Scope *s, ScopeState state, ScopeResult f) {
277 bool skip_signal = false;
278 int r;
279
280 assert(s);
281
282 if (s->result == SCOPE_SUCCESS)
283 s->result = f;
284
285 /* Before sending any signal, make sure we track all members of this cgroup */
286 (void) unit_watch_all_pids(UNIT(s));
287
288 /* Also, enqueue a job that we recheck all our PIDs a bit later, given that it's likely some processes have
289 * died now */
290 (void) unit_enqueue_rewatch_pids(UNIT(s));
291
292 /* If we have a controller set let's ask the controller nicely to terminate the scope, instead of us going
293 * directly into SIGTERM berserk mode */
294 if (state == SCOPE_STOP_SIGTERM)
295 skip_signal = bus_scope_send_request_stop(s) > 0;
296
297 if (skip_signal)
298 r = 1; /* wait */
299 else {
300 r = unit_kill_context(
301 UNIT(s),
302 &s->kill_context,
303 state != SCOPE_STOP_SIGTERM ? KILL_KILL :
304 s->was_abandoned ? KILL_TERMINATE_AND_LOG :
305 KILL_TERMINATE,
306 -1, -1, false);
307 if (r < 0)
308 goto fail;
309 }
310
311 if (r > 0) {
312 r = scope_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->timeout_stop_usec));
313 if (r < 0)
314 goto fail;
315
316 scope_set_state(s, state);
317 } else if (state == SCOPE_STOP_SIGTERM)
318 scope_enter_signal(s, SCOPE_STOP_SIGKILL, SCOPE_SUCCESS);
319 else
320 scope_enter_dead(s, SCOPE_SUCCESS);
321
322 return;
323
324 fail:
325 log_unit_warning_errno(UNIT(s), r, "Failed to kill processes: %m");
326
327 scope_enter_dead(s, SCOPE_FAILURE_RESOURCES);
328 }
329
330 static int scope_start(Unit *u) {
331 Scope *s = SCOPE(u);
332 int r;
333
334 assert(s);
335
336 if (unit_has_name(u, SPECIAL_INIT_SCOPE))
337 return -EPERM;
338
339 if (s->state == SCOPE_FAILED)
340 return -EPERM;
341
342 /* We can't fulfill this right now, please try again later */
343 if (IN_SET(s->state, SCOPE_STOP_SIGTERM, SCOPE_STOP_SIGKILL))
344 return -EAGAIN;
345
346 assert(s->state == SCOPE_DEAD);
347
348 if (!u->transient && !MANAGER_IS_RELOADING(u->manager))
349 return -ENOENT;
350
351 (void) bus_scope_track_controller(s);
352
353 r = unit_acquire_invocation_id(u);
354 if (r < 0)
355 return r;
356
357 (void) unit_realize_cgroup(u);
358 (void) unit_reset_accounting(u);
359
360 unit_export_state_files(u);
361
362 r = unit_attach_pids_to_cgroup(u, u->pids, NULL);
363 if (r < 0) {
364 log_unit_warning_errno(u, r, "Failed to add PIDs to scope's control group: %m");
365 scope_enter_dead(s, SCOPE_FAILURE_RESOURCES);
366 return r;
367 }
368
369 s->result = SCOPE_SUCCESS;
370
371 scope_set_state(s, SCOPE_RUNNING);
372
373 /* Set the maximum runtime timeout. */
374 scope_arm_timer(s, usec_add(UNIT(s)->active_enter_timestamp.monotonic, s->runtime_max_usec));
375
376 /* Start watching the PIDs currently in the scope */
377 (void) unit_enqueue_rewatch_pids(u);
378 return 1;
379 }
380
381 static int scope_stop(Unit *u) {
382 Scope *s = SCOPE(u);
383
384 assert(s);
385
386 if (IN_SET(s->state, SCOPE_STOP_SIGTERM, SCOPE_STOP_SIGKILL))
387 return 0;
388
389 assert(IN_SET(s->state, SCOPE_RUNNING, SCOPE_ABANDONED));
390
391 scope_enter_signal(s, SCOPE_STOP_SIGTERM, SCOPE_SUCCESS);
392 return 1;
393 }
394
395 static void scope_reset_failed(Unit *u) {
396 Scope *s = SCOPE(u);
397
398 assert(s);
399
400 if (s->state == SCOPE_FAILED)
401 scope_set_state(s, SCOPE_DEAD);
402
403 s->result = SCOPE_SUCCESS;
404 }
405
406 static int scope_kill(Unit *u, KillWho who, int signo, sd_bus_error *error) {
407 return unit_kill_common(u, who, signo, -1, -1, error);
408 }
409
410 static int scope_get_timeout(Unit *u, usec_t *timeout) {
411 Scope *s = SCOPE(u);
412 usec_t t;
413 int r;
414
415 if (!s->timer_event_source)
416 return 0;
417
418 r = sd_event_source_get_time(s->timer_event_source, &t);
419 if (r < 0)
420 return r;
421 if (t == USEC_INFINITY)
422 return 0;
423
424 *timeout = t;
425 return 1;
426 }
427
428 static int scope_serialize(Unit *u, FILE *f, FDSet *fds) {
429 Scope *s = SCOPE(u);
430
431 assert(s);
432 assert(f);
433 assert(fds);
434
435 (void) serialize_item(f, "state", scope_state_to_string(s->state));
436 (void) serialize_bool(f, "was-abandoned", s->was_abandoned);
437
438 if (s->controller)
439 (void) serialize_item(f, "controller", s->controller);
440
441 return 0;
442 }
443
444 static int scope_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
445 Scope *s = SCOPE(u);
446 int r;
447
448 assert(u);
449 assert(key);
450 assert(value);
451 assert(fds);
452
453 if (streq(key, "state")) {
454 ScopeState state;
455
456 state = scope_state_from_string(value);
457 if (state < 0)
458 log_unit_debug(u, "Failed to parse state value: %s", value);
459 else
460 s->deserialized_state = state;
461
462 } else if (streq(key, "was-abandoned")) {
463 int k;
464
465 k = parse_boolean(value);
466 if (k < 0)
467 log_unit_debug(u, "Failed to parse boolean value: %s", value);
468 else
469 s->was_abandoned = k;
470 } else if (streq(key, "controller")) {
471
472 r = free_and_strdup(&s->controller, value);
473 if (r < 0)
474 return log_oom();
475
476 } else
477 log_unit_debug(u, "Unknown serialization key: %s", key);
478
479 return 0;
480 }
481
482 static void scope_notify_cgroup_empty_event(Unit *u) {
483 Scope *s = SCOPE(u);
484 assert(u);
485
486 log_unit_debug(u, "cgroup is empty");
487
488 if (IN_SET(s->state, SCOPE_RUNNING, SCOPE_ABANDONED, SCOPE_STOP_SIGTERM, SCOPE_STOP_SIGKILL))
489 scope_enter_dead(s, SCOPE_SUCCESS);
490
491 /* If the cgroup empty notification comes when the unit is not active, we must have failed to clean
492 * up the cgroup earlier and should do it now. */
493 if (IN_SET(s->state, SCOPE_DEAD, SCOPE_FAILED))
494 unit_prune_cgroup(u);
495 }
496
497 static void scope_sigchld_event(Unit *u, pid_t pid, int code, int status) {
498 assert(u);
499
500 /* If we get a SIGCHLD event for one of the processes we were interested in, then we look for others to
501 * watch, under the assumption that we'll sooner or later get a SIGCHLD for them, as the original
502 * process we watched was probably the parent of them, and they are hence now our children. */
503
504 (void) unit_enqueue_rewatch_pids(u);
505 }
506
507 static int scope_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata) {
508 Scope *s = SCOPE(userdata);
509
510 assert(s);
511 assert(s->timer_event_source == source);
512
513 switch (s->state) {
514
515 case SCOPE_RUNNING:
516 log_unit_warning(UNIT(s), "Scope reached runtime time limit. Stopping.");
517 scope_enter_signal(s, SCOPE_STOP_SIGTERM, SCOPE_FAILURE_TIMEOUT);
518 break;
519
520 case SCOPE_STOP_SIGTERM:
521 if (s->kill_context.send_sigkill) {
522 log_unit_warning(UNIT(s), "Stopping timed out. Killing.");
523 scope_enter_signal(s, SCOPE_STOP_SIGKILL, SCOPE_FAILURE_TIMEOUT);
524 } else {
525 log_unit_warning(UNIT(s), "Stopping timed out. Skipping SIGKILL.");
526 scope_enter_dead(s, SCOPE_FAILURE_TIMEOUT);
527 }
528
529 break;
530
531 case SCOPE_STOP_SIGKILL:
532 log_unit_warning(UNIT(s), "Still around after SIGKILL. Ignoring.");
533 scope_enter_dead(s, SCOPE_FAILURE_TIMEOUT);
534 break;
535
536 default:
537 assert_not_reached("Timeout at wrong time.");
538 }
539
540 return 0;
541 }
542
543 int scope_abandon(Scope *s) {
544 assert(s);
545
546 if (unit_has_name(UNIT(s), SPECIAL_INIT_SCOPE))
547 return -EPERM;
548
549 if (!IN_SET(s->state, SCOPE_RUNNING, SCOPE_ABANDONED))
550 return -ESTALE;
551
552 s->was_abandoned = true;
553
554 s->controller = mfree(s->controller);
555 s->controller_track = sd_bus_track_unref(s->controller_track);
556
557 scope_set_state(s, SCOPE_ABANDONED);
558
559 /* The client is no longer watching the remaining processes, so let's step in here, under the assumption that
560 * the remaining processes will be sooner or later reassigned to us as parent. */
561 (void) unit_enqueue_rewatch_pids(UNIT(s));
562
563 return 0;
564 }
565
566 _pure_ static UnitActiveState scope_active_state(Unit *u) {
567 assert(u);
568
569 return state_translation_table[SCOPE(u)->state];
570 }
571
572 _pure_ static const char *scope_sub_state_to_string(Unit *u) {
573 assert(u);
574
575 return scope_state_to_string(SCOPE(u)->state);
576 }
577
578 static void scope_enumerate_perpetual(Manager *m) {
579 Unit *u;
580 int r;
581
582 assert(m);
583
584 /* Let's unconditionally add the "init.scope" special unit
585 * that encapsulates PID 1. Note that PID 1 already is in the
586 * cgroup for this, we hence just need to allocate the object
587 * for it and that's it. */
588
589 u = manager_get_unit(m, SPECIAL_INIT_SCOPE);
590 if (!u) {
591 r = unit_new_for_name(m, sizeof(Scope), SPECIAL_INIT_SCOPE, &u);
592 if (r < 0) {
593 log_error_errno(r, "Failed to allocate the special " SPECIAL_INIT_SCOPE " unit: %m");
594 return;
595 }
596 }
597
598 u->transient = true;
599 u->perpetual = true;
600 SCOPE(u)->deserialized_state = SCOPE_RUNNING;
601
602 unit_add_to_load_queue(u);
603 unit_add_to_dbus_queue(u);
604 }
605
606 static const char* const scope_result_table[_SCOPE_RESULT_MAX] = {
607 [SCOPE_SUCCESS] = "success",
608 [SCOPE_FAILURE_RESOURCES] = "resources",
609 [SCOPE_FAILURE_TIMEOUT] = "timeout",
610 };
611
612 DEFINE_STRING_TABLE_LOOKUP(scope_result, ScopeResult);
613
614 const UnitVTable scope_vtable = {
615 .object_size = sizeof(Scope),
616 .cgroup_context_offset = offsetof(Scope, cgroup_context),
617 .kill_context_offset = offsetof(Scope, kill_context),
618
619 .sections =
620 "Unit\0"
621 "Scope\0"
622 "Install\0",
623 .private_section = "Scope",
624
625 .can_transient = true,
626 .can_delegate = true,
627 .can_fail = true,
628 .once_only = true,
629 .can_set_managed_oom = true,
630
631 .init = scope_init,
632 .load = scope_load,
633 .done = scope_done,
634
635 .coldplug = scope_coldplug,
636
637 .dump = scope_dump,
638
639 .start = scope_start,
640 .stop = scope_stop,
641
642 .kill = scope_kill,
643
644 .freeze = unit_freeze_vtable_common,
645 .thaw = unit_thaw_vtable_common,
646
647 .get_timeout = scope_get_timeout,
648
649 .serialize = scope_serialize,
650 .deserialize_item = scope_deserialize_item,
651
652 .active_state = scope_active_state,
653 .sub_state_to_string = scope_sub_state_to_string,
654
655 .sigchld_event = scope_sigchld_event,
656
657 .reset_failed = scope_reset_failed,
658
659 .notify_cgroup_empty = scope_notify_cgroup_empty_event,
660
661 .bus_set_property = bus_scope_set_property,
662 .bus_commit_properties = bus_scope_commit_properties,
663
664 .enumerate_perpetual = scope_enumerate_perpetual,
665 };