1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
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.
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.
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/>.
25 #include <sys/epoll.h>
26 #include <sys/timerfd.h>
36 #include "load-fragment.h"
37 #include "load-dropin.h"
39 #include "unit-name.h"
40 #include "specifier.h"
41 #include "dbus-unit.h"
43 #include "cgroup-util.h"
45 #include "cgroup-attr.h"
47 const UnitVTable * const unit_vtable[_UNIT_TYPE_MAX] = {
48 [UNIT_SERVICE] = &service_vtable,
49 [UNIT_TIMER] = &timer_vtable,
50 [UNIT_SOCKET] = &socket_vtable,
51 [UNIT_TARGET] = &target_vtable,
52 [UNIT_DEVICE] = &device_vtable,
53 [UNIT_MOUNT] = &mount_vtable,
54 [UNIT_AUTOMOUNT] = &automount_vtable,
55 [UNIT_SNAPSHOT] = &snapshot_vtable,
56 [UNIT_SWAP] = &swap_vtable,
57 [UNIT_PATH] = &path_vtable
60 Unit *unit_new(Manager *m, size_t size) {
64 assert(size >= sizeof(Unit));
70 u->names = set_new(string_hash_func, string_compare_func);
77 u->type = _UNIT_TYPE_INVALID;
78 u->deserialized_job = _JOB_TYPE_INVALID;
79 u->default_dependencies = true;
80 u->unit_file_state = _UNIT_FILE_STATE_INVALID;
85 bool unit_has_name(Unit *u, const char *name) {
89 return !!set_get(u->names, (char*) name);
92 int unit_add_name(Unit *u, const char *text) {
100 if (unit_name_is_template(text)) {
104 s = unit_name_replace_instance(text, u->instance);
111 if (!unit_name_is_valid(s, false)) {
116 assert_se((t = unit_name_to_type(s)) >= 0);
118 if (u->type != _UNIT_TYPE_INVALID && t != u->type) {
123 if ((r = unit_name_to_instance(s, &i)) < 0)
126 if (i && unit_vtable[t]->no_instances) {
131 /* Ensure that this unit is either instanced or not instanced,
133 if (u->type != _UNIT_TYPE_INVALID && !u->instance != !i) {
138 if (unit_vtable[t]->no_alias &&
139 !set_isempty(u->names) &&
140 !set_get(u->names, s)) {
145 if (hashmap_size(u->manager->units) >= MANAGER_MAX_NAMES) {
150 if ((r = set_put(u->names, s)) < 0) {
156 if ((r = hashmap_put(u->manager->units, s, u)) < 0) {
157 set_remove(u->names, s);
161 if (u->type == _UNIT_TYPE_INVALID) {
167 LIST_PREPEND(Unit, units_by_type, u->manager->units_by_type[t], u);
169 if (UNIT_VTABLE(u)->init)
170 UNIT_VTABLE(u)->init(u);
174 unit_add_to_dbus_queue(u);
184 int unit_choose_id(Unit *u, const char *name) {
185 char *s, *t = NULL, *i;
191 if (unit_name_is_template(name)) {
196 if (!(t = unit_name_replace_instance(name, u->instance)))
202 /* Selects one of the names of this unit as the id */
203 s = set_get(u->names, (char*) name);
209 if ((r = unit_name_to_instance(s, &i)) < 0)
217 unit_add_to_dbus_queue(u);
222 int unit_set_description(Unit *u, const char *description) {
227 if (!(s = strdup(description)))
230 free(u->description);
233 unit_add_to_dbus_queue(u);
237 bool unit_check_gc(Unit *u) {
240 if (u->load_state == UNIT_STUB)
243 if (UNIT_VTABLE(u)->no_gc)
255 if (unit_active_state(u) != UNIT_INACTIVE)
258 if (UNIT_VTABLE(u)->check_gc)
259 if (UNIT_VTABLE(u)->check_gc(u))
265 void unit_add_to_load_queue(Unit *u) {
267 assert(u->type != _UNIT_TYPE_INVALID);
269 if (u->load_state != UNIT_STUB || u->in_load_queue)
272 LIST_PREPEND(Unit, load_queue, u->manager->load_queue, u);
273 u->in_load_queue = true;
276 void unit_add_to_cleanup_queue(Unit *u) {
279 if (u->in_cleanup_queue)
282 LIST_PREPEND(Unit, cleanup_queue, u->manager->cleanup_queue, u);
283 u->in_cleanup_queue = true;
286 void unit_add_to_gc_queue(Unit *u) {
289 if (u->in_gc_queue || u->in_cleanup_queue)
292 if (unit_check_gc(u))
295 LIST_PREPEND(Unit, gc_queue, u->manager->gc_queue, u);
296 u->in_gc_queue = true;
298 u->manager->n_in_gc_queue ++;
300 if (u->manager->gc_queue_timestamp <= 0)
301 u->manager->gc_queue_timestamp = now(CLOCK_MONOTONIC);
304 void unit_add_to_dbus_queue(Unit *u) {
306 assert(u->type != _UNIT_TYPE_INVALID);
308 if (u->load_state == UNIT_STUB || u->in_dbus_queue)
311 /* Shortcut things if nobody cares */
312 if (!bus_has_subscriber(u->manager)) {
313 u->sent_dbus_new_signal = true;
317 LIST_PREPEND(Unit, dbus_queue, u->manager->dbus_unit_queue, u);
318 u->in_dbus_queue = true;
321 static void bidi_set_free(Unit *u, Set *s) {
327 /* Frees the set and makes sure we are dropped from the
328 * inverse pointers */
330 SET_FOREACH(other, s, i) {
333 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
334 set_remove(other->dependencies[d], u);
336 unit_add_to_gc_queue(other);
342 void unit_free(Unit *u) {
349 bus_unit_send_removed_signal(u);
351 if (u->load_state != UNIT_STUB)
352 if (UNIT_VTABLE(u)->done)
353 UNIT_VTABLE(u)->done(u);
355 SET_FOREACH(t, u->names, i)
356 hashmap_remove_value(u->manager->units, t, u);
370 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
371 bidi_set_free(u, u->dependencies[d]);
373 if (u->requires_mounts_for) {
374 LIST_REMOVE(Unit, has_requires_mounts_for, u->manager->has_requires_mounts_for, u);
375 strv_free(u->requires_mounts_for);
378 if (u->type != _UNIT_TYPE_INVALID)
379 LIST_REMOVE(Unit, units_by_type, u->manager->units_by_type[u->type], u);
381 if (u->in_load_queue)
382 LIST_REMOVE(Unit, load_queue, u->manager->load_queue, u);
384 if (u->in_dbus_queue)
385 LIST_REMOVE(Unit, dbus_queue, u->manager->dbus_unit_queue, u);
387 if (u->in_cleanup_queue)
388 LIST_REMOVE(Unit, cleanup_queue, u->manager->cleanup_queue, u);
390 if (u->in_gc_queue) {
391 LIST_REMOVE(Unit, gc_queue, u->manager->gc_queue, u);
392 u->manager->n_in_gc_queue--;
395 cgroup_bonding_free_list(u->cgroup_bondings, u->manager->n_reloading <= 0);
396 cgroup_attribute_free_list(u->cgroup_attributes);
398 free(u->description);
399 free(u->fragment_path);
402 set_free_free(u->names);
404 condition_free_list(u->conditions);
407 unit_ref_unset(u->refs);
412 UnitActiveState unit_active_state(Unit *u) {
415 if (u->load_state == UNIT_MERGED)
416 return unit_active_state(unit_follow_merge(u));
418 /* After a reload it might happen that a unit is not correctly
419 * loaded but still has a process around. That's why we won't
420 * shortcut failed loading to UNIT_INACTIVE_FAILED. */
422 return UNIT_VTABLE(u)->active_state(u);
425 const char* unit_sub_state_to_string(Unit *u) {
428 return UNIT_VTABLE(u)->sub_state_to_string(u);
431 static void complete_move(Set **s, Set **other) {
439 set_move(*s, *other);
446 static void merge_names(Unit *u, Unit *other) {
453 complete_move(&u->names, &other->names);
455 set_free_free(other->names);
459 SET_FOREACH(t, u->names, i)
460 assert_se(hashmap_replace(u->manager->units, t, u) == 0);
463 static void merge_dependencies(Unit *u, Unit *other, UnitDependency d) {
470 assert(d < _UNIT_DEPENDENCY_MAX);
472 /* Fix backwards pointers */
473 SET_FOREACH(back, other->dependencies[d], i) {
476 for (k = 0; k < _UNIT_DEPENDENCY_MAX; k++)
477 if ((r = set_remove_and_put(back->dependencies[k], other, u)) < 0) {
480 set_remove(back->dependencies[k], other);
482 assert(r == -ENOENT);
486 complete_move(&u->dependencies[d], &other->dependencies[d]);
488 set_free(other->dependencies[d]);
489 other->dependencies[d] = NULL;
492 int unit_merge(Unit *u, Unit *other) {
497 assert(u->manager == other->manager);
498 assert(u->type != _UNIT_TYPE_INVALID);
500 other = unit_follow_merge(other);
505 if (u->type != other->type)
508 if (!u->instance != !other->instance)
511 if (other->load_state != UNIT_STUB &&
512 other->load_state != UNIT_ERROR)
521 if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other)))
525 merge_names(u, other);
527 /* Redirect all references */
529 unit_ref_set(other->refs, u);
531 /* Merge dependencies */
532 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
533 merge_dependencies(u, other, d);
535 other->load_state = UNIT_MERGED;
536 other->merged_into = u;
538 /* If there is still some data attached to the other node, we
539 * don't need it anymore, and can free it. */
540 if (other->load_state != UNIT_STUB)
541 if (UNIT_VTABLE(other)->done)
542 UNIT_VTABLE(other)->done(other);
544 unit_add_to_dbus_queue(u);
545 unit_add_to_cleanup_queue(other);
550 int unit_merge_by_name(Unit *u, const char *name) {
558 if (unit_name_is_template(name)) {
562 if (!(s = unit_name_replace_instance(name, u->instance)))
568 if (!(other = manager_get_unit(u->manager, name)))
569 r = unit_add_name(u, name);
571 r = unit_merge(u, other);
577 Unit* unit_follow_merge(Unit *u) {
580 while (u->load_state == UNIT_MERGED)
581 assert_se(u = u->merged_into);
586 int unit_add_exec_dependencies(Unit *u, ExecContext *c) {
592 if (c->std_output != EXEC_OUTPUT_KMSG &&
593 c->std_output != EXEC_OUTPUT_SYSLOG &&
594 c->std_output != EXEC_OUTPUT_JOURNAL &&
595 c->std_output != EXEC_OUTPUT_KMSG_AND_CONSOLE &&
596 c->std_output != EXEC_OUTPUT_SYSLOG_AND_CONSOLE &&
597 c->std_output != EXEC_OUTPUT_JOURNAL_AND_CONSOLE &&
598 c->std_error != EXEC_OUTPUT_KMSG &&
599 c->std_error != EXEC_OUTPUT_SYSLOG &&
600 c->std_error != EXEC_OUTPUT_JOURNAL &&
601 c->std_error != EXEC_OUTPUT_KMSG_AND_CONSOLE &&
602 c->std_error != EXEC_OUTPUT_JOURNAL_AND_CONSOLE &&
603 c->std_error != EXEC_OUTPUT_SYSLOG_AND_CONSOLE)
606 /* If syslog or kernel logging is requested, make sure our own
607 * logging daemon is run first. */
609 if (u->manager->running_as == MANAGER_SYSTEM)
610 if ((r = unit_add_two_dependencies_by_name(u, UNIT_REQUIRES, UNIT_AFTER, SPECIAL_JOURNALD_SOCKET, NULL, true)) < 0)
616 const char *unit_description(Unit *u) {
620 return u->description;
625 void unit_dump(Unit *u, FILE *f, const char *prefix) {
632 timestamp1[FORMAT_TIMESTAMP_MAX],
633 timestamp2[FORMAT_TIMESTAMP_MAX],
634 timestamp3[FORMAT_TIMESTAMP_MAX],
635 timestamp4[FORMAT_TIMESTAMP_MAX],
636 timespan[FORMAT_TIMESPAN_MAX];
640 assert(u->type >= 0);
644 p2 = strappend(prefix, "\t");
645 prefix2 = p2 ? p2 : prefix;
649 "%s\tDescription: %s\n"
651 "%s\tUnit Load State: %s\n"
652 "%s\tUnit Active State: %s\n"
653 "%s\tInactive Exit Timestamp: %s\n"
654 "%s\tActive Enter Timestamp: %s\n"
655 "%s\tActive Exit Timestamp: %s\n"
656 "%s\tInactive Enter Timestamp: %s\n"
657 "%s\tGC Check Good: %s\n"
658 "%s\tNeed Daemon Reload: %s\n",
660 prefix, unit_description(u),
661 prefix, strna(u->instance),
662 prefix, unit_load_state_to_string(u->load_state),
663 prefix, unit_active_state_to_string(unit_active_state(u)),
664 prefix, strna(format_timestamp(timestamp1, sizeof(timestamp1), u->inactive_exit_timestamp.realtime)),
665 prefix, strna(format_timestamp(timestamp2, sizeof(timestamp2), u->active_enter_timestamp.realtime)),
666 prefix, strna(format_timestamp(timestamp3, sizeof(timestamp3), u->active_exit_timestamp.realtime)),
667 prefix, strna(format_timestamp(timestamp4, sizeof(timestamp4), u->inactive_enter_timestamp.realtime)),
668 prefix, yes_no(unit_check_gc(u)),
669 prefix, yes_no(unit_need_daemon_reload(u)));
671 SET_FOREACH(t, u->names, i)
672 fprintf(f, "%s\tName: %s\n", prefix, t);
674 if ((following = unit_following(u)))
675 fprintf(f, "%s\tFollowing: %s\n", prefix, following->id);
677 if (u->fragment_path)
678 fprintf(f, "%s\tFragment Path: %s\n", prefix, u->fragment_path);
680 if (u->job_timeout > 0)
681 fprintf(f, "%s\tJob Timeout: %s\n", prefix, format_timespan(timespan, sizeof(timespan), u->job_timeout));
683 condition_dump_list(u->conditions, f, prefix);
685 if (dual_timestamp_is_set(&u->condition_timestamp))
687 "%s\tCondition Timestamp: %s\n"
688 "%s\tCondition Result: %s\n",
689 prefix, strna(format_timestamp(timestamp1, sizeof(timestamp1), u->condition_timestamp.realtime)),
690 prefix, yes_no(u->condition_result));
692 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++) {
695 SET_FOREACH(other, u->dependencies[d], i)
696 fprintf(f, "%s\t%s: %s\n", prefix, unit_dependency_to_string(d), other->id);
699 if (!strv_isempty(u->requires_mounts_for)) {
703 "%s\tRequiresMountsFor:", prefix);
705 STRV_FOREACH(j, u->requires_mounts_for)
706 fprintf(f, " %s", *j);
711 if (u->load_state == UNIT_LOADED) {
716 "%s\tStopWhenUnneeded: %s\n"
717 "%s\tRefuseManualStart: %s\n"
718 "%s\tRefuseManualStop: %s\n"
719 "%s\tDefaultDependencies: %s\n"
720 "%s\tOnFailureIsolate: %s\n"
721 "%s\tIgnoreOnIsolate: %s\n"
722 "%s\tIgnoreOnSnapshot: %s\n",
723 prefix, yes_no(u->stop_when_unneeded),
724 prefix, yes_no(u->refuse_manual_start),
725 prefix, yes_no(u->refuse_manual_stop),
726 prefix, yes_no(u->default_dependencies),
727 prefix, yes_no(u->on_failure_isolate),
728 prefix, yes_no(u->ignore_on_isolate),
729 prefix, yes_no(u->ignore_on_snapshot));
731 LIST_FOREACH(by_unit, b, u->cgroup_bondings)
732 fprintf(f, "%s\tControlGroup: %s:%s\n",
733 prefix, b->controller, b->path);
735 LIST_FOREACH(by_unit, a, u->cgroup_attributes) {
739 a->map_callback(a->controller, a->name, a->value, &v);
741 fprintf(f, "%s\tControlGroupAttribute: %s %s \"%s\"\n",
742 prefix, a->controller, a->name, v ? v : a->value);
747 if (UNIT_VTABLE(u)->dump)
748 UNIT_VTABLE(u)->dump(u, f, prefix2);
750 } else if (u->load_state == UNIT_MERGED)
752 "%s\tMerged into: %s\n",
753 prefix, u->merged_into->id);
754 else if (u->load_state == UNIT_ERROR)
755 fprintf(f, "%s\tLoad Error Code: %s\n", prefix, strerror(-u->load_error));
759 job_dump(u->job, f, prefix2);
762 job_dump(u->nop_job, f, prefix2);
767 /* Common implementation for multiple backends */
768 int unit_load_fragment_and_dropin(Unit *u) {
773 /* Load a .service file */
774 if ((r = unit_load_fragment(u)) < 0)
777 if (u->load_state == UNIT_STUB)
780 /* Load drop-in directory data */
781 if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
787 /* Common implementation for multiple backends */
788 int unit_load_fragment_and_dropin_optional(Unit *u) {
793 /* Same as unit_load_fragment_and_dropin(), but whether
794 * something can be loaded or not doesn't matter. */
796 /* Load a .service file */
797 if ((r = unit_load_fragment(u)) < 0)
800 if (u->load_state == UNIT_STUB)
801 u->load_state = UNIT_LOADED;
803 /* Load drop-in directory data */
804 if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
810 int unit_add_default_target_dependency(Unit *u, Unit *target) {
814 if (target->type != UNIT_TARGET)
817 /* Only add the dependency if both units are loaded, so that
818 * that loop check below is reliable */
819 if (u->load_state != UNIT_LOADED ||
820 target->load_state != UNIT_LOADED)
823 /* If either side wants no automatic dependencies, then let's
825 if (!u->default_dependencies ||
826 !target->default_dependencies)
829 /* Don't create loops */
830 if (set_get(target->dependencies[UNIT_BEFORE], u))
833 return unit_add_dependency(target, UNIT_AFTER, u, true);
836 static int unit_add_default_dependencies(Unit *u) {
837 static const UnitDependency deps[] = {
839 UNIT_REQUIRED_BY_OVERRIDABLE,
851 for (k = 0; k < ELEMENTSOF(deps); k++)
852 SET_FOREACH(target, u->dependencies[deps[k]], i)
853 if ((r = unit_add_default_target_dependency(u, target)) < 0)
859 int unit_load(Unit *u) {
864 if (u->in_load_queue) {
865 LIST_REMOVE(Unit, load_queue, u->manager->load_queue, u);
866 u->in_load_queue = false;
869 if (u->type == _UNIT_TYPE_INVALID)
872 if (u->load_state != UNIT_STUB)
875 if (UNIT_VTABLE(u)->load)
876 if ((r = UNIT_VTABLE(u)->load(u)) < 0)
879 if (u->load_state == UNIT_STUB) {
884 if (u->load_state == UNIT_LOADED &&
885 u->default_dependencies)
886 if ((r = unit_add_default_dependencies(u)) < 0)
889 if (u->load_state == UNIT_LOADED) {
890 r = unit_add_mount_links(u);
895 if (u->on_failure_isolate &&
896 set_size(u->dependencies[UNIT_ON_FAILURE]) > 1) {
898 log_error("More than one OnFailure= dependencies specified for %s but OnFailureIsolate= enabled. Refusing.",
905 assert((u->load_state != UNIT_MERGED) == !u->merged_into);
907 unit_add_to_dbus_queue(unit_follow_merge(u));
908 unit_add_to_gc_queue(u);
913 u->load_state = UNIT_ERROR;
915 unit_add_to_dbus_queue(u);
916 unit_add_to_gc_queue(u);
918 log_debug("Failed to load configuration for %s: %s", u->id, strerror(-r));
923 bool unit_condition_test(Unit *u) {
926 dual_timestamp_get(&u->condition_timestamp);
927 u->condition_result = condition_test_list(u->conditions);
929 return u->condition_result;
933 * -EBADR: This unit type does not support starting.
934 * -EALREADY: Unit is already started.
935 * -EAGAIN: An operation is already in progress. Retry later.
936 * -ECANCELED: Too many requests for now.
938 int unit_start(Unit *u) {
939 UnitActiveState state;
944 if (u->load_state != UNIT_LOADED)
947 /* If this is already started, then this will succeed. Note
948 * that this will even succeed if this unit is not startable
949 * by the user. This is relied on to detect when we need to
950 * wait for units and when waiting is finished. */
951 state = unit_active_state(u);
952 if (UNIT_IS_ACTIVE_OR_RELOADING(state))
955 /* If the conditions failed, don't do anything at all. If we
956 * already are activating this call might still be useful to
957 * speed up activation in case there is some hold-off time,
958 * but we don't want to recheck the condition in that case. */
959 if (state != UNIT_ACTIVATING &&
960 !unit_condition_test(u)) {
961 log_debug("Starting of %s requested but condition failed. Ignoring.", u->id);
965 /* Forward to the main object, if we aren't it. */
966 if ((following = unit_following(u))) {
967 log_debug("Redirecting start request from %s to %s.", u->id, following->id);
968 return unit_start(following);
971 /* If it is stopped, but we cannot start it, then fail */
972 if (!UNIT_VTABLE(u)->start)
975 /* We don't suppress calls to ->start() here when we are
976 * already starting, to allow this request to be used as a
977 * "hurry up" call, for example when the unit is in some "auto
978 * restart" state where it waits for a holdoff timer to elapse
979 * before it will start again. */
981 unit_add_to_dbus_queue(u);
983 unit_status_printf(u, NULL, "Starting %s...", unit_description(u));
984 return UNIT_VTABLE(u)->start(u);
987 bool unit_can_start(Unit *u) {
990 return !!UNIT_VTABLE(u)->start;
993 bool unit_can_isolate(Unit *u) {
996 return unit_can_start(u) &&
1001 * -EBADR: This unit type does not support stopping.
1002 * -EALREADY: Unit is already stopped.
1003 * -EAGAIN: An operation is already in progress. Retry later.
1005 int unit_stop(Unit *u) {
1006 UnitActiveState state;
1011 state = unit_active_state(u);
1012 if (UNIT_IS_INACTIVE_OR_FAILED(state))
1015 if ((following = unit_following(u))) {
1016 log_debug("Redirecting stop request from %s to %s.", u->id, following->id);
1017 return unit_stop(following);
1020 if (!UNIT_VTABLE(u)->stop)
1023 unit_add_to_dbus_queue(u);
1025 unit_status_printf(u, NULL, "Stopping %s...", unit_description(u));
1026 return UNIT_VTABLE(u)->stop(u);
1030 * -EBADR: This unit type does not support reloading.
1031 * -ENOEXEC: Unit is not started.
1032 * -EAGAIN: An operation is already in progress. Retry later.
1034 int unit_reload(Unit *u) {
1035 UnitActiveState state;
1040 if (u->load_state != UNIT_LOADED)
1043 if (!unit_can_reload(u))
1046 state = unit_active_state(u);
1047 if (state == UNIT_RELOADING)
1050 if (state != UNIT_ACTIVE)
1053 if ((following = unit_following(u))) {
1054 log_debug("Redirecting reload request from %s to %s.", u->id, following->id);
1055 return unit_reload(following);
1058 unit_add_to_dbus_queue(u);
1059 return UNIT_VTABLE(u)->reload(u);
1062 bool unit_can_reload(Unit *u) {
1065 if (!UNIT_VTABLE(u)->reload)
1068 if (!UNIT_VTABLE(u)->can_reload)
1071 return UNIT_VTABLE(u)->can_reload(u);
1074 static void unit_check_unneeded(Unit *u) {
1080 /* If this service shall be shut down when unneeded then do
1083 if (!u->stop_when_unneeded)
1086 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)))
1089 SET_FOREACH(other, u->dependencies[UNIT_REQUIRED_BY], i)
1090 if (unit_pending_active(other))
1093 SET_FOREACH(other, u->dependencies[UNIT_REQUIRED_BY_OVERRIDABLE], i)
1094 if (unit_pending_active(other))
1097 SET_FOREACH(other, u->dependencies[UNIT_WANTED_BY], i)
1098 if (unit_pending_active(other))
1101 SET_FOREACH(other, u->dependencies[UNIT_BOUND_BY], i)
1102 if (unit_pending_active(other))
1105 log_info("Service %s is not needed anymore. Stopping.", u->id);
1107 /* Ok, nobody needs us anymore. Sniff. Then let's commit suicide */
1108 manager_add_job(u->manager, JOB_STOP, u, JOB_FAIL, true, NULL, NULL);
1111 static void retroactively_start_dependencies(Unit *u) {
1116 assert(UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)));
1118 SET_FOREACH(other, u->dependencies[UNIT_REQUIRES], i)
1119 if (!set_get(u->dependencies[UNIT_AFTER], other) &&
1120 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
1121 manager_add_job(u->manager, JOB_START, other, JOB_REPLACE, true, NULL, NULL);
1123 SET_FOREACH(other, u->dependencies[UNIT_BIND_TO], i)
1124 if (!set_get(u->dependencies[UNIT_AFTER], other) &&
1125 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
1126 manager_add_job(u->manager, JOB_START, other, JOB_REPLACE, true, NULL, NULL);
1128 SET_FOREACH(other, u->dependencies[UNIT_REQUIRES_OVERRIDABLE], i)
1129 if (!set_get(u->dependencies[UNIT_AFTER], other) &&
1130 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
1131 manager_add_job(u->manager, JOB_START, other, JOB_FAIL, false, NULL, NULL);
1133 SET_FOREACH(other, u->dependencies[UNIT_REQUISITE], i)
1134 if (!set_get(u->dependencies[UNIT_AFTER], other) &&
1135 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
1136 manager_add_job(u->manager, JOB_START, other, JOB_REPLACE, true, NULL, NULL);
1138 SET_FOREACH(other, u->dependencies[UNIT_WANTS], i)
1139 if (!set_get(u->dependencies[UNIT_AFTER], other) &&
1140 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
1141 manager_add_job(u->manager, JOB_START, other, JOB_FAIL, false, NULL, NULL);
1143 SET_FOREACH(other, u->dependencies[UNIT_CONFLICTS], i)
1144 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1145 manager_add_job(u->manager, JOB_STOP, other, JOB_REPLACE, true, NULL, NULL);
1147 SET_FOREACH(other, u->dependencies[UNIT_CONFLICTED_BY], i)
1148 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1149 manager_add_job(u->manager, JOB_STOP, other, JOB_REPLACE, true, NULL, NULL);
1152 static void retroactively_stop_dependencies(Unit *u) {
1157 assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)));
1159 /* Pull down units which are bound to us recursively if enabled */
1160 SET_FOREACH(other, u->dependencies[UNIT_BOUND_BY], i)
1161 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1162 manager_add_job(u->manager, JOB_STOP, other, JOB_REPLACE, true, NULL, NULL);
1165 static void check_unneeded_dependencies(Unit *u) {
1170 assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)));
1172 /* Garbage collect services that might not be needed anymore, if enabled */
1173 SET_FOREACH(other, u->dependencies[UNIT_REQUIRES], i)
1174 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1175 unit_check_unneeded(other);
1176 SET_FOREACH(other, u->dependencies[UNIT_REQUIRES_OVERRIDABLE], i)
1177 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1178 unit_check_unneeded(other);
1179 SET_FOREACH(other, u->dependencies[UNIT_WANTS], i)
1180 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1181 unit_check_unneeded(other);
1182 SET_FOREACH(other, u->dependencies[UNIT_REQUISITE], i)
1183 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1184 unit_check_unneeded(other);
1185 SET_FOREACH(other, u->dependencies[UNIT_REQUISITE_OVERRIDABLE], i)
1186 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1187 unit_check_unneeded(other);
1188 SET_FOREACH(other, u->dependencies[UNIT_BIND_TO], i)
1189 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1190 unit_check_unneeded(other);
1193 void unit_trigger_on_failure(Unit *u) {
1199 if (set_size(u->dependencies[UNIT_ON_FAILURE]) <= 0)
1202 log_info("Triggering OnFailure= dependencies of %s.", u->id);
1204 SET_FOREACH(other, u->dependencies[UNIT_ON_FAILURE], i) {
1207 if ((r = manager_add_job(u->manager, JOB_START, other, u->on_failure_isolate ? JOB_ISOLATE : JOB_REPLACE, true, NULL, NULL)) < 0)
1208 log_error("Failed to enqueue OnFailure= job: %s", strerror(-r));
1212 void unit_notify(Unit *u, UnitActiveState os, UnitActiveState ns, bool reload_success) {
1216 assert(os < _UNIT_ACTIVE_STATE_MAX);
1217 assert(ns < _UNIT_ACTIVE_STATE_MAX);
1219 /* Note that this is called for all low-level state changes,
1220 * even if they might map to the same high-level
1221 * UnitActiveState! That means that ns == os is OK an expected
1222 * behaviour here. For example: if a mount point is remounted
1223 * this function will be called too! */
1225 if (u->manager->n_reloading <= 0) {
1228 dual_timestamp_get(&ts);
1230 if (UNIT_IS_INACTIVE_OR_FAILED(os) && !UNIT_IS_INACTIVE_OR_FAILED(ns))
1231 u->inactive_exit_timestamp = ts;
1232 else if (!UNIT_IS_INACTIVE_OR_FAILED(os) && UNIT_IS_INACTIVE_OR_FAILED(ns))
1233 u->inactive_enter_timestamp = ts;
1235 if (!UNIT_IS_ACTIVE_OR_RELOADING(os) && UNIT_IS_ACTIVE_OR_RELOADING(ns))
1236 u->active_enter_timestamp = ts;
1237 else if (UNIT_IS_ACTIVE_OR_RELOADING(os) && !UNIT_IS_ACTIVE_OR_RELOADING(ns))
1238 u->active_exit_timestamp = ts;
1240 timer_unit_notify(u, ns);
1241 path_unit_notify(u, ns);
1244 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
1245 cgroup_bonding_trim_list(u->cgroup_bondings, true);
1250 if (u->job->state == JOB_WAITING)
1252 /* So we reached a different state for this
1253 * job. Let's see if we can run it now if it
1254 * failed previously due to EAGAIN. */
1255 job_add_to_run_queue(u->job);
1257 /* Let's check whether this state change constitutes a
1258 * finished job, or maybe contradicts a running job and
1259 * hence needs to invalidate jobs. */
1261 switch (u->job->type) {
1264 case JOB_VERIFY_ACTIVE:
1266 if (UNIT_IS_ACTIVE_OR_RELOADING(ns))
1267 job_finish_and_invalidate(u->job, JOB_DONE, true);
1268 else if (u->job->state == JOB_RUNNING && ns != UNIT_ACTIVATING) {
1271 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
1272 job_finish_and_invalidate(u->job, ns == UNIT_FAILED ? JOB_FAILED : JOB_DONE, true);
1278 case JOB_RELOAD_OR_START:
1280 if (u->job->state == JOB_RUNNING) {
1281 if (ns == UNIT_ACTIVE)
1282 job_finish_and_invalidate(u->job, reload_success ? JOB_DONE : JOB_FAILED, true);
1283 else if (ns != UNIT_ACTIVATING && ns != UNIT_RELOADING) {
1286 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
1287 job_finish_and_invalidate(u->job, ns == UNIT_FAILED ? JOB_FAILED : JOB_DONE, true);
1295 case JOB_TRY_RESTART:
1297 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
1298 job_finish_and_invalidate(u->job, JOB_DONE, true);
1299 else if (u->job->state == JOB_RUNNING && ns != UNIT_DEACTIVATING) {
1301 job_finish_and_invalidate(u->job, JOB_FAILED, true);
1307 assert_not_reached("Job type unknown");
1313 if (u->manager->n_reloading <= 0) {
1315 /* If this state change happened without being
1316 * requested by a job, then let's retroactively start
1317 * or stop dependencies. We skip that step when
1318 * deserializing, since we don't want to create any
1319 * additional jobs just because something is already
1323 if (UNIT_IS_INACTIVE_OR_FAILED(os) && UNIT_IS_ACTIVE_OR_ACTIVATING(ns))
1324 retroactively_start_dependencies(u);
1325 else if (UNIT_IS_ACTIVE_OR_ACTIVATING(os) && UNIT_IS_INACTIVE_OR_DEACTIVATING(ns))
1326 retroactively_stop_dependencies(u);
1329 /* stop unneeded units regardless if going down was expected or not */
1330 if (UNIT_IS_ACTIVE_OR_ACTIVATING(os) && UNIT_IS_INACTIVE_OR_DEACTIVATING(ns))
1331 check_unneeded_dependencies(u);
1333 if (ns != os && ns == UNIT_FAILED) {
1334 log_notice("Unit %s entered failed state.", u->id);
1335 unit_trigger_on_failure(u);
1339 /* Some names are special */
1340 if (UNIT_IS_ACTIVE_OR_RELOADING(ns)) {
1342 if (unit_has_name(u, SPECIAL_DBUS_SERVICE))
1343 /* The bus just might have become available,
1344 * hence try to connect to it, if we aren't
1346 bus_init(u->manager, true);
1348 if (u->type == UNIT_SERVICE &&
1349 !UNIT_IS_ACTIVE_OR_RELOADING(os) &&
1350 u->manager->n_reloading <= 0) {
1351 /* Write audit record if we have just finished starting up */
1352 manager_send_unit_audit(u->manager, u, AUDIT_SERVICE_START, true);
1356 if (!UNIT_IS_ACTIVE_OR_RELOADING(os))
1357 manager_send_unit_plymouth(u->manager, u);
1361 /* We don't care about D-Bus here, since we'll get an
1362 * asynchronous notification for it anyway. */
1364 if (u->type == UNIT_SERVICE &&
1365 UNIT_IS_INACTIVE_OR_FAILED(ns) &&
1366 !UNIT_IS_INACTIVE_OR_FAILED(os) &&
1367 u->manager->n_reloading <= 0) {
1369 /* Hmm, if there was no start record written
1370 * write it now, so that we always have a nice
1373 manager_send_unit_audit(u->manager, u, AUDIT_SERVICE_START, ns == UNIT_INACTIVE);
1375 if (ns == UNIT_INACTIVE)
1376 manager_send_unit_audit(u->manager, u, AUDIT_SERVICE_STOP, true);
1378 /* Write audit record if we have just finished shutting down */
1379 manager_send_unit_audit(u->manager, u, AUDIT_SERVICE_STOP, ns == UNIT_INACTIVE);
1381 u->in_audit = false;
1385 manager_recheck_journal(u->manager);
1387 /* Maybe we finished startup and are now ready for being
1388 * stopped because unneeded? */
1389 unit_check_unneeded(u);
1391 unit_add_to_dbus_queue(u);
1392 unit_add_to_gc_queue(u);
1395 int unit_watch_fd(Unit *u, int fd, uint32_t events, Watch *w) {
1396 struct epoll_event ev;
1401 assert(w->type == WATCH_INVALID || (w->type == WATCH_FD && w->fd == fd && w->data.unit == u));
1407 if (epoll_ctl(u->manager->epoll_fd,
1408 w->type == WATCH_INVALID ? EPOLL_CTL_ADD : EPOLL_CTL_MOD,
1420 void unit_unwatch_fd(Unit *u, Watch *w) {
1424 if (w->type == WATCH_INVALID)
1427 assert(w->type == WATCH_FD);
1428 assert(w->data.unit == u);
1429 assert_se(epoll_ctl(u->manager->epoll_fd, EPOLL_CTL_DEL, w->fd, NULL) >= 0);
1432 w->type = WATCH_INVALID;
1433 w->data.unit = NULL;
1436 int unit_watch_pid(Unit *u, pid_t pid) {
1440 /* Watch a specific PID. We only support one unit watching
1441 * each PID for now. */
1443 return hashmap_put(u->manager->watch_pids, LONG_TO_PTR(pid), u);
1446 void unit_unwatch_pid(Unit *u, pid_t pid) {
1450 hashmap_remove_value(u->manager->watch_pids, LONG_TO_PTR(pid), u);
1453 int unit_watch_timer(Unit *u, usec_t delay, Watch *w) {
1454 struct itimerspec its;
1460 assert(w->type == WATCH_INVALID || (w->type == WATCH_UNIT_TIMER && w->data.unit == u));
1462 /* This will try to reuse the old timer if there is one */
1464 if (w->type == WATCH_UNIT_TIMER) {
1465 assert(w->data.unit == u);
1470 } else if (w->type == WATCH_INVALID) {
1473 if ((fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK|TFD_CLOEXEC)) < 0)
1476 assert_not_reached("Invalid watch type");
1481 /* Set absolute time in the past, but not 0, since we
1482 * don't want to disarm the timer */
1483 its.it_value.tv_sec = 0;
1484 its.it_value.tv_nsec = 1;
1486 flags = TFD_TIMER_ABSTIME;
1488 timespec_store(&its.it_value, delay);
1492 /* This will also flush the elapse counter */
1493 if (timerfd_settime(fd, flags, &its, NULL) < 0)
1496 if (w->type == WATCH_INVALID) {
1497 struct epoll_event ev;
1501 ev.events = EPOLLIN;
1503 if (epoll_ctl(u->manager->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0)
1507 w->type = WATCH_UNIT_TIMER;
1515 close_nointr_nofail(fd);
1520 void unit_unwatch_timer(Unit *u, Watch *w) {
1524 if (w->type == WATCH_INVALID)
1527 assert(w->type == WATCH_UNIT_TIMER);
1528 assert(w->data.unit == u);
1531 assert_se(epoll_ctl(u->manager->epoll_fd, EPOLL_CTL_DEL, w->fd, NULL) >= 0);
1532 close_nointr_nofail(w->fd);
1535 w->type = WATCH_INVALID;
1536 w->data.unit = NULL;
1539 bool unit_job_is_applicable(Unit *u, JobType j) {
1541 assert(j >= 0 && j < _JOB_TYPE_MAX);
1545 case JOB_VERIFY_ACTIVE:
1552 case JOB_TRY_RESTART:
1553 return unit_can_start(u);
1556 return unit_can_reload(u);
1558 case JOB_RELOAD_OR_START:
1559 return unit_can_reload(u) && unit_can_start(u);
1562 assert_not_reached("Invalid job type");
1566 int unit_add_dependency(Unit *u, UnitDependency d, Unit *other, bool add_reference) {
1568 static const UnitDependency inverse_table[_UNIT_DEPENDENCY_MAX] = {
1569 [UNIT_REQUIRES] = UNIT_REQUIRED_BY,
1570 [UNIT_REQUIRES_OVERRIDABLE] = UNIT_REQUIRED_BY_OVERRIDABLE,
1571 [UNIT_WANTS] = UNIT_WANTED_BY,
1572 [UNIT_REQUISITE] = UNIT_REQUIRED_BY,
1573 [UNIT_REQUISITE_OVERRIDABLE] = UNIT_REQUIRED_BY_OVERRIDABLE,
1574 [UNIT_BIND_TO] = UNIT_BOUND_BY,
1575 [UNIT_REQUIRED_BY] = _UNIT_DEPENDENCY_INVALID,
1576 [UNIT_REQUIRED_BY_OVERRIDABLE] = _UNIT_DEPENDENCY_INVALID,
1577 [UNIT_WANTED_BY] = _UNIT_DEPENDENCY_INVALID,
1578 [UNIT_BOUND_BY] = UNIT_BIND_TO,
1579 [UNIT_CONFLICTS] = UNIT_CONFLICTED_BY,
1580 [UNIT_CONFLICTED_BY] = UNIT_CONFLICTS,
1581 [UNIT_BEFORE] = UNIT_AFTER,
1582 [UNIT_AFTER] = UNIT_BEFORE,
1583 [UNIT_ON_FAILURE] = _UNIT_DEPENDENCY_INVALID,
1584 [UNIT_REFERENCES] = UNIT_REFERENCED_BY,
1585 [UNIT_REFERENCED_BY] = UNIT_REFERENCES,
1586 [UNIT_TRIGGERS] = UNIT_TRIGGERED_BY,
1587 [UNIT_TRIGGERED_BY] = UNIT_TRIGGERS,
1588 [UNIT_PROPAGATE_RELOAD_TO] = UNIT_PROPAGATE_RELOAD_FROM,
1589 [UNIT_PROPAGATE_RELOAD_FROM] = UNIT_PROPAGATE_RELOAD_TO
1591 int r, q = 0, v = 0, w = 0;
1594 assert(d >= 0 && d < _UNIT_DEPENDENCY_MAX);
1597 u = unit_follow_merge(u);
1598 other = unit_follow_merge(other);
1600 /* We won't allow dependencies on ourselves. We will not
1601 * consider them an error however. */
1605 if ((r = set_ensure_allocated(&u->dependencies[d], trivial_hash_func, trivial_compare_func)) < 0)
1608 if (inverse_table[d] != _UNIT_DEPENDENCY_INVALID)
1609 if ((r = set_ensure_allocated(&other->dependencies[inverse_table[d]], trivial_hash_func, trivial_compare_func)) < 0)
1613 if ((r = set_ensure_allocated(&u->dependencies[UNIT_REFERENCES], trivial_hash_func, trivial_compare_func)) < 0 ||
1614 (r = set_ensure_allocated(&other->dependencies[UNIT_REFERENCED_BY], trivial_hash_func, trivial_compare_func)) < 0)
1617 if ((q = set_put(u->dependencies[d], other)) < 0)
1620 if (inverse_table[d] != _UNIT_DEPENDENCY_INVALID)
1621 if ((v = set_put(other->dependencies[inverse_table[d]], u)) < 0) {
1626 if (add_reference) {
1627 if ((w = set_put(u->dependencies[UNIT_REFERENCES], other)) < 0) {
1632 if ((r = set_put(other->dependencies[UNIT_REFERENCED_BY], u)) < 0)
1636 unit_add_to_dbus_queue(u);
1641 set_remove(u->dependencies[d], other);
1644 set_remove(other->dependencies[inverse_table[d]], u);
1647 set_remove(u->dependencies[UNIT_REFERENCES], other);
1652 int unit_add_two_dependencies(Unit *u, UnitDependency d, UnitDependency e, Unit *other, bool add_reference) {
1657 if ((r = unit_add_dependency(u, d, other, add_reference)) < 0)
1660 if ((r = unit_add_dependency(u, e, other, add_reference)) < 0)
1666 static const char *resolve_template(Unit *u, const char *name, const char*path, char **p) {
1670 assert(name || path);
1673 name = file_name_from_path(path);
1675 if (!unit_name_is_template(name)) {
1681 s = unit_name_replace_instance(name, u->instance);
1685 if (!(i = unit_name_to_prefix(u->id)))
1688 s = unit_name_replace_instance(name, i);
1699 int unit_add_dependency_by_name(Unit *u, UnitDependency d, const char *name, const char *path, bool add_reference) {
1705 assert(name || path);
1707 if (!(name = resolve_template(u, name, path, &s)))
1710 if ((r = manager_load_unit(u->manager, name, path, NULL, &other)) < 0)
1713 r = unit_add_dependency(u, d, other, add_reference);
1720 int unit_add_two_dependencies_by_name(Unit *u, UnitDependency d, UnitDependency e, const char *name, const char *path, bool add_reference) {
1726 assert(name || path);
1728 if (!(name = resolve_template(u, name, path, &s)))
1731 if ((r = manager_load_unit(u->manager, name, path, NULL, &other)) < 0)
1734 r = unit_add_two_dependencies(u, d, e, other, add_reference);
1741 int unit_add_dependency_by_name_inverse(Unit *u, UnitDependency d, const char *name, const char *path, bool add_reference) {
1747 assert(name || path);
1749 if (!(name = resolve_template(u, name, path, &s)))
1752 if ((r = manager_load_unit(u->manager, name, path, NULL, &other)) < 0)
1755 r = unit_add_dependency(other, d, u, add_reference);
1762 int unit_add_two_dependencies_by_name_inverse(Unit *u, UnitDependency d, UnitDependency e, const char *name, const char *path, bool add_reference) {
1768 assert(name || path);
1770 if (!(name = resolve_template(u, name, path, &s)))
1773 if ((r = manager_load_unit(u->manager, name, path, NULL, &other)) < 0)
1776 if ((r = unit_add_two_dependencies(other, d, e, u, add_reference)) < 0)
1784 int set_unit_path(const char *p) {
1788 /* This is mostly for debug purposes */
1790 if (path_is_absolute(p)) {
1791 if (!(c = strdup(p)))
1794 if (!(cwd = get_current_dir_name()))
1797 r = asprintf(&c, "%s/%s", cwd, p);
1804 if (setenv("SYSTEMD_UNIT_PATH", c, 0) < 0) {
1813 char *unit_dbus_path(Unit *u) {
1821 if (!(e = bus_path_escape(u->id)))
1824 p = strappend("/org/freedesktop/systemd1/unit/", e);
1830 int unit_add_cgroup(Unit *u, CGroupBonding *b) {
1838 if (!b->controller) {
1839 if (!(b->controller = strdup(SYSTEMD_CGROUP_CONTROLLER)))
1845 /* Ensure this hasn't been added yet */
1848 if (streq(b->controller, SYSTEMD_CGROUP_CONTROLLER)) {
1851 l = hashmap_get(u->manager->cgroup_bondings, b->path);
1852 LIST_PREPEND(CGroupBonding, by_path, l, b);
1854 if ((r = hashmap_replace(u->manager->cgroup_bondings, b->path, l)) < 0) {
1855 LIST_REMOVE(CGroupBonding, by_path, l, b);
1860 LIST_PREPEND(CGroupBonding, by_unit, u->cgroup_bondings, b);
1866 static char *default_cgroup_path(Unit *u) {
1874 t = unit_name_template(u->id);
1878 p = join(u->manager->cgroup_hierarchy, "/", t, "/", u->instance, NULL);
1881 p = join(u->manager->cgroup_hierarchy, "/", u->id, NULL);
1886 int unit_add_cgroup_from_text(Unit *u, const char *name) {
1887 char *controller = NULL, *path = NULL;
1888 CGroupBonding *b = NULL;
1895 if ((r = cg_split_spec(name, &controller, &path)) < 0)
1899 path = default_cgroup_path(u);
1904 controller = strdup(SYSTEMD_CGROUP_CONTROLLER);
1908 if (!path || !controller) {
1915 if (cgroup_bonding_find_list(u->cgroup_bondings, controller)) {
1920 if (!(b = new0(CGroupBonding, 1))) {
1925 b->controller = controller;
1928 b->essential = streq(controller, SYSTEMD_CGROUP_CONTROLLER);
1930 if ((r = unit_add_cgroup(u, b)) < 0)
1943 static int unit_add_one_default_cgroup(Unit *u, const char *controller) {
1944 CGroupBonding *b = NULL;
1950 controller = SYSTEMD_CGROUP_CONTROLLER;
1952 if (cgroup_bonding_find_list(u->cgroup_bondings, controller))
1955 if (!(b = new0(CGroupBonding, 1)))
1958 if (!(b->controller = strdup(controller)))
1961 if (!(b->path = default_cgroup_path(u)))
1965 b->essential = streq(controller, SYSTEMD_CGROUP_CONTROLLER);
1967 if ((r = unit_add_cgroup(u, b)) < 0)
1974 free(b->controller);
1980 int unit_add_default_cgroups(Unit *u) {
1987 /* Adds in the default cgroups, if they weren't specified
1990 if (!u->manager->cgroup_hierarchy)
1993 if ((r = unit_add_one_default_cgroup(u, NULL)) < 0)
1996 STRV_FOREACH(c, u->manager->default_controllers)
1997 unit_add_one_default_cgroup(u, *c);
1999 LIST_FOREACH(by_unit, a, u->cgroup_attributes)
2000 unit_add_one_default_cgroup(u, a->controller);
2005 CGroupBonding* unit_get_default_cgroup(Unit *u) {
2008 return cgroup_bonding_find_list(u->cgroup_bondings, SYSTEMD_CGROUP_CONTROLLER);
2011 int unit_add_cgroup_attribute(Unit *u, const char *controller, const char *name, const char *value, CGroupAttributeMapCallback map_callback) {
2023 dot = strchr(name, '.');
2027 c = strndup(name, dot - name);
2034 if (streq(controller, SYSTEMD_CGROUP_CONTROLLER)) {
2039 a = new0(CGroupAttribute, 1);
2049 a->controller = strdup(controller);
2051 a->name = strdup(name);
2052 a->value = strdup(value);
2054 if (!a->controller || !a->name || !a->value) {
2055 free(a->controller);
2063 a->map_callback = map_callback;
2065 LIST_PREPEND(CGroupAttribute, by_unit, u->cgroup_attributes, a);
2074 int unit_load_related_unit(Unit *u, const char *type, Unit **_found) {
2082 if (!(t = unit_name_change_suffix(u->id, type)))
2085 assert(!unit_has_name(u, t));
2087 r = manager_load_unit(u->manager, t, NULL, NULL, _found);
2090 assert(r < 0 || *_found != u);
2095 int unit_get_related_unit(Unit *u, const char *type, Unit **_found) {
2103 if (!(t = unit_name_change_suffix(u->id, type)))
2106 assert(!unit_has_name(u, t));
2108 found = manager_get_unit(u->manager, t);
2118 static char *specifier_prefix_and_instance(char specifier, void *data, void *userdata) {
2122 return unit_name_to_prefix_and_instance(u->id);
2125 static char *specifier_prefix(char specifier, void *data, void *userdata) {
2129 return unit_name_to_prefix(u->id);
2132 static char *specifier_prefix_unescaped(char specifier, void *data, void *userdata) {
2138 if (!(p = unit_name_to_prefix(u->id)))
2141 r = unit_name_unescape(p);
2147 static char *specifier_instance_unescaped(char specifier, void *data, void *userdata) {
2152 return unit_name_unescape(u->instance);
2157 static char *specifier_filename(char specifier, void *data, void *userdata) {
2162 return unit_name_path_unescape(u->instance);
2164 return unit_name_to_path(u->instance);
2167 static char *specifier_cgroup(char specifier, void *data, void *userdata) {
2171 return default_cgroup_path(u);
2174 static char *specifier_cgroup_root(char specifier, void *data, void *userdata) {
2179 if (specifier == 'r')
2180 return strdup(u->manager->cgroup_hierarchy);
2182 if (parent_of_path(u->manager->cgroup_hierarchy, &p) < 0)
2185 if (streq(p, "/")) {
2193 static char *specifier_runtime(char specifier, void *data, void *userdata) {
2197 if (u->manager->running_as == MANAGER_USER) {
2200 e = getenv("XDG_RUNTIME_DIR");
2205 return strdup("/run");
2208 char *unit_name_printf(Unit *u, const char* format) {
2211 * This will use the passed string as format string and
2212 * replace the following specifiers:
2214 * %n: the full id of the unit (foo@bar.waldo)
2215 * %N: the id of the unit without the suffix (foo@bar)
2216 * %p: the prefix (foo)
2217 * %i: the instance (bar)
2220 const Specifier table[] = {
2221 { 'n', specifier_string, u->id },
2222 { 'N', specifier_prefix_and_instance, NULL },
2223 { 'p', specifier_prefix, NULL },
2224 { 'i', specifier_string, u->instance },
2231 return specifier_printf(format, table, u);
2234 char *unit_full_printf(Unit *u, const char *format) {
2236 /* This is similar to unit_name_printf() but also supports
2237 * unescaping. Also, adds a couple of additional codes:
2239 * %c cgroup path of unit
2240 * %r root cgroup path of this systemd instance (e.g. "/user/lennart/shared/systemd-4711")
2241 * %R parent of root cgroup path (e.g. "/usr/lennart/shared")
2242 * %t the runtime directory to place sockets in (e.g. "/run" or $XDG_RUNTIME_DIR)
2245 const Specifier table[] = {
2246 { 'n', specifier_string, u->id },
2247 { 'N', specifier_prefix_and_instance, NULL },
2248 { 'p', specifier_prefix, NULL },
2249 { 'P', specifier_prefix_unescaped, NULL },
2250 { 'i', specifier_string, u->instance },
2251 { 'I', specifier_instance_unescaped, NULL },
2252 { 'f', specifier_filename, NULL },
2253 { 'c', specifier_cgroup, NULL },
2254 { 'r', specifier_cgroup_root, NULL },
2255 { 'R', specifier_cgroup_root, NULL },
2256 { 't', specifier_runtime, NULL },
2263 return specifier_printf(format, table, u);
2266 char **unit_full_printf_strv(Unit *u, char **l) {
2270 /* Applies unit_full_printf to every entry in l */
2275 if (!(r = new(char*, n+1)))
2278 for (i = l, j = r; *i; i++, j++)
2279 if (!(*j = unit_full_printf(u, *i)))
2286 for (j--; j >= r; j--)
2294 int unit_watch_bus_name(Unit *u, const char *name) {
2298 /* Watch a specific name on the bus. We only support one unit
2299 * watching each name for now. */
2301 return hashmap_put(u->manager->watch_bus, name, u);
2304 void unit_unwatch_bus_name(Unit *u, const char *name) {
2308 hashmap_remove_value(u->manager->watch_bus, name, u);
2311 bool unit_can_serialize(Unit *u) {
2314 return UNIT_VTABLE(u)->serialize && UNIT_VTABLE(u)->deserialize_item;
2317 int unit_serialize(Unit *u, FILE *f, FDSet *fds) {
2324 if (!unit_can_serialize(u))
2327 if ((r = UNIT_VTABLE(u)->serialize(u, f, fds)) < 0)
2331 fprintf(f, "job\n");
2332 job_serialize(u->job, f, fds);
2336 fprintf(f, "job\n");
2337 job_serialize(u->nop_job, f, fds);
2340 dual_timestamp_serialize(f, "inactive-exit-timestamp", &u->inactive_exit_timestamp);
2341 dual_timestamp_serialize(f, "active-enter-timestamp", &u->active_enter_timestamp);
2342 dual_timestamp_serialize(f, "active-exit-timestamp", &u->active_exit_timestamp);
2343 dual_timestamp_serialize(f, "inactive-enter-timestamp", &u->inactive_enter_timestamp);
2344 dual_timestamp_serialize(f, "condition-timestamp", &u->condition_timestamp);
2346 if (dual_timestamp_is_set(&u->condition_timestamp))
2347 unit_serialize_item(u, f, "condition-result", yes_no(u->condition_result));
2354 void unit_serialize_item_format(Unit *u, FILE *f, const char *key, const char *format, ...) {
2365 va_start(ap, format);
2366 vfprintf(f, format, ap);
2372 void unit_serialize_item(Unit *u, FILE *f, const char *key, const char *value) {
2378 fprintf(f, "%s=%s\n", key, value);
2381 int unit_deserialize(Unit *u, FILE *f, FDSet *fds) {
2388 if (!unit_can_serialize(u))
2392 char line[LINE_MAX], *l, *v;
2395 if (!fgets(line, sizeof(line), f)) {
2408 k = strcspn(l, "=");
2416 if (streq(l, "job")) {
2418 /* new-style serialized job */
2419 Job *j = job_new_raw(u);
2423 r = job_deserialize(j, f, fds);
2429 r = hashmap_put(u->manager->jobs, UINT32_TO_PTR(j->id), j);
2435 r = job_install_deserialized(j);
2437 hashmap_remove(u->manager->jobs, UINT32_TO_PTR(j->id));
2443 JobType type = job_type_from_string(v);
2445 log_debug("Failed to parse job type value %s", v);
2447 u->deserialized_job = type;
2450 } else if (streq(l, "inactive-exit-timestamp")) {
2451 dual_timestamp_deserialize(v, &u->inactive_exit_timestamp);
2453 } else if (streq(l, "active-enter-timestamp")) {
2454 dual_timestamp_deserialize(v, &u->active_enter_timestamp);
2456 } else if (streq(l, "active-exit-timestamp")) {
2457 dual_timestamp_deserialize(v, &u->active_exit_timestamp);
2459 } else if (streq(l, "inactive-enter-timestamp")) {
2460 dual_timestamp_deserialize(v, &u->inactive_enter_timestamp);
2462 } else if (streq(l, "condition-timestamp")) {
2463 dual_timestamp_deserialize(v, &u->condition_timestamp);
2465 } else if (streq(l, "condition-result")) {
2468 if ((b = parse_boolean(v)) < 0)
2469 log_debug("Failed to parse condition result value %s", v);
2471 u->condition_result = b;
2476 if ((r = UNIT_VTABLE(u)->deserialize_item(u, l, v, fds)) < 0)
2481 int unit_add_node_link(Unit *u, const char *what, bool wants) {
2491 /* Adds in links to the device node that this unit is based on */
2493 if (!is_device_path(what))
2496 if (!(e = unit_name_build_escape(what+1, NULL, ".device")))
2499 r = manager_load_unit(u->manager, e, NULL, NULL, &device);
2505 if ((r = unit_add_two_dependencies(u, UNIT_AFTER, UNIT_BIND_TO, device, true)) < 0)
2509 if ((r = unit_add_dependency(device, UNIT_WANTS, u, false)) < 0)
2515 int unit_coldplug(Unit *u) {
2520 if (UNIT_VTABLE(u)->coldplug)
2521 if ((r = UNIT_VTABLE(u)->coldplug(u)) < 0)
2525 r = job_coldplug(u->job);
2528 } else if (u->deserialized_job >= 0) {
2530 r = manager_add_job(u->manager, u->deserialized_job, u, JOB_IGNORE_REQUIREMENTS, false, NULL, NULL);
2534 u->deserialized_job = _JOB_TYPE_INVALID;
2540 void unit_status_printf(Unit *u, const char *status, const char *format, ...) {
2546 if (!UNIT_VTABLE(u)->show_status)
2549 if (!manager_get_show_status(u->manager))
2552 if (!manager_is_booting_or_shutting_down(u->manager))
2555 va_start(ap, format);
2556 status_vprintf(status, true, format, ap);
2560 bool unit_need_daemon_reload(Unit *u) {
2563 if (u->fragment_path) {
2567 if (stat(u->fragment_path, &st) < 0)
2568 /* What, cannot access this anymore? */
2571 if (u->fragment_mtime > 0 &&
2572 timespec_load(&st.st_mtim) != u->fragment_mtime)
2576 if (UNIT_VTABLE(u)->need_daemon_reload)
2577 return UNIT_VTABLE(u)->need_daemon_reload(u);
2582 void unit_reset_failed(Unit *u) {
2585 if (UNIT_VTABLE(u)->reset_failed)
2586 UNIT_VTABLE(u)->reset_failed(u);
2589 Unit *unit_following(Unit *u) {
2592 if (UNIT_VTABLE(u)->following)
2593 return UNIT_VTABLE(u)->following(u);
2598 bool unit_pending_inactive(Unit *u) {
2601 /* Returns true if the unit is inactive or going down */
2603 if (UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)))
2606 if (u->job && u->job->type == JOB_STOP)
2612 bool unit_pending_active(Unit *u) {
2615 /* Returns true if the unit is active or going up */
2617 if (UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)))
2621 (u->job->type == JOB_START ||
2622 u->job->type == JOB_RELOAD_OR_START ||
2623 u->job->type == JOB_RESTART))
2629 UnitType unit_name_to_type(const char *n) {
2634 for (t = 0; t < _UNIT_TYPE_MAX; t++)
2635 if (endswith(n, unit_vtable[t]->suffix))
2638 return _UNIT_TYPE_INVALID;
2641 bool unit_name_is_valid(const char *n, bool template_ok) {
2644 t = unit_name_to_type(n);
2645 if (t < 0 || t >= _UNIT_TYPE_MAX)
2648 return unit_name_is_valid_no_type(n, template_ok);
2651 int unit_kill(Unit *u, KillWho w, KillMode m, int signo, DBusError *error) {
2653 assert(w >= 0 && w < _KILL_WHO_MAX);
2654 assert(m >= 0 && m < _KILL_MODE_MAX);
2656 assert(signo < _NSIG);
2661 if (!UNIT_VTABLE(u)->kill)
2664 return UNIT_VTABLE(u)->kill(u, w, m, signo, error);
2667 int unit_following_set(Unit *u, Set **s) {
2671 if (UNIT_VTABLE(u)->following_set)
2672 return UNIT_VTABLE(u)->following_set(u, s);
2678 UnitFileState unit_get_unit_file_state(Unit *u) {
2681 if (u->unit_file_state < 0 && u->fragment_path)
2682 u->unit_file_state = unit_file_get_state(
2683 u->manager->running_as == MANAGER_SYSTEM ? UNIT_FILE_SYSTEM : UNIT_FILE_USER,
2684 NULL, file_name_from_path(u->fragment_path));
2686 return u->unit_file_state;
2689 Unit* unit_ref_set(UnitRef *ref, Unit *u) {
2694 unit_ref_unset(ref);
2697 LIST_PREPEND(UnitRef, refs, u->refs, ref);
2701 void unit_ref_unset(UnitRef *ref) {
2707 LIST_REMOVE(UnitRef, refs, ref->unit->refs, ref);
2711 int unit_add_one_mount_link(Unit *u, Mount *m) {
2717 if (u->load_state != UNIT_LOADED ||
2718 UNIT(m)->load_state != UNIT_LOADED)
2721 STRV_FOREACH(i, u->requires_mounts_for) {
2726 if (!path_startswith(*i, m->where))
2729 return unit_add_two_dependencies(u, UNIT_AFTER, UNIT_REQUIRES, UNIT(m), true);
2735 int unit_add_mount_links(Unit *u) {
2741 LIST_FOREACH(units_by_type, other, u->manager->units_by_type[UNIT_MOUNT]) {
2742 r = unit_add_one_mount_link(u, MOUNT(other));
2750 static const char* const unit_load_state_table[_UNIT_LOAD_STATE_MAX] = {
2751 [UNIT_STUB] = "stub",
2752 [UNIT_LOADED] = "loaded",
2753 [UNIT_ERROR] = "error",
2754 [UNIT_MERGED] = "merged",
2755 [UNIT_MASKED] = "masked"
2758 DEFINE_STRING_TABLE_LOOKUP(unit_load_state, UnitLoadState);
2760 static const char* const unit_active_state_table[_UNIT_ACTIVE_STATE_MAX] = {
2761 [UNIT_ACTIVE] = "active",
2762 [UNIT_RELOADING] = "reloading",
2763 [UNIT_INACTIVE] = "inactive",
2764 [UNIT_FAILED] = "failed",
2765 [UNIT_ACTIVATING] = "activating",
2766 [UNIT_DEACTIVATING] = "deactivating"
2769 DEFINE_STRING_TABLE_LOOKUP(unit_active_state, UnitActiveState);
2771 static const char* const unit_dependency_table[_UNIT_DEPENDENCY_MAX] = {
2772 [UNIT_REQUIRES] = "Requires",
2773 [UNIT_REQUIRES_OVERRIDABLE] = "RequiresOverridable",
2774 [UNIT_WANTS] = "Wants",
2775 [UNIT_REQUISITE] = "Requisite",
2776 [UNIT_REQUISITE_OVERRIDABLE] = "RequisiteOverridable",
2777 [UNIT_REQUIRED_BY] = "RequiredBy",
2778 [UNIT_REQUIRED_BY_OVERRIDABLE] = "RequiredByOverridable",
2779 [UNIT_BIND_TO] = "BindTo",
2780 [UNIT_WANTED_BY] = "WantedBy",
2781 [UNIT_CONFLICTS] = "Conflicts",
2782 [UNIT_CONFLICTED_BY] = "ConflictedBy",
2783 [UNIT_BOUND_BY] = "BoundBy",
2784 [UNIT_BEFORE] = "Before",
2785 [UNIT_AFTER] = "After",
2786 [UNIT_REFERENCES] = "References",
2787 [UNIT_REFERENCED_BY] = "ReferencedBy",
2788 [UNIT_ON_FAILURE] = "OnFailure",
2789 [UNIT_TRIGGERS] = "Triggers",
2790 [UNIT_TRIGGERED_BY] = "TriggeredBy",
2791 [UNIT_PROPAGATE_RELOAD_TO] = "PropagateReloadTo",
2792 [UNIT_PROPAGATE_RELOAD_FROM] = "PropagateReloadFrom"
2795 DEFINE_STRING_TABLE_LOOKUP(unit_dependency, UnitDependency);