]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/unit.c
rules: set SYSTEMD_READY=0 on DM_UDEV_DISABLE_OTHER_RULES_FLAG=1 only with ADD event...
[thirdparty/systemd.git] / src / core / unit.c
CommitLineData
a7334b09
LP
1/***
2 This file is part of systemd.
3
4 Copyright 2010 Lennart Poettering
5
6 systemd is free software; you can redistribute it and/or modify it
5430f7f2
LP
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
a7334b09
LP
9 (at your option) any later version.
10
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
5430f7f2 14 Lesser General Public License for more details.
a7334b09 15
5430f7f2 16 You should have received a copy of the GNU Lesser General Public License
a7334b09
LP
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
18***/
19
87f0e418 20#include <errno.h>
0301abf4 21#include <stdlib.h>
4f5dd394 22#include <string.h>
45fb0699 23#include <sys/stat.h>
4f5dd394 24#include <unistd.h>
87f0e418 25
718db961
LP
26#include "sd-id128.h"
27#include "sd-messages.h"
4f5dd394 28
b5efdb8a 29#include "alloc-util.h"
4f5dd394
LP
30#include "bus-common-errors.h"
31#include "bus-util.h"
c6c18be3 32#include "cgroup-util.h"
4f5dd394
LP
33#include "dbus-unit.h"
34#include "dbus.h"
35#include "dropin.h"
36#include "escape.h"
37#include "execute.h"
a5c32cff 38#include "fileio-label.h"
6482f626 39#include "formats-util.h"
4f5dd394
LP
40#include "load-dropin.h"
41#include "load-fragment.h"
42#include "log.h"
43#include "macro.h"
44#include "missing.h"
45#include "mkdir.h"
6bedfcbb 46#include "parse-util.h"
4f5dd394 47#include "path-util.h"
0b452006 48#include "process-util.h"
4f5dd394 49#include "set.h"
e9db43d5 50#include "special.h"
8fcde012 51#include "stat-util.h"
d054f0a4 52#include "stdio-util.h"
07630cea 53#include "string-util.h"
4f5dd394
LP
54#include "strv.h"
55#include "unit-name.h"
e9db43d5 56#include "unit.h"
b1d4f8e1
LP
57#include "user-util.h"
58#include "virt.h"
87f0e418
LP
59
60const UnitVTable * const unit_vtable[_UNIT_TYPE_MAX] = {
61 [UNIT_SERVICE] = &service_vtable,
87f0e418 62 [UNIT_SOCKET] = &socket_vtable,
e821075a 63 [UNIT_BUSNAME] = &busname_vtable,
87f0e418
LP
64 [UNIT_TARGET] = &target_vtable,
65 [UNIT_DEVICE] = &device_vtable,
66 [UNIT_MOUNT] = &mount_vtable,
67 [UNIT_AUTOMOUNT] = &automount_vtable,
01f78473 68 [UNIT_SWAP] = &swap_vtable,
e821075a 69 [UNIT_TIMER] = &timer_vtable,
a016b922 70 [UNIT_PATH] = &path_vtable,
6c12b52e
LP
71 [UNIT_SLICE] = &slice_vtable,
72 [UNIT_SCOPE] = &scope_vtable
87f0e418
LP
73};
74
f2341e0a 75static void maybe_warn_about_dependency(Unit *u, const char *other, UnitDependency dependency);
d1fab3fe 76
7d17cfbc 77Unit *unit_new(Manager *m, size_t size) {
87f0e418
LP
78 Unit *u;
79
80 assert(m);
ac155bb8 81 assert(size >= sizeof(Unit));
87f0e418 82
7d17cfbc
MS
83 u = malloc0(size);
84 if (!u)
87f0e418
LP
85 return NULL;
86
d5099efc 87 u->names = set_new(&string_hash_ops);
ac155bb8 88 if (!u->names) {
87f0e418
LP
89 free(u);
90 return NULL;
91 }
92
ac155bb8
MS
93 u->manager = m;
94 u->type = _UNIT_TYPE_INVALID;
ac155bb8
MS
95 u->default_dependencies = true;
96 u->unit_file_state = _UNIT_FILE_STATE_INVALID;
d2dc52db 97 u->unit_file_preset = -1;
d420282b 98 u->on_failure_job_mode = JOB_REPLACE;
efdb0237 99 u->cgroup_inotify_wd = -1;
36c16a7c 100 u->job_timeout = USEC_INFINITY;
87f0e418 101
6bf0f408 102 RATELIMIT_INIT(u->start_limit, m->default_start_limit_interval, m->default_start_limit_burst);
67bfdc97 103 RATELIMIT_INIT(u->auto_stop_ratelimit, 10 * USEC_PER_SEC, 16);
bea355da 104
87f0e418
LP
105 return u;
106}
107
f278026d
LP
108bool unit_has_name(Unit *u, const char *name) {
109 assert(u);
110 assert(name);
111
ac155bb8 112 return !!set_get(u->names, (char*) name);
f278026d
LP
113}
114
598459ce
LP
115static void unit_init(Unit *u) {
116 CGroupContext *cc;
117 ExecContext *ec;
118 KillContext *kc;
119
120 assert(u);
121 assert(u->manager);
122 assert(u->type >= 0);
123
124 cc = unit_get_cgroup_context(u);
125 if (cc) {
126 cgroup_context_init(cc);
127
128 /* Copy in the manager defaults into the cgroup
129 * context, _before_ the rest of the settings have
130 * been initialized */
131
132 cc->cpu_accounting = u->manager->default_cpu_accounting;
133 cc->blockio_accounting = u->manager->default_blockio_accounting;
134 cc->memory_accounting = u->manager->default_memory_accounting;
03a7b521 135 cc->tasks_accounting = u->manager->default_tasks_accounting;
0af20ea2
LP
136
137 if (u->type != UNIT_SLICE)
138 cc->tasks_max = u->manager->default_tasks_max;
598459ce
LP
139 }
140
141 ec = unit_get_exec_context(u);
142 if (ec)
143 exec_context_init(ec);
144
145 kc = unit_get_kill_context(u);
146 if (kc)
147 kill_context_init(kc);
148
149 if (UNIT_VTABLE(u)->init)
150 UNIT_VTABLE(u)->init(u);
151}
152
87f0e418 153int unit_add_name(Unit *u, const char *text) {
598459ce 154 _cleanup_free_ char *s = NULL, *i = NULL;
87f0e418 155 UnitType t;
87f0e418
LP
156 int r;
157
158 assert(u);
159 assert(text);
160
7410616c 161 if (unit_name_is_valid(text, UNIT_NAME_TEMPLATE)) {
598459ce 162
ac155bb8 163 if (!u->instance)
9e2f7c11 164 return -EINVAL;
87f0e418 165
7410616c
LP
166 r = unit_name_replace_instance(text, u->instance, &s);
167 if (r < 0)
168 return r;
169 } else {
9e2f7c11 170 s = strdup(text);
7410616c
LP
171 if (!s)
172 return -ENOMEM;
173 }
87f0e418 174
7410616c
LP
175 if (set_contains(u->names, s))
176 return 0;
177 if (hashmap_contains(u->manager->units, s))
178 return -EEXIST;
179
180 if (!unit_name_is_valid(s, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
598459ce 181 return -EINVAL;
e537352b 182
7410616c
LP
183 t = unit_name_to_type(s);
184 if (t < 0)
185 return -EINVAL;
87f0e418 186
598459ce
LP
187 if (u->type != _UNIT_TYPE_INVALID && t != u->type)
188 return -EINVAL;
87f0e418 189
e48614c4
ZJS
190 r = unit_name_to_instance(s, &i);
191 if (r < 0)
598459ce 192 return r;
87f0e418 193
598459ce
LP
194 if (i && unit_vtable[t]->no_instances)
195 return -EINVAL;
9e2f7c11 196
276c3e78 197 /* Ensure that this unit is either instanced or not instanced,
7410616c
LP
198 * but not both. Note that we do allow names with different
199 * instance names however! */
598459ce
LP
200 if (u->type != _UNIT_TYPE_INVALID && !u->instance != !i)
201 return -EINVAL;
9e2f7c11 202
7410616c 203 if (unit_vtable[t]->no_alias && !set_isempty(u->names))
598459ce 204 return -EEXIST;
9e2f7c11 205
598459ce
LP
206 if (hashmap_size(u->manager->units) >= MANAGER_MAX_NAMES)
207 return -E2BIG;
4f0f902f 208
e48614c4 209 r = set_put(u->names, s);
7410616c 210 if (r < 0)
598459ce 211 return r;
7410616c 212 assert(r > 0);
87f0e418 213
e48614c4
ZJS
214 r = hashmap_put(u->manager->units, s, u);
215 if (r < 0) {
7410616c 216 (void) set_remove(u->names, s);
598459ce 217 return r;
87f0e418
LP
218 }
219
ac155bb8 220 if (u->type == _UNIT_TYPE_INVALID) {
ac155bb8
MS
221 u->type = t;
222 u->id = s;
223 u->instance = i;
9e2f7c11 224
71fda00f 225 LIST_PREPEND(units_by_type, u->manager->units_by_type[t], u);
e537352b 226
598459ce 227 unit_init(u);
87f0e418 228
598459ce
LP
229 i = NULL;
230 }
9e2f7c11 231
598459ce 232 s = NULL;
9e2f7c11 233
598459ce
LP
234 unit_add_to_dbus_queue(u);
235 return 0;
87f0e418
LP
236}
237
0ae97ec1 238int unit_choose_id(Unit *u, const char *name) {
68eda4bd 239 _cleanup_free_ char *t = NULL;
598459ce 240 char *s, *i;
276c3e78 241 int r;
0ae97ec1
LP
242
243 assert(u);
244 assert(name);
245
7410616c 246 if (unit_name_is_valid(name, UNIT_NAME_TEMPLATE)) {
9e2f7c11 247
ac155bb8 248 if (!u->instance)
9e2f7c11
LP
249 return -EINVAL;
250
7410616c
LP
251 r = unit_name_replace_instance(name, u->instance, &t);
252 if (r < 0)
253 return r;
9e2f7c11
LP
254
255 name = t;
256 }
257
0ae97ec1 258 /* Selects one of the names of this unit as the id */
ac155bb8 259 s = set_get(u->names, (char*) name);
9e2f7c11 260 if (!s)
0ae97ec1
LP
261 return -ENOENT;
262
7410616c 263 /* Determine the new instance from the new id */
e48614c4
ZJS
264 r = unit_name_to_instance(s, &i);
265 if (r < 0)
276c3e78
LP
266 return r;
267
ac155bb8 268 u->id = s;
276c3e78 269
ac155bb8
MS
270 free(u->instance);
271 u->instance = i;
276c3e78 272
c1e1601e 273 unit_add_to_dbus_queue(u);
9e2f7c11 274
0ae97ec1
LP
275 return 0;
276}
277
f50e0a01
LP
278int unit_set_description(Unit *u, const char *description) {
279 char *s;
280
281 assert(u);
282
8aec412f
LP
283 if (isempty(description))
284 s = NULL;
285 else {
286 s = strdup(description);
287 if (!s)
288 return -ENOMEM;
289 }
f50e0a01 290
ac155bb8
MS
291 free(u->description);
292 u->description = s;
c1e1601e
LP
293
294 unit_add_to_dbus_queue(u);
f50e0a01
LP
295 return 0;
296}
297
701cc384 298bool unit_check_gc(Unit *u) {
a354329f 299 UnitActiveState state;
701cc384
LP
300 assert(u);
301
a354329f 302 if (u->job)
701cc384
LP
303 return true;
304
a354329f 305 if (u->nop_job)
6c073082
LP
306 return true;
307
a354329f
LP
308 state = unit_active_state(u);
309
310 /* If the unit is inactive and failed and no job is queued for
311 * it, then release its runtime resources */
312 if (UNIT_IS_INACTIVE_OR_FAILED(state) &&
313 UNIT_VTABLE(u)->release_resources)
314 UNIT_VTABLE(u)->release_resources(u);
315
316 /* But we keep the unit object around for longer when it is
317 * referenced or configured to not be gc'ed */
318 if (state != UNIT_INACTIVE)
701cc384
LP
319 return true;
320
a354329f 321 if (u->no_gc)
701cc384
LP
322 return true;
323
9d576438
LP
324 if (u->refs)
325 return true;
326
701cc384
LP
327 if (UNIT_VTABLE(u)->check_gc)
328 if (UNIT_VTABLE(u)->check_gc(u))
329 return true;
330
331 return false;
332}
333
87f0e418
LP
334void unit_add_to_load_queue(Unit *u) {
335 assert(u);
ac155bb8 336 assert(u->type != _UNIT_TYPE_INVALID);
87f0e418 337
ac155bb8 338 if (u->load_state != UNIT_STUB || u->in_load_queue)
87f0e418
LP
339 return;
340
71fda00f 341 LIST_PREPEND(load_queue, u->manager->load_queue, u);
ac155bb8 342 u->in_load_queue = true;
87f0e418
LP
343}
344
23a177ef
LP
345void unit_add_to_cleanup_queue(Unit *u) {
346 assert(u);
347
ac155bb8 348 if (u->in_cleanup_queue)
23a177ef
LP
349 return;
350
71fda00f 351 LIST_PREPEND(cleanup_queue, u->manager->cleanup_queue, u);
ac155bb8 352 u->in_cleanup_queue = true;
23a177ef
LP
353}
354
701cc384
LP
355void unit_add_to_gc_queue(Unit *u) {
356 assert(u);
357
ac155bb8 358 if (u->in_gc_queue || u->in_cleanup_queue)
701cc384
LP
359 return;
360
361 if (unit_check_gc(u))
362 return;
363
71fda00f 364 LIST_PREPEND(gc_queue, u->manager->gc_queue, u);
ac155bb8 365 u->in_gc_queue = true;
701cc384 366
313cefa1 367 u->manager->n_in_gc_queue++;
701cc384
LP
368}
369
c1e1601e
LP
370void unit_add_to_dbus_queue(Unit *u) {
371 assert(u);
ac155bb8 372 assert(u->type != _UNIT_TYPE_INVALID);
c1e1601e 373
ac155bb8 374 if (u->load_state == UNIT_STUB || u->in_dbus_queue)
c1e1601e
LP
375 return;
376
a567261a 377 /* Shortcut things if nobody cares */
8f8f05a9
LP
378 if (sd_bus_track_count(u->manager->subscribed) <= 0 &&
379 set_isempty(u->manager->private_buses)) {
ac155bb8 380 u->sent_dbus_new_signal = true;
94b6dfa2
LP
381 return;
382 }
383
71fda00f 384 LIST_PREPEND(dbus_queue, u->manager->dbus_unit_queue, u);
ac155bb8 385 u->in_dbus_queue = true;
c1e1601e
LP
386}
387
87f0e418
LP
388static void bidi_set_free(Unit *u, Set *s) {
389 Iterator i;
390 Unit *other;
391
392 assert(u);
393
394 /* Frees the set and makes sure we are dropped from the
395 * inverse pointers */
396
397 SET_FOREACH(other, s, i) {
398 UnitDependency d;
399
400 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
ac155bb8 401 set_remove(other->dependencies[d], u);
701cc384
LP
402
403 unit_add_to_gc_queue(other);
87f0e418
LP
404 }
405
406 set_free(s);
407}
408
c2756a68
LP
409static void unit_remove_transient(Unit *u) {
410 char **i;
411
412 assert(u);
413
414 if (!u->transient)
415 return;
416
417 if (u->fragment_path)
3f5e8115 418 (void) unlink(u->fragment_path);
c2756a68
LP
419
420 STRV_FOREACH(i, u->dropin_paths) {
421 _cleanup_free_ char *p = NULL;
c2756a68 422
3f5e8115 423 (void) unlink(*i);
c2756a68 424
5f311f8c
LP
425 p = dirname_malloc(*i);
426 if (p)
3f5e8115 427 (void) rmdir(p);
c2756a68
LP
428 }
429}
430
a57f7e2c
LP
431static void unit_free_requires_mounts_for(Unit *u) {
432 char **j;
433
434 STRV_FOREACH(j, u->requires_mounts_for) {
435 char s[strlen(*j) + 1];
436
437 PATH_FOREACH_PREFIX_MORE(s, *j) {
438 char *y;
439 Set *x;
440
441 x = hashmap_get2(u->manager->units_requiring_mounts_for, s, (void**) &y);
442 if (!x)
443 continue;
444
445 set_remove(x, u);
446
447 if (set_isempty(x)) {
448 hashmap_remove(u->manager->units_requiring_mounts_for, y);
449 free(y);
450 set_free(x);
451 }
452 }
453 }
454
6796073e 455 u->requires_mounts_for = strv_free(u->requires_mounts_for);
a57f7e2c
LP
456}
457
598459ce
LP
458static void unit_done(Unit *u) {
459 ExecContext *ec;
460 CGroupContext *cc;
461
462 assert(u);
463
464 if (u->type < 0)
465 return;
466
467 if (UNIT_VTABLE(u)->done)
468 UNIT_VTABLE(u)->done(u);
469
470 ec = unit_get_exec_context(u);
471 if (ec)
472 exec_context_done(ec);
473
474 cc = unit_get_cgroup_context(u);
475 if (cc)
476 cgroup_context_done(cc);
477}
478
87f0e418
LP
479void unit_free(Unit *u) {
480 UnitDependency d;
481 Iterator i;
482 char *t;
483
484 assert(u);
485
c2756a68
LP
486 if (u->manager->n_reloading <= 0)
487 unit_remove_transient(u);
488
c1e1601e
LP
489 bus_unit_send_removed_signal(u);
490
598459ce 491 unit_done(u);
a013b84b 492
cf9fd508
DM
493 sd_bus_slot_unref(u->match_bus_slot);
494
a57f7e2c
LP
495 unit_free_requires_mounts_for(u);
496
ac155bb8
MS
497 SET_FOREACH(t, u->names, i)
498 hashmap_remove_value(u->manager->units, t, u);
87f0e418 499
97e7d748
MS
500 if (u->job) {
501 Job *j = u->job;
502 job_uninstall(j);
503 job_free(j);
504 }
964e0949 505
e0209d83
MS
506 if (u->nop_job) {
507 Job *j = u->nop_job;
508 job_uninstall(j);
509 job_free(j);
510 }
511
964e0949 512 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
ac155bb8 513 bidi_set_free(u, u->dependencies[d]);
964e0949 514
ac155bb8 515 if (u->type != _UNIT_TYPE_INVALID)
71fda00f 516 LIST_REMOVE(units_by_type, u->manager->units_by_type[u->type], u);
ef734fd6 517
ac155bb8 518 if (u->in_load_queue)
71fda00f 519 LIST_REMOVE(load_queue, u->manager->load_queue, u);
87f0e418 520
ac155bb8 521 if (u->in_dbus_queue)
71fda00f 522 LIST_REMOVE(dbus_queue, u->manager->dbus_unit_queue, u);
c1e1601e 523
ac155bb8 524 if (u->in_cleanup_queue)
71fda00f 525 LIST_REMOVE(cleanup_queue, u->manager->cleanup_queue, u);
23a177ef 526
ac155bb8 527 if (u->in_gc_queue) {
71fda00f 528 LIST_REMOVE(gc_queue, u->manager->gc_queue, u);
ac155bb8 529 u->manager->n_in_gc_queue--;
701cc384
LP
530 }
531
4ad49000 532 if (u->in_cgroup_queue)
71fda00f 533 LIST_REMOVE(cgroup_queue, u->manager->cgroup_queue, u);
87f0e418 534
efdb0237 535 unit_release_cgroup(u);
72673e86 536
5269eb6b 537 (void) manager_update_failed_units(u->manager, u, false);
db785129 538 set_remove(u->manager->startup_units, u);
f755e3b7 539
ac155bb8 540 free(u->description);
49dbfa7b 541 strv_free(u->documentation);
ac155bb8 542 free(u->fragment_path);
1b64d026 543 free(u->source_path);
ae7a7182 544 strv_free(u->dropin_paths);
ac155bb8 545 free(u->instance);
87f0e418 546
f189ab18
LP
547 free(u->job_timeout_reboot_arg);
548
ac155bb8 549 set_free_free(u->names);
87f0e418 550
a911bb9a
LP
551 unit_unwatch_all_pids(u);
552
ac155bb8 553 condition_free_list(u->conditions);
59fccdc5 554 condition_free_list(u->asserts);
52661efd 555
6bf0f408
LP
556 free(u->reboot_arg);
557
702a2d8f
LP
558 unit_ref_unset(&u->slice);
559
ac155bb8
MS
560 while (u->refs)
561 unit_ref_unset(u->refs);
57020a3a 562
87f0e418
LP
563 free(u);
564}
565
566UnitActiveState unit_active_state(Unit *u) {
567 assert(u);
568
ac155bb8 569 if (u->load_state == UNIT_MERGED)
6124958c
LP
570 return unit_active_state(unit_follow_merge(u));
571
572 /* After a reload it might happen that a unit is not correctly
573 * loaded but still has a process around. That's why we won't
fdf20a31 574 * shortcut failed loading to UNIT_INACTIVE_FAILED. */
87f0e418
LP
575
576 return UNIT_VTABLE(u)->active_state(u);
577}
578
10a94420
LP
579const char* unit_sub_state_to_string(Unit *u) {
580 assert(u);
581
582 return UNIT_VTABLE(u)->sub_state_to_string(u);
583}
584
7c0b05e5
MS
585static int complete_move(Set **s, Set **other) {
586 int r;
587
23a177ef
LP
588 assert(s);
589 assert(other);
87f0e418 590
23a177ef 591 if (!*other)
7c0b05e5 592 return 0;
87f0e418 593
7c0b05e5
MS
594 if (*s) {
595 r = set_move(*s, *other);
596 if (r < 0)
597 return r;
598 } else {
23a177ef
LP
599 *s = *other;
600 *other = NULL;
601 }
7c0b05e5
MS
602
603 return 0;
23a177ef 604}
87f0e418 605
7c0b05e5 606static int merge_names(Unit *u, Unit *other) {
23a177ef
LP
607 char *t;
608 Iterator i;
7c0b05e5 609 int r;
87f0e418 610
23a177ef
LP
611 assert(u);
612 assert(other);
613
7c0b05e5
MS
614 r = complete_move(&u->names, &other->names);
615 if (r < 0)
616 return r;
23a177ef 617
ac155bb8
MS
618 set_free_free(other->names);
619 other->names = NULL;
620 other->id = NULL;
23a177ef 621
ac155bb8
MS
622 SET_FOREACH(t, u->names, i)
623 assert_se(hashmap_replace(u->manager->units, t, u) == 0);
7c0b05e5
MS
624
625 return 0;
87f0e418
LP
626}
627
09a65f92
MS
628static int reserve_dependencies(Unit *u, Unit *other, UnitDependency d) {
629 unsigned n_reserve;
630
631 assert(u);
632 assert(other);
633 assert(d < _UNIT_DEPENDENCY_MAX);
634
635 /*
636 * If u does not have this dependency set allocated, there is no need
f131770b 637 * to reserve anything. In that case other's set will be transferred
09a65f92
MS
638 * as a whole to u by complete_move().
639 */
640 if (!u->dependencies[d])
641 return 0;
642
643 /* merge_dependencies() will skip a u-on-u dependency */
644 n_reserve = set_size(other->dependencies[d]) - !!set_get(other->dependencies[d], u);
645
646 return set_reserve(u->dependencies[d], n_reserve);
647}
648
d1fab3fe 649static void merge_dependencies(Unit *u, Unit *other, const char *other_id, UnitDependency d) {
23a177ef
LP
650 Iterator i;
651 Unit *back;
87f0e418 652 int r;
23a177ef
LP
653
654 assert(u);
655 assert(other);
656 assert(d < _UNIT_DEPENDENCY_MAX);
657
83a95334 658 /* Fix backwards pointers */
ac155bb8 659 SET_FOREACH(back, other->dependencies[d], i) {
23a177ef
LP
660 UnitDependency k;
661
e48614c4 662 for (k = 0; k < _UNIT_DEPENDENCY_MAX; k++) {
e66047ff
ZJS
663 /* Do not add dependencies between u and itself */
664 if (back == u) {
d1fab3fe 665 if (set_remove(back->dependencies[k], other))
f2341e0a 666 maybe_warn_about_dependency(u, other_id, k);
e66047ff
ZJS
667 } else {
668 r = set_remove_and_put(back->dependencies[k], other, u);
669 if (r == -EEXIST)
670 set_remove(back->dependencies[k], other);
671 else
672 assert(r >= 0 || r == -ENOENT);
673 }
e48614c4 674 }
23a177ef
LP
675 }
676
e66047ff 677 /* Also do not move dependencies on u to itself */
d1fab3fe
ZJS
678 back = set_remove(other->dependencies[d], u);
679 if (back)
f2341e0a 680 maybe_warn_about_dependency(u, other_id, d);
e66047ff 681
7c0b05e5
MS
682 /* The move cannot fail. The caller must have performed a reservation. */
683 assert_se(complete_move(&u->dependencies[d], &other->dependencies[d]) == 0);
23a177ef 684
525d3cc7 685 other->dependencies[d] = set_free(other->dependencies[d]);
23a177ef
LP
686}
687
688int unit_merge(Unit *u, Unit *other) {
87f0e418 689 UnitDependency d;
d1fab3fe 690 const char *other_id = NULL;
09a65f92 691 int r;
87f0e418
LP
692
693 assert(u);
694 assert(other);
ac155bb8
MS
695 assert(u->manager == other->manager);
696 assert(u->type != _UNIT_TYPE_INVALID);
87f0e418 697
cc916967
LP
698 other = unit_follow_merge(other);
699
23a177ef
LP
700 if (other == u)
701 return 0;
702
ac155bb8 703 if (u->type != other->type)
9e2f7c11
LP
704 return -EINVAL;
705
ac155bb8 706 if (!u->instance != !other->instance)
87f0e418
LP
707 return -EINVAL;
708
ac155bb8 709 if (other->load_state != UNIT_STUB &&
c2756a68 710 other->load_state != UNIT_NOT_FOUND)
23a177ef 711 return -EEXIST;
87f0e418 712
ac155bb8 713 if (other->job)
819e213f
LP
714 return -EEXIST;
715
e0209d83
MS
716 if (other->nop_job)
717 return -EEXIST;
718
fdf20a31 719 if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other)))
819e213f
LP
720 return -EEXIST;
721
d1fab3fe
ZJS
722 if (other->id)
723 other_id = strdupa(other->id);
724
09a65f92
MS
725 /* Make reservations to ensure merge_dependencies() won't fail */
726 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++) {
727 r = reserve_dependencies(u, other, d);
728 /*
729 * We don't rollback reservations if we fail. We don't have
730 * a way to undo reservations. A reservation is not a leak.
731 */
732 if (r < 0)
733 return r;
734 }
735
87f0e418 736 /* Merge names */
7c0b05e5
MS
737 r = merge_names(u, other);
738 if (r < 0)
739 return r;
87f0e418 740
57020a3a 741 /* Redirect all references */
ac155bb8
MS
742 while (other->refs)
743 unit_ref_set(other->refs, u);
57020a3a 744
87f0e418
LP
745 /* Merge dependencies */
746 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
d1fab3fe 747 merge_dependencies(u, other, other_id, d);
87f0e418 748
ac155bb8
MS
749 other->load_state = UNIT_MERGED;
750 other->merged_into = u;
23a177ef 751
3616a49c
LP
752 /* If there is still some data attached to the other node, we
753 * don't need it anymore, and can free it. */
ac155bb8 754 if (other->load_state != UNIT_STUB)
3616a49c
LP
755 if (UNIT_VTABLE(other)->done)
756 UNIT_VTABLE(other)->done(other);
757
758 unit_add_to_dbus_queue(u);
23a177ef
LP
759 unit_add_to_cleanup_queue(other);
760
761 return 0;
762}
763
764int unit_merge_by_name(Unit *u, const char *name) {
765 Unit *other;
9e2f7c11 766 int r;
68eda4bd 767 _cleanup_free_ char *s = NULL;
23a177ef
LP
768
769 assert(u);
770 assert(name);
771
7410616c 772 if (unit_name_is_valid(name, UNIT_NAME_TEMPLATE)) {
ac155bb8 773 if (!u->instance)
9e2f7c11
LP
774 return -EINVAL;
775
7410616c
LP
776 r = unit_name_replace_instance(name, u->instance, &s);
777 if (r < 0)
778 return r;
9e2f7c11
LP
779
780 name = s;
781 }
782
c2756a68 783 other = manager_get_unit(u->manager, name);
7410616c
LP
784 if (other)
785 return unit_merge(u, other);
23a177ef 786
7410616c 787 return unit_add_name(u, name);
23a177ef
LP
788}
789
790Unit* unit_follow_merge(Unit *u) {
791 assert(u);
792
ac155bb8
MS
793 while (u->load_state == UNIT_MERGED)
794 assert_se(u = u->merged_into);
23a177ef
LP
795
796 return u;
797}
798
799int unit_add_exec_dependencies(Unit *u, ExecContext *c) {
800 int r;
801
802 assert(u);
803 assert(c);
804
36be24c8
ZJS
805 if (c->working_directory) {
806 r = unit_require_mounts_for(u, c->working_directory);
807 if (r < 0)
808 return r;
809 }
810
811 if (c->root_directory) {
812 r = unit_require_mounts_for(u, c->root_directory);
813 if (r < 0)
814 return r;
815 }
816
b2c23da8 817 if (u->manager->running_as != MANAGER_SYSTEM)
b46a529c
LP
818 return 0;
819
820 if (c->private_tmp) {
821 r = unit_require_mounts_for(u, "/tmp");
822 if (r < 0)
823 return r;
824
825 r = unit_require_mounts_for(u, "/var/tmp");
826 if (r < 0)
827 return r;
828 }
829
ecc6e2b8
LP
830 if (c->std_output != EXEC_OUTPUT_KMSG &&
831 c->std_output != EXEC_OUTPUT_SYSLOG &&
706343f4 832 c->std_output != EXEC_OUTPUT_JOURNAL &&
28dbc1e8
LP
833 c->std_output != EXEC_OUTPUT_KMSG_AND_CONSOLE &&
834 c->std_output != EXEC_OUTPUT_SYSLOG_AND_CONSOLE &&
706343f4 835 c->std_output != EXEC_OUTPUT_JOURNAL_AND_CONSOLE &&
ecc6e2b8 836 c->std_error != EXEC_OUTPUT_KMSG &&
085c98af 837 c->std_error != EXEC_OUTPUT_SYSLOG &&
706343f4 838 c->std_error != EXEC_OUTPUT_JOURNAL &&
085c98af 839 c->std_error != EXEC_OUTPUT_KMSG_AND_CONSOLE &&
706343f4 840 c->std_error != EXEC_OUTPUT_JOURNAL_AND_CONSOLE &&
28dbc1e8 841 c->std_error != EXEC_OUTPUT_SYSLOG_AND_CONSOLE)
23a177ef
LP
842 return 0;
843
844 /* If syslog or kernel logging is requested, make sure our own
845 * logging daemon is run first. */
846
b46a529c
LP
847 r = unit_add_dependency_by_name(u, UNIT_AFTER, SPECIAL_JOURNALD_SOCKET, NULL, true);
848 if (r < 0)
849 return r;
23a177ef 850
87f0e418
LP
851 return 0;
852}
853
87f0e418
LP
854const char *unit_description(Unit *u) {
855 assert(u);
856
ac155bb8
MS
857 if (u->description)
858 return u->description;
87f0e418 859
ac155bb8 860 return strna(u->id);
87f0e418
LP
861}
862
863void unit_dump(Unit *u, FILE *f, const char *prefix) {
49dbfa7b 864 char *t, **j;
87f0e418
LP
865 UnitDependency d;
866 Iterator i;
47be870b 867 const char *prefix2;
173e3821 868 char
a483fb59 869 timestamp0[FORMAT_TIMESTAMP_MAX],
173e3821
LP
870 timestamp1[FORMAT_TIMESTAMP_MAX],
871 timestamp2[FORMAT_TIMESTAMP_MAX],
872 timestamp3[FORMAT_TIMESTAMP_MAX],
faf919f1
LP
873 timestamp4[FORMAT_TIMESTAMP_MAX],
874 timespan[FORMAT_TIMESPAN_MAX];
a7f241db 875 Unit *following;
eeaedb7c
LP
876 _cleanup_set_free_ Set *following_set = NULL;
877 int r;
87f0e418
LP
878
879 assert(u);
ac155bb8 880 assert(u->type >= 0);
87f0e418 881
4c940960 882 prefix = strempty(prefix);
63c372cb 883 prefix2 = strjoina(prefix, "\t");
87f0e418
LP
884
885 fprintf(f,
40d50879 886 "%s-> Unit %s:\n"
87f0e418 887 "%s\tDescription: %s\n"
9e2f7c11 888 "%s\tInstance: %s\n"
87f0e418 889 "%s\tUnit Load State: %s\n"
2fad8195 890 "%s\tUnit Active State: %s\n"
b895d155 891 "%s\tState Change Timestamp: %s\n"
173e3821 892 "%s\tInactive Exit Timestamp: %s\n"
2fad8195 893 "%s\tActive Enter Timestamp: %s\n"
701cc384 894 "%s\tActive Exit Timestamp: %s\n"
173e3821 895 "%s\tInactive Enter Timestamp: %s\n"
45fb0699 896 "%s\tGC Check Good: %s\n"
9444b1f2 897 "%s\tNeed Daemon Reload: %s\n"
c2756a68 898 "%s\tTransient: %s\n"
4ad49000
LP
899 "%s\tSlice: %s\n"
900 "%s\tCGroup: %s\n"
901 "%s\tCGroup realized: %s\n"
6414b7c9
DS
902 "%s\tCGroup mask: 0x%x\n"
903 "%s\tCGroup members mask: 0x%x\n",
ac155bb8 904 prefix, u->id,
87f0e418 905 prefix, unit_description(u),
ac155bb8
MS
906 prefix, strna(u->instance),
907 prefix, unit_load_state_to_string(u->load_state),
2fad8195 908 prefix, unit_active_state_to_string(unit_active_state(u)),
a483fb59 909 prefix, strna(format_timestamp(timestamp0, sizeof(timestamp0), u->state_change_timestamp.realtime)),
ac155bb8
MS
910 prefix, strna(format_timestamp(timestamp1, sizeof(timestamp1), u->inactive_exit_timestamp.realtime)),
911 prefix, strna(format_timestamp(timestamp2, sizeof(timestamp2), u->active_enter_timestamp.realtime)),
912 prefix, strna(format_timestamp(timestamp3, sizeof(timestamp3), u->active_exit_timestamp.realtime)),
913 prefix, strna(format_timestamp(timestamp4, sizeof(timestamp4), u->inactive_enter_timestamp.realtime)),
45fb0699 914 prefix, yes_no(unit_check_gc(u)),
9444b1f2 915 prefix, yes_no(unit_need_daemon_reload(u)),
c2756a68 916 prefix, yes_no(u->transient),
4ad49000
LP
917 prefix, strna(unit_slice_name(u)),
918 prefix, strna(u->cgroup_path),
919 prefix, yes_no(u->cgroup_realized),
bc432dc7 920 prefix, u->cgroup_realized_mask,
6414b7c9 921 prefix, u->cgroup_members_mask);
0301abf4 922
ac155bb8 923 SET_FOREACH(t, u->names, i)
87f0e418
LP
924 fprintf(f, "%s\tName: %s\n", prefix, t);
925
49dbfa7b
LP
926 STRV_FOREACH(j, u->documentation)
927 fprintf(f, "%s\tDocumentation: %s\n", prefix, *j);
928
eeaedb7c
LP
929 following = unit_following(u);
930 if (following)
ac155bb8 931 fprintf(f, "%s\tFollowing: %s\n", prefix, following->id);
8fe914ec 932
eeaedb7c
LP
933 r = unit_following_set(u, &following_set);
934 if (r >= 0) {
935 Unit *other;
936
937 SET_FOREACH(other, following_set, i)
938 fprintf(f, "%s\tFollowing Set Member: %s\n", prefix, other->id);
939 }
940
ac155bb8
MS
941 if (u->fragment_path)
942 fprintf(f, "%s\tFragment Path: %s\n", prefix, u->fragment_path);
23a177ef 943
1b64d026
LP
944 if (u->source_path)
945 fprintf(f, "%s\tSource Path: %s\n", prefix, u->source_path);
946
ae7a7182 947 STRV_FOREACH(j, u->dropin_paths)
2875e22b 948 fprintf(f, "%s\tDropIn Path: %s\n", prefix, *j);
ae7a7182 949
36c16a7c 950 if (u->job_timeout != USEC_INFINITY)
2fa4092c 951 fprintf(f, "%s\tJob Timeout: %s\n", prefix, format_timespan(timespan, sizeof(timespan), u->job_timeout, 0));
faf919f1 952
f189ab18
LP
953 if (u->job_timeout_action != FAILURE_ACTION_NONE)
954 fprintf(f, "%s\tJob Timeout Action: %s\n", prefix, failure_action_to_string(u->job_timeout_action));
955
956 if (u->job_timeout_reboot_arg)
957 fprintf(f, "%s\tJob Timeout Reboot Argument: %s\n", prefix, u->job_timeout_reboot_arg);
958
59fccdc5
LP
959 condition_dump_list(u->conditions, f, prefix, condition_type_to_string);
960 condition_dump_list(u->asserts, f, prefix, assert_type_to_string);
52661efd 961
ac155bb8 962 if (dual_timestamp_is_set(&u->condition_timestamp))
2791a8f8
LP
963 fprintf(f,
964 "%s\tCondition Timestamp: %s\n"
965 "%s\tCondition Result: %s\n",
ac155bb8
MS
966 prefix, strna(format_timestamp(timestamp1, sizeof(timestamp1), u->condition_timestamp.realtime)),
967 prefix, yes_no(u->condition_result));
2791a8f8 968
59fccdc5
LP
969 if (dual_timestamp_is_set(&u->assert_timestamp))
970 fprintf(f,
971 "%s\tAssert Timestamp: %s\n"
972 "%s\tAssert Result: %s\n",
973 prefix, strna(format_timestamp(timestamp1, sizeof(timestamp1), u->assert_timestamp.realtime)),
974 prefix, yes_no(u->assert_result));
975
87f0e418
LP
976 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++) {
977 Unit *other;
978
ac155bb8
MS
979 SET_FOREACH(other, u->dependencies[d], i)
980 fprintf(f, "%s\t%s: %s\n", prefix, unit_dependency_to_string(d), other->id);
87f0e418
LP
981 }
982
7c8fa05c 983 if (!strv_isempty(u->requires_mounts_for)) {
7c8fa05c
LP
984 fprintf(f,
985 "%s\tRequiresMountsFor:", prefix);
986
987 STRV_FOREACH(j, u->requires_mounts_for)
988 fprintf(f, " %s", *j);
989
990 fputs("\n", f);
991 }
992
ac155bb8 993 if (u->load_state == UNIT_LOADED) {
ab1f0633 994
b0650475 995 fprintf(f,
a40eb732 996 "%s\tStopWhenUnneeded: %s\n"
b5e9dba8
LP
997 "%s\tRefuseManualStart: %s\n"
998 "%s\tRefuseManualStop: %s\n"
222ae6a8 999 "%s\tDefaultDependencies: %s\n"
d420282b 1000 "%s\tOnFailureJobMode: %s\n"
36b4a7ba 1001 "%s\tIgnoreOnIsolate: %s\n",
ac155bb8
MS
1002 prefix, yes_no(u->stop_when_unneeded),
1003 prefix, yes_no(u->refuse_manual_start),
1004 prefix, yes_no(u->refuse_manual_stop),
1005 prefix, yes_no(u->default_dependencies),
d420282b 1006 prefix, job_mode_to_string(u->on_failure_job_mode),
36b4a7ba 1007 prefix, yes_no(u->ignore_on_isolate));
ac155bb8 1008
23a177ef
LP
1009 if (UNIT_VTABLE(u)->dump)
1010 UNIT_VTABLE(u)->dump(u, f, prefix2);
b0650475 1011
ac155bb8 1012 } else if (u->load_state == UNIT_MERGED)
b0650475
LP
1013 fprintf(f,
1014 "%s\tMerged into: %s\n",
ac155bb8
MS
1015 prefix, u->merged_into->id);
1016 else if (u->load_state == UNIT_ERROR)
1017 fprintf(f, "%s\tLoad Error Code: %s\n", prefix, strerror(-u->load_error));
8821a00f 1018
87f0e418 1019
ac155bb8
MS
1020 if (u->job)
1021 job_dump(u->job, f, prefix2);
87f0e418 1022
e0209d83
MS
1023 if (u->nop_job)
1024 job_dump(u->nop_job, f, prefix2);
1025
87f0e418
LP
1026}
1027
1028/* Common implementation for multiple backends */
e537352b 1029int unit_load_fragment_and_dropin(Unit *u) {
23a177ef
LP
1030 int r;
1031
1032 assert(u);
23a177ef 1033
e48614c4 1034 /* Load a .{service,socket,...} file */
4ad49000
LP
1035 r = unit_load_fragment(u);
1036 if (r < 0)
23a177ef
LP
1037 return r;
1038
ac155bb8 1039 if (u->load_state == UNIT_STUB)
23a177ef
LP
1040 return -ENOENT;
1041
1042 /* Load drop-in directory data */
4ad49000
LP
1043 r = unit_load_dropin(unit_follow_merge(u));
1044 if (r < 0)
23a177ef
LP
1045 return r;
1046
1047 return 0;
1048}
1049
1050/* Common implementation for multiple backends */
e537352b 1051int unit_load_fragment_and_dropin_optional(Unit *u) {
23a177ef 1052 int r;
87f0e418
LP
1053
1054 assert(u);
1055
23a177ef
LP
1056 /* Same as unit_load_fragment_and_dropin(), but whether
1057 * something can be loaded or not doesn't matter. */
1058
1059 /* Load a .service file */
4ad49000
LP
1060 r = unit_load_fragment(u);
1061 if (r < 0)
87f0e418
LP
1062 return r;
1063
ac155bb8
MS
1064 if (u->load_state == UNIT_STUB)
1065 u->load_state = UNIT_LOADED;
d46de8a1 1066
87f0e418 1067 /* Load drop-in directory data */
4ad49000
LP
1068 r = unit_load_dropin(unit_follow_merge(u));
1069 if (r < 0)
87f0e418
LP
1070 return r;
1071
23a177ef 1072 return 0;
87f0e418
LP
1073}
1074
bba34eed 1075int unit_add_default_target_dependency(Unit *u, Unit *target) {
98bc2000
LP
1076 assert(u);
1077 assert(target);
1078
ac155bb8 1079 if (target->type != UNIT_TARGET)
98bc2000
LP
1080 return 0;
1081
35b8ca3a 1082 /* Only add the dependency if both units are loaded, so that
bba34eed 1083 * that loop check below is reliable */
ac155bb8
MS
1084 if (u->load_state != UNIT_LOADED ||
1085 target->load_state != UNIT_LOADED)
bba34eed
LP
1086 return 0;
1087
21256a2b
LP
1088 /* If either side wants no automatic dependencies, then let's
1089 * skip this */
ac155bb8
MS
1090 if (!u->default_dependencies ||
1091 !target->default_dependencies)
21256a2b
LP
1092 return 0;
1093
98bc2000 1094 /* Don't create loops */
ac155bb8 1095 if (set_get(target->dependencies[UNIT_BEFORE], u))
98bc2000
LP
1096 return 0;
1097
1098 return unit_add_dependency(target, UNIT_AFTER, u, true);
1099}
1100
e954c9cf 1101static int unit_add_target_dependencies(Unit *u) {
a016b922 1102
21256a2b
LP
1103 static const UnitDependency deps[] = {
1104 UNIT_REQUIRED_BY,
be7d9ff7 1105 UNIT_REQUISITE_OF,
21256a2b
LP
1106 UNIT_WANTED_BY,
1107 UNIT_BOUND_BY
1108 };
1109
bba34eed 1110 Unit *target;
98bc2000 1111 Iterator i;
21256a2b 1112 unsigned k;
db57f3c6 1113 int r = 0;
98bc2000
LP
1114
1115 assert(u);
1116
21256a2b 1117 for (k = 0; k < ELEMENTSOF(deps); k++)
a016b922
LP
1118 SET_FOREACH(target, u->dependencies[deps[k]], i) {
1119 r = unit_add_default_target_dependency(u, target);
1120 if (r < 0)
21256a2b 1121 return r;
a016b922
LP
1122 }
1123
e954c9cf
LP
1124 return r;
1125}
4ad49000 1126
e954c9cf
LP
1127static int unit_add_slice_dependencies(Unit *u) {
1128 assert(u);
b81884e7 1129
35b7ff80 1130 if (!UNIT_HAS_CGROUP_CONTEXT(u))
e954c9cf
LP
1131 return 0;
1132
1133 if (UNIT_ISSET(u->slice))
8c8da0e0 1134 return unit_add_two_dependencies(u, UNIT_AFTER, UNIT_REQUIRES, UNIT_DEREF(u->slice), true);
e954c9cf 1135
8c8da0e0 1136 if (unit_has_name(u, SPECIAL_ROOT_SLICE))
d1fab3fe
ZJS
1137 return 0;
1138
8c8da0e0 1139 return unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_REQUIRES, SPECIAL_ROOT_SLICE, NULL, true);
98bc2000
LP
1140}
1141
e954c9cf 1142static int unit_add_mount_dependencies(Unit *u) {
9588bc32
LP
1143 char **i;
1144 int r;
1145
1146 assert(u);
1147
1148 STRV_FOREACH(i, u->requires_mounts_for) {
1149 char prefix[strlen(*i) + 1];
1150
1151 PATH_FOREACH_PREFIX_MORE(prefix, *i) {
c7c89abb 1152 _cleanup_free_ char *p = NULL;
9588bc32
LP
1153 Unit *m;
1154
c7c89abb 1155 r = unit_name_from_path(prefix, ".mount", &p);
9588bc32
LP
1156 if (r < 0)
1157 return r;
c7c89abb
FB
1158
1159 m = manager_get_unit(u->manager, p);
1160 if (!m) {
1161 /* Make sure to load the mount unit if
1162 * it exists. If so the dependencies
1163 * on this unit will be added later
1164 * during the loading of the mount
1165 * unit. */
1166 (void) manager_load_unit_prepare(u->manager, p, NULL, NULL, &m);
9588bc32 1167 continue;
c7c89abb 1168 }
9588bc32
LP
1169 if (m == u)
1170 continue;
1171
1172 if (m->load_state != UNIT_LOADED)
1173 continue;
1174
1175 r = unit_add_dependency(u, UNIT_AFTER, m, true);
1176 if (r < 0)
1177 return r;
1178
1179 if (m->fragment_path) {
1180 r = unit_add_dependency(u, UNIT_REQUIRES, m, true);
1181 if (r < 0)
1182 return r;
1183 }
1184 }
1185 }
1186
1187 return 0;
1188}
1189
95ae05c0
WC
1190static int unit_add_startup_units(Unit *u) {
1191 CGroupContext *c;
5269eb6b 1192 int r;
95ae05c0
WC
1193
1194 c = unit_get_cgroup_context(u);
db785129
LP
1195 if (!c)
1196 return 0;
1197
d53d9474
LP
1198 if (c->startup_cpu_shares == CGROUP_CPU_SHARES_INVALID &&
1199 c->startup_blockio_weight == CGROUP_BLKIO_WEIGHT_INVALID)
db785129
LP
1200 return 0;
1201
5269eb6b
LP
1202 r = set_ensure_allocated(&u->manager->startup_units, NULL);
1203 if (r < 0)
1204 return r;
1205
756c09e6 1206 return set_put(u->manager->startup_units, u);
95ae05c0
WC
1207}
1208
87f0e418
LP
1209int unit_load(Unit *u) {
1210 int r;
1211
1212 assert(u);
1213
ac155bb8 1214 if (u->in_load_queue) {
71fda00f 1215 LIST_REMOVE(load_queue, u->manager->load_queue, u);
ac155bb8 1216 u->in_load_queue = false;
87f0e418
LP
1217 }
1218
ac155bb8 1219 if (u->type == _UNIT_TYPE_INVALID)
e537352b
LP
1220 return -EINVAL;
1221
ac155bb8 1222 if (u->load_state != UNIT_STUB)
87f0e418
LP
1223 return 0;
1224
c2756a68
LP
1225 if (UNIT_VTABLE(u)->load) {
1226 r = UNIT_VTABLE(u)->load(u);
1227 if (r < 0)
87f0e418 1228 goto fail;
c2756a68 1229 }
23a177ef 1230
ac155bb8 1231 if (u->load_state == UNIT_STUB) {
23a177ef
LP
1232 r = -ENOENT;
1233 goto fail;
1234 }
1235
7c8fa05c 1236 if (u->load_state == UNIT_LOADED) {
c2756a68 1237
e954c9cf
LP
1238 r = unit_add_target_dependencies(u);
1239 if (r < 0)
1240 goto fail;
1241
1242 r = unit_add_slice_dependencies(u);
1243 if (r < 0)
1244 goto fail;
c2756a68 1245
e954c9cf 1246 r = unit_add_mount_dependencies(u);
7c8fa05c 1247 if (r < 0)
c2756a68 1248 goto fail;
7c8fa05c 1249
95ae05c0
WC
1250 r = unit_add_startup_units(u);
1251 if (r < 0)
1252 goto fail;
1253
bc432dc7 1254 if (u->on_failure_job_mode == JOB_ISOLATE && set_size(u->dependencies[UNIT_ON_FAILURE]) > 1) {
f2341e0a 1255 log_unit_error(u, "More than one OnFailure= dependencies specified but OnFailureJobMode=isolate set. Refusing.");
c2756a68
LP
1256 r = -EINVAL;
1257 goto fail;
1258 }
bc432dc7
LP
1259
1260 unit_update_cgroup_members_masks(u);
f68319bb
LP
1261 }
1262
ac155bb8 1263 assert((u->load_state != UNIT_MERGED) == !u->merged_into);
23a177ef
LP
1264
1265 unit_add_to_dbus_queue(unit_follow_merge(u));
701cc384 1266 unit_add_to_gc_queue(u);
87f0e418 1267
87f0e418
LP
1268 return 0;
1269
1270fail:
c2756a68 1271 u->load_state = u->load_state == UNIT_STUB ? UNIT_NOT_FOUND : UNIT_ERROR;
ac155bb8 1272 u->load_error = r;
c1e1601e 1273 unit_add_to_dbus_queue(u);
9a46fc3b 1274 unit_add_to_gc_queue(u);
23a177ef 1275
f2341e0a 1276 log_unit_debug_errno(u, r, "Failed to load configuration: %m");
23a177ef 1277
87f0e418
LP
1278 return r;
1279}
1280
49365733
LP
1281static bool unit_condition_test_list(Unit *u, Condition *first, const char *(*to_string)(ConditionType t)) {
1282 Condition *c;
1283 int triggered = -1;
1284
1285 assert(u);
1286 assert(to_string);
1287
1288 /* If the condition list is empty, then it is true */
1289 if (!first)
1290 return true;
1291
1292 /* Otherwise, if all of the non-trigger conditions apply and
1293 * if any of the trigger conditions apply (unless there are
1294 * none) we return true */
1295 LIST_FOREACH(conditions, c, first) {
1296 int r;
1297
1298 r = condition_test(c);
1299 if (r < 0)
f2341e0a
LP
1300 log_unit_warning(u,
1301 "Couldn't determine result for %s=%s%s%s, assuming failed: %m",
49365733
LP
1302 to_string(c->type),
1303 c->trigger ? "|" : "",
1304 c->negate ? "!" : "",
f2341e0a 1305 c->parameter);
49365733 1306 else
f2341e0a
LP
1307 log_unit_debug(u,
1308 "%s=%s%s%s %s.",
49365733
LP
1309 to_string(c->type),
1310 c->trigger ? "|" : "",
1311 c->negate ? "!" : "",
1312 c->parameter,
f2341e0a 1313 condition_result_to_string(c->result));
49365733
LP
1314
1315 if (!c->trigger && r <= 0)
1316 return false;
1317
1318 if (c->trigger && triggered <= 0)
1319 triggered = r > 0;
1320 }
1321
1322 return triggered != 0;
1323}
1324
9588bc32 1325static bool unit_condition_test(Unit *u) {
90bbc946
LP
1326 assert(u);
1327
ac155bb8 1328 dual_timestamp_get(&u->condition_timestamp);
49365733 1329 u->condition_result = unit_condition_test_list(u, u->conditions, condition_type_to_string);
90bbc946 1330
ac155bb8 1331 return u->condition_result;
90bbc946
LP
1332}
1333
59fccdc5
LP
1334static bool unit_assert_test(Unit *u) {
1335 assert(u);
1336
1337 dual_timestamp_get(&u->assert_timestamp);
49365733 1338 u->assert_result = unit_condition_test_list(u, u->asserts, assert_type_to_string);
59fccdc5
LP
1339
1340 return u->assert_result;
1341}
1342
df446f96
LP
1343void unit_status_printf(Unit *u, const char *status, const char *unit_status_msg_format) {
1344 DISABLE_WARNING_FORMAT_NONLITERAL;
1345 manager_status_printf(u->manager, STATUS_TYPE_NORMAL, status, unit_status_msg_format, unit_description(u));
1346 REENABLE_WARNING;
1347}
1348
44a6b1b6 1349_pure_ static const char* unit_get_status_message_format(Unit *u, JobType t) {
877d54e9 1350 const char *format;
a85ca902 1351 const UnitStatusMessageFormats *format_table;
877d54e9
LP
1352
1353 assert(u);
df446f96 1354 assert(IN_SET(t, JOB_START, JOB_STOP, JOB_RELOAD));
877d54e9 1355
b5bf308b 1356 if (t != JOB_RELOAD) {
a85ca902
MS
1357 format_table = &UNIT_VTABLE(u)->status_message_formats;
1358 if (format_table) {
1359 format = format_table->starting_stopping[t == JOB_STOP];
1360 if (format)
1361 return format;
1362 }
1363 }
877d54e9
LP
1364
1365 /* Return generic strings */
1366 if (t == JOB_START)
1367 return "Starting %s.";
1368 else if (t == JOB_STOP)
1369 return "Stopping %s.";
b5bf308b 1370 else
877d54e9 1371 return "Reloading %s.";
877d54e9
LP
1372}
1373
1374static void unit_status_print_starting_stopping(Unit *u, JobType t) {
1375 const char *format;
1376
1377 assert(u);
1378
df446f96
LP
1379 /* Reload status messages have traditionally not been printed to console. */
1380 if (!IN_SET(t, JOB_START, JOB_STOP))
1381 return;
1382
877d54e9 1383 format = unit_get_status_message_format(u, t);
c6918296 1384
bcfce235 1385 DISABLE_WARNING_FORMAT_NONLITERAL;
49b1d377 1386 unit_status_printf(u, "", format);
bcfce235 1387 REENABLE_WARNING;
c6918296
MS
1388}
1389
877d54e9
LP
1390static void unit_status_log_starting_stopping_reloading(Unit *u, JobType t) {
1391 const char *format;
1392 char buf[LINE_MAX];
1393 sd_id128_t mid;
1394
1395 assert(u);
1396
df446f96 1397 if (!IN_SET(t, JOB_START, JOB_STOP, JOB_RELOAD))
877d54e9
LP
1398 return;
1399
81270860
LP
1400 if (log_on_console())
1401 return;
1402
877d54e9
LP
1403 /* We log status messages for all units and all operations. */
1404
a85ca902 1405 format = unit_get_status_message_format(u, t);
877d54e9 1406
bcfce235 1407 DISABLE_WARNING_FORMAT_NONLITERAL;
d054f0a4 1408 xsprintf(buf, format, unit_description(u));
bcfce235 1409 REENABLE_WARNING;
877d54e9
LP
1410
1411 mid = t == JOB_START ? SD_MESSAGE_UNIT_STARTING :
1412 t == JOB_STOP ? SD_MESSAGE_UNIT_STOPPING :
1413 SD_MESSAGE_UNIT_RELOADING;
1414
f2341e0a
LP
1415 /* Note that we deliberately use LOG_MESSAGE() instead of
1416 * LOG_UNIT_MESSAGE() here, since this is supposed to mimic
1417 * closely what is written to screen using the status output,
1418 * which is supposed the highest level, friendliest output
1419 * possible, which means we should avoid the low-level unit
1420 * name. */
1421 log_struct(LOG_INFO,
1422 LOG_MESSAGE_ID(mid),
1423 LOG_UNIT_ID(u),
1424 LOG_MESSAGE("%s", buf),
1425 NULL);
877d54e9 1426}
877d54e9 1427
d1a34ae9 1428void unit_status_emit_starting_stopping_reloading(Unit *u, JobType t) {
df446f96
LP
1429 assert(u);
1430 assert(t >= 0);
1431 assert(t < _JOB_TYPE_MAX);
d1a34ae9
MS
1432
1433 unit_status_log_starting_stopping_reloading(u, t);
df446f96 1434 unit_status_print_starting_stopping(u, t);
d1a34ae9
MS
1435}
1436
6bf0f408
LP
1437static int unit_start_limit_test(Unit *u) {
1438 assert(u);
1439
1440 if (ratelimit_test(&u->start_limit)) {
1441 u->start_limit_hit = false;
1442 return 0;
1443 }
1444
1445 log_unit_warning(u, "Start request repeated too quickly.");
1446 u->start_limit_hit = true;
1447
1448 return failure_action(u->manager, u->start_limit_action, u->reboot_arg);
1449}
1450
87f0e418 1451/* Errors:
6bf0f408
LP
1452 * -EBADR: This unit type does not support starting.
1453 * -EALREADY: Unit is already started.
1454 * -EAGAIN: An operation is already in progress. Retry later.
1455 * -ECANCELED: Too many requests for now.
1456 * -EPROTO: Assert failed
1457 * -EINVAL: Unit not loaded
1458 * -EOPNOTSUPP: Unit type not supported
87f0e418
LP
1459 */
1460int unit_start(Unit *u) {
1461 UnitActiveState state;
92ab323c 1462 Unit *following;
6bf0f408 1463 int r;
87f0e418
LP
1464
1465 assert(u);
1466
a82e5507
LP
1467 /* If this is already started, then this will succeed. Note
1468 * that this will even succeed if this unit is not startable
1469 * by the user. This is relied on to detect when we need to
1470 * wait for units and when waiting is finished. */
87f0e418
LP
1471 state = unit_active_state(u);
1472 if (UNIT_IS_ACTIVE_OR_RELOADING(state))
1473 return -EALREADY;
1474
6bf0f408
LP
1475 /* Make sure we don't enter a busy loop of some kind. */
1476 r = unit_start_limit_test(u);
1477 if (r < 0)
1478 return r;
1479
1480 /* Units that aren't loaded cannot be started */
1481 if (u->load_state != UNIT_LOADED)
1482 return -EINVAL;
1483
a82e5507
LP
1484 /* If the conditions failed, don't do anything at all. If we
1485 * already are activating this call might still be useful to
1486 * speed up activation in case there is some hold-off time,
1487 * but we don't want to recheck the condition in that case. */
1488 if (state != UNIT_ACTIVATING &&
1489 !unit_condition_test(u)) {
f2341e0a 1490 log_unit_debug(u, "Starting requested but condition failed. Not starting unit.");
52661efd
LP
1491 return -EALREADY;
1492 }
1493
59fccdc5
LP
1494 /* If the asserts failed, fail the entire job */
1495 if (state != UNIT_ACTIVATING &&
1496 !unit_assert_test(u)) {
f2341e0a 1497 log_unit_notice(u, "Starting requested but asserts failed.");
59fccdc5
LP
1498 return -EPROTO;
1499 }
1500
d11a7645
LP
1501 /* Units of types that aren't supported cannot be
1502 * started. Note that we do this test only after the condition
1503 * checks, so that we rather return condition check errors
1504 * (which are usually not considered a true failure) than "not
1505 * supported" errors (which are considered a failure).
1506 */
1507 if (!unit_supported(u))
1508 return -EOPNOTSUPP;
1509
92ab323c 1510 /* Forward to the main object, if we aren't it. */
52990c2e
ZJS
1511 following = unit_following(u);
1512 if (following) {
f2341e0a 1513 log_unit_debug(u, "Redirecting start request from %s to %s.", u->id, following->id);
92ab323c
LP
1514 return unit_start(following);
1515 }
1516
1517 /* If it is stopped, but we cannot start it, then fail */
1518 if (!UNIT_VTABLE(u)->start)
1519 return -EBADR;
1520
87f0e418
LP
1521 /* We don't suppress calls to ->start() here when we are
1522 * already starting, to allow this request to be used as a
1523 * "hurry up" call, for example when the unit is in some "auto
1524 * restart" state where it waits for a holdoff timer to elapse
1525 * before it will start again. */
1526
c1e1601e 1527 unit_add_to_dbus_queue(u);
9e58ff9c 1528
d1a34ae9 1529 return UNIT_VTABLE(u)->start(u);
87f0e418
LP
1530}
1531
1532bool unit_can_start(Unit *u) {
1533 assert(u);
1534
8ff4d2ab
LP
1535 if (u->load_state != UNIT_LOADED)
1536 return false;
1537
1538 if (!unit_supported(u))
1539 return false;
1540
87f0e418
LP
1541 return !!UNIT_VTABLE(u)->start;
1542}
1543
2528a7a6
LP
1544bool unit_can_isolate(Unit *u) {
1545 assert(u);
1546
1547 return unit_can_start(u) &&
ac155bb8 1548 u->allow_isolate;
2528a7a6
LP
1549}
1550
87f0e418
LP
1551/* Errors:
1552 * -EBADR: This unit type does not support stopping.
1553 * -EALREADY: Unit is already stopped.
1554 * -EAGAIN: An operation is already in progress. Retry later.
1555 */
1556int unit_stop(Unit *u) {
1557 UnitActiveState state;
92ab323c 1558 Unit *following;
87f0e418
LP
1559
1560 assert(u);
1561
87f0e418 1562 state = unit_active_state(u);
fdf20a31 1563 if (UNIT_IS_INACTIVE_OR_FAILED(state))
87f0e418
LP
1564 return -EALREADY;
1565
0faacd47
LP
1566 following = unit_following(u);
1567 if (following) {
f2341e0a 1568 log_unit_debug(u, "Redirecting stop request from %s to %s.", u->id, following->id);
92ab323c
LP
1569 return unit_stop(following);
1570 }
1571
7898b0cf
LP
1572 if (!UNIT_VTABLE(u)->stop)
1573 return -EBADR;
1574
c1e1601e 1575 unit_add_to_dbus_queue(u);
9e58ff9c 1576
d1a34ae9 1577 return UNIT_VTABLE(u)->stop(u);
87f0e418
LP
1578}
1579
1580/* Errors:
1581 * -EBADR: This unit type does not support reloading.
1582 * -ENOEXEC: Unit is not started.
1583 * -EAGAIN: An operation is already in progress. Retry later.
1584 */
1585int unit_reload(Unit *u) {
1586 UnitActiveState state;
92ab323c 1587 Unit *following;
87f0e418
LP
1588
1589 assert(u);
1590
ac155bb8 1591 if (u->load_state != UNIT_LOADED)
6124958c
LP
1592 return -EINVAL;
1593
87f0e418
LP
1594 if (!unit_can_reload(u))
1595 return -EBADR;
1596
1597 state = unit_active_state(u);
e364ad06 1598 if (state == UNIT_RELOADING)
87f0e418
LP
1599 return -EALREADY;
1600
6a371e23 1601 if (state != UNIT_ACTIVE) {
f2341e0a 1602 log_unit_warning(u, "Unit cannot be reloaded because it is inactive.");
87f0e418 1603 return -ENOEXEC;
6a371e23 1604 }
87f0e418 1605
e48614c4
ZJS
1606 following = unit_following(u);
1607 if (following) {
f2341e0a 1608 log_unit_debug(u, "Redirecting reload request from %s to %s.", u->id, following->id);
92ab323c
LP
1609 return unit_reload(following);
1610 }
1611
c1e1601e 1612 unit_add_to_dbus_queue(u);
82a2b6bb 1613
d1a34ae9 1614 return UNIT_VTABLE(u)->reload(u);
87f0e418
LP
1615}
1616
1617bool unit_can_reload(Unit *u) {
1618 assert(u);
1619
1620 if (!UNIT_VTABLE(u)->reload)
1621 return false;
1622
1623 if (!UNIT_VTABLE(u)->can_reload)
1624 return true;
1625
1626 return UNIT_VTABLE(u)->can_reload(u);
1627}
1628
b4a16b7b 1629static void unit_check_unneeded(Unit *u) {
be7d9ff7 1630
4afd3348 1631 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
4bd29fe5 1632
be7d9ff7
LP
1633 static const UnitDependency needed_dependencies[] = {
1634 UNIT_REQUIRED_BY,
084918ba 1635 UNIT_REQUISITE_OF,
be7d9ff7
LP
1636 UNIT_WANTED_BY,
1637 UNIT_BOUND_BY,
1638 };
1639
f3bff0eb 1640 Unit *other;
be7d9ff7
LP
1641 Iterator i;
1642 unsigned j;
1643 int r;
f3bff0eb
LP
1644
1645 assert(u);
1646
1647 /* If this service shall be shut down when unneeded then do
1648 * so. */
1649
ac155bb8 1650 if (!u->stop_when_unneeded)
f3bff0eb
LP
1651 return;
1652
1653 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)))
1654 return;
1655
be7d9ff7 1656 for (j = 0; j < ELEMENTSOF(needed_dependencies); j++)
f3b85044 1657 SET_FOREACH(other, u->dependencies[needed_dependencies[j]], i)
be7d9ff7
LP
1658 if (unit_active_or_pending(other))
1659 return;
b81884e7 1660
bea355da
LP
1661 /* If stopping a unit fails continously we might enter a stop
1662 * loop here, hence stop acting on the service being
1663 * unnecessary after a while. */
67bfdc97 1664 if (!ratelimit_test(&u->auto_stop_ratelimit)) {
bea355da
LP
1665 log_unit_warning(u, "Unit not needed anymore, but not stopping since we tried this too often recently.");
1666 return;
1667 }
1668
f2341e0a 1669 log_unit_info(u, "Unit not needed anymore. Stopping.");
f3bff0eb
LP
1670
1671 /* Ok, nobody needs us anymore. Sniff. Then let's commit suicide */
4bd29fe5 1672 r = manager_add_job(u->manager, JOB_STOP, u, JOB_FAIL, &error, NULL);
be7d9ff7 1673 if (r < 0)
4bd29fe5 1674 log_unit_warning_errno(u, r, "Failed to enqueue stop job, ignoring: %s", bus_error_message(&error, r));
f3bff0eb
LP
1675}
1676
ff502445 1677static void unit_check_binds_to(Unit *u) {
4afd3348 1678 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
ff502445
LP
1679 bool stop = false;
1680 Unit *other;
1681 Iterator i;
67bfdc97 1682 int r;
ff502445
LP
1683
1684 assert(u);
1685
1686 if (u->job)
1687 return;
1688
1689 if (unit_active_state(u) != UNIT_ACTIVE)
1690 return;
1691
1692 SET_FOREACH(other, u->dependencies[UNIT_BINDS_TO], i) {
1693 if (other->job)
1694 continue;
1695
1696 if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other)))
1697 continue;
1698
1699 stop = true;
98f738b6 1700 break;
ff502445
LP
1701 }
1702
1703 if (!stop)
1704 return;
1705
67bfdc97
LP
1706 /* If stopping a unit fails continously we might enter a stop
1707 * loop here, hence stop acting on the service being
1708 * unnecessary after a while. */
1709 if (!ratelimit_test(&u->auto_stop_ratelimit)) {
1710 log_unit_warning(u, "Unit is bound to inactive unit %s, but not stopping since we tried this too often recently.", other->id);
1711 return;
1712 }
1713
98f738b6 1714 assert(other);
f2341e0a 1715 log_unit_info(u, "Unit is bound to inactive unit %s. Stopping, too.", other->id);
ff502445
LP
1716
1717 /* A unit we need to run is gone. Sniff. Let's stop this. */
4bd29fe5 1718 r = manager_add_job(u->manager, JOB_STOP, u, JOB_FAIL, &error, NULL);
67bfdc97 1719 if (r < 0)
4bd29fe5 1720 log_unit_warning_errno(u, r, "Failed to enqueue stop job, ignoring: %s", bus_error_message(&error, r));
ff502445
LP
1721}
1722
87f0e418
LP
1723static void retroactively_start_dependencies(Unit *u) {
1724 Iterator i;
1725 Unit *other;
1726
1727 assert(u);
1728 assert(UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)));
1729
ac155bb8
MS
1730 SET_FOREACH(other, u->dependencies[UNIT_REQUIRES], i)
1731 if (!set_get(u->dependencies[UNIT_AFTER], other) &&
b81884e7 1732 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
4bd29fe5 1733 manager_add_job(u->manager, JOB_START, other, JOB_REPLACE, NULL, NULL);
b81884e7 1734
7f2cddae 1735 SET_FOREACH(other, u->dependencies[UNIT_BINDS_TO], i)
ac155bb8 1736 if (!set_get(u->dependencies[UNIT_AFTER], other) &&
b81884e7 1737 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
4bd29fe5 1738 manager_add_job(u->manager, JOB_START, other, JOB_REPLACE, NULL, NULL);
87f0e418 1739
ac155bb8
MS
1740 SET_FOREACH(other, u->dependencies[UNIT_WANTS], i)
1741 if (!set_get(u->dependencies[UNIT_AFTER], other) &&
b81884e7 1742 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
4bd29fe5 1743 manager_add_job(u->manager, JOB_START, other, JOB_FAIL, NULL, NULL);
87f0e418 1744
ac155bb8 1745 SET_FOREACH(other, u->dependencies[UNIT_CONFLICTS], i)
b81884e7 1746 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
4bd29fe5 1747 manager_add_job(u->manager, JOB_STOP, other, JOB_REPLACE, NULL, NULL);
69dd2852 1748
ac155bb8 1749 SET_FOREACH(other, u->dependencies[UNIT_CONFLICTED_BY], i)
b81884e7 1750 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
4bd29fe5 1751 manager_add_job(u->manager, JOB_STOP, other, JOB_REPLACE, NULL, NULL);
87f0e418
LP
1752}
1753
1754static void retroactively_stop_dependencies(Unit *u) {
1755 Iterator i;
1756 Unit *other;
1757
1758 assert(u);
1759 assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)));
1760
b81884e7 1761 /* Pull down units which are bound to us recursively if enabled */
ac155bb8 1762 SET_FOREACH(other, u->dependencies[UNIT_BOUND_BY], i)
b81884e7 1763 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
4bd29fe5 1764 manager_add_job(u->manager, JOB_STOP, other, JOB_REPLACE, NULL, NULL);
cd0504d0
MS
1765}
1766
1767static void check_unneeded_dependencies(Unit *u) {
1768 Iterator i;
1769 Unit *other;
1770
1771 assert(u);
1772 assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)));
f3bff0eb
LP
1773
1774 /* Garbage collect services that might not be needed anymore, if enabled */
ac155bb8 1775 SET_FOREACH(other, u->dependencies[UNIT_REQUIRES], i)
87f0e418 1776 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
b4a16b7b 1777 unit_check_unneeded(other);
ac155bb8 1778 SET_FOREACH(other, u->dependencies[UNIT_WANTS], i)
f3bff0eb 1779 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
b4a16b7b 1780 unit_check_unneeded(other);
ac155bb8 1781 SET_FOREACH(other, u->dependencies[UNIT_REQUISITE], i)
f3bff0eb 1782 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
b4a16b7b 1783 unit_check_unneeded(other);
7f2cddae 1784 SET_FOREACH(other, u->dependencies[UNIT_BINDS_TO], i)
b81884e7
LP
1785 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1786 unit_check_unneeded(other);
87f0e418
LP
1787}
1788
3ecaa09b 1789void unit_start_on_failure(Unit *u) {
c0daa706
LP
1790 Unit *other;
1791 Iterator i;
1792
1793 assert(u);
1794
ac155bb8 1795 if (set_size(u->dependencies[UNIT_ON_FAILURE]) <= 0)
222ae6a8
LP
1796 return;
1797
f2341e0a 1798 log_unit_info(u, "Triggering OnFailure= dependencies.");
222ae6a8 1799
ac155bb8 1800 SET_FOREACH(other, u->dependencies[UNIT_ON_FAILURE], i) {
222ae6a8
LP
1801 int r;
1802
4bd29fe5 1803 r = manager_add_job(u->manager, JOB_START, other, u->on_failure_job_mode, NULL, NULL);
c1b6628d 1804 if (r < 0)
f2341e0a 1805 log_unit_error_errno(u, r, "Failed to enqueue OnFailure= job: %m");
222ae6a8 1806 }
c0daa706
LP
1807}
1808
3ecaa09b
LP
1809void unit_trigger_notify(Unit *u) {
1810 Unit *other;
1811 Iterator i;
1812
1813 assert(u);
1814
1815 SET_FOREACH(other, u->dependencies[UNIT_TRIGGERED_BY], i)
1816 if (UNIT_VTABLE(other)->trigger_notify)
1817 UNIT_VTABLE(other)->trigger_notify(other, u);
1818}
1819
e2f3b44c 1820void unit_notify(Unit *u, UnitActiveState os, UnitActiveState ns, bool reload_success) {
546ac4f0 1821 Manager *m;
7e6e7b06 1822 bool unexpected;
a096ed36 1823
87f0e418
LP
1824 assert(u);
1825 assert(os < _UNIT_ACTIVE_STATE_MAX);
1826 assert(ns < _UNIT_ACTIVE_STATE_MAX);
87f0e418 1827
8e471ccd
LP
1828 /* Note that this is called for all low-level state changes,
1829 * even if they might map to the same high-level
865cc19a 1830 * UnitActiveState! That means that ns == os is an expected
c5315881 1831 * behavior here. For example: if a mount point is remounted
cd6d0a45 1832 * this function will be called too! */
87f0e418 1833
546ac4f0
MS
1834 m = u->manager;
1835
f755e3b7 1836 /* Update timestamps for state changes */
546ac4f0 1837 if (m->n_reloading <= 0) {
a483fb59 1838 dual_timestamp_get(&u->state_change_timestamp);
173e3821 1839
bdbf9951 1840 if (UNIT_IS_INACTIVE_OR_FAILED(os) && !UNIT_IS_INACTIVE_OR_FAILED(ns))
a483fb59 1841 u->inactive_exit_timestamp = u->state_change_timestamp;
bdbf9951 1842 else if (!UNIT_IS_INACTIVE_OR_FAILED(os) && UNIT_IS_INACTIVE_OR_FAILED(ns))
a483fb59 1843 u->inactive_enter_timestamp = u->state_change_timestamp;
bdbf9951
LP
1844
1845 if (!UNIT_IS_ACTIVE_OR_RELOADING(os) && UNIT_IS_ACTIVE_OR_RELOADING(ns))
a483fb59 1846 u->active_enter_timestamp = u->state_change_timestamp;
bdbf9951 1847 else if (UNIT_IS_ACTIVE_OR_RELOADING(os) && !UNIT_IS_ACTIVE_OR_RELOADING(ns))
a483fb59 1848 u->active_exit_timestamp = u->state_change_timestamp;
bdbf9951 1849 }
87f0e418 1850
865cc19a 1851 /* Keep track of failed units */
5269eb6b 1852 (void) manager_update_failed_units(u->manager, u, ns == UNIT_FAILED);
f755e3b7
LP
1853
1854 /* Make sure the cgroup is always removed when we become inactive */
fdf20a31 1855 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
efdb0237 1856 unit_prune_cgroup(u);
fb385181 1857
9cd86184 1858 /* Note that this doesn't apply to RemainAfterExit services exiting
6f285378 1859 * successfully, since there's no change of state in that case. Which is
9cd86184 1860 * why it is handled in service_set_state() */
7ed9f6cd 1861 if (UNIT_IS_INACTIVE_OR_FAILED(os) != UNIT_IS_INACTIVE_OR_FAILED(ns)) {
b33918c2
LP
1862 ExecContext *ec;
1863
1864 ec = unit_get_exec_context(u);
7ed9f6cd 1865 if (ec && exec_context_may_touch_console(ec)) {
31a7eb86 1866 if (UNIT_IS_INACTIVE_OR_FAILED(ns)) {
313cefa1 1867 m->n_on_console--;
31a7eb86
ZJS
1868
1869 if (m->n_on_console == 0)
1870 /* unset no_console_output flag, since the console is free */
2f38577f 1871 m->no_console_output = false;
31a7eb86 1872 } else
313cefa1 1873 m->n_on_console++;
7ed9f6cd
MS
1874 }
1875 }
1876
ac155bb8 1877 if (u->job) {
7e6e7b06 1878 unexpected = false;
87f0e418 1879
ac155bb8 1880 if (u->job->state == JOB_WAITING)
87f0e418
LP
1881
1882 /* So we reached a different state for this
1883 * job. Let's see if we can run it now if it
1884 * failed previously due to EAGAIN. */
ac155bb8 1885 job_add_to_run_queue(u->job);
87f0e418 1886
b410e6b9 1887 /* Let's check whether this state change constitutes a
35b8ca3a 1888 * finished job, or maybe contradicts a running job and
b410e6b9 1889 * hence needs to invalidate jobs. */
87f0e418 1890
ac155bb8 1891 switch (u->job->type) {
87f0e418 1892
b410e6b9
LP
1893 case JOB_START:
1894 case JOB_VERIFY_ACTIVE:
87f0e418 1895
b410e6b9 1896 if (UNIT_IS_ACTIVE_OR_RELOADING(ns))
5273510e 1897 job_finish_and_invalidate(u->job, JOB_DONE, true);
ac155bb8 1898 else if (u->job->state == JOB_RUNNING && ns != UNIT_ACTIVATING) {
b410e6b9 1899 unexpected = true;
41b02ec7 1900
fdf20a31 1901 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
5273510e 1902 job_finish_and_invalidate(u->job, ns == UNIT_FAILED ? JOB_FAILED : JOB_DONE, true);
b410e6b9 1903 }
87f0e418 1904
b410e6b9 1905 break;
87f0e418 1906
b410e6b9
LP
1907 case JOB_RELOAD:
1908 case JOB_RELOAD_OR_START:
3282591d 1909 case JOB_TRY_RELOAD:
87f0e418 1910
ac155bb8 1911 if (u->job->state == JOB_RUNNING) {
a096ed36 1912 if (ns == UNIT_ACTIVE)
5273510e 1913 job_finish_and_invalidate(u->job, reload_success ? JOB_DONE : JOB_FAILED, true);
032ff4af 1914 else if (ns != UNIT_ACTIVATING && ns != UNIT_RELOADING) {
a096ed36 1915 unexpected = true;
41b02ec7 1916
fdf20a31 1917 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
5273510e 1918 job_finish_and_invalidate(u->job, ns == UNIT_FAILED ? JOB_FAILED : JOB_DONE, true);
a096ed36 1919 }
b410e6b9 1920 }
87f0e418 1921
b410e6b9 1922 break;
87f0e418 1923
b410e6b9
LP
1924 case JOB_STOP:
1925 case JOB_RESTART:
1926 case JOB_TRY_RESTART:
87f0e418 1927
fdf20a31 1928 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
5273510e 1929 job_finish_and_invalidate(u->job, JOB_DONE, true);
ac155bb8 1930 else if (u->job->state == JOB_RUNNING && ns != UNIT_DEACTIVATING) {
b410e6b9 1931 unexpected = true;
5273510e 1932 job_finish_and_invalidate(u->job, JOB_FAILED, true);
b410e6b9 1933 }
87f0e418 1934
b410e6b9 1935 break;
87f0e418 1936
b410e6b9
LP
1937 default:
1938 assert_not_reached("Job type unknown");
87f0e418 1939 }
87f0e418 1940
7e6e7b06
LP
1941 } else
1942 unexpected = true;
1943
546ac4f0 1944 if (m->n_reloading <= 0) {
f3bff0eb 1945
bdbf9951
LP
1946 /* If this state change happened without being
1947 * requested by a job, then let's retroactively start
1948 * or stop dependencies. We skip that step when
1949 * deserializing, since we don't want to create any
1950 * additional jobs just because something is already
1951 * activated. */
1952
1953 if (unexpected) {
1954 if (UNIT_IS_INACTIVE_OR_FAILED(os) && UNIT_IS_ACTIVE_OR_ACTIVATING(ns))
1955 retroactively_start_dependencies(u);
1956 else if (UNIT_IS_ACTIVE_OR_ACTIVATING(os) && UNIT_IS_INACTIVE_OR_DEACTIVATING(ns))
1957 retroactively_stop_dependencies(u);
1958 }
5de9682c 1959
cd0504d0 1960 /* stop unneeded units regardless if going down was expected or not */
b33918c2 1961 if (UNIT_IS_INACTIVE_OR_DEACTIVATING(ns))
cd0504d0
MS
1962 check_unneeded_dependencies(u);
1963
bdbf9951 1964 if (ns != os && ns == UNIT_FAILED) {
f2341e0a 1965 log_unit_notice(u, "Unit entered failed state.");
3ecaa09b 1966 unit_start_on_failure(u);
cd6d0a45 1967 }
3b2775c5 1968 }
e537352b 1969
3b2775c5
LP
1970 /* Some names are special */
1971 if (UNIT_IS_ACTIVE_OR_RELOADING(ns)) {
1972
1973 if (unit_has_name(u, SPECIAL_DBUS_SERVICE))
865cc19a 1974 /* The bus might have just become available,
3b2775c5
LP
1975 * hence try to connect to it, if we aren't
1976 * yet connected. */
546ac4f0 1977 bus_init(m, true);
3b2775c5 1978
ac155bb8 1979 if (u->type == UNIT_SERVICE &&
3b2775c5 1980 !UNIT_IS_ACTIVE_OR_RELOADING(os) &&
546ac4f0 1981 m->n_reloading <= 0) {
3b2775c5 1982 /* Write audit record if we have just finished starting up */
546ac4f0 1983 manager_send_unit_audit(m, u, AUDIT_SERVICE_START, true);
ac155bb8 1984 u->in_audit = true;
3b2775c5 1985 }
e983b760 1986
3b2775c5 1987 if (!UNIT_IS_ACTIVE_OR_RELOADING(os))
546ac4f0 1988 manager_send_unit_plymouth(m, u);
bdbf9951 1989
3b2775c5 1990 } else {
bdbf9951 1991
3b2775c5
LP
1992 /* We don't care about D-Bus here, since we'll get an
1993 * asynchronous notification for it anyway. */
cd6d0a45 1994
ac155bb8 1995 if (u->type == UNIT_SERVICE &&
3b2775c5
LP
1996 UNIT_IS_INACTIVE_OR_FAILED(ns) &&
1997 !UNIT_IS_INACTIVE_OR_FAILED(os) &&
546ac4f0 1998 m->n_reloading <= 0) {
4927fcae 1999
3b2775c5
LP
2000 /* Hmm, if there was no start record written
2001 * write it now, so that we always have a nice
2002 * pair */
ac155bb8 2003 if (!u->in_audit) {
546ac4f0 2004 manager_send_unit_audit(m, u, AUDIT_SERVICE_START, ns == UNIT_INACTIVE);
cd6d0a45 2005
3b2775c5 2006 if (ns == UNIT_INACTIVE)
546ac4f0 2007 manager_send_unit_audit(m, u, AUDIT_SERVICE_STOP, true);
3b2775c5
LP
2008 } else
2009 /* Write audit record if we have just finished shutting down */
546ac4f0 2010 manager_send_unit_audit(m, u, AUDIT_SERVICE_STOP, ns == UNIT_INACTIVE);
bdbf9951 2011
ac155bb8 2012 u->in_audit = false;
cd6d0a45 2013 }
f278026d
LP
2014 }
2015
546ac4f0 2016 manager_recheck_journal(m);
3ecaa09b 2017 unit_trigger_notify(u);
3b2775c5 2018
ff502445
LP
2019 if (u->manager->n_reloading <= 0) {
2020 /* Maybe we finished startup and are now ready for
2021 * being stopped because unneeded? */
bf6dcfa6 2022 unit_check_unneeded(u);
c1e1601e 2023
ff502445
LP
2024 /* Maybe we finished startup, but something we needed
2025 * has vanished? Let's die then. (This happens when
2026 * something BindsTo= to a Type=oneshot unit, as these
2027 * units go directly from starting to inactive,
2028 * without ever entering started.) */
2029 unit_check_binds_to(u);
2030 }
2031
c1e1601e 2032 unit_add_to_dbus_queue(u);
701cc384 2033 unit_add_to_gc_queue(u);
87f0e418
LP
2034}
2035
87f0e418 2036int unit_watch_pid(Unit *u, pid_t pid) {
a911bb9a
LP
2037 int q, r;
2038
87f0e418
LP
2039 assert(u);
2040 assert(pid >= 1);
2041
5ba6985b
LP
2042 /* Watch a specific PID. We only support one or two units
2043 * watching each PID for now, not more. */
2044
d5099efc 2045 r = set_ensure_allocated(&u->pids, NULL);
5ba6985b
LP
2046 if (r < 0)
2047 return r;
2048
d5099efc 2049 r = hashmap_ensure_allocated(&u->manager->watch_pids1, NULL);
a911bb9a
LP
2050 if (r < 0)
2051 return r;
2052
fea72cc0 2053 r = hashmap_put(u->manager->watch_pids1, PID_TO_PTR(pid), u);
5ba6985b 2054 if (r == -EEXIST) {
d5099efc 2055 r = hashmap_ensure_allocated(&u->manager->watch_pids2, NULL);
5ba6985b
LP
2056 if (r < 0)
2057 return r;
05e343b7 2058
fea72cc0 2059 r = hashmap_put(u->manager->watch_pids2, PID_TO_PTR(pid), u);
5ba6985b 2060 }
a911bb9a 2061
fea72cc0 2062 q = set_put(u->pids, PID_TO_PTR(pid));
a911bb9a
LP
2063 if (q < 0)
2064 return q;
2065
2066 return r;
87f0e418
LP
2067}
2068
2069void unit_unwatch_pid(Unit *u, pid_t pid) {
2070 assert(u);
2071 assert(pid >= 1);
2072
fea72cc0
LP
2073 (void) hashmap_remove_value(u->manager->watch_pids1, PID_TO_PTR(pid), u);
2074 (void) hashmap_remove_value(u->manager->watch_pids2, PID_TO_PTR(pid), u);
2075 (void) set_remove(u->pids, PID_TO_PTR(pid));
a911bb9a
LP
2076}
2077
bd44e61b
LP
2078void unit_unwatch_all_pids(Unit *u) {
2079 assert(u);
2080
2081 while (!set_isempty(u->pids))
fea72cc0 2082 unit_unwatch_pid(u, PTR_TO_PID(set_first(u->pids)));
bd44e61b 2083
efdb0237 2084 u->pids = set_free(u->pids);
a911bb9a
LP
2085}
2086
2087void unit_tidy_watch_pids(Unit *u, pid_t except1, pid_t except2) {
2088 Iterator i;
2089 void *e;
2090
2091 assert(u);
2092
2093 /* Cleans dead PIDs from our list */
2094
2095 SET_FOREACH(e, u->pids, i) {
fea72cc0 2096 pid_t pid = PTR_TO_PID(e);
a911bb9a
LP
2097
2098 if (pid == except1 || pid == except2)
2099 continue;
2100
9f5650ae 2101 if (!pid_is_unwaited(pid))
bd44e61b 2102 unit_unwatch_pid(u, pid);
a911bb9a 2103 }
87f0e418
LP
2104}
2105
87f0e418
LP
2106bool unit_job_is_applicable(Unit *u, JobType j) {
2107 assert(u);
2108 assert(j >= 0 && j < _JOB_TYPE_MAX);
2109
2110 switch (j) {
2111
2112 case JOB_VERIFY_ACTIVE:
2113 case JOB_START:
57339f47 2114 case JOB_STOP:
e0209d83 2115 case JOB_NOP:
87f0e418
LP
2116 return true;
2117
87f0e418
LP
2118 case JOB_RESTART:
2119 case JOB_TRY_RESTART:
2120 return unit_can_start(u);
2121
2122 case JOB_RELOAD:
3282591d 2123 case JOB_TRY_RELOAD:
87f0e418
LP
2124 return unit_can_reload(u);
2125
2126 case JOB_RELOAD_OR_START:
2127 return unit_can_reload(u) && unit_can_start(u);
2128
2129 default:
2130 assert_not_reached("Invalid job type");
2131 }
2132}
2133
f2341e0a
LP
2134static void maybe_warn_about_dependency(Unit *u, const char *other, UnitDependency dependency) {
2135 assert(u);
d1fab3fe 2136
f2341e0a
LP
2137 /* Only warn about some unit types */
2138 if (!IN_SET(dependency, UNIT_CONFLICTS, UNIT_CONFLICTED_BY, UNIT_BEFORE, UNIT_AFTER, UNIT_ON_FAILURE, UNIT_TRIGGERS, UNIT_TRIGGERED_BY))
2139 return;
3f3cc397 2140
f2341e0a
LP
2141 if (streq_ptr(u->id, other))
2142 log_unit_warning(u, "Dependency %s=%s dropped", unit_dependency_to_string(dependency), u->id);
2143 else
2144 log_unit_warning(u, "Dependency %s=%s dropped, merged into %s", unit_dependency_to_string(dependency), strna(other), u->id);
d1fab3fe
ZJS
2145}
2146
701cc384 2147int unit_add_dependency(Unit *u, UnitDependency d, Unit *other, bool add_reference) {
87f0e418
LP
2148
2149 static const UnitDependency inverse_table[_UNIT_DEPENDENCY_MAX] = {
2150 [UNIT_REQUIRES] = UNIT_REQUIRED_BY,
87f0e418 2151 [UNIT_WANTS] = UNIT_WANTED_BY,
be7d9ff7 2152 [UNIT_REQUISITE] = UNIT_REQUISITE_OF,
7f2cddae 2153 [UNIT_BINDS_TO] = UNIT_BOUND_BY,
60649f17 2154 [UNIT_PART_OF] = UNIT_CONSISTS_OF,
be7d9ff7 2155 [UNIT_REQUIRED_BY] = UNIT_REQUIRES,
be7d9ff7 2156 [UNIT_REQUISITE_OF] = UNIT_REQUISITE,
be7d9ff7 2157 [UNIT_WANTED_BY] = UNIT_WANTS,
7f2cddae 2158 [UNIT_BOUND_BY] = UNIT_BINDS_TO,
60649f17 2159 [UNIT_CONSISTS_OF] = UNIT_PART_OF,
69dd2852
LP
2160 [UNIT_CONFLICTS] = UNIT_CONFLICTED_BY,
2161 [UNIT_CONFLICTED_BY] = UNIT_CONFLICTS,
87f0e418 2162 [UNIT_BEFORE] = UNIT_AFTER,
701cc384 2163 [UNIT_AFTER] = UNIT_BEFORE,
5de9682c 2164 [UNIT_ON_FAILURE] = _UNIT_DEPENDENCY_INVALID,
701cc384 2165 [UNIT_REFERENCES] = UNIT_REFERENCED_BY,
57020a3a
LP
2166 [UNIT_REFERENCED_BY] = UNIT_REFERENCES,
2167 [UNIT_TRIGGERS] = UNIT_TRIGGERED_BY,
4dcc1cb4 2168 [UNIT_TRIGGERED_BY] = UNIT_TRIGGERS,
7f2cddae 2169 [UNIT_PROPAGATES_RELOAD_TO] = UNIT_RELOAD_PROPAGATED_FROM,
85e9a101 2170 [UNIT_RELOAD_PROPAGATED_FROM] = UNIT_PROPAGATES_RELOAD_TO,
613b411c 2171 [UNIT_JOINS_NAMESPACE_OF] = UNIT_JOINS_NAMESPACE_OF,
87f0e418 2172 };
701cc384 2173 int r, q = 0, v = 0, w = 0;
d1fab3fe 2174 Unit *orig_u = u, *orig_other = other;
87f0e418
LP
2175
2176 assert(u);
2177 assert(d >= 0 && d < _UNIT_DEPENDENCY_MAX);
87f0e418
LP
2178 assert(other);
2179
9f151f29
LP
2180 u = unit_follow_merge(u);
2181 other = unit_follow_merge(other);
2182
87f0e418
LP
2183 /* We won't allow dependencies on ourselves. We will not
2184 * consider them an error however. */
d1fab3fe 2185 if (u == other) {
f2341e0a 2186 maybe_warn_about_dependency(orig_u, orig_other->id, d);
87f0e418 2187 return 0;
d1fab3fe 2188 }
87f0e418 2189
d5099efc 2190 r = set_ensure_allocated(&u->dependencies[d], NULL);
613b411c 2191 if (r < 0)
87f0e418
LP
2192 return r;
2193
613b411c 2194 if (inverse_table[d] != _UNIT_DEPENDENCY_INVALID) {
d5099efc 2195 r = set_ensure_allocated(&other->dependencies[inverse_table[d]], NULL);
613b411c
LP
2196 if (r < 0)
2197 return r;
2198 }
2199
2200 if (add_reference) {
d5099efc 2201 r = set_ensure_allocated(&u->dependencies[UNIT_REFERENCES], NULL);
613b411c 2202 if (r < 0)
5de9682c
LP
2203 return r;
2204
d5099efc 2205 r = set_ensure_allocated(&other->dependencies[UNIT_REFERENCED_BY], NULL);
613b411c 2206 if (r < 0)
701cc384 2207 return r;
613b411c 2208 }
87f0e418 2209
613b411c
LP
2210 q = set_put(u->dependencies[d], other);
2211 if (q < 0)
701cc384 2212 return q;
87f0e418 2213
613b411c
LP
2214 if (inverse_table[d] != _UNIT_DEPENDENCY_INVALID && inverse_table[d] != d) {
2215 v = set_put(other->dependencies[inverse_table[d]], u);
2216 if (v < 0) {
5de9682c
LP
2217 r = v;
2218 goto fail;
2219 }
613b411c 2220 }
701cc384
LP
2221
2222 if (add_reference) {
613b411c
LP
2223 w = set_put(u->dependencies[UNIT_REFERENCES], other);
2224 if (w < 0) {
701cc384
LP
2225 r = w;
2226 goto fail;
2227 }
2228
613b411c
LP
2229 r = set_put(other->dependencies[UNIT_REFERENCED_BY], u);
2230 if (r < 0)
701cc384 2231 goto fail;
87f0e418
LP
2232 }
2233
c1e1601e 2234 unit_add_to_dbus_queue(u);
87f0e418 2235 return 0;
701cc384
LP
2236
2237fail:
2238 if (q > 0)
ac155bb8 2239 set_remove(u->dependencies[d], other);
701cc384
LP
2240
2241 if (v > 0)
ac155bb8 2242 set_remove(other->dependencies[inverse_table[d]], u);
701cc384
LP
2243
2244 if (w > 0)
ac155bb8 2245 set_remove(u->dependencies[UNIT_REFERENCES], other);
701cc384
LP
2246
2247 return r;
87f0e418 2248}
0301abf4 2249
2c966c03
LP
2250int unit_add_two_dependencies(Unit *u, UnitDependency d, UnitDependency e, Unit *other, bool add_reference) {
2251 int r;
2252
2253 assert(u);
2254
3f3cc397
LP
2255 r = unit_add_dependency(u, d, other, add_reference);
2256 if (r < 0)
2c966c03
LP
2257 return r;
2258
7410616c 2259 return unit_add_dependency(u, e, other, add_reference);
2c966c03
LP
2260}
2261
7410616c
LP
2262static int resolve_template(Unit *u, const char *name, const char*path, char **buf, const char **ret) {
2263 int r;
9e2f7c11
LP
2264
2265 assert(u);
2266 assert(name || path);
7410616c
LP
2267 assert(buf);
2268 assert(ret);
9e2f7c11
LP
2269
2270 if (!name)
2b6bf07d 2271 name = basename(path);
9e2f7c11 2272
7410616c
LP
2273 if (!unit_name_is_valid(name, UNIT_NAME_TEMPLATE)) {
2274 *buf = NULL;
2275 *ret = name;
2276 return 0;
9e2f7c11
LP
2277 }
2278
ac155bb8 2279 if (u->instance)
7410616c 2280 r = unit_name_replace_instance(name, u->instance, buf);
9e2f7c11 2281 else {
ae018d9b 2282 _cleanup_free_ char *i = NULL;
9e2f7c11 2283
7410616c
LP
2284 r = unit_name_to_prefix(u->id, &i);
2285 if (r < 0)
2286 return r;
9e2f7c11 2287
7410616c 2288 r = unit_name_replace_instance(name, i, buf);
9e2f7c11 2289 }
7410616c
LP
2290 if (r < 0)
2291 return r;
9e2f7c11 2292
7410616c
LP
2293 *ret = *buf;
2294 return 0;
9e2f7c11
LP
2295}
2296
701cc384 2297int unit_add_dependency_by_name(Unit *u, UnitDependency d, const char *name, const char *path, bool add_reference) {
7410616c 2298 _cleanup_free_ char *buf = NULL;
09b6b09f
LP
2299 Unit *other;
2300 int r;
2301
9e2f7c11
LP
2302 assert(u);
2303 assert(name || path);
09b6b09f 2304
7410616c
LP
2305 r = resolve_template(u, name, path, &buf, &name);
2306 if (r < 0)
2307 return r;
09b6b09f 2308
8afbb8e1
LP
2309 r = manager_load_unit(u->manager, name, path, NULL, &other);
2310 if (r < 0)
2311 return r;
9e2f7c11 2312
8afbb8e1 2313 return unit_add_dependency(u, d, other, add_reference);
09b6b09f
LP
2314}
2315
2c966c03 2316int unit_add_two_dependencies_by_name(Unit *u, UnitDependency d, UnitDependency e, const char *name, const char *path, bool add_reference) {
7410616c 2317 _cleanup_free_ char *buf = NULL;
2c966c03
LP
2318 Unit *other;
2319 int r;
2c966c03
LP
2320
2321 assert(u);
2322 assert(name || path);
2323
7410616c
LP
2324 r = resolve_template(u, name, path, &buf, &name);
2325 if (r < 0)
2326 return r;
2c966c03 2327
3f3cc397
LP
2328 r = manager_load_unit(u->manager, name, path, NULL, &other);
2329 if (r < 0)
68eda4bd 2330 return r;
2c966c03 2331
3f3cc397 2332 return unit_add_two_dependencies(u, d, e, other, add_reference);
2c966c03
LP
2333}
2334
0301abf4 2335int set_unit_path(const char *p) {
0301abf4 2336 /* This is mostly for debug purposes */
cbe46ead 2337 if (setenv("SYSTEMD_UNIT_PATH", p, 1) < 0)
26d04f86 2338 return -errno;
0301abf4
LP
2339
2340 return 0;
2341}
88066b3a 2342
ea430986 2343char *unit_dbus_path(Unit *u) {
ea430986
LP
2344 assert(u);
2345
ac155bb8 2346 if (!u->id)
04ade7d2
LP
2347 return NULL;
2348
48899192 2349 return unit_dbus_path_from_name(u->id);
ea430986
LP
2350}
2351
d79200e2
LP
2352int unit_set_slice(Unit *u, Unit *slice) {
2353 assert(u);
2354 assert(slice);
2355
2356 /* Sets the unit slice if it has not been set before. Is extra
2357 * careful, to only allow this for units that actually have a
2358 * cgroup context. Also, we don't allow to set this for slices
2359 * (since the parent slice is derived from the name). Make
2360 * sure the unit we set is actually a slice. */
2361
2362 if (!UNIT_HAS_CGROUP_CONTEXT(u))
2363 return -EOPNOTSUPP;
2364
2365 if (u->type == UNIT_SLICE)
2366 return -EINVAL;
2367
102ef982
LP
2368 if (unit_active_state(u) != UNIT_INACTIVE)
2369 return -EBUSY;
2370
d79200e2
LP
2371 if (slice->type != UNIT_SLICE)
2372 return -EINVAL;
2373
efdb0237
LP
2374 if (unit_has_name(u, SPECIAL_INIT_SCOPE) &&
2375 !unit_has_name(slice, SPECIAL_ROOT_SLICE))
2376 return -EPERM;
2377
d79200e2
LP
2378 if (UNIT_DEREF(u->slice) == slice)
2379 return 0;
2380
2381 if (UNIT_ISSET(u->slice))
2382 return -EBUSY;
2383
2384 unit_ref_set(&u->slice, slice);
2385 return 1;
2386}
2387
2388int unit_set_default_slice(Unit *u) {
a8833944
LP
2389 _cleanup_free_ char *b = NULL;
2390 const char *slice_name;
a016b922
LP
2391 Unit *slice;
2392 int r;
2393
2394 assert(u);
2395
9444b1f2 2396 if (UNIT_ISSET(u->slice))
a016b922
LP
2397 return 0;
2398
a8833944
LP
2399 if (u->instance) {
2400 _cleanup_free_ char *prefix = NULL, *escaped = NULL;
68eda4bd 2401
a8833944
LP
2402 /* Implicitly place all instantiated units in their
2403 * own per-template slice */
2404
7410616c
LP
2405 r = unit_name_to_prefix(u->id, &prefix);
2406 if (r < 0)
2407 return r;
a8833944
LP
2408
2409 /* The prefix is already escaped, but it might include
2410 * "-" which has a special meaning for slice units,
2411 * hence escape it here extra. */
7410616c 2412 escaped = unit_name_escape(prefix);
a8833944
LP
2413 if (!escaped)
2414 return -ENOMEM;
2415
b2c23da8 2416 if (u->manager->running_as == MANAGER_SYSTEM)
a8833944
LP
2417 b = strjoin("system-", escaped, ".slice", NULL);
2418 else
2419 b = strappend(escaped, ".slice");
2420 if (!b)
2421 return -ENOMEM;
2422
2423 slice_name = b;
2424 } else
2425 slice_name =
efdb0237 2426 u->manager->running_as == MANAGER_SYSTEM && !unit_has_name(u, SPECIAL_INIT_SCOPE)
a8833944
LP
2427 ? SPECIAL_SYSTEM_SLICE
2428 : SPECIAL_ROOT_SLICE;
2429
2430 r = manager_load_unit(u->manager, slice_name, NULL, NULL, &slice);
a016b922
LP
2431 if (r < 0)
2432 return r;
2433
d79200e2 2434 return unit_set_slice(u, slice);
a016b922
LP
2435}
2436
9444b1f2
LP
2437const char *unit_slice_name(Unit *u) {
2438 assert(u);
2439
2440 if (!UNIT_ISSET(u->slice))
2441 return NULL;
2442
2443 return UNIT_DEREF(u->slice)->id;
2444}
2445
f6ff8c29 2446int unit_load_related_unit(Unit *u, const char *type, Unit **_found) {
78edb35a 2447 _cleanup_free_ char *t = NULL;
f6ff8c29
LP
2448 int r;
2449
2450 assert(u);
2451 assert(type);
2452 assert(_found);
2453
7410616c
LP
2454 r = unit_name_change_suffix(u->id, type, &t);
2455 if (r < 0)
2456 return r;
2457 if (unit_has_name(u, t))
2458 return -EINVAL;
f6ff8c29 2459
ac155bb8 2460 r = manager_load_unit(u->manager, t, NULL, NULL, _found);
9e2f7c11 2461 assert(r < 0 || *_found != u);
f6ff8c29
LP
2462 return r;
2463}
2464
bbc29086
DM
2465static int signal_name_owner_changed(sd_bus_message *message, void *userdata, sd_bus_error *error) {
2466 const char *name, *old_owner, *new_owner;
2467 Unit *u = userdata;
2468 int r;
2469
2470 assert(message);
2471 assert(u);
2472
2473 r = sd_bus_message_read(message, "sss", &name, &old_owner, &new_owner);
2474 if (r < 0) {
2475 bus_log_parse_error(r);
2476 return 0;
2477 }
2478
2479 if (UNIT_VTABLE(u)->bus_name_owner_change)
2480 UNIT_VTABLE(u)->bus_name_owner_change(u, name, old_owner, new_owner);
2481
2482 return 0;
2483}
2484
9806e87d
LP
2485int unit_install_bus_match(Unit *u, sd_bus *bus, const char *name) {
2486 const char *match;
bbc29086 2487
9806e87d
LP
2488 assert(u);
2489 assert(bus);
2490 assert(name);
bbc29086
DM
2491
2492 if (u->match_bus_slot)
2493 return -EBUSY;
2494
9806e87d 2495 match = strjoina("type='signal',"
bbc29086
DM
2496 "sender='org.freedesktop.DBus',"
2497 "path='/org/freedesktop/DBus',"
2498 "interface='org.freedesktop.DBus',"
2499 "member='NameOwnerChanged',"
9806e87d 2500 "arg0='", name, "'",
bbc29086 2501 NULL);
bbc29086
DM
2502
2503 return sd_bus_add_match(bus, &u->match_bus_slot, match, signal_name_owner_changed, u);
2504}
2505
05e343b7 2506int unit_watch_bus_name(Unit *u, const char *name) {
bbc29086
DM
2507 int r;
2508
05e343b7
LP
2509 assert(u);
2510 assert(name);
2511
2512 /* Watch a specific name on the bus. We only support one unit
2513 * watching each name for now. */
2514
bbc29086
DM
2515 if (u->manager->api_bus) {
2516 /* If the bus is already available, install the match directly.
2517 * Otherwise, just put the name in the list. bus_setup_api() will take care later. */
9806e87d 2518 r = unit_install_bus_match(u, u->manager->api_bus, name);
bbc29086 2519 if (r < 0)
8ea823b6 2520 return log_warning_errno(r, "Failed to subscribe to NameOwnerChanged signal for '%s': %m", name);
bbc29086
DM
2521 }
2522
2523 r = hashmap_put(u->manager->watch_bus, name, u);
2524 if (r < 0) {
2525 u->match_bus_slot = sd_bus_slot_unref(u->match_bus_slot);
2526 return log_warning_errno(r, "Failed to put bus name to hashmap: %m");
2527 }
2528
2529 return 0;
05e343b7
LP
2530}
2531
2532void unit_unwatch_bus_name(Unit *u, const char *name) {
2533 assert(u);
2534 assert(name);
2535
ac155bb8 2536 hashmap_remove_value(u->manager->watch_bus, name, u);
bbc29086 2537 u->match_bus_slot = sd_bus_slot_unref(u->match_bus_slot);
05e343b7
LP
2538}
2539
a16e1123
LP
2540bool unit_can_serialize(Unit *u) {
2541 assert(u);
2542
2543 return UNIT_VTABLE(u)->serialize && UNIT_VTABLE(u)->deserialize_item;
2544}
2545
6b78f9b4 2546int unit_serialize(Unit *u, FILE *f, FDSet *fds, bool serialize_jobs) {
a16e1123
LP
2547 int r;
2548
2549 assert(u);
2550 assert(f);
2551 assert(fds);
2552
9bdb98c5
LP
2553 if (unit_can_serialize(u)) {
2554 ExecRuntime *rt;
a16e1123 2555
9bdb98c5 2556 r = UNIT_VTABLE(u)->serialize(u, f, fds);
613b411c
LP
2557 if (r < 0)
2558 return r;
9bdb98c5
LP
2559
2560 rt = unit_get_exec_runtime(u);
2561 if (rt) {
f2341e0a 2562 r = exec_runtime_serialize(u, rt, f, fds);
9bdb98c5
LP
2563 if (r < 0)
2564 return r;
2565 }
e0209d83
MS
2566 }
2567
a483fb59
LP
2568 dual_timestamp_serialize(f, "state-change-timestamp", &u->state_change_timestamp);
2569
ac155bb8
MS
2570 dual_timestamp_serialize(f, "inactive-exit-timestamp", &u->inactive_exit_timestamp);
2571 dual_timestamp_serialize(f, "active-enter-timestamp", &u->active_enter_timestamp);
2572 dual_timestamp_serialize(f, "active-exit-timestamp", &u->active_exit_timestamp);
2573 dual_timestamp_serialize(f, "inactive-enter-timestamp", &u->inactive_enter_timestamp);
a483fb59 2574
ac155bb8 2575 dual_timestamp_serialize(f, "condition-timestamp", &u->condition_timestamp);
59fccdc5 2576 dual_timestamp_serialize(f, "assert-timestamp", &u->assert_timestamp);
2791a8f8 2577
ac155bb8
MS
2578 if (dual_timestamp_is_set(&u->condition_timestamp))
2579 unit_serialize_item(u, f, "condition-result", yes_no(u->condition_result));
10717a1a 2580
59fccdc5
LP
2581 if (dual_timestamp_is_set(&u->assert_timestamp))
2582 unit_serialize_item(u, f, "assert-result", yes_no(u->assert_result));
2583
c2756a68 2584 unit_serialize_item(u, f, "transient", yes_no(u->transient));
5ad096b3 2585 unit_serialize_item_format(u, f, "cpuacct-usage-base", "%" PRIu64, u->cpuacct_usage_base);
c2756a68
LP
2586
2587 if (u->cgroup_path)
2588 unit_serialize_item(u, f, "cgroup", u->cgroup_path);
de1d4f9b 2589 unit_serialize_item(u, f, "cgroup-realized", yes_no(u->cgroup_realized));
c2756a68 2590
613b411c
LP
2591 if (serialize_jobs) {
2592 if (u->job) {
2593 fprintf(f, "job\n");
2594 job_serialize(u->job, f, fds);
2595 }
2596
2597 if (u->nop_job) {
2598 fprintf(f, "job\n");
2599 job_serialize(u->nop_job, f, fds);
2600 }
2601 }
2602
a16e1123
LP
2603 /* End marker */
2604 fputc('\n', f);
2605 return 0;
2606}
2607
a34ceba6
LP
2608int unit_serialize_item(Unit *u, FILE *f, const char *key, const char *value) {
2609 assert(u);
2610 assert(f);
2611 assert(key);
2612
2613 if (!value)
2614 return 0;
2615
2616 fputs(key, f);
2617 fputc('=', f);
2618 fputs(value, f);
2619 fputc('\n', f);
2620
2621 return 1;
2622}
2623
2624int unit_serialize_item_escaped(Unit *u, FILE *f, const char *key, const char *value) {
2625 _cleanup_free_ char *c = NULL;
2626
2627 assert(u);
2628 assert(f);
2629 assert(key);
2630
2631 if (!value)
2632 return 0;
2633
2634 c = cescape(value);
2635 if (!c)
2636 return -ENOMEM;
2637
2638 fputs(key, f);
2639 fputc('=', f);
2640 fputs(c, f);
2641 fputc('\n', f);
2642
2643 return 1;
2644}
2645
2646int unit_serialize_item_fd(Unit *u, FILE *f, FDSet *fds, const char *key, int fd) {
2647 int copy;
2648
2649 assert(u);
2650 assert(f);
2651 assert(key);
2652
2653 if (fd < 0)
2654 return 0;
2655
2656 copy = fdset_put_dup(fds, fd);
2657 if (copy < 0)
2658 return copy;
2659
2660 fprintf(f, "%s=%i\n", key, copy);
2661 return 1;
2662}
2663
a16e1123
LP
2664void unit_serialize_item_format(Unit *u, FILE *f, const char *key, const char *format, ...) {
2665 va_list ap;
2666
2667 assert(u);
2668 assert(f);
2669 assert(key);
2670 assert(format);
2671
2672 fputs(key, f);
2673 fputc('=', f);
2674
2675 va_start(ap, format);
2676 vfprintf(f, format, ap);
2677 va_end(ap);
2678
2679 fputc('\n', f);
2680}
2681
a16e1123 2682int unit_deserialize(Unit *u, FILE *f, FDSet *fds) {
28b99ccd 2683 ExecRuntime **rt = NULL;
9bdb98c5 2684 size_t offset;
a16e1123
LP
2685 int r;
2686
2687 assert(u);
2688 assert(f);
2689 assert(fds);
2690
613b411c
LP
2691 offset = UNIT_VTABLE(u)->exec_runtime_offset;
2692 if (offset > 0)
2693 rt = (ExecRuntime**) ((uint8_t*) u + offset);
2694
a16e1123 2695 for (;;) {
20c03b7b 2696 char line[LINE_MAX], *l, *v;
a16e1123
LP
2697 size_t k;
2698
2699 if (!fgets(line, sizeof(line), f)) {
2700 if (feof(f))
2701 return 0;
2702 return -errno;
2703 }
2704
10f8e83c 2705 char_array_0(line);
a16e1123
LP
2706 l = strstrip(line);
2707
2708 /* End marker */
e911de99 2709 if (isempty(l))
a483fb59 2710 break;
a16e1123
LP
2711
2712 k = strcspn(l, "=");
2713
2714 if (l[k] == '=') {
2715 l[k] = 0;
2716 v = l+k+1;
2717 } else
2718 v = l+k;
2719
cca098b0 2720 if (streq(l, "job")) {
39a18c60
MS
2721 if (v[0] == '\0') {
2722 /* new-style serialized job */
9c3349e2
LP
2723 Job *j;
2724
2725 j = job_new_raw(u);
39a18c60 2726 if (!j)
e911de99 2727 return log_oom();
39a18c60
MS
2728
2729 r = job_deserialize(j, f, fds);
2730 if (r < 0) {
2731 job_free(j);
2732 return r;
2733 }
cca098b0 2734
39a18c60
MS
2735 r = hashmap_put(u->manager->jobs, UINT32_TO_PTR(j->id), j);
2736 if (r < 0) {
2737 job_free(j);
2738 return r;
2739 }
e0209d83
MS
2740
2741 r = job_install_deserialized(j);
2742 if (r < 0) {
2743 hashmap_remove(u->manager->jobs, UINT32_TO_PTR(j->id));
2744 job_free(j);
2745 return r;
2746 }
ed10fa8c
LP
2747 } else /* legacy for pre-44 */
2748 log_unit_warning(u, "Update from too old systemd versions are unsupported, cannot deserialize job: %s", v);
cca098b0 2749 continue;
a483fb59
LP
2750 } else if (streq(l, "state-change-timestamp")) {
2751 dual_timestamp_deserialize(v, &u->state_change_timestamp);
2752 continue;
8aaf019b 2753 } else if (streq(l, "inactive-exit-timestamp")) {
ac155bb8 2754 dual_timestamp_deserialize(v, &u->inactive_exit_timestamp);
8aaf019b
LP
2755 continue;
2756 } else if (streq(l, "active-enter-timestamp")) {
ac155bb8 2757 dual_timestamp_deserialize(v, &u->active_enter_timestamp);
8aaf019b
LP
2758 continue;
2759 } else if (streq(l, "active-exit-timestamp")) {
ac155bb8 2760 dual_timestamp_deserialize(v, &u->active_exit_timestamp);
8aaf019b
LP
2761 continue;
2762 } else if (streq(l, "inactive-enter-timestamp")) {
ac155bb8 2763 dual_timestamp_deserialize(v, &u->inactive_enter_timestamp);
8aaf019b 2764 continue;
2791a8f8 2765 } else if (streq(l, "condition-timestamp")) {
ac155bb8 2766 dual_timestamp_deserialize(v, &u->condition_timestamp);
2791a8f8 2767 continue;
59fccdc5
LP
2768 } else if (streq(l, "assert-timestamp")) {
2769 dual_timestamp_deserialize(v, &u->assert_timestamp);
2770 continue;
2791a8f8 2771 } else if (streq(l, "condition-result")) {
2791a8f8 2772
e911de99
LP
2773 r = parse_boolean(v);
2774 if (r < 0)
f2341e0a 2775 log_unit_debug(u, "Failed to parse condition result value %s, ignoring.", v);
2791a8f8 2776 else
e911de99 2777 u->condition_result = r;
efbac6d2
LP
2778
2779 continue;
c2756a68 2780
59fccdc5 2781 } else if (streq(l, "assert-result")) {
59fccdc5 2782
e911de99
LP
2783 r = parse_boolean(v);
2784 if (r < 0)
f2341e0a 2785 log_unit_debug(u, "Failed to parse assert result value %s, ignoring.", v);
59fccdc5 2786 else
e911de99 2787 u->assert_result = r;
59fccdc5
LP
2788
2789 continue;
2790
c2756a68 2791 } else if (streq(l, "transient")) {
c2756a68 2792
e911de99
LP
2793 r = parse_boolean(v);
2794 if (r < 0)
f2341e0a 2795 log_unit_debug(u, "Failed to parse transient bool %s, ignoring.", v);
c2756a68 2796 else
e911de99 2797 u->transient = r;
c2756a68
LP
2798
2799 continue;
e911de99 2800
5ad096b3
LP
2801 } else if (streq(l, "cpuacct-usage-base")) {
2802
2803 r = safe_atou64(v, &u->cpuacct_usage_base);
2804 if (r < 0)
f2341e0a 2805 log_unit_debug(u, "Failed to parse CPU usage %s, ignoring.", v);
5ad096b3 2806
0f908397 2807 continue;
4e595329 2808
e911de99 2809 } else if (streq(l, "cgroup")) {
72673e86 2810
e911de99
LP
2811 r = unit_set_cgroup_path(u, v);
2812 if (r < 0)
f2341e0a 2813 log_unit_debug_errno(u, r, "Failed to set cgroup path %s, ignoring: %m", v);
4e595329 2814
efdb0237
LP
2815 (void) unit_watch_cgroup(u);
2816
de1d4f9b
WF
2817 continue;
2818 } else if (streq(l, "cgroup-realized")) {
2819 int b;
2820
2821 b = parse_boolean(v);
2822 if (b < 0)
2823 log_unit_debug(u, "Failed to parse cgroup-realized bool %s, ignoring.", v);
2824 else
2825 u->cgroup_realized = b;
2826
c2756a68 2827 continue;
8aaf019b 2828 }
cca098b0 2829
9bdb98c5
LP
2830 if (unit_can_serialize(u)) {
2831 if (rt) {
f2341e0a 2832 r = exec_runtime_deserialize_item(u, rt, l, v, fds);
e911de99 2833 if (r < 0) {
f2341e0a 2834 log_unit_warning(u, "Failed to deserialize runtime parameter '%s', ignoring.", l);
e911de99
LP
2835 continue;
2836 }
2837
2838 /* Returns positive if key was handled by the call */
9bdb98c5
LP
2839 if (r > 0)
2840 continue;
2841 }
2842
2843 r = UNIT_VTABLE(u)->deserialize_item(u, l, v, fds);
613b411c 2844 if (r < 0)
f2341e0a 2845 log_unit_warning(u, "Failed to deserialize unit parameter '%s', ignoring.", l);
613b411c 2846 }
a16e1123 2847 }
a483fb59
LP
2848
2849 /* Versions before 228 did not carry a state change timestamp. In this case, take the current time. This is
2850 * useful, so that timeouts based on this timestamp don't trigger too early, and is in-line with the logic from
1f133e0d 2851 * before 228 where the base for timeouts was not persistent across reboots. */
a483fb59
LP
2852
2853 if (!dual_timestamp_is_set(&u->state_change_timestamp))
2854 dual_timestamp_get(&u->state_change_timestamp);
2855
2856 return 0;
a16e1123
LP
2857}
2858
9d06297e 2859int unit_add_node_link(Unit *u, const char *what, bool wants, UnitDependency dep) {
6e2ef85b 2860 Unit *device;
68eda4bd 2861 _cleanup_free_ char *e = NULL;
6e2ef85b
LP
2862 int r;
2863
2864 assert(u);
2865
6e2ef85b 2866 /* Adds in links to the device node that this unit is based on */
47bc12e1
LP
2867 if (isempty(what))
2868 return 0;
6e2ef85b 2869
8407a5d0 2870 if (!is_device_path(what))
6e2ef85b
LP
2871 return 0;
2872
47bc12e1
LP
2873 /* When device units aren't supported (such as in a
2874 * container), don't create dependencies on them. */
1c2e9646 2875 if (!unit_type_supported(UNIT_DEVICE))
47bc12e1
LP
2876 return 0;
2877
7410616c
LP
2878 r = unit_name_from_path(what, ".device", &e);
2879 if (r < 0)
2880 return r;
6e2ef85b 2881
ac155bb8 2882 r = manager_load_unit(u->manager, e, NULL, NULL, &device);
6e2ef85b
LP
2883 if (r < 0)
2884 return r;
2885
9d06297e
HH
2886 r = unit_add_two_dependencies(u, UNIT_AFTER,
2887 u->manager->running_as == MANAGER_SYSTEM ? dep : UNIT_WANTS,
2888 device, true);
faa368e3 2889 if (r < 0)
6e2ef85b
LP
2890 return r;
2891
faa368e3
LP
2892 if (wants) {
2893 r = unit_add_dependency(device, UNIT_WANTS, u, false);
2894 if (r < 0)
6e2ef85b 2895 return r;
faa368e3 2896 }
6e2ef85b
LP
2897
2898 return 0;
2899}
a16e1123 2900
be847e82 2901int unit_coldplug(Unit *u) {
5a6158b6 2902 int r = 0, q = 0;
cca098b0
LP
2903
2904 assert(u);
2905
f78f265f
LP
2906 /* Make sure we don't enter a loop, when coldplugging
2907 * recursively. */
2908 if (u->coldplugged)
2909 return 0;
2910
2911 u->coldplugged = true;
2912
5a6158b6 2913 if (UNIT_VTABLE(u)->coldplug)
f78f265f 2914 r = UNIT_VTABLE(u)->coldplug(u);
cca098b0 2915
5a6158b6
LP
2916 if (u->job)
2917 q = job_coldplug(u->job);
2918
2919 if (r < 0)
2920 return r;
2921 if (q < 0)
2922 return q;
cca098b0
LP
2923
2924 return 0;
2925}
2926
45fb0699 2927bool unit_need_daemon_reload(Unit *u) {
ae7a7182
OS
2928 _cleanup_strv_free_ char **t = NULL;
2929 char **path;
1b64d026 2930 struct stat st;
ae7a7182 2931 unsigned loaded_cnt, current_cnt;
1b64d026 2932
45fb0699
LP
2933 assert(u);
2934
ac155bb8 2935 if (u->fragment_path) {
5f4b19f4 2936 zero(st);
ac155bb8 2937 if (stat(u->fragment_path, &st) < 0)
5f4b19f4
LP
2938 /* What, cannot access this anymore? */
2939 return true;
45fb0699 2940
ac155bb8
MS
2941 if (u->fragment_mtime > 0 &&
2942 timespec_load(&st.st_mtim) != u->fragment_mtime)
5f4b19f4
LP
2943 return true;
2944 }
2945
1b64d026
LP
2946 if (u->source_path) {
2947 zero(st);
2948 if (stat(u->source_path, &st) < 0)
2949 return true;
2950
2951 if (u->source_mtime > 0 &&
2952 timespec_load(&st.st_mtim) != u->source_mtime)
2953 return true;
2954 }
5f4b19f4 2955
1a7f1b38 2956 (void) unit_find_dropin_paths(u, &t);
ae7a7182
OS
2957 loaded_cnt = strv_length(t);
2958 current_cnt = strv_length(u->dropin_paths);
2959
2960 if (loaded_cnt == current_cnt) {
2961 if (loaded_cnt == 0)
2962 return false;
2963
2964 if (strv_overlap(u->dropin_paths, t)) {
2965 STRV_FOREACH(path, u->dropin_paths) {
2966 zero(st);
2967 if (stat(*path, &st) < 0)
2968 return true;
2969
2970 if (u->dropin_mtime > 0 &&
2971 timespec_load(&st.st_mtim) > u->dropin_mtime)
2972 return true;
2973 }
2974
2975 return false;
2976 } else
2977 return true;
2978 } else
2979 return true;
45fb0699
LP
2980}
2981
fdf20a31 2982void unit_reset_failed(Unit *u) {
5632e374
LP
2983 assert(u);
2984
fdf20a31
MM
2985 if (UNIT_VTABLE(u)->reset_failed)
2986 UNIT_VTABLE(u)->reset_failed(u);
6bf0f408
LP
2987
2988 RATELIMIT_RESET(u->start_limit);
2989 u->start_limit_hit = false;
5632e374
LP
2990}
2991
a7f241db
LP
2992Unit *unit_following(Unit *u) {
2993 assert(u);
2994
2995 if (UNIT_VTABLE(u)->following)
2996 return UNIT_VTABLE(u)->following(u);
2997
2998 return NULL;
2999}
3000
31afa0a4 3001bool unit_stop_pending(Unit *u) {
18ffdfda
LP
3002 assert(u);
3003
31afa0a4
LP
3004 /* This call does check the current state of the unit. It's
3005 * hence useful to be called from state change calls of the
3006 * unit itself, where the state isn't updated yet. This is
3007 * different from unit_inactive_or_pending() which checks both
3008 * the current state and for a queued job. */
18ffdfda 3009
31afa0a4
LP
3010 return u->job && u->job->type == JOB_STOP;
3011}
3012
3013bool unit_inactive_or_pending(Unit *u) {
3014 assert(u);
3015
3016 /* Returns true if the unit is inactive or going down */
18ffdfda 3017
d956ac29
LP
3018 if (UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)))
3019 return true;
3020
31afa0a4 3021 if (unit_stop_pending(u))
18ffdfda
LP
3022 return true;
3023
3024 return false;
3025}
3026
31afa0a4 3027bool unit_active_or_pending(Unit *u) {
f976f3f6
LP
3028 assert(u);
3029
f60c2665 3030 /* Returns true if the unit is active or going up */
f976f3f6
LP
3031
3032 if (UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)))
3033 return true;
3034
ac155bb8
MS
3035 if (u->job &&
3036 (u->job->type == JOB_START ||
3037 u->job->type == JOB_RELOAD_OR_START ||
3038 u->job->type == JOB_RESTART))
f976f3f6
LP
3039 return true;
3040
3041 return false;
3042}
3043
718db961 3044int unit_kill(Unit *u, KillWho w, int signo, sd_bus_error *error) {
8a0867d6
LP
3045 assert(u);
3046 assert(w >= 0 && w < _KILL_WHO_MAX);
8a0867d6
LP
3047 assert(signo > 0);
3048 assert(signo < _NSIG);
3049
8a0867d6 3050 if (!UNIT_VTABLE(u)->kill)
15411c0c 3051 return -EOPNOTSUPP;
8a0867d6 3052
c74f17d9 3053 return UNIT_VTABLE(u)->kill(u, w, signo, error);
8a0867d6
LP
3054}
3055
82659fd7
LP
3056static Set *unit_pid_set(pid_t main_pid, pid_t control_pid) {
3057 Set *pid_set;
3058 int r;
3059
d5099efc 3060 pid_set = set_new(NULL);
82659fd7
LP
3061 if (!pid_set)
3062 return NULL;
3063
3064 /* Exclude the main/control pids from being killed via the cgroup */
3065 if (main_pid > 0) {
fea72cc0 3066 r = set_put(pid_set, PID_TO_PTR(main_pid));
82659fd7
LP
3067 if (r < 0)
3068 goto fail;
3069 }
3070
3071 if (control_pid > 0) {
fea72cc0 3072 r = set_put(pid_set, PID_TO_PTR(control_pid));
82659fd7
LP
3073 if (r < 0)
3074 goto fail;
3075 }
3076
3077 return pid_set;
3078
3079fail:
3080 set_free(pid_set);
3081 return NULL;
3082}
3083
d91c34f2
LP
3084int unit_kill_common(
3085 Unit *u,
3086 KillWho who,
3087 int signo,
3088 pid_t main_pid,
3089 pid_t control_pid,
718db961 3090 sd_bus_error *error) {
d91c34f2 3091
814cc562 3092 int r = 0;
ac5e3a50 3093 bool killed = false;
814cc562 3094
ac5e3a50 3095 if (IN_SET(who, KILL_MAIN, KILL_MAIN_FAIL)) {
814cc562 3096 if (main_pid < 0)
7358dc02 3097 return sd_bus_error_setf(error, BUS_ERROR_NO_SUCH_PROCESS, "%s units have no main processes", unit_type_to_string(u->type));
52f448c3 3098 else if (main_pid == 0)
7358dc02 3099 return sd_bus_error_set_const(error, BUS_ERROR_NO_SUCH_PROCESS, "No main process to kill");
814cc562
MS
3100 }
3101
ac5e3a50 3102 if (IN_SET(who, KILL_CONTROL, KILL_CONTROL_FAIL)) {
814cc562 3103 if (control_pid < 0)
7358dc02 3104 return sd_bus_error_setf(error, BUS_ERROR_NO_SUCH_PROCESS, "%s units have no control processes", unit_type_to_string(u->type));
52f448c3 3105 else if (control_pid == 0)
7358dc02 3106 return sd_bus_error_set_const(error, BUS_ERROR_NO_SUCH_PROCESS, "No control process to kill");
814cc562
MS
3107 }
3108
ac5e3a50
JS
3109 if (IN_SET(who, KILL_CONTROL, KILL_CONTROL_FAIL, KILL_ALL, KILL_ALL_FAIL))
3110 if (control_pid > 0) {
814cc562
MS
3111 if (kill(control_pid, signo) < 0)
3112 r = -errno;
ac5e3a50
JS
3113 else
3114 killed = true;
3115 }
814cc562 3116
ac5e3a50
JS
3117 if (IN_SET(who, KILL_MAIN, KILL_MAIN_FAIL, KILL_ALL, KILL_ALL_FAIL))
3118 if (main_pid > 0) {
814cc562
MS
3119 if (kill(main_pid, signo) < 0)
3120 r = -errno;
ac5e3a50
JS
3121 else
3122 killed = true;
3123 }
814cc562 3124
ac5e3a50 3125 if (IN_SET(who, KILL_ALL, KILL_ALL_FAIL) && u->cgroup_path) {
814cc562
MS
3126 _cleanup_set_free_ Set *pid_set = NULL;
3127 int q;
3128
82659fd7
LP
3129 /* Exclude the main/control pids from being killed via the cgroup */
3130 pid_set = unit_pid_set(main_pid, control_pid);
814cc562
MS
3131 if (!pid_set)
3132 return -ENOMEM;
3133
d0667321 3134 q = cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, signo, false, false, false, pid_set);
814cc562
MS
3135 if (q < 0 && q != -EAGAIN && q != -ESRCH && q != -ENOENT)
3136 r = q;
ac5e3a50
JS
3137 else
3138 killed = true;
814cc562
MS
3139 }
3140
201f0c91 3141 if (r == 0 && !killed && IN_SET(who, KILL_ALL_FAIL, KILL_CONTROL_FAIL))
ac5e3a50
JS
3142 return -ESRCH;
3143
814cc562
MS
3144 return r;
3145}
3146
6210e7fc
LP
3147int unit_following_set(Unit *u, Set **s) {
3148 assert(u);
3149 assert(s);
3150
3151 if (UNIT_VTABLE(u)->following_set)
3152 return UNIT_VTABLE(u)->following_set(u, s);
3153
3154 *s = NULL;
3155 return 0;
3156}
3157
a4375746 3158UnitFileState unit_get_unit_file_state(Unit *u) {
0ec0deaa
LP
3159 int r;
3160
a4375746
LP
3161 assert(u);
3162
0ec0deaa
LP
3163 if (u->unit_file_state < 0 && u->fragment_path) {
3164 r = unit_file_get_state(
b2c23da8 3165 u->manager->running_as == MANAGER_SYSTEM ? UNIT_FILE_SYSTEM : UNIT_FILE_USER,
0ec0deaa
LP
3166 NULL,
3167 basename(u->fragment_path),
3168 &u->unit_file_state);
3169 if (r < 0)
3170 u->unit_file_state = UNIT_FILE_BAD;
3171 }
a4375746 3172
ac155bb8 3173 return u->unit_file_state;
a4375746
LP
3174}
3175
d2dc52db
LP
3176int unit_get_unit_file_preset(Unit *u) {
3177 assert(u);
3178
3179 if (u->unit_file_preset < 0 && u->fragment_path)
3180 u->unit_file_preset = unit_file_query_preset(
b2c23da8 3181 u->manager->running_as == MANAGER_SYSTEM ? UNIT_FILE_SYSTEM : UNIT_FILE_USER,
0ec0deaa
LP
3182 NULL,
3183 basename(u->fragment_path));
d2dc52db
LP
3184
3185 return u->unit_file_preset;
3186}
3187
57020a3a
LP
3188Unit* unit_ref_set(UnitRef *ref, Unit *u) {
3189 assert(ref);
3190 assert(u);
3191
3192 if (ref->unit)
3193 unit_ref_unset(ref);
3194
3195 ref->unit = u;
71fda00f 3196 LIST_PREPEND(refs, u->refs, ref);
57020a3a
LP
3197 return u;
3198}
3199
3200void unit_ref_unset(UnitRef *ref) {
3201 assert(ref);
3202
3203 if (!ref->unit)
3204 return;
3205
71fda00f 3206 LIST_REMOVE(refs, ref->unit->refs, ref);
57020a3a
LP
3207 ref->unit = NULL;
3208}
3209
598459ce
LP
3210int unit_patch_contexts(Unit *u) {
3211 CGroupContext *cc;
3212 ExecContext *ec;
cba6e062
LP
3213 unsigned i;
3214 int r;
3215
e06c73cc 3216 assert(u);
e06c73cc 3217
598459ce
LP
3218 /* Patch in the manager defaults into the exec and cgroup
3219 * contexts, _after_ the rest of the settings have been
3220 * initialized */
085afe36 3221
598459ce
LP
3222 ec = unit_get_exec_context(u);
3223 if (ec) {
3224 /* This only copies in the ones that need memory */
3225 for (i = 0; i < _RLIMIT_MAX; i++)
3226 if (u->manager->rlimit[i] && !ec->rlimit[i]) {
3227 ec->rlimit[i] = newdup(struct rlimit, u->manager->rlimit[i], 1);
3228 if (!ec->rlimit[i])
3229 return -ENOMEM;
3230 }
3231
b2c23da8 3232 if (u->manager->running_as == MANAGER_USER &&
598459ce
LP
3233 !ec->working_directory) {
3234
3235 r = get_home_dir(&ec->working_directory);
3236 if (r < 0)
3237 return r;
4c08c824
LP
3238
3239 /* Allow user services to run, even if the
3240 * home directory is missing */
3241 ec->working_directory_missing_ok = true;
cba6e062
LP
3242 }
3243
b2c23da8 3244 if (u->manager->running_as == MANAGER_USER &&
598459ce
LP
3245 (ec->syscall_whitelist ||
3246 !set_isempty(ec->syscall_filter) ||
3247 !set_isempty(ec->syscall_archs) ||
3248 ec->address_families_whitelist ||
3249 !set_isempty(ec->address_families)))
3250 ec->no_new_privileges = true;
e06c73cc 3251
598459ce 3252 if (ec->private_devices)
a103496c 3253 ec->capability_bounding_set &= ~(UINT64_C(1) << CAP_MKNOD);
cba6e062
LP
3254 }
3255
598459ce
LP
3256 cc = unit_get_cgroup_context(u);
3257 if (cc) {
f513e420 3258
598459ce
LP
3259 if (ec &&
3260 ec->private_devices &&
3261 cc->device_policy == CGROUP_AUTO)
3262 cc->device_policy = CGROUP_CLOSED;
3263 }
f1660f96 3264
cba6e062 3265 return 0;
e06c73cc
LP
3266}
3267
3ef63c31
LP
3268ExecContext *unit_get_exec_context(Unit *u) {
3269 size_t offset;
3270 assert(u);
3271
598459ce
LP
3272 if (u->type < 0)
3273 return NULL;
3274
3ef63c31
LP
3275 offset = UNIT_VTABLE(u)->exec_context_offset;
3276 if (offset <= 0)
3277 return NULL;
3278
3279 return (ExecContext*) ((uint8_t*) u + offset);
3280}
3281
718db961
LP
3282KillContext *unit_get_kill_context(Unit *u) {
3283 size_t offset;
3284 assert(u);
3285
598459ce
LP
3286 if (u->type < 0)
3287 return NULL;
3288
718db961
LP
3289 offset = UNIT_VTABLE(u)->kill_context_offset;
3290 if (offset <= 0)
3291 return NULL;
3292
3293 return (KillContext*) ((uint8_t*) u + offset);
3294}
3295
4ad49000
LP
3296CGroupContext *unit_get_cgroup_context(Unit *u) {
3297 size_t offset;
3298
598459ce
LP
3299 if (u->type < 0)
3300 return NULL;
3301
4ad49000
LP
3302 offset = UNIT_VTABLE(u)->cgroup_context_offset;
3303 if (offset <= 0)
3304 return NULL;
3305
3306 return (CGroupContext*) ((uint8_t*) u + offset);
3307}
3308
613b411c
LP
3309ExecRuntime *unit_get_exec_runtime(Unit *u) {
3310 size_t offset;
3311
598459ce
LP
3312 if (u->type < 0)
3313 return NULL;
3314
613b411c
LP
3315 offset = UNIT_VTABLE(u)->exec_runtime_offset;
3316 if (offset <= 0)
3317 return NULL;
3318
3319 return *(ExecRuntime**) ((uint8_t*) u + offset);
3320}
3321
29686440 3322static int unit_drop_in_dir(Unit *u, UnitSetPropertiesMode mode, bool transient, char **dir) {
3f5e8115
LP
3323 assert(u);
3324
b2c23da8 3325 if (u->manager->running_as == MANAGER_USER) {
29686440 3326 int r;
26d04f86 3327
718880ba
SA
3328 if (mode == UNIT_PERSISTENT && !transient)
3329 r = user_config_home(dir);
3330 else
4d5dec23 3331 r = user_runtime_dir(dir);
26d04f86
LP
3332 if (r == 0)
3333 return -ENOENT;
3f5e8115 3334
29686440
ZJS
3335 return r;
3336 }
26d04f86 3337
29686440
ZJS
3338 if (mode == UNIT_PERSISTENT && !transient)
3339 *dir = strdup("/etc/systemd/system");
8e2af478 3340 else
29686440
ZJS
3341 *dir = strdup("/run/systemd/system");
3342 if (!*dir)
71645aca
LP
3343 return -ENOMEM;
3344
26d04f86 3345 return 0;
71645aca
LP
3346}
3347
8e2af478 3348int unit_write_drop_in(Unit *u, UnitSetPropertiesMode mode, const char *name, const char *data) {
29686440 3349
adb76a70 3350 _cleanup_free_ char *dir = NULL, *p = NULL, *q = NULL;
26d04f86 3351 int r;
71645aca
LP
3352
3353 assert(u);
3354
6d235724 3355 if (!IN_SET(mode, UNIT_PERSISTENT, UNIT_RUNTIME))
8e2af478
LP
3356 return 0;
3357
29686440 3358 r = unit_drop_in_dir(u, mode, u->transient, &dir);
26d04f86
LP
3359 if (r < 0)
3360 return r;
71645aca 3361
adb76a70
WC
3362 r = write_drop_in(dir, u->id, 50, name, data);
3363 if (r < 0)
3364 return r;
3365
3366 r = drop_in_file(dir, u->id, 50, name, &p, &q);
3367 if (r < 0)
3368 return r;
3369
3370 r = strv_extend(&u->dropin_paths, q);
3371 if (r < 0)
3372 return r;
3373
3374 strv_sort(u->dropin_paths);
3375 strv_uniq(u->dropin_paths);
3376
3377 u->dropin_mtime = now(CLOCK_REALTIME);
3378
3379 return 0;
26d04f86 3380}
71645aca 3381
b9ec9359
LP
3382int unit_write_drop_in_format(Unit *u, UnitSetPropertiesMode mode, const char *name, const char *format, ...) {
3383 _cleanup_free_ char *p = NULL;
3384 va_list ap;
3385 int r;
3386
3387 assert(u);
3388 assert(name);
3389 assert(format);
3390
6d235724 3391 if (!IN_SET(mode, UNIT_PERSISTENT, UNIT_RUNTIME))
b9ec9359
LP
3392 return 0;
3393
3394 va_start(ap, format);
3395 r = vasprintf(&p, format, ap);
3396 va_end(ap);
3397
3398 if (r < 0)
3399 return -ENOMEM;
3400
3401 return unit_write_drop_in(u, mode, name, p);
3402}
3403
3404int unit_write_drop_in_private(Unit *u, UnitSetPropertiesMode mode, const char *name, const char *data) {
b42defe3
LP
3405 _cleanup_free_ char *ndata = NULL;
3406
3407 assert(u);
3408 assert(name);
3409 assert(data);
3410
3411 if (!UNIT_VTABLE(u)->private_section)
3412 return -EINVAL;
3413
6d235724 3414 if (!IN_SET(mode, UNIT_PERSISTENT, UNIT_RUNTIME))
b9ec9359
LP
3415 return 0;
3416
b42defe3
LP
3417 ndata = strjoin("[", UNIT_VTABLE(u)->private_section, "]\n", data, NULL);
3418 if (!ndata)
3419 return -ENOMEM;
3420
3421 return unit_write_drop_in(u, mode, name, ndata);
3422}
3423
b9ec9359
LP
3424int unit_write_drop_in_private_format(Unit *u, UnitSetPropertiesMode mode, const char *name, const char *format, ...) {
3425 _cleanup_free_ char *p = NULL;
3426 va_list ap;
3427 int r;
3428
3429 assert(u);
3430 assert(name);
3431 assert(format);
3432
6d235724 3433 if (!IN_SET(mode, UNIT_PERSISTENT, UNIT_RUNTIME))
b9ec9359
LP
3434 return 0;
3435
3436 va_start(ap, format);
3437 r = vasprintf(&p, format, ap);
3438 va_end(ap);
3439
3440 if (r < 0)
3441 return -ENOMEM;
3442
3443 return unit_write_drop_in_private(u, mode, name, p);
3444}
71645aca 3445
c2756a68 3446int unit_make_transient(Unit *u) {
c2756a68
LP
3447 assert(u);
3448
3f5e8115
LP
3449 if (!UNIT_VTABLE(u)->can_transient)
3450 return -EOPNOTSUPP;
3451
c2756a68
LP
3452 u->load_state = UNIT_STUB;
3453 u->load_error = 0;
3454 u->transient = true;
7c65093a 3455
3f5e8115 3456 u->fragment_path = mfree(u->fragment_path);
7c65093a
LP
3457 u->source_path = mfree(u->source_path);
3458 u->dropin_paths = strv_free(u->dropin_paths);
3459 u->fragment_mtime = u->source_mtime = u->dropin_mtime = 0;
3460
3461 unit_add_to_dbus_queue(u);
3462 unit_add_to_gc_queue(u);
3463 unit_add_to_load_queue(u);
c2756a68 3464
3f5e8115 3465 return 0;
c2756a68
LP
3466}
3467
cd2086fe
LP
3468int unit_kill_context(
3469 Unit *u,
3470 KillContext *c,
db2cb23b 3471 KillOperation k,
cd2086fe
LP
3472 pid_t main_pid,
3473 pid_t control_pid,
3474 bool main_pid_alien) {
3475
b821a397
LP
3476 bool wait_for_exit = false;
3477 int sig, r;
cd2086fe
LP
3478
3479 assert(u);
3480 assert(c);
3481
3482 if (c->kill_mode == KILL_NONE)
3483 return 0;
3484
db2cb23b
UTL
3485 switch (k) {
3486 case KILL_KILL:
3487 sig = SIGKILL;
3488 break;
3489 case KILL_ABORT:
3490 sig = SIGABRT;
3491 break;
3492 case KILL_TERMINATE:
3493 sig = c->kill_signal;
3494 break;
3495 default:
3496 assert_not_reached("KillOperation unknown");
3497 }
cd2086fe
LP
3498
3499 if (main_pid > 0) {
3500 r = kill_and_sigcont(main_pid, sig);
3501
3502 if (r < 0 && r != -ESRCH) {
3503 _cleanup_free_ char *comm = NULL;
3504 get_process_comm(main_pid, &comm);
3505
b821a397 3506 log_unit_warning_errno(u, r, "Failed to kill main process " PID_FMT " (%s), ignoring: %m", main_pid, strna(comm));
82659fd7 3507 } else {
bc6aed7b
LP
3508 if (!main_pid_alien)
3509 wait_for_exit = true;
82659fd7 3510
d0667321
LP
3511 if (c->send_sighup && k == KILL_TERMINATE)
3512 (void) kill(main_pid, SIGHUP);
82659fd7 3513 }
cd2086fe
LP
3514 }
3515
3516 if (control_pid > 0) {
3517 r = kill_and_sigcont(control_pid, sig);
3518
3519 if (r < 0 && r != -ESRCH) {
3520 _cleanup_free_ char *comm = NULL;
3521 get_process_comm(control_pid, &comm);
3522
b821a397 3523 log_unit_warning_errno(u, r, "Failed to kill control process " PID_FMT " (%s), ignoring: %m", control_pid, strna(comm));
82659fd7 3524 } else {
cd2086fe 3525 wait_for_exit = true;
82659fd7 3526
d0667321
LP
3527 if (c->send_sighup && k == KILL_TERMINATE)
3528 (void) kill(control_pid, SIGHUP);
82659fd7 3529 }
cd2086fe
LP
3530 }
3531
b821a397
LP
3532 if (u->cgroup_path &&
3533 (c->kill_mode == KILL_CONTROL_GROUP || (c->kill_mode == KILL_MIXED && k == KILL_KILL))) {
cd2086fe
LP
3534 _cleanup_set_free_ Set *pid_set = NULL;
3535
82659fd7
LP
3536 /* Exclude the main/control pids from being killed via the cgroup */
3537 pid_set = unit_pid_set(main_pid, control_pid);
cd2086fe
LP
3538 if (!pid_set)
3539 return -ENOMEM;
3540
d0667321 3541 r = cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, sig, true, k != KILL_TERMINATE, false, pid_set);
cd2086fe
LP
3542 if (r < 0) {
3543 if (r != -EAGAIN && r != -ESRCH && r != -ENOENT)
b821a397
LP
3544 log_unit_warning_errno(u, r, "Failed to kill control group %s, ignoring: %m", u->cgroup_path);
3545
82659fd7 3546 } else if (r > 0) {
bc6aed7b 3547
efdb0237
LP
3548 /* FIXME: For now, on the legacy hierarchy, we
3549 * will not wait for the cgroup members to die
3550 * if we are running in a container or if this
3551 * is a delegation unit, simply because cgroup
3552 * notification is unreliable in these
3553 * cases. It doesn't work at all in
3554 * containers, and outside of containers it
3555 * can be confused easily by left-over
3556 * directories in the cgroup -- which however
3557 * should not exist in non-delegated units. On
3558 * the unified hierarchy that's different,
3559 * there we get proper events. Hence rely on
3560 * them.*/
3561
3562 if (cg_unified() > 0 ||
75f86906 3563 (detect_container() == 0 && !unit_cgroup_delegate(u)))
e9db43d5 3564 wait_for_exit = true;
58ea275a 3565
db2cb23b 3566 if (c->send_sighup && k != KILL_KILL) {
82659fd7
LP
3567 set_free(pid_set);
3568
3569 pid_set = unit_pid_set(main_pid, control_pid);
3570 if (!pid_set)
3571 return -ENOMEM;
3572
8190da36 3573 cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, SIGHUP, false, true, false, pid_set);
82659fd7
LP
3574 }
3575 }
cd2086fe
LP
3576 }
3577
3578 return wait_for_exit;
3579}
3580
a57f7e2c
LP
3581int unit_require_mounts_for(Unit *u, const char *path) {
3582 char prefix[strlen(path) + 1], *p;
3583 int r;
3584
3585 assert(u);
3586 assert(path);
3587
3588 /* Registers a unit for requiring a certain path and all its
3589 * prefixes. We keep a simple array of these paths in the
3590 * unit, since its usually short. However, we build a prefix
3591 * table for all possible prefixes so that new appearing mount
3592 * units can easily determine which units to make themselves a
3593 * dependency of. */
3594
70b64bd3
ZJS
3595 if (!path_is_absolute(path))
3596 return -EINVAL;
3597
a57f7e2c
LP
3598 p = strdup(path);
3599 if (!p)
3600 return -ENOMEM;
3601
3602 path_kill_slashes(p);
3603
a57f7e2c
LP
3604 if (!path_is_safe(p)) {
3605 free(p);
3606 return -EPERM;
3607 }
3608
3609 if (strv_contains(u->requires_mounts_for, p)) {
3610 free(p);
3611 return 0;
3612 }
3613
6e18964d
ZJS
3614 r = strv_consume(&u->requires_mounts_for, p);
3615 if (r < 0)
a57f7e2c 3616 return r;
a57f7e2c
LP
3617
3618 PATH_FOREACH_PREFIX_MORE(prefix, p) {
3619 Set *x;
3620
3621 x = hashmap_get(u->manager->units_requiring_mounts_for, prefix);
3622 if (!x) {
3623 char *q;
3624
742f41ad
LP
3625 r = hashmap_ensure_allocated(&u->manager->units_requiring_mounts_for, &string_hash_ops);
3626 if (r < 0)
3627 return r;
a57f7e2c
LP
3628
3629 q = strdup(prefix);
3630 if (!q)
3631 return -ENOMEM;
3632
d5099efc 3633 x = set_new(NULL);
a57f7e2c
LP
3634 if (!x) {
3635 free(q);
3636 return -ENOMEM;
3637 }
3638
3639 r = hashmap_put(u->manager->units_requiring_mounts_for, q, x);
3640 if (r < 0) {
3641 free(q);
3642 set_free(x);
3643 return r;
3644 }
3645 }
3646
3647 r = set_put(x, u);
3648 if (r < 0)
3649 return r;
3650 }
3651
3652 return 0;
3653}
3654
613b411c
LP
3655int unit_setup_exec_runtime(Unit *u) {
3656 ExecRuntime **rt;
3657 size_t offset;
3658 Iterator i;
3659 Unit *other;
3660
3661 offset = UNIT_VTABLE(u)->exec_runtime_offset;
3662 assert(offset > 0);
3663
06b643e7 3664 /* Check if there already is an ExecRuntime for this unit? */
613b411c
LP
3665 rt = (ExecRuntime**) ((uint8_t*) u + offset);
3666 if (*rt)
3667 return 0;
3668
3669 /* Try to get it from somebody else */
3670 SET_FOREACH(other, u->dependencies[UNIT_JOINS_NAMESPACE_OF], i) {
3671
3672 *rt = unit_get_exec_runtime(other);
3673 if (*rt) {
3674 exec_runtime_ref(*rt);
3675 return 0;
3676 }
3677 }
3678
3679 return exec_runtime_make(rt, unit_get_exec_context(u), u->id);
3680}
3681
1c2e9646
LP
3682bool unit_type_supported(UnitType t) {
3683 if (_unlikely_(t < 0))
3684 return false;
3685 if (_unlikely_(t >= _UNIT_TYPE_MAX))
3686 return false;
3687
3688 if (!unit_vtable[t]->supported)
3689 return true;
3690
3691 return unit_vtable[t]->supported();
3692}
3693
8b4305c7
LP
3694void unit_warn_if_dir_nonempty(Unit *u, const char* where) {
3695 int r;
3696
3697 assert(u);
3698 assert(where);
3699
3700 r = dir_is_empty(where);
3701 if (r > 0)
3702 return;
3703 if (r < 0) {
3704 log_unit_warning_errno(u, r, "Failed to check directory %s: %m", where);
3705 return;
3706 }
3707
3708 log_struct(LOG_NOTICE,
3709 LOG_MESSAGE_ID(SD_MESSAGE_OVERMOUNTING),
3710 LOG_UNIT_ID(u),
3711 LOG_UNIT_MESSAGE(u, "Directory %s to mount over is not empty, mounting anyway.", where),
3712 "WHERE=%s", where,
3713 NULL);
3714}
3715
3716int unit_fail_if_symlink(Unit *u, const char* where) {
3717 int r;
3718
3719 assert(u);
3720 assert(where);
3721
3722 r = is_symlink(where);
3723 if (r < 0) {
3724 log_unit_debug_errno(u, r, "Failed to check symlink %s, ignoring: %m", where);
3725 return 0;
3726 }
3727 if (r == 0)
3728 return 0;
3729
3730 log_struct(LOG_ERR,
3731 LOG_MESSAGE_ID(SD_MESSAGE_OVERMOUNTING),
3732 LOG_UNIT_ID(u),
3733 LOG_UNIT_MESSAGE(u, "Mount on symlink %s not allowed.", where),
3734 "WHERE=%s", where,
3735 NULL);
3736
3737 return -ELOOP;
3738}
0f13f3bd
LP
3739
3740bool unit_is_pristine(Unit *u) {
3741 assert(u);
3742
7c65093a 3743 /* Check if the unit already exists or is already around,
0f13f3bd
LP
3744 * in a number of different ways. Note that to cater for unit
3745 * types such as slice, we are generally fine with units that
3746 * are marked UNIT_LOADED even even though nothing was
3747 * actually loaded, as those unit types don't require a file
3748 * on disk to validly load. */
3749
3750 return !(!IN_SET(u->load_state, UNIT_NOT_FOUND, UNIT_LOADED) ||
3751 u->fragment_path ||
3752 u->source_path ||
3753 !strv_isempty(u->dropin_paths) ||
0f13f3bd
LP
3754 u->job ||
3755 u->merged_into);
3756}