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