]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/unit.c
varlink: add server write states to disconnect check
[thirdparty/systemd.git] / src / core / unit.c
CommitLineData
53e1b683 1/* SPDX-License-Identifier: LGPL-2.1+ */
a7334b09 2
87f0e418 3#include <errno.h>
0301abf4 4#include <stdlib.h>
4c253ed1 5#include <sys/prctl.h>
4f5dd394 6#include <unistd.h>
87f0e418 7
718db961
LP
8#include "sd-id128.h"
9#include "sd-messages.h"
4f5dd394 10
57b7a260 11#include "all-units.h"
d68c645b 12#include "alloc-util.h"
fab34748 13#include "bpf-firewall.h"
4f5dd394
LP
14#include "bus-common-errors.h"
15#include "bus-util.h"
fdb3deca 16#include "cgroup-setup.h"
c6c18be3 17#include "cgroup-util.h"
4f5dd394
LP
18#include "dbus-unit.h"
19#include "dbus.h"
20#include "dropin.h"
21#include "escape.h"
22#include "execute.h"
6a48d82f 23#include "fd-util.h"
a5c32cff 24#include "fileio-label.h"
ee228be1 25#include "fileio.h"
f97b34a6 26#include "format-util.h"
4b58153d 27#include "id128-util.h"
915b1d01 28#include "io-util.h"
5cfa33e0 29#include "install.h"
a3f5fd96 30#include "label.h"
4f5dd394
LP
31#include "load-dropin.h"
32#include "load-fragment.h"
33#include "log.h"
34#include "macro.h"
f5947a5e 35#include "missing_audit.h"
4f5dd394 36#include "mkdir.h"
6bedfcbb 37#include "parse-util.h"
4f5dd394 38#include "path-util.h"
0b452006 39#include "process-util.h"
810ef318 40#include "rm-rf.h"
d68c645b 41#include "serialize.h"
4f5dd394 42#include "set.h"
6eb7c172 43#include "signal-util.h"
d3070fbd 44#include "sparse-endian.h"
e9db43d5 45#include "special.h"
2e59b241 46#include "specifier.h"
8fcde012 47#include "stat-util.h"
d054f0a4 48#include "stdio-util.h"
5afe510c 49#include "string-table.h"
07630cea 50#include "string-util.h"
4f5dd394 51#include "strv.h"
5b262f74 52#include "terminal-util.h"
e4de7287 53#include "tmpfile-util.h"
4f4afc88 54#include "umask-util.h"
4f5dd394 55#include "unit-name.h"
e9db43d5 56#include "unit.h"
b1d4f8e1
LP
57#include "user-util.h"
58#include "virt.h"
87f0e418 59
37109b85
ZJS
60/* Thresholds for logging at INFO level about resource consumption */
61#define MENTIONWORTHY_CPU_NSEC (1 * NSEC_PER_SEC)
62#define MENTIONWORTHY_IO_BYTES (1024 * 1024ULL)
63#define MENTIONWORTHY_IP_BYTES (0ULL)
64
65/* Thresholds for logging at INFO level about resource consumption */
66#define NOTICEWORTHY_CPU_NSEC (10*60 * NSEC_PER_SEC) /* 10 minutes */
67#define NOTICEWORTHY_IO_BYTES (10 * 1024 * 1024ULL) /* 10 MB */
68#define NOTICEWORTHY_IP_BYTES (128 * 1024 * 1024ULL) /* 128 MB */
69
87f0e418
LP
70const UnitVTable * const unit_vtable[_UNIT_TYPE_MAX] = {
71 [UNIT_SERVICE] = &service_vtable,
87f0e418
LP
72 [UNIT_SOCKET] = &socket_vtable,
73 [UNIT_TARGET] = &target_vtable,
74 [UNIT_DEVICE] = &device_vtable,
75 [UNIT_MOUNT] = &mount_vtable,
76 [UNIT_AUTOMOUNT] = &automount_vtable,
01f78473 77 [UNIT_SWAP] = &swap_vtable,
e821075a 78 [UNIT_TIMER] = &timer_vtable,
a016b922 79 [UNIT_PATH] = &path_vtable,
6c12b52e 80 [UNIT_SLICE] = &slice_vtable,
5afe510c 81 [UNIT_SCOPE] = &scope_vtable,
87f0e418
LP
82};
83
f2341e0a 84static void maybe_warn_about_dependency(Unit *u, const char *other, UnitDependency dependency);
d1fab3fe 85
7d17cfbc 86Unit *unit_new(Manager *m, size_t size) {
87f0e418
LP
87 Unit *u;
88
89 assert(m);
ac155bb8 90 assert(size >= sizeof(Unit));
87f0e418 91
7d17cfbc
MS
92 u = malloc0(size);
93 if (!u)
87f0e418
LP
94 return NULL;
95
ac155bb8
MS
96 u->manager = m;
97 u->type = _UNIT_TYPE_INVALID;
ac155bb8
MS
98 u->default_dependencies = true;
99 u->unit_file_state = _UNIT_FILE_STATE_INVALID;
d2dc52db 100 u->unit_file_preset = -1;
d420282b 101 u->on_failure_job_mode = JOB_REPLACE;
0bb814c2 102 u->cgroup_control_inotify_wd = -1;
afcfaa69 103 u->cgroup_memory_inotify_wd = -1;
36c16a7c 104 u->job_timeout = USEC_INFINITY;
a2df3ea4 105 u->job_running_timeout = USEC_INFINITY;
00d9ef85
LP
106 u->ref_uid = UID_INVALID;
107 u->ref_gid = GID_INVALID;
fe700f46 108 u->cpu_usage_last = NSEC_INFINITY;
17f14955 109 u->cgroup_invalidated_mask |= CGROUP_MASK_BPF_FIREWALL;
7af67e9a 110 u->failure_action_exit_status = u->success_action_exit_status = -1;
87f0e418 111
6a48d82f
DM
112 u->ip_accounting_ingress_map_fd = -1;
113 u->ip_accounting_egress_map_fd = -1;
114 u->ipv4_allow_map_fd = -1;
115 u->ipv6_allow_map_fd = -1;
116 u->ipv4_deny_map_fd = -1;
117 u->ipv6_deny_map_fd = -1;
118
2e59b241
LP
119 u->last_section_private = -1;
120
7bf081a1 121 u->start_ratelimit = (RateLimit) { m->default_start_limit_interval, m->default_start_limit_burst };
8c227e7f 122 u->auto_stop_ratelimit = (RateLimit) { 10 * USEC_PER_SEC, 16 };
bea355da 123
fbe14fc9
LP
124 for (CGroupIOAccountingMetric i = 0; i < _CGROUP_IO_ACCOUNTING_METRIC_MAX; i++)
125 u->io_accounting_last[i] = UINT64_MAX;
126
87f0e418
LP
127 return u;
128}
129
a581e45a 130int unit_new_for_name(Manager *m, size_t size, const char *name, Unit **ret) {
dc409696 131 _cleanup_(unit_freep) Unit *u = NULL;
a581e45a
LP
132 int r;
133
134 u = unit_new(m, size);
135 if (!u)
136 return -ENOMEM;
137
138 r = unit_add_name(u, name);
dc409696 139 if (r < 0)
a581e45a 140 return r;
a581e45a 141
1cc6c93a
YW
142 *ret = TAKE_PTR(u);
143
a581e45a
LP
144 return r;
145}
146
303ee601 147bool unit_has_name(const Unit *u, const char *name) {
f278026d
LP
148 assert(u);
149 assert(name);
150
4562c355
ZJS
151 return streq_ptr(name, u->id) ||
152 set_contains(u->aliases, name);
f278026d
LP
153}
154
598459ce
LP
155static void unit_init(Unit *u) {
156 CGroupContext *cc;
157 ExecContext *ec;
158 KillContext *kc;
159
160 assert(u);
161 assert(u->manager);
162 assert(u->type >= 0);
163
164 cc = unit_get_cgroup_context(u);
165 if (cc) {
166 cgroup_context_init(cc);
167
168 /* Copy in the manager defaults into the cgroup
169 * context, _before_ the rest of the settings have
170 * been initialized */
171
172 cc->cpu_accounting = u->manager->default_cpu_accounting;
13c31542 173 cc->io_accounting = u->manager->default_io_accounting;
598459ce
LP
174 cc->blockio_accounting = u->manager->default_blockio_accounting;
175 cc->memory_accounting = u->manager->default_memory_accounting;
03a7b521 176 cc->tasks_accounting = u->manager->default_tasks_accounting;
6a48d82f 177 cc->ip_accounting = u->manager->default_ip_accounting;
0af20ea2
LP
178
179 if (u->type != UNIT_SLICE)
180 cc->tasks_max = u->manager->default_tasks_max;
598459ce
LP
181 }
182
183 ec = unit_get_exec_context(u);
b1edf445 184 if (ec) {
598459ce
LP
185 exec_context_init(ec);
186
5e37d193
FB
187 if (MANAGER_IS_SYSTEM(u->manager))
188 ec->keyring_mode = EXEC_KEYRING_SHARED;
189 else {
190 ec->keyring_mode = EXEC_KEYRING_INHERIT;
191
192 /* User manager might have its umask redefined by PAM or UMask=. In this
193 * case let the units it manages inherit this value by default. They can
194 * still tune this value through their own unit file */
195 (void) get_process_umask(getpid_cached(), &ec->umask);
196 }
b1edf445
LP
197 }
198
598459ce
LP
199 kc = unit_get_kill_context(u);
200 if (kc)
201 kill_context_init(kc);
202
203 if (UNIT_VTABLE(u)->init)
204 UNIT_VTABLE(u)->init(u);
205}
206
4562c355
ZJS
207static int unit_add_alias(Unit *u, char *donated_name) {
208 int r;
209
210 /* Make sure that u->names is allocated. We may leave u->names
211 * empty if we fail later, but this is not a problem. */
973bc32a 212 r = set_ensure_put(&u->aliases, &string_hash_ops, donated_name);
4562c355
ZJS
213 if (r < 0)
214 return r;
215 assert(r > 0);
216
217 return 0;
218}
219
87f0e418 220int unit_add_name(Unit *u, const char *text) {
4562c355 221 _cleanup_free_ char *name = NULL, *instance = NULL;
87f0e418 222 UnitType t;
87f0e418
LP
223 int r;
224
225 assert(u);
226 assert(text);
227
7410616c 228 if (unit_name_is_valid(text, UNIT_NAME_TEMPLATE)) {
ac155bb8 229 if (!u->instance)
acd1987a
WY
230 return log_unit_debug_errno(u, SYNTHETIC_ERRNO(EINVAL),
231 "instance is not set when adding name '%s': %m", text);
87f0e418 232
4562c355 233 r = unit_name_replace_instance(text, u->instance, &name);
7410616c 234 if (r < 0)
acd1987a
WY
235 return log_unit_debug_errno(u, r,
236 "failed to build instance name from '%s': %m", text);
7410616c 237 } else {
4562c355
ZJS
238 name = strdup(text);
239 if (!name)
7410616c
LP
240 return -ENOMEM;
241 }
87f0e418 242
4562c355 243 if (unit_has_name(u, name))
7410616c 244 return 0;
4562c355
ZJS
245
246 if (hashmap_contains(u->manager->units, name))
acd1987a 247 return log_unit_debug_errno(u, SYNTHETIC_ERRNO(EEXIST),
4562c355 248 "unit already exist when adding name '%s': %m", name);
7410616c 249
4562c355 250 if (!unit_name_is_valid(name, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
acd1987a 251 return log_unit_debug_errno(u, SYNTHETIC_ERRNO(EINVAL),
4562c355 252 "name '%s' is invalid: %m", name);
e537352b 253
4562c355 254 t = unit_name_to_type(name);
7410616c 255 if (t < 0)
acd1987a 256 return log_unit_debug_errno(u, SYNTHETIC_ERRNO(EINVAL),
cd990847 257 "failed to derive unit type from name '%s': %m", name);
87f0e418 258
598459ce 259 if (u->type != _UNIT_TYPE_INVALID && t != u->type)
acd1987a
WY
260 return log_unit_debug_errno(u, SYNTHETIC_ERRNO(EINVAL),
261 "unit type is illegal: u->type(%d) and t(%d) for name '%s': %m",
4562c355 262 u->type, t, name);
87f0e418 263
4562c355 264 r = unit_name_to_instance(name, &instance);
e48614c4 265 if (r < 0)
4562c355 266 return log_unit_debug_errno(u, r, "failed to extract instance from name '%s': %m", name);
87f0e418 267
4562c355
ZJS
268 if (instance && !unit_type_may_template(t))
269 return log_unit_debug_errno(u, SYNTHETIC_ERRNO(EINVAL), "templates are not allowed for name '%s': %m", name);
9e2f7c11 270
d383acad
ZJS
271 /* Ensure that this unit either has no instance, or that the instance matches. */
272 if (u->type != _UNIT_TYPE_INVALID && !streq_ptr(u->instance, instance))
acd1987a 273 return log_unit_debug_errno(u, SYNTHETIC_ERRNO(EINVAL),
ada4b34e
ZJS
274 "cannot add name %s, the instances don't match (\"%s\" != \"%s\").",
275 name, instance, u->instance);
9e2f7c11 276
4562c355 277 if (u->id && !unit_type_may_alias(t))
ada4b34e
ZJS
278 return log_unit_debug_errno(u, SYNTHETIC_ERRNO(EEXIST),
279 "cannot add name %s, aliases are not allowed for %s units.",
280 name, unit_type_to_string(t));
9e2f7c11 281
598459ce 282 if (hashmap_size(u->manager->units) >= MANAGER_MAX_NAMES)
ada4b34e 283 return log_unit_warning_errno(u, SYNTHETIC_ERRNO(E2BIG), "cannot add name, manager has too many units: %m");
4f0f902f 284
4562c355
ZJS
285 /* Add name to the global hashmap first, because that's easier to undo */
286 r = hashmap_put(u->manager->units, name, u);
7410616c 287 if (r < 0)
acd1987a 288 return log_unit_debug_errno(u, r, "add unit to hashmap failed for name '%s': %m", text);
87f0e418 289
4562c355
ZJS
290 if (u->id) {
291 r = unit_add_alias(u, name); /* unit_add_alias() takes ownership of the name on success */
292 if (r < 0) {
293 hashmap_remove(u->manager->units, name);
294 return r;
295 }
296 TAKE_PTR(name);
297
298 } else {
299 /* A new name, we don't need the set yet. */
300 assert(u->type == _UNIT_TYPE_INVALID);
301 assert(!u->instance);
302
ac155bb8 303 u->type = t;
4562c355
ZJS
304 u->id = TAKE_PTR(name);
305 u->instance = TAKE_PTR(instance);
9e2f7c11 306
71fda00f 307 LIST_PREPEND(units_by_type, u->manager->units_by_type[t], u);
598459ce 308 unit_init(u);
598459ce 309 }
9e2f7c11 310
598459ce
LP
311 unit_add_to_dbus_queue(u);
312 return 0;
87f0e418
LP
313}
314
0ae97ec1 315int unit_choose_id(Unit *u, const char *name) {
68eda4bd 316 _cleanup_free_ char *t = NULL;
4562c355 317 char *s;
276c3e78 318 int r;
0ae97ec1
LP
319
320 assert(u);
321 assert(name);
322
7410616c 323 if (unit_name_is_valid(name, UNIT_NAME_TEMPLATE)) {
ac155bb8 324 if (!u->instance)
9e2f7c11
LP
325 return -EINVAL;
326
7410616c
LP
327 r = unit_name_replace_instance(name, u->instance, &t);
328 if (r < 0)
329 return r;
9e2f7c11
LP
330
331 name = t;
332 }
333
4562c355
ZJS
334 if (streq_ptr(u->id, name))
335 return 0; /* Nothing to do. */
336
337 /* Selects one of the aliases of this unit as the id */
338 s = set_get(u->aliases, (char*) name);
9e2f7c11 339 if (!s)
0ae97ec1
LP
340 return -ENOENT;
341
4562c355
ZJS
342 if (u->id) {
343 r = set_remove_and_put(u->aliases, name, u->id);
344 if (r < 0)
345 return r;
346 } else
347 assert_se(set_remove(u->aliases, name)); /* see set_get() above… */
276c3e78 348
4562c355 349 u->id = s; /* Old u->id is now stored in the set, and s is not stored anywhere */
c1e1601e 350 unit_add_to_dbus_queue(u);
9e2f7c11 351
0ae97ec1
LP
352 return 0;
353}
354
f50e0a01 355int unit_set_description(Unit *u, const char *description) {
84b26d51 356 int r;
f50e0a01
LP
357
358 assert(u);
359
84b26d51
LP
360 r = free_and_strdup(&u->description, empty_to_null(description));
361 if (r < 0)
362 return r;
363 if (r > 0)
364 unit_add_to_dbus_queue(u);
c1e1601e 365
f50e0a01
LP
366 return 0;
367}
368
f2f725e5 369bool unit_may_gc(Unit *u) {
a354329f 370 UnitActiveState state;
e98b2fbb 371 int r;
5afe510c 372
701cc384
LP
373 assert(u);
374
f2f725e5
ZJS
375 /* Checks whether the unit is ready to be unloaded for garbage collection.
376 * Returns true when the unit may be collected, and false if there's some
2641f02e
ZJS
377 * reason to keep it loaded.
378 *
379 * References from other units are *not* checked here. Instead, this is done
380 * in unit_gc_sweep(), but using markers to properly collect dependency loops.
381 */
5afe510c 382
a354329f 383 if (u->job)
f2f725e5 384 return false;
701cc384 385
a354329f 386 if (u->nop_job)
f2f725e5 387 return false;
6c073082 388
a354329f
LP
389 state = unit_active_state(u);
390
7eb2a8a1 391 /* If the unit is inactive and failed and no job is queued for it, then release its runtime resources */
a354329f
LP
392 if (UNIT_IS_INACTIVE_OR_FAILED(state) &&
393 UNIT_VTABLE(u)->release_resources)
7eb2a8a1 394 UNIT_VTABLE(u)->release_resources(u);
a354329f 395
f5869324 396 if (u->perpetual)
f2f725e5 397 return false;
9d576438 398
05a98afd 399 if (sd_bus_track_count(u->bus_track) > 0)
f2f725e5 400 return false;
05a98afd 401
5afe510c
LP
402 /* But we keep the unit object around for longer when it is referenced or configured to not be gc'ed */
403 switch (u->collect_mode) {
404
405 case COLLECT_INACTIVE:
406 if (state != UNIT_INACTIVE)
f2f725e5 407 return false;
5afe510c
LP
408
409 break;
410
411 case COLLECT_INACTIVE_OR_FAILED:
412 if (!IN_SET(state, UNIT_INACTIVE, UNIT_FAILED))
f2f725e5 413 return false;
5afe510c
LP
414
415 break;
416
417 default:
418 assert_not_reached("Unknown garbage collection mode");
419 }
420
e98b2fbb
LP
421 if (u->cgroup_path) {
422 /* If the unit has a cgroup, then check whether there's anything in it. If so, we should stay
423 * around. Units with active processes should never be collected. */
424
425 r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path);
426 if (r < 0)
427 log_unit_debug_errno(u, r, "Failed to determine whether cgroup %s is empty: %m", u->cgroup_path);
428 if (r <= 0)
f2f725e5 429 return false;
e98b2fbb
LP
430 }
431
f2f725e5
ZJS
432 if (UNIT_VTABLE(u)->may_gc && !UNIT_VTABLE(u)->may_gc(u))
433 return false;
701cc384 434
f2f725e5 435 return true;
701cc384
LP
436}
437
87f0e418
LP
438void unit_add_to_load_queue(Unit *u) {
439 assert(u);
ac155bb8 440 assert(u->type != _UNIT_TYPE_INVALID);
87f0e418 441
ac155bb8 442 if (u->load_state != UNIT_STUB || u->in_load_queue)
87f0e418
LP
443 return;
444
71fda00f 445 LIST_PREPEND(load_queue, u->manager->load_queue, u);
ac155bb8 446 u->in_load_queue = true;
87f0e418
LP
447}
448
23a177ef
LP
449void unit_add_to_cleanup_queue(Unit *u) {
450 assert(u);
451
ac155bb8 452 if (u->in_cleanup_queue)
23a177ef
LP
453 return;
454
71fda00f 455 LIST_PREPEND(cleanup_queue, u->manager->cleanup_queue, u);
ac155bb8 456 u->in_cleanup_queue = true;
23a177ef
LP
457}
458
701cc384
LP
459void unit_add_to_gc_queue(Unit *u) {
460 assert(u);
461
ac155bb8 462 if (u->in_gc_queue || u->in_cleanup_queue)
701cc384
LP
463 return;
464
f2f725e5 465 if (!unit_may_gc(u))
701cc384
LP
466 return;
467
c5a97ed1 468 LIST_PREPEND(gc_queue, u->manager->gc_unit_queue, u);
ac155bb8 469 u->in_gc_queue = true;
701cc384
LP
470}
471
c1e1601e
LP
472void unit_add_to_dbus_queue(Unit *u) {
473 assert(u);
ac155bb8 474 assert(u->type != _UNIT_TYPE_INVALID);
c1e1601e 475
ac155bb8 476 if (u->load_state == UNIT_STUB || u->in_dbus_queue)
c1e1601e
LP
477 return;
478
a567261a 479 /* Shortcut things if nobody cares */
8f8f05a9 480 if (sd_bus_track_count(u->manager->subscribed) <= 0 &&
ae572acd 481 sd_bus_track_count(u->bus_track) <= 0 &&
8f8f05a9 482 set_isempty(u->manager->private_buses)) {
ac155bb8 483 u->sent_dbus_new_signal = true;
94b6dfa2
LP
484 return;
485 }
486
71fda00f 487 LIST_PREPEND(dbus_queue, u->manager->dbus_unit_queue, u);
ac155bb8 488 u->in_dbus_queue = true;
c1e1601e
LP
489}
490
fda09318 491void unit_submit_to_stop_when_unneeded_queue(Unit *u) {
a3c1168a
LP
492 assert(u);
493
494 if (u->in_stop_when_unneeded_queue)
495 return;
496
497 if (!u->stop_when_unneeded)
498 return;
499
500 if (!UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u)))
501 return;
502
503 LIST_PREPEND(stop_when_unneeded_queue, u->manager->stop_when_unneeded_queue, u);
504 u->in_stop_when_unneeded_queue = true;
505}
506
eef85c4a 507static void bidi_set_free(Unit *u, Hashmap *h) {
87f0e418 508 Unit *other;
eef85c4a 509 void *v;
87f0e418
LP
510
511 assert(u);
512
eef85c4a 513 /* Frees the hashmap and makes sure we are dropped from the inverse pointers */
87f0e418 514
90e74a66 515 HASHMAP_FOREACH_KEY(v, other, h) {
f6173cb9 516 for (UnitDependency d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
eef85c4a 517 hashmap_remove(other->dependencies[d], u);
701cc384
LP
518
519 unit_add_to_gc_queue(other);
87f0e418
LP
520 }
521
eef85c4a 522 hashmap_free(h);
87f0e418
LP
523}
524
c2756a68
LP
525static void unit_remove_transient(Unit *u) {
526 char **i;
527
528 assert(u);
529
530 if (!u->transient)
531 return;
532
533 if (u->fragment_path)
3f5e8115 534 (void) unlink(u->fragment_path);
c2756a68
LP
535
536 STRV_FOREACH(i, u->dropin_paths) {
39591351 537 _cleanup_free_ char *p = NULL, *pp = NULL;
c2756a68 538
39591351
LP
539 p = dirname_malloc(*i); /* Get the drop-in directory from the drop-in file */
540 if (!p)
541 continue;
542
543 pp = dirname_malloc(p); /* Get the config directory from the drop-in directory */
544 if (!pp)
545 continue;
546
547 /* Only drop transient drop-ins */
548 if (!path_equal(u->manager->lookup_paths.transient, pp))
549 continue;
c2756a68 550
39591351
LP
551 (void) unlink(*i);
552 (void) rmdir(p);
c2756a68
LP
553 }
554}
555
a57f7e2c 556static void unit_free_requires_mounts_for(Unit *u) {
eef85c4a 557 assert(u);
a57f7e2c 558
eef85c4a
LP
559 for (;;) {
560 _cleanup_free_ char *path;
a57f7e2c 561
eef85c4a
LP
562 path = hashmap_steal_first_key(u->requires_mounts_for);
563 if (!path)
564 break;
565 else {
566 char s[strlen(path) + 1];
a57f7e2c 567
eef85c4a
LP
568 PATH_FOREACH_PREFIX_MORE(s, path) {
569 char *y;
570 Set *x;
571
572 x = hashmap_get2(u->manager->units_requiring_mounts_for, s, (void**) &y);
573 if (!x)
574 continue;
a57f7e2c 575
eef85c4a 576 (void) set_remove(x, u);
a57f7e2c 577
eef85c4a
LP
578 if (set_isempty(x)) {
579 (void) hashmap_remove(u->manager->units_requiring_mounts_for, y);
580 free(y);
581 set_free(x);
582 }
a57f7e2c
LP
583 }
584 }
585 }
586
eef85c4a 587 u->requires_mounts_for = hashmap_free(u->requires_mounts_for);
a57f7e2c
LP
588}
589
598459ce
LP
590static void unit_done(Unit *u) {
591 ExecContext *ec;
592 CGroupContext *cc;
593
594 assert(u);
595
596 if (u->type < 0)
597 return;
598
599 if (UNIT_VTABLE(u)->done)
600 UNIT_VTABLE(u)->done(u);
601
602 ec = unit_get_exec_context(u);
603 if (ec)
604 exec_context_done(ec);
605
606 cc = unit_get_cgroup_context(u);
607 if (cc)
608 cgroup_context_done(cc);
609}
610
87f0e418 611void unit_free(Unit *u) {
87f0e418
LP
612 char *t;
613
c9d5c9c0
LP
614 if (!u)
615 return;
87f0e418 616
50fb00b7 617 u->transient_file = safe_fclose(u->transient_file);
4f4afc88 618
2c289ea8 619 if (!MANAGER_IS_RELOADING(u->manager))
c2756a68
LP
620 unit_remove_transient(u);
621
c1e1601e
LP
622 bus_unit_send_removed_signal(u);
623
598459ce 624 unit_done(u);
a013b84b 625
50be4f4a 626 unit_dequeue_rewatch_pids(u);
cf9fd508 627
50be4f4a 628 sd_bus_slot_unref(u->match_bus_slot);
05a98afd
LP
629 sd_bus_track_unref(u->bus_track);
630 u->deserialized_refs = strv_free(u->deserialized_refs);
d9e45bc3 631 u->pending_freezer_message = sd_bus_message_unref(u->pending_freezer_message);
05a98afd 632
a57f7e2c
LP
633 unit_free_requires_mounts_for(u);
634
90e74a66 635 SET_FOREACH(t, u->aliases)
ac155bb8 636 hashmap_remove_value(u->manager->units, t, u);
4562c355
ZJS
637 if (u->id)
638 hashmap_remove_value(u->manager->units, u->id, u);
87f0e418 639
4b58153d
LP
640 if (!sd_id128_is_null(u->invocation_id))
641 hashmap_remove_value(u->manager->units_by_invocation_id, &u->invocation_id, u);
642
97e7d748
MS
643 if (u->job) {
644 Job *j = u->job;
645 job_uninstall(j);
646 job_free(j);
647 }
964e0949 648
e0209d83
MS
649 if (u->nop_job) {
650 Job *j = u->nop_job;
651 job_uninstall(j);
652 job_free(j);
653 }
654
f6173cb9 655 for (UnitDependency d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
ac155bb8 656 bidi_set_free(u, u->dependencies[d]);
964e0949 657
4c591f39
MK
658 /* A unit is being dropped from the tree, make sure our family is realized properly. Do this after we
659 * detach the unit from slice tree in order to eliminate its effect on controller masks. */
f23ba94d 660 if (UNIT_ISSET(u->slice))
4c591f39 661 unit_add_family_to_cgroup_realize_queue(UNIT_DEREF(u->slice));
fb46fca7 662
adefcf28
LP
663 if (u->on_console)
664 manager_unref_console(u->manager);
665
efdb0237 666 unit_release_cgroup(u);
72673e86 667
d3070fbd
LP
668 if (!MANAGER_IS_RELOADING(u->manager))
669 unit_unlink_state_files(u);
670
00d9ef85
LP
671 unit_unref_uid_gid(u, false);
672
5269eb6b 673 (void) manager_update_failed_units(u->manager, u, false);
db785129 674 set_remove(u->manager->startup_units, u);
f755e3b7 675
a911bb9a
LP
676 unit_unwatch_all_pids(u);
677
702a2d8f 678 unit_ref_unset(&u->slice);
7f7d01ed
ZJS
679 while (u->refs_by_target)
680 unit_ref_unset(u->refs_by_target);
57020a3a 681
ac155bb8 682 if (u->type != _UNIT_TYPE_INVALID)
71fda00f 683 LIST_REMOVE(units_by_type, u->manager->units_by_type[u->type], u);
ef734fd6 684
ac155bb8 685 if (u->in_load_queue)
71fda00f 686 LIST_REMOVE(load_queue, u->manager->load_queue, u);
87f0e418 687
ac155bb8 688 if (u->in_dbus_queue)
71fda00f 689 LIST_REMOVE(dbus_queue, u->manager->dbus_unit_queue, u);
c1e1601e 690
a2d72e26 691 if (u->in_gc_queue)
c5a97ed1 692 LIST_REMOVE(gc_queue, u->manager->gc_unit_queue, u);
701cc384 693
91a6073e
LP
694 if (u->in_cgroup_realize_queue)
695 LIST_REMOVE(cgroup_realize_queue, u->manager->cgroup_realize_queue, u);
87f0e418 696
09e24654
LP
697 if (u->in_cgroup_empty_queue)
698 LIST_REMOVE(cgroup_empty_queue, u->manager->cgroup_empty_queue, u);
699
1bdf2790
ZJS
700 if (u->in_cleanup_queue)
701 LIST_REMOVE(cleanup_queue, u->manager->cleanup_queue, u);
adefcf28 702
19496554
MS
703 if (u->in_target_deps_queue)
704 LIST_REMOVE(target_deps_queue, u->manager->target_deps_queue, u);
705
a3c1168a
LP
706 if (u->in_stop_when_unneeded_queue)
707 LIST_REMOVE(stop_when_unneeded_queue, u->manager->stop_when_unneeded_queue, u);
708
6a48d82f
DM
709 safe_close(u->ip_accounting_ingress_map_fd);
710 safe_close(u->ip_accounting_egress_map_fd);
72673e86 711
6a48d82f
DM
712 safe_close(u->ipv4_allow_map_fd);
713 safe_close(u->ipv6_allow_map_fd);
714 safe_close(u->ipv4_deny_map_fd);
715 safe_close(u->ipv6_deny_map_fd);
d3070fbd 716
6a48d82f 717 bpf_program_unref(u->ip_bpf_ingress);
aa2b6f1d 718 bpf_program_unref(u->ip_bpf_ingress_installed);
6a48d82f 719 bpf_program_unref(u->ip_bpf_egress);
aa2b6f1d 720 bpf_program_unref(u->ip_bpf_egress_installed);
00d9ef85 721
fab34748
KL
722 set_free(u->ip_bpf_custom_ingress);
723 set_free(u->ip_bpf_custom_egress);
724 set_free(u->ip_bpf_custom_ingress_installed);
725 set_free(u->ip_bpf_custom_egress_installed);
726
084c7007
RG
727 bpf_program_unref(u->bpf_device_control_installed);
728
a946fa9b
ZJS
729 condition_free_list(u->conditions);
730 condition_free_list(u->asserts);
f755e3b7 731
ac155bb8 732 free(u->description);
49dbfa7b 733 strv_free(u->documentation);
ac155bb8 734 free(u->fragment_path);
1b64d026 735 free(u->source_path);
ae7a7182 736 strv_free(u->dropin_paths);
ac155bb8 737 free(u->instance);
87f0e418 738
f189ab18 739 free(u->job_timeout_reboot_arg);
6bf0f408
LP
740 free(u->reboot_arg);
741
4562c355
ZJS
742 set_free_free(u->aliases);
743 free(u->id);
744
87f0e418
LP
745 free(u);
746}
747
d9e45bc3
MS
748FreezerState unit_freezer_state(Unit *u) {
749 assert(u);
750
751 return u->freezer_state;
752}
753
754int unit_freezer_state_kernel(Unit *u, FreezerState *ret) {
755 char *values[1] = {};
756 int r;
757
758 assert(u);
759
760 r = cg_get_keyed_attribute(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, "cgroup.events",
761 STRV_MAKE("frozen"), values);
762 if (r < 0)
763 return r;
764
765 r = _FREEZER_STATE_INVALID;
766
767 if (values[0]) {
768 if (streq(values[0], "0"))
769 r = FREEZER_RUNNING;
770 else if (streq(values[0], "1"))
771 r = FREEZER_FROZEN;
772 }
773
774 free(values[0]);
775 *ret = r;
776
777 return 0;
778}
779
87f0e418
LP
780UnitActiveState unit_active_state(Unit *u) {
781 assert(u);
782
ac155bb8 783 if (u->load_state == UNIT_MERGED)
6124958c
LP
784 return unit_active_state(unit_follow_merge(u));
785
786 /* After a reload it might happen that a unit is not correctly
787 * loaded but still has a process around. That's why we won't
fdf20a31 788 * shortcut failed loading to UNIT_INACTIVE_FAILED. */
87f0e418
LP
789
790 return UNIT_VTABLE(u)->active_state(u);
791}
792
10a94420
LP
793const char* unit_sub_state_to_string(Unit *u) {
794 assert(u);
795
796 return UNIT_VTABLE(u)->sub_state_to_string(u);
797}
798
eef85c4a 799static int hashmap_complete_move(Hashmap **s, Hashmap **other) {
23a177ef
LP
800 assert(s);
801 assert(other);
87f0e418 802
23a177ef 803 if (!*other)
7c0b05e5 804 return 0;
87f0e418 805
eef85c4a
LP
806 if (*s)
807 return hashmap_move(*s, *other);
ae2a15bc
LP
808 else
809 *s = TAKE_PTR(*other);
7c0b05e5
MS
810
811 return 0;
23a177ef 812}
87f0e418 813
7c0b05e5 814static int merge_names(Unit *u, Unit *other) {
4562c355 815 char *name;
7c0b05e5 816 int r;
87f0e418 817
23a177ef
LP
818 assert(u);
819 assert(other);
820
4562c355 821 r = unit_add_alias(u, other->id);
7c0b05e5
MS
822 if (r < 0)
823 return r;
23a177ef 824
4562c355
ZJS
825 r = set_move(u->aliases, other->aliases);
826 if (r < 0) {
827 set_remove(u->aliases, other->id);
828 return r;
829 }
23a177ef 830
4562c355
ZJS
831 TAKE_PTR(other->id);
832 other->aliases = set_free_free(other->aliases);
23a177ef 833
90e74a66 834 SET_FOREACH(name, u->aliases)
4562c355 835 assert_se(hashmap_replace(u->manager->units, name, u) == 0);
7c0b05e5
MS
836
837 return 0;
87f0e418
LP
838}
839
09a65f92
MS
840static int reserve_dependencies(Unit *u, Unit *other, UnitDependency d) {
841 unsigned n_reserve;
842
843 assert(u);
844 assert(other);
845 assert(d < _UNIT_DEPENDENCY_MAX);
846
847 /*
848 * If u does not have this dependency set allocated, there is no need
f131770b 849 * to reserve anything. In that case other's set will be transferred
09a65f92
MS
850 * as a whole to u by complete_move().
851 */
852 if (!u->dependencies[d])
853 return 0;
854
855 /* merge_dependencies() will skip a u-on-u dependency */
eef85c4a 856 n_reserve = hashmap_size(other->dependencies[d]) - !!hashmap_get(other->dependencies[d], u);
09a65f92 857
eef85c4a 858 return hashmap_reserve(u->dependencies[d], n_reserve);
09a65f92
MS
859}
860
d1fab3fe 861static void merge_dependencies(Unit *u, Unit *other, const char *other_id, UnitDependency d) {
23a177ef 862 Unit *back;
eef85c4a 863 void *v;
87f0e418 864 int r;
23a177ef 865
eef85c4a
LP
866 /* Merges all dependencies of type 'd' of the unit 'other' into the deps of the unit 'u' */
867
23a177ef
LP
868 assert(u);
869 assert(other);
870 assert(d < _UNIT_DEPENDENCY_MAX);
871
5238e957 872 /* Fix backwards pointers. Let's iterate through all dependent units of the other unit. */
90e74a66 873 HASHMAP_FOREACH_KEY(v, back, other->dependencies[d])
eef85c4a 874
f6173cb9
ZJS
875 /* Let's now iterate through the dependencies of that dependencies of the other units,
876 * looking for pointers back, and let's fix them up, to instead point to 'u'. */
877 for (UnitDependency k = 0; k < _UNIT_DEPENDENCY_MAX; k++)
e66047ff 878 if (back == u) {
eef85c4a
LP
879 /* Do not add dependencies between u and itself. */
880 if (hashmap_remove(back->dependencies[k], other))
f2341e0a 881 maybe_warn_about_dependency(u, other_id, k);
e66047ff 882 } else {
f6173cb9 883 UnitDependencyInfo di_u, di_other;
eef85c4a
LP
884
885 /* Let's drop this dependency between "back" and "other", and let's create it between
886 * "back" and "u" instead. Let's merge the bit masks of the dependency we are moving,
887 * and any such dependency which might already exist */
888
889 di_other.data = hashmap_get(back->dependencies[k], other);
890 if (!di_other.data)
891 continue; /* dependency isn't set, let's try the next one */
892
893 di_u.data = hashmap_get(back->dependencies[k], u);
894
f6173cb9 895 UnitDependencyInfo di_merged = {
eef85c4a
LP
896 .origin_mask = di_u.origin_mask | di_other.origin_mask,
897 .destination_mask = di_u.destination_mask | di_other.destination_mask,
898 };
899
900 r = hashmap_remove_and_replace(back->dependencies[k], other, u, di_merged.data);
901 if (r < 0)
902 log_warning_errno(r, "Failed to remove/replace: back=%s other=%s u=%s: %m", back->id, other_id, u->id);
903 assert(r >= 0);
904
905 /* assert_se(hashmap_remove_and_replace(back->dependencies[k], other, u, di_merged.data) >= 0); */
e66047ff 906 }
23a177ef 907
e66047ff 908 /* Also do not move dependencies on u to itself */
eef85c4a 909 back = hashmap_remove(other->dependencies[d], u);
d1fab3fe 910 if (back)
f2341e0a 911 maybe_warn_about_dependency(u, other_id, d);
e66047ff 912
7c0b05e5 913 /* The move cannot fail. The caller must have performed a reservation. */
eef85c4a 914 assert_se(hashmap_complete_move(&u->dependencies[d], &other->dependencies[d]) == 0);
23a177ef 915
eef85c4a 916 other->dependencies[d] = hashmap_free(other->dependencies[d]);
23a177ef
LP
917}
918
919int unit_merge(Unit *u, Unit *other) {
d1fab3fe 920 const char *other_id = NULL;
09a65f92 921 int r;
87f0e418
LP
922
923 assert(u);
924 assert(other);
ac155bb8
MS
925 assert(u->manager == other->manager);
926 assert(u->type != _UNIT_TYPE_INVALID);
87f0e418 927
cc916967
LP
928 other = unit_follow_merge(other);
929
23a177ef
LP
930 if (other == u)
931 return 0;
932
ac155bb8 933 if (u->type != other->type)
9e2f7c11
LP
934 return -EINVAL;
935
8a993b61 936 if (!unit_type_may_alias(u->type)) /* Merging only applies to unit names that support aliases */
934e749e
LP
937 return -EEXIST;
938
ec2ce0c5 939 if (!IN_SET(other->load_state, UNIT_STUB, UNIT_NOT_FOUND))
23a177ef 940 return -EEXIST;
87f0e418 941
d383acad
ZJS
942 if (!streq_ptr(u->instance, other->instance))
943 return -EINVAL;
944
ac155bb8 945 if (other->job)
819e213f
LP
946 return -EEXIST;
947
e0209d83
MS
948 if (other->nop_job)
949 return -EEXIST;
950
fdf20a31 951 if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other)))
819e213f
LP
952 return -EEXIST;
953
d1fab3fe
ZJS
954 if (other->id)
955 other_id = strdupa(other->id);
956
09a65f92 957 /* Make reservations to ensure merge_dependencies() won't fail */
f6173cb9 958 for (UnitDependency d = 0; d < _UNIT_DEPENDENCY_MAX; d++) {
09a65f92
MS
959 r = reserve_dependencies(u, other, d);
960 /*
961 * We don't rollback reservations if we fail. We don't have
962 * a way to undo reservations. A reservation is not a leak.
963 */
964 if (r < 0)
965 return r;
966 }
967
87f0e418 968 /* Merge names */
7c0b05e5
MS
969 r = merge_names(u, other);
970 if (r < 0)
971 return r;
87f0e418 972
57020a3a 973 /* Redirect all references */
7f7d01ed
ZJS
974 while (other->refs_by_target)
975 unit_ref_set(other->refs_by_target, other->refs_by_target->source, u);
57020a3a 976
87f0e418 977 /* Merge dependencies */
f6173cb9 978 for (UnitDependency d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
d1fab3fe 979 merge_dependencies(u, other, other_id, d);
87f0e418 980
ac155bb8
MS
981 other->load_state = UNIT_MERGED;
982 other->merged_into = u;
23a177ef 983
3616a49c
LP
984 /* If there is still some data attached to the other node, we
985 * don't need it anymore, and can free it. */
ac155bb8 986 if (other->load_state != UNIT_STUB)
3616a49c
LP
987 if (UNIT_VTABLE(other)->done)
988 UNIT_VTABLE(other)->done(other);
989
990 unit_add_to_dbus_queue(u);
23a177ef
LP
991 unit_add_to_cleanup_queue(other);
992
993 return 0;
994}
995
996int unit_merge_by_name(Unit *u, const char *name) {
934e749e 997 _cleanup_free_ char *s = NULL;
23a177ef 998 Unit *other;
9e2f7c11 999 int r;
23a177ef 1000
e8630e69
ZJS
1001 /* Either add name to u, or if a unit with name already exists, merge it with u.
1002 * If name is a template, do the same for name@instance, where instance is u's instance. */
1003
23a177ef
LP
1004 assert(u);
1005 assert(name);
1006
7410616c 1007 if (unit_name_is_valid(name, UNIT_NAME_TEMPLATE)) {
ac155bb8 1008 if (!u->instance)
9e2f7c11
LP
1009 return -EINVAL;
1010
7410616c
LP
1011 r = unit_name_replace_instance(name, u->instance, &s);
1012 if (r < 0)
1013 return r;
9e2f7c11
LP
1014
1015 name = s;
1016 }
1017
c2756a68 1018 other = manager_get_unit(u->manager, name);
7410616c
LP
1019 if (other)
1020 return unit_merge(u, other);
23a177ef 1021
7410616c 1022 return unit_add_name(u, name);
23a177ef
LP
1023}
1024
1025Unit* unit_follow_merge(Unit *u) {
1026 assert(u);
1027
ac155bb8
MS
1028 while (u->load_state == UNIT_MERGED)
1029 assert_se(u = u->merged_into);
23a177ef
LP
1030
1031 return u;
1032}
1033
1034int unit_add_exec_dependencies(Unit *u, ExecContext *c) {
1035 int r;
1036
1037 assert(u);
1038 assert(c);
1039
e1e74614 1040 if (c->working_directory && !c->working_directory_missing_ok) {
eef85c4a 1041 r = unit_require_mounts_for(u, c->working_directory, UNIT_DEPENDENCY_FILE);
36be24c8
ZJS
1042 if (r < 0)
1043 return r;
1044 }
1045
1046 if (c->root_directory) {
eef85c4a 1047 r = unit_require_mounts_for(u, c->root_directory, UNIT_DEPENDENCY_FILE);
36be24c8
ZJS
1048 if (r < 0)
1049 return r;
1050 }
1051
915e6d16 1052 if (c->root_image) {
eef85c4a 1053 r = unit_require_mounts_for(u, c->root_image, UNIT_DEPENDENCY_FILE);
915e6d16
LP
1054 if (r < 0)
1055 return r;
1056 }
1057
12375b95 1058 for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++) {
ada5e276
YW
1059 if (!u->manager->prefix[dt])
1060 continue;
1061
12375b95 1062 char **dp;
ada5e276
YW
1063 STRV_FOREACH(dp, c->directories[dt].paths) {
1064 _cleanup_free_ char *p;
1065
657ee2d8 1066 p = path_join(u->manager->prefix[dt], *dp);
ada5e276
YW
1067 if (!p)
1068 return -ENOMEM;
1069
eef85c4a 1070 r = unit_require_mounts_for(u, p, UNIT_DEPENDENCY_FILE);
ada5e276
YW
1071 if (r < 0)
1072 return r;
1073 }
1074 }
1075
463d0d15 1076 if (!MANAGER_IS_SYSTEM(u->manager))
b46a529c
LP
1077 return 0;
1078
f3b7a79b
LP
1079 /* For the following three directory types we need write access, and /var/ is possibly on the root
1080 * fs. Hence order after systemd-remount-fs.service, to ensure things are writable. */
1081 if (!strv_isempty(c->directories[EXEC_DIRECTORY_STATE].paths) ||
1082 !strv_isempty(c->directories[EXEC_DIRECTORY_CACHE].paths) ||
1083 !strv_isempty(c->directories[EXEC_DIRECTORY_LOGS].paths)) {
1084 r = unit_add_dependency_by_name(u, UNIT_AFTER, SPECIAL_REMOUNT_FS_SERVICE, true, UNIT_DEPENDENCY_FILE);
1085 if (r < 0)
1086 return r;
1087 }
1088
b46a529c 1089 if (c->private_tmp) {
d71f0505
LP
1090 const char *p;
1091
1092 FOREACH_STRING(p, "/tmp", "/var/tmp") {
eef85c4a 1093 r = unit_require_mounts_for(u, p, UNIT_DEPENDENCY_FILE);
d71f0505
LP
1094 if (r < 0)
1095 return r;
1096 }
b46a529c 1097
35d8c19a 1098 r = unit_add_dependency_by_name(u, UNIT_AFTER, SPECIAL_TMPFILES_SETUP_SERVICE, true, UNIT_DEPENDENCY_FILE);
b46a529c
LP
1099 if (r < 0)
1100 return r;
1101 }
1102
33b58dfb
LP
1103 if (c->root_image) {
1104 /* We need to wait for /dev/loopX to appear when doing RootImage=, hence let's add an
1105 * implicit dependency on udev */
1106
1107 r = unit_add_dependency_by_name(u, UNIT_AFTER, SPECIAL_UDEVD_SERVICE, true, UNIT_DEPENDENCY_FILE);
1108 if (r < 0)
1109 return r;
1110 }
1111
52c239d7
LB
1112 if (!IN_SET(c->std_output,
1113 EXEC_OUTPUT_JOURNAL, EXEC_OUTPUT_JOURNAL_AND_CONSOLE,
f3dc6af2 1114 EXEC_OUTPUT_KMSG, EXEC_OUTPUT_KMSG_AND_CONSOLE) &&
52c239d7
LB
1115 !IN_SET(c->std_error,
1116 EXEC_OUTPUT_JOURNAL, EXEC_OUTPUT_JOURNAL_AND_CONSOLE,
f3dc6af2 1117 EXEC_OUTPUT_KMSG, EXEC_OUTPUT_KMSG_AND_CONSOLE) &&
91dd5f7c 1118 !c->log_namespace)
23a177ef
LP
1119 return 0;
1120
91dd5f7c
LP
1121 /* If syslog or kernel logging is requested (or log namespacing is), make sure our own logging daemon
1122 * is run first. */
1123
1124 if (c->log_namespace) {
dc5437c7 1125 _cleanup_free_ char *socket_unit = NULL, *varlink_socket_unit = NULL;
23a177ef 1126
91dd5f7c
LP
1127 r = unit_name_build_from_type("systemd-journald", c->log_namespace, UNIT_SOCKET, &socket_unit);
1128 if (r < 0)
1129 return r;
1130
1131 r = unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_REQUIRES, socket_unit, true, UNIT_DEPENDENCY_FILE);
1132 if (r < 0)
1133 return r;
dc5437c7
LP
1134
1135 r = unit_name_build_from_type("systemd-journald-varlink", c->log_namespace, UNIT_SOCKET, &varlink_socket_unit);
1136 if (r < 0)
1137 return r;
1138
1139 r = unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_REQUIRES, varlink_socket_unit, true, UNIT_DEPENDENCY_FILE);
1140 if (r < 0)
1141 return r;
91dd5f7c
LP
1142 } else
1143 r = unit_add_dependency_by_name(u, UNIT_AFTER, SPECIAL_JOURNALD_SOCKET, true, UNIT_DEPENDENCY_FILE);
b46a529c
LP
1144 if (r < 0)
1145 return r;
23a177ef 1146
87f0e418
LP
1147 return 0;
1148}
1149
87f0e418
LP
1150const char *unit_description(Unit *u) {
1151 assert(u);
1152
ac155bb8
MS
1153 if (u->description)
1154 return u->description;
87f0e418 1155
ac155bb8 1156 return strna(u->id);
87f0e418
LP
1157}
1158
2a8f53c6
ZJS
1159const char *unit_status_string(Unit *u) {
1160 assert(u);
1161
1162 if (u->manager->status_unit_format == STATUS_UNIT_FORMAT_NAME && u->id)
1163 return u->id;
1164
1165 return unit_description(u);
1166}
1167
eef85c4a
LP
1168static void print_unit_dependency_mask(FILE *f, const char *kind, UnitDependencyMask mask, bool *space) {
1169 const struct {
1170 UnitDependencyMask mask;
1171 const char *name;
1172 } table[] = {
1173 { UNIT_DEPENDENCY_FILE, "file" },
1174 { UNIT_DEPENDENCY_IMPLICIT, "implicit" },
1175 { UNIT_DEPENDENCY_DEFAULT, "default" },
1176 { UNIT_DEPENDENCY_UDEV, "udev" },
1177 { UNIT_DEPENDENCY_PATH, "path" },
1178 { UNIT_DEPENDENCY_MOUNTINFO_IMPLICIT, "mountinfo-implicit" },
1179 { UNIT_DEPENDENCY_MOUNTINFO_DEFAULT, "mountinfo-default" },
1180 { UNIT_DEPENDENCY_PROC_SWAP, "proc-swap" },
1181 };
eef85c4a
LP
1182
1183 assert(f);
1184 assert(kind);
1185 assert(space);
1186
12375b95 1187 for (size_t i = 0; i < ELEMENTSOF(table); i++) {
eef85c4a
LP
1188
1189 if (mask == 0)
1190 break;
1191
d94a24ca 1192 if (FLAGS_SET(mask, table[i].mask)) {
eef85c4a
LP
1193 if (*space)
1194 fputc(' ', f);
1195 else
1196 *space = true;
1197
1198 fputs(kind, f);
1199 fputs("-", f);
1200 fputs(table[i].name, f);
1201
1202 mask &= ~table[i].mask;
1203 }
1204 }
1205
1206 assert(mask == 0);
1207}
1208
87f0e418 1209void unit_dump(Unit *u, FILE *f, const char *prefix) {
49dbfa7b 1210 char *t, **j;
47be870b 1211 const char *prefix2;
8d5e5931 1212 char timestamp[5][FORMAT_TIMESTAMP_MAX], timespan[FORMAT_TIMESPAN_MAX];
a7f241db 1213 Unit *following;
eeaedb7c 1214 _cleanup_set_free_ Set *following_set = NULL;
02638280
LP
1215 CGroupMask m;
1216 int r;
87f0e418
LP
1217
1218 assert(u);
ac155bb8 1219 assert(u->type >= 0);
87f0e418 1220
4c940960 1221 prefix = strempty(prefix);
63c372cb 1222 prefix2 = strjoina(prefix, "\t");
87f0e418
LP
1223
1224 fprintf(f,
0121d1f2
ZJS
1225 "%s-> Unit %s:\n",
1226 prefix, u->id);
1227
90e74a66 1228 SET_FOREACH(t, u->aliases)
4562c355 1229 fprintf(f, "%s\tAlias: %s\n", prefix, t);
0121d1f2
ZJS
1230
1231 fprintf(f,
87f0e418 1232 "%s\tDescription: %s\n"
9e2f7c11 1233 "%s\tInstance: %s\n"
87f0e418 1234 "%s\tUnit Load State: %s\n"
2fad8195 1235 "%s\tUnit Active State: %s\n"
b895d155 1236 "%s\tState Change Timestamp: %s\n"
173e3821 1237 "%s\tInactive Exit Timestamp: %s\n"
2fad8195 1238 "%s\tActive Enter Timestamp: %s\n"
701cc384 1239 "%s\tActive Exit Timestamp: %s\n"
173e3821 1240 "%s\tInactive Enter Timestamp: %s\n"
f2f725e5 1241 "%s\tMay GC: %s\n"
9444b1f2 1242 "%s\tNeed Daemon Reload: %s\n"
c2756a68 1243 "%s\tTransient: %s\n"
f5869324 1244 "%s\tPerpetual: %s\n"
5afe510c 1245 "%s\tGarbage Collection Mode: %s\n"
4ad49000
LP
1246 "%s\tSlice: %s\n"
1247 "%s\tCGroup: %s\n"
aae7e17f 1248 "%s\tCGroup realized: %s\n",
87f0e418 1249 prefix, unit_description(u),
ac155bb8
MS
1250 prefix, strna(u->instance),
1251 prefix, unit_load_state_to_string(u->load_state),
2fad8195 1252 prefix, unit_active_state_to_string(unit_active_state(u)),
8d5e5931
ZJS
1253 prefix, strna(format_timestamp(timestamp[0], sizeof(timestamp[0]), u->state_change_timestamp.realtime)),
1254 prefix, strna(format_timestamp(timestamp[1], sizeof(timestamp[1]), u->inactive_exit_timestamp.realtime)),
1255 prefix, strna(format_timestamp(timestamp[2], sizeof(timestamp[2]), u->active_enter_timestamp.realtime)),
1256 prefix, strna(format_timestamp(timestamp[3], sizeof(timestamp[3]), u->active_exit_timestamp.realtime)),
1257 prefix, strna(format_timestamp(timestamp[4], sizeof(timestamp[4]), u->inactive_enter_timestamp.realtime)),
f2f725e5 1258 prefix, yes_no(unit_may_gc(u)),
9444b1f2 1259 prefix, yes_no(unit_need_daemon_reload(u)),
c2756a68 1260 prefix, yes_no(u->transient),
f5869324 1261 prefix, yes_no(u->perpetual),
5afe510c 1262 prefix, collect_mode_to_string(u->collect_mode),
4ad49000
LP
1263 prefix, strna(unit_slice_name(u)),
1264 prefix, strna(u->cgroup_path),
aae7e17f
FB
1265 prefix, yes_no(u->cgroup_realized));
1266
1267 if (u->cgroup_realized_mask != 0) {
1268 _cleanup_free_ char *s = NULL;
1269 (void) cg_mask_to_string(u->cgroup_realized_mask, &s);
02638280
LP
1270 fprintf(f, "%s\tCGroup realized mask: %s\n", prefix, strnull(s));
1271 }
0adf88b6 1272
02638280
LP
1273 if (u->cgroup_enabled_mask != 0) {
1274 _cleanup_free_ char *s = NULL;
1275 (void) cg_mask_to_string(u->cgroup_enabled_mask, &s);
1276 fprintf(f, "%s\tCGroup enabled mask: %s\n", prefix, strnull(s));
1277 }
0adf88b6 1278
02638280
LP
1279 m = unit_get_own_mask(u);
1280 if (m != 0) {
1281 _cleanup_free_ char *s = NULL;
1282 (void) cg_mask_to_string(m, &s);
1283 fprintf(f, "%s\tCGroup own mask: %s\n", prefix, strnull(s));
aae7e17f 1284 }
0adf88b6 1285
02638280
LP
1286 m = unit_get_members_mask(u);
1287 if (m != 0) {
aae7e17f 1288 _cleanup_free_ char *s = NULL;
02638280 1289 (void) cg_mask_to_string(m, &s);
aae7e17f
FB
1290 fprintf(f, "%s\tCGroup members mask: %s\n", prefix, strnull(s));
1291 }
0301abf4 1292
0adf88b6
LP
1293 m = unit_get_delegate_mask(u);
1294 if (m != 0) {
1295 _cleanup_free_ char *s = NULL;
1296 (void) cg_mask_to_string(m, &s);
1297 fprintf(f, "%s\tCGroup delegate mask: %s\n", prefix, strnull(s));
1298 }
1299
4b58153d
LP
1300 if (!sd_id128_is_null(u->invocation_id))
1301 fprintf(f, "%s\tInvocation ID: " SD_ID128_FORMAT_STR "\n",
1302 prefix, SD_ID128_FORMAT_VAL(u->invocation_id));
1303
49dbfa7b
LP
1304 STRV_FOREACH(j, u->documentation)
1305 fprintf(f, "%s\tDocumentation: %s\n", prefix, *j);
1306
eeaedb7c
LP
1307 following = unit_following(u);
1308 if (following)
ac155bb8 1309 fprintf(f, "%s\tFollowing: %s\n", prefix, following->id);
8fe914ec 1310
eeaedb7c
LP
1311 r = unit_following_set(u, &following_set);
1312 if (r >= 0) {
1313 Unit *other;
1314
90e74a66 1315 SET_FOREACH(other, following_set)
eeaedb7c
LP
1316 fprintf(f, "%s\tFollowing Set Member: %s\n", prefix, other->id);
1317 }
1318
ac155bb8
MS
1319 if (u->fragment_path)
1320 fprintf(f, "%s\tFragment Path: %s\n", prefix, u->fragment_path);
23a177ef 1321
1b64d026
LP
1322 if (u->source_path)
1323 fprintf(f, "%s\tSource Path: %s\n", prefix, u->source_path);
1324
ae7a7182 1325 STRV_FOREACH(j, u->dropin_paths)
2875e22b 1326 fprintf(f, "%s\tDropIn Path: %s\n", prefix, *j);
ae7a7182 1327
e7dfbb4e
LP
1328 if (u->failure_action != EMERGENCY_ACTION_NONE)
1329 fprintf(f, "%s\tFailure Action: %s\n", prefix, emergency_action_to_string(u->failure_action));
7af67e9a
LP
1330 if (u->failure_action_exit_status >= 0)
1331 fprintf(f, "%s\tFailure Action Exit Status: %i\n", prefix, u->failure_action_exit_status);
e7dfbb4e
LP
1332 if (u->success_action != EMERGENCY_ACTION_NONE)
1333 fprintf(f, "%s\tSuccess Action: %s\n", prefix, emergency_action_to_string(u->success_action));
7af67e9a
LP
1334 if (u->success_action_exit_status >= 0)
1335 fprintf(f, "%s\tSuccess Action Exit Status: %i\n", prefix, u->success_action_exit_status);
e7dfbb4e 1336
36c16a7c 1337 if (u->job_timeout != USEC_INFINITY)
2fa4092c 1338 fprintf(f, "%s\tJob Timeout: %s\n", prefix, format_timespan(timespan, sizeof(timespan), u->job_timeout, 0));
faf919f1 1339
87a47f99
LN
1340 if (u->job_timeout_action != EMERGENCY_ACTION_NONE)
1341 fprintf(f, "%s\tJob Timeout Action: %s\n", prefix, emergency_action_to_string(u->job_timeout_action));
f189ab18
LP
1342
1343 if (u->job_timeout_reboot_arg)
1344 fprintf(f, "%s\tJob Timeout Reboot Argument: %s\n", prefix, u->job_timeout_reboot_arg);
1345
59fccdc5
LP
1346 condition_dump_list(u->conditions, f, prefix, condition_type_to_string);
1347 condition_dump_list(u->asserts, f, prefix, assert_type_to_string);
52661efd 1348
ac155bb8 1349 if (dual_timestamp_is_set(&u->condition_timestamp))
2791a8f8
LP
1350 fprintf(f,
1351 "%s\tCondition Timestamp: %s\n"
1352 "%s\tCondition Result: %s\n",
8d5e5931 1353 prefix, strna(format_timestamp(timestamp[0], sizeof(timestamp[0]), u->condition_timestamp.realtime)),
ac155bb8 1354 prefix, yes_no(u->condition_result));
2791a8f8 1355
59fccdc5
LP
1356 if (dual_timestamp_is_set(&u->assert_timestamp))
1357 fprintf(f,
1358 "%s\tAssert Timestamp: %s\n"
1359 "%s\tAssert Result: %s\n",
8d5e5931 1360 prefix, strna(format_timestamp(timestamp[0], sizeof(timestamp[0]), u->assert_timestamp.realtime)),
59fccdc5
LP
1361 prefix, yes_no(u->assert_result));
1362
f6173cb9 1363 for (UnitDependency d = 0; d < _UNIT_DEPENDENCY_MAX; d++) {
eef85c4a 1364 UnitDependencyInfo di;
87f0e418
LP
1365 Unit *other;
1366
90e74a66 1367 HASHMAP_FOREACH_KEY(di.data, other, u->dependencies[d]) {
eef85c4a
LP
1368 bool space = false;
1369
1370 fprintf(f, "%s\t%s: %s (", prefix, unit_dependency_to_string(d), other->id);
1371
1372 print_unit_dependency_mask(f, "origin", di.origin_mask, &space);
1373 print_unit_dependency_mask(f, "destination", di.destination_mask, &space);
1374
1375 fputs(")\n", f);
1376 }
87f0e418
LP
1377 }
1378
eef85c4a
LP
1379 if (!hashmap_isempty(u->requires_mounts_for)) {
1380 UnitDependencyInfo di;
1381 const char *path;
1382
90e74a66 1383 HASHMAP_FOREACH_KEY(di.data, path, u->requires_mounts_for) {
eef85c4a 1384 bool space = false;
7c8fa05c 1385
eef85c4a 1386 fprintf(f, "%s\tRequiresMountsFor: %s (", prefix, path);
7c8fa05c 1387
eef85c4a
LP
1388 print_unit_dependency_mask(f, "origin", di.origin_mask, &space);
1389 print_unit_dependency_mask(f, "destination", di.destination_mask, &space);
1390
1391 fputs(")\n", f);
1392 }
7c8fa05c
LP
1393 }
1394
ac155bb8 1395 if (u->load_state == UNIT_LOADED) {
ab1f0633 1396
b0650475 1397 fprintf(f,
a40eb732 1398 "%s\tStopWhenUnneeded: %s\n"
b5e9dba8
LP
1399 "%s\tRefuseManualStart: %s\n"
1400 "%s\tRefuseManualStop: %s\n"
222ae6a8 1401 "%s\tDefaultDependencies: %s\n"
d420282b 1402 "%s\tOnFailureJobMode: %s\n"
36b4a7ba 1403 "%s\tIgnoreOnIsolate: %s\n",
ac155bb8
MS
1404 prefix, yes_no(u->stop_when_unneeded),
1405 prefix, yes_no(u->refuse_manual_start),
1406 prefix, yes_no(u->refuse_manual_stop),
1407 prefix, yes_no(u->default_dependencies),
d420282b 1408 prefix, job_mode_to_string(u->on_failure_job_mode),
36b4a7ba 1409 prefix, yes_no(u->ignore_on_isolate));
ac155bb8 1410
23a177ef
LP
1411 if (UNIT_VTABLE(u)->dump)
1412 UNIT_VTABLE(u)->dump(u, f, prefix2);
b0650475 1413
ac155bb8 1414 } else if (u->load_state == UNIT_MERGED)
b0650475
LP
1415 fprintf(f,
1416 "%s\tMerged into: %s\n",
ac155bb8
MS
1417 prefix, u->merged_into->id);
1418 else if (u->load_state == UNIT_ERROR)
4bbccb02 1419 fprintf(f, "%s\tLoad Error Code: %s\n", prefix, strerror_safe(u->load_error));
8821a00f 1420
12375b95 1421 for (const char *n = sd_bus_track_first(u->bus_track); n; n = sd_bus_track_next(u->bus_track))
05a98afd 1422 fprintf(f, "%s\tBus Ref: %s\n", prefix, n);
87f0e418 1423
ac155bb8
MS
1424 if (u->job)
1425 job_dump(u->job, f, prefix2);
87f0e418 1426
e0209d83
MS
1427 if (u->nop_job)
1428 job_dump(u->nop_job, f, prefix2);
87f0e418
LP
1429}
1430
1431/* Common implementation for multiple backends */
c3620770 1432int unit_load_fragment_and_dropin(Unit *u, bool fragment_required) {
23a177ef
LP
1433 int r;
1434
1435 assert(u);
23a177ef 1436
e48614c4 1437 /* Load a .{service,socket,...} file */
4ad49000
LP
1438 r = unit_load_fragment(u);
1439 if (r < 0)
23a177ef
LP
1440 return r;
1441
c3620770
ZJS
1442 if (u->load_state == UNIT_STUB) {
1443 if (fragment_required)
1444 return -ENOENT;
1445
1446 u->load_state = UNIT_LOADED;
1447 }
23a177ef 1448
9e4ea9cc
ZJS
1449 /* Load drop-in directory data. If u is an alias, we might be reloading the
1450 * target unit needlessly. But we cannot be sure which drops-ins have already
1451 * been loaded and which not, at least without doing complicated book-keeping,
1452 * so let's always reread all drop-ins. */
c9e06956
ZJS
1453 r = unit_load_dropin(unit_follow_merge(u));
1454 if (r < 0)
1455 return r;
1456
1457 if (u->source_path) {
1458 struct stat st;
1459
1460 if (stat(u->source_path, &st) >= 0)
1461 u->source_mtime = timespec_load(&st.st_mtim);
1462 else
1463 u->source_mtime = 0;
1464 }
1465
1466 return 0;
23a177ef
LP
1467}
1468
19496554
MS
1469void unit_add_to_target_deps_queue(Unit *u) {
1470 Manager *m = u->manager;
1471
1472 assert(u);
1473
1474 if (u->in_target_deps_queue)
1475 return;
1476
1477 LIST_PREPEND(target_deps_queue, m->target_deps_queue, u);
1478 u->in_target_deps_queue = true;
1479}
1480
bba34eed 1481int unit_add_default_target_dependency(Unit *u, Unit *target) {
98bc2000
LP
1482 assert(u);
1483 assert(target);
1484
ac155bb8 1485 if (target->type != UNIT_TARGET)
98bc2000
LP
1486 return 0;
1487
35b8ca3a 1488 /* Only add the dependency if both units are loaded, so that
bba34eed 1489 * that loop check below is reliable */
ac155bb8
MS
1490 if (u->load_state != UNIT_LOADED ||
1491 target->load_state != UNIT_LOADED)
bba34eed
LP
1492 return 0;
1493
21256a2b
LP
1494 /* If either side wants no automatic dependencies, then let's
1495 * skip this */
ac155bb8
MS
1496 if (!u->default_dependencies ||
1497 !target->default_dependencies)
21256a2b
LP
1498 return 0;
1499
98bc2000 1500 /* Don't create loops */
eef85c4a 1501 if (hashmap_get(target->dependencies[UNIT_BEFORE], u))
98bc2000
LP
1502 return 0;
1503
eef85c4a 1504 return unit_add_dependency(target, UNIT_AFTER, u, true, UNIT_DEPENDENCY_DEFAULT);
98bc2000
LP
1505}
1506
e954c9cf
LP
1507static int unit_add_slice_dependencies(Unit *u) {
1508 assert(u);
b81884e7 1509
35b7ff80 1510 if (!UNIT_HAS_CGROUP_CONTEXT(u))
e954c9cf
LP
1511 return 0;
1512
eef85c4a
LP
1513 /* Slice units are implicitly ordered against their parent slices (as this relationship is encoded in the
1514 name), while all other units are ordered based on configuration (as in their case Slice= configures the
1515 relationship). */
f6173cb9 1516 UnitDependencyMask mask = u->type == UNIT_SLICE ? UNIT_DEPENDENCY_IMPLICIT : UNIT_DEPENDENCY_FILE;
eef85c4a 1517
e954c9cf 1518 if (UNIT_ISSET(u->slice))
eef85c4a 1519 return unit_add_two_dependencies(u, UNIT_AFTER, UNIT_REQUIRES, UNIT_DEREF(u->slice), true, mask);
e954c9cf 1520
8c8da0e0 1521 if (unit_has_name(u, SPECIAL_ROOT_SLICE))
d1fab3fe
ZJS
1522 return 0;
1523
5a724170 1524 return unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_REQUIRES, SPECIAL_ROOT_SLICE, true, mask);
98bc2000
LP
1525}
1526
e954c9cf 1527static int unit_add_mount_dependencies(Unit *u) {
eef85c4a
LP
1528 UnitDependencyInfo di;
1529 const char *path;
9588bc32
LP
1530 int r;
1531
1532 assert(u);
1533
90e74a66 1534 HASHMAP_FOREACH_KEY(di.data, path, u->requires_mounts_for) {
eef85c4a 1535 char prefix[strlen(path) + 1];
9588bc32 1536
eef85c4a 1537 PATH_FOREACH_PREFIX_MORE(prefix, path) {
c7c89abb 1538 _cleanup_free_ char *p = NULL;
9588bc32
LP
1539 Unit *m;
1540
c7c89abb 1541 r = unit_name_from_path(prefix, ".mount", &p);
9588bc32
LP
1542 if (r < 0)
1543 return r;
c7c89abb
FB
1544
1545 m = manager_get_unit(u->manager, p);
1546 if (!m) {
1547 /* Make sure to load the mount unit if
1548 * it exists. If so the dependencies
1549 * on this unit will be added later
1550 * during the loading of the mount
1551 * unit. */
1552 (void) manager_load_unit_prepare(u->manager, p, NULL, NULL, &m);
9588bc32 1553 continue;
c7c89abb 1554 }
9588bc32
LP
1555 if (m == u)
1556 continue;
1557
1558 if (m->load_state != UNIT_LOADED)
1559 continue;
1560
eef85c4a 1561 r = unit_add_dependency(u, UNIT_AFTER, m, true, di.origin_mask);
9588bc32
LP
1562 if (r < 0)
1563 return r;
1564
1565 if (m->fragment_path) {
eef85c4a 1566 r = unit_add_dependency(u, UNIT_REQUIRES, m, true, di.origin_mask);
9588bc32
LP
1567 if (r < 0)
1568 return r;
1569 }
1570 }
1571 }
1572
1573 return 0;
1574}
1575
95ae05c0
WC
1576static int unit_add_startup_units(Unit *u) {
1577 CGroupContext *c;
95ae05c0
WC
1578
1579 c = unit_get_cgroup_context(u);
db785129
LP
1580 if (!c)
1581 return 0;
1582
d53d9474 1583 if (c->startup_cpu_shares == CGROUP_CPU_SHARES_INVALID &&
13c31542 1584 c->startup_io_weight == CGROUP_WEIGHT_INVALID &&
d53d9474 1585 c->startup_blockio_weight == CGROUP_BLKIO_WEIGHT_INVALID)
db785129
LP
1586 return 0;
1587
de7fef4b 1588 return set_ensure_put(&u->manager->startup_units, NULL, u);
95ae05c0
WC
1589}
1590
87f0e418
LP
1591int unit_load(Unit *u) {
1592 int r;
1593
1594 assert(u);
1595
ac155bb8 1596 if (u->in_load_queue) {
71fda00f 1597 LIST_REMOVE(load_queue, u->manager->load_queue, u);
ac155bb8 1598 u->in_load_queue = false;
87f0e418
LP
1599 }
1600
ac155bb8 1601 if (u->type == _UNIT_TYPE_INVALID)
e537352b
LP
1602 return -EINVAL;
1603
ac155bb8 1604 if (u->load_state != UNIT_STUB)
87f0e418
LP
1605 return 0;
1606
4f4afc88 1607 if (u->transient_file) {
66fa4bdd
LP
1608 /* Finalize transient file: if this is a transient unit file, as soon as we reach unit_load() the setup
1609 * is complete, hence let's synchronize the unit file we just wrote to disk. */
1610
4f4afc88
LP
1611 r = fflush_and_check(u->transient_file);
1612 if (r < 0)
1613 goto fail;
1614
50fb00b7 1615 u->transient_file = safe_fclose(u->transient_file);
f76707da 1616 u->fragment_mtime = now(CLOCK_REALTIME);
4f4afc88
LP
1617 }
1618
c3784a7d
ZJS
1619 r = UNIT_VTABLE(u)->load(u);
1620 if (r < 0)
23a177ef 1621 goto fail;
c3784a7d
ZJS
1622
1623 assert(u->load_state != UNIT_STUB);
23a177ef 1624
7c8fa05c 1625 if (u->load_state == UNIT_LOADED) {
19496554 1626 unit_add_to_target_deps_queue(u);
e954c9cf
LP
1627
1628 r = unit_add_slice_dependencies(u);
1629 if (r < 0)
1630 goto fail;
c2756a68 1631
e954c9cf 1632 r = unit_add_mount_dependencies(u);
7c8fa05c 1633 if (r < 0)
c2756a68 1634 goto fail;
7c8fa05c 1635
95ae05c0
WC
1636 r = unit_add_startup_units(u);
1637 if (r < 0)
1638 goto fail;
1639
eef85c4a 1640 if (u->on_failure_job_mode == JOB_ISOLATE && hashmap_size(u->dependencies[UNIT_ON_FAILURE]) > 1) {
f2341e0a 1641 log_unit_error(u, "More than one OnFailure= dependencies specified but OnFailureJobMode=isolate set. Refusing.");
6f40aa45 1642 r = -ENOEXEC;
c2756a68
LP
1643 goto fail;
1644 }
bc432dc7 1645
a2df3ea4
MK
1646 if (u->job_running_timeout != USEC_INFINITY && u->job_running_timeout > u->job_timeout)
1647 log_unit_warning(u, "JobRunningTimeoutSec= is greater than JobTimeoutSec=, it has no effect.");
1648
5af88058
LP
1649 /* We finished loading, let's ensure our parents recalculate the members mask */
1650 unit_invalidate_cgroup_members_masks(u);
f68319bb
LP
1651 }
1652
ac155bb8 1653 assert((u->load_state != UNIT_MERGED) == !u->merged_into);
23a177ef
LP
1654
1655 unit_add_to_dbus_queue(unit_follow_merge(u));
701cc384 1656 unit_add_to_gc_queue(u);
87f0e418 1657
87f0e418
LP
1658 return 0;
1659
1660fail:
81be2388
ZJS
1661 /* We convert ENOEXEC errors to the UNIT_BAD_SETTING load state here. Configuration parsing code
1662 * should hence return ENOEXEC to ensure units are placed in this state after loading. */
c4555ad8
LP
1663
1664 u->load_state = u->load_state == UNIT_STUB ? UNIT_NOT_FOUND :
1665 r == -ENOEXEC ? UNIT_BAD_SETTING :
1666 UNIT_ERROR;
ac155bb8 1667 u->load_error = r;
c4555ad8 1668
c149d2b4
ZJS
1669 /* Record the timestamp on the cache, so that if the cache gets updated between now and the next time
1670 * an attempt is made to load this unit, we know we need to check again. */
7233e91a 1671 if (u->load_state == UNIT_NOT_FOUND)
c2911d48 1672 u->fragment_not_found_timestamp_hash = u->manager->unit_cache_timestamp_hash;
7233e91a 1673
c1e1601e 1674 unit_add_to_dbus_queue(u);
9a46fc3b 1675 unit_add_to_gc_queue(u);
23a177ef 1676
c4555ad8 1677 return log_unit_debug_errno(u, r, "Failed to load configuration: %m");
87f0e418
LP
1678}
1679
f9f88198
YW
1680_printf_(7, 8)
1681static int log_unit_internal(void *userdata, int level, int error, const char *file, int line, const char *func, const char *format, ...) {
1682 Unit *u = userdata;
1683 va_list ap;
1684 int r;
49365733 1685
f9f88198
YW
1686 va_start(ap, format);
1687 if (u)
1688 r = log_object_internalv(level, error, file, line, func,
1689 u->manager->unit_log_field,
1690 u->id,
1691 u->manager->invocation_log_field,
1692 u->invocation_id_string,
1693 format, ap);
1694 else
1695 r = log_internalv(level, error, file, line, func, format, ap);
1696 va_end(ap);
49365733 1697
f9f88198 1698 return r;
49365733
LP
1699}
1700
97a3f4ee 1701static bool unit_test_condition(Unit *u) {
a0b191b7
LP
1702 _cleanup_strv_free_ char **env = NULL;
1703 int r;
1704
90bbc946
LP
1705 assert(u);
1706
ac155bb8 1707 dual_timestamp_get(&u->condition_timestamp);
90bbc946 1708
a0b191b7
LP
1709 r = manager_get_effective_environment(u->manager, &env);
1710 if (r < 0) {
1711 log_unit_error_errno(u, r, "Failed to determine effective environment: %m");
1712 u->condition_result = CONDITION_ERROR;
1713 } else
1714 u->condition_result = condition_test_list(
1715 u->conditions,
1716 env,
1717 condition_type_to_string,
1718 log_unit_internal,
1719 u);
e18f8852 1720
a0b191b7 1721 unit_add_to_dbus_queue(u);
ac155bb8 1722 return u->condition_result;
90bbc946
LP
1723}
1724
97a3f4ee 1725static bool unit_test_assert(Unit *u) {
a0b191b7
LP
1726 _cleanup_strv_free_ char **env = NULL;
1727 int r;
1728
59fccdc5
LP
1729 assert(u);
1730
1731 dual_timestamp_get(&u->assert_timestamp);
59fccdc5 1732
a0b191b7
LP
1733 r = manager_get_effective_environment(u->manager, &env);
1734 if (r < 0) {
1735 log_unit_error_errno(u, r, "Failed to determine effective environment: %m");
1736 u->assert_result = CONDITION_ERROR;
1737 } else
1738 u->assert_result = condition_test_list(
1739 u->asserts,
1740 env,
1741 assert_type_to_string,
1742 log_unit_internal,
1743 u);
e18f8852 1744
a0b191b7 1745 unit_add_to_dbus_queue(u);
59fccdc5
LP
1746 return u->assert_result;
1747}
1748
5bcf34eb 1749void unit_status_printf(Unit *u, StatusType status_type, const char *status, const char *unit_status_msg_format) {
5b262f74
LP
1750 const char *d;
1751
2a8f53c6 1752 d = unit_status_string(u);
5b262f74
LP
1753 if (log_get_show_color())
1754 d = strjoina(ANSI_HIGHLIGHT, d, ANSI_NORMAL);
1755
df446f96 1756 DISABLE_WARNING_FORMAT_NONLITERAL;
5bcf34eb 1757 manager_status_printf(u->manager, status_type, status, unit_status_msg_format, d);
df446f96
LP
1758 REENABLE_WARNING;
1759}
1760
97a3f4ee 1761int unit_test_start_limit(Unit *u) {
429926e9
TR
1762 const char *reason;
1763
6bf0f408
LP
1764 assert(u);
1765
7bf081a1 1766 if (ratelimit_below(&u->start_ratelimit)) {
6bf0f408
LP
1767 u->start_limit_hit = false;
1768 return 0;
1769 }
1770
1771 log_unit_warning(u, "Start request repeated too quickly.");
1772 u->start_limit_hit = true;
1773
429926e9
TR
1774 reason = strjoina("unit ", u->id, " failed");
1775
36c4dc08
LP
1776 emergency_action(u->manager, u->start_limit_action,
1777 EMERGENCY_ACTION_IS_WATCHDOG|EMERGENCY_ACTION_WARN,
1778 u->reboot_arg, -1, reason);
1779
1780 return -ECANCELED;
6bf0f408
LP
1781}
1782
c891efaf 1783bool unit_shall_confirm_spawn(Unit *u) {
631b676b 1784 assert(u);
c891efaf
FB
1785
1786 if (manager_is_confirm_spawn_disabled(u->manager))
1787 return false;
1788
1789 /* For some reasons units remaining in the same process group
1790 * as PID 1 fail to acquire the console even if it's not used
1791 * by any process. So skip the confirmation question for them. */
1792 return !unit_get_exec_context(u)->same_pgrp;
1793}
1794
631b676b
LP
1795static bool unit_verify_deps(Unit *u) {
1796 Unit *other;
eef85c4a 1797 void *v;
631b676b
LP
1798
1799 assert(u);
1800
1801 /* Checks whether all BindsTo= dependencies of this unit are fulfilled — if they are also combined with
1802 * After=. We do not check Requires= or Requisite= here as they only should have an effect on the job
1803 * processing, but do not have any effect afterwards. We don't check BindsTo= dependencies that are not used in
1804 * conjunction with After= as for them any such check would make things entirely racy. */
1805
90e74a66 1806 HASHMAP_FOREACH_KEY(v, other, u->dependencies[UNIT_BINDS_TO]) {
631b676b 1807
eef85c4a 1808 if (!hashmap_contains(u->dependencies[UNIT_AFTER], other))
631b676b
LP
1809 continue;
1810
1811 if (!UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(other))) {
1812 log_unit_notice(u, "Bound to unit %s, but unit isn't active.", other->id);
1813 return false;
1814 }
1815 }
1816
1817 return true;
1818}
1819
9adb6959 1820/* Errors that aren't really errors:
6bf0f408 1821 * -EALREADY: Unit is already started.
9adb6959 1822 * -ECOMM: Condition failed
6bf0f408 1823 * -EAGAIN: An operation is already in progress. Retry later.
9adb6959
LP
1824 *
1825 * Errors that are real errors:
1826 * -EBADR: This unit type does not support starting.
2de9b979 1827 * -ECANCELED: Start limit hit, too many requests for now
6bf0f408
LP
1828 * -EPROTO: Assert failed
1829 * -EINVAL: Unit not loaded
1830 * -EOPNOTSUPP: Unit type not supported
631b676b 1831 * -ENOLINK: The necessary dependencies are not fulfilled.
d4fd1cf2 1832 * -ESTALE: This unit has been started before and can't be started a second time
a4191c9f 1833 * -ENOENT: This is a triggering unit and unit to trigger is not loaded
87f0e418
LP
1834 */
1835int unit_start(Unit *u) {
1836 UnitActiveState state;
92ab323c 1837 Unit *following;
87f0e418
LP
1838
1839 assert(u);
1840
5766aca8
LP
1841 /* If this is already started, then this will succeed. Note that this will even succeed if this unit
1842 * is not startable by the user. This is relied on to detect when we need to wait for units and when
1843 * waiting is finished. */
87f0e418
LP
1844 state = unit_active_state(u);
1845 if (UNIT_IS_ACTIVE_OR_RELOADING(state))
1846 return -EALREADY;
380dc8b0
LP
1847 if (state == UNIT_MAINTENANCE)
1848 return -EAGAIN;
87f0e418 1849
6bf0f408
LP
1850 /* Units that aren't loaded cannot be started */
1851 if (u->load_state != UNIT_LOADED)
1852 return -EINVAL;
1853
d4fd1cf2
LP
1854 /* Refuse starting scope units more than once */
1855 if (UNIT_VTABLE(u)->once_only && dual_timestamp_is_set(&u->inactive_enter_timestamp))
1856 return -ESTALE;
1857
5766aca8
LP
1858 /* If the conditions failed, don't do anything at all. If we already are activating this call might
1859 * still be useful to speed up activation in case there is some hold-off time, but we don't want to
1860 * recheck the condition in that case. */
a82e5507 1861 if (state != UNIT_ACTIVATING &&
5af6aa58 1862 !unit_test_condition(u))
5766aca8 1863 return log_unit_debug_errno(u, SYNTHETIC_ERRNO(ECOMM), "Starting requested but condition failed. Not starting unit.");
52661efd 1864
59fccdc5
LP
1865 /* If the asserts failed, fail the entire job */
1866 if (state != UNIT_ACTIVATING &&
5766aca8
LP
1867 !unit_test_assert(u))
1868 return log_unit_notice_errno(u, SYNTHETIC_ERRNO(EPROTO), "Starting requested but asserts failed.");
59fccdc5 1869
5766aca8
LP
1870 /* Units of types that aren't supported cannot be started. Note that we do this test only after the
1871 * condition checks, so that we rather return condition check errors (which are usually not
1872 * considered a true failure) than "not supported" errors (which are considered a failure).
d11a7645 1873 */
96cf3ec9 1874 if (!unit_type_supported(u->type))
d11a7645
LP
1875 return -EOPNOTSUPP;
1876
5766aca8
LP
1877 /* Let's make sure that the deps really are in order before we start this. Normally the job engine
1878 * should have taken care of this already, but let's check this here again. After all, our
1879 * dependencies might not be in effect anymore, due to a reload or due to a failed condition. */
631b676b
LP
1880 if (!unit_verify_deps(u))
1881 return -ENOLINK;
1882
92ab323c 1883 /* Forward to the main object, if we aren't it. */
52990c2e
ZJS
1884 following = unit_following(u);
1885 if (following) {
f2341e0a 1886 log_unit_debug(u, "Redirecting start request from %s to %s.", u->id, following->id);
92ab323c
LP
1887 return unit_start(following);
1888 }
1889
1890 /* If it is stopped, but we cannot start it, then fail */
1891 if (!UNIT_VTABLE(u)->start)
1892 return -EBADR;
1893
5766aca8
LP
1894 /* We don't suppress calls to ->start() here when we are already starting, to allow this request to
1895 * be used as a "hurry up" call, for example when the unit is in some "auto restart" state where it
1896 * waits for a holdoff timer to elapse before it will start again. */
87f0e418 1897
c1e1601e 1898 unit_add_to_dbus_queue(u);
d9e45bc3 1899 unit_cgroup_freezer_action(u, FREEZER_THAW);
9e58ff9c 1900
d1a34ae9 1901 return UNIT_VTABLE(u)->start(u);
87f0e418
LP
1902}
1903
1904bool unit_can_start(Unit *u) {
1905 assert(u);
1906
8ff4d2ab
LP
1907 if (u->load_state != UNIT_LOADED)
1908 return false;
1909
96cf3ec9 1910 if (!unit_type_supported(u->type))
8ff4d2ab
LP
1911 return false;
1912
d4fd1cf2
LP
1913 /* Scope units may be started only once */
1914 if (UNIT_VTABLE(u)->once_only && dual_timestamp_is_set(&u->inactive_exit_timestamp))
1915 return false;
1916
87f0e418
LP
1917 return !!UNIT_VTABLE(u)->start;
1918}
1919
2528a7a6
LP
1920bool unit_can_isolate(Unit *u) {
1921 assert(u);
1922
1923 return unit_can_start(u) &&
ac155bb8 1924 u->allow_isolate;
2528a7a6
LP
1925}
1926
87f0e418
LP
1927/* Errors:
1928 * -EBADR: This unit type does not support stopping.
1929 * -EALREADY: Unit is already stopped.
1930 * -EAGAIN: An operation is already in progress. Retry later.
1931 */
1932int unit_stop(Unit *u) {
1933 UnitActiveState state;
92ab323c 1934 Unit *following;
87f0e418
LP
1935
1936 assert(u);
1937
87f0e418 1938 state = unit_active_state(u);
fdf20a31 1939 if (UNIT_IS_INACTIVE_OR_FAILED(state))
87f0e418
LP
1940 return -EALREADY;
1941
0faacd47
LP
1942 following = unit_following(u);
1943 if (following) {
f2341e0a 1944 log_unit_debug(u, "Redirecting stop request from %s to %s.", u->id, following->id);
92ab323c
LP
1945 return unit_stop(following);
1946 }
1947
7898b0cf
LP
1948 if (!UNIT_VTABLE(u)->stop)
1949 return -EBADR;
1950
c1e1601e 1951 unit_add_to_dbus_queue(u);
d9e45bc3 1952 unit_cgroup_freezer_action(u, FREEZER_THAW);
9e58ff9c 1953
d1a34ae9 1954 return UNIT_VTABLE(u)->stop(u);
87f0e418
LP
1955}
1956
f5869324
LP
1957bool unit_can_stop(Unit *u) {
1958 assert(u);
1959
96cf3ec9 1960 if (!unit_type_supported(u->type))
f5869324
LP
1961 return false;
1962
1963 if (u->perpetual)
1964 return false;
1965
1966 return !!UNIT_VTABLE(u)->stop;
1967}
1968
87f0e418
LP
1969/* Errors:
1970 * -EBADR: This unit type does not support reloading.
1971 * -ENOEXEC: Unit is not started.
1972 * -EAGAIN: An operation is already in progress. Retry later.
1973 */
1974int unit_reload(Unit *u) {
1975 UnitActiveState state;
92ab323c 1976 Unit *following;
87f0e418
LP
1977
1978 assert(u);
1979
ac155bb8 1980 if (u->load_state != UNIT_LOADED)
6124958c
LP
1981 return -EINVAL;
1982
87f0e418
LP
1983 if (!unit_can_reload(u))
1984 return -EBADR;
1985
1986 state = unit_active_state(u);
e364ad06 1987 if (state == UNIT_RELOADING)
6255af75 1988 return -EAGAIN;
87f0e418 1989
6a371e23 1990 if (state != UNIT_ACTIVE) {
f2341e0a 1991 log_unit_warning(u, "Unit cannot be reloaded because it is inactive.");
87f0e418 1992 return -ENOEXEC;
6a371e23 1993 }
87f0e418 1994
e48614c4
ZJS
1995 following = unit_following(u);
1996 if (following) {
f2341e0a 1997 log_unit_debug(u, "Redirecting reload request from %s to %s.", u->id, following->id);
92ab323c
LP
1998 return unit_reload(following);
1999 }
2000
c1e1601e 2001 unit_add_to_dbus_queue(u);
82a2b6bb 2002
f54bcca5
JR
2003 if (!UNIT_VTABLE(u)->reload) {
2004 /* Unit doesn't have a reload function, but we need to propagate the reload anyway */
2ad2e41a 2005 unit_notify(u, unit_active_state(u), unit_active_state(u), 0);
f54bcca5
JR
2006 return 0;
2007 }
2008
d9e45bc3
MS
2009 unit_cgroup_freezer_action(u, FREEZER_THAW);
2010
d1a34ae9 2011 return UNIT_VTABLE(u)->reload(u);
87f0e418
LP
2012}
2013
2014bool unit_can_reload(Unit *u) {
2015 assert(u);
2016
f54bcca5
JR
2017 if (UNIT_VTABLE(u)->can_reload)
2018 return UNIT_VTABLE(u)->can_reload(u);
87f0e418 2019
eef85c4a 2020 if (!hashmap_isempty(u->dependencies[UNIT_PROPAGATES_RELOAD_TO]))
87f0e418
LP
2021 return true;
2022
f54bcca5 2023 return UNIT_VTABLE(u)->reload;
87f0e418
LP
2024}
2025
a3c1168a
LP
2026bool unit_is_unneeded(Unit *u) {
2027 static const UnitDependency deps[] = {
be7d9ff7 2028 UNIT_REQUIRED_BY,
084918ba 2029 UNIT_REQUISITE_OF,
be7d9ff7
LP
2030 UNIT_WANTED_BY,
2031 UNIT_BOUND_BY,
2032 };
f3bff0eb
LP
2033
2034 assert(u);
2035
ac155bb8 2036 if (!u->stop_when_unneeded)
a3c1168a 2037 return false;
f3bff0eb 2038
a3c1168a
LP
2039 /* Don't clean up while the unit is transitioning or is even inactive. */
2040 if (!UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u)))
2041 return false;
2042 if (u->job)
2043 return false;
f3bff0eb 2044
12375b95 2045 for (size_t j = 0; j < ELEMENTSOF(deps); j++) {
eef85c4a 2046 Unit *other;
eef85c4a
LP
2047 void *v;
2048
fda09318 2049 /* If a dependent unit has a job queued, is active or transitioning, or is marked for
a3c1168a 2050 * restart, then don't clean this one up. */
b81884e7 2051
90e74a66 2052 HASHMAP_FOREACH_KEY(v, other, u->dependencies[deps[j]]) {
93d4cb09 2053 if (other->job)
a3c1168a
LP
2054 return false;
2055
2056 if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other)))
2057 return false;
2058
2059 if (unit_will_restart(other))
2060 return false;
2061 }
bea355da
LP
2062 }
2063
a3c1168a
LP
2064 return true;
2065}
f3bff0eb 2066
a3c1168a
LP
2067static void check_unneeded_dependencies(Unit *u) {
2068
2069 static const UnitDependency deps[] = {
2070 UNIT_REQUIRES,
2071 UNIT_REQUISITE,
2072 UNIT_WANTS,
2073 UNIT_BINDS_TO,
2074 };
a3c1168a
LP
2075
2076 assert(u);
2077
2078 /* Add all units this unit depends on to the queue that processes StopWhenUnneeded= behaviour. */
2079
12375b95 2080 for (size_t j = 0; j < ELEMENTSOF(deps); j++) {
a3c1168a 2081 Unit *other;
a3c1168a
LP
2082 void *v;
2083
90e74a66 2084 HASHMAP_FOREACH_KEY(v, other, u->dependencies[deps[j]])
fda09318 2085 unit_submit_to_stop_when_unneeded_queue(other);
a3c1168a 2086 }
f3bff0eb
LP
2087}
2088
ff502445 2089static void unit_check_binds_to(Unit *u) {
4afd3348 2090 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
ff502445
LP
2091 bool stop = false;
2092 Unit *other;
eef85c4a 2093 void *v;
67bfdc97 2094 int r;
ff502445
LP
2095
2096 assert(u);
2097
2098 if (u->job)
2099 return;
2100
2101 if (unit_active_state(u) != UNIT_ACTIVE)
2102 return;
2103
90e74a66 2104 HASHMAP_FOREACH_KEY(v, other, u->dependencies[UNIT_BINDS_TO]) {
ff502445
LP
2105 if (other->job)
2106 continue;
13ddc3fc
ZJS
2107
2108 if (!other->coldplugged)
2109 /* We might yet create a job for the other unit… */
2110 continue;
ff502445
LP
2111
2112 if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other)))
2113 continue;
2114
2115 stop = true;
98f738b6 2116 break;
ff502445
LP
2117 }
2118
2119 if (!stop)
2120 return;
2121
595bfe7d 2122 /* If stopping a unit fails continuously we might enter a stop
67bfdc97
LP
2123 * loop here, hence stop acting on the service being
2124 * unnecessary after a while. */
7994ac1d 2125 if (!ratelimit_below(&u->auto_stop_ratelimit)) {
67bfdc97
LP
2126 log_unit_warning(u, "Unit is bound to inactive unit %s, but not stopping since we tried this too often recently.", other->id);
2127 return;
2128 }
2129
98f738b6 2130 assert(other);
f2341e0a 2131 log_unit_info(u, "Unit is bound to inactive unit %s. Stopping, too.", other->id);
ff502445
LP
2132
2133 /* A unit we need to run is gone. Sniff. Let's stop this. */
50cbaba4 2134 r = manager_add_job(u->manager, JOB_STOP, u, JOB_FAIL, NULL, &error, NULL);
67bfdc97 2135 if (r < 0)
4bd29fe5 2136 log_unit_warning_errno(u, r, "Failed to enqueue stop job, ignoring: %s", bus_error_message(&error, r));
ff502445
LP
2137}
2138
87f0e418 2139static void retroactively_start_dependencies(Unit *u) {
87f0e418 2140 Unit *other;
eef85c4a 2141 void *v;
87f0e418
LP
2142
2143 assert(u);
2144 assert(UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)));
2145
90e74a66 2146 HASHMAP_FOREACH_KEY(v, other, u->dependencies[UNIT_REQUIRES])
eef85c4a 2147 if (!hashmap_get(u->dependencies[UNIT_AFTER], other) &&
b81884e7 2148 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
50cbaba4 2149 manager_add_job(u->manager, JOB_START, other, JOB_REPLACE, NULL, NULL, NULL);
b81884e7 2150
90e74a66 2151 HASHMAP_FOREACH_KEY(v, other, u->dependencies[UNIT_BINDS_TO])
eef85c4a 2152 if (!hashmap_get(u->dependencies[UNIT_AFTER], other) &&
b81884e7 2153 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
50cbaba4 2154 manager_add_job(u->manager, JOB_START, other, JOB_REPLACE, NULL, NULL, NULL);
87f0e418 2155
90e74a66 2156 HASHMAP_FOREACH_KEY(v, other, u->dependencies[UNIT_WANTS])
eef85c4a 2157 if (!hashmap_get(u->dependencies[UNIT_AFTER], other) &&
b81884e7 2158 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
50cbaba4 2159 manager_add_job(u->manager, JOB_START, other, JOB_FAIL, NULL, NULL, NULL);
87f0e418 2160
90e74a66 2161 HASHMAP_FOREACH_KEY(v, other, u->dependencies[UNIT_CONFLICTS])
b81884e7 2162 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
50cbaba4 2163 manager_add_job(u->manager, JOB_STOP, other, JOB_REPLACE, NULL, NULL, NULL);
69dd2852 2164
90e74a66 2165 HASHMAP_FOREACH_KEY(v, other, u->dependencies[UNIT_CONFLICTED_BY])
b81884e7 2166 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
50cbaba4 2167 manager_add_job(u->manager, JOB_STOP, other, JOB_REPLACE, NULL, NULL, NULL);
87f0e418
LP
2168}
2169
2170static void retroactively_stop_dependencies(Unit *u) {
87f0e418 2171 Unit *other;
eef85c4a 2172 void *v;
87f0e418
LP
2173
2174 assert(u);
2175 assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)));
2176
b81884e7 2177 /* Pull down units which are bound to us recursively if enabled */
90e74a66 2178 HASHMAP_FOREACH_KEY(v, other, u->dependencies[UNIT_BOUND_BY])
b81884e7 2179 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
50cbaba4 2180 manager_add_job(u->manager, JOB_STOP, other, JOB_REPLACE, NULL, NULL, NULL);
cd0504d0
MS
2181}
2182
3ecaa09b 2183void unit_start_on_failure(Unit *u) {
c0daa706 2184 Unit *other;
eef85c4a 2185 void *v;
7f66b026 2186 int r;
c0daa706
LP
2187
2188 assert(u);
2189
eef85c4a 2190 if (hashmap_size(u->dependencies[UNIT_ON_FAILURE]) <= 0)
222ae6a8
LP
2191 return;
2192
f2341e0a 2193 log_unit_info(u, "Triggering OnFailure= dependencies.");
222ae6a8 2194
90e74a66 2195 HASHMAP_FOREACH_KEY(v, other, u->dependencies[UNIT_ON_FAILURE]) {
7f66b026 2196 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
222ae6a8 2197
50cbaba4 2198 r = manager_add_job(u->manager, JOB_START, other, u->on_failure_job_mode, NULL, &error, NULL);
c1b6628d 2199 if (r < 0)
7f66b026 2200 log_unit_warning_errno(u, r, "Failed to enqueue OnFailure= job, ignoring: %s", bus_error_message(&error, r));
222ae6a8 2201 }
c0daa706
LP
2202}
2203
3ecaa09b
LP
2204void unit_trigger_notify(Unit *u) {
2205 Unit *other;
eef85c4a 2206 void *v;
3ecaa09b
LP
2207
2208 assert(u);
2209
90e74a66 2210 HASHMAP_FOREACH_KEY(v, other, u->dependencies[UNIT_TRIGGERED_BY])
3ecaa09b
LP
2211 if (UNIT_VTABLE(other)->trigger_notify)
2212 UNIT_VTABLE(other)->trigger_notify(other, u);
2213}
2214
37109b85
ZJS
2215static int raise_level(int log_level, bool condition_info, bool condition_notice) {
2216 if (condition_notice && log_level > LOG_NOTICE)
2217 return LOG_NOTICE;
2218 if (condition_info && log_level > LOG_INFO)
2219 return LOG_INFO;
2220 return log_level;
2221}
2222
915b1d01 2223static int unit_log_resources(Unit *u) {
bc40a20e
LP
2224 struct iovec iovec[1 + _CGROUP_IP_ACCOUNTING_METRIC_MAX + _CGROUP_IO_ACCOUNTING_METRIC_MAX + 4];
2225 bool any_traffic = false, have_ip_accounting = false, any_io = false, have_io_accounting = false;
2226 _cleanup_free_ char *igress = NULL, *egress = NULL, *rr = NULL, *wr = NULL;
162392b7 2227 int log_level = LOG_DEBUG; /* May be raised if resources consumed over a threshold */
915b1d01 2228 size_t n_message_parts = 0, n_iovec = 0;
bc40a20e 2229 char* message_parts[1 + 2 + 2 + 1], *t;
915b1d01 2230 nsec_t nsec = NSEC_INFINITY;
915b1d01
LP
2231 int r;
2232 const char* const ip_fields[_CGROUP_IP_ACCOUNTING_METRIC_MAX] = {
2233 [CGROUP_IP_INGRESS_BYTES] = "IP_METRIC_INGRESS_BYTES",
2234 [CGROUP_IP_INGRESS_PACKETS] = "IP_METRIC_INGRESS_PACKETS",
2235 [CGROUP_IP_EGRESS_BYTES] = "IP_METRIC_EGRESS_BYTES",
2236 [CGROUP_IP_EGRESS_PACKETS] = "IP_METRIC_EGRESS_PACKETS",
2237 };
bc40a20e
LP
2238 const char* const io_fields[_CGROUP_IO_ACCOUNTING_METRIC_MAX] = {
2239 [CGROUP_IO_READ_BYTES] = "IO_METRIC_READ_BYTES",
2240 [CGROUP_IO_WRITE_BYTES] = "IO_METRIC_WRITE_BYTES",
2241 [CGROUP_IO_READ_OPERATIONS] = "IO_METRIC_READ_OPERATIONS",
2242 [CGROUP_IO_WRITE_OPERATIONS] = "IO_METRIC_WRITE_OPERATIONS",
2243 };
915b1d01
LP
2244
2245 assert(u);
2246
2247 /* Invoked whenever a unit enters failed or dead state. Logs information about consumed resources if resource
2248 * accounting was enabled for a unit. It does this in two ways: a friendly human readable string with reduced
2249 * information and the complete data in structured fields. */
2250
2251 (void) unit_get_cpu_usage(u, &nsec);
2252 if (nsec != NSEC_INFINITY) {
2253 char buf[FORMAT_TIMESPAN_MAX] = "";
2254
2255 /* Format the CPU time for inclusion in the structured log message */
2256 if (asprintf(&t, "CPU_USAGE_NSEC=%" PRIu64, nsec) < 0) {
2257 r = log_oom();
2258 goto finish;
2259 }
2260 iovec[n_iovec++] = IOVEC_MAKE_STRING(t);
2261
2262 /* Format the CPU time for inclusion in the human language message string */
2263 format_timespan(buf, sizeof(buf), nsec / NSEC_PER_USEC, USEC_PER_MSEC);
ec9d636b 2264 t = strjoin("consumed ", buf, " CPU time");
915b1d01
LP
2265 if (!t) {
2266 r = log_oom();
2267 goto finish;
2268 }
2269
2270 message_parts[n_message_parts++] = t;
37109b85
ZJS
2271
2272 log_level = raise_level(log_level,
2273 nsec > NOTICEWORTHY_CPU_NSEC,
2274 nsec > MENTIONWORTHY_CPU_NSEC);
915b1d01
LP
2275 }
2276
bc40a20e
LP
2277 for (CGroupIOAccountingMetric k = 0; k < _CGROUP_IO_ACCOUNTING_METRIC_MAX; k++) {
2278 char buf[FORMAT_BYTES_MAX] = "";
2279 uint64_t value = UINT64_MAX;
2280
2281 assert(io_fields[k]);
2282
2283 (void) unit_get_io_accounting(u, k, k > 0, &value);
2284 if (value == UINT64_MAX)
2285 continue;
2286
2287 have_io_accounting = true;
2288 if (value > 0)
2289 any_io = true;
2290
2291 /* Format IO accounting data for inclusion in the structured log message */
2292 if (asprintf(&t, "%s=%" PRIu64, io_fields[k], value) < 0) {
2293 r = log_oom();
2294 goto finish;
2295 }
2296 iovec[n_iovec++] = IOVEC_MAKE_STRING(t);
2297
2298 /* Format the IO accounting data for inclusion in the human language message string, but only
2299 * for the bytes counters (and not for the operations counters) */
2300 if (k == CGROUP_IO_READ_BYTES) {
2301 assert(!rr);
2302 rr = strjoin("read ", format_bytes(buf, sizeof(buf), value), " from disk");
2303 if (!rr) {
2304 r = log_oom();
2305 goto finish;
2306 }
2307 } else if (k == CGROUP_IO_WRITE_BYTES) {
2308 assert(!wr);
2309 wr = strjoin("written ", format_bytes(buf, sizeof(buf), value), " to disk");
2310 if (!wr) {
2311 r = log_oom();
2312 goto finish;
2313 }
2314 }
37109b85
ZJS
2315
2316 if (IN_SET(k, CGROUP_IO_READ_BYTES, CGROUP_IO_WRITE_BYTES))
2317 log_level = raise_level(log_level,
2318 value > MENTIONWORTHY_IO_BYTES,
2319 value > NOTICEWORTHY_IO_BYTES);
bc40a20e
LP
2320 }
2321
2322 if (have_io_accounting) {
2323 if (any_io) {
2324 if (rr)
2325 message_parts[n_message_parts++] = TAKE_PTR(rr);
2326 if (wr)
2327 message_parts[n_message_parts++] = TAKE_PTR(wr);
2328
2329 } else {
2330 char *k;
2331
2332 k = strdup("no IO");
2333 if (!k) {
2334 r = log_oom();
2335 goto finish;
2336 }
2337
2338 message_parts[n_message_parts++] = k;
2339 }
2340 }
2341
12375b95 2342 for (CGroupIPAccountingMetric m = 0; m < _CGROUP_IP_ACCOUNTING_METRIC_MAX; m++) {
915b1d01
LP
2343 char buf[FORMAT_BYTES_MAX] = "";
2344 uint64_t value = UINT64_MAX;
2345
2346 assert(ip_fields[m]);
2347
2348 (void) unit_get_ip_accounting(u, m, &value);
2349 if (value == UINT64_MAX)
2350 continue;
82044702
LP
2351
2352 have_ip_accounting = true;
a87b1faa
LP
2353 if (value > 0)
2354 any_traffic = true;
915b1d01
LP
2355
2356 /* Format IP accounting data for inclusion in the structured log message */
2357 if (asprintf(&t, "%s=%" PRIu64, ip_fields[m], value) < 0) {
2358 r = log_oom();
2359 goto finish;
2360 }
2361 iovec[n_iovec++] = IOVEC_MAKE_STRING(t);
2362
2363 /* Format the IP accounting data for inclusion in the human language message string, but only for the
2364 * bytes counters (and not for the packets counters) */
a87b1faa
LP
2365 if (m == CGROUP_IP_INGRESS_BYTES) {
2366 assert(!igress);
ec9d636b 2367 igress = strjoin("received ", format_bytes(buf, sizeof(buf), value), " IP traffic");
a87b1faa
LP
2368 if (!igress) {
2369 r = log_oom();
2370 goto finish;
2371 }
2372 } else if (m == CGROUP_IP_EGRESS_BYTES) {
2373 assert(!egress);
ec9d636b 2374 egress = strjoin("sent ", format_bytes(buf, sizeof(buf), value), " IP traffic");
a87b1faa
LP
2375 if (!egress) {
2376 r = log_oom();
2377 goto finish;
2378 }
2379 }
37109b85
ZJS
2380
2381 if (IN_SET(m, CGROUP_IP_INGRESS_BYTES, CGROUP_IP_EGRESS_BYTES))
2382 log_level = raise_level(log_level,
2383 value > MENTIONWORTHY_IP_BYTES,
2384 value > NOTICEWORTHY_IP_BYTES);
a87b1faa
LP
2385 }
2386
82044702
LP
2387 if (have_ip_accounting) {
2388 if (any_traffic) {
2389 if (igress)
2390 message_parts[n_message_parts++] = TAKE_PTR(igress);
2391 if (egress)
2392 message_parts[n_message_parts++] = TAKE_PTR(egress);
a87b1faa 2393
82044702
LP
2394 } else {
2395 char *k;
915b1d01 2396
82044702
LP
2397 k = strdup("no IP traffic");
2398 if (!k) {
2399 r = log_oom();
2400 goto finish;
2401 }
2402
2403 message_parts[n_message_parts++] = k;
2404 }
915b1d01
LP
2405 }
2406
2407 /* Is there any accounting data available at all? */
2408 if (n_iovec == 0) {
2409 r = 0;
2410 goto finish;
2411 }
2412
2413 if (n_message_parts == 0)
a87b1faa 2414 t = strjoina("MESSAGE=", u->id, ": Completed.");
915b1d01
LP
2415 else {
2416 _cleanup_free_ char *joined;
2417
2418 message_parts[n_message_parts] = NULL;
2419
2420 joined = strv_join(message_parts, ", ");
2421 if (!joined) {
2422 r = log_oom();
2423 goto finish;
2424 }
2425
ec9d636b 2426 joined[0] = ascii_toupper(joined[0]);
a87b1faa 2427 t = strjoina("MESSAGE=", u->id, ": ", joined, ".");
915b1d01
LP
2428 }
2429
2430 /* The following four fields we allocate on the stack or are static strings, we hence don't want to free them,
2431 * and hence don't increase n_iovec for them */
2432 iovec[n_iovec] = IOVEC_MAKE_STRING(t);
2433 iovec[n_iovec + 1] = IOVEC_MAKE_STRING("MESSAGE_ID=" SD_MESSAGE_UNIT_RESOURCES_STR);
2434
2435 t = strjoina(u->manager->unit_log_field, u->id);
2436 iovec[n_iovec + 2] = IOVEC_MAKE_STRING(t);
2437
2438 t = strjoina(u->manager->invocation_log_field, u->invocation_id_string);
2439 iovec[n_iovec + 3] = IOVEC_MAKE_STRING(t);
2440
37109b85 2441 log_struct_iovec(log_level, iovec, n_iovec + 4);
915b1d01
LP
2442 r = 0;
2443
2444finish:
12375b95 2445 for (size_t i = 0; i < n_message_parts; i++)
915b1d01
LP
2446 free(message_parts[i]);
2447
12375b95 2448 for (size_t i = 0; i < n_iovec; i++)
915b1d01
LP
2449 free(iovec[i].iov_base);
2450
2451 return r;
2452
2453}
2454
adefcf28
LP
2455static void unit_update_on_console(Unit *u) {
2456 bool b;
2457
2458 assert(u);
2459
2460 b = unit_needs_console(u);
2461 if (u->on_console == b)
2462 return;
2463
2464 u->on_console = b;
2465 if (b)
2466 manager_ref_console(u->manager);
2467 else
2468 manager_unref_console(u->manager);
adefcf28
LP
2469}
2470
6eb65e7c
LP
2471static void unit_emit_audit_start(Unit *u) {
2472 assert(u);
2473
2474 if (u->type != UNIT_SERVICE)
2475 return;
2476
2477 /* Write audit record if we have just finished starting up */
2478 manager_send_unit_audit(u->manager, u, AUDIT_SERVICE_START, true);
2479 u->in_audit = true;
2480}
2481
2482static void unit_emit_audit_stop(Unit *u, UnitActiveState state) {
2483 assert(u);
2484
2485 if (u->type != UNIT_SERVICE)
2486 return;
2487
2488 if (u->in_audit) {
2489 /* Write audit record if we have just finished shutting down */
2490 manager_send_unit_audit(u->manager, u, AUDIT_SERVICE_STOP, state == UNIT_INACTIVE);
2491 u->in_audit = false;
2492 } else {
2493 /* Hmm, if there was no start record written write it now, so that we always have a nice pair */
2494 manager_send_unit_audit(u->manager, u, AUDIT_SERVICE_START, state == UNIT_INACTIVE);
2495
2496 if (state == UNIT_INACTIVE)
2497 manager_send_unit_audit(u->manager, u, AUDIT_SERVICE_STOP, true);
2498 }
2499}
2500
16c74914
LP
2501static bool unit_process_job(Job *j, UnitActiveState ns, UnitNotifyFlags flags) {
2502 bool unexpected = false;
31cd5f63 2503 JobResult result;
16c74914
LP
2504
2505 assert(j);
2506
2507 if (j->state == JOB_WAITING)
2508
2509 /* So we reached a different state for this job. Let's see if we can run it now if it failed previously
2510 * due to EAGAIN. */
2511 job_add_to_run_queue(j);
2512
2513 /* Let's check whether the unit's new state constitutes a finished job, or maybe contradicts a running job and
2514 * hence needs to invalidate jobs. */
2515
2516 switch (j->type) {
2517
2518 case JOB_START:
2519 case JOB_VERIFY_ACTIVE:
2520
2521 if (UNIT_IS_ACTIVE_OR_RELOADING(ns))
2522 job_finish_and_invalidate(j, JOB_DONE, true, false);
2523 else if (j->state == JOB_RUNNING && ns != UNIT_ACTIVATING) {
2524 unexpected = true;
2525
31cd5f63
AZ
2526 if (UNIT_IS_INACTIVE_OR_FAILED(ns)) {
2527 if (ns == UNIT_FAILED)
2528 result = JOB_FAILED;
2529 else if (FLAGS_SET(flags, UNIT_NOTIFY_SKIP_CONDITION))
2530 result = JOB_SKIPPED;
2531 else
2532 result = JOB_DONE;
2533
2534 job_finish_and_invalidate(j, result, true, false);
2535 }
16c74914
LP
2536 }
2537
2538 break;
2539
2540 case JOB_RELOAD:
2541 case JOB_RELOAD_OR_START:
2542 case JOB_TRY_RELOAD:
2543
2544 if (j->state == JOB_RUNNING) {
2545 if (ns == UNIT_ACTIVE)
2546 job_finish_and_invalidate(j, (flags & UNIT_NOTIFY_RELOAD_FAILURE) ? JOB_FAILED : JOB_DONE, true, false);
2547 else if (!IN_SET(ns, UNIT_ACTIVATING, UNIT_RELOADING)) {
2548 unexpected = true;
2549
2550 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
2551 job_finish_and_invalidate(j, ns == UNIT_FAILED ? JOB_FAILED : JOB_DONE, true, false);
2552 }
2553 }
2554
2555 break;
2556
2557 case JOB_STOP:
2558 case JOB_RESTART:
2559 case JOB_TRY_RESTART:
2560
2561 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
2562 job_finish_and_invalidate(j, JOB_DONE, true, false);
2563 else if (j->state == JOB_RUNNING && ns != UNIT_DEACTIVATING) {
2564 unexpected = true;
2565 job_finish_and_invalidate(j, JOB_FAILED, true, false);
2566 }
2567
2568 break;
2569
2570 default:
2571 assert_not_reached("Job type unknown");
2572 }
2573
2574 return unexpected;
2575}
2576
2ad2e41a 2577void unit_notify(Unit *u, UnitActiveState os, UnitActiveState ns, UnitNotifyFlags flags) {
429926e9 2578 const char *reason;
8559b3b7 2579 Manager *m;
a096ed36 2580
87f0e418
LP
2581 assert(u);
2582 assert(os < _UNIT_ACTIVE_STATE_MAX);
2583 assert(ns < _UNIT_ACTIVE_STATE_MAX);
87f0e418 2584
8559b3b7
LP
2585 /* Note that this is called for all low-level state changes, even if they might map to the same high-level
2586 * UnitActiveState! That means that ns == os is an expected behavior here. For example: if a mount point is
2587 * remounted this function will be called too! */
87f0e418 2588
546ac4f0
MS
2589 m = u->manager;
2590
3c4832ad
LP
2591 /* Let's enqueue the change signal early. In case this unit has a job associated we want that this unit is in
2592 * the bus queue, so that any job change signal queued will force out the unit change signal first. */
2593 unit_add_to_dbus_queue(u);
2594
f755e3b7 2595 /* Update timestamps for state changes */
2c289ea8 2596 if (!MANAGER_IS_RELOADING(m)) {
a483fb59 2597 dual_timestamp_get(&u->state_change_timestamp);
173e3821 2598
bdbf9951 2599 if (UNIT_IS_INACTIVE_OR_FAILED(os) && !UNIT_IS_INACTIVE_OR_FAILED(ns))
a483fb59 2600 u->inactive_exit_timestamp = u->state_change_timestamp;
bdbf9951 2601 else if (!UNIT_IS_INACTIVE_OR_FAILED(os) && UNIT_IS_INACTIVE_OR_FAILED(ns))
a483fb59 2602 u->inactive_enter_timestamp = u->state_change_timestamp;
bdbf9951
LP
2603
2604 if (!UNIT_IS_ACTIVE_OR_RELOADING(os) && UNIT_IS_ACTIVE_OR_RELOADING(ns))
a483fb59 2605 u->active_enter_timestamp = u->state_change_timestamp;
bdbf9951 2606 else if (UNIT_IS_ACTIVE_OR_RELOADING(os) && !UNIT_IS_ACTIVE_OR_RELOADING(ns))
a483fb59 2607 u->active_exit_timestamp = u->state_change_timestamp;
bdbf9951 2608 }
87f0e418 2609
865cc19a 2610 /* Keep track of failed units */
8724defe 2611 (void) manager_update_failed_units(m, u, ns == UNIT_FAILED);
f755e3b7 2612
d3070fbd
LP
2613 /* Make sure the cgroup and state files are always removed when we become inactive */
2614 if (UNIT_IS_INACTIVE_OR_FAILED(ns)) {
efdb0237 2615 unit_prune_cgroup(u);
d3070fbd
LP
2616 unit_unlink_state_files(u);
2617 }
fb385181 2618
adefcf28 2619 unit_update_on_console(u);
7ed9f6cd 2620
2c289ea8 2621 if (!MANAGER_IS_RELOADING(m)) {
a1c7334b
LP
2622 bool unexpected;
2623
2624 /* Let's propagate state changes to the job */
2625 if (u->job)
2626 unexpected = unit_process_job(u->job, ns, flags);
2627 else
2628 unexpected = true;
f3bff0eb 2629
a1c7334b
LP
2630 /* If this state change happened without being requested by a job, then let's retroactively start or
2631 * stop dependencies. We skip that step when deserializing, since we don't want to create any
2632 * additional jobs just because something is already activated. */
bdbf9951
LP
2633
2634 if (unexpected) {
2635 if (UNIT_IS_INACTIVE_OR_FAILED(os) && UNIT_IS_ACTIVE_OR_ACTIVATING(ns))
2636 retroactively_start_dependencies(u);
2637 else if (UNIT_IS_ACTIVE_OR_ACTIVATING(os) && UNIT_IS_INACTIVE_OR_DEACTIVATING(ns))
2638 retroactively_stop_dependencies(u);
2639 }
5de9682c 2640
cd0504d0 2641 /* stop unneeded units regardless if going down was expected or not */
a3c1168a 2642 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
cd0504d0
MS
2643 check_unneeded_dependencies(u);
2644
bdbf9951 2645 if (ns != os && ns == UNIT_FAILED) {
ed77d407 2646 log_unit_debug(u, "Unit entered failed state.");
2ad2e41a
LP
2647
2648 if (!(flags & UNIT_NOTIFY_WILL_AUTO_RESTART))
2649 unit_start_on_failure(u);
cd6d0a45 2650 }
e537352b 2651
256f65d0
LP
2652 if (UNIT_IS_ACTIVE_OR_RELOADING(ns) && !UNIT_IS_ACTIVE_OR_RELOADING(os)) {
2653 /* This unit just finished starting up */
3b2775c5 2654
6eb65e7c 2655 unit_emit_audit_start(u);
546ac4f0 2656 manager_send_unit_plymouth(m, u);
256f65d0 2657 }
bdbf9951 2658
256f65d0 2659 if (UNIT_IS_INACTIVE_OR_FAILED(ns) && !UNIT_IS_INACTIVE_OR_FAILED(os)) {
915b1d01 2660 /* This unit just stopped/failed. */
256f65d0 2661
6eb65e7c 2662 unit_emit_audit_stop(u, ns);
915b1d01 2663 unit_log_resources(u);
cd6d0a45 2664 }
f278026d
LP
2665 }
2666
31dc1ca3
LP
2667 manager_recheck_journal(m);
2668 manager_recheck_dbus(m);
e63ebf71 2669
3ecaa09b 2670 unit_trigger_notify(u);
3b2775c5 2671
8724defe 2672 if (!MANAGER_IS_RELOADING(m)) {
8559b3b7 2673 /* Maybe we finished startup and are now ready for being stopped because unneeded? */
fda09318 2674 unit_submit_to_stop_when_unneeded_queue(u);
c1e1601e 2675
8559b3b7
LP
2676 /* Maybe we finished startup, but something we needed has vanished? Let's die then. (This happens when
2677 * something BindsTo= to a Type=oneshot unit, as these units go directly from starting to inactive,
ff502445
LP
2678 * without ever entering started.) */
2679 unit_check_binds_to(u);
53c35a76 2680
429926e9
TR
2681 if (os != UNIT_FAILED && ns == UNIT_FAILED) {
2682 reason = strjoina("unit ", u->id, " failed");
36c4dc08 2683 emergency_action(m, u->failure_action, 0, u->reboot_arg, unit_failure_action_exit_status(u), reason);
429926e9
TR
2684 } else if (!UNIT_IS_INACTIVE_OR_FAILED(os) && ns == UNIT_INACTIVE) {
2685 reason = strjoina("unit ", u->id, " succeeded");
36c4dc08 2686 emergency_action(m, u->success_action, 0, u->reboot_arg, unit_success_action_exit_status(u), reason);
429926e9 2687 }
ff502445
LP
2688 }
2689
701cc384 2690 unit_add_to_gc_queue(u);
87f0e418
LP
2691}
2692
f75f613d 2693int unit_watch_pid(Unit *u, pid_t pid, bool exclusive) {
62a76913 2694 int r;
a911bb9a 2695
87f0e418 2696 assert(u);
62a76913 2697 assert(pid_is_valid(pid));
87f0e418 2698
62a76913 2699 /* Watch a specific PID */
5ba6985b 2700
f75f613d
FB
2701 /* Caller might be sure that this PID belongs to this unit only. Let's take this
2702 * opportunity to remove any stalled references to this PID as they can be created
2703 * easily (when watching a process which is not our direct child). */
2704 if (exclusive)
2705 manager_unwatch_pid(u->manager, pid);
2706
d5099efc 2707 r = set_ensure_allocated(&u->pids, NULL);
5ba6985b
LP
2708 if (r < 0)
2709 return r;
2710
62a76913 2711 r = hashmap_ensure_allocated(&u->manager->watch_pids, NULL);
a911bb9a
LP
2712 if (r < 0)
2713 return r;
2714
62a76913
LP
2715 /* First try, let's add the unit keyed by "pid". */
2716 r = hashmap_put(u->manager->watch_pids, PID_TO_PTR(pid), u);
2717 if (r == -EEXIST) {
2718 Unit **array;
2719 bool found = false;
2720 size_t n = 0;
05e343b7 2721
62a76913
LP
2722 /* OK, the "pid" key is already assigned to a different unit. Let's see if the "-pid" key (which points
2723 * to an array of Units rather than just a Unit), lists us already. */
a911bb9a 2724
62a76913
LP
2725 array = hashmap_get(u->manager->watch_pids, PID_TO_PTR(-pid));
2726 if (array)
2727 for (; array[n]; n++)
2728 if (array[n] == u)
2729 found = true;
a911bb9a 2730
62a76913
LP
2731 if (found) /* Found it already? if so, do nothing */
2732 r = 0;
2733 else {
2734 Unit **new_array;
2735
2736 /* Allocate a new array */
2737 new_array = new(Unit*, n + 2);
2738 if (!new_array)
2739 return -ENOMEM;
2740
2741 memcpy_safe(new_array, array, sizeof(Unit*) * n);
2742 new_array[n] = u;
2743 new_array[n+1] = NULL;
2744
2745 /* Add or replace the old array */
2746 r = hashmap_replace(u->manager->watch_pids, PID_TO_PTR(-pid), new_array);
2747 if (r < 0) {
2748 free(new_array);
2749 return r;
2750 }
2751
2752 free(array);
2753 }
2754 } else if (r < 0)
2755 return r;
2756
2757 r = set_put(u->pids, PID_TO_PTR(pid));
2758 if (r < 0)
2759 return r;
2760
2761 return 0;
87f0e418
LP
2762}
2763
2764void unit_unwatch_pid(Unit *u, pid_t pid) {
62a76913
LP
2765 Unit **array;
2766
87f0e418 2767 assert(u);
62a76913
LP
2768 assert(pid_is_valid(pid));
2769
2770 /* First let's drop the unit in case it's keyed as "pid". */
2771 (void) hashmap_remove_value(u->manager->watch_pids, PID_TO_PTR(pid), u);
2772
2773 /* Then, let's also drop the unit, in case it's in the array keyed by -pid */
2774 array = hashmap_get(u->manager->watch_pids, PID_TO_PTR(-pid));
2775 if (array) {
62a76913 2776 /* Let's iterate through the array, dropping our own entry */
12375b95
ZJS
2777
2778 size_t m = 0;
2779 for (size_t n = 0; array[n]; n++)
62a76913
LP
2780 if (array[n] != u)
2781 array[m++] = array[n];
2782 array[m] = NULL;
2783
2784 if (m == 0) {
2785 /* The array is now empty, remove the entire entry */
20c3acfa 2786 assert_se(hashmap_remove(u->manager->watch_pids, PID_TO_PTR(-pid)) == array);
62a76913
LP
2787 free(array);
2788 }
2789 }
87f0e418 2790
fea72cc0 2791 (void) set_remove(u->pids, PID_TO_PTR(pid));
a911bb9a
LP
2792}
2793
bd44e61b
LP
2794void unit_unwatch_all_pids(Unit *u) {
2795 assert(u);
2796
2797 while (!set_isempty(u->pids))
fea72cc0 2798 unit_unwatch_pid(u, PTR_TO_PID(set_first(u->pids)));
bd44e61b 2799
efdb0237 2800 u->pids = set_free(u->pids);
a911bb9a
LP
2801}
2802
50be4f4a
LP
2803static void unit_tidy_watch_pids(Unit *u) {
2804 pid_t except1, except2;
a911bb9a
LP
2805 void *e;
2806
2807 assert(u);
2808
2809 /* Cleans dead PIDs from our list */
2810
50be4f4a
LP
2811 except1 = unit_main_pid(u);
2812 except2 = unit_control_pid(u);
2813
90e74a66 2814 SET_FOREACH(e, u->pids) {
fea72cc0 2815 pid_t pid = PTR_TO_PID(e);
a911bb9a
LP
2816
2817 if (pid == except1 || pid == except2)
2818 continue;
2819
9f5650ae 2820 if (!pid_is_unwaited(pid))
bd44e61b 2821 unit_unwatch_pid(u, pid);
a911bb9a 2822 }
87f0e418
LP
2823}
2824
50be4f4a
LP
2825static int on_rewatch_pids_event(sd_event_source *s, void *userdata) {
2826 Unit *u = userdata;
2827
2828 assert(s);
2829 assert(u);
2830
2831 unit_tidy_watch_pids(u);
2832 unit_watch_all_pids(u);
2833
2834 /* If the PID set is empty now, then let's finish this off. */
2835 unit_synthesize_cgroup_empty_event(u);
2836
2837 return 0;
2838}
2839
2840int unit_enqueue_rewatch_pids(Unit *u) {
2841 int r;
2842
2843 assert(u);
2844
2845 if (!u->cgroup_path)
2846 return -ENOENT;
2847
2848 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
2849 if (r < 0)
2850 return r;
2851 if (r > 0) /* On unified we can use proper notifications */
2852 return 0;
2853
2854 /* Enqueues a low-priority job that will clean up dead PIDs from our list of PIDs to watch and subscribe to new
2855 * PIDs that might have appeared. We do this in a delayed job because the work might be quite slow, as it
2856 * involves issuing kill(pid, 0) on all processes we watch. */
2857
2858 if (!u->rewatch_pids_event_source) {
2859 _cleanup_(sd_event_source_unrefp) sd_event_source *s = NULL;
2860
2861 r = sd_event_add_defer(u->manager->event, &s, on_rewatch_pids_event, u);
2862 if (r < 0)
2863 return log_error_errno(r, "Failed to allocate event source for tidying watched PIDs: %m");
2864
2865 r = sd_event_source_set_priority(s, SD_EVENT_PRIORITY_IDLE);
2866 if (r < 0)
28b77ab2 2867 return log_error_errno(r, "Failed to adjust priority of event source for tidying watched PIDs: %m");
50be4f4a
LP
2868
2869 (void) sd_event_source_set_description(s, "tidy-watch-pids");
2870
2871 u->rewatch_pids_event_source = TAKE_PTR(s);
2872 }
2873
2874 r = sd_event_source_set_enabled(u->rewatch_pids_event_source, SD_EVENT_ONESHOT);
2875 if (r < 0)
2876 return log_error_errno(r, "Failed to enable event source for tidying watched PIDs: %m");
2877
2878 return 0;
2879}
2880
2881void unit_dequeue_rewatch_pids(Unit *u) {
2882 int r;
2883 assert(u);
2884
2885 if (!u->rewatch_pids_event_source)
2886 return;
2887
2888 r = sd_event_source_set_enabled(u->rewatch_pids_event_source, SD_EVENT_OFF);
2889 if (r < 0)
2890 log_warning_errno(r, "Failed to disable event source for tidying watched PIDs, ignoring: %m");
2891
2892 u->rewatch_pids_event_source = sd_event_source_unref(u->rewatch_pids_event_source);
2893}
2894
87f0e418
LP
2895bool unit_job_is_applicable(Unit *u, JobType j) {
2896 assert(u);
2897 assert(j >= 0 && j < _JOB_TYPE_MAX);
2898
2899 switch (j) {
2900
2901 case JOB_VERIFY_ACTIVE:
2902 case JOB_START:
e0209d83 2903 case JOB_NOP:
f5869324 2904 /* Note that we don't check unit_can_start() here. That's because .device units and suchlike are not
86b52a39 2905 * startable by us but may appear due to external events, and it thus makes sense to permit enqueuing
f5869324 2906 * jobs for it. */
87f0e418
LP
2907 return true;
2908
f5869324
LP
2909 case JOB_STOP:
2910 /* Similar as above. However, perpetual units can never be stopped (neither explicitly nor due to
86b52a39 2911 * external events), hence it makes no sense to permit enqueuing such a request either. */
f5869324
LP
2912 return !u->perpetual;
2913
87f0e418
LP
2914 case JOB_RESTART:
2915 case JOB_TRY_RESTART:
f5869324 2916 return unit_can_stop(u) && unit_can_start(u);
87f0e418
LP
2917
2918 case JOB_RELOAD:
3282591d 2919 case JOB_TRY_RELOAD:
87f0e418
LP
2920 return unit_can_reload(u);
2921
2922 case JOB_RELOAD_OR_START:
2923 return unit_can_reload(u) && unit_can_start(u);
2924
2925 default:
2926 assert_not_reached("Invalid job type");
2927 }
2928}
2929
f2341e0a
LP
2930static void maybe_warn_about_dependency(Unit *u, const char *other, UnitDependency dependency) {
2931 assert(u);
d1fab3fe 2932
f2341e0a
LP
2933 /* Only warn about some unit types */
2934 if (!IN_SET(dependency, UNIT_CONFLICTS, UNIT_CONFLICTED_BY, UNIT_BEFORE, UNIT_AFTER, UNIT_ON_FAILURE, UNIT_TRIGGERS, UNIT_TRIGGERED_BY))
2935 return;
3f3cc397 2936
f2341e0a
LP
2937 if (streq_ptr(u->id, other))
2938 log_unit_warning(u, "Dependency %s=%s dropped", unit_dependency_to_string(dependency), u->id);
2939 else
2940 log_unit_warning(u, "Dependency %s=%s dropped, merged into %s", unit_dependency_to_string(dependency), strna(other), u->id);
d1fab3fe
ZJS
2941}
2942
eef85c4a
LP
2943static int unit_add_dependency_hashmap(
2944 Hashmap **h,
2945 Unit *other,
2946 UnitDependencyMask origin_mask,
2947 UnitDependencyMask destination_mask) {
2948
2949 UnitDependencyInfo info;
2950 int r;
2951
2952 assert(h);
2953 assert(other);
2954 assert(origin_mask < _UNIT_DEPENDENCY_MASK_FULL);
2955 assert(destination_mask < _UNIT_DEPENDENCY_MASK_FULL);
2956 assert(origin_mask > 0 || destination_mask > 0);
2957
2958 r = hashmap_ensure_allocated(h, NULL);
2959 if (r < 0)
2960 return r;
2961
2962 assert_cc(sizeof(void*) == sizeof(info));
2963
2964 info.data = hashmap_get(*h, other);
2965 if (info.data) {
2966 /* Entry already exists. Add in our mask. */
2967
d94a24ca
ZJS
2968 if (FLAGS_SET(origin_mask, info.origin_mask) &&
2969 FLAGS_SET(destination_mask, info.destination_mask))
eef85c4a
LP
2970 return 0; /* NOP */
2971
2972 info.origin_mask |= origin_mask;
2973 info.destination_mask |= destination_mask;
2974
2975 r = hashmap_update(*h, other, info.data);
2976 } else {
2977 info = (UnitDependencyInfo) {
2978 .origin_mask = origin_mask,
2979 .destination_mask = destination_mask,
2980 };
2981
2982 r = hashmap_put(*h, other, info.data);
2983 }
2984 if (r < 0)
2985 return r;
2986
2987 return 1;
2988}
2989
2990int unit_add_dependency(
2991 Unit *u,
2992 UnitDependency d,
2993 Unit *other,
2994 bool add_reference,
2995 UnitDependencyMask mask) {
87f0e418
LP
2996
2997 static const UnitDependency inverse_table[_UNIT_DEPENDENCY_MAX] = {
2998 [UNIT_REQUIRES] = UNIT_REQUIRED_BY,
87f0e418 2999 [UNIT_WANTS] = UNIT_WANTED_BY,
be7d9ff7 3000 [UNIT_REQUISITE] = UNIT_REQUISITE_OF,
7f2cddae 3001 [UNIT_BINDS_TO] = UNIT_BOUND_BY,
60649f17 3002 [UNIT_PART_OF] = UNIT_CONSISTS_OF,
be7d9ff7 3003 [UNIT_REQUIRED_BY] = UNIT_REQUIRES,
be7d9ff7 3004 [UNIT_REQUISITE_OF] = UNIT_REQUISITE,
be7d9ff7 3005 [UNIT_WANTED_BY] = UNIT_WANTS,
7f2cddae 3006 [UNIT_BOUND_BY] = UNIT_BINDS_TO,
60649f17 3007 [UNIT_CONSISTS_OF] = UNIT_PART_OF,
69dd2852
LP
3008 [UNIT_CONFLICTS] = UNIT_CONFLICTED_BY,
3009 [UNIT_CONFLICTED_BY] = UNIT_CONFLICTS,
87f0e418 3010 [UNIT_BEFORE] = UNIT_AFTER,
701cc384 3011 [UNIT_AFTER] = UNIT_BEFORE,
5de9682c 3012 [UNIT_ON_FAILURE] = _UNIT_DEPENDENCY_INVALID,
701cc384 3013 [UNIT_REFERENCES] = UNIT_REFERENCED_BY,
57020a3a
LP
3014 [UNIT_REFERENCED_BY] = UNIT_REFERENCES,
3015 [UNIT_TRIGGERS] = UNIT_TRIGGERED_BY,
4dcc1cb4 3016 [UNIT_TRIGGERED_BY] = UNIT_TRIGGERS,
7f2cddae 3017 [UNIT_PROPAGATES_RELOAD_TO] = UNIT_RELOAD_PROPAGATED_FROM,
85e9a101 3018 [UNIT_RELOAD_PROPAGATED_FROM] = UNIT_PROPAGATES_RELOAD_TO,
613b411c 3019 [UNIT_JOINS_NAMESPACE_OF] = UNIT_JOINS_NAMESPACE_OF,
87f0e418 3020 };
eef85c4a
LP
3021 Unit *original_u = u, *original_other = other;
3022 int r;
5177cb0a
RM
3023 /* Helper to know whether sending a notification is necessary or not:
3024 * if the dependency is already there, no need to notify! */
3025 bool noop = true;
87f0e418
LP
3026
3027 assert(u);
3028 assert(d >= 0 && d < _UNIT_DEPENDENCY_MAX);
87f0e418
LP
3029 assert(other);
3030
9f151f29
LP
3031 u = unit_follow_merge(u);
3032 other = unit_follow_merge(other);
3033
87f0e418
LP
3034 /* We won't allow dependencies on ourselves. We will not
3035 * consider them an error however. */
d1fab3fe 3036 if (u == other) {
eef85c4a 3037 maybe_warn_about_dependency(original_u, original_other->id, d);
87f0e418 3038 return 0;
d1fab3fe 3039 }
87f0e418 3040
b862c257
FB
3041 /* Note that ordering a device unit after a unit is permitted since it
3042 * allows to start its job running timeout at a specific time. */
3043 if (d == UNIT_BEFORE && other->type == UNIT_DEVICE) {
3044 log_unit_warning(u, "Dependency Before=%s ignored (.device units cannot be delayed)", other->id);
c80a9a33
LP
3045 return 0;
3046 }
3047
3048 if (d == UNIT_ON_FAILURE && !UNIT_VTABLE(u)->can_fail) {
3049 log_unit_warning(u, "Requested dependency OnFailure=%s ignored (%s units cannot fail).", other->id, unit_type_to_string(u->type));
3050 return 0;
3051 }
3052
3053 if (d == UNIT_TRIGGERS && !UNIT_VTABLE(u)->can_trigger)
3054 return log_unit_error_errno(u, SYNTHETIC_ERRNO(EINVAL),
3055 "Requested dependency Triggers=%s refused (%s units cannot trigger other units).", other->id, unit_type_to_string(u->type));
3056 if (d == UNIT_TRIGGERED_BY && !UNIT_VTABLE(other)->can_trigger)
3057 return log_unit_error_errno(u, SYNTHETIC_ERRNO(EINVAL),
3058 "Requested dependency TriggeredBy=%s refused (%s units cannot trigger other units).", other->id, unit_type_to_string(other->type));
3059
eef85c4a 3060 r = unit_add_dependency_hashmap(u->dependencies + d, other, mask, 0);
613b411c 3061 if (r < 0)
87f0e418 3062 return r;
5177cb0a
RM
3063 else if (r > 0)
3064 noop = false;
87f0e418 3065
eef85c4a
LP
3066 if (inverse_table[d] != _UNIT_DEPENDENCY_INVALID && inverse_table[d] != d) {
3067 r = unit_add_dependency_hashmap(other->dependencies + inverse_table[d], u, 0, mask);
613b411c
LP
3068 if (r < 0)
3069 return r;
5177cb0a
RM
3070 else if (r > 0)
3071 noop = false;
613b411c
LP
3072 }
3073
3074 if (add_reference) {
eef85c4a 3075 r = unit_add_dependency_hashmap(u->dependencies + UNIT_REFERENCES, other, mask, 0);
613b411c 3076 if (r < 0)
5de9682c 3077 return r;
5177cb0a
RM
3078 else if (r > 0)
3079 noop = false;
5de9682c 3080
eef85c4a 3081 r = unit_add_dependency_hashmap(other->dependencies + UNIT_REFERENCED_BY, u, 0, mask);
613b411c 3082 if (r < 0)
701cc384 3083 return r;
5177cb0a
RM
3084 else if (r > 0)
3085 noop = false;
613b411c 3086 }
87f0e418 3087
5177cb0a
RM
3088 if (!noop)
3089 unit_add_to_dbus_queue(u);
87f0e418
LP
3090 return 0;
3091}
0301abf4 3092
eef85c4a 3093int unit_add_two_dependencies(Unit *u, UnitDependency d, UnitDependency e, Unit *other, bool add_reference, UnitDependencyMask mask) {
2c966c03
LP
3094 int r;
3095
3096 assert(u);
3097
eef85c4a 3098 r = unit_add_dependency(u, d, other, add_reference, mask);
3f3cc397 3099 if (r < 0)
2c966c03
LP
3100 return r;
3101
eef85c4a 3102 return unit_add_dependency(u, e, other, add_reference, mask);
2c966c03
LP
3103}
3104
23e8c796 3105static int resolve_template(Unit *u, const char *name, char **buf, const char **ret) {
7410616c 3106 int r;
9e2f7c11
LP
3107
3108 assert(u);
23e8c796 3109 assert(name);
7410616c
LP
3110 assert(buf);
3111 assert(ret);
9e2f7c11 3112
7410616c
LP
3113 if (!unit_name_is_valid(name, UNIT_NAME_TEMPLATE)) {
3114 *buf = NULL;
3115 *ret = name;
3116 return 0;
9e2f7c11
LP
3117 }
3118
ac155bb8 3119 if (u->instance)
7410616c 3120 r = unit_name_replace_instance(name, u->instance, buf);
9e2f7c11 3121 else {
ae018d9b 3122 _cleanup_free_ char *i = NULL;
9e2f7c11 3123
7410616c
LP
3124 r = unit_name_to_prefix(u->id, &i);
3125 if (r < 0)
3126 return r;
9e2f7c11 3127
7410616c 3128 r = unit_name_replace_instance(name, i, buf);
9e2f7c11 3129 }
7410616c
LP
3130 if (r < 0)
3131 return r;
9e2f7c11 3132
7410616c
LP
3133 *ret = *buf;
3134 return 0;
9e2f7c11
LP
3135}
3136
35d8c19a 3137int unit_add_dependency_by_name(Unit *u, UnitDependency d, const char *name, bool add_reference, UnitDependencyMask mask) {
7410616c 3138 _cleanup_free_ char *buf = NULL;
09b6b09f
LP
3139 Unit *other;
3140 int r;
3141
9e2f7c11 3142 assert(u);
35d8c19a 3143 assert(name);
09b6b09f 3144
23e8c796 3145 r = resolve_template(u, name, &buf, &name);
7410616c
LP
3146 if (r < 0)
3147 return r;
09b6b09f 3148
35d8c19a 3149 r = manager_load_unit(u->manager, name, NULL, NULL, &other);
8afbb8e1
LP
3150 if (r < 0)
3151 return r;
9e2f7c11 3152
eef85c4a 3153 return unit_add_dependency(u, d, other, add_reference, mask);
09b6b09f
LP
3154}
3155
5a724170 3156int unit_add_two_dependencies_by_name(Unit *u, UnitDependency d, UnitDependency e, const char *name, bool add_reference, UnitDependencyMask mask) {
7410616c 3157 _cleanup_free_ char *buf = NULL;
2c966c03
LP
3158 Unit *other;
3159 int r;
2c966c03
LP
3160
3161 assert(u);
5a724170 3162 assert(name);
2c966c03 3163
23e8c796 3164 r = resolve_template(u, name, &buf, &name);
7410616c
LP
3165 if (r < 0)
3166 return r;
2c966c03 3167
5a724170 3168 r = manager_load_unit(u->manager, name, NULL, NULL, &other);
3f3cc397 3169 if (r < 0)
68eda4bd 3170 return r;
2c966c03 3171
eef85c4a 3172 return unit_add_two_dependencies(u, d, e, other, add_reference, mask);
2c966c03
LP
3173}
3174
0301abf4 3175int set_unit_path(const char *p) {
0301abf4 3176 /* This is mostly for debug purposes */
cbe46ead 3177 if (setenv("SYSTEMD_UNIT_PATH", p, 1) < 0)
26d04f86 3178 return -errno;
0301abf4
LP
3179
3180 return 0;
3181}
88066b3a 3182
ea430986 3183char *unit_dbus_path(Unit *u) {
ea430986
LP
3184 assert(u);
3185
ac155bb8 3186 if (!u->id)
04ade7d2
LP
3187 return NULL;
3188
48899192 3189 return unit_dbus_path_from_name(u->id);
ea430986
LP
3190}
3191
4b58153d
LP
3192char *unit_dbus_path_invocation_id(Unit *u) {
3193 assert(u);
3194
3195 if (sd_id128_is_null(u->invocation_id))
3196 return NULL;
3197
3198 return unit_dbus_path_from_name(u->invocation_id_string);
3199}
3200
db868d45
ZJS
3201static int unit_set_invocation_id(Unit *u, sd_id128_t id) {
3202 int r;
3203
3204 assert(u);
3205
3206 /* Set the invocation ID for this unit. If we cannot, this will not roll back, but reset the whole thing. */
3207
3208 if (sd_id128_equal(u->invocation_id, id))
3209 return 0;
3210
3211 if (!sd_id128_is_null(u->invocation_id))
3212 (void) hashmap_remove_value(u->manager->units_by_invocation_id, &u->invocation_id, u);
3213
3214 if (sd_id128_is_null(id)) {
3215 r = 0;
3216 goto reset;
3217 }
3218
3219 r = hashmap_ensure_allocated(&u->manager->units_by_invocation_id, &id128_hash_ops);
3220 if (r < 0)
3221 goto reset;
3222
3223 u->invocation_id = id;
3224 sd_id128_to_string(id, u->invocation_id_string);
3225
3226 r = hashmap_put(u->manager->units_by_invocation_id, &u->invocation_id, u);
3227 if (r < 0)
3228 goto reset;
3229
3230 return 0;
3231
3232reset:
3233 u->invocation_id = SD_ID128_NULL;
3234 u->invocation_id_string[0] = 0;
3235 return r;
3236}
3237
d79200e2
LP
3238int unit_set_slice(Unit *u, Unit *slice) {
3239 assert(u);
3240 assert(slice);
3241
3242 /* Sets the unit slice if it has not been set before. Is extra
3243 * careful, to only allow this for units that actually have a
3244 * cgroup context. Also, we don't allow to set this for slices
3245 * (since the parent slice is derived from the name). Make
3246 * sure the unit we set is actually a slice. */
3247
3248 if (!UNIT_HAS_CGROUP_CONTEXT(u))
3249 return -EOPNOTSUPP;
3250
3251 if (u->type == UNIT_SLICE)
3252 return -EINVAL;
3253
102ef982
LP
3254 if (unit_active_state(u) != UNIT_INACTIVE)
3255 return -EBUSY;
3256
d79200e2
LP
3257 if (slice->type != UNIT_SLICE)
3258 return -EINVAL;
3259
efdb0237
LP
3260 if (unit_has_name(u, SPECIAL_INIT_SCOPE) &&
3261 !unit_has_name(slice, SPECIAL_ROOT_SLICE))
3262 return -EPERM;
3263
d79200e2
LP
3264 if (UNIT_DEREF(u->slice) == slice)
3265 return 0;
3266
99e66921
TH
3267 /* Disallow slice changes if @u is already bound to cgroups */
3268 if (UNIT_ISSET(u->slice) && u->cgroup_realized)
d79200e2
LP
3269 return -EBUSY;
3270
7f7d01ed 3271 unit_ref_set(&u->slice, u, slice);
d79200e2
LP
3272 return 1;
3273}
3274
3275int unit_set_default_slice(Unit *u) {
a8833944 3276 const char *slice_name;
a016b922
LP
3277 Unit *slice;
3278 int r;
3279
3280 assert(u);
3281
9444b1f2 3282 if (UNIT_ISSET(u->slice))
a016b922
LP
3283 return 0;
3284
a8833944
LP
3285 if (u->instance) {
3286 _cleanup_free_ char *prefix = NULL, *escaped = NULL;
68eda4bd 3287
a8833944
LP
3288 /* Implicitly place all instantiated units in their
3289 * own per-template slice */
3290
7410616c
LP
3291 r = unit_name_to_prefix(u->id, &prefix);
3292 if (r < 0)
3293 return r;
a8833944
LP
3294
3295 /* The prefix is already escaped, but it might include
3296 * "-" which has a special meaning for slice units,
3297 * hence escape it here extra. */
7410616c 3298 escaped = unit_name_escape(prefix);
a8833944
LP
3299 if (!escaped)
3300 return -ENOMEM;
3301
463d0d15 3302 if (MANAGER_IS_SYSTEM(u->manager))
00e7b3c8 3303 slice_name = strjoina("system-", escaped, ".slice");
a8833944 3304 else
00e7b3c8 3305 slice_name = strjoina(escaped, ".slice");
a8833944
LP
3306 } else
3307 slice_name =
463d0d15 3308 MANAGER_IS_SYSTEM(u->manager) && !unit_has_name(u, SPECIAL_INIT_SCOPE)
a8833944
LP
3309 ? SPECIAL_SYSTEM_SLICE
3310 : SPECIAL_ROOT_SLICE;
3311
3312 r = manager_load_unit(u->manager, slice_name, NULL, NULL, &slice);
a016b922
LP
3313 if (r < 0)
3314 return r;
3315
d79200e2 3316 return unit_set_slice(u, slice);
a016b922
LP
3317}
3318
9444b1f2
LP
3319const char *unit_slice_name(Unit *u) {
3320 assert(u);
3321
3322 if (!UNIT_ISSET(u->slice))
3323 return NULL;
3324
3325 return UNIT_DEREF(u->slice)->id;
3326}
3327
f6ff8c29 3328int unit_load_related_unit(Unit *u, const char *type, Unit **_found) {
78edb35a 3329 _cleanup_free_ char *t = NULL;
f6ff8c29
LP
3330 int r;
3331
3332 assert(u);
3333 assert(type);
3334 assert(_found);
3335
7410616c
LP
3336 r = unit_name_change_suffix(u->id, type, &t);
3337 if (r < 0)
3338 return r;
3339 if (unit_has_name(u, t))
3340 return -EINVAL;
f6ff8c29 3341
ac155bb8 3342 r = manager_load_unit(u->manager, t, NULL, NULL, _found);
9e2f7c11 3343 assert(r < 0 || *_found != u);
f6ff8c29
LP
3344 return r;
3345}
3346
bbc29086 3347static int signal_name_owner_changed(sd_bus_message *message, void *userdata, sd_bus_error *error) {
fc67a943 3348 const char *new_owner;
bbc29086
DM
3349 Unit *u = userdata;
3350 int r;
3351
3352 assert(message);
3353 assert(u);
3354
fc67a943 3355 r = sd_bus_message_read(message, "sss", NULL, NULL, &new_owner);
bbc29086
DM
3356 if (r < 0) {
3357 bus_log_parse_error(r);
3358 return 0;
3359 }
3360
3361 if (UNIT_VTABLE(u)->bus_name_owner_change)
fc67a943 3362 UNIT_VTABLE(u)->bus_name_owner_change(u, empty_to_null(new_owner));
a5a8776a
MJ
3363
3364 return 0;
3365}
3366
3367static int get_name_owner_handler(sd_bus_message *message, void *userdata, sd_bus_error *error) {
3368 const sd_bus_error *e;
3369 const char *new_owner;
3370 Unit *u = userdata;
3371 int r;
3372
3373 assert(message);
3374 assert(u);
3375
3376 u->get_name_owner_slot = sd_bus_slot_unref(u->get_name_owner_slot);
3377
a5a8776a 3378 e = sd_bus_message_get_error(message);
a5a8776a 3379 if (e) {
a54654ba
LP
3380 if (!sd_bus_error_has_name(e, "org.freedesktop.DBus.Error.NameHasNoOwner"))
3381 log_unit_error(u, "Unexpected error response from GetNameOwner(): %s", e->message);
a5a8776a 3382
fc67a943
LP
3383 new_owner = NULL;
3384 } else {
3385 r = sd_bus_message_read(message, "s", &new_owner);
3386 if (r < 0)
3387 return bus_log_parse_error(r);
a5a8776a 3388
fc67a943
LP
3389 assert(!isempty(new_owner));
3390 }
a5a8776a
MJ
3391
3392 if (UNIT_VTABLE(u)->bus_name_owner_change)
fc67a943 3393 UNIT_VTABLE(u)->bus_name_owner_change(u, new_owner);
bbc29086
DM
3394
3395 return 0;
3396}
3397
9806e87d
LP
3398int unit_install_bus_match(Unit *u, sd_bus *bus, const char *name) {
3399 const char *match;
a5b07847 3400 int r;
bbc29086 3401
9806e87d
LP
3402 assert(u);
3403 assert(bus);
3404 assert(name);
bbc29086 3405
a5b07847 3406 if (u->match_bus_slot || u->get_name_owner_slot)
bbc29086
DM
3407 return -EBUSY;
3408
9806e87d 3409 match = strjoina("type='signal',"
81d62103
ZJS
3410 "sender='org.freedesktop.DBus',"
3411 "path='/org/freedesktop/DBus',"
3412 "interface='org.freedesktop.DBus',"
3413 "member='NameOwnerChanged',"
3414 "arg0='", name, "'");
bbc29086 3415
a5b07847 3416 r = sd_bus_add_match_async(bus, &u->match_bus_slot, match, signal_name_owner_changed, NULL, u);
a5a8776a
MJ
3417 if (r < 0)
3418 return r;
3419
a5b07847
LP
3420 r = sd_bus_call_method_async(
3421 bus,
3422 &u->get_name_owner_slot,
3423 "org.freedesktop.DBus",
3424 "/org/freedesktop/DBus",
3425 "org.freedesktop.DBus",
3426 "GetNameOwner",
3427 get_name_owner_handler,
3428 u,
3429 "s", name);
3430 if (r < 0) {
3431 u->match_bus_slot = sd_bus_slot_unref(u->match_bus_slot);
3432 return r;
3433 }
3434
3435 log_unit_debug(u, "Watching D-Bus name '%s'.", name);
3436 return 0;
bbc29086
DM
3437}
3438
05e343b7 3439int unit_watch_bus_name(Unit *u, const char *name) {
bbc29086
DM
3440 int r;
3441
05e343b7
LP
3442 assert(u);
3443 assert(name);
3444
3445 /* Watch a specific name on the bus. We only support one unit
3446 * watching each name for now. */
3447
bbc29086
DM
3448 if (u->manager->api_bus) {
3449 /* If the bus is already available, install the match directly.
3450 * Otherwise, just put the name in the list. bus_setup_api() will take care later. */
9806e87d 3451 r = unit_install_bus_match(u, u->manager->api_bus, name);
bbc29086 3452 if (r < 0)
8ea823b6 3453 return log_warning_errno(r, "Failed to subscribe to NameOwnerChanged signal for '%s': %m", name);
bbc29086
DM
3454 }
3455
3456 r = hashmap_put(u->manager->watch_bus, name, u);
3457 if (r < 0) {
3458 u->match_bus_slot = sd_bus_slot_unref(u->match_bus_slot);
a5b07847 3459 u->get_name_owner_slot = sd_bus_slot_unref(u->get_name_owner_slot);
bbc29086
DM
3460 return log_warning_errno(r, "Failed to put bus name to hashmap: %m");
3461 }
3462
3463 return 0;
05e343b7
LP
3464}
3465
3466void unit_unwatch_bus_name(Unit *u, const char *name) {
3467 assert(u);
3468 assert(name);
3469
8367fea5 3470 (void) hashmap_remove_value(u->manager->watch_bus, name, u);
bbc29086 3471 u->match_bus_slot = sd_bus_slot_unref(u->match_bus_slot);
a5a8776a 3472 u->get_name_owner_slot = sd_bus_slot_unref(u->get_name_owner_slot);
05e343b7
LP
3473}
3474
a16e1123
LP
3475bool unit_can_serialize(Unit *u) {
3476 assert(u);
3477
3478 return UNIT_VTABLE(u)->serialize && UNIT_VTABLE(u)->deserialize_item;
3479}
3480
d68c645b 3481static int serialize_cgroup_mask(FILE *f, const char *key, CGroupMask mask) {
8b108bd0 3482 _cleanup_free_ char *s = NULL;
d68c645b 3483 int r;
8b108bd0
FB
3484
3485 assert(f);
3486 assert(key);
3487
d68c645b
LP
3488 if (mask == 0)
3489 return 0;
3490
3491 r = cg_mask_to_string(mask, &s);
3492 if (r < 0)
3493 return log_error_errno(r, "Failed to format cgroup mask: %m");
3494
3495 return serialize_item(f, key, s);
8b108bd0
FB
3496}
3497
b82f71c7 3498static const char *const ip_accounting_metric_field[_CGROUP_IP_ACCOUNTING_METRIC_MAX] = {
6b659ed8
LP
3499 [CGROUP_IP_INGRESS_BYTES] = "ip-accounting-ingress-bytes",
3500 [CGROUP_IP_INGRESS_PACKETS] = "ip-accounting-ingress-packets",
3501 [CGROUP_IP_EGRESS_BYTES] = "ip-accounting-egress-bytes",
3502 [CGROUP_IP_EGRESS_PACKETS] = "ip-accounting-egress-packets",
3503};
3504
fbe14fc9
LP
3505static const char *const io_accounting_metric_field_base[_CGROUP_IO_ACCOUNTING_METRIC_MAX] = {
3506 [CGROUP_IO_READ_BYTES] = "io-accounting-read-bytes-base",
3507 [CGROUP_IO_WRITE_BYTES] = "io-accounting-write-bytes-base",
3508 [CGROUP_IO_READ_OPERATIONS] = "io-accounting-read-operations-base",
3509 [CGROUP_IO_WRITE_OPERATIONS] = "io-accounting-write-operations-base",
3510};
3511
3512static const char *const io_accounting_metric_field_last[_CGROUP_IO_ACCOUNTING_METRIC_MAX] = {
3513 [CGROUP_IO_READ_BYTES] = "io-accounting-read-bytes-last",
3514 [CGROUP_IO_WRITE_BYTES] = "io-accounting-write-bytes-last",
3515 [CGROUP_IO_READ_OPERATIONS] = "io-accounting-read-operations-last",
3516 [CGROUP_IO_WRITE_OPERATIONS] = "io-accounting-write-operations-last",
3517};
3518
6b78f9b4 3519int unit_serialize(Unit *u, FILE *f, FDSet *fds, bool serialize_jobs) {
a16e1123
LP
3520 int r;
3521
3522 assert(u);
3523 assert(f);
3524 assert(fds);
3525
9bdb98c5 3526 if (unit_can_serialize(u)) {
9bdb98c5 3527 r = UNIT_VTABLE(u)->serialize(u, f, fds);
613b411c
LP
3528 if (r < 0)
3529 return r;
e0209d83
MS
3530 }
3531
d68c645b 3532 (void) serialize_dual_timestamp(f, "state-change-timestamp", &u->state_change_timestamp);
a483fb59 3533
d68c645b
LP
3534 (void) serialize_dual_timestamp(f, "inactive-exit-timestamp", &u->inactive_exit_timestamp);
3535 (void) serialize_dual_timestamp(f, "active-enter-timestamp", &u->active_enter_timestamp);
3536 (void) serialize_dual_timestamp(f, "active-exit-timestamp", &u->active_exit_timestamp);
3537 (void) serialize_dual_timestamp(f, "inactive-enter-timestamp", &u->inactive_enter_timestamp);
a483fb59 3538
d68c645b
LP
3539 (void) serialize_dual_timestamp(f, "condition-timestamp", &u->condition_timestamp);
3540 (void) serialize_dual_timestamp(f, "assert-timestamp", &u->assert_timestamp);
2791a8f8 3541
ac155bb8 3542 if (dual_timestamp_is_set(&u->condition_timestamp))
d68c645b 3543 (void) serialize_bool(f, "condition-result", u->condition_result);
10717a1a 3544
59fccdc5 3545 if (dual_timestamp_is_set(&u->assert_timestamp))
d68c645b 3546 (void) serialize_bool(f, "assert-result", u->assert_result);
59fccdc5 3547
d68c645b
LP
3548 (void) serialize_bool(f, "transient", u->transient);
3549 (void) serialize_bool(f, "in-audit", u->in_audit);
fe700f46 3550
d68c645b
LP
3551 (void) serialize_bool(f, "exported-invocation-id", u->exported_invocation_id);
3552 (void) serialize_bool(f, "exported-log-level-max", u->exported_log_level_max);
3553 (void) serialize_bool(f, "exported-log-extra-fields", u->exported_log_extra_fields);
5ac1530e
ZJS
3554 (void) serialize_bool(f, "exported-log-rate-limit-interval", u->exported_log_ratelimit_interval);
3555 (void) serialize_bool(f, "exported-log-rate-limit-burst", u->exported_log_ratelimit_burst);
0e699122 3556
d68c645b 3557 (void) serialize_item_format(f, "cpu-usage-base", "%" PRIu64, u->cpu_usage_base);
fe700f46 3558 if (u->cpu_usage_last != NSEC_INFINITY)
d68c645b 3559 (void) serialize_item_format(f, "cpu-usage-last", "%" PRIu64, u->cpu_usage_last);
c2756a68 3560
afcfaa69
LP
3561 if (u->oom_kill_last > 0)
3562 (void) serialize_item_format(f, "oom-kill-last", "%" PRIu64, u->oom_kill_last);
3563
fbe14fc9
LP
3564 for (CGroupIOAccountingMetric im = 0; im < _CGROUP_IO_ACCOUNTING_METRIC_MAX; im++) {
3565 (void) serialize_item_format(f, io_accounting_metric_field_base[im], "%" PRIu64, u->io_accounting_base[im]);
3566
3567 if (u->io_accounting_last[im] != UINT64_MAX)
3568 (void) serialize_item_format(f, io_accounting_metric_field_last[im], "%" PRIu64, u->io_accounting_last[im]);
3569 }
3570
c2756a68 3571 if (u->cgroup_path)
d68c645b
LP
3572 (void) serialize_item(f, "cgroup", u->cgroup_path);
3573
3574 (void) serialize_bool(f, "cgroup-realized", u->cgroup_realized);
3575 (void) serialize_cgroup_mask(f, "cgroup-realized-mask", u->cgroup_realized_mask);
3576 (void) serialize_cgroup_mask(f, "cgroup-enabled-mask", u->cgroup_enabled_mask);
3577 (void) serialize_cgroup_mask(f, "cgroup-invalidated-mask", u->cgroup_invalidated_mask);
c2756a68 3578
00d9ef85 3579 if (uid_is_valid(u->ref_uid))
d68c645b 3580 (void) serialize_item_format(f, "ref-uid", UID_FMT, u->ref_uid);
00d9ef85 3581 if (gid_is_valid(u->ref_gid))
d68c645b 3582 (void) serialize_item_format(f, "ref-gid", GID_FMT, u->ref_gid);
00d9ef85 3583
4b58153d 3584 if (!sd_id128_is_null(u->invocation_id))
d68c645b 3585 (void) serialize_item_format(f, "invocation-id", SD_ID128_FORMAT_STR, SD_ID128_FORMAT_VAL(u->invocation_id));
4b58153d 3586
d9e45bc3
MS
3587 (void) serialize_item_format(f, "freezer-state", "%s", freezer_state_to_string(unit_freezer_state(u)));
3588
05a98afd
LP
3589 bus_track_serialize(u->bus_track, f, "ref");
3590
12375b95 3591 for (CGroupIPAccountingMetric m = 0; m < _CGROUP_IP_ACCOUNTING_METRIC_MAX; m++) {
6b659ed8
LP
3592 uint64_t v;
3593
3594 r = unit_get_ip_accounting(u, m, &v);
3595 if (r >= 0)
d68c645b 3596 (void) serialize_item_format(f, ip_accounting_metric_field[m], "%" PRIu64, v);
6b659ed8
LP
3597 }
3598
613b411c
LP
3599 if (serialize_jobs) {
3600 if (u->job) {
d68c645b 3601 fputs("job\n", f);
05a98afd 3602 job_serialize(u->job, f);
613b411c
LP
3603 }
3604
3605 if (u->nop_job) {
d68c645b 3606 fputs("job\n", f);
05a98afd 3607 job_serialize(u->nop_job, f);
613b411c
LP
3608 }
3609 }
3610
a16e1123
LP
3611 /* End marker */
3612 fputc('\n', f);
3613 return 0;
3614}
3615
b17c9620
LP
3616static int unit_deserialize_job(Unit *u, FILE *f) {
3617 _cleanup_(job_freep) Job *j = NULL;
3618 int r;
3619
3620 assert(u);
3621 assert(f);
3622
3623 j = job_new_raw(u);
3624 if (!j)
3625 return log_oom();
3626
3627 r = job_deserialize(j, f);
3628 if (r < 0)
3629 return r;
3630
3631 r = job_install_deserialized(j);
3632 if (r < 0)
3633 return r;
3634
3635 TAKE_PTR(j);
3636 return 0;
3637}
3638
a16e1123
LP
3639int unit_deserialize(Unit *u, FILE *f, FDSet *fds) {
3640 int r;
3641
3642 assert(u);
3643 assert(f);
3644 assert(fds);
3645
a16e1123 3646 for (;;) {
8948b341 3647 _cleanup_free_ char *line = NULL;
8948b341 3648 char *l, *v;
83f18c91 3649 ssize_t m;
a16e1123
LP
3650 size_t k;
3651
8948b341
LP
3652 r = read_line(f, LONG_LINE_MAX, &line);
3653 if (r < 0)
3654 return log_error_errno(r, "Failed to read serialization line: %m");
3655 if (r == 0) /* eof */
3656 break;
a16e1123
LP
3657
3658 l = strstrip(line);
8948b341 3659 if (isempty(l)) /* End marker */
a483fb59 3660 break;
a16e1123
LP
3661
3662 k = strcspn(l, "=");
3663
3664 if (l[k] == '=') {
3665 l[k] = 0;
3666 v = l+k+1;
3667 } else
3668 v = l+k;
3669
cca098b0 3670 if (streq(l, "job")) {
39a18c60 3671 if (v[0] == '\0') {
b17c9620
LP
3672 /* New-style serialized job */
3673 r = unit_deserialize_job(u, f);
3674 if (r < 0)
e0209d83 3675 return r;
b17c9620 3676 } else /* Legacy for pre-44 */
ed10fa8c 3677 log_unit_warning(u, "Update from too old systemd versions are unsupported, cannot deserialize job: %s", v);
cca098b0 3678 continue;
a483fb59 3679 } else if (streq(l, "state-change-timestamp")) {
d68c645b 3680 (void) deserialize_dual_timestamp(v, &u->state_change_timestamp);
a483fb59 3681 continue;
8aaf019b 3682 } else if (streq(l, "inactive-exit-timestamp")) {
d68c645b 3683 (void) deserialize_dual_timestamp(v, &u->inactive_exit_timestamp);
8aaf019b
LP
3684 continue;
3685 } else if (streq(l, "active-enter-timestamp")) {
d68c645b 3686 (void) deserialize_dual_timestamp(v, &u->active_enter_timestamp);
8aaf019b
LP
3687 continue;
3688 } else if (streq(l, "active-exit-timestamp")) {
d68c645b 3689 (void) deserialize_dual_timestamp(v, &u->active_exit_timestamp);
8aaf019b
LP
3690 continue;
3691 } else if (streq(l, "inactive-enter-timestamp")) {
d68c645b 3692 (void) deserialize_dual_timestamp(v, &u->inactive_enter_timestamp);
8aaf019b 3693 continue;
2791a8f8 3694 } else if (streq(l, "condition-timestamp")) {
d68c645b 3695 (void) deserialize_dual_timestamp(v, &u->condition_timestamp);
2791a8f8 3696 continue;
59fccdc5 3697 } else if (streq(l, "assert-timestamp")) {
d68c645b 3698 (void) deserialize_dual_timestamp(v, &u->assert_timestamp);
59fccdc5 3699 continue;
2791a8f8 3700 } else if (streq(l, "condition-result")) {
2791a8f8 3701
e911de99
LP
3702 r = parse_boolean(v);
3703 if (r < 0)
f2341e0a 3704 log_unit_debug(u, "Failed to parse condition result value %s, ignoring.", v);
2791a8f8 3705 else
e911de99 3706 u->condition_result = r;
efbac6d2
LP
3707
3708 continue;
c2756a68 3709
59fccdc5 3710 } else if (streq(l, "assert-result")) {
59fccdc5 3711
e911de99
LP
3712 r = parse_boolean(v);
3713 if (r < 0)
f2341e0a 3714 log_unit_debug(u, "Failed to parse assert result value %s, ignoring.", v);
59fccdc5 3715 else
e911de99 3716 u->assert_result = r;
59fccdc5
LP
3717
3718 continue;
3719
c2756a68 3720 } else if (streq(l, "transient")) {
c2756a68 3721
e911de99
LP
3722 r = parse_boolean(v);
3723 if (r < 0)
f2341e0a 3724 log_unit_debug(u, "Failed to parse transient bool %s, ignoring.", v);
c2756a68 3725 else
e911de99 3726 u->transient = r;
c2756a68
LP
3727
3728 continue;
e911de99 3729
0e699122
LP
3730 } else if (streq(l, "in-audit")) {
3731
3732 r = parse_boolean(v);
3733 if (r < 0)
3734 log_unit_debug(u, "Failed to parse in-audit bool %s, ignoring.", v);
3735 else
3736 u->in_audit = r;
3737
3738 continue;
3739
d3070fbd
LP
3740 } else if (streq(l, "exported-invocation-id")) {
3741
3742 r = parse_boolean(v);
3743 if (r < 0)
3744 log_unit_debug(u, "Failed to parse exported invocation ID bool %s, ignoring.", v);
3745 else
3746 u->exported_invocation_id = r;
3747
3748 continue;
3749
3750 } else if (streq(l, "exported-log-level-max")) {
3751
3752 r = parse_boolean(v);
3753 if (r < 0)
3754 log_unit_debug(u, "Failed to parse exported log level max bool %s, ignoring.", v);
3755 else
3756 u->exported_log_level_max = r;
3757
3758 continue;
3759
3760 } else if (streq(l, "exported-log-extra-fields")) {
3761
3762 r = parse_boolean(v);
3763 if (r < 0)
3764 log_unit_debug(u, "Failed to parse exported log extra fields bool %s, ignoring.", v);
3765 else
3766 u->exported_log_extra_fields = r;
3767
3768 continue;
3769
90fc172e
AZ
3770 } else if (streq(l, "exported-log-rate-limit-interval")) {
3771
3772 r = parse_boolean(v);
3773 if (r < 0)
3774 log_unit_debug(u, "Failed to parse exported log rate limit interval %s, ignoring.", v);
3775 else
5ac1530e 3776 u->exported_log_ratelimit_interval = r;
90fc172e
AZ
3777
3778 continue;
3779
3780 } else if (streq(l, "exported-log-rate-limit-burst")) {
3781
3782 r = parse_boolean(v);
3783 if (r < 0)
3784 log_unit_debug(u, "Failed to parse exported log rate limit burst %s, ignoring.", v);
3785 else
5ac1530e 3786 u->exported_log_ratelimit_burst = r;
90fc172e
AZ
3787
3788 continue;
3789
fe700f46 3790 } else if (STR_IN_SET(l, "cpu-usage-base", "cpuacct-usage-base")) {
5ad096b3 3791
66ebf6c0 3792 r = safe_atou64(v, &u->cpu_usage_base);
5ad096b3 3793 if (r < 0)
fe700f46
LP
3794 log_unit_debug(u, "Failed to parse CPU usage base %s, ignoring.", v);
3795
3796 continue;
3797
3798 } else if (streq(l, "cpu-usage-last")) {
3799
3800 r = safe_atou64(v, &u->cpu_usage_last);
3801 if (r < 0)
3802 log_unit_debug(u, "Failed to read CPU usage last %s, ignoring.", v);
5ad096b3 3803
0f908397 3804 continue;
4e595329 3805
afcfaa69
LP
3806 } else if (streq(l, "oom-kill-last")) {
3807
3808 r = safe_atou64(v, &u->oom_kill_last);
3809 if (r < 0)
3810 log_unit_debug(u, "Failed to read OOM kill last %s, ignoring.", v);
3811
3812 continue;
3813
e911de99 3814 } else if (streq(l, "cgroup")) {
72673e86 3815
e911de99
LP
3816 r = unit_set_cgroup_path(u, v);
3817 if (r < 0)
f2341e0a 3818 log_unit_debug_errno(u, r, "Failed to set cgroup path %s, ignoring: %m", v);
4e595329 3819
efdb0237 3820 (void) unit_watch_cgroup(u);
afcfaa69 3821 (void) unit_watch_cgroup_memory(u);
efdb0237 3822
de1d4f9b
WF
3823 continue;
3824 } else if (streq(l, "cgroup-realized")) {
3825 int b;
3826
3827 b = parse_boolean(v);
3828 if (b < 0)
3829 log_unit_debug(u, "Failed to parse cgroup-realized bool %s, ignoring.", v);
3830 else
3831 u->cgroup_realized = b;
3832
c2756a68 3833 continue;
00d9ef85 3834
8b108bd0
FB
3835 } else if (streq(l, "cgroup-realized-mask")) {
3836
3837 r = cg_mask_from_string(v, &u->cgroup_realized_mask);
3838 if (r < 0)
3839 log_unit_debug(u, "Failed to parse cgroup-realized-mask %s, ignoring.", v);
3840 continue;
3841
3842 } else if (streq(l, "cgroup-enabled-mask")) {
3843
3844 r = cg_mask_from_string(v, &u->cgroup_enabled_mask);
3845 if (r < 0)
3846 log_unit_debug(u, "Failed to parse cgroup-enabled-mask %s, ignoring.", v);
3847 continue;
3848
17f14955 3849 } else if (streq(l, "cgroup-invalidated-mask")) {
906c06f6 3850
17f14955 3851 r = cg_mask_from_string(v, &u->cgroup_invalidated_mask);
906c06f6 3852 if (r < 0)
17f14955 3853 log_unit_debug(u, "Failed to parse cgroup-invalidated-mask %s, ignoring.", v);
906c06f6
DM
3854 continue;
3855
00d9ef85
LP
3856 } else if (streq(l, "ref-uid")) {
3857 uid_t uid;
3858
3859 r = parse_uid(v, &uid);
3860 if (r < 0)
3861 log_unit_debug(u, "Failed to parse referenced UID %s, ignoring.", v);
3862 else
3863 unit_ref_uid_gid(u, uid, GID_INVALID);
3864
3865 continue;
3866
3867 } else if (streq(l, "ref-gid")) {
3868 gid_t gid;
3869
3870 r = parse_gid(v, &gid);
3871 if (r < 0)
3872 log_unit_debug(u, "Failed to parse referenced GID %s, ignoring.", v);
3873 else
3874 unit_ref_uid_gid(u, UID_INVALID, gid);
3875
5f616d5f
LP
3876 continue;
3877
05a98afd
LP
3878 } else if (streq(l, "ref")) {
3879
3880 r = strv_extend(&u->deserialized_refs, v);
3881 if (r < 0)
d68c645b 3882 return log_oom();
05a98afd 3883
4b58153d
LP
3884 continue;
3885 } else if (streq(l, "invocation-id")) {
3886 sd_id128_t id;
3887
3888 r = sd_id128_from_string(v, &id);
3889 if (r < 0)
3890 log_unit_debug(u, "Failed to parse invocation id %s, ignoring.", v);
3891 else {
3892 r = unit_set_invocation_id(u, id);
3893 if (r < 0)
3894 log_unit_warning_errno(u, r, "Failed to set invocation ID for unit: %m");
3895 }
3896
d9e45bc3
MS
3897 continue;
3898 } else if (streq(l, "freezer-state")) {
3899 FreezerState s;
3900
3901 s = freezer_state_from_string(v);
3902 if (s < 0)
3903 log_unit_debug(u, "Failed to deserialize freezer-state '%s', ignoring.", v);
3904 else
3905 u->freezer_state = s;
3906
00d9ef85 3907 continue;
8aaf019b 3908 }
cca098b0 3909
6b659ed8 3910 /* Check if this is an IP accounting metric serialization field */
83f18c91
LP
3911 m = string_table_lookup(ip_accounting_metric_field, ELEMENTSOF(ip_accounting_metric_field), l);
3912 if (m >= 0) {
6b659ed8
LP
3913 uint64_t c;
3914
3915 r = safe_atou64(v, &c);
3916 if (r < 0)
3917 log_unit_debug(u, "Failed to parse IP accounting value %s, ignoring.", v);
3918 else
3919 u->ip_accounting_extra[m] = c;
3920 continue;
3921 }
3922
fbe14fc9
LP
3923 m = string_table_lookup(io_accounting_metric_field_base, ELEMENTSOF(io_accounting_metric_field_base), l);
3924 if (m >= 0) {
3925 uint64_t c;
3926
3927 r = safe_atou64(v, &c);
3928 if (r < 0)
3929 log_unit_debug(u, "Failed to parse IO accounting base value %s, ignoring.", v);
3930 else
3931 u->io_accounting_base[m] = c;
3932 continue;
3933 }
3934
3935 m = string_table_lookup(io_accounting_metric_field_last, ELEMENTSOF(io_accounting_metric_field_last), l);
3936 if (m >= 0) {
3937 uint64_t c;
3938
3939 r = safe_atou64(v, &c);
3940 if (r < 0)
3941 log_unit_debug(u, "Failed to parse IO accounting last value %s, ignoring.", v);
3942 else
3943 u->io_accounting_last[m] = c;
3944 continue;
3945 }
3946
9bdb98c5 3947 if (unit_can_serialize(u)) {
e8a565cb
YW
3948 r = exec_runtime_deserialize_compat(u, l, v, fds);
3949 if (r < 0) {
3950 log_unit_warning(u, "Failed to deserialize runtime parameter '%s', ignoring.", l);
3951 continue;
9bdb98c5
LP
3952 }
3953
e8a565cb
YW
3954 /* Returns positive if key was handled by the call */
3955 if (r > 0)
3956 continue;
3957
9bdb98c5 3958 r = UNIT_VTABLE(u)->deserialize_item(u, l, v, fds);
613b411c 3959 if (r < 0)
f2341e0a 3960 log_unit_warning(u, "Failed to deserialize unit parameter '%s', ignoring.", l);
613b411c 3961 }
a16e1123 3962 }
a483fb59
LP
3963
3964 /* Versions before 228 did not carry a state change timestamp. In this case, take the current time. This is
3965 * useful, so that timeouts based on this timestamp don't trigger too early, and is in-line with the logic from
1f133e0d 3966 * before 228 where the base for timeouts was not persistent across reboots. */
a483fb59
LP
3967
3968 if (!dual_timestamp_is_set(&u->state_change_timestamp))
3969 dual_timestamp_get(&u->state_change_timestamp);
3970
58d83430
LP
3971 /* Let's make sure that everything that is deserialized also gets any potential new cgroup settings applied
3972 * after we are done. For that we invalidate anything already realized, so that we can realize it again. */
3973 unit_invalidate_cgroup(u, _CGROUP_MASK_ALL);
3974 unit_invalidate_cgroup_bpf(u);
3975
a483fb59 3976 return 0;
a16e1123
LP
3977}
3978
8948b341
LP
3979int unit_deserialize_skip(FILE *f) {
3980 int r;
07429866
ZJS
3981 assert(f);
3982
3983 /* Skip serialized data for this unit. We don't know what it is. */
3984
3985 for (;;) {
8948b341
LP
3986 _cleanup_free_ char *line = NULL;
3987 char *l;
07429866 3988
8948b341
LP
3989 r = read_line(f, LONG_LINE_MAX, &line);
3990 if (r < 0)
3991 return log_error_errno(r, "Failed to read serialization line: %m");
3992 if (r == 0)
3993 return 0;
07429866 3994
07429866
ZJS
3995 l = strstrip(line);
3996
3997 /* End marker */
3998 if (isempty(l))
8948b341 3999 return 1;
07429866
ZJS
4000 }
4001}
4002
d336ba9f 4003int unit_add_node_dependency(Unit *u, const char *what, UnitDependency dep, UnitDependencyMask mask) {
68eda4bd 4004 _cleanup_free_ char *e = NULL;
44b0d1fd 4005 Unit *device;
6e2ef85b
LP
4006 int r;
4007
4008 assert(u);
4009
6e2ef85b 4010 /* Adds in links to the device node that this unit is based on */
47bc12e1
LP
4011 if (isempty(what))
4012 return 0;
6e2ef85b 4013
8407a5d0 4014 if (!is_device_path(what))
6e2ef85b
LP
4015 return 0;
4016
44b0d1fd 4017 /* When device units aren't supported (such as in a container), don't create dependencies on them. */
1c2e9646 4018 if (!unit_type_supported(UNIT_DEVICE))
47bc12e1
LP
4019 return 0;
4020
7410616c
LP
4021 r = unit_name_from_path(what, ".device", &e);
4022 if (r < 0)
4023 return r;
6e2ef85b 4024
ac155bb8 4025 r = manager_load_unit(u->manager, e, NULL, NULL, &device);
6e2ef85b
LP
4026 if (r < 0)
4027 return r;
4028
ebc8968b
FB
4029 if (dep == UNIT_REQUIRES && device_shall_be_bound_by(device, u))
4030 dep = UNIT_BINDS_TO;
4031
d336ba9f
FB
4032 return unit_add_two_dependencies(u, UNIT_AFTER,
4033 MANAGER_IS_SYSTEM(u->manager) ? dep : UNIT_WANTS,
4034 device, true, mask);
6e2ef85b 4035}
a16e1123 4036
44b0d1fd
LP
4037int unit_add_blockdev_dependency(Unit *u, const char *what, UnitDependencyMask mask) {
4038 _cleanup_free_ char *escaped = NULL, *target = NULL;
4039 int r;
4040
4041 assert(u);
4042
4043 if (isempty(what))
4044 return 0;
4045
4046 if (!path_startswith(what, "/dev/"))
4047 return 0;
4048
4049 /* If we don't support devices, then also don't bother with blockdev@.target */
4050 if (!unit_type_supported(UNIT_DEVICE))
4051 return 0;
4052
4053 r = unit_name_path_escape(what, &escaped);
4054 if (r < 0)
4055 return r;
4056
4057 r = unit_name_build("blockdev", escaped, ".target", &target);
4058 if (r < 0)
4059 return r;
4060
4061 return unit_add_dependency_by_name(u, UNIT_AFTER, target, true, mask);
4062}
4063
be847e82 4064int unit_coldplug(Unit *u) {
05a98afd
LP
4065 int r = 0, q;
4066 char **i;
b49e14d5 4067 Job *uj;
cca098b0
LP
4068
4069 assert(u);
4070
f0831ed2 4071 /* Make sure we don't enter a loop, when coldplugging recursively. */
f78f265f
LP
4072 if (u->coldplugged)
4073 return 0;
4074
4075 u->coldplugged = true;
4076
05a98afd
LP
4077 STRV_FOREACH(i, u->deserialized_refs) {
4078 q = bus_unit_track_add_name(u, *i);
4079 if (q < 0 && r >= 0)
4080 r = q;
4081 }
4082 u->deserialized_refs = strv_free(u->deserialized_refs);
cca098b0 4083
05a98afd
LP
4084 if (UNIT_VTABLE(u)->coldplug) {
4085 q = UNIT_VTABLE(u)->coldplug(u);
4086 if (q < 0 && r >= 0)
4087 r = q;
4088 }
5a6158b6 4089
b49e14d5 4090 uj = u->job ?: u->nop_job;
4091 if (uj) {
4092 q = job_coldplug(uj);
05a98afd
LP
4093 if (q < 0 && r >= 0)
4094 r = q;
4095 }
cca098b0 4096
05a98afd 4097 return r;
cca098b0
LP
4098}
4099
f0831ed2
LP
4100void unit_catchup(Unit *u) {
4101 assert(u);
4102
4103 if (UNIT_VTABLE(u)->catchup)
4104 UNIT_VTABLE(u)->catchup(u);
4105}
4106
ba25d39e 4107static bool fragment_mtime_newer(const char *path, usec_t mtime, bool path_masked) {
21b95806
ZJS
4108 struct stat st;
4109
4110 if (!path)
4111 return false;
4112
77969722
LP
4113 /* If the source is some virtual kernel file system, then we assume we watch it anyway, and hence pretend we
4114 * are never out-of-date. */
4115 if (PATH_STARTSWITH_SET(path, "/proc", "/sys"))
4116 return false;
4117
21b95806
ZJS
4118 if (stat(path, &st) < 0)
4119 /* What, cannot access this anymore? */
4120 return true;
4121
ba25d39e
ZJS
4122 if (path_masked)
4123 /* For masked files check if they are still so */
4124 return !null_or_empty(&st);
4125 else
3a8db9fe 4126 /* For non-empty files check the mtime */
87ec20ef 4127 return timespec_load(&st.st_mtim) > mtime;
21b95806
ZJS
4128
4129 return false;
4130}
4131
45fb0699 4132bool unit_need_daemon_reload(Unit *u) {
ae7a7182
OS
4133 _cleanup_strv_free_ char **t = NULL;
4134 char **path;
1b64d026 4135
45fb0699
LP
4136 assert(u);
4137
ba25d39e
ZJS
4138 /* For unit files, we allow masking… */
4139 if (fragment_mtime_newer(u->fragment_path, u->fragment_mtime,
4140 u->load_state == UNIT_MASKED))
21b95806 4141 return true;
5f4b19f4 4142
ba25d39e
ZJS
4143 /* Source paths should not be masked… */
4144 if (fragment_mtime_newer(u->source_path, u->source_mtime, false))
ab932a62 4145 return true;
ae7a7182 4146
19a44dfe
LR
4147 if (u->load_state == UNIT_LOADED)
4148 (void) unit_find_dropin_paths(u, &t);
ab932a62
LP
4149 if (!strv_equal(u->dropin_paths, t))
4150 return true;
6d10d308 4151
ba25d39e 4152 /* … any drop-ins that are masked are simply omitted from the list. */
ab932a62 4153 STRV_FOREACH(path, u->dropin_paths)
ba25d39e 4154 if (fragment_mtime_newer(*path, u->dropin_mtime, false))
ab932a62 4155 return true;
21b95806 4156
ab932a62 4157 return false;
45fb0699
LP
4158}
4159
fdf20a31 4160void unit_reset_failed(Unit *u) {
5632e374
LP
4161 assert(u);
4162
fdf20a31
MM
4163 if (UNIT_VTABLE(u)->reset_failed)
4164 UNIT_VTABLE(u)->reset_failed(u);
6bf0f408 4165
7bf081a1 4166 ratelimit_reset(&u->start_ratelimit);
6bf0f408 4167 u->start_limit_hit = false;
5632e374
LP
4168}
4169
a7f241db
LP
4170Unit *unit_following(Unit *u) {
4171 assert(u);
4172
4173 if (UNIT_VTABLE(u)->following)
4174 return UNIT_VTABLE(u)->following(u);
4175
4176 return NULL;
4177}
4178
31afa0a4 4179bool unit_stop_pending(Unit *u) {
18ffdfda
LP
4180 assert(u);
4181
31afa0a4
LP
4182 /* This call does check the current state of the unit. It's
4183 * hence useful to be called from state change calls of the
4184 * unit itself, where the state isn't updated yet. This is
4185 * different from unit_inactive_or_pending() which checks both
4186 * the current state and for a queued job. */
18ffdfda 4187
28a2dfe8 4188 return unit_has_job_type(u, JOB_STOP);
31afa0a4
LP
4189}
4190
4191bool unit_inactive_or_pending(Unit *u) {
4192 assert(u);
4193
4194 /* Returns true if the unit is inactive or going down */
18ffdfda 4195
d956ac29
LP
4196 if (UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)))
4197 return true;
4198
31afa0a4 4199 if (unit_stop_pending(u))
18ffdfda
LP
4200 return true;
4201
4202 return false;
4203}
4204
31afa0a4 4205bool unit_active_or_pending(Unit *u) {
f976f3f6
LP
4206 assert(u);
4207
f60c2665 4208 /* Returns true if the unit is active or going up */
f976f3f6
LP
4209
4210 if (UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)))
4211 return true;
4212
ac155bb8 4213 if (u->job &&
3742095b 4214 IN_SET(u->job->type, JOB_START, JOB_RELOAD_OR_START, JOB_RESTART))
f976f3f6
LP
4215 return true;
4216
4217 return false;
4218}
4219
52a12341
YW
4220bool unit_will_restart_default(Unit *u) {
4221 assert(u);
4222
28a2dfe8 4223 return unit_has_job_type(u, JOB_START);
52a12341
YW
4224}
4225
deb4e708
MK
4226bool unit_will_restart(Unit *u) {
4227 assert(u);
4228
4229 if (!UNIT_VTABLE(u)->will_restart)
4230 return false;
4231
4232 return UNIT_VTABLE(u)->will_restart(u);
4233}
4234
718db961 4235int unit_kill(Unit *u, KillWho w, int signo, sd_bus_error *error) {
8a0867d6
LP
4236 assert(u);
4237 assert(w >= 0 && w < _KILL_WHO_MAX);
6eb7c172 4238 assert(SIGNAL_VALID(signo));
8a0867d6 4239
8a0867d6 4240 if (!UNIT_VTABLE(u)->kill)
15411c0c 4241 return -EOPNOTSUPP;
8a0867d6 4242
c74f17d9 4243 return UNIT_VTABLE(u)->kill(u, w, signo, error);
8a0867d6
LP
4244}
4245
82659fd7 4246static Set *unit_pid_set(pid_t main_pid, pid_t control_pid) {
af4fa99d 4247 _cleanup_set_free_ Set *pid_set = NULL;
82659fd7
LP
4248 int r;
4249
d5099efc 4250 pid_set = set_new(NULL);
82659fd7
LP
4251 if (!pid_set)
4252 return NULL;
4253
4254 /* Exclude the main/control pids from being killed via the cgroup */
4255 if (main_pid > 0) {
fea72cc0 4256 r = set_put(pid_set, PID_TO_PTR(main_pid));
82659fd7 4257 if (r < 0)
95f14a3e 4258 return NULL;
82659fd7
LP
4259 }
4260
4261 if (control_pid > 0) {
fea72cc0 4262 r = set_put(pid_set, PID_TO_PTR(control_pid));
82659fd7 4263 if (r < 0)
95f14a3e 4264 return NULL;
82659fd7
LP
4265 }
4266
95f14a3e 4267 return TAKE_PTR(pid_set);
82659fd7
LP
4268}
4269
d91c34f2
LP
4270int unit_kill_common(
4271 Unit *u,
4272 KillWho who,
4273 int signo,
4274 pid_t main_pid,
4275 pid_t control_pid,
718db961 4276 sd_bus_error *error) {
d91c34f2 4277
814cc562 4278 int r = 0;
ac5e3a50 4279 bool killed = false;
814cc562 4280
ac5e3a50 4281 if (IN_SET(who, KILL_MAIN, KILL_MAIN_FAIL)) {
814cc562 4282 if (main_pid < 0)
7358dc02 4283 return sd_bus_error_setf(error, BUS_ERROR_NO_SUCH_PROCESS, "%s units have no main processes", unit_type_to_string(u->type));
52f448c3 4284 else if (main_pid == 0)
7358dc02 4285 return sd_bus_error_set_const(error, BUS_ERROR_NO_SUCH_PROCESS, "No main process to kill");
814cc562
MS
4286 }
4287
ac5e3a50 4288 if (IN_SET(who, KILL_CONTROL, KILL_CONTROL_FAIL)) {
814cc562 4289 if (control_pid < 0)
7358dc02 4290 return sd_bus_error_setf(error, BUS_ERROR_NO_SUCH_PROCESS, "%s units have no control processes", unit_type_to_string(u->type));
52f448c3 4291 else if (control_pid == 0)
7358dc02 4292 return sd_bus_error_set_const(error, BUS_ERROR_NO_SUCH_PROCESS, "No control process to kill");
814cc562
MS
4293 }
4294
ac5e3a50
JS
4295 if (IN_SET(who, KILL_CONTROL, KILL_CONTROL_FAIL, KILL_ALL, KILL_ALL_FAIL))
4296 if (control_pid > 0) {
814cc562
MS
4297 if (kill(control_pid, signo) < 0)
4298 r = -errno;
ac5e3a50
JS
4299 else
4300 killed = true;
4301 }
814cc562 4302
ac5e3a50
JS
4303 if (IN_SET(who, KILL_MAIN, KILL_MAIN_FAIL, KILL_ALL, KILL_ALL_FAIL))
4304 if (main_pid > 0) {
814cc562
MS
4305 if (kill(main_pid, signo) < 0)
4306 r = -errno;
ac5e3a50
JS
4307 else
4308 killed = true;
4309 }
814cc562 4310
ac5e3a50 4311 if (IN_SET(who, KILL_ALL, KILL_ALL_FAIL) && u->cgroup_path) {
814cc562
MS
4312 _cleanup_set_free_ Set *pid_set = NULL;
4313 int q;
4314
82659fd7
LP
4315 /* Exclude the main/control pids from being killed via the cgroup */
4316 pid_set = unit_pid_set(main_pid, control_pid);
814cc562
MS
4317 if (!pid_set)
4318 return -ENOMEM;
4319
1d98fef1 4320 q = cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, signo, 0, pid_set, NULL, NULL);
4c701096 4321 if (q < 0 && !IN_SET(q, -EAGAIN, -ESRCH, -ENOENT))
814cc562 4322 r = q;
ac5e3a50
JS
4323 else
4324 killed = true;
814cc562
MS
4325 }
4326
201f0c91 4327 if (r == 0 && !killed && IN_SET(who, KILL_ALL_FAIL, KILL_CONTROL_FAIL))
ac5e3a50
JS
4328 return -ESRCH;
4329
814cc562
MS
4330 return r;
4331}
4332
6210e7fc
LP
4333int unit_following_set(Unit *u, Set **s) {
4334 assert(u);
4335 assert(s);
4336
4337 if (UNIT_VTABLE(u)->following_set)
4338 return UNIT_VTABLE(u)->following_set(u, s);
4339
4340 *s = NULL;
4341 return 0;
4342}
4343
a4375746 4344UnitFileState unit_get_unit_file_state(Unit *u) {
0ec0deaa
LP
4345 int r;
4346
a4375746
LP
4347 assert(u);
4348
0ec0deaa
LP
4349 if (u->unit_file_state < 0 && u->fragment_path) {
4350 r = unit_file_get_state(
463d0d15 4351 u->manager->unit_file_scope,
0ec0deaa 4352 NULL,
9ea3a0e7 4353 u->id,
0ec0deaa
LP
4354 &u->unit_file_state);
4355 if (r < 0)
4356 u->unit_file_state = UNIT_FILE_BAD;
4357 }
a4375746 4358
ac155bb8 4359 return u->unit_file_state;
a4375746
LP
4360}
4361
d2dc52db
LP
4362int unit_get_unit_file_preset(Unit *u) {
4363 assert(u);
4364
4365 if (u->unit_file_preset < 0 && u->fragment_path)
4366 u->unit_file_preset = unit_file_query_preset(
463d0d15 4367 u->manager->unit_file_scope,
0ec0deaa 4368 NULL,
8f7b2566
ZJS
4369 basename(u->fragment_path),
4370 NULL);
d2dc52db
LP
4371
4372 return u->unit_file_preset;
4373}
4374
7f7d01ed 4375Unit* unit_ref_set(UnitRef *ref, Unit *source, Unit *target) {
57020a3a 4376 assert(ref);
7f7d01ed
ZJS
4377 assert(source);
4378 assert(target);
57020a3a 4379
7f7d01ed 4380 if (ref->target)
57020a3a
LP
4381 unit_ref_unset(ref);
4382
7f7d01ed
ZJS
4383 ref->source = source;
4384 ref->target = target;
4385 LIST_PREPEND(refs_by_target, target->refs_by_target, ref);
4386 return target;
57020a3a
LP
4387}
4388
4389void unit_ref_unset(UnitRef *ref) {
4390 assert(ref);
4391
7f7d01ed 4392 if (!ref->target)
57020a3a
LP
4393 return;
4394
b75102e5
LP
4395 /* We are about to drop a reference to the unit, make sure the garbage collection has a look at it as it might
4396 * be unreferenced now. */
7f7d01ed 4397 unit_add_to_gc_queue(ref->target);
b75102e5 4398
7f7d01ed
ZJS
4399 LIST_REMOVE(refs_by_target, ref->target->refs_by_target, ref);
4400 ref->source = ref->target = NULL;
57020a3a
LP
4401}
4402
29206d46
LP
4403static int user_from_unit_name(Unit *u, char **ret) {
4404
4405 static const uint8_t hash_key[] = {
4406 0x58, 0x1a, 0xaf, 0xe6, 0x28, 0x58, 0x4e, 0x96,
4407 0xb4, 0x4e, 0xf5, 0x3b, 0x8c, 0x92, 0x07, 0xec
4408 };
4409
4410 _cleanup_free_ char *n = NULL;
4411 int r;
4412
4413 r = unit_name_to_prefix(u->id, &n);
4414 if (r < 0)
4415 return r;
4416
7a8867ab 4417 if (valid_user_group_name(n, 0)) {
ae2a15bc 4418 *ret = TAKE_PTR(n);
29206d46
LP
4419 return 0;
4420 }
4421
4422 /* If we can't use the unit name as a user name, then let's hash it and use that */
4423 if (asprintf(ret, "_du%016" PRIx64, siphash24(n, strlen(n), hash_key)) < 0)
4424 return -ENOMEM;
4425
4426 return 0;
4427}
4428
598459ce
LP
4429int unit_patch_contexts(Unit *u) {
4430 CGroupContext *cc;
4431 ExecContext *ec;
cba6e062
LP
4432 int r;
4433
e06c73cc 4434 assert(u);
e06c73cc 4435
598459ce
LP
4436 /* Patch in the manager defaults into the exec and cgroup
4437 * contexts, _after_ the rest of the settings have been
4438 * initialized */
085afe36 4439
598459ce
LP
4440 ec = unit_get_exec_context(u);
4441 if (ec) {
4442 /* This only copies in the ones that need memory */
12375b95 4443 for (unsigned i = 0; i < _RLIMIT_MAX; i++)
598459ce
LP
4444 if (u->manager->rlimit[i] && !ec->rlimit[i]) {
4445 ec->rlimit[i] = newdup(struct rlimit, u->manager->rlimit[i], 1);
4446 if (!ec->rlimit[i])
4447 return -ENOMEM;
4448 }
4449
463d0d15 4450 if (MANAGER_IS_USER(u->manager) &&
598459ce
LP
4451 !ec->working_directory) {
4452
4453 r = get_home_dir(&ec->working_directory);
4454 if (r < 0)
4455 return r;
4c08c824
LP
4456
4457 /* Allow user services to run, even if the
4458 * home directory is missing */
4459 ec->working_directory_missing_ok = true;
cba6e062
LP
4460 }
4461
598459ce 4462 if (ec->private_devices)
2cd0a735 4463 ec->capability_bounding_set &= ~((UINT64_C(1) << CAP_MKNOD) | (UINT64_C(1) << CAP_SYS_RAWIO));
502d704e
DH
4464
4465 if (ec->protect_kernel_modules)
4466 ec->capability_bounding_set &= ~(UINT64_C(1) << CAP_SYS_MODULE);
29206d46 4467
84703040
KK
4468 if (ec->protect_kernel_logs)
4469 ec->capability_bounding_set &= ~(UINT64_C(1) << CAP_SYSLOG);
4470
fc64760d
KK
4471 if (ec->protect_clock)
4472 ec->capability_bounding_set &= ~((UINT64_C(1) << CAP_SYS_TIME) | (UINT64_C(1) << CAP_WAKE_ALARM));
4473
29206d46
LP
4474 if (ec->dynamic_user) {
4475 if (!ec->user) {
4476 r = user_from_unit_name(u, &ec->user);
4477 if (r < 0)
4478 return r;
4479 }
4480
4481 if (!ec->group) {
4482 ec->group = strdup(ec->user);
4483 if (!ec->group)
4484 return -ENOMEM;
4485 }
4486
bf65b7e0
LP
4487 /* If the dynamic user option is on, let's make sure that the unit can't leave its
4488 * UID/GID around in the file system or on IPC objects. Hence enforce a strict
4489 * sandbox. */
63bb64a0 4490
29206d46 4491 ec->private_tmp = true;
00d9ef85 4492 ec->remove_ipc = true;
63bb64a0
LP
4493 ec->protect_system = PROTECT_SYSTEM_STRICT;
4494 if (ec->protect_home == PROTECT_HOME_NO)
4495 ec->protect_home = PROTECT_HOME_READ_ONLY;
bf65b7e0
LP
4496
4497 /* Make sure this service can neither benefit from SUID/SGID binaries nor create
4498 * them. */
4499 ec->no_new_privileges = true;
4500 ec->restrict_suid_sgid = true;
29206d46 4501 }
cba6e062
LP
4502 }
4503
598459ce 4504 cc = unit_get_cgroup_context(u);
fe65e88b 4505 if (cc && ec) {
f513e420 4506
fe65e88b 4507 if (ec->private_devices &&
084870f9
ZJS
4508 cc->device_policy == CGROUP_DEVICE_POLICY_AUTO)
4509 cc->device_policy = CGROUP_DEVICE_POLICY_CLOSED;
fe65e88b 4510
b3d13314 4511 if ((ec->root_image || !LIST_IS_EMPTY(ec->mount_images)) &&
084870f9 4512 (cc->device_policy != CGROUP_DEVICE_POLICY_AUTO || cc->device_allow)) {
0cffae95 4513 const char *p;
fe65e88b 4514
b3d13314 4515 /* When RootImage= or MountImages= is specified, the following devices are touched. */
0cffae95
LB
4516 FOREACH_STRING(p, "/dev/loop-control", "/dev/mapper/control") {
4517 r = cgroup_add_device_allow(cc, p, "rw");
4518 if (r < 0)
4519 return r;
4520 }
4521 FOREACH_STRING(p, "block-loop", "block-blkext", "block-device-mapper") {
4522 r = cgroup_add_device_allow(cc, p, "rwm");
4523 if (r < 0)
4524 return r;
4525 }
867af728 4526
0cffae95
LB
4527 /* Make sure "block-loop" can be resolved, i.e. make sure "loop" shows up in /proc/devices.
4528 * Same for mapper and verity. */
4529 FOREACH_STRING(p, "modprobe@loop.service", "modprobe@dm_mod.service", "modprobe@dm_verity.service") {
4530 r = unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_WANTS, p, true, UNIT_DEPENDENCY_FILE);
4531 if (r < 0)
4532 return r;
4533 }
fe65e88b 4534 }
fc64760d
KK
4535
4536 if (ec->protect_clock) {
4537 r = cgroup_add_device_allow(cc, "char-rtc", "r");
4538 if (r < 0)
4539 return r;
4540 }
598459ce 4541 }
f1660f96 4542
cba6e062 4543 return 0;
e06c73cc
LP
4544}
4545
3ef63c31
LP
4546ExecContext *unit_get_exec_context(Unit *u) {
4547 size_t offset;
4548 assert(u);
4549
598459ce
LP
4550 if (u->type < 0)
4551 return NULL;
4552
3ef63c31
LP
4553 offset = UNIT_VTABLE(u)->exec_context_offset;
4554 if (offset <= 0)
4555 return NULL;
4556
4557 return (ExecContext*) ((uint8_t*) u + offset);
4558}
4559
718db961
LP
4560KillContext *unit_get_kill_context(Unit *u) {
4561 size_t offset;
4562 assert(u);
4563
598459ce
LP
4564 if (u->type < 0)
4565 return NULL;
4566
718db961
LP
4567 offset = UNIT_VTABLE(u)->kill_context_offset;
4568 if (offset <= 0)
4569 return NULL;
4570
4571 return (KillContext*) ((uint8_t*) u + offset);
4572}
4573
4ad49000
LP
4574CGroupContext *unit_get_cgroup_context(Unit *u) {
4575 size_t offset;
4576
598459ce
LP
4577 if (u->type < 0)
4578 return NULL;
4579
4ad49000
LP
4580 offset = UNIT_VTABLE(u)->cgroup_context_offset;
4581 if (offset <= 0)
4582 return NULL;
4583
4584 return (CGroupContext*) ((uint8_t*) u + offset);
4585}
4586
613b411c
LP
4587ExecRuntime *unit_get_exec_runtime(Unit *u) {
4588 size_t offset;
4589
598459ce
LP
4590 if (u->type < 0)
4591 return NULL;
4592
613b411c
LP
4593 offset = UNIT_VTABLE(u)->exec_runtime_offset;
4594 if (offset <= 0)
4595 return NULL;
4596
4597 return *(ExecRuntime**) ((uint8_t*) u + offset);
4598}
4599
2e59b241 4600static const char* unit_drop_in_dir(Unit *u, UnitWriteFlags flags) {
3f5e8115
LP
4601 assert(u);
4602
2e59b241 4603 if (UNIT_WRITE_FLAGS_NOOP(flags))
4f4afc88
LP
4604 return NULL;
4605
39591351
LP
4606 if (u->transient) /* Redirect drop-ins for transient units always into the transient directory. */
4607 return u->manager->lookup_paths.transient;
26d04f86 4608
2e59b241 4609 if (flags & UNIT_PERSISTENT)
4f4afc88 4610 return u->manager->lookup_paths.persistent_control;
26d04f86 4611
2e59b241
LP
4612 if (flags & UNIT_RUNTIME)
4613 return u->manager->lookup_paths.runtime_control;
4614
39591351 4615 return NULL;
71645aca
LP
4616}
4617
2e59b241
LP
4618char* unit_escape_setting(const char *s, UnitWriteFlags flags, char **buf) {
4619 char *ret = NULL;
4620
4621 if (!s)
4622 return NULL;
4623
4624 /* Escapes the input string as requested. Returns the escaped string. If 'buf' is specified then the allocated
4625 * return buffer pointer is also written to *buf, except if no escaping was necessary, in which case *buf is
4626 * set to NULL, and the input pointer is returned as-is. This means the return value always contains a properly
4627 * escaped version, but *buf when passed only contains a pointer if an allocation was necessary. If *buf is
4628 * not specified, then the return value always needs to be freed. Callers can use this to optimize memory
4629 * allocations. */
4630
4631 if (flags & UNIT_ESCAPE_SPECIFIERS) {
4632 ret = specifier_escape(s);
4633 if (!ret)
4634 return NULL;
4635
4636 s = ret;
4637 }
4638
4639 if (flags & UNIT_ESCAPE_C) {
4640 char *a;
4641
4642 a = cescape(s);
4643 free(ret);
4644 if (!a)
4645 return NULL;
4646
4647 ret = a;
4648 }
4649
4650 if (buf) {
4651 *buf = ret;
4652 return ret ?: (char*) s;
4653 }
4654
4655 return ret ?: strdup(s);
4656}
4657
4658char* unit_concat_strv(char **l, UnitWriteFlags flags) {
4659 _cleanup_free_ char *result = NULL;
4660 size_t n = 0, allocated = 0;
ae2a15bc 4661 char **i;
2e59b241
LP
4662
4663 /* Takes a list of strings, escapes them, and concatenates them. This may be used to format command lines in a
4664 * way suitable for ExecStart= stanzas */
4665
4666 STRV_FOREACH(i, l) {
4667 _cleanup_free_ char *buf = NULL;
4668 const char *p;
4669 size_t a;
4670 char *q;
4671
4672 p = unit_escape_setting(*i, flags, &buf);
4673 if (!p)
4674 return NULL;
4675
4676 a = (n > 0) + 1 + strlen(p) + 1; /* separating space + " + entry + " */
4677 if (!GREEDY_REALLOC(result, allocated, n + a + 1))
4678 return NULL;
4679
4680 q = result + n;
4681 if (n > 0)
4682 *(q++) = ' ';
4683
4684 *(q++) = '"';
4685 q = stpcpy(q, p);
4686 *(q++) = '"';
4687
4688 n += a;
4689 }
4690
4691 if (!GREEDY_REALLOC(result, allocated, n + 1))
4692 return NULL;
4693
4694 result[n] = 0;
4695
ae2a15bc 4696 return TAKE_PTR(result);
2e59b241
LP
4697}
4698
4699int unit_write_setting(Unit *u, UnitWriteFlags flags, const char *name, const char *data) {
4700 _cleanup_free_ char *p = NULL, *q = NULL, *escaped = NULL;
2a9a6f8a 4701 const char *dir, *wrapped;
26d04f86 4702 int r;
71645aca
LP
4703
4704 assert(u);
2e59b241
LP
4705 assert(name);
4706 assert(data);
4707
4708 if (UNIT_WRITE_FLAGS_NOOP(flags))
4709 return 0;
4710
4711 data = unit_escape_setting(data, flags, &escaped);
4712 if (!data)
4713 return -ENOMEM;
4714
4715 /* Prefix the section header. If we are writing this out as transient file, then let's suppress this if the
4716 * previous section header is the same */
4717
4718 if (flags & UNIT_PRIVATE) {
4719 if (!UNIT_VTABLE(u)->private_section)
4720 return -EINVAL;
4721
4722 if (!u->transient_file || u->last_section_private < 0)
4723 data = strjoina("[", UNIT_VTABLE(u)->private_section, "]\n", data);
4724 else if (u->last_section_private == 0)
4725 data = strjoina("\n[", UNIT_VTABLE(u)->private_section, "]\n", data);
4726 } else {
4727 if (!u->transient_file || u->last_section_private < 0)
4728 data = strjoina("[Unit]\n", data);
4729 else if (u->last_section_private > 0)
4730 data = strjoina("\n[Unit]\n", data);
4731 }
71645aca 4732
4f4afc88
LP
4733 if (u->transient_file) {
4734 /* When this is a transient unit file in creation, then let's not create a new drop-in but instead
4735 * write to the transient unit file. */
4736 fputs(data, u->transient_file);
4f4afc88 4737
2e59b241
LP
4738 if (!endswith(data, "\n"))
4739 fputc('\n', u->transient_file);
4740
4741 /* Remember which section we wrote this entry to */
4742 u->last_section_private = !!(flags & UNIT_PRIVATE);
8e2af478 4743 return 0;
2e59b241 4744 }
8e2af478 4745
2e59b241 4746 dir = unit_drop_in_dir(u, flags);
39591351
LP
4747 if (!dir)
4748 return -EINVAL;
71645aca 4749
2a9a6f8a 4750 wrapped = strjoina("# This is a drop-in unit file extension, created via \"systemctl set-property\"\n"
3f71dec5 4751 "# or an equivalent operation. Do not edit.\n",
2a9a6f8a
ZJS
4752 data,
4753 "\n");
e20b2a86 4754
815b09d3 4755 r = drop_in_file(dir, u->id, 50, name, &p, &q);
adb76a70
WC
4756 if (r < 0)
4757 return r;
4758
45639f1b 4759 (void) mkdir_p_label(p, 0755);
4dba44a5
ZJS
4760
4761 /* Make sure the drop-in dir is registered in our path cache. This way we don't need to stupidly
4762 * recreate the cache after every drop-in we write. */
4763 if (u->manager->unit_path_cache) {
be327321 4764 r = set_put_strdup(&u->manager->unit_path_cache, p);
4dba44a5
ZJS
4765 if (r < 0)
4766 return r;
4767 }
4768
2a9a6f8a 4769 r = write_string_file_atomic_label(q, wrapped);
adb76a70
WC
4770 if (r < 0)
4771 return r;
4772
815b09d3 4773 r = strv_push(&u->dropin_paths, q);
adb76a70
WC
4774 if (r < 0)
4775 return r;
815b09d3 4776 q = NULL;
adb76a70 4777
adb76a70
WC
4778 strv_uniq(u->dropin_paths);
4779
4780 u->dropin_mtime = now(CLOCK_REALTIME);
4781
4782 return 0;
26d04f86 4783}
71645aca 4784
2e59b241 4785int unit_write_settingf(Unit *u, UnitWriteFlags flags, const char *name, const char *format, ...) {
b9ec9359
LP
4786 _cleanup_free_ char *p = NULL;
4787 va_list ap;
4788 int r;
4789
4790 assert(u);
4791 assert(name);
4792 assert(format);
4793
2e59b241 4794 if (UNIT_WRITE_FLAGS_NOOP(flags))
b9ec9359
LP
4795 return 0;
4796
4797 va_start(ap, format);
4798 r = vasprintf(&p, format, ap);
4799 va_end(ap);
4800
4801 if (r < 0)
4802 return -ENOMEM;
4803
2e59b241 4804 return unit_write_setting(u, flags, name, p);
b9ec9359 4805}
71645aca 4806
c2756a68 4807int unit_make_transient(Unit *u) {
0126c8f3 4808 _cleanup_free_ char *path = NULL;
4f4afc88 4809 FILE *f;
4f4afc88 4810
c2756a68
LP
4811 assert(u);
4812
3f5e8115
LP
4813 if (!UNIT_VTABLE(u)->can_transient)
4814 return -EOPNOTSUPP;
4815
45639f1b
LP
4816 (void) mkdir_p_label(u->manager->lookup_paths.transient, 0755);
4817
657ee2d8 4818 path = path_join(u->manager->lookup_paths.transient, u->id);
4f4afc88
LP
4819 if (!path)
4820 return -ENOMEM;
4821
4822 /* Let's open the file we'll write the transient settings into. This file is kept open as long as we are
4823 * creating the transient, and is closed in unit_load(), as soon as we start loading the file. */
4824
78e334b5 4825 RUN_WITH_UMASK(0022) {
4f4afc88 4826 f = fopen(path, "we");
0126c8f3 4827 if (!f)
78e334b5 4828 return -errno;
4f4afc88
LP
4829 }
4830
0126c8f3 4831 safe_fclose(u->transient_file);
4f4afc88
LP
4832 u->transient_file = f;
4833
0126c8f3 4834 free_and_replace(u->fragment_path, path);
7c65093a 4835
7c65093a
LP
4836 u->source_path = mfree(u->source_path);
4837 u->dropin_paths = strv_free(u->dropin_paths);
4838 u->fragment_mtime = u->source_mtime = u->dropin_mtime = 0;
4839
4f4afc88
LP
4840 u->load_state = UNIT_STUB;
4841 u->load_error = 0;
4842 u->transient = true;
4843
7c65093a
LP
4844 unit_add_to_dbus_queue(u);
4845 unit_add_to_gc_queue(u);
c2756a68 4846
4f4afc88
LP
4847 fputs("# This is a transient unit file, created programmatically via the systemd API. Do not edit.\n",
4848 u->transient_file);
4849
3f5e8115 4850 return 0;
c2756a68
LP
4851}
4852
c53d2d54 4853static int log_kill(pid_t pid, int sig, void *userdata) {
1d98fef1
LP
4854 _cleanup_free_ char *comm = NULL;
4855
4856 (void) get_process_comm(pid, &comm);
4857
4858 /* Don't log about processes marked with brackets, under the assumption that these are temporary processes
4859 only, like for example systemd's own PAM stub process. */
4860 if (comm && comm[0] == '(')
c53d2d54 4861 return 0;
1d98fef1
LP
4862
4863 log_unit_notice(userdata,
4864 "Killing process " PID_FMT " (%s) with signal SIG%s.",
4865 pid,
4866 strna(comm),
4867 signal_to_string(sig));
c53d2d54
DB
4868
4869 return 1;
1d98fef1
LP
4870}
4871
4ab1670f 4872static int operation_to_signal(const KillContext *c, KillOperation k, bool *noteworthy) {
1d98fef1
LP
4873 assert(c);
4874
4875 switch (k) {
4876
4877 case KILL_TERMINATE:
4878 case KILL_TERMINATE_AND_LOG:
4ab1670f 4879 *noteworthy = false;
1d98fef1
LP
4880 return c->kill_signal;
4881
a232ebcc 4882 case KILL_RESTART:
4ab1670f 4883 *noteworthy = false;
a232ebcc
ZJS
4884 return restart_kill_signal(c);
4885
1d98fef1 4886 case KILL_KILL:
4ab1670f 4887 *noteworthy = true;
fbb48d4c 4888 return c->final_kill_signal;
1d98fef1 4889
c87700a1 4890 case KILL_WATCHDOG:
4ab1670f 4891 *noteworthy = true;
c87700a1 4892 return c->watchdog_signal;
1d98fef1
LP
4893
4894 default:
4895 assert_not_reached("KillOperation unknown");
4896 }
4897}
4898
cd2086fe
LP
4899int unit_kill_context(
4900 Unit *u,
4901 KillContext *c,
db2cb23b 4902 KillOperation k,
cd2086fe
LP
4903 pid_t main_pid,
4904 pid_t control_pid,
4905 bool main_pid_alien) {
4906
1d98fef1 4907 bool wait_for_exit = false, send_sighup;
59ec09a8 4908 cg_kill_log_func_t log_func = NULL;
b821a397 4909 int sig, r;
cd2086fe
LP
4910
4911 assert(u);
4912 assert(c);
4913
59ec09a8
ZJS
4914 /* Kill the processes belonging to this unit, in preparation for shutting the unit down.
4915 * Returns > 0 if we killed something worth waiting for, 0 otherwise. */
1d98fef1 4916
cd2086fe
LP
4917 if (c->kill_mode == KILL_NONE)
4918 return 0;
4919
4ab1670f
ZJS
4920 bool noteworthy;
4921 sig = operation_to_signal(c, k, &noteworthy);
4922 if (noteworthy)
4923 log_func = log_kill;
1d98fef1
LP
4924
4925 send_sighup =
4926 c->send_sighup &&
4927 IN_SET(k, KILL_TERMINATE, KILL_TERMINATE_AND_LOG) &&
4928 sig != SIGHUP;
4929
cd2086fe 4930 if (main_pid > 0) {
1d98fef1
LP
4931 if (log_func)
4932 log_func(main_pid, sig, u);
cd2086fe 4933
1d98fef1 4934 r = kill_and_sigcont(main_pid, sig);
cd2086fe
LP
4935 if (r < 0 && r != -ESRCH) {
4936 _cleanup_free_ char *comm = NULL;
1d98fef1 4937 (void) get_process_comm(main_pid, &comm);
cd2086fe 4938
b821a397 4939 log_unit_warning_errno(u, r, "Failed to kill main process " PID_FMT " (%s), ignoring: %m", main_pid, strna(comm));
82659fd7 4940 } else {
bc6aed7b
LP
4941 if (!main_pid_alien)
4942 wait_for_exit = true;
82659fd7 4943
1d98fef1 4944 if (r != -ESRCH && send_sighup)
d0667321 4945 (void) kill(main_pid, SIGHUP);
82659fd7 4946 }
cd2086fe
LP
4947 }
4948
4949 if (control_pid > 0) {
1d98fef1
LP
4950 if (log_func)
4951 log_func(control_pid, sig, u);
cd2086fe 4952
1d98fef1 4953 r = kill_and_sigcont(control_pid, sig);
cd2086fe
LP
4954 if (r < 0 && r != -ESRCH) {
4955 _cleanup_free_ char *comm = NULL;
1d98fef1 4956 (void) get_process_comm(control_pid, &comm);
cd2086fe 4957
b821a397 4958 log_unit_warning_errno(u, r, "Failed to kill control process " PID_FMT " (%s), ignoring: %m", control_pid, strna(comm));
82659fd7 4959 } else {
cd2086fe 4960 wait_for_exit = true;
82659fd7 4961
1d98fef1 4962 if (r != -ESRCH && send_sighup)
d0667321 4963 (void) kill(control_pid, SIGHUP);
82659fd7 4964 }
cd2086fe
LP
4965 }
4966
b821a397
LP
4967 if (u->cgroup_path &&
4968 (c->kill_mode == KILL_CONTROL_GROUP || (c->kill_mode == KILL_MIXED && k == KILL_KILL))) {
cd2086fe
LP
4969 _cleanup_set_free_ Set *pid_set = NULL;
4970
82659fd7
LP
4971 /* Exclude the main/control pids from being killed via the cgroup */
4972 pid_set = unit_pid_set(main_pid, control_pid);
cd2086fe
LP
4973 if (!pid_set)
4974 return -ENOMEM;
4975
1d98fef1
LP
4976 r = cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path,
4977 sig,
4978 CGROUP_SIGCONT|CGROUP_IGNORE_SELF,
4979 pid_set,
4980 log_func, u);
cd2086fe 4981 if (r < 0) {
4c701096 4982 if (!IN_SET(r, -EAGAIN, -ESRCH, -ENOENT))
b821a397
LP
4983 log_unit_warning_errno(u, r, "Failed to kill control group %s, ignoring: %m", u->cgroup_path);
4984
82659fd7 4985 } else if (r > 0) {
bc6aed7b 4986
1d9cc876
LP
4987 /* FIXME: For now, on the legacy hierarchy, we will not wait for the cgroup members to die if
4988 * we are running in a container or if this is a delegation unit, simply because cgroup
4989 * notification is unreliable in these cases. It doesn't work at all in containers, and outside
4990 * of containers it can be confused easily by left-over directories in the cgroup — which
4991 * however should not exist in non-delegated units. On the unified hierarchy that's different,
4992 * there we get proper events. Hence rely on them. */
efdb0237 4993
c22800e4 4994 if (cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER) > 0 ||
1d9cc876 4995 (detect_container() == 0 && !unit_cgroup_delegate(u)))
e9db43d5 4996 wait_for_exit = true;
58ea275a 4997
1d98fef1 4998 if (send_sighup) {
82659fd7
LP
4999 set_free(pid_set);
5000
5001 pid_set = unit_pid_set(main_pid, control_pid);
5002 if (!pid_set)
5003 return -ENOMEM;
5004
c8aa4b5b
LP
5005 (void) cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path,
5006 SIGHUP,
5007 CGROUP_IGNORE_SELF,
5008 pid_set,
5009 NULL, NULL);
82659fd7
LP
5010 }
5011 }
cd2086fe
LP
5012 }
5013
5014 return wait_for_exit;
5015}
5016
eef85c4a 5017int unit_require_mounts_for(Unit *u, const char *path, UnitDependencyMask mask) {
ca8700e9 5018 _cleanup_free_ char *p = NULL;
eef85c4a 5019 UnitDependencyInfo di;
a57f7e2c
LP
5020 int r;
5021
5022 assert(u);
5023 assert(path);
5024
eef85c4a
LP
5025 /* Registers a unit for requiring a certain path and all its prefixes. We keep a hashtable of these paths in
5026 * the unit (from the path to the UnitDependencyInfo structure indicating how to the dependency came to
5027 * be). However, we build a prefix table for all possible prefixes so that new appearing mount units can easily
5028 * determine which units to make themselves a dependency of. */
a57f7e2c 5029
70b64bd3
ZJS
5030 if (!path_is_absolute(path))
5031 return -EINVAL;
5032
548f6937 5033 r = hashmap_ensure_allocated(&u->requires_mounts_for, &path_hash_ops);
eef85c4a
LP
5034 if (r < 0)
5035 return r;
5036
a57f7e2c
LP
5037 p = strdup(path);
5038 if (!p)
5039 return -ENOMEM;
5040
106bf8e4 5041 path = path_simplify(p, true);
a57f7e2c 5042
ca8700e9 5043 if (!path_is_normalized(path))
a57f7e2c 5044 return -EPERM;
a57f7e2c 5045
ca8700e9 5046 if (hashmap_contains(u->requires_mounts_for, path))
a57f7e2c 5047 return 0;
a57f7e2c 5048
eef85c4a
LP
5049 di = (UnitDependencyInfo) {
5050 .origin_mask = mask
5051 };
5052
ca8700e9
ZJS
5053 r = hashmap_put(u->requires_mounts_for, path, di.data);
5054 if (r < 0)
a57f7e2c 5055 return r;
ca8700e9 5056 p = NULL;
a57f7e2c 5057
4cb06c59 5058 char prefix[strlen(path) + 1];
ca8700e9 5059 PATH_FOREACH_PREFIX_MORE(prefix, path) {
a57f7e2c
LP
5060 Set *x;
5061
5062 x = hashmap_get(u->manager->units_requiring_mounts_for, prefix);
5063 if (!x) {
ca8700e9 5064 _cleanup_free_ char *q = NULL;
a57f7e2c 5065
548f6937 5066 r = hashmap_ensure_allocated(&u->manager->units_requiring_mounts_for, &path_hash_ops);
742f41ad
LP
5067 if (r < 0)
5068 return r;
a57f7e2c
LP
5069
5070 q = strdup(prefix);
5071 if (!q)
5072 return -ENOMEM;
5073
d5099efc 5074 x = set_new(NULL);
ca8700e9 5075 if (!x)
a57f7e2c 5076 return -ENOMEM;
a57f7e2c
LP
5077
5078 r = hashmap_put(u->manager->units_requiring_mounts_for, q, x);
5079 if (r < 0) {
a57f7e2c
LP
5080 set_free(x);
5081 return r;
5082 }
ca8700e9 5083 q = NULL;
a57f7e2c
LP
5084 }
5085
5086 r = set_put(x, u);
5087 if (r < 0)
5088 return r;
5089 }
5090
5091 return 0;
5092}
5093
613b411c
LP
5094int unit_setup_exec_runtime(Unit *u) {
5095 ExecRuntime **rt;
5096 size_t offset;
613b411c 5097 Unit *other;
eef85c4a 5098 void *v;
e8a565cb 5099 int r;
613b411c
LP
5100
5101 offset = UNIT_VTABLE(u)->exec_runtime_offset;
5102 assert(offset > 0);
5103
06b643e7 5104 /* Check if there already is an ExecRuntime for this unit? */
613b411c
LP
5105 rt = (ExecRuntime**) ((uint8_t*) u + offset);
5106 if (*rt)
5107 return 0;
5108
5109 /* Try to get it from somebody else */
90e74a66 5110 HASHMAP_FOREACH_KEY(v, other, u->dependencies[UNIT_JOINS_NAMESPACE_OF]) {
e8a565cb
YW
5111 r = exec_runtime_acquire(u->manager, NULL, other->id, false, rt);
5112 if (r == 1)
5113 return 1;
613b411c
LP
5114 }
5115
e8a565cb 5116 return exec_runtime_acquire(u->manager, unit_get_exec_context(u), u->id, true, rt);
613b411c
LP
5117}
5118
29206d46
LP
5119int unit_setup_dynamic_creds(Unit *u) {
5120 ExecContext *ec;
5121 DynamicCreds *dcreds;
5122 size_t offset;
5123
5124 assert(u);
5125
5126 offset = UNIT_VTABLE(u)->dynamic_creds_offset;
5127 assert(offset > 0);
5128 dcreds = (DynamicCreds*) ((uint8_t*) u + offset);
5129
5130 ec = unit_get_exec_context(u);
5131 assert(ec);
5132
5133 if (!ec->dynamic_user)
5134 return 0;
5135
5136 return dynamic_creds_acquire(dcreds, u->manager, ec->user, ec->group);
5137}
5138
1c2e9646
LP
5139bool unit_type_supported(UnitType t) {
5140 if (_unlikely_(t < 0))
5141 return false;
5142 if (_unlikely_(t >= _UNIT_TYPE_MAX))
5143 return false;
5144
5145 if (!unit_vtable[t]->supported)
5146 return true;
5147
5148 return unit_vtable[t]->supported();
5149}
5150
8b4305c7
LP
5151void unit_warn_if_dir_nonempty(Unit *u, const char* where) {
5152 int r;
5153
5154 assert(u);
5155 assert(where);
5156
5157 r = dir_is_empty(where);
3f602115 5158 if (r > 0 || r == -ENOTDIR)
8b4305c7
LP
5159 return;
5160 if (r < 0) {
5161 log_unit_warning_errno(u, r, "Failed to check directory %s: %m", where);
5162 return;
5163 }
5164
5165 log_struct(LOG_NOTICE,
2b044526 5166 "MESSAGE_ID=" SD_MESSAGE_OVERMOUNTING_STR,
8b4305c7 5167 LOG_UNIT_ID(u),
f1c50bec 5168 LOG_UNIT_INVOCATION_ID(u),
8b4305c7 5169 LOG_UNIT_MESSAGE(u, "Directory %s to mount over is not empty, mounting anyway.", where),
a1230ff9 5170 "WHERE=%s", where);
8b4305c7
LP
5171}
5172
25cd4964 5173int unit_fail_if_noncanonical(Unit *u, const char* where) {
58d9d89b 5174 _cleanup_free_ char *canonical_where = NULL;
8b4305c7
LP
5175 int r;
5176
5177 assert(u);
5178 assert(where);
5179
a5648b80 5180 r = chase_symlinks(where, NULL, CHASE_NONEXISTENT, &canonical_where, NULL);
8b4305c7 5181 if (r < 0) {
25cd4964 5182 log_unit_debug_errno(u, r, "Failed to check %s for symlinks, ignoring: %m", where);
8b4305c7
LP
5183 return 0;
5184 }
25cd4964
AJ
5185
5186 /* We will happily ignore a trailing slash (or any redundant slashes) */
5187 if (path_equal(where, canonical_where))
8b4305c7
LP
5188 return 0;
5189
25cd4964 5190 /* No need to mention "." or "..", they would already have been rejected by unit_name_from_path() */
8b4305c7 5191 log_struct(LOG_ERR,
2b044526 5192 "MESSAGE_ID=" SD_MESSAGE_OVERMOUNTING_STR,
8b4305c7 5193 LOG_UNIT_ID(u),
f1c50bec 5194 LOG_UNIT_INVOCATION_ID(u),
25cd4964 5195 LOG_UNIT_MESSAGE(u, "Mount path %s is not canonical (contains a symlink).", where),
a1230ff9 5196 "WHERE=%s", where);
8b4305c7
LP
5197
5198 return -ELOOP;
5199}
0f13f3bd
LP
5200
5201bool unit_is_pristine(Unit *u) {
5202 assert(u);
5203
7c65093a 5204 /* Check if the unit already exists or is already around,
0f13f3bd
LP
5205 * in a number of different ways. Note that to cater for unit
5206 * types such as slice, we are generally fine with units that
e9e8cbc8
ZJS
5207 * are marked UNIT_LOADED even though nothing was actually
5208 * loaded, as those unit types don't require a file on disk. */
0f13f3bd
LP
5209
5210 return !(!IN_SET(u->load_state, UNIT_NOT_FOUND, UNIT_LOADED) ||
5211 u->fragment_path ||
5212 u->source_path ||
5213 !strv_isempty(u->dropin_paths) ||
0f13f3bd
LP
5214 u->job ||
5215 u->merged_into);
5216}
291d565a
LP
5217
5218pid_t unit_control_pid(Unit *u) {
5219 assert(u);
5220
5221 if (UNIT_VTABLE(u)->control_pid)
5222 return UNIT_VTABLE(u)->control_pid(u);
5223
5224 return 0;
5225}
5226
5227pid_t unit_main_pid(Unit *u) {
5228 assert(u);
5229
5230 if (UNIT_VTABLE(u)->main_pid)
5231 return UNIT_VTABLE(u)->main_pid(u);
5232
5233 return 0;
5234}
00d9ef85
LP
5235
5236static void unit_unref_uid_internal(
5237 Unit *u,
5238 uid_t *ref_uid,
5239 bool destroy_now,
5240 void (*_manager_unref_uid)(Manager *m, uid_t uid, bool destroy_now)) {
5241
5242 assert(u);
5243 assert(ref_uid);
5244 assert(_manager_unref_uid);
5245
5246 /* Generic implementation of both unit_unref_uid() and unit_unref_gid(), under the assumption that uid_t and
5247 * gid_t are actually the same time, with the same validity rules.
5248 *
5249 * Drops a reference to UID/GID from a unit. */
5250
5251 assert_cc(sizeof(uid_t) == sizeof(gid_t));
5252 assert_cc(UID_INVALID == (uid_t) GID_INVALID);
5253
5254 if (!uid_is_valid(*ref_uid))
5255 return;
5256
5257 _manager_unref_uid(u->manager, *ref_uid, destroy_now);
5258 *ref_uid = UID_INVALID;
5259}
5260
b90cf102 5261static void unit_unref_uid(Unit *u, bool destroy_now) {
00d9ef85
LP
5262 unit_unref_uid_internal(u, &u->ref_uid, destroy_now, manager_unref_uid);
5263}
5264
b90cf102 5265static void unit_unref_gid(Unit *u, bool destroy_now) {
00d9ef85
LP
5266 unit_unref_uid_internal(u, (uid_t*) &u->ref_gid, destroy_now, manager_unref_gid);
5267}
5268
b90cf102
LP
5269void unit_unref_uid_gid(Unit *u, bool destroy_now) {
5270 assert(u);
5271
5272 unit_unref_uid(u, destroy_now);
5273 unit_unref_gid(u, destroy_now);
5274}
5275
00d9ef85
LP
5276static int unit_ref_uid_internal(
5277 Unit *u,
5278 uid_t *ref_uid,
5279 uid_t uid,
5280 bool clean_ipc,
5281 int (*_manager_ref_uid)(Manager *m, uid_t uid, bool clean_ipc)) {
5282
5283 int r;
5284
5285 assert(u);
5286 assert(ref_uid);
5287 assert(uid_is_valid(uid));
5288 assert(_manager_ref_uid);
5289
5290 /* Generic implementation of both unit_ref_uid() and unit_ref_guid(), under the assumption that uid_t and gid_t
5291 * are actually the same type, and have the same validity rules.
5292 *
5293 * Adds a reference on a specific UID/GID to this unit. Each unit referencing the same UID/GID maintains a
5294 * reference so that we can destroy the UID/GID's IPC resources as soon as this is requested and the counter
5295 * drops to zero. */
5296
5297 assert_cc(sizeof(uid_t) == sizeof(gid_t));
5298 assert_cc(UID_INVALID == (uid_t) GID_INVALID);
5299
5300 if (*ref_uid == uid)
5301 return 0;
5302
5303 if (uid_is_valid(*ref_uid)) /* Already set? */
5304 return -EBUSY;
5305
5306 r = _manager_ref_uid(u->manager, uid, clean_ipc);
5307 if (r < 0)
5308 return r;
5309
5310 *ref_uid = uid;
5311 return 1;
5312}
5313
b90cf102 5314static int unit_ref_uid(Unit *u, uid_t uid, bool clean_ipc) {
00d9ef85
LP
5315 return unit_ref_uid_internal(u, &u->ref_uid, uid, clean_ipc, manager_ref_uid);
5316}
5317
b90cf102 5318static int unit_ref_gid(Unit *u, gid_t gid, bool clean_ipc) {
00d9ef85
LP
5319 return unit_ref_uid_internal(u, (uid_t*) &u->ref_gid, (uid_t) gid, clean_ipc, manager_ref_gid);
5320}
5321
5322static int unit_ref_uid_gid_internal(Unit *u, uid_t uid, gid_t gid, bool clean_ipc) {
5323 int r = 0, q = 0;
5324
5325 assert(u);
5326
5327 /* Reference both a UID and a GID in one go. Either references both, or neither. */
5328
5329 if (uid_is_valid(uid)) {
5330 r = unit_ref_uid(u, uid, clean_ipc);
5331 if (r < 0)
5332 return r;
5333 }
5334
5335 if (gid_is_valid(gid)) {
5336 q = unit_ref_gid(u, gid, clean_ipc);
5337 if (q < 0) {
5338 if (r > 0)
5339 unit_unref_uid(u, false);
5340
5341 return q;
5342 }
5343 }
5344
5345 return r > 0 || q > 0;
5346}
5347
5348int unit_ref_uid_gid(Unit *u, uid_t uid, gid_t gid) {
5349 ExecContext *c;
5350 int r;
5351
5352 assert(u);
5353
5354 c = unit_get_exec_context(u);
5355
5356 r = unit_ref_uid_gid_internal(u, uid, gid, c ? c->remove_ipc : false);
5357 if (r < 0)
5358 return log_unit_warning_errno(u, r, "Couldn't add UID/GID reference to unit, proceeding without: %m");
5359
5360 return r;
5361}
5362
00d9ef85
LP
5363void unit_notify_user_lookup(Unit *u, uid_t uid, gid_t gid) {
5364 int r;
5365
5366 assert(u);
5367
5368 /* This is invoked whenever one of the forked off processes let's us know the UID/GID its user name/group names
5369 * resolved to. We keep track of which UID/GID is currently assigned in order to be able to destroy its IPC
5370 * objects when no service references the UID/GID anymore. */
5371
5372 r = unit_ref_uid_gid(u, uid, gid);
5373 if (r > 0)
37d0b962 5374 unit_add_to_dbus_queue(u);
00d9ef85 5375}
4b58153d 5376
4b58153d
LP
5377int unit_acquire_invocation_id(Unit *u) {
5378 sd_id128_t id;
5379 int r;
5380
5381 assert(u);
5382
5383 r = sd_id128_randomize(&id);
5384 if (r < 0)
5385 return log_unit_error_errno(u, r, "Failed to generate invocation ID for unit: %m");
5386
5387 r = unit_set_invocation_id(u, id);
5388 if (r < 0)
5389 return log_unit_error_errno(u, r, "Failed to set invocation ID for unit: %m");
5390
af92c603 5391 unit_add_to_dbus_queue(u);
4b58153d
LP
5392 return 0;
5393}
f0d47797 5394
1ad6e8b3
LP
5395int unit_set_exec_params(Unit *u, ExecParameters *p) {
5396 int r;
5397
7960b0c7
LP
5398 assert(u);
5399 assert(p);
f0d47797 5400
004c7f16 5401 /* Copy parameters from manager */
1ad6e8b3
LP
5402 r = manager_get_effective_environment(u->manager, &p->environment);
5403 if (r < 0)
5404 return r;
5405
004c7f16
LP
5406 p->confirm_spawn = manager_get_confirm_spawn(u->manager);
5407 p->cgroup_supported = u->manager->cgroup_supported;
5408 p->prefix = u->manager->prefix;
5409 SET_FLAG(p->flags, EXEC_PASS_LOG_UNIT|EXEC_CHOWN_DIRECTORIES, MANAGER_IS_SYSTEM(u->manager));
5410
5238e957 5411 /* Copy parameters from unit */
7960b0c7 5412 p->cgroup_path = u->cgroup_path;
1d9cc876 5413 SET_FLAG(p->flags, EXEC_CGROUP_DELEGATE, unit_cgroup_delegate(u));
1ad6e8b3 5414
bb0c0d6f
LP
5415 p->received_credentials = u->manager->received_credentials;
5416
1ad6e8b3 5417 return 0;
f0d47797 5418}
a79279c7 5419
4c253ed1 5420int unit_fork_helper_process(Unit *u, const char *name, pid_t *ret) {
a79279c7
LP
5421 int r;
5422
5423 assert(u);
5424 assert(ret);
5425
5426 /* Forks off a helper process and makes sure it is a member of the unit's cgroup. Returns == 0 in the child,
5427 * and > 0 in the parent. The pid parameter is always filled in with the child's PID. */
5428
5429 (void) unit_realize_cgroup(u);
5430
4c253ed1
LP
5431 r = safe_fork(name, FORK_REOPEN_LOG, ret);
5432 if (r != 0)
5433 return r;
a79279c7 5434
4c253ed1
LP
5435 (void) default_signals(SIGNALS_CRASH_HANDLER, SIGNALS_IGNORE, -1);
5436 (void) ignore_signals(SIGPIPE, -1);
a79279c7 5437
4c253ed1 5438 (void) prctl(PR_SET_PDEATHSIG, SIGTERM);
a79279c7 5439
4c253ed1
LP
5440 if (u->cgroup_path) {
5441 r = cg_attach_everywhere(u->manager->cgroup_supported, u->cgroup_path, 0, NULL, NULL);
5442 if (r < 0) {
5443 log_unit_error_errno(u, r, "Failed to join unit cgroup %s: %m", u->cgroup_path);
5444 _exit(EXIT_CGROUP);
a79279c7 5445 }
a79279c7
LP
5446 }
5447
4c253ed1 5448 return 0;
a79279c7 5449}
c999cf38 5450
810ef318
YW
5451int unit_fork_and_watch_rm_rf(Unit *u, char **paths, pid_t *ret_pid) {
5452 pid_t pid;
5453 int r;
5454
5455 assert(u);
5456 assert(ret_pid);
5457
5458 r = unit_fork_helper_process(u, "(sd-rmrf)", &pid);
5459 if (r < 0)
5460 return r;
5461 if (r == 0) {
5462 int ret = EXIT_SUCCESS;
5463 char **i;
5464
5465 STRV_FOREACH(i, paths) {
5466 r = rm_rf(*i, REMOVE_ROOT|REMOVE_PHYSICAL|REMOVE_MISSING_OK);
5467 if (r < 0) {
5468 log_error_errno(r, "Failed to remove '%s': %m", *i);
5469 ret = EXIT_FAILURE;
5470 }
5471 }
5472
5473 _exit(ret);
5474 }
5475
5476 r = unit_watch_pid(u, pid, true);
5477 if (r < 0)
5478 return r;
5479
5480 *ret_pid = pid;
5481 return 0;
5482}
5483
c999cf38
LP
5484static void unit_update_dependency_mask(Unit *u, UnitDependency d, Unit *other, UnitDependencyInfo di) {
5485 assert(u);
5486 assert(d >= 0);
5487 assert(d < _UNIT_DEPENDENCY_MAX);
5488 assert(other);
5489
5490 if (di.origin_mask == 0 && di.destination_mask == 0) {
5491 /* No bit set anymore, let's drop the whole entry */
5492 assert_se(hashmap_remove(u->dependencies[d], other));
29a743f9 5493 log_unit_debug(u, "lost dependency %s=%s", unit_dependency_to_string(d), other->id);
c999cf38
LP
5494 } else
5495 /* Mask was reduced, let's update the entry */
5496 assert_se(hashmap_update(u->dependencies[d], other, di.data) == 0);
5497}
5498
5499void unit_remove_dependencies(Unit *u, UnitDependencyMask mask) {
c999cf38
LP
5500 assert(u);
5501
5502 /* Removes all dependencies u has on other units marked for ownership by 'mask'. */
5503
5504 if (mask == 0)
5505 return;
5506
f6173cb9 5507 for (UnitDependency d = 0; d < _UNIT_DEPENDENCY_MAX; d++) {
c999cf38
LP
5508 bool done;
5509
5510 do {
5511 UnitDependencyInfo di;
5512 Unit *other;
c999cf38
LP
5513
5514 done = true;
5515
90e74a66 5516 HASHMAP_FOREACH_KEY(di.data, other, u->dependencies[d]) {
1d6cc5d0 5517 if (FLAGS_SET(~mask, di.origin_mask))
c999cf38
LP
5518 continue;
5519 di.origin_mask &= ~mask;
5520 unit_update_dependency_mask(u, d, other, di);
5521
5522 /* We updated the dependency from our unit to the other unit now. But most dependencies
5523 * imply a reverse dependency. Hence, let's delete that one too. For that we go through
5524 * all dependency types on the other unit and delete all those which point to us and
5525 * have the right mask set. */
5526
f6173cb9 5527 for (UnitDependency q = 0; q < _UNIT_DEPENDENCY_MAX; q++) {
c999cf38
LP
5528 UnitDependencyInfo dj;
5529
5530 dj.data = hashmap_get(other->dependencies[q], u);
1d6cc5d0 5531 if (FLAGS_SET(~mask, dj.destination_mask))
c999cf38
LP
5532 continue;
5533 dj.destination_mask &= ~mask;
5534
5535 unit_update_dependency_mask(other, q, u, dj);
5536 }
5537
5538 unit_add_to_gc_queue(other);
5539
5540 done = false;
5541 break;
5542 }
5543
5544 } while (!done);
5545 }
5546}
d3070fbd 5547
2f8c48b6
AZ
5548static int unit_get_invocation_path(Unit *u, char **ret) {
5549 char *p;
5550 int r;
5551
5552 assert(u);
5553 assert(ret);
5554
5555 if (MANAGER_IS_SYSTEM(u->manager))
5556 p = strjoin("/run/systemd/units/invocation:", u->id);
5557 else {
5558 _cleanup_free_ char *user_path = NULL;
5559 r = xdg_user_runtime_dir(&user_path, "/systemd/units/invocation:");
5560 if (r < 0)
5561 return r;
5562 p = strjoin(user_path, u->id);
5563 }
5564
5565 if (!p)
5566 return -ENOMEM;
5567
5568 *ret = p;
5569 return 0;
5570}
5571
d3070fbd 5572static int unit_export_invocation_id(Unit *u) {
2f8c48b6 5573 _cleanup_free_ char *p = NULL;
d3070fbd
LP
5574 int r;
5575
5576 assert(u);
5577
5578 if (u->exported_invocation_id)
5579 return 0;
5580
5581 if (sd_id128_is_null(u->invocation_id))
5582 return 0;
5583
2f8c48b6
AZ
5584 r = unit_get_invocation_path(u, &p);
5585 if (r < 0)
5586 return log_unit_debug_errno(u, r, "Failed to get invocation path: %m");
5587
a3f5fd96 5588 r = symlink_atomic_label(u->invocation_id_string, p);
d3070fbd
LP
5589 if (r < 0)
5590 return log_unit_debug_errno(u, r, "Failed to create invocation ID symlink %s: %m", p);
5591
5592 u->exported_invocation_id = true;
5593 return 0;
5594}
5595
5596static int unit_export_log_level_max(Unit *u, const ExecContext *c) {
5597 const char *p;
5598 char buf[2];
5599 int r;
5600
5601 assert(u);
5602 assert(c);
5603
5604 if (u->exported_log_level_max)
5605 return 0;
5606
5607 if (c->log_level_max < 0)
5608 return 0;
5609
5610 assert(c->log_level_max <= 7);
5611
5612 buf[0] = '0' + c->log_level_max;
5613 buf[1] = 0;
5614
5615 p = strjoina("/run/systemd/units/log-level-max:", u->id);
5616 r = symlink_atomic(buf, p);
5617 if (r < 0)
5618 return log_unit_debug_errno(u, r, "Failed to create maximum log level symlink %s: %m", p);
5619
5620 u->exported_log_level_max = true;
5621 return 0;
5622}
5623
5624static int unit_export_log_extra_fields(Unit *u, const ExecContext *c) {
5625 _cleanup_close_ int fd = -1;
5626 struct iovec *iovec;
5627 const char *p;
5628 char *pattern;
5629 le64_t *sizes;
5630 ssize_t n;
d3070fbd
LP
5631 int r;
5632
5633 if (u->exported_log_extra_fields)
5634 return 0;
5635
5636 if (c->n_log_extra_fields <= 0)
5637 return 0;
5638
5639 sizes = newa(le64_t, c->n_log_extra_fields);
5640 iovec = newa(struct iovec, c->n_log_extra_fields * 2);
5641
12375b95 5642 for (size_t i = 0; i < c->n_log_extra_fields; i++) {
d3070fbd
LP
5643 sizes[i] = htole64(c->log_extra_fields[i].iov_len);
5644
5645 iovec[i*2] = IOVEC_MAKE(sizes + i, sizeof(le64_t));
5646 iovec[i*2+1] = c->log_extra_fields[i];
5647 }
5648
5649 p = strjoina("/run/systemd/units/log-extra-fields:", u->id);
5650 pattern = strjoina(p, ".XXXXXX");
5651
5652 fd = mkostemp_safe(pattern);
5653 if (fd < 0)
5654 return log_unit_debug_errno(u, fd, "Failed to create extra fields file %s: %m", p);
5655
5656 n = writev(fd, iovec, c->n_log_extra_fields*2);
5657 if (n < 0) {
5658 r = log_unit_debug_errno(u, errno, "Failed to write extra fields: %m");
5659 goto fail;
5660 }
5661
5662 (void) fchmod(fd, 0644);
5663
5664 if (rename(pattern, p) < 0) {
5665 r = log_unit_debug_errno(u, errno, "Failed to rename extra fields file: %m");
5666 goto fail;
5667 }
5668
5669 u->exported_log_extra_fields = true;
5670 return 0;
5671
5672fail:
5673 (void) unlink(pattern);
5674 return r;
5675}
5676
5ac1530e 5677static int unit_export_log_ratelimit_interval(Unit *u, const ExecContext *c) {
90fc172e
AZ
5678 _cleanup_free_ char *buf = NULL;
5679 const char *p;
5680 int r;
5681
5682 assert(u);
5683 assert(c);
5684
5ac1530e 5685 if (u->exported_log_ratelimit_interval)
90fc172e
AZ
5686 return 0;
5687
5ac1530e 5688 if (c->log_ratelimit_interval_usec == 0)
90fc172e
AZ
5689 return 0;
5690
5691 p = strjoina("/run/systemd/units/log-rate-limit-interval:", u->id);
5692
5ac1530e 5693 if (asprintf(&buf, "%" PRIu64, c->log_ratelimit_interval_usec) < 0)
90fc172e
AZ
5694 return log_oom();
5695
5696 r = symlink_atomic(buf, p);
5697 if (r < 0)
5698 return log_unit_debug_errno(u, r, "Failed to create log rate limit interval symlink %s: %m", p);
5699
5ac1530e 5700 u->exported_log_ratelimit_interval = true;
90fc172e
AZ
5701 return 0;
5702}
5703
5ac1530e 5704static int unit_export_log_ratelimit_burst(Unit *u, const ExecContext *c) {
90fc172e
AZ
5705 _cleanup_free_ char *buf = NULL;
5706 const char *p;
5707 int r;
5708
5709 assert(u);
5710 assert(c);
5711
5ac1530e 5712 if (u->exported_log_ratelimit_burst)
90fc172e
AZ
5713 return 0;
5714
5ac1530e 5715 if (c->log_ratelimit_burst == 0)
90fc172e
AZ
5716 return 0;
5717
5718 p = strjoina("/run/systemd/units/log-rate-limit-burst:", u->id);
5719
5ac1530e 5720 if (asprintf(&buf, "%u", c->log_ratelimit_burst) < 0)
90fc172e
AZ
5721 return log_oom();
5722
5723 r = symlink_atomic(buf, p);
5724 if (r < 0)
5725 return log_unit_debug_errno(u, r, "Failed to create log rate limit burst symlink %s: %m", p);
5726
5ac1530e 5727 u->exported_log_ratelimit_burst = true;
90fc172e
AZ
5728 return 0;
5729}
5730
d3070fbd
LP
5731void unit_export_state_files(Unit *u) {
5732 const ExecContext *c;
5733
5734 assert(u);
5735
5736 if (!u->id)
5737 return;
5738
638cece4 5739 if (MANAGER_IS_TEST_RUN(u->manager))
8f632531
LP
5740 return;
5741
d3070fbd
LP
5742 /* Exports a couple of unit properties to /run/systemd/units/, so that journald can quickly query this data
5743 * from there. Ideally, journald would use IPC to query this, like everybody else, but that's hard, as long as
5744 * the IPC system itself and PID 1 also log to the journal.
5745 *
5746 * Note that these files really shouldn't be considered API for anyone else, as use a runtime file system as
5747 * IPC replacement is not compatible with today's world of file system namespaces. However, this doesn't really
5748 * apply to communication between the journal and systemd, as we assume that these two daemons live in the same
5749 * namespace at least.
5750 *
5751 * Note that some of the "files" exported here are actually symlinks and not regular files. Symlinks work
5752 * better for storing small bits of data, in particular as we can write them with two system calls, and read
5753 * them with one. */
5754
5755 (void) unit_export_invocation_id(u);
5756
2f8c48b6
AZ
5757 if (!MANAGER_IS_SYSTEM(u->manager))
5758 return;
5759
d3070fbd
LP
5760 c = unit_get_exec_context(u);
5761 if (c) {
5762 (void) unit_export_log_level_max(u, c);
5763 (void) unit_export_log_extra_fields(u, c);
5ac1530e
ZJS
5764 (void) unit_export_log_ratelimit_interval(u, c);
5765 (void) unit_export_log_ratelimit_burst(u, c);
d3070fbd
LP
5766 }
5767}
5768
5769void unit_unlink_state_files(Unit *u) {
5770 const char *p;
5771
5772 assert(u);
5773
5774 if (!u->id)
5775 return;
5776
d3070fbd
LP
5777 /* Undoes the effect of unit_export_state() */
5778
5779 if (u->exported_invocation_id) {
2f8c48b6
AZ
5780 _cleanup_free_ char *invocation_path = NULL;
5781 int r = unit_get_invocation_path(u, &invocation_path);
5782 if (r >= 0) {
5783 (void) unlink(invocation_path);
5784 u->exported_invocation_id = false;
5785 }
d3070fbd
LP
5786 }
5787
2f8c48b6
AZ
5788 if (!MANAGER_IS_SYSTEM(u->manager))
5789 return;
5790
d3070fbd
LP
5791 if (u->exported_log_level_max) {
5792 p = strjoina("/run/systemd/units/log-level-max:", u->id);
5793 (void) unlink(p);
5794
5795 u->exported_log_level_max = false;
5796 }
5797
5798 if (u->exported_log_extra_fields) {
5799 p = strjoina("/run/systemd/units/extra-fields:", u->id);
5800 (void) unlink(p);
5801
5802 u->exported_log_extra_fields = false;
5803 }
90fc172e 5804
5ac1530e 5805 if (u->exported_log_ratelimit_interval) {
90fc172e
AZ
5806 p = strjoina("/run/systemd/units/log-rate-limit-interval:", u->id);
5807 (void) unlink(p);
5808
5ac1530e 5809 u->exported_log_ratelimit_interval = false;
90fc172e
AZ
5810 }
5811
5ac1530e 5812 if (u->exported_log_ratelimit_burst) {
90fc172e
AZ
5813 p = strjoina("/run/systemd/units/log-rate-limit-burst:", u->id);
5814 (void) unlink(p);
5815
5ac1530e 5816 u->exported_log_ratelimit_burst = false;
90fc172e 5817 }
d3070fbd 5818}
5afe510c 5819
3c7416b6
LP
5820int unit_prepare_exec(Unit *u) {
5821 int r;
5822
5823 assert(u);
5824
fab34748
KL
5825 /* Load any custom firewall BPF programs here once to test if they are existing and actually loadable.
5826 * Fail here early since later errors in the call chain unit_realize_cgroup to cgroup_context_apply are ignored. */
5827 r = bpf_firewall_load_custom(u);
5828 if (r < 0)
5829 return r;
5830
3c7416b6
LP
5831 /* Prepares everything so that we can fork of a process for this unit */
5832
5833 (void) unit_realize_cgroup(u);
5834
5835 if (u->reset_accounting) {
9b2559a1 5836 (void) unit_reset_accounting(u);
3c7416b6
LP
5837 u->reset_accounting = false;
5838 }
5839
5840 unit_export_state_files(u);
5841
5842 r = unit_setup_exec_runtime(u);
5843 if (r < 0)
5844 return r;
5845
5846 r = unit_setup_dynamic_creds(u);
5847 if (r < 0)
5848 return r;
5849
5850 return 0;
5851}
5852
4c425434
LP
5853static bool ignore_leftover_process(const char *comm) {
5854 return comm && comm[0] == '('; /* Most likely our own helper process (PAM?), ignore */
5855}
5856
5857int unit_log_leftover_process_start(pid_t pid, int sig, void *userdata) {
a4634b21
LP
5858 _cleanup_free_ char *comm = NULL;
5859
5860 (void) get_process_comm(pid, &comm);
5861
4c425434 5862 if (ignore_leftover_process(comm))
c53d2d54 5863 return 0;
a4634b21 5864
4c425434
LP
5865 /* During start we print a warning */
5866
a4634b21
LP
5867 log_unit_warning(userdata,
5868 "Found left-over process " PID_FMT " (%s) in control group while starting unit. Ignoring.\n"
5869 "This usually indicates unclean termination of a previous run, or service implementation deficiencies.",
5870 pid, strna(comm));
c53d2d54
DB
5871
5872 return 1;
a4634b21
LP
5873}
5874
4c425434
LP
5875int unit_log_leftover_process_stop(pid_t pid, int sig, void *userdata) {
5876 _cleanup_free_ char *comm = NULL;
5877
5878 (void) get_process_comm(pid, &comm);
5879
5880 if (ignore_leftover_process(comm))
5881 return 0;
5882
5883 /* During stop we only print an informational message */
5884
5885 log_unit_info(userdata,
5886 "Unit process " PID_FMT " (%s) remains running after unit stopped.",
5887 pid, strna(comm));
5888
5889 return 1;
5890}
5891
5892int unit_warn_leftover_processes(Unit *u, cg_kill_log_func_t log_func) {
a4634b21
LP
5893 assert(u);
5894
5895 (void) unit_pick_cgroup_path(u);
5896
5897 if (!u->cgroup_path)
c53d2d54 5898 return 0;
a4634b21 5899
4c425434 5900 return cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, 0, 0, NULL, log_func, u);
a4634b21
LP
5901}
5902
bb2c7685
LP
5903bool unit_needs_console(Unit *u) {
5904 ExecContext *ec;
5905 UnitActiveState state;
5906
5907 assert(u);
5908
5909 state = unit_active_state(u);
5910
5911 if (UNIT_IS_INACTIVE_OR_FAILED(state))
5912 return false;
5913
5914 if (UNIT_VTABLE(u)->needs_console)
5915 return UNIT_VTABLE(u)->needs_console(u);
5916
5917 /* If this unit type doesn't implement this call, let's use a generic fallback implementation: */
5918 ec = unit_get_exec_context(u);
5919 if (!ec)
5920 return false;
5921
5922 return exec_context_may_touch_console(ec);
5923}
5924
f156e60c 5925const char *unit_label_path(const Unit *u) {
81e9871e
LP
5926 const char *p;
5927
f156e60c
CG
5928 assert(u);
5929
81e9871e
LP
5930 /* Returns the file system path to use for MAC access decisions, i.e. the file to read the SELinux label off
5931 * when validating access checks. */
5932
5933 p = u->source_path ?: u->fragment_path;
5934 if (!p)
5935 return NULL;
5936
5937 /* If a unit is masked, then don't read the SELinux label of /dev/null, as that really makes no sense */
640f3b14 5938 if (null_or_empty_path(p) > 0)
81e9871e
LP
5939 return NULL;
5940
5941 return p;
5942}
5943
6592b975
LP
5944int unit_pid_attachable(Unit *u, pid_t pid, sd_bus_error *error) {
5945 int r;
5946
5947 assert(u);
5948
5949 /* Checks whether the specified PID is generally good for attaching, i.e. a valid PID, not our manager itself,
5950 * and not a kernel thread either */
5951
5952 /* First, a simple range check */
5953 if (!pid_is_valid(pid))
5954 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Process identifier " PID_FMT " is not valid.", pid);
5955
5956 /* Some extra safety check */
5957 if (pid == 1 || pid == getpid_cached())
3fe91079 5958 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Process " PID_FMT " is a manager process, refusing.", pid);
6592b975
LP
5959
5960 /* Don't even begin to bother with kernel threads */
5961 r = is_kernel_thread(pid);
5962 if (r == -ESRCH)
5963 return sd_bus_error_setf(error, SD_BUS_ERROR_UNIX_PROCESS_ID_UNKNOWN, "Process with ID " PID_FMT " does not exist.", pid);
5964 if (r < 0)
5965 return sd_bus_error_set_errnof(error, r, "Failed to determine whether process " PID_FMT " is a kernel thread: %m", pid);
5966 if (r > 0)
5967 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Process " PID_FMT " is a kernel thread, refusing.", pid);
5968
5969 return 0;
5970}
5971
523ee2d4
LP
5972void unit_log_success(Unit *u) {
5973 assert(u);
5974
5975 log_struct(LOG_INFO,
5976 "MESSAGE_ID=" SD_MESSAGE_UNIT_SUCCESS_STR,
5977 LOG_UNIT_ID(u),
5978 LOG_UNIT_INVOCATION_ID(u),
5979 LOG_UNIT_MESSAGE(u, "Succeeded."));
5980}
5981
7c047d74
LP
5982void unit_log_failure(Unit *u, const char *result) {
5983 assert(u);
5984 assert(result);
5985
5986 log_struct(LOG_WARNING,
5987 "MESSAGE_ID=" SD_MESSAGE_UNIT_FAILURE_RESULT_STR,
5988 LOG_UNIT_ID(u),
5989 LOG_UNIT_INVOCATION_ID(u),
5990 LOG_UNIT_MESSAGE(u, "Failed with result '%s'.", result),
5991 "UNIT_RESULT=%s", result);
5992}
5993
31cd5f63
AZ
5994void unit_log_skip(Unit *u, const char *result) {
5995 assert(u);
5996 assert(result);
5997
5998 log_struct(LOG_INFO,
5999 "MESSAGE_ID=" SD_MESSAGE_UNIT_SKIPPED_STR,
6000 LOG_UNIT_ID(u),
6001 LOG_UNIT_INVOCATION_ID(u),
6002 LOG_UNIT_MESSAGE(u, "Skipped due to '%s'.", result),
6003 "UNIT_RESULT=%s", result);
6004}
6005
91bbd9b7
LP
6006void unit_log_process_exit(
6007 Unit *u,
91bbd9b7
LP
6008 const char *kind,
6009 const char *command,
5cc2cd1c 6010 bool success,
91bbd9b7
LP
6011 int code,
6012 int status) {
6013
5cc2cd1c
ZJS
6014 int level;
6015
91bbd9b7
LP
6016 assert(u);
6017 assert(kind);
6018
5cc2cd1c
ZJS
6019 /* If this is a successful exit, let's log about the exit code on DEBUG level. If this is a failure
6020 * and the process exited on its own via exit(), then let's make this a NOTICE, under the assumption
6021 * that the service already logged the reason at a higher log level on its own. Otherwise, make it a
6022 * WARNING. */
6023 if (success)
6024 level = LOG_DEBUG;
6025 else if (code == CLD_EXITED)
6026 level = LOG_NOTICE;
6027 else
91bbd9b7
LP
6028 level = LOG_WARNING;
6029
6030 log_struct(level,
6031 "MESSAGE_ID=" SD_MESSAGE_UNIT_PROCESS_EXIT_STR,
6032 LOG_UNIT_MESSAGE(u, "%s exited, code=%s, status=%i/%s",
6033 kind,
6034 sigchld_code_to_string(code), status,
6035 strna(code == CLD_EXITED
6036 ? exit_status_to_string(status, EXIT_STATUS_FULL)
6037 : signal_to_string(status))),
6038 "EXIT_CODE=%s", sigchld_code_to_string(code),
6039 "EXIT_STATUS=%i", status,
6040 "COMMAND=%s", strna(command),
6041 LOG_UNIT_ID(u),
6042 LOG_UNIT_INVOCATION_ID(u));
6043}
6044
7af67e9a
LP
6045int unit_exit_status(Unit *u) {
6046 assert(u);
6047
6048 /* Returns the exit status to propagate for the most recent cycle of this unit. Returns a value in the range
6049 * 0…255 if there's something to propagate. EOPNOTSUPP if the concept does not apply to this unit type, ENODATA
6050 * if no data is currently known (for example because the unit hasn't deactivated yet) and EBADE if the main
6051 * service process has exited abnormally (signal/coredump). */
6052
6053 if (!UNIT_VTABLE(u)->exit_status)
6054 return -EOPNOTSUPP;
6055
6056 return UNIT_VTABLE(u)->exit_status(u);
6057}
6058
6059int unit_failure_action_exit_status(Unit *u) {
6060 int r;
6061
6062 assert(u);
6063
6064 /* Returns the exit status to propagate on failure, or an error if there's nothing to propagate */
6065
6066 if (u->failure_action_exit_status >= 0)
6067 return u->failure_action_exit_status;
6068
6069 r = unit_exit_status(u);
6070 if (r == -EBADE) /* Exited, but not cleanly (i.e. by signal or such) */
6071 return 255;
6072
6073 return r;
6074}
6075
6076int unit_success_action_exit_status(Unit *u) {
6077 int r;
6078
6079 assert(u);
6080
6081 /* Returns the exit status to propagate on success, or an error if there's nothing to propagate */
6082
6083 if (u->success_action_exit_status >= 0)
6084 return u->success_action_exit_status;
6085
6086 r = unit_exit_status(u);
6087 if (r == -EBADE) /* Exited, but not cleanly (i.e. by signal or such) */
6088 return 255;
6089
6090 return r;
6091}
6092
a4191c9f
LP
6093int unit_test_trigger_loaded(Unit *u) {
6094 Unit *trigger;
6095
6096 /* Tests whether the unit to trigger is loaded */
6097
6098 trigger = UNIT_TRIGGER(u);
6099 if (!trigger)
e7b9f4d9
ZJS
6100 return log_unit_error_errno(u, SYNTHETIC_ERRNO(ENOENT),
6101 "Refusing to start, no unit to trigger.");
a4191c9f 6102 if (trigger->load_state != UNIT_LOADED)
e7b9f4d9
ZJS
6103 return log_unit_error_errno(u, SYNTHETIC_ERRNO(ENOENT),
6104 "Refusing to start, unit %s to trigger not loaded.", trigger->id);
a4191c9f
LP
6105
6106 return 0;
6107}
6108
bb0c0d6f
LP
6109void unit_destroy_runtime_data(Unit *u, const ExecContext *context) {
6110 assert(u);
6111 assert(context);
6112
95939aed
YW
6113 if (context->runtime_directory_preserve_mode == EXEC_PRESERVE_NO ||
6114 (context->runtime_directory_preserve_mode == EXEC_PRESERVE_RESTART && !unit_will_restart(u)))
6115 exec_context_destroy_runtime_directory(context, u->manager->prefix[EXEC_DIRECTORY_RUNTIME]);
bb0c0d6f
LP
6116
6117 exec_context_destroy_credentials(context, u->manager->prefix[EXEC_DIRECTORY_RUNTIME], u->id);
95939aed
YW
6118}
6119
380dc8b0
LP
6120int unit_clean(Unit *u, ExecCleanMask mask) {
6121 UnitActiveState state;
6122
6123 assert(u);
6124
6125 /* Special return values:
6126 *
6127 * -EOPNOTSUPP → cleaning not supported for this unit type
6128 * -EUNATCH → cleaning not defined for this resource type
6129 * -EBUSY → unit currently can't be cleaned since it's running or not properly loaded, or has
6130 * a job queued or similar
6131 */
6132
6133 if (!UNIT_VTABLE(u)->clean)
6134 return -EOPNOTSUPP;
6135
6136 if (mask == 0)
6137 return -EUNATCH;
6138
6139 if (u->load_state != UNIT_LOADED)
6140 return -EBUSY;
6141
6142 if (u->job)
6143 return -EBUSY;
6144
6145 state = unit_active_state(u);
6146 if (!IN_SET(state, UNIT_INACTIVE))
6147 return -EBUSY;
6148
6149 return UNIT_VTABLE(u)->clean(u, mask);
6150}
6151
6152int unit_can_clean(Unit *u, ExecCleanMask *ret) {
6153 assert(u);
6154
6155 if (!UNIT_VTABLE(u)->clean ||
6156 u->load_state != UNIT_LOADED) {
6157 *ret = 0;
6158 return 0;
6159 }
6160
6161 /* When the clean() method is set, can_clean() really should be set too */
6162 assert(UNIT_VTABLE(u)->can_clean);
6163
6164 return UNIT_VTABLE(u)->can_clean(u, ret);
6165}
6166
d9e45bc3
MS
6167bool unit_can_freeze(Unit *u) {
6168 assert(u);
6169
6170 if (UNIT_VTABLE(u)->can_freeze)
6171 return UNIT_VTABLE(u)->can_freeze(u);
6172
6173 return UNIT_VTABLE(u)->freeze;
6174}
6175
6176void unit_frozen(Unit *u) {
6177 assert(u);
6178
6179 u->freezer_state = FREEZER_FROZEN;
6180
6181 bus_unit_send_pending_freezer_message(u);
6182}
6183
6184void unit_thawed(Unit *u) {
6185 assert(u);
6186
6187 u->freezer_state = FREEZER_RUNNING;
6188
6189 bus_unit_send_pending_freezer_message(u);
6190}
6191
6192static int unit_freezer_action(Unit *u, FreezerAction action) {
6193 UnitActiveState s;
6194 int (*method)(Unit*);
6195 int r;
6196
6197 assert(u);
6198 assert(IN_SET(action, FREEZER_FREEZE, FREEZER_THAW));
6199
6200 method = action == FREEZER_FREEZE ? UNIT_VTABLE(u)->freeze : UNIT_VTABLE(u)->thaw;
6201 if (!method || !cg_freezer_supported())
6202 return -EOPNOTSUPP;
6203
6204 if (u->job)
6205 return -EBUSY;
6206
6207 if (u->load_state != UNIT_LOADED)
6208 return -EHOSTDOWN;
6209
6210 s = unit_active_state(u);
6211 if (s != UNIT_ACTIVE)
6212 return -EHOSTDOWN;
6213
6214 if (IN_SET(u->freezer_state, FREEZER_FREEZING, FREEZER_THAWING))
6215 return -EALREADY;
6216
6217 r = method(u);
6218 if (r <= 0)
6219 return r;
6220
6221 return 1;
6222}
6223
6224int unit_freeze(Unit *u) {
6225 return unit_freezer_action(u, FREEZER_FREEZE);
6226}
6227
6228int unit_thaw(Unit *u) {
6229 return unit_freezer_action(u, FREEZER_THAW);
6230}
6231
6232/* Wrappers around low-level cgroup freezer operations common for service and scope units */
6233int unit_freeze_vtable_common(Unit *u) {
6234 return unit_cgroup_freezer_action(u, FREEZER_FREEZE);
6235}
6236
6237int unit_thaw_vtable_common(Unit *u) {
6238 return unit_cgroup_freezer_action(u, FREEZER_THAW);
6239}
6240
5afe510c
LP
6241static const char* const collect_mode_table[_COLLECT_MODE_MAX] = {
6242 [COLLECT_INACTIVE] = "inactive",
6243 [COLLECT_INACTIVE_OR_FAILED] = "inactive-or-failed",
6244};
6245
6246DEFINE_STRING_TABLE_LOOKUP(collect_mode, CollectMode);