]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/unit.c
update TODO
[thirdparty/systemd.git] / src / core / unit.c
CommitLineData
d6c9574f 1/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
87f0e418 2
a7334b09
LP
3/***
4 This file is part of systemd.
5
6 Copyright 2010 Lennart Poettering
7
8 systemd is free software; you can redistribute it and/or modify it
5430f7f2
LP
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
a7334b09
LP
11 (at your option) any later version.
12
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
5430f7f2 16 Lesser General Public License for more details.
a7334b09 17
5430f7f2 18 You should have received a copy of the GNU Lesser General Public License
a7334b09
LP
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
20***/
21
87f0e418 22#include <errno.h>
0301abf4 23#include <stdlib.h>
4f5dd394 24#include <string.h>
45fb0699 25#include <sys/stat.h>
4f5dd394 26#include <unistd.h>
87f0e418 27
718db961
LP
28#include "sd-id128.h"
29#include "sd-messages.h"
4f5dd394 30
b5efdb8a 31#include "alloc-util.h"
4f5dd394
LP
32#include "bus-common-errors.h"
33#include "bus-util.h"
c6c18be3 34#include "cgroup-util.h"
4f5dd394
LP
35#include "dbus-unit.h"
36#include "dbus.h"
37#include "dropin.h"
38#include "escape.h"
39#include "execute.h"
a5c32cff 40#include "fileio-label.h"
6482f626 41#include "formats-util.h"
4f5dd394
LP
42#include "load-dropin.h"
43#include "load-fragment.h"
44#include "log.h"
45#include "macro.h"
46#include "missing.h"
47#include "mkdir.h"
6bedfcbb 48#include "parse-util.h"
4f5dd394 49#include "path-util.h"
0b452006 50#include "process-util.h"
4f5dd394 51#include "set.h"
e9db43d5 52#include "special.h"
8fcde012 53#include "stat-util.h"
d054f0a4 54#include "stdio-util.h"
07630cea 55#include "string-util.h"
4f5dd394
LP
56#include "strv.h"
57#include "unit-name.h"
e9db43d5 58#include "unit.h"
b1d4f8e1
LP
59#include "user-util.h"
60#include "virt.h"
87f0e418
LP
61
62const UnitVTable * const unit_vtable[_UNIT_TYPE_MAX] = {
63 [UNIT_SERVICE] = &service_vtable,
87f0e418 64 [UNIT_SOCKET] = &socket_vtable,
e821075a 65 [UNIT_BUSNAME] = &busname_vtable,
87f0e418
LP
66 [UNIT_TARGET] = &target_vtable,
67 [UNIT_DEVICE] = &device_vtable,
68 [UNIT_MOUNT] = &mount_vtable,
69 [UNIT_AUTOMOUNT] = &automount_vtable,
01f78473 70 [UNIT_SWAP] = &swap_vtable,
e821075a 71 [UNIT_TIMER] = &timer_vtable,
a016b922 72 [UNIT_PATH] = &path_vtable,
6c12b52e
LP
73 [UNIT_SLICE] = &slice_vtable,
74 [UNIT_SCOPE] = &scope_vtable
87f0e418
LP
75};
76
f2341e0a 77static void maybe_warn_about_dependency(Unit *u, const char *other, UnitDependency dependency);
d1fab3fe 78
7d17cfbc 79Unit *unit_new(Manager *m, size_t size) {
87f0e418
LP
80 Unit *u;
81
82 assert(m);
ac155bb8 83 assert(size >= sizeof(Unit));
87f0e418 84
7d17cfbc
MS
85 u = malloc0(size);
86 if (!u)
87f0e418
LP
87 return NULL;
88
d5099efc 89 u->names = set_new(&string_hash_ops);
ac155bb8 90 if (!u->names) {
87f0e418
LP
91 free(u);
92 return NULL;
93 }
94
ac155bb8
MS
95 u->manager = m;
96 u->type = _UNIT_TYPE_INVALID;
ac155bb8
MS
97 u->default_dependencies = true;
98 u->unit_file_state = _UNIT_FILE_STATE_INVALID;
d2dc52db 99 u->unit_file_preset = -1;
d420282b 100 u->on_failure_job_mode = JOB_REPLACE;
efdb0237 101 u->cgroup_inotify_wd = -1;
87f0e418 102
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
ac155bb8 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;
32ee7d33 461 int r;
598459ce
LP
462
463 assert(u);
464
465 if (u->type < 0)
466 return;
467
468 if (UNIT_VTABLE(u)->done)
469 UNIT_VTABLE(u)->done(u);
470
471 ec = unit_get_exec_context(u);
472 if (ec)
473 exec_context_done(ec);
474
475 cc = unit_get_cgroup_context(u);
476 if (cc)
477 cgroup_context_done(cc);
32ee7d33
DM
478
479 r = unit_remove_from_netclass_cgroup(u);
480 if (r < 0)
481 log_warning_errno(r, "Unable to remove unit from netclass group: %m");
598459ce
LP
482}
483
87f0e418
LP
484void unit_free(Unit *u) {
485 UnitDependency d;
486 Iterator i;
487 char *t;
488
489 assert(u);
490
c2756a68
LP
491 if (u->manager->n_reloading <= 0)
492 unit_remove_transient(u);
493
c1e1601e
LP
494 bus_unit_send_removed_signal(u);
495
598459ce 496 unit_done(u);
a013b84b 497
cf9fd508
DM
498 sd_bus_slot_unref(u->match_bus_slot);
499
a57f7e2c
LP
500 unit_free_requires_mounts_for(u);
501
ac155bb8
MS
502 SET_FOREACH(t, u->names, i)
503 hashmap_remove_value(u->manager->units, t, u);
87f0e418 504
97e7d748
MS
505 if (u->job) {
506 Job *j = u->job;
507 job_uninstall(j);
508 job_free(j);
509 }
964e0949 510
e0209d83
MS
511 if (u->nop_job) {
512 Job *j = u->nop_job;
513 job_uninstall(j);
514 job_free(j);
515 }
516
964e0949 517 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
ac155bb8 518 bidi_set_free(u, u->dependencies[d]);
964e0949 519
ac155bb8 520 if (u->type != _UNIT_TYPE_INVALID)
71fda00f 521 LIST_REMOVE(units_by_type, u->manager->units_by_type[u->type], u);
ef734fd6 522
ac155bb8 523 if (u->in_load_queue)
71fda00f 524 LIST_REMOVE(load_queue, u->manager->load_queue, u);
87f0e418 525
ac155bb8 526 if (u->in_dbus_queue)
71fda00f 527 LIST_REMOVE(dbus_queue, u->manager->dbus_unit_queue, u);
c1e1601e 528
ac155bb8 529 if (u->in_cleanup_queue)
71fda00f 530 LIST_REMOVE(cleanup_queue, u->manager->cleanup_queue, u);
23a177ef 531
ac155bb8 532 if (u->in_gc_queue) {
71fda00f 533 LIST_REMOVE(gc_queue, u->manager->gc_queue, u);
ac155bb8 534 u->manager->n_in_gc_queue--;
701cc384
LP
535 }
536
4ad49000 537 if (u->in_cgroup_queue)
71fda00f 538 LIST_REMOVE(cgroup_queue, u->manager->cgroup_queue, u);
87f0e418 539
efdb0237 540 unit_release_cgroup(u);
72673e86 541
5269eb6b 542 (void) manager_update_failed_units(u->manager, u, false);
db785129 543 set_remove(u->manager->startup_units, u);
f755e3b7 544
ac155bb8 545 free(u->description);
49dbfa7b 546 strv_free(u->documentation);
ac155bb8 547 free(u->fragment_path);
1b64d026 548 free(u->source_path);
ae7a7182 549 strv_free(u->dropin_paths);
ac155bb8 550 free(u->instance);
87f0e418 551
f189ab18
LP
552 free(u->job_timeout_reboot_arg);
553
ac155bb8 554 set_free_free(u->names);
87f0e418 555
a911bb9a
LP
556 unit_unwatch_all_pids(u);
557
ac155bb8 558 condition_free_list(u->conditions);
59fccdc5 559 condition_free_list(u->asserts);
52661efd 560
702a2d8f
LP
561 unit_ref_unset(&u->slice);
562
ac155bb8
MS
563 while (u->refs)
564 unit_ref_unset(u->refs);
57020a3a 565
87f0e418
LP
566 free(u);
567}
568
569UnitActiveState unit_active_state(Unit *u) {
570 assert(u);
571
ac155bb8 572 if (u->load_state == UNIT_MERGED)
6124958c
LP
573 return unit_active_state(unit_follow_merge(u));
574
575 /* After a reload it might happen that a unit is not correctly
576 * loaded but still has a process around. That's why we won't
fdf20a31 577 * shortcut failed loading to UNIT_INACTIVE_FAILED. */
87f0e418
LP
578
579 return UNIT_VTABLE(u)->active_state(u);
580}
581
10a94420
LP
582const char* unit_sub_state_to_string(Unit *u) {
583 assert(u);
584
585 return UNIT_VTABLE(u)->sub_state_to_string(u);
586}
587
7c0b05e5
MS
588static int complete_move(Set **s, Set **other) {
589 int r;
590
23a177ef
LP
591 assert(s);
592 assert(other);
87f0e418 593
23a177ef 594 if (!*other)
7c0b05e5 595 return 0;
87f0e418 596
7c0b05e5
MS
597 if (*s) {
598 r = set_move(*s, *other);
599 if (r < 0)
600 return r;
601 } else {
23a177ef
LP
602 *s = *other;
603 *other = NULL;
604 }
7c0b05e5
MS
605
606 return 0;
23a177ef 607}
87f0e418 608
7c0b05e5 609static int merge_names(Unit *u, Unit *other) {
23a177ef
LP
610 char *t;
611 Iterator i;
7c0b05e5 612 int r;
87f0e418 613
23a177ef
LP
614 assert(u);
615 assert(other);
616
7c0b05e5
MS
617 r = complete_move(&u->names, &other->names);
618 if (r < 0)
619 return r;
23a177ef 620
ac155bb8
MS
621 set_free_free(other->names);
622 other->names = NULL;
623 other->id = NULL;
23a177ef 624
ac155bb8
MS
625 SET_FOREACH(t, u->names, i)
626 assert_se(hashmap_replace(u->manager->units, t, u) == 0);
7c0b05e5
MS
627
628 return 0;
87f0e418
LP
629}
630
09a65f92
MS
631static int reserve_dependencies(Unit *u, Unit *other, UnitDependency d) {
632 unsigned n_reserve;
633
634 assert(u);
635 assert(other);
636 assert(d < _UNIT_DEPENDENCY_MAX);
637
638 /*
639 * If u does not have this dependency set allocated, there is no need
f131770b 640 * to reserve anything. In that case other's set will be transferred
09a65f92
MS
641 * as a whole to u by complete_move().
642 */
643 if (!u->dependencies[d])
644 return 0;
645
646 /* merge_dependencies() will skip a u-on-u dependency */
647 n_reserve = set_size(other->dependencies[d]) - !!set_get(other->dependencies[d], u);
648
649 return set_reserve(u->dependencies[d], n_reserve);
650}
651
d1fab3fe 652static void merge_dependencies(Unit *u, Unit *other, const char *other_id, UnitDependency d) {
23a177ef
LP
653 Iterator i;
654 Unit *back;
87f0e418 655 int r;
23a177ef
LP
656
657 assert(u);
658 assert(other);
659 assert(d < _UNIT_DEPENDENCY_MAX);
660
83a95334 661 /* Fix backwards pointers */
ac155bb8 662 SET_FOREACH(back, other->dependencies[d], i) {
23a177ef
LP
663 UnitDependency k;
664
e48614c4 665 for (k = 0; k < _UNIT_DEPENDENCY_MAX; k++) {
e66047ff
ZJS
666 /* Do not add dependencies between u and itself */
667 if (back == u) {
d1fab3fe 668 if (set_remove(back->dependencies[k], other))
f2341e0a 669 maybe_warn_about_dependency(u, other_id, k);
e66047ff
ZJS
670 } else {
671 r = set_remove_and_put(back->dependencies[k], other, u);
672 if (r == -EEXIST)
673 set_remove(back->dependencies[k], other);
674 else
675 assert(r >= 0 || r == -ENOENT);
676 }
e48614c4 677 }
23a177ef
LP
678 }
679
e66047ff 680 /* Also do not move dependencies on u to itself */
d1fab3fe
ZJS
681 back = set_remove(other->dependencies[d], u);
682 if (back)
f2341e0a 683 maybe_warn_about_dependency(u, other_id, d);
e66047ff 684
7c0b05e5
MS
685 /* The move cannot fail. The caller must have performed a reservation. */
686 assert_se(complete_move(&u->dependencies[d], &other->dependencies[d]) == 0);
23a177ef 687
525d3cc7 688 other->dependencies[d] = set_free(other->dependencies[d]);
23a177ef
LP
689}
690
691int unit_merge(Unit *u, Unit *other) {
87f0e418 692 UnitDependency d;
d1fab3fe 693 const char *other_id = NULL;
09a65f92 694 int r;
87f0e418
LP
695
696 assert(u);
697 assert(other);
ac155bb8
MS
698 assert(u->manager == other->manager);
699 assert(u->type != _UNIT_TYPE_INVALID);
87f0e418 700
cc916967
LP
701 other = unit_follow_merge(other);
702
23a177ef
LP
703 if (other == u)
704 return 0;
705
ac155bb8 706 if (u->type != other->type)
9e2f7c11
LP
707 return -EINVAL;
708
ac155bb8 709 if (!u->instance != !other->instance)
87f0e418
LP
710 return -EINVAL;
711
ac155bb8 712 if (other->load_state != UNIT_STUB &&
c2756a68 713 other->load_state != UNIT_NOT_FOUND)
23a177ef 714 return -EEXIST;
87f0e418 715
ac155bb8 716 if (other->job)
819e213f
LP
717 return -EEXIST;
718
e0209d83
MS
719 if (other->nop_job)
720 return -EEXIST;
721
fdf20a31 722 if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other)))
819e213f
LP
723 return -EEXIST;
724
d1fab3fe
ZJS
725 if (other->id)
726 other_id = strdupa(other->id);
727
09a65f92
MS
728 /* Make reservations to ensure merge_dependencies() won't fail */
729 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++) {
730 r = reserve_dependencies(u, other, d);
731 /*
732 * We don't rollback reservations if we fail. We don't have
733 * a way to undo reservations. A reservation is not a leak.
734 */
735 if (r < 0)
736 return r;
737 }
738
87f0e418 739 /* Merge names */
7c0b05e5
MS
740 r = merge_names(u, other);
741 if (r < 0)
742 return r;
87f0e418 743
57020a3a 744 /* Redirect all references */
ac155bb8
MS
745 while (other->refs)
746 unit_ref_set(other->refs, u);
57020a3a 747
87f0e418
LP
748 /* Merge dependencies */
749 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
d1fab3fe 750 merge_dependencies(u, other, other_id, d);
87f0e418 751
ac155bb8
MS
752 other->load_state = UNIT_MERGED;
753 other->merged_into = u;
23a177ef 754
3616a49c
LP
755 /* If there is still some data attached to the other node, we
756 * don't need it anymore, and can free it. */
ac155bb8 757 if (other->load_state != UNIT_STUB)
3616a49c
LP
758 if (UNIT_VTABLE(other)->done)
759 UNIT_VTABLE(other)->done(other);
760
761 unit_add_to_dbus_queue(u);
23a177ef
LP
762 unit_add_to_cleanup_queue(other);
763
764 return 0;
765}
766
767int unit_merge_by_name(Unit *u, const char *name) {
768 Unit *other;
9e2f7c11 769 int r;
68eda4bd 770 _cleanup_free_ char *s = NULL;
23a177ef
LP
771
772 assert(u);
773 assert(name);
774
7410616c 775 if (unit_name_is_valid(name, UNIT_NAME_TEMPLATE)) {
ac155bb8 776 if (!u->instance)
9e2f7c11
LP
777 return -EINVAL;
778
7410616c
LP
779 r = unit_name_replace_instance(name, u->instance, &s);
780 if (r < 0)
781 return r;
9e2f7c11
LP
782
783 name = s;
784 }
785
c2756a68 786 other = manager_get_unit(u->manager, name);
7410616c
LP
787 if (other)
788 return unit_merge(u, other);
23a177ef 789
7410616c 790 return unit_add_name(u, name);
23a177ef
LP
791}
792
793Unit* unit_follow_merge(Unit *u) {
794 assert(u);
795
ac155bb8
MS
796 while (u->load_state == UNIT_MERGED)
797 assert_se(u = u->merged_into);
23a177ef
LP
798
799 return u;
800}
801
802int unit_add_exec_dependencies(Unit *u, ExecContext *c) {
803 int r;
804
805 assert(u);
806 assert(c);
807
36be24c8
ZJS
808 if (c->working_directory) {
809 r = unit_require_mounts_for(u, c->working_directory);
810 if (r < 0)
811 return r;
812 }
813
814 if (c->root_directory) {
815 r = unit_require_mounts_for(u, c->root_directory);
816 if (r < 0)
817 return r;
818 }
819
b2c23da8 820 if (u->manager->running_as != MANAGER_SYSTEM)
b46a529c
LP
821 return 0;
822
823 if (c->private_tmp) {
824 r = unit_require_mounts_for(u, "/tmp");
825 if (r < 0)
826 return r;
827
828 r = unit_require_mounts_for(u, "/var/tmp");
829 if (r < 0)
830 return r;
831 }
832
ecc6e2b8
LP
833 if (c->std_output != EXEC_OUTPUT_KMSG &&
834 c->std_output != EXEC_OUTPUT_SYSLOG &&
706343f4 835 c->std_output != EXEC_OUTPUT_JOURNAL &&
28dbc1e8
LP
836 c->std_output != EXEC_OUTPUT_KMSG_AND_CONSOLE &&
837 c->std_output != EXEC_OUTPUT_SYSLOG_AND_CONSOLE &&
706343f4 838 c->std_output != EXEC_OUTPUT_JOURNAL_AND_CONSOLE &&
ecc6e2b8 839 c->std_error != EXEC_OUTPUT_KMSG &&
085c98af 840 c->std_error != EXEC_OUTPUT_SYSLOG &&
706343f4 841 c->std_error != EXEC_OUTPUT_JOURNAL &&
085c98af 842 c->std_error != EXEC_OUTPUT_KMSG_AND_CONSOLE &&
706343f4 843 c->std_error != EXEC_OUTPUT_JOURNAL_AND_CONSOLE &&
28dbc1e8 844 c->std_error != EXEC_OUTPUT_SYSLOG_AND_CONSOLE)
23a177ef
LP
845 return 0;
846
847 /* If syslog or kernel logging is requested, make sure our own
848 * logging daemon is run first. */
849
b46a529c
LP
850 r = unit_add_dependency_by_name(u, UNIT_AFTER, SPECIAL_JOURNALD_SOCKET, NULL, true);
851 if (r < 0)
852 return r;
23a177ef 853
87f0e418
LP
854 return 0;
855}
856
87f0e418
LP
857const char *unit_description(Unit *u) {
858 assert(u);
859
ac155bb8
MS
860 if (u->description)
861 return u->description;
87f0e418 862
ac155bb8 863 return strna(u->id);
87f0e418
LP
864}
865
866void unit_dump(Unit *u, FILE *f, const char *prefix) {
49dbfa7b 867 char *t, **j;
87f0e418
LP
868 UnitDependency d;
869 Iterator i;
47be870b 870 const char *prefix2;
173e3821 871 char
a483fb59 872 timestamp0[FORMAT_TIMESTAMP_MAX],
173e3821
LP
873 timestamp1[FORMAT_TIMESTAMP_MAX],
874 timestamp2[FORMAT_TIMESTAMP_MAX],
875 timestamp3[FORMAT_TIMESTAMP_MAX],
faf919f1
LP
876 timestamp4[FORMAT_TIMESTAMP_MAX],
877 timespan[FORMAT_TIMESPAN_MAX];
a7f241db 878 Unit *following;
eeaedb7c
LP
879 _cleanup_set_free_ Set *following_set = NULL;
880 int r;
87f0e418
LP
881
882 assert(u);
ac155bb8 883 assert(u->type >= 0);
87f0e418 884
4c940960 885 prefix = strempty(prefix);
63c372cb 886 prefix2 = strjoina(prefix, "\t");
87f0e418
LP
887
888 fprintf(f,
40d50879 889 "%s-> Unit %s:\n"
87f0e418 890 "%s\tDescription: %s\n"
9e2f7c11 891 "%s\tInstance: %s\n"
87f0e418 892 "%s\tUnit Load State: %s\n"
2fad8195 893 "%s\tUnit Active State: %s\n"
a483fb59 894 "%s\nState Change Timestamp: %s\n"
173e3821 895 "%s\tInactive Exit Timestamp: %s\n"
2fad8195 896 "%s\tActive Enter Timestamp: %s\n"
701cc384 897 "%s\tActive Exit Timestamp: %s\n"
173e3821 898 "%s\tInactive Enter Timestamp: %s\n"
45fb0699 899 "%s\tGC Check Good: %s\n"
9444b1f2 900 "%s\tNeed Daemon Reload: %s\n"
c2756a68 901 "%s\tTransient: %s\n"
4ad49000
LP
902 "%s\tSlice: %s\n"
903 "%s\tCGroup: %s\n"
904 "%s\tCGroup realized: %s\n"
6414b7c9
DS
905 "%s\tCGroup mask: 0x%x\n"
906 "%s\tCGroup members mask: 0x%x\n",
ac155bb8 907 prefix, u->id,
87f0e418 908 prefix, unit_description(u),
ac155bb8
MS
909 prefix, strna(u->instance),
910 prefix, unit_load_state_to_string(u->load_state),
2fad8195 911 prefix, unit_active_state_to_string(unit_active_state(u)),
a483fb59 912 prefix, strna(format_timestamp(timestamp0, sizeof(timestamp0), u->state_change_timestamp.realtime)),
ac155bb8
MS
913 prefix, strna(format_timestamp(timestamp1, sizeof(timestamp1), u->inactive_exit_timestamp.realtime)),
914 prefix, strna(format_timestamp(timestamp2, sizeof(timestamp2), u->active_enter_timestamp.realtime)),
915 prefix, strna(format_timestamp(timestamp3, sizeof(timestamp3), u->active_exit_timestamp.realtime)),
916 prefix, strna(format_timestamp(timestamp4, sizeof(timestamp4), u->inactive_enter_timestamp.realtime)),
45fb0699 917 prefix, yes_no(unit_check_gc(u)),
9444b1f2 918 prefix, yes_no(unit_need_daemon_reload(u)),
c2756a68 919 prefix, yes_no(u->transient),
4ad49000
LP
920 prefix, strna(unit_slice_name(u)),
921 prefix, strna(u->cgroup_path),
922 prefix, yes_no(u->cgroup_realized),
bc432dc7 923 prefix, u->cgroup_realized_mask,
6414b7c9 924 prefix, u->cgroup_members_mask);
0301abf4 925
ac155bb8 926 SET_FOREACH(t, u->names, i)
87f0e418
LP
927 fprintf(f, "%s\tName: %s\n", prefix, t);
928
49dbfa7b
LP
929 STRV_FOREACH(j, u->documentation)
930 fprintf(f, "%s\tDocumentation: %s\n", prefix, *j);
931
eeaedb7c
LP
932 following = unit_following(u);
933 if (following)
ac155bb8 934 fprintf(f, "%s\tFollowing: %s\n", prefix, following->id);
8fe914ec 935
eeaedb7c
LP
936 r = unit_following_set(u, &following_set);
937 if (r >= 0) {
938 Unit *other;
939
940 SET_FOREACH(other, following_set, i)
941 fprintf(f, "%s\tFollowing Set Member: %s\n", prefix, other->id);
942 }
943
ac155bb8
MS
944 if (u->fragment_path)
945 fprintf(f, "%s\tFragment Path: %s\n", prefix, u->fragment_path);
23a177ef 946
1b64d026
LP
947 if (u->source_path)
948 fprintf(f, "%s\tSource Path: %s\n", prefix, u->source_path);
949
ae7a7182 950 STRV_FOREACH(j, u->dropin_paths)
2875e22b 951 fprintf(f, "%s\tDropIn Path: %s\n", prefix, *j);
ae7a7182 952
ac155bb8 953 if (u->job_timeout > 0)
2fa4092c 954 fprintf(f, "%s\tJob Timeout: %s\n", prefix, format_timespan(timespan, sizeof(timespan), u->job_timeout, 0));
faf919f1 955
f189ab18
LP
956 if (u->job_timeout_action != FAILURE_ACTION_NONE)
957 fprintf(f, "%s\tJob Timeout Action: %s\n", prefix, failure_action_to_string(u->job_timeout_action));
958
959 if (u->job_timeout_reboot_arg)
960 fprintf(f, "%s\tJob Timeout Reboot Argument: %s\n", prefix, u->job_timeout_reboot_arg);
961
59fccdc5
LP
962 condition_dump_list(u->conditions, f, prefix, condition_type_to_string);
963 condition_dump_list(u->asserts, f, prefix, assert_type_to_string);
52661efd 964
ac155bb8 965 if (dual_timestamp_is_set(&u->condition_timestamp))
2791a8f8
LP
966 fprintf(f,
967 "%s\tCondition Timestamp: %s\n"
968 "%s\tCondition Result: %s\n",
ac155bb8
MS
969 prefix, strna(format_timestamp(timestamp1, sizeof(timestamp1), u->condition_timestamp.realtime)),
970 prefix, yes_no(u->condition_result));
2791a8f8 971
59fccdc5
LP
972 if (dual_timestamp_is_set(&u->assert_timestamp))
973 fprintf(f,
974 "%s\tAssert Timestamp: %s\n"
975 "%s\tAssert Result: %s\n",
976 prefix, strna(format_timestamp(timestamp1, sizeof(timestamp1), u->assert_timestamp.realtime)),
977 prefix, yes_no(u->assert_result));
978
87f0e418
LP
979 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++) {
980 Unit *other;
981
ac155bb8
MS
982 SET_FOREACH(other, u->dependencies[d], i)
983 fprintf(f, "%s\t%s: %s\n", prefix, unit_dependency_to_string(d), other->id);
87f0e418
LP
984 }
985
7c8fa05c 986 if (!strv_isempty(u->requires_mounts_for)) {
7c8fa05c
LP
987 fprintf(f,
988 "%s\tRequiresMountsFor:", prefix);
989
990 STRV_FOREACH(j, u->requires_mounts_for)
991 fprintf(f, " %s", *j);
992
993 fputs("\n", f);
994 }
995
ac155bb8 996 if (u->load_state == UNIT_LOADED) {
ab1f0633 997
b0650475 998 fprintf(f,
a40eb732 999 "%s\tStopWhenUnneeded: %s\n"
b5e9dba8
LP
1000 "%s\tRefuseManualStart: %s\n"
1001 "%s\tRefuseManualStop: %s\n"
222ae6a8 1002 "%s\tDefaultDependencies: %s\n"
d420282b 1003 "%s\tOnFailureJobMode: %s\n"
36b4a7ba 1004 "%s\tIgnoreOnIsolate: %s\n",
ac155bb8
MS
1005 prefix, yes_no(u->stop_when_unneeded),
1006 prefix, yes_no(u->refuse_manual_start),
1007 prefix, yes_no(u->refuse_manual_stop),
1008 prefix, yes_no(u->default_dependencies),
d420282b 1009 prefix, job_mode_to_string(u->on_failure_job_mode),
36b4a7ba 1010 prefix, yes_no(u->ignore_on_isolate));
ac155bb8 1011
23a177ef
LP
1012 if (UNIT_VTABLE(u)->dump)
1013 UNIT_VTABLE(u)->dump(u, f, prefix2);
b0650475 1014
ac155bb8 1015 } else if (u->load_state == UNIT_MERGED)
b0650475
LP
1016 fprintf(f,
1017 "%s\tMerged into: %s\n",
ac155bb8
MS
1018 prefix, u->merged_into->id);
1019 else if (u->load_state == UNIT_ERROR)
1020 fprintf(f, "%s\tLoad Error Code: %s\n", prefix, strerror(-u->load_error));
8821a00f 1021
87f0e418 1022
ac155bb8
MS
1023 if (u->job)
1024 job_dump(u->job, f, prefix2);
87f0e418 1025
e0209d83
MS
1026 if (u->nop_job)
1027 job_dump(u->nop_job, f, prefix2);
1028
87f0e418
LP
1029}
1030
1031/* Common implementation for multiple backends */
e537352b 1032int unit_load_fragment_and_dropin(Unit *u) {
23a177ef
LP
1033 int r;
1034
1035 assert(u);
23a177ef 1036
e48614c4 1037 /* Load a .{service,socket,...} file */
4ad49000
LP
1038 r = unit_load_fragment(u);
1039 if (r < 0)
23a177ef
LP
1040 return r;
1041
ac155bb8 1042 if (u->load_state == UNIT_STUB)
23a177ef
LP
1043 return -ENOENT;
1044
1045 /* Load drop-in directory data */
4ad49000
LP
1046 r = unit_load_dropin(unit_follow_merge(u));
1047 if (r < 0)
23a177ef
LP
1048 return r;
1049
1050 return 0;
1051}
1052
1053/* Common implementation for multiple backends */
e537352b 1054int unit_load_fragment_and_dropin_optional(Unit *u) {
23a177ef 1055 int r;
87f0e418
LP
1056
1057 assert(u);
1058
23a177ef
LP
1059 /* Same as unit_load_fragment_and_dropin(), but whether
1060 * something can be loaded or not doesn't matter. */
1061
1062 /* Load a .service file */
4ad49000
LP
1063 r = unit_load_fragment(u);
1064 if (r < 0)
87f0e418
LP
1065 return r;
1066
ac155bb8
MS
1067 if (u->load_state == UNIT_STUB)
1068 u->load_state = UNIT_LOADED;
d46de8a1 1069
87f0e418 1070 /* Load drop-in directory data */
4ad49000
LP
1071 r = unit_load_dropin(unit_follow_merge(u));
1072 if (r < 0)
87f0e418
LP
1073 return r;
1074
23a177ef 1075 return 0;
87f0e418
LP
1076}
1077
bba34eed 1078int unit_add_default_target_dependency(Unit *u, Unit *target) {
98bc2000
LP
1079 assert(u);
1080 assert(target);
1081
ac155bb8 1082 if (target->type != UNIT_TARGET)
98bc2000
LP
1083 return 0;
1084
35b8ca3a 1085 /* Only add the dependency if both units are loaded, so that
bba34eed 1086 * that loop check below is reliable */
ac155bb8
MS
1087 if (u->load_state != UNIT_LOADED ||
1088 target->load_state != UNIT_LOADED)
bba34eed
LP
1089 return 0;
1090
21256a2b
LP
1091 /* If either side wants no automatic dependencies, then let's
1092 * skip this */
ac155bb8
MS
1093 if (!u->default_dependencies ||
1094 !target->default_dependencies)
21256a2b
LP
1095 return 0;
1096
98bc2000 1097 /* Don't create loops */
ac155bb8 1098 if (set_get(target->dependencies[UNIT_BEFORE], u))
98bc2000
LP
1099 return 0;
1100
1101 return unit_add_dependency(target, UNIT_AFTER, u, true);
1102}
1103
e954c9cf 1104static int unit_add_target_dependencies(Unit *u) {
a016b922 1105
21256a2b
LP
1106 static const UnitDependency deps[] = {
1107 UNIT_REQUIRED_BY,
be7d9ff7 1108 UNIT_REQUISITE_OF,
21256a2b
LP
1109 UNIT_WANTED_BY,
1110 UNIT_BOUND_BY
1111 };
1112
bba34eed 1113 Unit *target;
98bc2000 1114 Iterator i;
21256a2b 1115 unsigned k;
db57f3c6 1116 int r = 0;
98bc2000
LP
1117
1118 assert(u);
1119
21256a2b 1120 for (k = 0; k < ELEMENTSOF(deps); k++)
a016b922
LP
1121 SET_FOREACH(target, u->dependencies[deps[k]], i) {
1122 r = unit_add_default_target_dependency(u, target);
1123 if (r < 0)
21256a2b 1124 return r;
a016b922
LP
1125 }
1126
e954c9cf
LP
1127 return r;
1128}
4ad49000 1129
e954c9cf
LP
1130static int unit_add_slice_dependencies(Unit *u) {
1131 assert(u);
b81884e7 1132
35b7ff80 1133 if (!UNIT_HAS_CGROUP_CONTEXT(u))
e954c9cf
LP
1134 return 0;
1135
1136 if (UNIT_ISSET(u->slice))
8c8da0e0 1137 return unit_add_two_dependencies(u, UNIT_AFTER, UNIT_REQUIRES, UNIT_DEREF(u->slice), true);
e954c9cf 1138
8c8da0e0 1139 if (unit_has_name(u, SPECIAL_ROOT_SLICE))
d1fab3fe
ZJS
1140 return 0;
1141
8c8da0e0 1142 return unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_REQUIRES, SPECIAL_ROOT_SLICE, NULL, true);
98bc2000
LP
1143}
1144
e954c9cf 1145static int unit_add_mount_dependencies(Unit *u) {
9588bc32
LP
1146 char **i;
1147 int r;
1148
1149 assert(u);
1150
1151 STRV_FOREACH(i, u->requires_mounts_for) {
1152 char prefix[strlen(*i) + 1];
1153
1154 PATH_FOREACH_PREFIX_MORE(prefix, *i) {
c7c89abb 1155 _cleanup_free_ char *p = NULL;
9588bc32
LP
1156 Unit *m;
1157
c7c89abb 1158 r = unit_name_from_path(prefix, ".mount", &p);
9588bc32
LP
1159 if (r < 0)
1160 return r;
c7c89abb
FB
1161
1162 m = manager_get_unit(u->manager, p);
1163 if (!m) {
1164 /* Make sure to load the mount unit if
1165 * it exists. If so the dependencies
1166 * on this unit will be added later
1167 * during the loading of the mount
1168 * unit. */
1169 (void) manager_load_unit_prepare(u->manager, p, NULL, NULL, &m);
9588bc32 1170 continue;
c7c89abb 1171 }
9588bc32
LP
1172 if (m == u)
1173 continue;
1174
1175 if (m->load_state != UNIT_LOADED)
1176 continue;
1177
1178 r = unit_add_dependency(u, UNIT_AFTER, m, true);
1179 if (r < 0)
1180 return r;
1181
1182 if (m->fragment_path) {
1183 r = unit_add_dependency(u, UNIT_REQUIRES, m, true);
1184 if (r < 0)
1185 return r;
1186 }
1187 }
1188 }
1189
1190 return 0;
1191}
1192
95ae05c0
WC
1193static int unit_add_startup_units(Unit *u) {
1194 CGroupContext *c;
5269eb6b 1195 int r;
95ae05c0
WC
1196
1197 c = unit_get_cgroup_context(u);
db785129
LP
1198 if (!c)
1199 return 0;
1200
d53d9474
LP
1201 if (c->startup_cpu_shares == CGROUP_CPU_SHARES_INVALID &&
1202 c->startup_blockio_weight == CGROUP_BLKIO_WEIGHT_INVALID)
db785129
LP
1203 return 0;
1204
5269eb6b
LP
1205 r = set_ensure_allocated(&u->manager->startup_units, NULL);
1206 if (r < 0)
1207 return r;
1208
756c09e6 1209 return set_put(u->manager->startup_units, u);
95ae05c0
WC
1210}
1211
87f0e418
LP
1212int unit_load(Unit *u) {
1213 int r;
1214
1215 assert(u);
1216
ac155bb8 1217 if (u->in_load_queue) {
71fda00f 1218 LIST_REMOVE(load_queue, u->manager->load_queue, u);
ac155bb8 1219 u->in_load_queue = false;
87f0e418
LP
1220 }
1221
ac155bb8 1222 if (u->type == _UNIT_TYPE_INVALID)
e537352b
LP
1223 return -EINVAL;
1224
ac155bb8 1225 if (u->load_state != UNIT_STUB)
87f0e418
LP
1226 return 0;
1227
c2756a68
LP
1228 if (UNIT_VTABLE(u)->load) {
1229 r = UNIT_VTABLE(u)->load(u);
1230 if (r < 0)
87f0e418 1231 goto fail;
c2756a68 1232 }
23a177ef 1233
ac155bb8 1234 if (u->load_state == UNIT_STUB) {
23a177ef
LP
1235 r = -ENOENT;
1236 goto fail;
1237 }
1238
7c8fa05c 1239 if (u->load_state == UNIT_LOADED) {
c2756a68 1240
e954c9cf
LP
1241 r = unit_add_target_dependencies(u);
1242 if (r < 0)
1243 goto fail;
1244
1245 r = unit_add_slice_dependencies(u);
1246 if (r < 0)
1247 goto fail;
c2756a68 1248
e954c9cf 1249 r = unit_add_mount_dependencies(u);
7c8fa05c 1250 if (r < 0)
c2756a68 1251 goto fail;
7c8fa05c 1252
95ae05c0
WC
1253 r = unit_add_startup_units(u);
1254 if (r < 0)
1255 goto fail;
1256
bc432dc7 1257 if (u->on_failure_job_mode == JOB_ISOLATE && set_size(u->dependencies[UNIT_ON_FAILURE]) > 1) {
f2341e0a 1258 log_unit_error(u, "More than one OnFailure= dependencies specified but OnFailureJobMode=isolate set. Refusing.");
c2756a68
LP
1259 r = -EINVAL;
1260 goto fail;
1261 }
bc432dc7
LP
1262
1263 unit_update_cgroup_members_masks(u);
32ee7d33
DM
1264
1265 /* If we are reloading, we need to wait for the deserializer
1266 * to restore the net_cls ids that have been set previously */
1267 if (u->manager->n_reloading <= 0) {
1268 r = unit_add_to_netclass_cgroup(u);
1269 if (r < 0)
1270 return r;
1271 }
f68319bb
LP
1272 }
1273
ac155bb8 1274 assert((u->load_state != UNIT_MERGED) == !u->merged_into);
23a177ef
LP
1275
1276 unit_add_to_dbus_queue(unit_follow_merge(u));
701cc384 1277 unit_add_to_gc_queue(u);
87f0e418 1278
87f0e418
LP
1279 return 0;
1280
1281fail:
c2756a68 1282 u->load_state = u->load_state == UNIT_STUB ? UNIT_NOT_FOUND : UNIT_ERROR;
ac155bb8 1283 u->load_error = r;
c1e1601e 1284 unit_add_to_dbus_queue(u);
9a46fc3b 1285 unit_add_to_gc_queue(u);
23a177ef 1286
f2341e0a 1287 log_unit_debug_errno(u, r, "Failed to load configuration: %m");
23a177ef 1288
87f0e418
LP
1289 return r;
1290}
1291
49365733
LP
1292static bool unit_condition_test_list(Unit *u, Condition *first, const char *(*to_string)(ConditionType t)) {
1293 Condition *c;
1294 int triggered = -1;
1295
1296 assert(u);
1297 assert(to_string);
1298
1299 /* If the condition list is empty, then it is true */
1300 if (!first)
1301 return true;
1302
1303 /* Otherwise, if all of the non-trigger conditions apply and
1304 * if any of the trigger conditions apply (unless there are
1305 * none) we return true */
1306 LIST_FOREACH(conditions, c, first) {
1307 int r;
1308
1309 r = condition_test(c);
1310 if (r < 0)
f2341e0a
LP
1311 log_unit_warning(u,
1312 "Couldn't determine result for %s=%s%s%s, assuming failed: %m",
49365733
LP
1313 to_string(c->type),
1314 c->trigger ? "|" : "",
1315 c->negate ? "!" : "",
f2341e0a 1316 c->parameter);
49365733 1317 else
f2341e0a
LP
1318 log_unit_debug(u,
1319 "%s=%s%s%s %s.",
49365733
LP
1320 to_string(c->type),
1321 c->trigger ? "|" : "",
1322 c->negate ? "!" : "",
1323 c->parameter,
f2341e0a 1324 condition_result_to_string(c->result));
49365733
LP
1325
1326 if (!c->trigger && r <= 0)
1327 return false;
1328
1329 if (c->trigger && triggered <= 0)
1330 triggered = r > 0;
1331 }
1332
1333 return triggered != 0;
1334}
1335
9588bc32 1336static bool unit_condition_test(Unit *u) {
90bbc946
LP
1337 assert(u);
1338
ac155bb8 1339 dual_timestamp_get(&u->condition_timestamp);
49365733 1340 u->condition_result = unit_condition_test_list(u, u->conditions, condition_type_to_string);
90bbc946 1341
ac155bb8 1342 return u->condition_result;
90bbc946
LP
1343}
1344
59fccdc5
LP
1345static bool unit_assert_test(Unit *u) {
1346 assert(u);
1347
1348 dual_timestamp_get(&u->assert_timestamp);
49365733 1349 u->assert_result = unit_condition_test_list(u, u->asserts, assert_type_to_string);
59fccdc5
LP
1350
1351 return u->assert_result;
1352}
1353
df446f96
LP
1354void unit_status_printf(Unit *u, const char *status, const char *unit_status_msg_format) {
1355 DISABLE_WARNING_FORMAT_NONLITERAL;
1356 manager_status_printf(u->manager, STATUS_TYPE_NORMAL, status, unit_status_msg_format, unit_description(u));
1357 REENABLE_WARNING;
1358}
1359
44a6b1b6 1360_pure_ static const char* unit_get_status_message_format(Unit *u, JobType t) {
877d54e9 1361 const char *format;
a85ca902 1362 const UnitStatusMessageFormats *format_table;
877d54e9
LP
1363
1364 assert(u);
df446f96 1365 assert(IN_SET(t, JOB_START, JOB_STOP, JOB_RELOAD));
877d54e9 1366
b5bf308b 1367 if (t != JOB_RELOAD) {
a85ca902
MS
1368 format_table = &UNIT_VTABLE(u)->status_message_formats;
1369 if (format_table) {
1370 format = format_table->starting_stopping[t == JOB_STOP];
1371 if (format)
1372 return format;
1373 }
1374 }
877d54e9
LP
1375
1376 /* Return generic strings */
1377 if (t == JOB_START)
1378 return "Starting %s.";
1379 else if (t == JOB_STOP)
1380 return "Stopping %s.";
b5bf308b 1381 else
877d54e9 1382 return "Reloading %s.";
877d54e9
LP
1383}
1384
1385static void unit_status_print_starting_stopping(Unit *u, JobType t) {
1386 const char *format;
1387
1388 assert(u);
1389
df446f96
LP
1390 /* Reload status messages have traditionally not been printed to console. */
1391 if (!IN_SET(t, JOB_START, JOB_STOP))
1392 return;
1393
877d54e9 1394 format = unit_get_status_message_format(u, t);
c6918296 1395
bcfce235 1396 DISABLE_WARNING_FORMAT_NONLITERAL;
49b1d377 1397 unit_status_printf(u, "", format);
bcfce235 1398 REENABLE_WARNING;
c6918296
MS
1399}
1400
877d54e9
LP
1401static void unit_status_log_starting_stopping_reloading(Unit *u, JobType t) {
1402 const char *format;
1403 char buf[LINE_MAX];
1404 sd_id128_t mid;
1405
1406 assert(u);
1407
df446f96 1408 if (!IN_SET(t, JOB_START, JOB_STOP, JOB_RELOAD))
877d54e9
LP
1409 return;
1410
81270860
LP
1411 if (log_on_console())
1412 return;
1413
877d54e9
LP
1414 /* We log status messages for all units and all operations. */
1415
a85ca902 1416 format = unit_get_status_message_format(u, t);
877d54e9 1417
bcfce235 1418 DISABLE_WARNING_FORMAT_NONLITERAL;
d054f0a4 1419 xsprintf(buf, format, unit_description(u));
bcfce235 1420 REENABLE_WARNING;
877d54e9
LP
1421
1422 mid = t == JOB_START ? SD_MESSAGE_UNIT_STARTING :
1423 t == JOB_STOP ? SD_MESSAGE_UNIT_STOPPING :
1424 SD_MESSAGE_UNIT_RELOADING;
1425
f2341e0a
LP
1426 /* Note that we deliberately use LOG_MESSAGE() instead of
1427 * LOG_UNIT_MESSAGE() here, since this is supposed to mimic
1428 * closely what is written to screen using the status output,
1429 * which is supposed the highest level, friendliest output
1430 * possible, which means we should avoid the low-level unit
1431 * name. */
1432 log_struct(LOG_INFO,
1433 LOG_MESSAGE_ID(mid),
1434 LOG_UNIT_ID(u),
1435 LOG_MESSAGE("%s", buf),
1436 NULL);
877d54e9 1437}
877d54e9 1438
d1a34ae9 1439void unit_status_emit_starting_stopping_reloading(Unit *u, JobType t) {
df446f96
LP
1440 assert(u);
1441 assert(t >= 0);
1442 assert(t < _JOB_TYPE_MAX);
d1a34ae9
MS
1443
1444 unit_status_log_starting_stopping_reloading(u, t);
df446f96 1445 unit_status_print_starting_stopping(u, t);
d1a34ae9
MS
1446}
1447
87f0e418 1448/* Errors:
d5159713
LP
1449 * -EBADR: This unit type does not support starting.
1450 * -EALREADY: Unit is already started.
1451 * -EAGAIN: An operation is already in progress. Retry later.
1452 * -ECANCELED: Too many requests for now.
59fccdc5 1453 * -EPROTO: Assert failed
87f0e418
LP
1454 */
1455int unit_start(Unit *u) {
1456 UnitActiveState state;
92ab323c 1457 Unit *following;
87f0e418
LP
1458
1459 assert(u);
1460
8ff4d2ab 1461 /* Units that aren't loaded cannot be started */
ac155bb8 1462 if (u->load_state != UNIT_LOADED)
6124958c
LP
1463 return -EINVAL;
1464
a82e5507
LP
1465 /* If this is already started, then this will succeed. Note
1466 * that this will even succeed if this unit is not startable
1467 * by the user. This is relied on to detect when we need to
1468 * wait for units and when waiting is finished. */
87f0e418
LP
1469 state = unit_active_state(u);
1470 if (UNIT_IS_ACTIVE_OR_RELOADING(state))
1471 return -EALREADY;
1472
a82e5507
LP
1473 /* If the conditions failed, don't do anything at all. If we
1474 * already are activating this call might still be useful to
1475 * speed up activation in case there is some hold-off time,
1476 * but we don't want to recheck the condition in that case. */
1477 if (state != UNIT_ACTIVATING &&
1478 !unit_condition_test(u)) {
f2341e0a 1479 log_unit_debug(u, "Starting requested but condition failed. Not starting unit.");
52661efd
LP
1480 return -EALREADY;
1481 }
1482
59fccdc5
LP
1483 /* If the asserts failed, fail the entire job */
1484 if (state != UNIT_ACTIVATING &&
1485 !unit_assert_test(u)) {
f2341e0a 1486 log_unit_notice(u, "Starting requested but asserts failed.");
59fccdc5
LP
1487 return -EPROTO;
1488 }
1489
d11a7645
LP
1490 /* Units of types that aren't supported cannot be
1491 * started. Note that we do this test only after the condition
1492 * checks, so that we rather return condition check errors
1493 * (which are usually not considered a true failure) than "not
1494 * supported" errors (which are considered a failure).
1495 */
1496 if (!unit_supported(u))
1497 return -EOPNOTSUPP;
1498
92ab323c 1499 /* Forward to the main object, if we aren't it. */
52990c2e
ZJS
1500 following = unit_following(u);
1501 if (following) {
f2341e0a 1502 log_unit_debug(u, "Redirecting start request from %s to %s.", u->id, following->id);
92ab323c
LP
1503 return unit_start(following);
1504 }
1505
1506 /* If it is stopped, but we cannot start it, then fail */
1507 if (!UNIT_VTABLE(u)->start)
1508 return -EBADR;
1509
87f0e418
LP
1510 /* We don't suppress calls to ->start() here when we are
1511 * already starting, to allow this request to be used as a
1512 * "hurry up" call, for example when the unit is in some "auto
1513 * restart" state where it waits for a holdoff timer to elapse
1514 * before it will start again. */
1515
c1e1601e 1516 unit_add_to_dbus_queue(u);
9e58ff9c 1517
d1a34ae9 1518 return UNIT_VTABLE(u)->start(u);
87f0e418
LP
1519}
1520
1521bool unit_can_start(Unit *u) {
1522 assert(u);
1523
8ff4d2ab
LP
1524 if (u->load_state != UNIT_LOADED)
1525 return false;
1526
1527 if (!unit_supported(u))
1528 return false;
1529
87f0e418
LP
1530 return !!UNIT_VTABLE(u)->start;
1531}
1532
2528a7a6
LP
1533bool unit_can_isolate(Unit *u) {
1534 assert(u);
1535
1536 return unit_can_start(u) &&
ac155bb8 1537 u->allow_isolate;
2528a7a6
LP
1538}
1539
87f0e418
LP
1540/* Errors:
1541 * -EBADR: This unit type does not support stopping.
1542 * -EALREADY: Unit is already stopped.
1543 * -EAGAIN: An operation is already in progress. Retry later.
1544 */
1545int unit_stop(Unit *u) {
1546 UnitActiveState state;
92ab323c 1547 Unit *following;
87f0e418
LP
1548
1549 assert(u);
1550
87f0e418 1551 state = unit_active_state(u);
fdf20a31 1552 if (UNIT_IS_INACTIVE_OR_FAILED(state))
87f0e418
LP
1553 return -EALREADY;
1554
0faacd47
LP
1555 following = unit_following(u);
1556 if (following) {
f2341e0a 1557 log_unit_debug(u, "Redirecting stop request from %s to %s.", u->id, following->id);
92ab323c
LP
1558 return unit_stop(following);
1559 }
1560
7898b0cf
LP
1561 if (!UNIT_VTABLE(u)->stop)
1562 return -EBADR;
1563
c1e1601e 1564 unit_add_to_dbus_queue(u);
9e58ff9c 1565
d1a34ae9 1566 return UNIT_VTABLE(u)->stop(u);
87f0e418
LP
1567}
1568
1569/* Errors:
1570 * -EBADR: This unit type does not support reloading.
1571 * -ENOEXEC: Unit is not started.
1572 * -EAGAIN: An operation is already in progress. Retry later.
1573 */
1574int unit_reload(Unit *u) {
1575 UnitActiveState state;
92ab323c 1576 Unit *following;
87f0e418
LP
1577
1578 assert(u);
1579
ac155bb8 1580 if (u->load_state != UNIT_LOADED)
6124958c
LP
1581 return -EINVAL;
1582
87f0e418
LP
1583 if (!unit_can_reload(u))
1584 return -EBADR;
1585
1586 state = unit_active_state(u);
e364ad06 1587 if (state == UNIT_RELOADING)
87f0e418
LP
1588 return -EALREADY;
1589
6a371e23 1590 if (state != UNIT_ACTIVE) {
f2341e0a 1591 log_unit_warning(u, "Unit cannot be reloaded because it is inactive.");
87f0e418 1592 return -ENOEXEC;
6a371e23 1593 }
87f0e418 1594
e48614c4
ZJS
1595 following = unit_following(u);
1596 if (following) {
f2341e0a 1597 log_unit_debug(u, "Redirecting reload request from %s to %s.", u->id, following->id);
92ab323c
LP
1598 return unit_reload(following);
1599 }
1600
c1e1601e 1601 unit_add_to_dbus_queue(u);
82a2b6bb 1602
d1a34ae9 1603 return UNIT_VTABLE(u)->reload(u);
87f0e418
LP
1604}
1605
1606bool unit_can_reload(Unit *u) {
1607 assert(u);
1608
1609 if (!UNIT_VTABLE(u)->reload)
1610 return false;
1611
1612 if (!UNIT_VTABLE(u)->can_reload)
1613 return true;
1614
1615 return UNIT_VTABLE(u)->can_reload(u);
1616}
1617
b4a16b7b 1618static void unit_check_unneeded(Unit *u) {
be7d9ff7 1619
4afd3348 1620 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
4bd29fe5 1621
be7d9ff7
LP
1622 static const UnitDependency needed_dependencies[] = {
1623 UNIT_REQUIRED_BY,
084918ba 1624 UNIT_REQUISITE_OF,
be7d9ff7
LP
1625 UNIT_WANTED_BY,
1626 UNIT_BOUND_BY,
1627 };
1628
f3bff0eb 1629 Unit *other;
be7d9ff7
LP
1630 Iterator i;
1631 unsigned j;
1632 int r;
f3bff0eb
LP
1633
1634 assert(u);
1635
1636 /* If this service shall be shut down when unneeded then do
1637 * so. */
1638
ac155bb8 1639 if (!u->stop_when_unneeded)
f3bff0eb
LP
1640 return;
1641
1642 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)))
1643 return;
1644
be7d9ff7 1645 for (j = 0; j < ELEMENTSOF(needed_dependencies); j++)
f3b85044 1646 SET_FOREACH(other, u->dependencies[needed_dependencies[j]], i)
be7d9ff7
LP
1647 if (unit_active_or_pending(other))
1648 return;
b81884e7 1649
bea355da
LP
1650 /* If stopping a unit fails continously we might enter a stop
1651 * loop here, hence stop acting on the service being
1652 * unnecessary after a while. */
67bfdc97 1653 if (!ratelimit_test(&u->auto_stop_ratelimit)) {
bea355da
LP
1654 log_unit_warning(u, "Unit not needed anymore, but not stopping since we tried this too often recently.");
1655 return;
1656 }
1657
f2341e0a 1658 log_unit_info(u, "Unit not needed anymore. Stopping.");
f3bff0eb
LP
1659
1660 /* Ok, nobody needs us anymore. Sniff. Then let's commit suicide */
4bd29fe5 1661 r = manager_add_job(u->manager, JOB_STOP, u, JOB_FAIL, &error, NULL);
be7d9ff7 1662 if (r < 0)
4bd29fe5 1663 log_unit_warning_errno(u, r, "Failed to enqueue stop job, ignoring: %s", bus_error_message(&error, r));
f3bff0eb
LP
1664}
1665
ff502445 1666static void unit_check_binds_to(Unit *u) {
4afd3348 1667 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
ff502445
LP
1668 bool stop = false;
1669 Unit *other;
1670 Iterator i;
67bfdc97 1671 int r;
ff502445
LP
1672
1673 assert(u);
1674
1675 if (u->job)
1676 return;
1677
1678 if (unit_active_state(u) != UNIT_ACTIVE)
1679 return;
1680
1681 SET_FOREACH(other, u->dependencies[UNIT_BINDS_TO], i) {
1682 if (other->job)
1683 continue;
1684
1685 if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other)))
1686 continue;
1687
1688 stop = true;
98f738b6 1689 break;
ff502445
LP
1690 }
1691
1692 if (!stop)
1693 return;
1694
67bfdc97
LP
1695 /* If stopping a unit fails continously we might enter a stop
1696 * loop here, hence stop acting on the service being
1697 * unnecessary after a while. */
1698 if (!ratelimit_test(&u->auto_stop_ratelimit)) {
1699 log_unit_warning(u, "Unit is bound to inactive unit %s, but not stopping since we tried this too often recently.", other->id);
1700 return;
1701 }
1702
98f738b6 1703 assert(other);
f2341e0a 1704 log_unit_info(u, "Unit is bound to inactive unit %s. Stopping, too.", other->id);
ff502445
LP
1705
1706 /* A unit we need to run is gone. Sniff. Let's stop this. */
4bd29fe5 1707 r = manager_add_job(u->manager, JOB_STOP, u, JOB_FAIL, &error, NULL);
67bfdc97 1708 if (r < 0)
4bd29fe5 1709 log_unit_warning_errno(u, r, "Failed to enqueue stop job, ignoring: %s", bus_error_message(&error, r));
ff502445
LP
1710}
1711
87f0e418
LP
1712static void retroactively_start_dependencies(Unit *u) {
1713 Iterator i;
1714 Unit *other;
1715
1716 assert(u);
1717 assert(UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)));
1718
ac155bb8
MS
1719 SET_FOREACH(other, u->dependencies[UNIT_REQUIRES], i)
1720 if (!set_get(u->dependencies[UNIT_AFTER], other) &&
b81884e7 1721 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
4bd29fe5 1722 manager_add_job(u->manager, JOB_START, other, JOB_REPLACE, NULL, NULL);
b81884e7 1723
7f2cddae 1724 SET_FOREACH(other, u->dependencies[UNIT_BINDS_TO], i)
ac155bb8 1725 if (!set_get(u->dependencies[UNIT_AFTER], other) &&
b81884e7 1726 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
4bd29fe5 1727 manager_add_job(u->manager, JOB_START, other, JOB_REPLACE, NULL, NULL);
87f0e418 1728
ac155bb8
MS
1729 SET_FOREACH(other, u->dependencies[UNIT_WANTS], i)
1730 if (!set_get(u->dependencies[UNIT_AFTER], other) &&
b81884e7 1731 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
4bd29fe5 1732 manager_add_job(u->manager, JOB_START, other, JOB_FAIL, NULL, NULL);
87f0e418 1733
ac155bb8 1734 SET_FOREACH(other, u->dependencies[UNIT_CONFLICTS], i)
b81884e7 1735 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
4bd29fe5 1736 manager_add_job(u->manager, JOB_STOP, other, JOB_REPLACE, NULL, NULL);
69dd2852 1737
ac155bb8 1738 SET_FOREACH(other, u->dependencies[UNIT_CONFLICTED_BY], i)
b81884e7 1739 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
4bd29fe5 1740 manager_add_job(u->manager, JOB_STOP, other, JOB_REPLACE, NULL, NULL);
87f0e418
LP
1741}
1742
1743static void retroactively_stop_dependencies(Unit *u) {
1744 Iterator i;
1745 Unit *other;
1746
1747 assert(u);
1748 assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)));
1749
b81884e7 1750 /* Pull down units which are bound to us recursively if enabled */
ac155bb8 1751 SET_FOREACH(other, u->dependencies[UNIT_BOUND_BY], i)
b81884e7 1752 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
4bd29fe5 1753 manager_add_job(u->manager, JOB_STOP, other, JOB_REPLACE, NULL, NULL);
cd0504d0
MS
1754}
1755
1756static void check_unneeded_dependencies(Unit *u) {
1757 Iterator i;
1758 Unit *other;
1759
1760 assert(u);
1761 assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)));
f3bff0eb
LP
1762
1763 /* Garbage collect services that might not be needed anymore, if enabled */
ac155bb8 1764 SET_FOREACH(other, u->dependencies[UNIT_REQUIRES], i)
87f0e418 1765 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
b4a16b7b 1766 unit_check_unneeded(other);
ac155bb8 1767 SET_FOREACH(other, u->dependencies[UNIT_WANTS], i)
f3bff0eb 1768 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
b4a16b7b 1769 unit_check_unneeded(other);
ac155bb8 1770 SET_FOREACH(other, u->dependencies[UNIT_REQUISITE], i)
f3bff0eb 1771 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
b4a16b7b 1772 unit_check_unneeded(other);
7f2cddae 1773 SET_FOREACH(other, u->dependencies[UNIT_BINDS_TO], i)
b81884e7
LP
1774 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1775 unit_check_unneeded(other);
87f0e418
LP
1776}
1777
3ecaa09b 1778void unit_start_on_failure(Unit *u) {
c0daa706
LP
1779 Unit *other;
1780 Iterator i;
1781
1782 assert(u);
1783
ac155bb8 1784 if (set_size(u->dependencies[UNIT_ON_FAILURE]) <= 0)
222ae6a8
LP
1785 return;
1786
f2341e0a 1787 log_unit_info(u, "Triggering OnFailure= dependencies.");
222ae6a8 1788
ac155bb8 1789 SET_FOREACH(other, u->dependencies[UNIT_ON_FAILURE], i) {
222ae6a8
LP
1790 int r;
1791
4bd29fe5 1792 r = manager_add_job(u->manager, JOB_START, other, u->on_failure_job_mode, NULL, NULL);
c1b6628d 1793 if (r < 0)
f2341e0a 1794 log_unit_error_errno(u, r, "Failed to enqueue OnFailure= job: %m");
222ae6a8 1795 }
c0daa706
LP
1796}
1797
3ecaa09b
LP
1798void unit_trigger_notify(Unit *u) {
1799 Unit *other;
1800 Iterator i;
1801
1802 assert(u);
1803
1804 SET_FOREACH(other, u->dependencies[UNIT_TRIGGERED_BY], i)
1805 if (UNIT_VTABLE(other)->trigger_notify)
1806 UNIT_VTABLE(other)->trigger_notify(other, u);
1807}
1808
e2f3b44c 1809void unit_notify(Unit *u, UnitActiveState os, UnitActiveState ns, bool reload_success) {
546ac4f0 1810 Manager *m;
7e6e7b06 1811 bool unexpected;
a096ed36 1812
87f0e418
LP
1813 assert(u);
1814 assert(os < _UNIT_ACTIVE_STATE_MAX);
1815 assert(ns < _UNIT_ACTIVE_STATE_MAX);
87f0e418 1816
8e471ccd
LP
1817 /* Note that this is called for all low-level state changes,
1818 * even if they might map to the same high-level
865cc19a 1819 * UnitActiveState! That means that ns == os is an expected
c5315881 1820 * behavior here. For example: if a mount point is remounted
cd6d0a45 1821 * this function will be called too! */
87f0e418 1822
546ac4f0
MS
1823 m = u->manager;
1824
f755e3b7 1825 /* Update timestamps for state changes */
546ac4f0 1826 if (m->n_reloading <= 0) {
a483fb59 1827 dual_timestamp_get(&u->state_change_timestamp);
173e3821 1828
bdbf9951 1829 if (UNIT_IS_INACTIVE_OR_FAILED(os) && !UNIT_IS_INACTIVE_OR_FAILED(ns))
a483fb59 1830 u->inactive_exit_timestamp = u->state_change_timestamp;
bdbf9951 1831 else if (!UNIT_IS_INACTIVE_OR_FAILED(os) && UNIT_IS_INACTIVE_OR_FAILED(ns))
a483fb59 1832 u->inactive_enter_timestamp = u->state_change_timestamp;
bdbf9951
LP
1833
1834 if (!UNIT_IS_ACTIVE_OR_RELOADING(os) && UNIT_IS_ACTIVE_OR_RELOADING(ns))
a483fb59 1835 u->active_enter_timestamp = u->state_change_timestamp;
bdbf9951 1836 else if (UNIT_IS_ACTIVE_OR_RELOADING(os) && !UNIT_IS_ACTIVE_OR_RELOADING(ns))
a483fb59 1837 u->active_exit_timestamp = u->state_change_timestamp;
bdbf9951 1838 }
87f0e418 1839
865cc19a 1840 /* Keep track of failed units */
5269eb6b 1841 (void) manager_update_failed_units(u->manager, u, ns == UNIT_FAILED);
f755e3b7
LP
1842
1843 /* Make sure the cgroup is always removed when we become inactive */
fdf20a31 1844 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
efdb0237 1845 unit_prune_cgroup(u);
fb385181 1846
9cd86184 1847 /* Note that this doesn't apply to RemainAfterExit services exiting
6f285378 1848 * successfully, since there's no change of state in that case. Which is
9cd86184 1849 * why it is handled in service_set_state() */
7ed9f6cd 1850 if (UNIT_IS_INACTIVE_OR_FAILED(os) != UNIT_IS_INACTIVE_OR_FAILED(ns)) {
b33918c2
LP
1851 ExecContext *ec;
1852
1853 ec = unit_get_exec_context(u);
7ed9f6cd 1854 if (ec && exec_context_may_touch_console(ec)) {
31a7eb86
ZJS
1855 if (UNIT_IS_INACTIVE_OR_FAILED(ns)) {
1856 m->n_on_console --;
1857
1858 if (m->n_on_console == 0)
1859 /* unset no_console_output flag, since the console is free */
2f38577f 1860 m->no_console_output = false;
31a7eb86
ZJS
1861 } else
1862 m->n_on_console ++;
7ed9f6cd
MS
1863 }
1864 }
1865
ac155bb8 1866 if (u->job) {
7e6e7b06 1867 unexpected = false;
87f0e418 1868
ac155bb8 1869 if (u->job->state == JOB_WAITING)
87f0e418
LP
1870
1871 /* So we reached a different state for this
1872 * job. Let's see if we can run it now if it
1873 * failed previously due to EAGAIN. */
ac155bb8 1874 job_add_to_run_queue(u->job);
87f0e418 1875
b410e6b9 1876 /* Let's check whether this state change constitutes a
35b8ca3a 1877 * finished job, or maybe contradicts a running job and
b410e6b9 1878 * hence needs to invalidate jobs. */
87f0e418 1879
ac155bb8 1880 switch (u->job->type) {
87f0e418 1881
b410e6b9
LP
1882 case JOB_START:
1883 case JOB_VERIFY_ACTIVE:
87f0e418 1884
b410e6b9 1885 if (UNIT_IS_ACTIVE_OR_RELOADING(ns))
5273510e 1886 job_finish_and_invalidate(u->job, JOB_DONE, true);
ac155bb8 1887 else if (u->job->state == JOB_RUNNING && ns != UNIT_ACTIVATING) {
b410e6b9 1888 unexpected = true;
41b02ec7 1889
fdf20a31 1890 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
5273510e 1891 job_finish_and_invalidate(u->job, ns == UNIT_FAILED ? JOB_FAILED : JOB_DONE, true);
b410e6b9 1892 }
87f0e418 1893
b410e6b9 1894 break;
87f0e418 1895
b410e6b9
LP
1896 case JOB_RELOAD:
1897 case JOB_RELOAD_OR_START:
3282591d 1898 case JOB_TRY_RELOAD:
87f0e418 1899
ac155bb8 1900 if (u->job->state == JOB_RUNNING) {
a096ed36 1901 if (ns == UNIT_ACTIVE)
5273510e 1902 job_finish_and_invalidate(u->job, reload_success ? JOB_DONE : JOB_FAILED, true);
032ff4af 1903 else if (ns != UNIT_ACTIVATING && ns != UNIT_RELOADING) {
a096ed36 1904 unexpected = true;
41b02ec7 1905
fdf20a31 1906 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
5273510e 1907 job_finish_and_invalidate(u->job, ns == UNIT_FAILED ? JOB_FAILED : JOB_DONE, true);
a096ed36 1908 }
b410e6b9 1909 }
87f0e418 1910
b410e6b9 1911 break;
87f0e418 1912
b410e6b9
LP
1913 case JOB_STOP:
1914 case JOB_RESTART:
1915 case JOB_TRY_RESTART:
87f0e418 1916
fdf20a31 1917 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
5273510e 1918 job_finish_and_invalidate(u->job, JOB_DONE, true);
ac155bb8 1919 else if (u->job->state == JOB_RUNNING && ns != UNIT_DEACTIVATING) {
b410e6b9 1920 unexpected = true;
5273510e 1921 job_finish_and_invalidate(u->job, JOB_FAILED, true);
b410e6b9 1922 }
87f0e418 1923
b410e6b9 1924 break;
87f0e418 1925
b410e6b9
LP
1926 default:
1927 assert_not_reached("Job type unknown");
87f0e418 1928 }
87f0e418 1929
7e6e7b06
LP
1930 } else
1931 unexpected = true;
1932
546ac4f0 1933 if (m->n_reloading <= 0) {
f3bff0eb 1934
bdbf9951
LP
1935 /* If this state change happened without being
1936 * requested by a job, then let's retroactively start
1937 * or stop dependencies. We skip that step when
1938 * deserializing, since we don't want to create any
1939 * additional jobs just because something is already
1940 * activated. */
1941
1942 if (unexpected) {
1943 if (UNIT_IS_INACTIVE_OR_FAILED(os) && UNIT_IS_ACTIVE_OR_ACTIVATING(ns))
1944 retroactively_start_dependencies(u);
1945 else if (UNIT_IS_ACTIVE_OR_ACTIVATING(os) && UNIT_IS_INACTIVE_OR_DEACTIVATING(ns))
1946 retroactively_stop_dependencies(u);
1947 }
5de9682c 1948
cd0504d0 1949 /* stop unneeded units regardless if going down was expected or not */
b33918c2 1950 if (UNIT_IS_INACTIVE_OR_DEACTIVATING(ns))
cd0504d0
MS
1951 check_unneeded_dependencies(u);
1952
bdbf9951 1953 if (ns != os && ns == UNIT_FAILED) {
f2341e0a 1954 log_unit_notice(u, "Unit entered failed state.");
3ecaa09b 1955 unit_start_on_failure(u);
cd6d0a45 1956 }
3b2775c5 1957 }
e537352b 1958
3b2775c5
LP
1959 /* Some names are special */
1960 if (UNIT_IS_ACTIVE_OR_RELOADING(ns)) {
1961
1962 if (unit_has_name(u, SPECIAL_DBUS_SERVICE))
865cc19a 1963 /* The bus might have just become available,
3b2775c5
LP
1964 * hence try to connect to it, if we aren't
1965 * yet connected. */
546ac4f0 1966 bus_init(m, true);
3b2775c5 1967
ac155bb8 1968 if (u->type == UNIT_SERVICE &&
3b2775c5 1969 !UNIT_IS_ACTIVE_OR_RELOADING(os) &&
546ac4f0 1970 m->n_reloading <= 0) {
3b2775c5 1971 /* Write audit record if we have just finished starting up */
546ac4f0 1972 manager_send_unit_audit(m, u, AUDIT_SERVICE_START, true);
ac155bb8 1973 u->in_audit = true;
3b2775c5 1974 }
e983b760 1975
3b2775c5 1976 if (!UNIT_IS_ACTIVE_OR_RELOADING(os))
546ac4f0 1977 manager_send_unit_plymouth(m, u);
bdbf9951 1978
3b2775c5 1979 } else {
bdbf9951 1980
3b2775c5
LP
1981 /* We don't care about D-Bus here, since we'll get an
1982 * asynchronous notification for it anyway. */
cd6d0a45 1983
ac155bb8 1984 if (u->type == UNIT_SERVICE &&
3b2775c5
LP
1985 UNIT_IS_INACTIVE_OR_FAILED(ns) &&
1986 !UNIT_IS_INACTIVE_OR_FAILED(os) &&
546ac4f0 1987 m->n_reloading <= 0) {
4927fcae 1988
3b2775c5
LP
1989 /* Hmm, if there was no start record written
1990 * write it now, so that we always have a nice
1991 * pair */
ac155bb8 1992 if (!u->in_audit) {
546ac4f0 1993 manager_send_unit_audit(m, u, AUDIT_SERVICE_START, ns == UNIT_INACTIVE);
cd6d0a45 1994
3b2775c5 1995 if (ns == UNIT_INACTIVE)
546ac4f0 1996 manager_send_unit_audit(m, u, AUDIT_SERVICE_STOP, true);
3b2775c5
LP
1997 } else
1998 /* Write audit record if we have just finished shutting down */
546ac4f0 1999 manager_send_unit_audit(m, u, AUDIT_SERVICE_STOP, ns == UNIT_INACTIVE);
bdbf9951 2000
ac155bb8 2001 u->in_audit = false;
cd6d0a45 2002 }
f278026d
LP
2003 }
2004
546ac4f0 2005 manager_recheck_journal(m);
3ecaa09b 2006 unit_trigger_notify(u);
3b2775c5 2007
ff502445
LP
2008 if (u->manager->n_reloading <= 0) {
2009 /* Maybe we finished startup and are now ready for
2010 * being stopped because unneeded? */
bf6dcfa6 2011 unit_check_unneeded(u);
c1e1601e 2012
ff502445
LP
2013 /* Maybe we finished startup, but something we needed
2014 * has vanished? Let's die then. (This happens when
2015 * something BindsTo= to a Type=oneshot unit, as these
2016 * units go directly from starting to inactive,
2017 * without ever entering started.) */
2018 unit_check_binds_to(u);
2019 }
2020
c1e1601e 2021 unit_add_to_dbus_queue(u);
701cc384 2022 unit_add_to_gc_queue(u);
87f0e418
LP
2023}
2024
87f0e418 2025int unit_watch_pid(Unit *u, pid_t pid) {
a911bb9a
LP
2026 int q, r;
2027
87f0e418
LP
2028 assert(u);
2029 assert(pid >= 1);
2030
5ba6985b
LP
2031 /* Watch a specific PID. We only support one or two units
2032 * watching each PID for now, not more. */
2033
d5099efc 2034 r = set_ensure_allocated(&u->pids, NULL);
5ba6985b
LP
2035 if (r < 0)
2036 return r;
2037
d5099efc 2038 r = hashmap_ensure_allocated(&u->manager->watch_pids1, NULL);
a911bb9a
LP
2039 if (r < 0)
2040 return r;
2041
fea72cc0 2042 r = hashmap_put(u->manager->watch_pids1, PID_TO_PTR(pid), u);
5ba6985b 2043 if (r == -EEXIST) {
d5099efc 2044 r = hashmap_ensure_allocated(&u->manager->watch_pids2, NULL);
5ba6985b
LP
2045 if (r < 0)
2046 return r;
05e343b7 2047
fea72cc0 2048 r = hashmap_put(u->manager->watch_pids2, PID_TO_PTR(pid), u);
5ba6985b 2049 }
a911bb9a 2050
fea72cc0 2051 q = set_put(u->pids, PID_TO_PTR(pid));
a911bb9a
LP
2052 if (q < 0)
2053 return q;
2054
2055 return r;
87f0e418
LP
2056}
2057
2058void unit_unwatch_pid(Unit *u, pid_t pid) {
2059 assert(u);
2060 assert(pid >= 1);
2061
fea72cc0
LP
2062 (void) hashmap_remove_value(u->manager->watch_pids1, PID_TO_PTR(pid), u);
2063 (void) hashmap_remove_value(u->manager->watch_pids2, PID_TO_PTR(pid), u);
2064 (void) set_remove(u->pids, PID_TO_PTR(pid));
a911bb9a
LP
2065}
2066
bd44e61b
LP
2067void unit_unwatch_all_pids(Unit *u) {
2068 assert(u);
2069
2070 while (!set_isempty(u->pids))
fea72cc0 2071 unit_unwatch_pid(u, PTR_TO_PID(set_first(u->pids)));
bd44e61b 2072
efdb0237 2073 u->pids = set_free(u->pids);
a911bb9a
LP
2074}
2075
2076void unit_tidy_watch_pids(Unit *u, pid_t except1, pid_t except2) {
2077 Iterator i;
2078 void *e;
2079
2080 assert(u);
2081
2082 /* Cleans dead PIDs from our list */
2083
2084 SET_FOREACH(e, u->pids, i) {
fea72cc0 2085 pid_t pid = PTR_TO_PID(e);
a911bb9a
LP
2086
2087 if (pid == except1 || pid == except2)
2088 continue;
2089
9f5650ae 2090 if (!pid_is_unwaited(pid))
bd44e61b 2091 unit_unwatch_pid(u, pid);
a911bb9a 2092 }
87f0e418
LP
2093}
2094
87f0e418
LP
2095bool unit_job_is_applicable(Unit *u, JobType j) {
2096 assert(u);
2097 assert(j >= 0 && j < _JOB_TYPE_MAX);
2098
2099 switch (j) {
2100
2101 case JOB_VERIFY_ACTIVE:
2102 case JOB_START:
57339f47 2103 case JOB_STOP:
e0209d83 2104 case JOB_NOP:
87f0e418
LP
2105 return true;
2106
87f0e418
LP
2107 case JOB_RESTART:
2108 case JOB_TRY_RESTART:
2109 return unit_can_start(u);
2110
2111 case JOB_RELOAD:
3282591d 2112 case JOB_TRY_RELOAD:
87f0e418
LP
2113 return unit_can_reload(u);
2114
2115 case JOB_RELOAD_OR_START:
2116 return unit_can_reload(u) && unit_can_start(u);
2117
2118 default:
2119 assert_not_reached("Invalid job type");
2120 }
2121}
2122
f2341e0a
LP
2123static void maybe_warn_about_dependency(Unit *u, const char *other, UnitDependency dependency) {
2124 assert(u);
d1fab3fe 2125
f2341e0a
LP
2126 /* Only warn about some unit types */
2127 if (!IN_SET(dependency, UNIT_CONFLICTS, UNIT_CONFLICTED_BY, UNIT_BEFORE, UNIT_AFTER, UNIT_ON_FAILURE, UNIT_TRIGGERS, UNIT_TRIGGERED_BY))
2128 return;
3f3cc397 2129
f2341e0a
LP
2130 if (streq_ptr(u->id, other))
2131 log_unit_warning(u, "Dependency %s=%s dropped", unit_dependency_to_string(dependency), u->id);
2132 else
2133 log_unit_warning(u, "Dependency %s=%s dropped, merged into %s", unit_dependency_to_string(dependency), strna(other), u->id);
d1fab3fe
ZJS
2134}
2135
701cc384 2136int unit_add_dependency(Unit *u, UnitDependency d, Unit *other, bool add_reference) {
87f0e418
LP
2137
2138 static const UnitDependency inverse_table[_UNIT_DEPENDENCY_MAX] = {
2139 [UNIT_REQUIRES] = UNIT_REQUIRED_BY,
87f0e418 2140 [UNIT_WANTS] = UNIT_WANTED_BY,
be7d9ff7 2141 [UNIT_REQUISITE] = UNIT_REQUISITE_OF,
7f2cddae 2142 [UNIT_BINDS_TO] = UNIT_BOUND_BY,
60649f17 2143 [UNIT_PART_OF] = UNIT_CONSISTS_OF,
be7d9ff7 2144 [UNIT_REQUIRED_BY] = UNIT_REQUIRES,
be7d9ff7 2145 [UNIT_REQUISITE_OF] = UNIT_REQUISITE,
be7d9ff7 2146 [UNIT_WANTED_BY] = UNIT_WANTS,
7f2cddae 2147 [UNIT_BOUND_BY] = UNIT_BINDS_TO,
60649f17 2148 [UNIT_CONSISTS_OF] = UNIT_PART_OF,
69dd2852
LP
2149 [UNIT_CONFLICTS] = UNIT_CONFLICTED_BY,
2150 [UNIT_CONFLICTED_BY] = UNIT_CONFLICTS,
87f0e418 2151 [UNIT_BEFORE] = UNIT_AFTER,
701cc384 2152 [UNIT_AFTER] = UNIT_BEFORE,
5de9682c 2153 [UNIT_ON_FAILURE] = _UNIT_DEPENDENCY_INVALID,
701cc384 2154 [UNIT_REFERENCES] = UNIT_REFERENCED_BY,
57020a3a
LP
2155 [UNIT_REFERENCED_BY] = UNIT_REFERENCES,
2156 [UNIT_TRIGGERS] = UNIT_TRIGGERED_BY,
4dcc1cb4 2157 [UNIT_TRIGGERED_BY] = UNIT_TRIGGERS,
7f2cddae 2158 [UNIT_PROPAGATES_RELOAD_TO] = UNIT_RELOAD_PROPAGATED_FROM,
85e9a101 2159 [UNIT_RELOAD_PROPAGATED_FROM] = UNIT_PROPAGATES_RELOAD_TO,
613b411c 2160 [UNIT_JOINS_NAMESPACE_OF] = UNIT_JOINS_NAMESPACE_OF,
87f0e418 2161 };
701cc384 2162 int r, q = 0, v = 0, w = 0;
d1fab3fe 2163 Unit *orig_u = u, *orig_other = other;
87f0e418
LP
2164
2165 assert(u);
2166 assert(d >= 0 && d < _UNIT_DEPENDENCY_MAX);
87f0e418
LP
2167 assert(other);
2168
9f151f29
LP
2169 u = unit_follow_merge(u);
2170 other = unit_follow_merge(other);
2171
87f0e418
LP
2172 /* We won't allow dependencies on ourselves. We will not
2173 * consider them an error however. */
d1fab3fe 2174 if (u == other) {
f2341e0a 2175 maybe_warn_about_dependency(orig_u, orig_other->id, d);
87f0e418 2176 return 0;
d1fab3fe 2177 }
87f0e418 2178
d5099efc 2179 r = set_ensure_allocated(&u->dependencies[d], NULL);
613b411c 2180 if (r < 0)
87f0e418
LP
2181 return r;
2182
613b411c 2183 if (inverse_table[d] != _UNIT_DEPENDENCY_INVALID) {
d5099efc 2184 r = set_ensure_allocated(&other->dependencies[inverse_table[d]], NULL);
613b411c
LP
2185 if (r < 0)
2186 return r;
2187 }
2188
2189 if (add_reference) {
d5099efc 2190 r = set_ensure_allocated(&u->dependencies[UNIT_REFERENCES], NULL);
613b411c 2191 if (r < 0)
5de9682c
LP
2192 return r;
2193
d5099efc 2194 r = set_ensure_allocated(&other->dependencies[UNIT_REFERENCED_BY], NULL);
613b411c 2195 if (r < 0)
701cc384 2196 return r;
613b411c 2197 }
87f0e418 2198
613b411c
LP
2199 q = set_put(u->dependencies[d], other);
2200 if (q < 0)
701cc384 2201 return q;
87f0e418 2202
613b411c
LP
2203 if (inverse_table[d] != _UNIT_DEPENDENCY_INVALID && inverse_table[d] != d) {
2204 v = set_put(other->dependencies[inverse_table[d]], u);
2205 if (v < 0) {
5de9682c
LP
2206 r = v;
2207 goto fail;
2208 }
613b411c 2209 }
701cc384
LP
2210
2211 if (add_reference) {
613b411c
LP
2212 w = set_put(u->dependencies[UNIT_REFERENCES], other);
2213 if (w < 0) {
701cc384
LP
2214 r = w;
2215 goto fail;
2216 }
2217
613b411c
LP
2218 r = set_put(other->dependencies[UNIT_REFERENCED_BY], u);
2219 if (r < 0)
701cc384 2220 goto fail;
87f0e418
LP
2221 }
2222
c1e1601e 2223 unit_add_to_dbus_queue(u);
87f0e418 2224 return 0;
701cc384
LP
2225
2226fail:
2227 if (q > 0)
ac155bb8 2228 set_remove(u->dependencies[d], other);
701cc384
LP
2229
2230 if (v > 0)
ac155bb8 2231 set_remove(other->dependencies[inverse_table[d]], u);
701cc384
LP
2232
2233 if (w > 0)
ac155bb8 2234 set_remove(u->dependencies[UNIT_REFERENCES], other);
701cc384
LP
2235
2236 return r;
87f0e418 2237}
0301abf4 2238
2c966c03
LP
2239int unit_add_two_dependencies(Unit *u, UnitDependency d, UnitDependency e, Unit *other, bool add_reference) {
2240 int r;
2241
2242 assert(u);
2243
3f3cc397
LP
2244 r = unit_add_dependency(u, d, other, add_reference);
2245 if (r < 0)
2c966c03
LP
2246 return r;
2247
7410616c 2248 return unit_add_dependency(u, e, other, add_reference);
2c966c03
LP
2249}
2250
7410616c
LP
2251static int resolve_template(Unit *u, const char *name, const char*path, char **buf, const char **ret) {
2252 int r;
9e2f7c11
LP
2253
2254 assert(u);
2255 assert(name || path);
7410616c
LP
2256 assert(buf);
2257 assert(ret);
9e2f7c11
LP
2258
2259 if (!name)
2b6bf07d 2260 name = basename(path);
9e2f7c11 2261
7410616c
LP
2262 if (!unit_name_is_valid(name, UNIT_NAME_TEMPLATE)) {
2263 *buf = NULL;
2264 *ret = name;
2265 return 0;
9e2f7c11
LP
2266 }
2267
ac155bb8 2268 if (u->instance)
7410616c 2269 r = unit_name_replace_instance(name, u->instance, buf);
9e2f7c11 2270 else {
ae018d9b 2271 _cleanup_free_ char *i = NULL;
9e2f7c11 2272
7410616c
LP
2273 r = unit_name_to_prefix(u->id, &i);
2274 if (r < 0)
2275 return r;
9e2f7c11 2276
7410616c 2277 r = unit_name_replace_instance(name, i, buf);
9e2f7c11 2278 }
7410616c
LP
2279 if (r < 0)
2280 return r;
9e2f7c11 2281
7410616c
LP
2282 *ret = *buf;
2283 return 0;
9e2f7c11
LP
2284}
2285
701cc384 2286int unit_add_dependency_by_name(Unit *u, UnitDependency d, const char *name, const char *path, bool add_reference) {
7410616c 2287 _cleanup_free_ char *buf = NULL;
09b6b09f
LP
2288 Unit *other;
2289 int r;
2290
9e2f7c11
LP
2291 assert(u);
2292 assert(name || path);
09b6b09f 2293
7410616c
LP
2294 r = resolve_template(u, name, path, &buf, &name);
2295 if (r < 0)
2296 return r;
09b6b09f 2297
8afbb8e1
LP
2298 r = manager_load_unit(u->manager, name, path, NULL, &other);
2299 if (r < 0)
2300 return r;
9e2f7c11 2301
8afbb8e1 2302 return unit_add_dependency(u, d, other, add_reference);
09b6b09f
LP
2303}
2304
2c966c03 2305int unit_add_two_dependencies_by_name(Unit *u, UnitDependency d, UnitDependency e, const char *name, const char *path, bool add_reference) {
7410616c 2306 _cleanup_free_ char *buf = NULL;
2c966c03
LP
2307 Unit *other;
2308 int r;
2c966c03
LP
2309
2310 assert(u);
2311 assert(name || path);
2312
7410616c
LP
2313 r = resolve_template(u, name, path, &buf, &name);
2314 if (r < 0)
2315 return r;
2c966c03 2316
3f3cc397
LP
2317 r = manager_load_unit(u->manager, name, path, NULL, &other);
2318 if (r < 0)
68eda4bd 2319 return r;
2c966c03 2320
3f3cc397 2321 return unit_add_two_dependencies(u, d, e, other, add_reference);
2c966c03
LP
2322}
2323
0301abf4 2324int set_unit_path(const char *p) {
0301abf4 2325 /* This is mostly for debug purposes */
cbe46ead 2326 if (setenv("SYSTEMD_UNIT_PATH", p, 1) < 0)
26d04f86 2327 return -errno;
0301abf4
LP
2328
2329 return 0;
2330}
88066b3a 2331
ea430986 2332char *unit_dbus_path(Unit *u) {
ea430986
LP
2333 assert(u);
2334
ac155bb8 2335 if (!u->id)
04ade7d2
LP
2336 return NULL;
2337
48899192 2338 return unit_dbus_path_from_name(u->id);
ea430986
LP
2339}
2340
d79200e2
LP
2341int unit_set_slice(Unit *u, Unit *slice) {
2342 assert(u);
2343 assert(slice);
2344
2345 /* Sets the unit slice if it has not been set before. Is extra
2346 * careful, to only allow this for units that actually have a
2347 * cgroup context. Also, we don't allow to set this for slices
2348 * (since the parent slice is derived from the name). Make
2349 * sure the unit we set is actually a slice. */
2350
2351 if (!UNIT_HAS_CGROUP_CONTEXT(u))
2352 return -EOPNOTSUPP;
2353
2354 if (u->type == UNIT_SLICE)
2355 return -EINVAL;
2356
102ef982
LP
2357 if (unit_active_state(u) != UNIT_INACTIVE)
2358 return -EBUSY;
2359
d79200e2
LP
2360 if (slice->type != UNIT_SLICE)
2361 return -EINVAL;
2362
efdb0237
LP
2363 if (unit_has_name(u, SPECIAL_INIT_SCOPE) &&
2364 !unit_has_name(slice, SPECIAL_ROOT_SLICE))
2365 return -EPERM;
2366
d79200e2
LP
2367 if (UNIT_DEREF(u->slice) == slice)
2368 return 0;
2369
2370 if (UNIT_ISSET(u->slice))
2371 return -EBUSY;
2372
2373 unit_ref_set(&u->slice, slice);
2374 return 1;
2375}
2376
2377int unit_set_default_slice(Unit *u) {
a8833944
LP
2378 _cleanup_free_ char *b = NULL;
2379 const char *slice_name;
a016b922
LP
2380 Unit *slice;
2381 int r;
2382
2383 assert(u);
2384
9444b1f2 2385 if (UNIT_ISSET(u->slice))
a016b922
LP
2386 return 0;
2387
a8833944
LP
2388 if (u->instance) {
2389 _cleanup_free_ char *prefix = NULL, *escaped = NULL;
68eda4bd 2390
a8833944
LP
2391 /* Implicitly place all instantiated units in their
2392 * own per-template slice */
2393
7410616c
LP
2394 r = unit_name_to_prefix(u->id, &prefix);
2395 if (r < 0)
2396 return r;
a8833944
LP
2397
2398 /* The prefix is already escaped, but it might include
2399 * "-" which has a special meaning for slice units,
2400 * hence escape it here extra. */
7410616c 2401 escaped = unit_name_escape(prefix);
a8833944
LP
2402 if (!escaped)
2403 return -ENOMEM;
2404
b2c23da8 2405 if (u->manager->running_as == MANAGER_SYSTEM)
a8833944
LP
2406 b = strjoin("system-", escaped, ".slice", NULL);
2407 else
2408 b = strappend(escaped, ".slice");
2409 if (!b)
2410 return -ENOMEM;
2411
2412 slice_name = b;
2413 } else
2414 slice_name =
efdb0237 2415 u->manager->running_as == MANAGER_SYSTEM && !unit_has_name(u, SPECIAL_INIT_SCOPE)
a8833944
LP
2416 ? SPECIAL_SYSTEM_SLICE
2417 : SPECIAL_ROOT_SLICE;
2418
2419 r = manager_load_unit(u->manager, slice_name, NULL, NULL, &slice);
a016b922
LP
2420 if (r < 0)
2421 return r;
2422
d79200e2 2423 return unit_set_slice(u, slice);
a016b922
LP
2424}
2425
9444b1f2
LP
2426const char *unit_slice_name(Unit *u) {
2427 assert(u);
2428
2429 if (!UNIT_ISSET(u->slice))
2430 return NULL;
2431
2432 return UNIT_DEREF(u->slice)->id;
2433}
2434
f6ff8c29 2435int unit_load_related_unit(Unit *u, const char *type, Unit **_found) {
78edb35a 2436 _cleanup_free_ char *t = NULL;
f6ff8c29
LP
2437 int r;
2438
2439 assert(u);
2440 assert(type);
2441 assert(_found);
2442
7410616c
LP
2443 r = unit_name_change_suffix(u->id, type, &t);
2444 if (r < 0)
2445 return r;
2446 if (unit_has_name(u, t))
2447 return -EINVAL;
f6ff8c29 2448
ac155bb8 2449 r = manager_load_unit(u->manager, t, NULL, NULL, _found);
9e2f7c11 2450 assert(r < 0 || *_found != u);
f6ff8c29
LP
2451 return r;
2452}
2453
bbc29086
DM
2454static int signal_name_owner_changed(sd_bus_message *message, void *userdata, sd_bus_error *error) {
2455 const char *name, *old_owner, *new_owner;
2456 Unit *u = userdata;
2457 int r;
2458
2459 assert(message);
2460 assert(u);
2461
2462 r = sd_bus_message_read(message, "sss", &name, &old_owner, &new_owner);
2463 if (r < 0) {
2464 bus_log_parse_error(r);
2465 return 0;
2466 }
2467
2468 if (UNIT_VTABLE(u)->bus_name_owner_change)
2469 UNIT_VTABLE(u)->bus_name_owner_change(u, name, old_owner, new_owner);
2470
2471 return 0;
2472}
2473
9806e87d
LP
2474int unit_install_bus_match(Unit *u, sd_bus *bus, const char *name) {
2475 const char *match;
bbc29086 2476
9806e87d
LP
2477 assert(u);
2478 assert(bus);
2479 assert(name);
bbc29086
DM
2480
2481 if (u->match_bus_slot)
2482 return -EBUSY;
2483
9806e87d 2484 match = strjoina("type='signal',"
bbc29086
DM
2485 "sender='org.freedesktop.DBus',"
2486 "path='/org/freedesktop/DBus',"
2487 "interface='org.freedesktop.DBus',"
2488 "member='NameOwnerChanged',"
9806e87d 2489 "arg0='", name, "'",
bbc29086 2490 NULL);
bbc29086
DM
2491
2492 return sd_bus_add_match(bus, &u->match_bus_slot, match, signal_name_owner_changed, u);
2493}
2494
05e343b7 2495int unit_watch_bus_name(Unit *u, const char *name) {
bbc29086
DM
2496 int r;
2497
05e343b7
LP
2498 assert(u);
2499 assert(name);
2500
2501 /* Watch a specific name on the bus. We only support one unit
2502 * watching each name for now. */
2503
bbc29086
DM
2504 if (u->manager->api_bus) {
2505 /* If the bus is already available, install the match directly.
2506 * Otherwise, just put the name in the list. bus_setup_api() will take care later. */
9806e87d 2507 r = unit_install_bus_match(u, u->manager->api_bus, name);
bbc29086 2508 if (r < 0)
8ea823b6 2509 return log_warning_errno(r, "Failed to subscribe to NameOwnerChanged signal for '%s': %m", name);
bbc29086
DM
2510 }
2511
2512 r = hashmap_put(u->manager->watch_bus, name, u);
2513 if (r < 0) {
2514 u->match_bus_slot = sd_bus_slot_unref(u->match_bus_slot);
2515 return log_warning_errno(r, "Failed to put bus name to hashmap: %m");
2516 }
2517
2518 return 0;
05e343b7
LP
2519}
2520
2521void unit_unwatch_bus_name(Unit *u, const char *name) {
2522 assert(u);
2523 assert(name);
2524
ac155bb8 2525 hashmap_remove_value(u->manager->watch_bus, name, u);
bbc29086 2526 u->match_bus_slot = sd_bus_slot_unref(u->match_bus_slot);
05e343b7
LP
2527}
2528
a16e1123
LP
2529bool unit_can_serialize(Unit *u) {
2530 assert(u);
2531
2532 return UNIT_VTABLE(u)->serialize && UNIT_VTABLE(u)->deserialize_item;
2533}
2534
6b78f9b4 2535int unit_serialize(Unit *u, FILE *f, FDSet *fds, bool serialize_jobs) {
a16e1123
LP
2536 int r;
2537
2538 assert(u);
2539 assert(f);
2540 assert(fds);
2541
9bdb98c5
LP
2542 if (unit_can_serialize(u)) {
2543 ExecRuntime *rt;
a16e1123 2544
9bdb98c5 2545 r = UNIT_VTABLE(u)->serialize(u, f, fds);
613b411c
LP
2546 if (r < 0)
2547 return r;
9bdb98c5
LP
2548
2549 rt = unit_get_exec_runtime(u);
2550 if (rt) {
f2341e0a 2551 r = exec_runtime_serialize(u, rt, f, fds);
9bdb98c5
LP
2552 if (r < 0)
2553 return r;
2554 }
e0209d83
MS
2555 }
2556
a483fb59
LP
2557 dual_timestamp_serialize(f, "state-change-timestamp", &u->state_change_timestamp);
2558
ac155bb8
MS
2559 dual_timestamp_serialize(f, "inactive-exit-timestamp", &u->inactive_exit_timestamp);
2560 dual_timestamp_serialize(f, "active-enter-timestamp", &u->active_enter_timestamp);
2561 dual_timestamp_serialize(f, "active-exit-timestamp", &u->active_exit_timestamp);
2562 dual_timestamp_serialize(f, "inactive-enter-timestamp", &u->inactive_enter_timestamp);
a483fb59 2563
ac155bb8 2564 dual_timestamp_serialize(f, "condition-timestamp", &u->condition_timestamp);
59fccdc5 2565 dual_timestamp_serialize(f, "assert-timestamp", &u->assert_timestamp);
2791a8f8 2566
ac155bb8
MS
2567 if (dual_timestamp_is_set(&u->condition_timestamp))
2568 unit_serialize_item(u, f, "condition-result", yes_no(u->condition_result));
10717a1a 2569
59fccdc5
LP
2570 if (dual_timestamp_is_set(&u->assert_timestamp))
2571 unit_serialize_item(u, f, "assert-result", yes_no(u->assert_result));
2572
c2756a68 2573 unit_serialize_item(u, f, "transient", yes_no(u->transient));
5ad096b3 2574 unit_serialize_item_format(u, f, "cpuacct-usage-base", "%" PRIu64, u->cpuacct_usage_base);
c2756a68
LP
2575
2576 if (u->cgroup_path)
2577 unit_serialize_item(u, f, "cgroup", u->cgroup_path);
de1d4f9b 2578 unit_serialize_item(u, f, "cgroup-realized", yes_no(u->cgroup_realized));
c2756a68 2579
32ee7d33
DM
2580 if (u->cgroup_netclass_id)
2581 unit_serialize_item_format(u, f, "netclass-id", "%" PRIu32, u->cgroup_netclass_id);
2582
613b411c
LP
2583 if (serialize_jobs) {
2584 if (u->job) {
2585 fprintf(f, "job\n");
2586 job_serialize(u->job, f, fds);
2587 }
2588
2589 if (u->nop_job) {
2590 fprintf(f, "job\n");
2591 job_serialize(u->nop_job, f, fds);
2592 }
2593 }
2594
a16e1123
LP
2595 /* End marker */
2596 fputc('\n', f);
2597 return 0;
2598}
2599
a34ceba6
LP
2600int unit_serialize_item(Unit *u, FILE *f, const char *key, const char *value) {
2601 assert(u);
2602 assert(f);
2603 assert(key);
2604
2605 if (!value)
2606 return 0;
2607
2608 fputs(key, f);
2609 fputc('=', f);
2610 fputs(value, f);
2611 fputc('\n', f);
2612
2613 return 1;
2614}
2615
2616int unit_serialize_item_escaped(Unit *u, FILE *f, const char *key, const char *value) {
2617 _cleanup_free_ char *c = NULL;
2618
2619 assert(u);
2620 assert(f);
2621 assert(key);
2622
2623 if (!value)
2624 return 0;
2625
2626 c = cescape(value);
2627 if (!c)
2628 return -ENOMEM;
2629
2630 fputs(key, f);
2631 fputc('=', f);
2632 fputs(c, f);
2633 fputc('\n', f);
2634
2635 return 1;
2636}
2637
2638int unit_serialize_item_fd(Unit *u, FILE *f, FDSet *fds, const char *key, int fd) {
2639 int copy;
2640
2641 assert(u);
2642 assert(f);
2643 assert(key);
2644
2645 if (fd < 0)
2646 return 0;
2647
2648 copy = fdset_put_dup(fds, fd);
2649 if (copy < 0)
2650 return copy;
2651
2652 fprintf(f, "%s=%i\n", key, copy);
2653 return 1;
2654}
2655
a16e1123
LP
2656void unit_serialize_item_format(Unit *u, FILE *f, const char *key, const char *format, ...) {
2657 va_list ap;
2658
2659 assert(u);
2660 assert(f);
2661 assert(key);
2662 assert(format);
2663
2664 fputs(key, f);
2665 fputc('=', f);
2666
2667 va_start(ap, format);
2668 vfprintf(f, format, ap);
2669 va_end(ap);
2670
2671 fputc('\n', f);
2672}
2673
a16e1123 2674int unit_deserialize(Unit *u, FILE *f, FDSet *fds) {
28b99ccd 2675 ExecRuntime **rt = NULL;
9bdb98c5 2676 size_t offset;
a16e1123
LP
2677 int r;
2678
2679 assert(u);
2680 assert(f);
2681 assert(fds);
2682
613b411c
LP
2683 offset = UNIT_VTABLE(u)->exec_runtime_offset;
2684 if (offset > 0)
2685 rt = (ExecRuntime**) ((uint8_t*) u + offset);
2686
a16e1123 2687 for (;;) {
20c03b7b 2688 char line[LINE_MAX], *l, *v;
a16e1123
LP
2689 size_t k;
2690
2691 if (!fgets(line, sizeof(line), f)) {
2692 if (feof(f))
2693 return 0;
2694 return -errno;
2695 }
2696
10f8e83c 2697 char_array_0(line);
a16e1123
LP
2698 l = strstrip(line);
2699
2700 /* End marker */
e911de99 2701 if (isempty(l))
a483fb59 2702 break;
a16e1123
LP
2703
2704 k = strcspn(l, "=");
2705
2706 if (l[k] == '=') {
2707 l[k] = 0;
2708 v = l+k+1;
2709 } else
2710 v = l+k;
2711
cca098b0 2712 if (streq(l, "job")) {
39a18c60
MS
2713 if (v[0] == '\0') {
2714 /* new-style serialized job */
9c3349e2
LP
2715 Job *j;
2716
2717 j = job_new_raw(u);
39a18c60 2718 if (!j)
e911de99 2719 return log_oom();
39a18c60
MS
2720
2721 r = job_deserialize(j, f, fds);
2722 if (r < 0) {
2723 job_free(j);
2724 return r;
2725 }
cca098b0 2726
39a18c60
MS
2727 r = hashmap_put(u->manager->jobs, UINT32_TO_PTR(j->id), j);
2728 if (r < 0) {
2729 job_free(j);
2730 return r;
2731 }
e0209d83
MS
2732
2733 r = job_install_deserialized(j);
2734 if (r < 0) {
2735 hashmap_remove(u->manager->jobs, UINT32_TO_PTR(j->id));
2736 job_free(j);
2737 return r;
2738 }
ed10fa8c
LP
2739 } else /* legacy for pre-44 */
2740 log_unit_warning(u, "Update from too old systemd versions are unsupported, cannot deserialize job: %s", v);
cca098b0 2741 continue;
a483fb59
LP
2742 } else if (streq(l, "state-change-timestamp")) {
2743 dual_timestamp_deserialize(v, &u->state_change_timestamp);
2744 continue;
8aaf019b 2745 } else if (streq(l, "inactive-exit-timestamp")) {
ac155bb8 2746 dual_timestamp_deserialize(v, &u->inactive_exit_timestamp);
8aaf019b
LP
2747 continue;
2748 } else if (streq(l, "active-enter-timestamp")) {
ac155bb8 2749 dual_timestamp_deserialize(v, &u->active_enter_timestamp);
8aaf019b
LP
2750 continue;
2751 } else if (streq(l, "active-exit-timestamp")) {
ac155bb8 2752 dual_timestamp_deserialize(v, &u->active_exit_timestamp);
8aaf019b
LP
2753 continue;
2754 } else if (streq(l, "inactive-enter-timestamp")) {
ac155bb8 2755 dual_timestamp_deserialize(v, &u->inactive_enter_timestamp);
8aaf019b 2756 continue;
2791a8f8 2757 } else if (streq(l, "condition-timestamp")) {
ac155bb8 2758 dual_timestamp_deserialize(v, &u->condition_timestamp);
2791a8f8 2759 continue;
59fccdc5
LP
2760 } else if (streq(l, "assert-timestamp")) {
2761 dual_timestamp_deserialize(v, &u->assert_timestamp);
2762 continue;
2791a8f8 2763 } else if (streq(l, "condition-result")) {
2791a8f8 2764
e911de99
LP
2765 r = parse_boolean(v);
2766 if (r < 0)
f2341e0a 2767 log_unit_debug(u, "Failed to parse condition result value %s, ignoring.", v);
2791a8f8 2768 else
e911de99 2769 u->condition_result = r;
efbac6d2
LP
2770
2771 continue;
c2756a68 2772
59fccdc5 2773 } else if (streq(l, "assert-result")) {
59fccdc5 2774
e911de99
LP
2775 r = parse_boolean(v);
2776 if (r < 0)
f2341e0a 2777 log_unit_debug(u, "Failed to parse assert result value %s, ignoring.", v);
59fccdc5 2778 else
e911de99 2779 u->assert_result = r;
59fccdc5
LP
2780
2781 continue;
2782
c2756a68 2783 } else if (streq(l, "transient")) {
c2756a68 2784
e911de99
LP
2785 r = parse_boolean(v);
2786 if (r < 0)
f2341e0a 2787 log_unit_debug(u, "Failed to parse transient bool %s, ignoring.", v);
c2756a68 2788 else
e911de99 2789 u->transient = r;
c2756a68
LP
2790
2791 continue;
e911de99 2792
5ad096b3
LP
2793 } else if (streq(l, "cpuacct-usage-base")) {
2794
2795 r = safe_atou64(v, &u->cpuacct_usage_base);
2796 if (r < 0)
f2341e0a 2797 log_unit_debug(u, "Failed to parse CPU usage %s, ignoring.", v);
5ad096b3 2798
0f908397 2799 continue;
4e595329 2800
e911de99 2801 } else if (streq(l, "cgroup")) {
72673e86 2802
e911de99
LP
2803 r = unit_set_cgroup_path(u, v);
2804 if (r < 0)
f2341e0a 2805 log_unit_debug_errno(u, r, "Failed to set cgroup path %s, ignoring: %m", v);
4e595329 2806
efdb0237
LP
2807 (void) unit_watch_cgroup(u);
2808
de1d4f9b
WF
2809 continue;
2810 } else if (streq(l, "cgroup-realized")) {
2811 int b;
2812
2813 b = parse_boolean(v);
2814 if (b < 0)
2815 log_unit_debug(u, "Failed to parse cgroup-realized bool %s, ignoring.", v);
2816 else
2817 u->cgroup_realized = b;
2818
32ee7d33
DM
2819 continue;
2820 } else if (streq(l, "netclass-id")) {
2821 r = safe_atou32(v, &u->cgroup_netclass_id);
2822 if (r < 0)
2823 log_unit_debug(u, "Failed to parse netclass ID %s, ignoring.", v);
2824 else {
2825 r = unit_add_to_netclass_cgroup(u);
2826 if (r < 0)
2827 log_unit_debug_errno(u, r, "Failed to add unit to netclass cgroup, ignoring: %m");
2828 }
2829
c2756a68 2830 continue;
8aaf019b 2831 }
cca098b0 2832
9bdb98c5
LP
2833 if (unit_can_serialize(u)) {
2834 if (rt) {
f2341e0a 2835 r = exec_runtime_deserialize_item(u, rt, l, v, fds);
e911de99 2836 if (r < 0) {
f2341e0a 2837 log_unit_warning(u, "Failed to deserialize runtime parameter '%s', ignoring.", l);
e911de99
LP
2838 continue;
2839 }
2840
2841 /* Returns positive if key was handled by the call */
9bdb98c5
LP
2842 if (r > 0)
2843 continue;
2844 }
2845
2846 r = UNIT_VTABLE(u)->deserialize_item(u, l, v, fds);
613b411c 2847 if (r < 0)
f2341e0a 2848 log_unit_warning(u, "Failed to deserialize unit parameter '%s', ignoring.", l);
613b411c 2849 }
a16e1123 2850 }
a483fb59
LP
2851
2852 /* Versions before 228 did not carry a state change timestamp. In this case, take the current time. This is
2853 * useful, so that timeouts based on this timestamp don't trigger too early, and is in-line with the logic from
2854 * before 228 where the base for timeouts was not peristet across reboots. */
2855
2856 if (!dual_timestamp_is_set(&u->state_change_timestamp))
2857 dual_timestamp_get(&u->state_change_timestamp);
2858
2859 return 0;
a16e1123
LP
2860}
2861
9d06297e 2862int unit_add_node_link(Unit *u, const char *what, bool wants, UnitDependency dep) {
6e2ef85b 2863 Unit *device;
68eda4bd 2864 _cleanup_free_ char *e = NULL;
6e2ef85b
LP
2865 int r;
2866
2867 assert(u);
2868
6e2ef85b 2869 /* Adds in links to the device node that this unit is based on */
47bc12e1
LP
2870 if (isempty(what))
2871 return 0;
6e2ef85b 2872
8407a5d0 2873 if (!is_device_path(what))
6e2ef85b
LP
2874 return 0;
2875
47bc12e1
LP
2876 /* When device units aren't supported (such as in a
2877 * container), don't create dependencies on them. */
1c2e9646 2878 if (!unit_type_supported(UNIT_DEVICE))
47bc12e1
LP
2879 return 0;
2880
7410616c
LP
2881 r = unit_name_from_path(what, ".device", &e);
2882 if (r < 0)
2883 return r;
6e2ef85b 2884
ac155bb8 2885 r = manager_load_unit(u->manager, e, NULL, NULL, &device);
6e2ef85b
LP
2886 if (r < 0)
2887 return r;
2888
9d06297e
HH
2889 r = unit_add_two_dependencies(u, UNIT_AFTER,
2890 u->manager->running_as == MANAGER_SYSTEM ? dep : UNIT_WANTS,
2891 device, true);
faa368e3 2892 if (r < 0)
6e2ef85b
LP
2893 return r;
2894
faa368e3
LP
2895 if (wants) {
2896 r = unit_add_dependency(device, UNIT_WANTS, u, false);
2897 if (r < 0)
6e2ef85b 2898 return r;
faa368e3 2899 }
6e2ef85b
LP
2900
2901 return 0;
2902}
a16e1123 2903
be847e82 2904int unit_coldplug(Unit *u) {
5a6158b6 2905 int r = 0, q = 0;
cca098b0
LP
2906
2907 assert(u);
2908
f78f265f
LP
2909 /* Make sure we don't enter a loop, when coldplugging
2910 * recursively. */
2911 if (u->coldplugged)
2912 return 0;
2913
2914 u->coldplugged = true;
2915
5a6158b6 2916 if (UNIT_VTABLE(u)->coldplug)
f78f265f 2917 r = UNIT_VTABLE(u)->coldplug(u);
cca098b0 2918
5a6158b6
LP
2919 if (u->job)
2920 q = job_coldplug(u->job);
2921
2922 if (r < 0)
2923 return r;
2924 if (q < 0)
2925 return q;
cca098b0
LP
2926
2927 return 0;
2928}
2929
45fb0699 2930bool unit_need_daemon_reload(Unit *u) {
ae7a7182
OS
2931 _cleanup_strv_free_ char **t = NULL;
2932 char **path;
1b64d026 2933 struct stat st;
ae7a7182 2934 unsigned loaded_cnt, current_cnt;
1b64d026 2935
45fb0699
LP
2936 assert(u);
2937
ac155bb8 2938 if (u->fragment_path) {
5f4b19f4 2939 zero(st);
ac155bb8 2940 if (stat(u->fragment_path, &st) < 0)
5f4b19f4
LP
2941 /* What, cannot access this anymore? */
2942 return true;
45fb0699 2943
ac155bb8
MS
2944 if (u->fragment_mtime > 0 &&
2945 timespec_load(&st.st_mtim) != u->fragment_mtime)
5f4b19f4
LP
2946 return true;
2947 }
2948
1b64d026
LP
2949 if (u->source_path) {
2950 zero(st);
2951 if (stat(u->source_path, &st) < 0)
2952 return true;
2953
2954 if (u->source_mtime > 0 &&
2955 timespec_load(&st.st_mtim) != u->source_mtime)
2956 return true;
2957 }
5f4b19f4 2958
1a7f1b38 2959 (void) unit_find_dropin_paths(u, &t);
ae7a7182
OS
2960 loaded_cnt = strv_length(t);
2961 current_cnt = strv_length(u->dropin_paths);
2962
2963 if (loaded_cnt == current_cnt) {
2964 if (loaded_cnt == 0)
2965 return false;
2966
2967 if (strv_overlap(u->dropin_paths, t)) {
2968 STRV_FOREACH(path, u->dropin_paths) {
2969 zero(st);
2970 if (stat(*path, &st) < 0)
2971 return true;
2972
2973 if (u->dropin_mtime > 0 &&
2974 timespec_load(&st.st_mtim) > u->dropin_mtime)
2975 return true;
2976 }
2977
2978 return false;
2979 } else
2980 return true;
2981 } else
2982 return true;
45fb0699
LP
2983}
2984
fdf20a31 2985void unit_reset_failed(Unit *u) {
5632e374
LP
2986 assert(u);
2987
fdf20a31
MM
2988 if (UNIT_VTABLE(u)->reset_failed)
2989 UNIT_VTABLE(u)->reset_failed(u);
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}