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