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 General Public License as published by
10 the Free Software Foundation; either version 2 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 General Public License for more details.
18 You should have received a copy of the GNU 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) {
65 if (!(u = new0(Unit, 1)))
68 if (!(u->meta.names = set_new(string_hash_func, string_compare_func))) {
74 u->meta.type = _UNIT_TYPE_INVALID;
75 u->meta.deserialized_job = _JOB_TYPE_INVALID;
76 u->meta.default_dependencies = true;
77 u->meta.unit_file_state = _UNIT_FILE_STATE_INVALID;
82 bool unit_has_name(Unit *u, const char *name) {
86 return !!set_get(u->meta.names, (char*) name);
89 int unit_add_name(Unit *u, const char *text) {
97 if (unit_name_is_template(text)) {
98 if (!u->meta.instance)
101 s = unit_name_replace_instance(text, u->meta.instance);
108 if (!unit_name_is_valid(s, false)) {
113 assert_se((t = unit_name_to_type(s)) >= 0);
115 if (u->meta.type != _UNIT_TYPE_INVALID && t != u->meta.type) {
120 if ((r = unit_name_to_instance(s, &i)) < 0)
123 if (i && unit_vtable[t]->no_instances) {
128 /* Ensure that this unit is either instanced or not instanced,
130 if (u->meta.type != _UNIT_TYPE_INVALID && !u->meta.instance != !i) {
135 if (unit_vtable[t]->no_alias &&
136 !set_isempty(u->meta.names) &&
137 !set_get(u->meta.names, s)) {
142 if (hashmap_size(u->meta.manager->units) >= MANAGER_MAX_NAMES) {
147 if ((r = set_put(u->meta.names, s)) < 0) {
153 if ((r = hashmap_put(u->meta.manager->units, s, u)) < 0) {
154 set_remove(u->meta.names, s);
158 if (u->meta.type == _UNIT_TYPE_INVALID) {
162 u->meta.instance = i;
164 LIST_PREPEND(Meta, units_by_type, u->meta.manager->units_by_type[t], &u->meta);
166 if (UNIT_VTABLE(u)->init)
167 UNIT_VTABLE(u)->init(u);
171 unit_add_to_dbus_queue(u);
181 int unit_choose_id(Unit *u, const char *name) {
182 char *s, *t = NULL, *i;
188 if (unit_name_is_template(name)) {
190 if (!u->meta.instance)
193 if (!(t = unit_name_replace_instance(name, u->meta.instance)))
199 /* Selects one of the names of this unit as the id */
200 s = set_get(u->meta.names, (char*) name);
206 if ((r = unit_name_to_instance(s, &i)) < 0)
211 free(u->meta.instance);
212 u->meta.instance = i;
214 unit_add_to_dbus_queue(u);
219 int unit_set_description(Unit *u, const char *description) {
224 if (!(s = strdup(description)))
227 free(u->meta.description);
228 u->meta.description = s;
230 unit_add_to_dbus_queue(u);
234 bool unit_check_gc(Unit *u) {
237 if (u->meta.load_state == UNIT_STUB)
240 if (UNIT_VTABLE(u)->no_gc)
249 if (unit_active_state(u) != UNIT_INACTIVE)
252 if (UNIT_VTABLE(u)->check_gc)
253 if (UNIT_VTABLE(u)->check_gc(u))
259 void unit_add_to_load_queue(Unit *u) {
261 assert(u->meta.type != _UNIT_TYPE_INVALID);
263 if (u->meta.load_state != UNIT_STUB || u->meta.in_load_queue)
266 LIST_PREPEND(Meta, load_queue, u->meta.manager->load_queue, &u->meta);
267 u->meta.in_load_queue = true;
270 void unit_add_to_cleanup_queue(Unit *u) {
273 if (u->meta.in_cleanup_queue)
276 LIST_PREPEND(Meta, cleanup_queue, u->meta.manager->cleanup_queue, &u->meta);
277 u->meta.in_cleanup_queue = true;
280 void unit_add_to_gc_queue(Unit *u) {
283 if (u->meta.in_gc_queue || u->meta.in_cleanup_queue)
286 if (unit_check_gc(u))
289 LIST_PREPEND(Meta, gc_queue, u->meta.manager->gc_queue, &u->meta);
290 u->meta.in_gc_queue = true;
292 u->meta.manager->n_in_gc_queue ++;
294 if (u->meta.manager->gc_queue_timestamp <= 0)
295 u->meta.manager->gc_queue_timestamp = now(CLOCK_MONOTONIC);
298 void unit_add_to_dbus_queue(Unit *u) {
300 assert(u->meta.type != _UNIT_TYPE_INVALID);
302 if (u->meta.load_state == UNIT_STUB || u->meta.in_dbus_queue)
305 /* Shortcut things if nobody cares */
306 if (!bus_has_subscriber(u->meta.manager)) {
307 u->meta.sent_dbus_new_signal = true;
311 LIST_PREPEND(Meta, dbus_queue, u->meta.manager->dbus_unit_queue, &u->meta);
312 u->meta.in_dbus_queue = true;
315 static void bidi_set_free(Unit *u, Set *s) {
321 /* Frees the set and makes sure we are dropped from the
322 * inverse pointers */
324 SET_FOREACH(other, s, i) {
327 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
328 set_remove(other->meta.dependencies[d], u);
330 unit_add_to_gc_queue(other);
336 void unit_free(Unit *u) {
343 bus_unit_send_removed_signal(u);
345 if (u->meta.load_state != UNIT_STUB)
346 if (UNIT_VTABLE(u)->done)
347 UNIT_VTABLE(u)->done(u);
349 SET_FOREACH(t, u->meta.names, i)
350 hashmap_remove_value(u->meta.manager->units, t, u);
353 job_free(u->meta.job);
355 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
356 bidi_set_free(u, u->meta.dependencies[d]);
358 if (u->meta.type != _UNIT_TYPE_INVALID)
359 LIST_REMOVE(Meta, units_by_type, u->meta.manager->units_by_type[u->meta.type], &u->meta);
361 if (u->meta.in_load_queue)
362 LIST_REMOVE(Meta, load_queue, u->meta.manager->load_queue, &u->meta);
364 if (u->meta.in_dbus_queue)
365 LIST_REMOVE(Meta, dbus_queue, u->meta.manager->dbus_unit_queue, &u->meta);
367 if (u->meta.in_cleanup_queue)
368 LIST_REMOVE(Meta, cleanup_queue, u->meta.manager->cleanup_queue, &u->meta);
370 if (u->meta.in_gc_queue) {
371 LIST_REMOVE(Meta, gc_queue, u->meta.manager->gc_queue, &u->meta);
372 u->meta.manager->n_in_gc_queue--;
375 cgroup_bonding_free_list(u->meta.cgroup_bondings, u->meta.manager->n_reloading <= 0);
376 cgroup_attribute_free_list(u->meta.cgroup_attributes);
378 free(u->meta.description);
379 free(u->meta.fragment_path);
381 set_free_free(u->meta.names);
383 condition_free_list(u->meta.conditions);
385 free(u->meta.instance);
389 UnitActiveState unit_active_state(Unit *u) {
392 if (u->meta.load_state == UNIT_MERGED)
393 return unit_active_state(unit_follow_merge(u));
395 /* After a reload it might happen that a unit is not correctly
396 * loaded but still has a process around. That's why we won't
397 * shortcut failed loading to UNIT_INACTIVE_FAILED. */
399 return UNIT_VTABLE(u)->active_state(u);
402 const char* unit_sub_state_to_string(Unit *u) {
405 return UNIT_VTABLE(u)->sub_state_to_string(u);
408 static void complete_move(Set **s, Set **other) {
416 set_move(*s, *other);
423 static void merge_names(Unit *u, Unit *other) {
430 complete_move(&u->meta.names, &other->meta.names);
432 set_free_free(other->meta.names);
433 other->meta.names = NULL;
434 other->meta.id = NULL;
436 SET_FOREACH(t, u->meta.names, i)
437 assert_se(hashmap_replace(u->meta.manager->units, t, u) == 0);
440 static void merge_dependencies(Unit *u, Unit *other, UnitDependency d) {
447 assert(d < _UNIT_DEPENDENCY_MAX);
449 /* Fix backwards pointers */
450 SET_FOREACH(back, other->meta.dependencies[d], i) {
453 for (k = 0; k < _UNIT_DEPENDENCY_MAX; k++)
454 if ((r = set_remove_and_put(back->meta.dependencies[k], other, u)) < 0) {
457 set_remove(back->meta.dependencies[k], other);
459 assert(r == -ENOENT);
463 complete_move(&u->meta.dependencies[d], &other->meta.dependencies[d]);
465 set_free(other->meta.dependencies[d]);
466 other->meta.dependencies[d] = NULL;
469 int unit_merge(Unit *u, Unit *other) {
474 assert(u->meta.manager == other->meta.manager);
475 assert(u->meta.type != _UNIT_TYPE_INVALID);
477 other = unit_follow_merge(other);
482 if (u->meta.type != other->meta.type)
485 if (!u->meta.instance != !other->meta.instance)
488 if (other->meta.load_state != UNIT_STUB &&
489 other->meta.load_state != UNIT_ERROR)
495 if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other)))
499 merge_names(u, other);
501 /* Merge dependencies */
502 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
503 merge_dependencies(u, other, d);
505 other->meta.load_state = UNIT_MERGED;
506 other->meta.merged_into = u;
508 /* If there is still some data attached to the other node, we
509 * don't need it anymore, and can free it. */
510 if (other->meta.load_state != UNIT_STUB)
511 if (UNIT_VTABLE(other)->done)
512 UNIT_VTABLE(other)->done(other);
514 unit_add_to_dbus_queue(u);
515 unit_add_to_cleanup_queue(other);
520 int unit_merge_by_name(Unit *u, const char *name) {
528 if (unit_name_is_template(name)) {
529 if (!u->meta.instance)
532 if (!(s = unit_name_replace_instance(name, u->meta.instance)))
538 if (!(other = manager_get_unit(u->meta.manager, name)))
539 r = unit_add_name(u, name);
541 r = unit_merge(u, other);
547 Unit* unit_follow_merge(Unit *u) {
550 while (u->meta.load_state == UNIT_MERGED)
551 assert_se(u = u->meta.merged_into);
556 int unit_add_exec_dependencies(Unit *u, ExecContext *c) {
562 if (c->std_output != EXEC_OUTPUT_KMSG &&
563 c->std_output != EXEC_OUTPUT_SYSLOG &&
564 c->std_output != EXEC_OUTPUT_KMSG_AND_CONSOLE &&
565 c->std_output != EXEC_OUTPUT_SYSLOG_AND_CONSOLE &&
566 c->std_error != EXEC_OUTPUT_KMSG &&
567 c->std_error != EXEC_OUTPUT_SYSLOG_AND_CONSOLE &&
568 c->std_error != EXEC_OUTPUT_KMSG &&
569 c->std_error != EXEC_OUTPUT_SYSLOG_AND_CONSOLE)
572 /* If syslog or kernel logging is requested, make sure our own
573 * logging daemon is run first. */
575 if (u->meta.manager->running_as == MANAGER_SYSTEM)
576 if ((r = unit_add_two_dependencies_by_name(u, UNIT_REQUIRES, UNIT_AFTER, SPECIAL_STDOUT_SYSLOG_BRIDGE_SOCKET, NULL, true)) < 0)
582 const char *unit_description(Unit *u) {
585 if (u->meta.description)
586 return u->meta.description;
588 return strna(u->meta.id);
591 void unit_dump(Unit *u, FILE *f, const char *prefix) {
598 timestamp1[FORMAT_TIMESTAMP_MAX],
599 timestamp2[FORMAT_TIMESTAMP_MAX],
600 timestamp3[FORMAT_TIMESTAMP_MAX],
601 timestamp4[FORMAT_TIMESTAMP_MAX],
602 timespan[FORMAT_TIMESPAN_MAX];
606 assert(u->meta.type >= 0);
610 p2 = strappend(prefix, "\t");
611 prefix2 = p2 ? p2 : prefix;
615 "%s\tDescription: %s\n"
617 "%s\tUnit Load State: %s\n"
618 "%s\tUnit Active State: %s\n"
619 "%s\tInactive Exit Timestamp: %s\n"
620 "%s\tActive Enter Timestamp: %s\n"
621 "%s\tActive Exit Timestamp: %s\n"
622 "%s\tInactive Enter Timestamp: %s\n"
623 "%s\tGC Check Good: %s\n"
624 "%s\tNeed Daemon Reload: %s\n",
626 prefix, unit_description(u),
627 prefix, strna(u->meta.instance),
628 prefix, unit_load_state_to_string(u->meta.load_state),
629 prefix, unit_active_state_to_string(unit_active_state(u)),
630 prefix, strna(format_timestamp(timestamp1, sizeof(timestamp1), u->meta.inactive_exit_timestamp.realtime)),
631 prefix, strna(format_timestamp(timestamp2, sizeof(timestamp2), u->meta.active_enter_timestamp.realtime)),
632 prefix, strna(format_timestamp(timestamp3, sizeof(timestamp3), u->meta.active_exit_timestamp.realtime)),
633 prefix, strna(format_timestamp(timestamp4, sizeof(timestamp4), u->meta.inactive_enter_timestamp.realtime)),
634 prefix, yes_no(unit_check_gc(u)),
635 prefix, yes_no(unit_need_daemon_reload(u)));
637 SET_FOREACH(t, u->meta.names, i)
638 fprintf(f, "%s\tName: %s\n", prefix, t);
640 if ((following = unit_following(u)))
641 fprintf(f, "%s\tFollowing: %s\n", prefix, following->meta.id);
643 if (u->meta.fragment_path)
644 fprintf(f, "%s\tFragment Path: %s\n", prefix, u->meta.fragment_path);
646 if (u->meta.job_timeout > 0)
647 fprintf(f, "%s\tJob Timeout: %s\n", prefix, format_timespan(timespan, sizeof(timespan), u->meta.job_timeout));
649 condition_dump_list(u->meta.conditions, f, prefix);
651 if (dual_timestamp_is_set(&u->meta.condition_timestamp))
653 "%s\tCondition Timestamp: %s\n"
654 "%s\tCondition Result: %s\n",
655 prefix, strna(format_timestamp(timestamp1, sizeof(timestamp1), u->meta.condition_timestamp.realtime)),
656 prefix, yes_no(u->meta.condition_result));
658 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++) {
661 SET_FOREACH(other, u->meta.dependencies[d], i)
662 fprintf(f, "%s\t%s: %s\n", prefix, unit_dependency_to_string(d), other->meta.id);
665 if (u->meta.load_state == UNIT_LOADED) {
670 "%s\tStopWhenUnneeded: %s\n"
671 "%s\tRefuseManualStart: %s\n"
672 "%s\tRefuseManualStop: %s\n"
673 "%s\tDefaultDependencies: %s\n"
674 "%s\tOnFailureIsolate: %s\n"
675 "%s\tIgnoreOnIsolate: %s\n"
676 "%s\tIgnoreOnSnapshot: %s\n",
677 prefix, yes_no(u->meta.stop_when_unneeded),
678 prefix, yes_no(u->meta.refuse_manual_start),
679 prefix, yes_no(u->meta.refuse_manual_stop),
680 prefix, yes_no(u->meta.default_dependencies),
681 prefix, yes_no(u->meta.on_failure_isolate),
682 prefix, yes_no(u->meta.ignore_on_isolate),
683 prefix, yes_no(u->meta.ignore_on_snapshot));
685 LIST_FOREACH(by_unit, b, u->meta.cgroup_bondings)
686 fprintf(f, "%s\tControlGroup: %s:%s\n",
687 prefix, b->controller, b->path);
689 LIST_FOREACH(by_unit, a, u->meta.cgroup_attributes) {
693 a->map_callback(a->controller, a->name, a->value, &v);
695 fprintf(f, "%s\tControlGroupAttribute: %s %s \"%s\"\n",
696 prefix, a->controller, a->name, v ? v : a->value);
701 if (UNIT_VTABLE(u)->dump)
702 UNIT_VTABLE(u)->dump(u, f, prefix2);
704 } else if (u->meta.load_state == UNIT_MERGED)
706 "%s\tMerged into: %s\n",
707 prefix, u->meta.merged_into->meta.id);
708 else if (u->meta.load_state == UNIT_ERROR)
709 fprintf(f, "%s\tLoad Error Code: %s\n", prefix, strerror(-u->meta.load_error));
713 job_dump(u->meta.job, f, prefix2);
718 /* Common implementation for multiple backends */
719 int unit_load_fragment_and_dropin(Unit *u) {
724 /* Load a .service file */
725 if ((r = unit_load_fragment(u)) < 0)
728 if (u->meta.load_state == UNIT_STUB)
731 /* Load drop-in directory data */
732 if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
738 /* Common implementation for multiple backends */
739 int unit_load_fragment_and_dropin_optional(Unit *u) {
744 /* Same as unit_load_fragment_and_dropin(), but whether
745 * something can be loaded or not doesn't matter. */
747 /* Load a .service file */
748 if ((r = unit_load_fragment(u)) < 0)
751 if (u->meta.load_state == UNIT_STUB)
752 u->meta.load_state = UNIT_LOADED;
754 /* Load drop-in directory data */
755 if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
761 int unit_add_default_target_dependency(Unit *u, Unit *target) {
765 if (target->meta.type != UNIT_TARGET)
768 /* Only add the dependency if both units are loaded, so that
769 * that loop check below is reliable */
770 if (u->meta.load_state != UNIT_LOADED ||
771 target->meta.load_state != UNIT_LOADED)
774 /* If either side wants no automatic dependencies, then let's
776 if (!u->meta.default_dependencies ||
777 target->meta.default_dependencies)
780 /* Don't create loops */
781 if (set_get(target->meta.dependencies[UNIT_BEFORE], u))
784 return unit_add_dependency(target, UNIT_AFTER, u, true);
787 static int unit_add_default_dependencies(Unit *u) {
788 static const UnitDependency deps[] = {
790 UNIT_REQUIRED_BY_OVERRIDABLE,
802 for (k = 0; k < ELEMENTSOF(deps); k++)
803 SET_FOREACH(target, u->meta.dependencies[deps[k]], i)
804 if ((r = unit_add_default_target_dependency(u, target)) < 0)
810 int unit_load(Unit *u) {
815 if (u->meta.in_load_queue) {
816 LIST_REMOVE(Meta, load_queue, u->meta.manager->load_queue, &u->meta);
817 u->meta.in_load_queue = false;
820 if (u->meta.type == _UNIT_TYPE_INVALID)
823 if (u->meta.load_state != UNIT_STUB)
826 if (UNIT_VTABLE(u)->load)
827 if ((r = UNIT_VTABLE(u)->load(u)) < 0)
830 if (u->meta.load_state == UNIT_STUB) {
835 if (u->meta.load_state == UNIT_LOADED &&
836 u->meta.default_dependencies)
837 if ((r = unit_add_default_dependencies(u)) < 0)
840 if (u->meta.on_failure_isolate &&
841 set_size(u->meta.dependencies[UNIT_ON_FAILURE]) > 1) {
843 log_error("More than one OnFailure= dependencies specified for %s but OnFailureIsolate= enabled. Refusing.",
850 assert((u->meta.load_state != UNIT_MERGED) == !u->meta.merged_into);
852 unit_add_to_dbus_queue(unit_follow_merge(u));
853 unit_add_to_gc_queue(u);
858 u->meta.load_state = UNIT_ERROR;
859 u->meta.load_error = r;
860 unit_add_to_dbus_queue(u);
862 log_debug("Failed to load configuration for %s: %s", u->meta.id, strerror(-r));
867 bool unit_condition_test(Unit *u) {
870 dual_timestamp_get(&u->meta.condition_timestamp);
871 u->meta.condition_result = condition_test_list(u->meta.conditions);
873 return u->meta.condition_result;
877 * -EBADR: This unit type does not support starting.
878 * -EALREADY: Unit is already started.
879 * -EAGAIN: An operation is already in progress. Retry later.
880 * -ECANCELED: Too many requests for now.
882 int unit_start(Unit *u) {
883 UnitActiveState state;
888 if (u->meta.load_state != UNIT_LOADED)
891 /* If this is already (being) started, then this will
892 * succeed. Note that this will even succeed if this unit is
893 * not startable by the user. This is relied on to detect when
894 * we need to wait for units and when waiting is finished. */
895 state = unit_active_state(u);
896 if (UNIT_IS_ACTIVE_OR_RELOADING(state))
899 /* If the conditions failed, don't do anything at all */
900 if (!unit_condition_test(u)) {
901 log_debug("Starting of %s requested but condition failed. Ignoring.", u->meta.id);
905 /* Forward to the main object, if we aren't it. */
906 if ((following = unit_following(u))) {
907 log_debug("Redirecting start request from %s to %s.", u->meta.id, following->meta.id);
908 return unit_start(following);
911 /* If it is stopped, but we cannot start it, then fail */
912 if (!UNIT_VTABLE(u)->start)
915 /* We don't suppress calls to ->start() here when we are
916 * already starting, to allow this request to be used as a
917 * "hurry up" call, for example when the unit is in some "auto
918 * restart" state where it waits for a holdoff timer to elapse
919 * before it will start again. */
921 unit_add_to_dbus_queue(u);
923 unit_status_printf(u, "Starting %s...\n", unit_description(u));
924 return UNIT_VTABLE(u)->start(u);
927 bool unit_can_start(Unit *u) {
930 return !!UNIT_VTABLE(u)->start;
933 bool unit_can_isolate(Unit *u) {
936 return unit_can_start(u) &&
937 u->meta.allow_isolate;
941 * -EBADR: This unit type does not support stopping.
942 * -EALREADY: Unit is already stopped.
943 * -EAGAIN: An operation is already in progress. Retry later.
945 int unit_stop(Unit *u) {
946 UnitActiveState state;
951 state = unit_active_state(u);
952 if (UNIT_IS_INACTIVE_OR_FAILED(state))
955 if ((following = unit_following(u))) {
956 log_debug("Redirecting stop request from %s to %s.", u->meta.id, following->meta.id);
957 return unit_stop(following);
960 if (!UNIT_VTABLE(u)->stop)
963 unit_add_to_dbus_queue(u);
965 unit_status_printf(u, "Stopping %s...\n", unit_description(u));
966 return UNIT_VTABLE(u)->stop(u);
970 * -EBADR: This unit type does not support reloading.
971 * -ENOEXEC: Unit is not started.
972 * -EAGAIN: An operation is already in progress. Retry later.
974 int unit_reload(Unit *u) {
975 UnitActiveState state;
980 if (u->meta.load_state != UNIT_LOADED)
983 if (!unit_can_reload(u))
986 state = unit_active_state(u);
987 if (state == UNIT_RELOADING)
990 if (state != UNIT_ACTIVE)
993 if ((following = unit_following(u))) {
994 log_debug("Redirecting reload request from %s to %s.", u->meta.id, following->meta.id);
995 return unit_reload(following);
998 unit_add_to_dbus_queue(u);
999 return UNIT_VTABLE(u)->reload(u);
1002 bool unit_can_reload(Unit *u) {
1005 if (!UNIT_VTABLE(u)->reload)
1008 if (!UNIT_VTABLE(u)->can_reload)
1011 return UNIT_VTABLE(u)->can_reload(u);
1014 static void unit_check_unneeded(Unit *u) {
1020 /* If this service shall be shut down when unneeded then do
1023 if (!u->meta.stop_when_unneeded)
1026 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)))
1029 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRED_BY], i)
1030 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1033 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRED_BY_OVERRIDABLE], i)
1034 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1037 SET_FOREACH(other, u->meta.dependencies[UNIT_WANTED_BY], i)
1038 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1041 SET_FOREACH(other, u->meta.dependencies[UNIT_BOUND_BY], i)
1042 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1045 log_info("Service %s is not needed anymore. Stopping.", u->meta.id);
1047 /* Ok, nobody needs us anymore. Sniff. Then let's commit suicide */
1048 manager_add_job(u->meta.manager, JOB_STOP, u, JOB_FAIL, true, NULL, NULL);
1051 static void retroactively_start_dependencies(Unit *u) {
1056 assert(UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)));
1058 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRES], i)
1059 if (!set_get(u->meta.dependencies[UNIT_AFTER], other) &&
1060 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
1061 manager_add_job(u->meta.manager, JOB_START, other, JOB_REPLACE, true, NULL, NULL);
1063 SET_FOREACH(other, u->meta.dependencies[UNIT_BIND_TO], i)
1064 if (!set_get(u->meta.dependencies[UNIT_AFTER], other) &&
1065 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
1066 manager_add_job(u->meta.manager, JOB_START, other, JOB_REPLACE, true, NULL, NULL);
1068 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRES_OVERRIDABLE], i)
1069 if (!set_get(u->meta.dependencies[UNIT_AFTER], other) &&
1070 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
1071 manager_add_job(u->meta.manager, JOB_START, other, JOB_FAIL, false, NULL, NULL);
1073 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUISITE], i)
1074 if (!set_get(u->meta.dependencies[UNIT_AFTER], other) &&
1075 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
1076 manager_add_job(u->meta.manager, JOB_START, other, JOB_REPLACE, true, NULL, NULL);
1078 SET_FOREACH(other, u->meta.dependencies[UNIT_WANTS], i)
1079 if (!set_get(u->meta.dependencies[UNIT_AFTER], other) &&
1080 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
1081 manager_add_job(u->meta.manager, JOB_START, other, JOB_FAIL, false, NULL, NULL);
1083 SET_FOREACH(other, u->meta.dependencies[UNIT_CONFLICTS], i)
1084 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1085 manager_add_job(u->meta.manager, JOB_STOP, other, JOB_REPLACE, true, NULL, NULL);
1087 SET_FOREACH(other, u->meta.dependencies[UNIT_CONFLICTED_BY], i)
1088 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1089 manager_add_job(u->meta.manager, JOB_STOP, other, JOB_REPLACE, true, NULL, NULL);
1092 static void retroactively_stop_dependencies(Unit *u) {
1097 assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)));
1099 /* Pull down units which are bound to us recursively if enabled */
1100 SET_FOREACH(other, u->meta.dependencies[UNIT_BOUND_BY], i)
1101 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1102 manager_add_job(u->meta.manager, JOB_STOP, other, JOB_REPLACE, true, NULL, NULL);
1104 /* Garbage collect services that might not be needed anymore, if enabled */
1105 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRES], i)
1106 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1107 unit_check_unneeded(other);
1108 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRES_OVERRIDABLE], i)
1109 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1110 unit_check_unneeded(other);
1111 SET_FOREACH(other, u->meta.dependencies[UNIT_WANTS], i)
1112 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1113 unit_check_unneeded(other);
1114 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUISITE], i)
1115 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1116 unit_check_unneeded(other);
1117 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUISITE_OVERRIDABLE], i)
1118 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1119 unit_check_unneeded(other);
1120 SET_FOREACH(other, u->meta.dependencies[UNIT_BIND_TO], i)
1121 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1122 unit_check_unneeded(other);
1125 void unit_trigger_on_failure(Unit *u) {
1131 if (set_size(u->meta.dependencies[UNIT_ON_FAILURE]) <= 0)
1134 log_info("Triggering OnFailure= dependencies of %s.", u->meta.id);
1136 SET_FOREACH(other, u->meta.dependencies[UNIT_ON_FAILURE], i) {
1139 if ((r = manager_add_job(u->meta.manager, JOB_START, other, u->meta.on_failure_isolate ? JOB_ISOLATE : JOB_REPLACE, true, NULL, NULL)) < 0)
1140 log_error("Failed to enqueue OnFailure= job: %s", strerror(-r));
1144 void unit_notify(Unit *u, UnitActiveState os, UnitActiveState ns, bool reload_success) {
1148 assert(os < _UNIT_ACTIVE_STATE_MAX);
1149 assert(ns < _UNIT_ACTIVE_STATE_MAX);
1151 /* Note that this is called for all low-level state changes,
1152 * even if they might map to the same high-level
1153 * UnitActiveState! That means that ns == os is OK an expected
1154 * behaviour here. For example: if a mount point is remounted
1155 * this function will be called too! */
1157 if (u->meta.manager->n_reloading <= 0) {
1160 dual_timestamp_get(&ts);
1162 if (UNIT_IS_INACTIVE_OR_FAILED(os) && !UNIT_IS_INACTIVE_OR_FAILED(ns))
1163 u->meta.inactive_exit_timestamp = ts;
1164 else if (!UNIT_IS_INACTIVE_OR_FAILED(os) && UNIT_IS_INACTIVE_OR_FAILED(ns))
1165 u->meta.inactive_enter_timestamp = ts;
1167 if (!UNIT_IS_ACTIVE_OR_RELOADING(os) && UNIT_IS_ACTIVE_OR_RELOADING(ns))
1168 u->meta.active_enter_timestamp = ts;
1169 else if (UNIT_IS_ACTIVE_OR_RELOADING(os) && !UNIT_IS_ACTIVE_OR_RELOADING(ns))
1170 u->meta.active_exit_timestamp = ts;
1172 timer_unit_notify(u, ns);
1173 path_unit_notify(u, ns);
1176 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
1177 cgroup_bonding_trim_list(u->meta.cgroup_bondings, true);
1182 if (u->meta.job->state == JOB_WAITING)
1184 /* So we reached a different state for this
1185 * job. Let's see if we can run it now if it
1186 * failed previously due to EAGAIN. */
1187 job_add_to_run_queue(u->meta.job);
1189 /* Let's check whether this state change constitutes a
1190 * finished job, or maybe contradicts a running job and
1191 * hence needs to invalidate jobs. */
1193 switch (u->meta.job->type) {
1196 case JOB_VERIFY_ACTIVE:
1198 if (UNIT_IS_ACTIVE_OR_RELOADING(ns))
1199 job_finish_and_invalidate(u->meta.job, JOB_DONE);
1200 else if (u->meta.job->state == JOB_RUNNING && ns != UNIT_ACTIVATING) {
1203 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
1204 job_finish_and_invalidate(u->meta.job, ns == UNIT_FAILED ? JOB_FAILED : JOB_DONE);
1210 case JOB_RELOAD_OR_START:
1212 if (u->meta.job->state == JOB_RUNNING) {
1213 if (ns == UNIT_ACTIVE)
1214 job_finish_and_invalidate(u->meta.job, reload_success ? JOB_DONE : JOB_FAILED);
1215 else if (ns != UNIT_ACTIVATING && ns != UNIT_RELOADING) {
1218 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
1219 job_finish_and_invalidate(u->meta.job, ns == UNIT_FAILED ? JOB_FAILED : JOB_DONE);
1227 case JOB_TRY_RESTART:
1229 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
1230 job_finish_and_invalidate(u->meta.job, JOB_DONE);
1231 else if (u->meta.job->state == JOB_RUNNING && ns != UNIT_DEACTIVATING) {
1233 job_finish_and_invalidate(u->meta.job, JOB_FAILED);
1239 assert_not_reached("Job type unknown");
1245 if (u->meta.manager->n_reloading <= 0) {
1247 /* If this state change happened without being
1248 * requested by a job, then let's retroactively start
1249 * or stop dependencies. We skip that step when
1250 * deserializing, since we don't want to create any
1251 * additional jobs just because something is already
1255 if (UNIT_IS_INACTIVE_OR_FAILED(os) && UNIT_IS_ACTIVE_OR_ACTIVATING(ns))
1256 retroactively_start_dependencies(u);
1257 else if (UNIT_IS_ACTIVE_OR_ACTIVATING(os) && UNIT_IS_INACTIVE_OR_DEACTIVATING(ns))
1258 retroactively_stop_dependencies(u);
1261 if (ns != os && ns == UNIT_FAILED) {
1262 log_notice("Unit %s entered failed state.", u->meta.id);
1263 unit_trigger_on_failure(u);
1267 /* Some names are special */
1268 if (UNIT_IS_ACTIVE_OR_RELOADING(ns)) {
1270 if (unit_has_name(u, SPECIAL_DBUS_SERVICE))
1271 /* The bus just might have become available,
1272 * hence try to connect to it, if we aren't
1274 bus_init(u->meta.manager, true);
1276 if (u->meta.type == UNIT_SERVICE &&
1277 !UNIT_IS_ACTIVE_OR_RELOADING(os) &&
1278 u->meta.manager->n_reloading <= 0) {
1279 /* Write audit record if we have just finished starting up */
1280 manager_send_unit_audit(u->meta.manager, u, AUDIT_SERVICE_START, true);
1281 u->meta.in_audit = true;
1284 if (!UNIT_IS_ACTIVE_OR_RELOADING(os))
1285 manager_send_unit_plymouth(u->meta.manager, u);
1289 /* We don't care about D-Bus here, since we'll get an
1290 * asynchronous notification for it anyway. */
1292 if (u->meta.type == UNIT_SERVICE &&
1293 UNIT_IS_INACTIVE_OR_FAILED(ns) &&
1294 !UNIT_IS_INACTIVE_OR_FAILED(os) &&
1295 u->meta.manager->n_reloading <= 0) {
1297 /* Hmm, if there was no start record written
1298 * write it now, so that we always have a nice
1300 if (!u->meta.in_audit) {
1301 manager_send_unit_audit(u->meta.manager, u, AUDIT_SERVICE_START, ns == UNIT_INACTIVE);
1303 if (ns == UNIT_INACTIVE)
1304 manager_send_unit_audit(u->meta.manager, u, AUDIT_SERVICE_STOP, true);
1306 /* Write audit record if we have just finished shutting down */
1307 manager_send_unit_audit(u->meta.manager, u, AUDIT_SERVICE_STOP, ns == UNIT_INACTIVE);
1309 u->meta.in_audit = false;
1313 manager_recheck_syslog(u->meta.manager);
1315 /* Maybe we finished startup and are now ready for being
1316 * stopped because unneeded? */
1317 unit_check_unneeded(u);
1319 unit_add_to_dbus_queue(u);
1320 unit_add_to_gc_queue(u);
1323 int unit_watch_fd(Unit *u, int fd, uint32_t events, Watch *w) {
1324 struct epoll_event ev;
1329 assert(w->type == WATCH_INVALID || (w->type == WATCH_FD && w->fd == fd && w->data.unit == u));
1335 if (epoll_ctl(u->meta.manager->epoll_fd,
1336 w->type == WATCH_INVALID ? EPOLL_CTL_ADD : EPOLL_CTL_MOD,
1348 void unit_unwatch_fd(Unit *u, Watch *w) {
1352 if (w->type == WATCH_INVALID)
1355 assert(w->type == WATCH_FD);
1356 assert(w->data.unit == u);
1357 assert_se(epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_DEL, w->fd, NULL) >= 0);
1360 w->type = WATCH_INVALID;
1361 w->data.unit = NULL;
1364 int unit_watch_pid(Unit *u, pid_t pid) {
1368 /* Watch a specific PID. We only support one unit watching
1369 * each PID for now. */
1371 return hashmap_put(u->meta.manager->watch_pids, LONG_TO_PTR(pid), u);
1374 void unit_unwatch_pid(Unit *u, pid_t pid) {
1378 hashmap_remove_value(u->meta.manager->watch_pids, LONG_TO_PTR(pid), u);
1381 int unit_watch_timer(Unit *u, usec_t delay, Watch *w) {
1382 struct itimerspec its;
1388 assert(w->type == WATCH_INVALID || (w->type == WATCH_UNIT_TIMER && w->data.unit == u));
1390 /* This will try to reuse the old timer if there is one */
1392 if (w->type == WATCH_UNIT_TIMER) {
1393 assert(w->data.unit == u);
1398 } else if (w->type == WATCH_INVALID) {
1401 if ((fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK|TFD_CLOEXEC)) < 0)
1404 assert_not_reached("Invalid watch type");
1409 /* Set absolute time in the past, but not 0, since we
1410 * don't want to disarm the timer */
1411 its.it_value.tv_sec = 0;
1412 its.it_value.tv_nsec = 1;
1414 flags = TFD_TIMER_ABSTIME;
1416 timespec_store(&its.it_value, delay);
1420 /* This will also flush the elapse counter */
1421 if (timerfd_settime(fd, flags, &its, NULL) < 0)
1424 if (w->type == WATCH_INVALID) {
1425 struct epoll_event ev;
1429 ev.events = EPOLLIN;
1431 if (epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0)
1435 w->type = WATCH_UNIT_TIMER;
1443 close_nointr_nofail(fd);
1448 void unit_unwatch_timer(Unit *u, Watch *w) {
1452 if (w->type == WATCH_INVALID)
1455 assert(w->type == WATCH_UNIT_TIMER);
1456 assert(w->data.unit == u);
1459 assert_se(epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_DEL, w->fd, NULL) >= 0);
1460 close_nointr_nofail(w->fd);
1463 w->type = WATCH_INVALID;
1464 w->data.unit = NULL;
1467 bool unit_job_is_applicable(Unit *u, JobType j) {
1469 assert(j >= 0 && j < _JOB_TYPE_MAX);
1473 case JOB_VERIFY_ACTIVE:
1479 case JOB_TRY_RESTART:
1480 return unit_can_start(u);
1483 return unit_can_reload(u);
1485 case JOB_RELOAD_OR_START:
1486 return unit_can_reload(u) && unit_can_start(u);
1489 assert_not_reached("Invalid job type");
1493 int unit_add_dependency(Unit *u, UnitDependency d, Unit *other, bool add_reference) {
1495 static const UnitDependency inverse_table[_UNIT_DEPENDENCY_MAX] = {
1496 [UNIT_REQUIRES] = UNIT_REQUIRED_BY,
1497 [UNIT_REQUIRES_OVERRIDABLE] = UNIT_REQUIRED_BY_OVERRIDABLE,
1498 [UNIT_WANTS] = UNIT_WANTED_BY,
1499 [UNIT_REQUISITE] = UNIT_REQUIRED_BY,
1500 [UNIT_REQUISITE_OVERRIDABLE] = UNIT_REQUIRED_BY_OVERRIDABLE,
1501 [UNIT_BIND_TO] = UNIT_BOUND_BY,
1502 [UNIT_REQUIRED_BY] = _UNIT_DEPENDENCY_INVALID,
1503 [UNIT_REQUIRED_BY_OVERRIDABLE] = _UNIT_DEPENDENCY_INVALID,
1504 [UNIT_WANTED_BY] = _UNIT_DEPENDENCY_INVALID,
1505 [UNIT_BOUND_BY] = UNIT_BIND_TO,
1506 [UNIT_CONFLICTS] = UNIT_CONFLICTED_BY,
1507 [UNIT_CONFLICTED_BY] = UNIT_CONFLICTS,
1508 [UNIT_BEFORE] = UNIT_AFTER,
1509 [UNIT_AFTER] = UNIT_BEFORE,
1510 [UNIT_ON_FAILURE] = _UNIT_DEPENDENCY_INVALID,
1511 [UNIT_REFERENCES] = UNIT_REFERENCED_BY,
1512 [UNIT_REFERENCED_BY] = UNIT_REFERENCES
1514 int r, q = 0, v = 0, w = 0;
1517 assert(d >= 0 && d < _UNIT_DEPENDENCY_MAX);
1520 u = unit_follow_merge(u);
1521 other = unit_follow_merge(other);
1523 /* We won't allow dependencies on ourselves. We will not
1524 * consider them an error however. */
1528 if ((r = set_ensure_allocated(&u->meta.dependencies[d], trivial_hash_func, trivial_compare_func)) < 0)
1531 if (inverse_table[d] != _UNIT_DEPENDENCY_INVALID)
1532 if ((r = set_ensure_allocated(&other->meta.dependencies[inverse_table[d]], trivial_hash_func, trivial_compare_func)) < 0)
1536 if ((r = set_ensure_allocated(&u->meta.dependencies[UNIT_REFERENCES], trivial_hash_func, trivial_compare_func)) < 0 ||
1537 (r = set_ensure_allocated(&other->meta.dependencies[UNIT_REFERENCED_BY], trivial_hash_func, trivial_compare_func)) < 0)
1540 if ((q = set_put(u->meta.dependencies[d], other)) < 0)
1543 if (inverse_table[d] != _UNIT_DEPENDENCY_INVALID)
1544 if ((v = set_put(other->meta.dependencies[inverse_table[d]], u)) < 0) {
1549 if (add_reference) {
1550 if ((w = set_put(u->meta.dependencies[UNIT_REFERENCES], other)) < 0) {
1555 if ((r = set_put(other->meta.dependencies[UNIT_REFERENCED_BY], u)) < 0)
1559 unit_add_to_dbus_queue(u);
1564 set_remove(u->meta.dependencies[d], other);
1567 set_remove(other->meta.dependencies[inverse_table[d]], u);
1570 set_remove(u->meta.dependencies[UNIT_REFERENCES], other);
1575 int unit_add_two_dependencies(Unit *u, UnitDependency d, UnitDependency e, Unit *other, bool add_reference) {
1580 if ((r = unit_add_dependency(u, d, other, add_reference)) < 0)
1583 if ((r = unit_add_dependency(u, e, other, add_reference)) < 0)
1589 static const char *resolve_template(Unit *u, const char *name, const char*path, char **p) {
1593 assert(name || path);
1596 name = file_name_from_path(path);
1598 if (!unit_name_is_template(name)) {
1603 if (u->meta.instance)
1604 s = unit_name_replace_instance(name, u->meta.instance);
1608 if (!(i = unit_name_to_prefix(u->meta.id)))
1611 s = unit_name_replace_instance(name, i);
1622 int unit_add_dependency_by_name(Unit *u, UnitDependency d, const char *name, const char *path, bool add_reference) {
1628 assert(name || path);
1630 if (!(name = resolve_template(u, name, path, &s)))
1633 if ((r = manager_load_unit(u->meta.manager, name, path, NULL, &other)) < 0)
1636 r = unit_add_dependency(u, d, other, add_reference);
1643 int unit_add_two_dependencies_by_name(Unit *u, UnitDependency d, UnitDependency e, const char *name, const char *path, bool add_reference) {
1649 assert(name || path);
1651 if (!(name = resolve_template(u, name, path, &s)))
1654 if ((r = manager_load_unit(u->meta.manager, name, path, NULL, &other)) < 0)
1657 r = unit_add_two_dependencies(u, d, e, other, add_reference);
1664 int unit_add_dependency_by_name_inverse(Unit *u, UnitDependency d, const char *name, const char *path, bool add_reference) {
1670 assert(name || path);
1672 if (!(name = resolve_template(u, name, path, &s)))
1675 if ((r = manager_load_unit(u->meta.manager, name, path, NULL, &other)) < 0)
1678 r = unit_add_dependency(other, d, u, add_reference);
1685 int unit_add_two_dependencies_by_name_inverse(Unit *u, UnitDependency d, UnitDependency e, const char *name, const char *path, bool add_reference) {
1691 assert(name || path);
1693 if (!(name = resolve_template(u, name, path, &s)))
1696 if ((r = manager_load_unit(u->meta.manager, name, path, NULL, &other)) < 0)
1699 if ((r = unit_add_two_dependencies(other, d, e, u, add_reference)) < 0)
1707 int set_unit_path(const char *p) {
1711 /* This is mostly for debug purposes */
1713 if (path_is_absolute(p)) {
1714 if (!(c = strdup(p)))
1717 if (!(cwd = get_current_dir_name()))
1720 r = asprintf(&c, "%s/%s", cwd, p);
1727 if (setenv("SYSTEMD_UNIT_PATH", c, 0) < 0) {
1736 char *unit_dbus_path(Unit *u) {
1744 if (!(e = bus_path_escape(u->meta.id)))
1747 p = strappend("/org/freedesktop/systemd1/unit/", e);
1753 int unit_add_cgroup(Unit *u, CGroupBonding *b) {
1761 if (!b->controller) {
1762 if (!(b->controller = strdup(SYSTEMD_CGROUP_CONTROLLER)))
1768 /* Ensure this hasn't been added yet */
1771 if (streq(b->controller, SYSTEMD_CGROUP_CONTROLLER)) {
1774 l = hashmap_get(u->meta.manager->cgroup_bondings, b->path);
1775 LIST_PREPEND(CGroupBonding, by_path, l, b);
1777 if ((r = hashmap_replace(u->meta.manager->cgroup_bondings, b->path, l)) < 0) {
1778 LIST_REMOVE(CGroupBonding, by_path, l, b);
1783 LIST_PREPEND(CGroupBonding, by_unit, u->meta.cgroup_bondings, b);
1789 static char *default_cgroup_path(Unit *u) {
1794 if (u->meta.instance) {
1797 t = unit_name_template(u->meta.id);
1801 p = join(u->meta.manager->cgroup_hierarchy, "/", t, "/", u->meta.instance, NULL);
1804 p = join(u->meta.manager->cgroup_hierarchy, "/", u->meta.id, NULL);
1809 int unit_add_cgroup_from_text(Unit *u, const char *name) {
1810 char *controller = NULL, *path = NULL;
1811 CGroupBonding *b = NULL;
1818 if ((r = cg_split_spec(name, &controller, &path)) < 0)
1822 path = default_cgroup_path(u);
1827 controller = strdup(SYSTEMD_CGROUP_CONTROLLER);
1831 if (!path || !controller) {
1838 if (cgroup_bonding_find_list(u->meta.cgroup_bondings, controller)) {
1843 if (!(b = new0(CGroupBonding, 1))) {
1848 b->controller = controller;
1851 b->essential = streq(controller, SYSTEMD_CGROUP_CONTROLLER);
1853 if ((r = unit_add_cgroup(u, b)) < 0)
1866 static int unit_add_one_default_cgroup(Unit *u, const char *controller) {
1867 CGroupBonding *b = NULL;
1873 controller = SYSTEMD_CGROUP_CONTROLLER;
1875 if (cgroup_bonding_find_list(u->meta.cgroup_bondings, controller))
1878 if (!(b = new0(CGroupBonding, 1)))
1881 if (!(b->controller = strdup(controller)))
1884 if (!(b->path = default_cgroup_path(u)))
1888 b->essential = streq(controller, SYSTEMD_CGROUP_CONTROLLER);
1890 if ((r = unit_add_cgroup(u, b)) < 0)
1897 free(b->controller);
1903 int unit_add_default_cgroups(Unit *u) {
1910 /* Adds in the default cgroups, if they weren't specified
1913 if (!u->meta.manager->cgroup_hierarchy)
1916 if ((r = unit_add_one_default_cgroup(u, NULL)) < 0)
1919 STRV_FOREACH(c, u->meta.manager->default_controllers)
1920 unit_add_one_default_cgroup(u, *c);
1922 LIST_FOREACH(by_unit, a, u->meta.cgroup_attributes)
1923 unit_add_one_default_cgroup(u, a->controller);
1928 CGroupBonding* unit_get_default_cgroup(Unit *u) {
1931 return cgroup_bonding_find_list(u->meta.cgroup_bondings, SYSTEMD_CGROUP_CONTROLLER);
1934 int unit_add_cgroup_attribute(Unit *u, const char *controller, const char *name, const char *value, CGroupAttributeMapCallback map_callback) {
1946 dot = strchr(name, '.');
1950 c = strndup(name, dot - name);
1957 if (streq(controller, SYSTEMD_CGROUP_CONTROLLER)) {
1962 a = new0(CGroupAttribute, 1);
1972 a->controller = strdup(controller);
1974 a->name = strdup(name);
1975 a->value = strdup(value);
1977 if (!a->controller || !a->name || !a->value) {
1978 free(a->controller);
1986 a->map_callback = map_callback;
1988 LIST_PREPEND(CGroupAttribute, by_unit, u->meta.cgroup_attributes, a);
1997 int unit_load_related_unit(Unit *u, const char *type, Unit **_found) {
2005 if (!(t = unit_name_change_suffix(u->meta.id, type)))
2008 assert(!unit_has_name(u, t));
2010 r = manager_load_unit(u->meta.manager, t, NULL, NULL, _found);
2013 assert(r < 0 || *_found != u);
2018 int unit_get_related_unit(Unit *u, const char *type, Unit **_found) {
2026 if (!(t = unit_name_change_suffix(u->meta.id, type)))
2029 assert(!unit_has_name(u, t));
2031 found = manager_get_unit(u->meta.manager, t);
2041 static char *specifier_prefix_and_instance(char specifier, void *data, void *userdata) {
2045 return unit_name_to_prefix_and_instance(u->meta.id);
2048 static char *specifier_prefix(char specifier, void *data, void *userdata) {
2052 return unit_name_to_prefix(u->meta.id);
2055 static char *specifier_prefix_unescaped(char specifier, void *data, void *userdata) {
2061 if (!(p = unit_name_to_prefix(u->meta.id)))
2064 r = unit_name_unescape(p);
2070 static char *specifier_instance_unescaped(char specifier, void *data, void *userdata) {
2074 if (u->meta.instance)
2075 return unit_name_unescape(u->meta.instance);
2080 static char *specifier_filename(char specifier, void *data, void *userdata) {
2084 if (u->meta.instance)
2085 return unit_name_path_unescape(u->meta.instance);
2087 return unit_name_to_path(u->meta.instance);
2090 static char *specifier_cgroup(char specifier, void *data, void *userdata) {
2094 return default_cgroup_path(u);
2097 static char *specifier_cgroup_root(char specifier, void *data, void *userdata) {
2102 if (specifier == 'r')
2103 return strdup(u->meta.manager->cgroup_hierarchy);
2105 if (parent_of_path(u->meta.manager->cgroup_hierarchy, &p) < 0)
2108 if (streq(p, "/")) {
2116 static char *specifier_runtime(char specifier, void *data, void *userdata) {
2120 if (u->meta.manager->running_as == MANAGER_USER) {
2123 e = getenv("XDG_RUNTIME_DIR");
2128 return strdup("/run");
2131 char *unit_name_printf(Unit *u, const char* format) {
2134 * This will use the passed string as format string and
2135 * replace the following specifiers:
2137 * %n: the full id of the unit (foo@bar.waldo)
2138 * %N: the id of the unit without the suffix (foo@bar)
2139 * %p: the prefix (foo)
2140 * %i: the instance (bar)
2143 const Specifier table[] = {
2144 { 'n', specifier_string, u->meta.id },
2145 { 'N', specifier_prefix_and_instance, NULL },
2146 { 'p', specifier_prefix, NULL },
2147 { 'i', specifier_string, u->meta.instance },
2154 return specifier_printf(format, table, u);
2157 char *unit_full_printf(Unit *u, const char *format) {
2159 /* This is similar to unit_name_printf() but also supports
2160 * unescaping. Also, adds a couple of additional codes:
2162 * %c cgroup path of unit
2163 * %r root cgroup path of this systemd instance (e.g. "/user/lennart/shared/systemd-4711")
2164 * %R parent of root cgroup path (e.g. "/usr/lennart/shared")
2165 * %t the runtime directory to place sockets in (e.g. "/run" or $XDG_RUNTIME_DIR)
2168 const Specifier table[] = {
2169 { 'n', specifier_string, u->meta.id },
2170 { 'N', specifier_prefix_and_instance, NULL },
2171 { 'p', specifier_prefix, NULL },
2172 { 'P', specifier_prefix_unescaped, NULL },
2173 { 'i', specifier_string, u->meta.instance },
2174 { 'I', specifier_instance_unescaped, NULL },
2175 { 'f', specifier_filename, NULL },
2176 { 'c', specifier_cgroup, NULL },
2177 { 'r', specifier_cgroup_root, NULL },
2178 { 'R', specifier_cgroup_root, NULL },
2179 { 't', specifier_runtime, NULL },
2186 return specifier_printf(format, table, u);
2189 char **unit_full_printf_strv(Unit *u, char **l) {
2193 /* Applies unit_full_printf to every entry in l */
2198 if (!(r = new(char*, n+1)))
2201 for (i = l, j = r; *i; i++, j++)
2202 if (!(*j = unit_full_printf(u, *i)))
2209 for (j--; j >= r; j--)
2217 int unit_watch_bus_name(Unit *u, const char *name) {
2221 /* Watch a specific name on the bus. We only support one unit
2222 * watching each name for now. */
2224 return hashmap_put(u->meta.manager->watch_bus, name, u);
2227 void unit_unwatch_bus_name(Unit *u, const char *name) {
2231 hashmap_remove_value(u->meta.manager->watch_bus, name, u);
2234 bool unit_can_serialize(Unit *u) {
2237 return UNIT_VTABLE(u)->serialize && UNIT_VTABLE(u)->deserialize_item;
2240 int unit_serialize(Unit *u, FILE *f, FDSet *fds) {
2247 if (!unit_can_serialize(u))
2250 if ((r = UNIT_VTABLE(u)->serialize(u, f, fds)) < 0)
2254 unit_serialize_item(u, f, "job", job_type_to_string(u->meta.job->type));
2256 dual_timestamp_serialize(f, "inactive-exit-timestamp", &u->meta.inactive_exit_timestamp);
2257 dual_timestamp_serialize(f, "active-enter-timestamp", &u->meta.active_enter_timestamp);
2258 dual_timestamp_serialize(f, "active-exit-timestamp", &u->meta.active_exit_timestamp);
2259 dual_timestamp_serialize(f, "inactive-enter-timestamp", &u->meta.inactive_enter_timestamp);
2260 dual_timestamp_serialize(f, "condition-timestamp", &u->meta.condition_timestamp);
2262 if (dual_timestamp_is_set(&u->meta.condition_timestamp))
2263 unit_serialize_item(u, f, "condition-result", yes_no(u->meta.condition_result));
2270 void unit_serialize_item_format(Unit *u, FILE *f, const char *key, const char *format, ...) {
2281 va_start(ap, format);
2282 vfprintf(f, format, ap);
2288 void unit_serialize_item(Unit *u, FILE *f, const char *key, const char *value) {
2294 fprintf(f, "%s=%s\n", key, value);
2297 int unit_deserialize(Unit *u, FILE *f, FDSet *fds) {
2304 if (!unit_can_serialize(u))
2308 char line[LINE_MAX], *l, *v;
2311 if (!fgets(line, sizeof(line), f)) {
2324 k = strcspn(l, "=");
2332 if (streq(l, "job")) {
2335 if ((type = job_type_from_string(v)) < 0)
2336 log_debug("Failed to parse job type value %s", v);
2338 u->meta.deserialized_job = type;
2341 } else if (streq(l, "inactive-exit-timestamp")) {
2342 dual_timestamp_deserialize(v, &u->meta.inactive_exit_timestamp);
2344 } else if (streq(l, "active-enter-timestamp")) {
2345 dual_timestamp_deserialize(v, &u->meta.active_enter_timestamp);
2347 } else if (streq(l, "active-exit-timestamp")) {
2348 dual_timestamp_deserialize(v, &u->meta.active_exit_timestamp);
2350 } else if (streq(l, "inactive-enter-timestamp")) {
2351 dual_timestamp_deserialize(v, &u->meta.inactive_enter_timestamp);
2353 } else if (streq(l, "condition-timestamp")) {
2354 dual_timestamp_deserialize(v, &u->meta.condition_timestamp);
2356 } else if (streq(l, "condition-result")) {
2359 if ((b = parse_boolean(v)) < 0)
2360 log_debug("Failed to parse condition result value %s", v);
2362 u->meta.condition_result = b;
2367 if ((r = UNIT_VTABLE(u)->deserialize_item(u, l, v, fds)) < 0)
2372 int unit_add_node_link(Unit *u, const char *what, bool wants) {
2382 /* Adds in links to the device node that this unit is based on */
2384 if (!is_device_path(what))
2387 if (!(e = unit_name_build_escape(what+1, NULL, ".device")))
2390 r = manager_load_unit(u->meta.manager, e, NULL, NULL, &device);
2396 if ((r = unit_add_two_dependencies(u, UNIT_AFTER, UNIT_BIND_TO, device, true)) < 0)
2400 if ((r = unit_add_dependency(device, UNIT_WANTS, u, false)) < 0)
2406 int unit_coldplug(Unit *u) {
2411 if (UNIT_VTABLE(u)->coldplug)
2412 if ((r = UNIT_VTABLE(u)->coldplug(u)) < 0)
2415 if (u->meta.deserialized_job >= 0) {
2416 if ((r = manager_add_job(u->meta.manager, u->meta.deserialized_job, u, JOB_IGNORE_REQUIREMENTS, false, NULL, NULL)) < 0)
2419 u->meta.deserialized_job = _JOB_TYPE_INVALID;
2425 void unit_status_printf(Unit *u, const char *format, ...) {
2431 if (!UNIT_VTABLE(u)->show_status)
2434 if (!manager_get_show_status(u->meta.manager))
2437 if (!manager_is_booting_or_shutting_down(u->meta.manager))
2440 va_start(ap, format);
2441 status_vprintf(format, ap);
2445 bool unit_need_daemon_reload(Unit *u) {
2448 if (u->meta.fragment_path) {
2452 if (stat(u->meta.fragment_path, &st) < 0)
2453 /* What, cannot access this anymore? */
2456 if (u->meta.fragment_mtime > 0 &&
2457 timespec_load(&st.st_mtim) != u->meta.fragment_mtime)
2461 if (UNIT_VTABLE(u)->need_daemon_reload)
2462 return UNIT_VTABLE(u)->need_daemon_reload(u);
2467 void unit_reset_failed(Unit *u) {
2470 if (UNIT_VTABLE(u)->reset_failed)
2471 UNIT_VTABLE(u)->reset_failed(u);
2474 Unit *unit_following(Unit *u) {
2477 if (UNIT_VTABLE(u)->following)
2478 return UNIT_VTABLE(u)->following(u);
2483 bool unit_pending_inactive(Unit *u) {
2486 /* Returns true if the unit is inactive or going down */
2488 if (UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)))
2491 if (u->meta.job && u->meta.job->type == JOB_STOP)
2497 bool unit_pending_active(Unit *u) {
2500 /* Returns true if the unit is inactive or going down */
2502 if (UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)))
2506 (u->meta.job->type == JOB_START ||
2507 u->meta.job->type == JOB_RELOAD_OR_START ||
2508 u->meta.job->type == JOB_RESTART))
2514 UnitType unit_name_to_type(const char *n) {
2519 for (t = 0; t < _UNIT_TYPE_MAX; t++)
2520 if (endswith(n, unit_vtable[t]->suffix))
2523 return _UNIT_TYPE_INVALID;
2526 bool unit_name_is_valid(const char *n, bool template_ok) {
2529 t = unit_name_to_type(n);
2530 if (t < 0 || t >= _UNIT_TYPE_MAX)
2533 return unit_name_is_valid_no_type(n, template_ok);
2536 int unit_kill(Unit *u, KillWho w, KillMode m, int signo, DBusError *error) {
2538 assert(w >= 0 && w < _KILL_WHO_MAX);
2539 assert(m >= 0 && m < _KILL_MODE_MAX);
2541 assert(signo < _NSIG);
2546 if (!UNIT_VTABLE(u)->kill)
2549 return UNIT_VTABLE(u)->kill(u, w, m, signo, error);
2552 int unit_following_set(Unit *u, Set **s) {
2556 if (UNIT_VTABLE(u)->following_set)
2557 return UNIT_VTABLE(u)->following_set(u, s);
2563 UnitFileState unit_get_unit_file_state(Unit *u) {
2566 if (u->meta.unit_file_state < 0 && u->meta.fragment_path)
2567 u->meta.unit_file_state = unit_file_get_state(
2568 u->meta.manager->running_as == MANAGER_SYSTEM ? UNIT_FILE_SYSTEM : UNIT_FILE_USER,
2569 NULL, file_name_from_path(u->meta.fragment_path));
2571 return u->meta.unit_file_state;
2574 static const char* const unit_load_state_table[_UNIT_LOAD_STATE_MAX] = {
2575 [UNIT_STUB] = "stub",
2576 [UNIT_LOADED] = "loaded",
2577 [UNIT_ERROR] = "error",
2578 [UNIT_MERGED] = "merged",
2579 [UNIT_MASKED] = "masked"
2582 DEFINE_STRING_TABLE_LOOKUP(unit_load_state, UnitLoadState);
2584 static const char* const unit_active_state_table[_UNIT_ACTIVE_STATE_MAX] = {
2585 [UNIT_ACTIVE] = "active",
2586 [UNIT_RELOADING] = "reloading",
2587 [UNIT_INACTIVE] = "inactive",
2588 [UNIT_FAILED] = "failed",
2589 [UNIT_ACTIVATING] = "activating",
2590 [UNIT_DEACTIVATING] = "deactivating"
2593 DEFINE_STRING_TABLE_LOOKUP(unit_active_state, UnitActiveState);
2595 static const char* const unit_dependency_table[_UNIT_DEPENDENCY_MAX] = {
2596 [UNIT_REQUIRES] = "Requires",
2597 [UNIT_REQUIRES_OVERRIDABLE] = "RequiresOverridable",
2598 [UNIT_WANTS] = "Wants",
2599 [UNIT_REQUISITE] = "Requisite",
2600 [UNIT_REQUISITE_OVERRIDABLE] = "RequisiteOverridable",
2601 [UNIT_REQUIRED_BY] = "RequiredBy",
2602 [UNIT_REQUIRED_BY_OVERRIDABLE] = "RequiredByOverridable",
2603 [UNIT_BIND_TO] = "BindTo",
2604 [UNIT_WANTED_BY] = "WantedBy",
2605 [UNIT_CONFLICTS] = "Conflicts",
2606 [UNIT_CONFLICTED_BY] = "ConflictedBy",
2607 [UNIT_BOUND_BY] = "BoundBy",
2608 [UNIT_BEFORE] = "Before",
2609 [UNIT_AFTER] = "After",
2610 [UNIT_REFERENCES] = "References",
2611 [UNIT_REFERENCED_BY] = "ReferencedBy",
2612 [UNIT_ON_FAILURE] = "OnFailure"
2615 DEFINE_STRING_TABLE_LOOKUP(unit_dependency, UnitDependency);