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);
380 free(u->meta.instance);
382 set_free_free(u->meta.names);
384 condition_free_list(u->meta.conditions);
387 unit_ref_unset(u->meta.refs);
392 UnitActiveState unit_active_state(Unit *u) {
395 if (u->meta.load_state == UNIT_MERGED)
396 return unit_active_state(unit_follow_merge(u));
398 /* After a reload it might happen that a unit is not correctly
399 * loaded but still has a process around. That's why we won't
400 * shortcut failed loading to UNIT_INACTIVE_FAILED. */
402 return UNIT_VTABLE(u)->active_state(u);
405 const char* unit_sub_state_to_string(Unit *u) {
408 return UNIT_VTABLE(u)->sub_state_to_string(u);
411 static void complete_move(Set **s, Set **other) {
419 set_move(*s, *other);
426 static void merge_names(Unit *u, Unit *other) {
433 complete_move(&u->meta.names, &other->meta.names);
435 set_free_free(other->meta.names);
436 other->meta.names = NULL;
437 other->meta.id = NULL;
439 SET_FOREACH(t, u->meta.names, i)
440 assert_se(hashmap_replace(u->meta.manager->units, t, u) == 0);
443 static void merge_dependencies(Unit *u, Unit *other, UnitDependency d) {
450 assert(d < _UNIT_DEPENDENCY_MAX);
452 /* Fix backwards pointers */
453 SET_FOREACH(back, other->meta.dependencies[d], i) {
456 for (k = 0; k < _UNIT_DEPENDENCY_MAX; k++)
457 if ((r = set_remove_and_put(back->meta.dependencies[k], other, u)) < 0) {
460 set_remove(back->meta.dependencies[k], other);
462 assert(r == -ENOENT);
466 complete_move(&u->meta.dependencies[d], &other->meta.dependencies[d]);
468 set_free(other->meta.dependencies[d]);
469 other->meta.dependencies[d] = NULL;
472 int unit_merge(Unit *u, Unit *other) {
477 assert(u->meta.manager == other->meta.manager);
478 assert(u->meta.type != _UNIT_TYPE_INVALID);
480 other = unit_follow_merge(other);
485 if (u->meta.type != other->meta.type)
488 if (!u->meta.instance != !other->meta.instance)
491 if (other->meta.load_state != UNIT_STUB &&
492 other->meta.load_state != UNIT_ERROR)
498 if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other)))
502 merge_names(u, other);
504 /* Redirect all references */
505 while (other->meta.refs)
506 unit_ref_set(other->meta.refs, u);
508 /* Merge dependencies */
509 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
510 merge_dependencies(u, other, d);
512 other->meta.load_state = UNIT_MERGED;
513 other->meta.merged_into = u;
515 /* If there is still some data attached to the other node, we
516 * don't need it anymore, and can free it. */
517 if (other->meta.load_state != UNIT_STUB)
518 if (UNIT_VTABLE(other)->done)
519 UNIT_VTABLE(other)->done(other);
521 unit_add_to_dbus_queue(u);
522 unit_add_to_cleanup_queue(other);
527 int unit_merge_by_name(Unit *u, const char *name) {
535 if (unit_name_is_template(name)) {
536 if (!u->meta.instance)
539 if (!(s = unit_name_replace_instance(name, u->meta.instance)))
545 if (!(other = manager_get_unit(u->meta.manager, name)))
546 r = unit_add_name(u, name);
548 r = unit_merge(u, other);
554 Unit* unit_follow_merge(Unit *u) {
557 while (u->meta.load_state == UNIT_MERGED)
558 assert_se(u = u->meta.merged_into);
563 int unit_add_exec_dependencies(Unit *u, ExecContext *c) {
569 if (c->std_output != EXEC_OUTPUT_KMSG &&
570 c->std_output != EXEC_OUTPUT_SYSLOG &&
571 c->std_output != EXEC_OUTPUT_JOURNAL &&
572 c->std_output != EXEC_OUTPUT_KMSG_AND_CONSOLE &&
573 c->std_output != EXEC_OUTPUT_SYSLOG_AND_CONSOLE &&
574 c->std_output != EXEC_OUTPUT_JOURNAL_AND_CONSOLE &&
575 c->std_error != EXEC_OUTPUT_KMSG &&
576 c->std_error != EXEC_OUTPUT_SYSLOG &&
577 c->std_error != EXEC_OUTPUT_JOURNAL &&
578 c->std_error != EXEC_OUTPUT_KMSG_AND_CONSOLE &&
579 c->std_error != EXEC_OUTPUT_JOURNAL_AND_CONSOLE &&
580 c->std_error != EXEC_OUTPUT_SYSLOG_AND_CONSOLE)
583 /* If syslog or kernel logging is requested, make sure our own
584 * logging daemon is run first. */
586 if (u->meta.manager->running_as == MANAGER_SYSTEM)
587 if ((r = unit_add_two_dependencies_by_name(u, UNIT_REQUIRES, UNIT_AFTER, SPECIAL_JOURNALD_SOCKET, NULL, true)) < 0)
593 const char *unit_description(Unit *u) {
596 if (u->meta.description)
597 return u->meta.description;
599 return strna(u->meta.id);
602 void unit_dump(Unit *u, FILE *f, const char *prefix) {
609 timestamp1[FORMAT_TIMESTAMP_MAX],
610 timestamp2[FORMAT_TIMESTAMP_MAX],
611 timestamp3[FORMAT_TIMESTAMP_MAX],
612 timestamp4[FORMAT_TIMESTAMP_MAX],
613 timespan[FORMAT_TIMESPAN_MAX];
617 assert(u->meta.type >= 0);
621 p2 = strappend(prefix, "\t");
622 prefix2 = p2 ? p2 : prefix;
626 "%s\tDescription: %s\n"
628 "%s\tUnit Load State: %s\n"
629 "%s\tUnit Active State: %s\n"
630 "%s\tInactive Exit Timestamp: %s\n"
631 "%s\tActive Enter Timestamp: %s\n"
632 "%s\tActive Exit Timestamp: %s\n"
633 "%s\tInactive Enter Timestamp: %s\n"
634 "%s\tGC Check Good: %s\n"
635 "%s\tNeed Daemon Reload: %s\n",
637 prefix, unit_description(u),
638 prefix, strna(u->meta.instance),
639 prefix, unit_load_state_to_string(u->meta.load_state),
640 prefix, unit_active_state_to_string(unit_active_state(u)),
641 prefix, strna(format_timestamp(timestamp1, sizeof(timestamp1), u->meta.inactive_exit_timestamp.realtime)),
642 prefix, strna(format_timestamp(timestamp2, sizeof(timestamp2), u->meta.active_enter_timestamp.realtime)),
643 prefix, strna(format_timestamp(timestamp3, sizeof(timestamp3), u->meta.active_exit_timestamp.realtime)),
644 prefix, strna(format_timestamp(timestamp4, sizeof(timestamp4), u->meta.inactive_enter_timestamp.realtime)),
645 prefix, yes_no(unit_check_gc(u)),
646 prefix, yes_no(unit_need_daemon_reload(u)));
648 SET_FOREACH(t, u->meta.names, i)
649 fprintf(f, "%s\tName: %s\n", prefix, t);
651 if ((following = unit_following(u)))
652 fprintf(f, "%s\tFollowing: %s\n", prefix, following->meta.id);
654 if (u->meta.fragment_path)
655 fprintf(f, "%s\tFragment Path: %s\n", prefix, u->meta.fragment_path);
657 if (u->meta.job_timeout > 0)
658 fprintf(f, "%s\tJob Timeout: %s\n", prefix, format_timespan(timespan, sizeof(timespan), u->meta.job_timeout));
660 condition_dump_list(u->meta.conditions, f, prefix);
662 if (dual_timestamp_is_set(&u->meta.condition_timestamp))
664 "%s\tCondition Timestamp: %s\n"
665 "%s\tCondition Result: %s\n",
666 prefix, strna(format_timestamp(timestamp1, sizeof(timestamp1), u->meta.condition_timestamp.realtime)),
667 prefix, yes_no(u->meta.condition_result));
669 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++) {
672 SET_FOREACH(other, u->meta.dependencies[d], i)
673 fprintf(f, "%s\t%s: %s\n", prefix, unit_dependency_to_string(d), other->meta.id);
676 if (u->meta.load_state == UNIT_LOADED) {
681 "%s\tStopWhenUnneeded: %s\n"
682 "%s\tRefuseManualStart: %s\n"
683 "%s\tRefuseManualStop: %s\n"
684 "%s\tDefaultDependencies: %s\n"
685 "%s\tOnFailureIsolate: %s\n"
686 "%s\tIgnoreOnIsolate: %s\n"
687 "%s\tIgnoreOnSnapshot: %s\n",
688 prefix, yes_no(u->meta.stop_when_unneeded),
689 prefix, yes_no(u->meta.refuse_manual_start),
690 prefix, yes_no(u->meta.refuse_manual_stop),
691 prefix, yes_no(u->meta.default_dependencies),
692 prefix, yes_no(u->meta.on_failure_isolate),
693 prefix, yes_no(u->meta.ignore_on_isolate),
694 prefix, yes_no(u->meta.ignore_on_snapshot));
696 LIST_FOREACH(by_unit, b, u->meta.cgroup_bondings)
697 fprintf(f, "%s\tControlGroup: %s:%s\n",
698 prefix, b->controller, b->path);
700 LIST_FOREACH(by_unit, a, u->meta.cgroup_attributes) {
704 a->map_callback(a->controller, a->name, a->value, &v);
706 fprintf(f, "%s\tControlGroupAttribute: %s %s \"%s\"\n",
707 prefix, a->controller, a->name, v ? v : a->value);
712 if (UNIT_VTABLE(u)->dump)
713 UNIT_VTABLE(u)->dump(u, f, prefix2);
715 } else if (u->meta.load_state == UNIT_MERGED)
717 "%s\tMerged into: %s\n",
718 prefix, u->meta.merged_into->meta.id);
719 else if (u->meta.load_state == UNIT_ERROR)
720 fprintf(f, "%s\tLoad Error Code: %s\n", prefix, strerror(-u->meta.load_error));
724 job_dump(u->meta.job, f, prefix2);
729 /* Common implementation for multiple backends */
730 int unit_load_fragment_and_dropin(Unit *u) {
735 /* Load a .service file */
736 if ((r = unit_load_fragment(u)) < 0)
739 if (u->meta.load_state == UNIT_STUB)
742 /* Load drop-in directory data */
743 if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
749 /* Common implementation for multiple backends */
750 int unit_load_fragment_and_dropin_optional(Unit *u) {
755 /* Same as unit_load_fragment_and_dropin(), but whether
756 * something can be loaded or not doesn't matter. */
758 /* Load a .service file */
759 if ((r = unit_load_fragment(u)) < 0)
762 if (u->meta.load_state == UNIT_STUB)
763 u->meta.load_state = UNIT_LOADED;
765 /* Load drop-in directory data */
766 if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
772 int unit_add_default_target_dependency(Unit *u, Unit *target) {
776 if (target->meta.type != UNIT_TARGET)
779 /* Only add the dependency if both units are loaded, so that
780 * that loop check below is reliable */
781 if (u->meta.load_state != UNIT_LOADED ||
782 target->meta.load_state != UNIT_LOADED)
785 /* If either side wants no automatic dependencies, then let's
787 if (!u->meta.default_dependencies ||
788 !target->meta.default_dependencies)
791 /* Don't create loops */
792 if (set_get(target->meta.dependencies[UNIT_BEFORE], u))
795 return unit_add_dependency(target, UNIT_AFTER, u, true);
798 static int unit_add_default_dependencies(Unit *u) {
799 static const UnitDependency deps[] = {
801 UNIT_REQUIRED_BY_OVERRIDABLE,
813 for (k = 0; k < ELEMENTSOF(deps); k++)
814 SET_FOREACH(target, u->meta.dependencies[deps[k]], i)
815 if ((r = unit_add_default_target_dependency(u, target)) < 0)
821 int unit_load(Unit *u) {
826 if (u->meta.in_load_queue) {
827 LIST_REMOVE(Meta, load_queue, u->meta.manager->load_queue, &u->meta);
828 u->meta.in_load_queue = false;
831 if (u->meta.type == _UNIT_TYPE_INVALID)
834 if (u->meta.load_state != UNIT_STUB)
837 if (UNIT_VTABLE(u)->load)
838 if ((r = UNIT_VTABLE(u)->load(u)) < 0)
841 if (u->meta.load_state == UNIT_STUB) {
846 if (u->meta.load_state == UNIT_LOADED &&
847 u->meta.default_dependencies)
848 if ((r = unit_add_default_dependencies(u)) < 0)
851 if (u->meta.on_failure_isolate &&
852 set_size(u->meta.dependencies[UNIT_ON_FAILURE]) > 1) {
854 log_error("More than one OnFailure= dependencies specified for %s but OnFailureIsolate= enabled. Refusing.",
861 assert((u->meta.load_state != UNIT_MERGED) == !u->meta.merged_into);
863 unit_add_to_dbus_queue(unit_follow_merge(u));
864 unit_add_to_gc_queue(u);
869 u->meta.load_state = UNIT_ERROR;
870 u->meta.load_error = r;
871 unit_add_to_dbus_queue(u);
872 unit_add_to_gc_queue(u);
874 log_debug("Failed to load configuration for %s: %s", u->meta.id, strerror(-r));
879 bool unit_condition_test(Unit *u) {
882 dual_timestamp_get(&u->meta.condition_timestamp);
883 u->meta.condition_result = condition_test_list(u->meta.conditions);
885 return u->meta.condition_result;
889 * -EBADR: This unit type does not support starting.
890 * -EALREADY: Unit is already started.
891 * -EAGAIN: An operation is already in progress. Retry later.
892 * -ECANCELED: Too many requests for now.
894 int unit_start(Unit *u) {
895 UnitActiveState state;
900 if (u->meta.load_state != UNIT_LOADED)
903 /* If this is already started, then this will succeed. Note
904 * that this will even succeed if this unit is not startable
905 * by the user. This is relied on to detect when we need to
906 * wait for units and when waiting is finished. */
907 state = unit_active_state(u);
908 if (UNIT_IS_ACTIVE_OR_RELOADING(state))
911 /* If the conditions failed, don't do anything at all. If we
912 * already are activating this call might still be useful to
913 * speed up activation in case there is some hold-off time,
914 * but we don't want to recheck the condition in that case. */
915 if (state != UNIT_ACTIVATING &&
916 !unit_condition_test(u)) {
917 log_debug("Starting of %s requested but condition failed. Ignoring.", u->meta.id);
921 /* Forward to the main object, if we aren't it. */
922 if ((following = unit_following(u))) {
923 log_debug("Redirecting start request from %s to %s.", u->meta.id, following->meta.id);
924 return unit_start(following);
927 /* If it is stopped, but we cannot start it, then fail */
928 if (!UNIT_VTABLE(u)->start)
931 /* We don't suppress calls to ->start() here when we are
932 * already starting, to allow this request to be used as a
933 * "hurry up" call, for example when the unit is in some "auto
934 * restart" state where it waits for a holdoff timer to elapse
935 * before it will start again. */
937 unit_add_to_dbus_queue(u);
939 unit_status_printf(u, NULL, "Starting %s...", unit_description(u));
940 return UNIT_VTABLE(u)->start(u);
943 bool unit_can_start(Unit *u) {
946 return !!UNIT_VTABLE(u)->start;
949 bool unit_can_isolate(Unit *u) {
952 return unit_can_start(u) &&
953 u->meta.allow_isolate;
957 * -EBADR: This unit type does not support stopping.
958 * -EALREADY: Unit is already stopped.
959 * -EAGAIN: An operation is already in progress. Retry later.
961 int unit_stop(Unit *u) {
962 UnitActiveState state;
967 state = unit_active_state(u);
968 if (UNIT_IS_INACTIVE_OR_FAILED(state))
971 if ((following = unit_following(u))) {
972 log_debug("Redirecting stop request from %s to %s.", u->meta.id, following->meta.id);
973 return unit_stop(following);
976 if (!UNIT_VTABLE(u)->stop)
979 unit_add_to_dbus_queue(u);
981 unit_status_printf(u, NULL, "Stopping %s...", unit_description(u));
982 return UNIT_VTABLE(u)->stop(u);
986 * -EBADR: This unit type does not support reloading.
987 * -ENOEXEC: Unit is not started.
988 * -EAGAIN: An operation is already in progress. Retry later.
990 int unit_reload(Unit *u) {
991 UnitActiveState state;
996 if (u->meta.load_state != UNIT_LOADED)
999 if (!unit_can_reload(u))
1002 state = unit_active_state(u);
1003 if (state == UNIT_RELOADING)
1006 if (state != UNIT_ACTIVE)
1009 if ((following = unit_following(u))) {
1010 log_debug("Redirecting reload request from %s to %s.", u->meta.id, following->meta.id);
1011 return unit_reload(following);
1014 unit_add_to_dbus_queue(u);
1015 return UNIT_VTABLE(u)->reload(u);
1018 bool unit_can_reload(Unit *u) {
1021 if (!UNIT_VTABLE(u)->reload)
1024 if (!UNIT_VTABLE(u)->can_reload)
1027 return UNIT_VTABLE(u)->can_reload(u);
1030 static void unit_check_unneeded(Unit *u) {
1036 /* If this service shall be shut down when unneeded then do
1039 if (!u->meta.stop_when_unneeded)
1042 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)))
1045 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRED_BY], i)
1046 if (unit_pending_active(other))
1049 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRED_BY_OVERRIDABLE], i)
1050 if (unit_pending_active(other))
1053 SET_FOREACH(other, u->meta.dependencies[UNIT_WANTED_BY], i)
1054 if (unit_pending_active(other))
1057 SET_FOREACH(other, u->meta.dependencies[UNIT_BOUND_BY], i)
1058 if (unit_pending_active(other))
1061 log_info("Service %s is not needed anymore. Stopping.", u->meta.id);
1063 /* Ok, nobody needs us anymore. Sniff. Then let's commit suicide */
1064 manager_add_job(u->meta.manager, JOB_STOP, u, JOB_FAIL, true, NULL, NULL);
1067 static void retroactively_start_dependencies(Unit *u) {
1072 assert(UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)));
1074 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRES], i)
1075 if (!set_get(u->meta.dependencies[UNIT_AFTER], other) &&
1076 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
1077 manager_add_job(u->meta.manager, JOB_START, other, JOB_REPLACE, true, NULL, NULL);
1079 SET_FOREACH(other, u->meta.dependencies[UNIT_BIND_TO], i)
1080 if (!set_get(u->meta.dependencies[UNIT_AFTER], other) &&
1081 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
1082 manager_add_job(u->meta.manager, JOB_START, other, JOB_REPLACE, true, NULL, NULL);
1084 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRES_OVERRIDABLE], i)
1085 if (!set_get(u->meta.dependencies[UNIT_AFTER], other) &&
1086 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
1087 manager_add_job(u->meta.manager, JOB_START, other, JOB_FAIL, false, NULL, NULL);
1089 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUISITE], i)
1090 if (!set_get(u->meta.dependencies[UNIT_AFTER], other) &&
1091 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
1092 manager_add_job(u->meta.manager, JOB_START, other, JOB_REPLACE, true, NULL, NULL);
1094 SET_FOREACH(other, u->meta.dependencies[UNIT_WANTS], i)
1095 if (!set_get(u->meta.dependencies[UNIT_AFTER], other) &&
1096 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
1097 manager_add_job(u->meta.manager, JOB_START, other, JOB_FAIL, false, NULL, NULL);
1099 SET_FOREACH(other, u->meta.dependencies[UNIT_CONFLICTS], i)
1100 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1101 manager_add_job(u->meta.manager, JOB_STOP, other, JOB_REPLACE, true, NULL, NULL);
1103 SET_FOREACH(other, u->meta.dependencies[UNIT_CONFLICTED_BY], i)
1104 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1105 manager_add_job(u->meta.manager, JOB_STOP, other, JOB_REPLACE, true, NULL, NULL);
1108 static void retroactively_stop_dependencies(Unit *u) {
1113 assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)));
1115 /* Pull down units which are bound to us recursively if enabled */
1116 SET_FOREACH(other, u->meta.dependencies[UNIT_BOUND_BY], i)
1117 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1118 manager_add_job(u->meta.manager, JOB_STOP, other, JOB_REPLACE, true, NULL, NULL);
1121 static void check_unneeded_dependencies(Unit *u) {
1126 assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)));
1128 /* Garbage collect services that might not be needed anymore, if enabled */
1129 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRES], i)
1130 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1131 unit_check_unneeded(other);
1132 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRES_OVERRIDABLE], i)
1133 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1134 unit_check_unneeded(other);
1135 SET_FOREACH(other, u->meta.dependencies[UNIT_WANTS], i)
1136 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1137 unit_check_unneeded(other);
1138 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUISITE], i)
1139 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1140 unit_check_unneeded(other);
1141 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUISITE_OVERRIDABLE], i)
1142 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1143 unit_check_unneeded(other);
1144 SET_FOREACH(other, u->meta.dependencies[UNIT_BIND_TO], i)
1145 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1146 unit_check_unneeded(other);
1149 void unit_trigger_on_failure(Unit *u) {
1155 if (set_size(u->meta.dependencies[UNIT_ON_FAILURE]) <= 0)
1158 log_info("Triggering OnFailure= dependencies of %s.", u->meta.id);
1160 SET_FOREACH(other, u->meta.dependencies[UNIT_ON_FAILURE], i) {
1163 if ((r = manager_add_job(u->meta.manager, JOB_START, other, u->meta.on_failure_isolate ? JOB_ISOLATE : JOB_REPLACE, true, NULL, NULL)) < 0)
1164 log_error("Failed to enqueue OnFailure= job: %s", strerror(-r));
1168 void unit_notify(Unit *u, UnitActiveState os, UnitActiveState ns, bool reload_success) {
1172 assert(os < _UNIT_ACTIVE_STATE_MAX);
1173 assert(ns < _UNIT_ACTIVE_STATE_MAX);
1175 /* Note that this is called for all low-level state changes,
1176 * even if they might map to the same high-level
1177 * UnitActiveState! That means that ns == os is OK an expected
1178 * behaviour here. For example: if a mount point is remounted
1179 * this function will be called too! */
1181 if (u->meta.manager->n_reloading <= 0) {
1184 dual_timestamp_get(&ts);
1186 if (UNIT_IS_INACTIVE_OR_FAILED(os) && !UNIT_IS_INACTIVE_OR_FAILED(ns))
1187 u->meta.inactive_exit_timestamp = ts;
1188 else if (!UNIT_IS_INACTIVE_OR_FAILED(os) && UNIT_IS_INACTIVE_OR_FAILED(ns))
1189 u->meta.inactive_enter_timestamp = ts;
1191 if (!UNIT_IS_ACTIVE_OR_RELOADING(os) && UNIT_IS_ACTIVE_OR_RELOADING(ns))
1192 u->meta.active_enter_timestamp = ts;
1193 else if (UNIT_IS_ACTIVE_OR_RELOADING(os) && !UNIT_IS_ACTIVE_OR_RELOADING(ns))
1194 u->meta.active_exit_timestamp = ts;
1196 timer_unit_notify(u, ns);
1197 path_unit_notify(u, ns);
1200 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
1201 cgroup_bonding_trim_list(u->meta.cgroup_bondings, true);
1206 if (u->meta.job->state == JOB_WAITING)
1208 /* So we reached a different state for this
1209 * job. Let's see if we can run it now if it
1210 * failed previously due to EAGAIN. */
1211 job_add_to_run_queue(u->meta.job);
1213 /* Let's check whether this state change constitutes a
1214 * finished job, or maybe contradicts a running job and
1215 * hence needs to invalidate jobs. */
1217 switch (u->meta.job->type) {
1220 case JOB_VERIFY_ACTIVE:
1222 if (UNIT_IS_ACTIVE_OR_RELOADING(ns))
1223 job_finish_and_invalidate(u->meta.job, JOB_DONE);
1224 else if (u->meta.job->state == JOB_RUNNING && ns != UNIT_ACTIVATING) {
1227 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
1228 job_finish_and_invalidate(u->meta.job, ns == UNIT_FAILED ? JOB_FAILED : JOB_DONE);
1234 case JOB_RELOAD_OR_START:
1236 if (u->meta.job->state == JOB_RUNNING) {
1237 if (ns == UNIT_ACTIVE)
1238 job_finish_and_invalidate(u->meta.job, reload_success ? JOB_DONE : JOB_FAILED);
1239 else if (ns != UNIT_ACTIVATING && ns != UNIT_RELOADING) {
1242 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
1243 job_finish_and_invalidate(u->meta.job, ns == UNIT_FAILED ? JOB_FAILED : JOB_DONE);
1251 case JOB_TRY_RESTART:
1253 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
1254 job_finish_and_invalidate(u->meta.job, JOB_DONE);
1255 else if (u->meta.job->state == JOB_RUNNING && ns != UNIT_DEACTIVATING) {
1257 job_finish_and_invalidate(u->meta.job, JOB_FAILED);
1263 assert_not_reached("Job type unknown");
1269 if (u->meta.manager->n_reloading <= 0) {
1271 /* If this state change happened without being
1272 * requested by a job, then let's retroactively start
1273 * or stop dependencies. We skip that step when
1274 * deserializing, since we don't want to create any
1275 * additional jobs just because something is already
1279 if (UNIT_IS_INACTIVE_OR_FAILED(os) && UNIT_IS_ACTIVE_OR_ACTIVATING(ns))
1280 retroactively_start_dependencies(u);
1281 else if (UNIT_IS_ACTIVE_OR_ACTIVATING(os) && UNIT_IS_INACTIVE_OR_DEACTIVATING(ns))
1282 retroactively_stop_dependencies(u);
1285 /* stop unneeded units regardless if going down was expected or not */
1286 if (UNIT_IS_ACTIVE_OR_ACTIVATING(os) && UNIT_IS_INACTIVE_OR_DEACTIVATING(ns))
1287 check_unneeded_dependencies(u);
1289 if (ns != os && ns == UNIT_FAILED) {
1290 log_notice("Unit %s entered failed state.", u->meta.id);
1291 unit_trigger_on_failure(u);
1295 /* Some names are special */
1296 if (UNIT_IS_ACTIVE_OR_RELOADING(ns)) {
1298 if (unit_has_name(u, SPECIAL_DBUS_SERVICE))
1299 /* The bus just might have become available,
1300 * hence try to connect to it, if we aren't
1302 bus_init(u->meta.manager, true);
1304 if (u->meta.type == UNIT_SERVICE &&
1305 !UNIT_IS_ACTIVE_OR_RELOADING(os) &&
1306 u->meta.manager->n_reloading <= 0) {
1307 /* Write audit record if we have just finished starting up */
1308 manager_send_unit_audit(u->meta.manager, u, AUDIT_SERVICE_START, true);
1309 u->meta.in_audit = true;
1312 if (!UNIT_IS_ACTIVE_OR_RELOADING(os))
1313 manager_send_unit_plymouth(u->meta.manager, u);
1317 /* We don't care about D-Bus here, since we'll get an
1318 * asynchronous notification for it anyway. */
1320 if (u->meta.type == UNIT_SERVICE &&
1321 UNIT_IS_INACTIVE_OR_FAILED(ns) &&
1322 !UNIT_IS_INACTIVE_OR_FAILED(os) &&
1323 u->meta.manager->n_reloading <= 0) {
1325 /* Hmm, if there was no start record written
1326 * write it now, so that we always have a nice
1328 if (!u->meta.in_audit) {
1329 manager_send_unit_audit(u->meta.manager, u, AUDIT_SERVICE_START, ns == UNIT_INACTIVE);
1331 if (ns == UNIT_INACTIVE)
1332 manager_send_unit_audit(u->meta.manager, u, AUDIT_SERVICE_STOP, true);
1334 /* Write audit record if we have just finished shutting down */
1335 manager_send_unit_audit(u->meta.manager, u, AUDIT_SERVICE_STOP, ns == UNIT_INACTIVE);
1337 u->meta.in_audit = false;
1341 manager_recheck_journal(u->meta.manager);
1343 /* Maybe we finished startup and are now ready for being
1344 * stopped because unneeded? */
1345 unit_check_unneeded(u);
1347 unit_add_to_dbus_queue(u);
1348 unit_add_to_gc_queue(u);
1351 int unit_watch_fd(Unit *u, int fd, uint32_t events, Watch *w) {
1352 struct epoll_event ev;
1357 assert(w->type == WATCH_INVALID || (w->type == WATCH_FD && w->fd == fd && w->data.unit == u));
1363 if (epoll_ctl(u->meta.manager->epoll_fd,
1364 w->type == WATCH_INVALID ? EPOLL_CTL_ADD : EPOLL_CTL_MOD,
1376 void unit_unwatch_fd(Unit *u, Watch *w) {
1380 if (w->type == WATCH_INVALID)
1383 assert(w->type == WATCH_FD);
1384 assert(w->data.unit == u);
1385 assert_se(epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_DEL, w->fd, NULL) >= 0);
1388 w->type = WATCH_INVALID;
1389 w->data.unit = NULL;
1392 int unit_watch_pid(Unit *u, pid_t pid) {
1396 /* Watch a specific PID. We only support one unit watching
1397 * each PID for now. */
1399 return hashmap_put(u->meta.manager->watch_pids, LONG_TO_PTR(pid), u);
1402 void unit_unwatch_pid(Unit *u, pid_t pid) {
1406 hashmap_remove_value(u->meta.manager->watch_pids, LONG_TO_PTR(pid), u);
1409 int unit_watch_timer(Unit *u, usec_t delay, Watch *w) {
1410 struct itimerspec its;
1416 assert(w->type == WATCH_INVALID || (w->type == WATCH_UNIT_TIMER && w->data.unit == u));
1418 /* This will try to reuse the old timer if there is one */
1420 if (w->type == WATCH_UNIT_TIMER) {
1421 assert(w->data.unit == u);
1426 } else if (w->type == WATCH_INVALID) {
1429 if ((fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK|TFD_CLOEXEC)) < 0)
1432 assert_not_reached("Invalid watch type");
1437 /* Set absolute time in the past, but not 0, since we
1438 * don't want to disarm the timer */
1439 its.it_value.tv_sec = 0;
1440 its.it_value.tv_nsec = 1;
1442 flags = TFD_TIMER_ABSTIME;
1444 timespec_store(&its.it_value, delay);
1448 /* This will also flush the elapse counter */
1449 if (timerfd_settime(fd, flags, &its, NULL) < 0)
1452 if (w->type == WATCH_INVALID) {
1453 struct epoll_event ev;
1457 ev.events = EPOLLIN;
1459 if (epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0)
1463 w->type = WATCH_UNIT_TIMER;
1471 close_nointr_nofail(fd);
1476 void unit_unwatch_timer(Unit *u, Watch *w) {
1480 if (w->type == WATCH_INVALID)
1483 assert(w->type == WATCH_UNIT_TIMER);
1484 assert(w->data.unit == u);
1487 assert_se(epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_DEL, w->fd, NULL) >= 0);
1488 close_nointr_nofail(w->fd);
1491 w->type = WATCH_INVALID;
1492 w->data.unit = NULL;
1495 bool unit_job_is_applicable(Unit *u, JobType j) {
1497 assert(j >= 0 && j < _JOB_TYPE_MAX);
1501 case JOB_VERIFY_ACTIVE:
1507 case JOB_TRY_RESTART:
1508 return unit_can_start(u);
1511 return unit_can_reload(u);
1513 case JOB_RELOAD_OR_START:
1514 return unit_can_reload(u) && unit_can_start(u);
1517 assert_not_reached("Invalid job type");
1521 int unit_add_dependency(Unit *u, UnitDependency d, Unit *other, bool add_reference) {
1523 static const UnitDependency inverse_table[_UNIT_DEPENDENCY_MAX] = {
1524 [UNIT_REQUIRES] = UNIT_REQUIRED_BY,
1525 [UNIT_REQUIRES_OVERRIDABLE] = UNIT_REQUIRED_BY_OVERRIDABLE,
1526 [UNIT_WANTS] = UNIT_WANTED_BY,
1527 [UNIT_REQUISITE] = UNIT_REQUIRED_BY,
1528 [UNIT_REQUISITE_OVERRIDABLE] = UNIT_REQUIRED_BY_OVERRIDABLE,
1529 [UNIT_BIND_TO] = UNIT_BOUND_BY,
1530 [UNIT_REQUIRED_BY] = _UNIT_DEPENDENCY_INVALID,
1531 [UNIT_REQUIRED_BY_OVERRIDABLE] = _UNIT_DEPENDENCY_INVALID,
1532 [UNIT_WANTED_BY] = _UNIT_DEPENDENCY_INVALID,
1533 [UNIT_BOUND_BY] = UNIT_BIND_TO,
1534 [UNIT_CONFLICTS] = UNIT_CONFLICTED_BY,
1535 [UNIT_CONFLICTED_BY] = UNIT_CONFLICTS,
1536 [UNIT_BEFORE] = UNIT_AFTER,
1537 [UNIT_AFTER] = UNIT_BEFORE,
1538 [UNIT_ON_FAILURE] = _UNIT_DEPENDENCY_INVALID,
1539 [UNIT_REFERENCES] = UNIT_REFERENCED_BY,
1540 [UNIT_REFERENCED_BY] = UNIT_REFERENCES,
1541 [UNIT_TRIGGERS] = UNIT_TRIGGERED_BY,
1542 [UNIT_TRIGGERED_BY] = UNIT_TRIGGERS,
1543 [UNIT_PROPAGATE_RELOAD_TO] = UNIT_PROPAGATE_RELOAD_FROM,
1544 [UNIT_PROPAGATE_RELOAD_FROM] = UNIT_PROPAGATE_RELOAD_TO
1546 int r, q = 0, v = 0, w = 0;
1549 assert(d >= 0 && d < _UNIT_DEPENDENCY_MAX);
1552 u = unit_follow_merge(u);
1553 other = unit_follow_merge(other);
1555 /* We won't allow dependencies on ourselves. We will not
1556 * consider them an error however. */
1560 if ((r = set_ensure_allocated(&u->meta.dependencies[d], trivial_hash_func, trivial_compare_func)) < 0)
1563 if (inverse_table[d] != _UNIT_DEPENDENCY_INVALID)
1564 if ((r = set_ensure_allocated(&other->meta.dependencies[inverse_table[d]], trivial_hash_func, trivial_compare_func)) < 0)
1568 if ((r = set_ensure_allocated(&u->meta.dependencies[UNIT_REFERENCES], trivial_hash_func, trivial_compare_func)) < 0 ||
1569 (r = set_ensure_allocated(&other->meta.dependencies[UNIT_REFERENCED_BY], trivial_hash_func, trivial_compare_func)) < 0)
1572 if ((q = set_put(u->meta.dependencies[d], other)) < 0)
1575 if (inverse_table[d] != _UNIT_DEPENDENCY_INVALID)
1576 if ((v = set_put(other->meta.dependencies[inverse_table[d]], u)) < 0) {
1581 if (add_reference) {
1582 if ((w = set_put(u->meta.dependencies[UNIT_REFERENCES], other)) < 0) {
1587 if ((r = set_put(other->meta.dependencies[UNIT_REFERENCED_BY], u)) < 0)
1591 unit_add_to_dbus_queue(u);
1596 set_remove(u->meta.dependencies[d], other);
1599 set_remove(other->meta.dependencies[inverse_table[d]], u);
1602 set_remove(u->meta.dependencies[UNIT_REFERENCES], other);
1607 int unit_add_two_dependencies(Unit *u, UnitDependency d, UnitDependency e, Unit *other, bool add_reference) {
1612 if ((r = unit_add_dependency(u, d, other, add_reference)) < 0)
1615 if ((r = unit_add_dependency(u, e, other, add_reference)) < 0)
1621 static const char *resolve_template(Unit *u, const char *name, const char*path, char **p) {
1625 assert(name || path);
1628 name = file_name_from_path(path);
1630 if (!unit_name_is_template(name)) {
1635 if (u->meta.instance)
1636 s = unit_name_replace_instance(name, u->meta.instance);
1640 if (!(i = unit_name_to_prefix(u->meta.id)))
1643 s = unit_name_replace_instance(name, i);
1654 int unit_add_dependency_by_name(Unit *u, UnitDependency d, const char *name, const char *path, bool add_reference) {
1660 assert(name || path);
1662 if (!(name = resolve_template(u, name, path, &s)))
1665 if ((r = manager_load_unit(u->meta.manager, name, path, NULL, &other)) < 0)
1668 r = unit_add_dependency(u, d, other, add_reference);
1675 int unit_add_two_dependencies_by_name(Unit *u, UnitDependency d, UnitDependency e, const char *name, const char *path, bool add_reference) {
1681 assert(name || path);
1683 if (!(name = resolve_template(u, name, path, &s)))
1686 if ((r = manager_load_unit(u->meta.manager, name, path, NULL, &other)) < 0)
1689 r = unit_add_two_dependencies(u, d, e, other, add_reference);
1696 int unit_add_dependency_by_name_inverse(Unit *u, UnitDependency d, const char *name, const char *path, bool add_reference) {
1702 assert(name || path);
1704 if (!(name = resolve_template(u, name, path, &s)))
1707 if ((r = manager_load_unit(u->meta.manager, name, path, NULL, &other)) < 0)
1710 r = unit_add_dependency(other, d, u, add_reference);
1717 int unit_add_two_dependencies_by_name_inverse(Unit *u, UnitDependency d, UnitDependency e, const char *name, const char *path, bool add_reference) {
1723 assert(name || path);
1725 if (!(name = resolve_template(u, name, path, &s)))
1728 if ((r = manager_load_unit(u->meta.manager, name, path, NULL, &other)) < 0)
1731 if ((r = unit_add_two_dependencies(other, d, e, u, add_reference)) < 0)
1739 int set_unit_path(const char *p) {
1743 /* This is mostly for debug purposes */
1745 if (path_is_absolute(p)) {
1746 if (!(c = strdup(p)))
1749 if (!(cwd = get_current_dir_name()))
1752 r = asprintf(&c, "%s/%s", cwd, p);
1759 if (setenv("SYSTEMD_UNIT_PATH", c, 0) < 0) {
1768 char *unit_dbus_path(Unit *u) {
1776 if (!(e = bus_path_escape(u->meta.id)))
1779 p = strappend("/org/freedesktop/systemd1/unit/", e);
1785 int unit_add_cgroup(Unit *u, CGroupBonding *b) {
1793 if (!b->controller) {
1794 if (!(b->controller = strdup(SYSTEMD_CGROUP_CONTROLLER)))
1800 /* Ensure this hasn't been added yet */
1803 if (streq(b->controller, SYSTEMD_CGROUP_CONTROLLER)) {
1806 l = hashmap_get(u->meta.manager->cgroup_bondings, b->path);
1807 LIST_PREPEND(CGroupBonding, by_path, l, b);
1809 if ((r = hashmap_replace(u->meta.manager->cgroup_bondings, b->path, l)) < 0) {
1810 LIST_REMOVE(CGroupBonding, by_path, l, b);
1815 LIST_PREPEND(CGroupBonding, by_unit, u->meta.cgroup_bondings, b);
1821 static char *default_cgroup_path(Unit *u) {
1826 if (u->meta.instance) {
1829 t = unit_name_template(u->meta.id);
1833 p = join(u->meta.manager->cgroup_hierarchy, "/", t, "/", u->meta.instance, NULL);
1836 p = join(u->meta.manager->cgroup_hierarchy, "/", u->meta.id, NULL);
1841 int unit_add_cgroup_from_text(Unit *u, const char *name) {
1842 char *controller = NULL, *path = NULL;
1843 CGroupBonding *b = NULL;
1850 if ((r = cg_split_spec(name, &controller, &path)) < 0)
1854 path = default_cgroup_path(u);
1859 controller = strdup(SYSTEMD_CGROUP_CONTROLLER);
1863 if (!path || !controller) {
1870 if (cgroup_bonding_find_list(u->meta.cgroup_bondings, controller)) {
1875 if (!(b = new0(CGroupBonding, 1))) {
1880 b->controller = controller;
1883 b->essential = streq(controller, SYSTEMD_CGROUP_CONTROLLER);
1885 if ((r = unit_add_cgroup(u, b)) < 0)
1898 static int unit_add_one_default_cgroup(Unit *u, const char *controller) {
1899 CGroupBonding *b = NULL;
1905 controller = SYSTEMD_CGROUP_CONTROLLER;
1907 if (cgroup_bonding_find_list(u->meta.cgroup_bondings, controller))
1910 if (!(b = new0(CGroupBonding, 1)))
1913 if (!(b->controller = strdup(controller)))
1916 if (!(b->path = default_cgroup_path(u)))
1920 b->essential = streq(controller, SYSTEMD_CGROUP_CONTROLLER);
1922 if ((r = unit_add_cgroup(u, b)) < 0)
1929 free(b->controller);
1935 int unit_add_default_cgroups(Unit *u) {
1942 /* Adds in the default cgroups, if they weren't specified
1945 if (!u->meta.manager->cgroup_hierarchy)
1948 if ((r = unit_add_one_default_cgroup(u, NULL)) < 0)
1951 STRV_FOREACH(c, u->meta.manager->default_controllers)
1952 unit_add_one_default_cgroup(u, *c);
1954 LIST_FOREACH(by_unit, a, u->meta.cgroup_attributes)
1955 unit_add_one_default_cgroup(u, a->controller);
1960 CGroupBonding* unit_get_default_cgroup(Unit *u) {
1963 return cgroup_bonding_find_list(u->meta.cgroup_bondings, SYSTEMD_CGROUP_CONTROLLER);
1966 int unit_add_cgroup_attribute(Unit *u, const char *controller, const char *name, const char *value, CGroupAttributeMapCallback map_callback) {
1978 dot = strchr(name, '.');
1982 c = strndup(name, dot - name);
1989 if (streq(controller, SYSTEMD_CGROUP_CONTROLLER)) {
1994 a = new0(CGroupAttribute, 1);
2004 a->controller = strdup(controller);
2006 a->name = strdup(name);
2007 a->value = strdup(value);
2009 if (!a->controller || !a->name || !a->value) {
2010 free(a->controller);
2018 a->map_callback = map_callback;
2020 LIST_PREPEND(CGroupAttribute, by_unit, u->meta.cgroup_attributes, a);
2029 int unit_load_related_unit(Unit *u, const char *type, Unit **_found) {
2037 if (!(t = unit_name_change_suffix(u->meta.id, type)))
2040 assert(!unit_has_name(u, t));
2042 r = manager_load_unit(u->meta.manager, t, NULL, NULL, _found);
2045 assert(r < 0 || *_found != u);
2050 int unit_get_related_unit(Unit *u, const char *type, Unit **_found) {
2058 if (!(t = unit_name_change_suffix(u->meta.id, type)))
2061 assert(!unit_has_name(u, t));
2063 found = manager_get_unit(u->meta.manager, t);
2073 static char *specifier_prefix_and_instance(char specifier, void *data, void *userdata) {
2077 return unit_name_to_prefix_and_instance(u->meta.id);
2080 static char *specifier_prefix(char specifier, void *data, void *userdata) {
2084 return unit_name_to_prefix(u->meta.id);
2087 static char *specifier_prefix_unescaped(char specifier, void *data, void *userdata) {
2093 if (!(p = unit_name_to_prefix(u->meta.id)))
2096 r = unit_name_unescape(p);
2102 static char *specifier_instance_unescaped(char specifier, void *data, void *userdata) {
2106 if (u->meta.instance)
2107 return unit_name_unescape(u->meta.instance);
2112 static char *specifier_filename(char specifier, void *data, void *userdata) {
2116 if (u->meta.instance)
2117 return unit_name_path_unescape(u->meta.instance);
2119 return unit_name_to_path(u->meta.instance);
2122 static char *specifier_cgroup(char specifier, void *data, void *userdata) {
2126 return default_cgroup_path(u);
2129 static char *specifier_cgroup_root(char specifier, void *data, void *userdata) {
2134 if (specifier == 'r')
2135 return strdup(u->meta.manager->cgroup_hierarchy);
2137 if (parent_of_path(u->meta.manager->cgroup_hierarchy, &p) < 0)
2140 if (streq(p, "/")) {
2148 static char *specifier_runtime(char specifier, void *data, void *userdata) {
2152 if (u->meta.manager->running_as == MANAGER_USER) {
2155 e = getenv("XDG_RUNTIME_DIR");
2160 return strdup("/run");
2163 char *unit_name_printf(Unit *u, const char* format) {
2166 * This will use the passed string as format string and
2167 * replace the following specifiers:
2169 * %n: the full id of the unit (foo@bar.waldo)
2170 * %N: the id of the unit without the suffix (foo@bar)
2171 * %p: the prefix (foo)
2172 * %i: the instance (bar)
2175 const Specifier table[] = {
2176 { 'n', specifier_string, u->meta.id },
2177 { 'N', specifier_prefix_and_instance, NULL },
2178 { 'p', specifier_prefix, NULL },
2179 { 'i', specifier_string, u->meta.instance },
2186 return specifier_printf(format, table, u);
2189 char *unit_full_printf(Unit *u, const char *format) {
2191 /* This is similar to unit_name_printf() but also supports
2192 * unescaping. Also, adds a couple of additional codes:
2194 * %c cgroup path of unit
2195 * %r root cgroup path of this systemd instance (e.g. "/user/lennart/shared/systemd-4711")
2196 * %R parent of root cgroup path (e.g. "/usr/lennart/shared")
2197 * %t the runtime directory to place sockets in (e.g. "/run" or $XDG_RUNTIME_DIR)
2200 const Specifier table[] = {
2201 { 'n', specifier_string, u->meta.id },
2202 { 'N', specifier_prefix_and_instance, NULL },
2203 { 'p', specifier_prefix, NULL },
2204 { 'P', specifier_prefix_unescaped, NULL },
2205 { 'i', specifier_string, u->meta.instance },
2206 { 'I', specifier_instance_unescaped, NULL },
2207 { 'f', specifier_filename, NULL },
2208 { 'c', specifier_cgroup, NULL },
2209 { 'r', specifier_cgroup_root, NULL },
2210 { 'R', specifier_cgroup_root, NULL },
2211 { 't', specifier_runtime, NULL },
2218 return specifier_printf(format, table, u);
2221 char **unit_full_printf_strv(Unit *u, char **l) {
2225 /* Applies unit_full_printf to every entry in l */
2230 if (!(r = new(char*, n+1)))
2233 for (i = l, j = r; *i; i++, j++)
2234 if (!(*j = unit_full_printf(u, *i)))
2241 for (j--; j >= r; j--)
2249 int unit_watch_bus_name(Unit *u, const char *name) {
2253 /* Watch a specific name on the bus. We only support one unit
2254 * watching each name for now. */
2256 return hashmap_put(u->meta.manager->watch_bus, name, u);
2259 void unit_unwatch_bus_name(Unit *u, const char *name) {
2263 hashmap_remove_value(u->meta.manager->watch_bus, name, u);
2266 bool unit_can_serialize(Unit *u) {
2269 return UNIT_VTABLE(u)->serialize && UNIT_VTABLE(u)->deserialize_item;
2272 int unit_serialize(Unit *u, FILE *f, FDSet *fds) {
2279 if (!unit_can_serialize(u))
2282 if ((r = UNIT_VTABLE(u)->serialize(u, f, fds)) < 0)
2286 unit_serialize_item(u, f, "job", job_type_to_string(u->meta.job->type));
2288 dual_timestamp_serialize(f, "inactive-exit-timestamp", &u->meta.inactive_exit_timestamp);
2289 dual_timestamp_serialize(f, "active-enter-timestamp", &u->meta.active_enter_timestamp);
2290 dual_timestamp_serialize(f, "active-exit-timestamp", &u->meta.active_exit_timestamp);
2291 dual_timestamp_serialize(f, "inactive-enter-timestamp", &u->meta.inactive_enter_timestamp);
2292 dual_timestamp_serialize(f, "condition-timestamp", &u->meta.condition_timestamp);
2294 if (dual_timestamp_is_set(&u->meta.condition_timestamp))
2295 unit_serialize_item(u, f, "condition-result", yes_no(u->meta.condition_result));
2302 void unit_serialize_item_format(Unit *u, FILE *f, const char *key, const char *format, ...) {
2313 va_start(ap, format);
2314 vfprintf(f, format, ap);
2320 void unit_serialize_item(Unit *u, FILE *f, const char *key, const char *value) {
2326 fprintf(f, "%s=%s\n", key, value);
2329 int unit_deserialize(Unit *u, FILE *f, FDSet *fds) {
2336 if (!unit_can_serialize(u))
2340 char line[LINE_MAX], *l, *v;
2343 if (!fgets(line, sizeof(line), f)) {
2356 k = strcspn(l, "=");
2364 if (streq(l, "job")) {
2367 if ((type = job_type_from_string(v)) < 0)
2368 log_debug("Failed to parse job type value %s", v);
2370 u->meta.deserialized_job = type;
2373 } else if (streq(l, "inactive-exit-timestamp")) {
2374 dual_timestamp_deserialize(v, &u->meta.inactive_exit_timestamp);
2376 } else if (streq(l, "active-enter-timestamp")) {
2377 dual_timestamp_deserialize(v, &u->meta.active_enter_timestamp);
2379 } else if (streq(l, "active-exit-timestamp")) {
2380 dual_timestamp_deserialize(v, &u->meta.active_exit_timestamp);
2382 } else if (streq(l, "inactive-enter-timestamp")) {
2383 dual_timestamp_deserialize(v, &u->meta.inactive_enter_timestamp);
2385 } else if (streq(l, "condition-timestamp")) {
2386 dual_timestamp_deserialize(v, &u->meta.condition_timestamp);
2388 } else if (streq(l, "condition-result")) {
2391 if ((b = parse_boolean(v)) < 0)
2392 log_debug("Failed to parse condition result value %s", v);
2394 u->meta.condition_result = b;
2399 if ((r = UNIT_VTABLE(u)->deserialize_item(u, l, v, fds)) < 0)
2404 int unit_add_node_link(Unit *u, const char *what, bool wants) {
2414 /* Adds in links to the device node that this unit is based on */
2416 if (!is_device_path(what))
2419 if (!(e = unit_name_build_escape(what+1, NULL, ".device")))
2422 r = manager_load_unit(u->meta.manager, e, NULL, NULL, &device);
2428 if ((r = unit_add_two_dependencies(u, UNIT_AFTER, UNIT_BIND_TO, device, true)) < 0)
2432 if ((r = unit_add_dependency(device, UNIT_WANTS, u, false)) < 0)
2438 int unit_coldplug(Unit *u) {
2443 if (UNIT_VTABLE(u)->coldplug)
2444 if ((r = UNIT_VTABLE(u)->coldplug(u)) < 0)
2447 if (u->meta.deserialized_job >= 0) {
2448 if ((r = manager_add_job(u->meta.manager, u->meta.deserialized_job, u, JOB_IGNORE_REQUIREMENTS, false, NULL, NULL)) < 0)
2451 u->meta.deserialized_job = _JOB_TYPE_INVALID;
2457 void unit_status_printf(Unit *u, const char *status, const char *format, ...) {
2463 if (!UNIT_VTABLE(u)->show_status)
2466 if (!manager_get_show_status(u->meta.manager))
2469 if (!manager_is_booting_or_shutting_down(u->meta.manager))
2472 va_start(ap, format);
2473 status_vprintf(status, true, format, ap);
2477 bool unit_need_daemon_reload(Unit *u) {
2480 if (u->meta.fragment_path) {
2484 if (stat(u->meta.fragment_path, &st) < 0)
2485 /* What, cannot access this anymore? */
2488 if (u->meta.fragment_mtime > 0 &&
2489 timespec_load(&st.st_mtim) != u->meta.fragment_mtime)
2493 if (UNIT_VTABLE(u)->need_daemon_reload)
2494 return UNIT_VTABLE(u)->need_daemon_reload(u);
2499 void unit_reset_failed(Unit *u) {
2502 if (UNIT_VTABLE(u)->reset_failed)
2503 UNIT_VTABLE(u)->reset_failed(u);
2506 Unit *unit_following(Unit *u) {
2509 if (UNIT_VTABLE(u)->following)
2510 return UNIT_VTABLE(u)->following(u);
2515 bool unit_pending_inactive(Unit *u) {
2518 /* Returns true if the unit is inactive or going down */
2520 if (UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)))
2523 if (u->meta.job && u->meta.job->type == JOB_STOP)
2529 bool unit_pending_active(Unit *u) {
2532 /* Returns true if the unit is active or going up */
2534 if (UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)))
2538 (u->meta.job->type == JOB_START ||
2539 u->meta.job->type == JOB_RELOAD_OR_START ||
2540 u->meta.job->type == JOB_RESTART))
2546 UnitType unit_name_to_type(const char *n) {
2551 for (t = 0; t < _UNIT_TYPE_MAX; t++)
2552 if (endswith(n, unit_vtable[t]->suffix))
2555 return _UNIT_TYPE_INVALID;
2558 bool unit_name_is_valid(const char *n, bool template_ok) {
2561 t = unit_name_to_type(n);
2562 if (t < 0 || t >= _UNIT_TYPE_MAX)
2565 return unit_name_is_valid_no_type(n, template_ok);
2568 int unit_kill(Unit *u, KillWho w, KillMode m, int signo, DBusError *error) {
2570 assert(w >= 0 && w < _KILL_WHO_MAX);
2571 assert(m >= 0 && m < _KILL_MODE_MAX);
2573 assert(signo < _NSIG);
2578 if (!UNIT_VTABLE(u)->kill)
2581 return UNIT_VTABLE(u)->kill(u, w, m, signo, error);
2584 int unit_following_set(Unit *u, Set **s) {
2588 if (UNIT_VTABLE(u)->following_set)
2589 return UNIT_VTABLE(u)->following_set(u, s);
2595 UnitFileState unit_get_unit_file_state(Unit *u) {
2598 if (u->meta.unit_file_state < 0 && u->meta.fragment_path)
2599 u->meta.unit_file_state = unit_file_get_state(
2600 u->meta.manager->running_as == MANAGER_SYSTEM ? UNIT_FILE_SYSTEM : UNIT_FILE_USER,
2601 NULL, file_name_from_path(u->meta.fragment_path));
2603 return u->meta.unit_file_state;
2606 Unit* unit_ref_set(UnitRef *ref, Unit *u) {
2611 unit_ref_unset(ref);
2614 LIST_PREPEND(UnitRef, refs, u->meta.refs, ref);
2618 void unit_ref_unset(UnitRef *ref) {
2624 LIST_REMOVE(UnitRef, refs, ref->unit->meta.refs, ref);
2628 static const char* const unit_load_state_table[_UNIT_LOAD_STATE_MAX] = {
2629 [UNIT_STUB] = "stub",
2630 [UNIT_LOADED] = "loaded",
2631 [UNIT_ERROR] = "error",
2632 [UNIT_MERGED] = "merged",
2633 [UNIT_MASKED] = "masked"
2636 DEFINE_STRING_TABLE_LOOKUP(unit_load_state, UnitLoadState);
2638 static const char* const unit_active_state_table[_UNIT_ACTIVE_STATE_MAX] = {
2639 [UNIT_ACTIVE] = "active",
2640 [UNIT_RELOADING] = "reloading",
2641 [UNIT_INACTIVE] = "inactive",
2642 [UNIT_FAILED] = "failed",
2643 [UNIT_ACTIVATING] = "activating",
2644 [UNIT_DEACTIVATING] = "deactivating"
2647 DEFINE_STRING_TABLE_LOOKUP(unit_active_state, UnitActiveState);
2649 static const char* const unit_dependency_table[_UNIT_DEPENDENCY_MAX] = {
2650 [UNIT_REQUIRES] = "Requires",
2651 [UNIT_REQUIRES_OVERRIDABLE] = "RequiresOverridable",
2652 [UNIT_WANTS] = "Wants",
2653 [UNIT_REQUISITE] = "Requisite",
2654 [UNIT_REQUISITE_OVERRIDABLE] = "RequisiteOverridable",
2655 [UNIT_REQUIRED_BY] = "RequiredBy",
2656 [UNIT_REQUIRED_BY_OVERRIDABLE] = "RequiredByOverridable",
2657 [UNIT_BIND_TO] = "BindTo",
2658 [UNIT_WANTED_BY] = "WantedBy",
2659 [UNIT_CONFLICTS] = "Conflicts",
2660 [UNIT_CONFLICTED_BY] = "ConflictedBy",
2661 [UNIT_BOUND_BY] = "BoundBy",
2662 [UNIT_BEFORE] = "Before",
2663 [UNIT_AFTER] = "After",
2664 [UNIT_REFERENCES] = "References",
2665 [UNIT_REFERENCED_BY] = "ReferencedBy",
2666 [UNIT_ON_FAILURE] = "OnFailure",
2667 [UNIT_TRIGGERS] = "Triggers",
2668 [UNIT_TRIGGERED_BY] = "TriggeredBy",
2669 [UNIT_PROPAGATE_RELOAD_TO] = "PropagateReloadTo",
2670 [UNIT_PROPAGATE_RELOAD_FROM] = "PropagateReloadFrom"
2673 DEFINE_STRING_TABLE_LOOKUP(unit_dependency, UnitDependency);