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