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"
46 const UnitVTable * const unit_vtable[_UNIT_TYPE_MAX] = {
47 [UNIT_SERVICE] = &service_vtable,
48 [UNIT_TIMER] = &timer_vtable,
49 [UNIT_SOCKET] = &socket_vtable,
50 [UNIT_TARGET] = &target_vtable,
51 [UNIT_DEVICE] = &device_vtable,
52 [UNIT_MOUNT] = &mount_vtable,
53 [UNIT_AUTOMOUNT] = &automount_vtable,
54 [UNIT_SNAPSHOT] = &snapshot_vtable,
55 [UNIT_SWAP] = &swap_vtable,
56 [UNIT_PATH] = &path_vtable
59 Unit *unit_new(Manager *m) {
64 if (!(u = new0(Unit, 1)))
67 if (!(u->meta.names = set_new(string_hash_func, string_compare_func))) {
73 u->meta.type = _UNIT_TYPE_INVALID;
74 u->meta.deserialized_job = _JOB_TYPE_INVALID;
75 u->meta.default_dependencies = true;
76 u->meta.unit_file_state = _UNIT_FILE_STATE_INVALID;
81 bool unit_has_name(Unit *u, const char *name) {
85 return !!set_get(u->meta.names, (char*) name);
88 int unit_add_name(Unit *u, const char *text) {
96 if (unit_name_is_template(text)) {
97 if (!u->meta.instance)
100 s = unit_name_replace_instance(text, u->meta.instance);
107 if (!unit_name_is_valid(s, false)) {
112 assert_se((t = unit_name_to_type(s)) >= 0);
114 if (u->meta.type != _UNIT_TYPE_INVALID && t != u->meta.type) {
119 if ((r = unit_name_to_instance(s, &i)) < 0)
122 if (i && unit_vtable[t]->no_instances) {
127 /* Ensure that this unit is either instanced or not instanced,
129 if (u->meta.type != _UNIT_TYPE_INVALID && !u->meta.instance != !i) {
134 if (unit_vtable[t]->no_alias &&
135 !set_isempty(u->meta.names) &&
136 !set_get(u->meta.names, s)) {
141 if (hashmap_size(u->meta.manager->units) >= MANAGER_MAX_NAMES) {
146 if ((r = set_put(u->meta.names, s)) < 0) {
152 if ((r = hashmap_put(u->meta.manager->units, s, u)) < 0) {
153 set_remove(u->meta.names, s);
157 if (u->meta.type == _UNIT_TYPE_INVALID) {
161 u->meta.instance = i;
163 LIST_PREPEND(Meta, units_by_type, u->meta.manager->units_by_type[t], &u->meta);
165 if (UNIT_VTABLE(u)->init)
166 UNIT_VTABLE(u)->init(u);
170 unit_add_to_dbus_queue(u);
180 int unit_choose_id(Unit *u, const char *name) {
181 char *s, *t = NULL, *i;
187 if (unit_name_is_template(name)) {
189 if (!u->meta.instance)
192 if (!(t = unit_name_replace_instance(name, u->meta.instance)))
198 /* Selects one of the names of this unit as the id */
199 s = set_get(u->meta.names, (char*) name);
205 if ((r = unit_name_to_instance(s, &i)) < 0)
210 free(u->meta.instance);
211 u->meta.instance = i;
213 unit_add_to_dbus_queue(u);
218 int unit_set_description(Unit *u, const char *description) {
223 if (!(s = strdup(description)))
226 free(u->meta.description);
227 u->meta.description = s;
229 unit_add_to_dbus_queue(u);
233 bool unit_check_gc(Unit *u) {
236 if (u->meta.load_state == UNIT_STUB)
239 if (UNIT_VTABLE(u)->no_gc)
248 if (unit_active_state(u) != UNIT_INACTIVE)
251 if (UNIT_VTABLE(u)->check_gc)
252 if (UNIT_VTABLE(u)->check_gc(u))
258 void unit_add_to_load_queue(Unit *u) {
260 assert(u->meta.type != _UNIT_TYPE_INVALID);
262 if (u->meta.load_state != UNIT_STUB || u->meta.in_load_queue)
265 LIST_PREPEND(Meta, load_queue, u->meta.manager->load_queue, &u->meta);
266 u->meta.in_load_queue = true;
269 void unit_add_to_cleanup_queue(Unit *u) {
272 if (u->meta.in_cleanup_queue)
275 LIST_PREPEND(Meta, cleanup_queue, u->meta.manager->cleanup_queue, &u->meta);
276 u->meta.in_cleanup_queue = true;
279 void unit_add_to_gc_queue(Unit *u) {
282 if (u->meta.in_gc_queue || u->meta.in_cleanup_queue)
285 if (unit_check_gc(u))
288 LIST_PREPEND(Meta, gc_queue, u->meta.manager->gc_queue, &u->meta);
289 u->meta.in_gc_queue = true;
291 u->meta.manager->n_in_gc_queue ++;
293 if (u->meta.manager->gc_queue_timestamp <= 0)
294 u->meta.manager->gc_queue_timestamp = now(CLOCK_MONOTONIC);
297 void unit_add_to_dbus_queue(Unit *u) {
299 assert(u->meta.type != _UNIT_TYPE_INVALID);
301 if (u->meta.load_state == UNIT_STUB || u->meta.in_dbus_queue)
304 /* Shortcut things if nobody cares */
305 if (!bus_has_subscriber(u->meta.manager)) {
306 u->meta.sent_dbus_new_signal = true;
310 LIST_PREPEND(Meta, dbus_queue, u->meta.manager->dbus_unit_queue, &u->meta);
311 u->meta.in_dbus_queue = true;
314 static void bidi_set_free(Unit *u, Set *s) {
320 /* Frees the set and makes sure we are dropped from the
321 * inverse pointers */
323 SET_FOREACH(other, s, i) {
326 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
327 set_remove(other->meta.dependencies[d], u);
329 unit_add_to_gc_queue(other);
335 void unit_free(Unit *u) {
342 bus_unit_send_removed_signal(u);
344 if (u->meta.load_state != UNIT_STUB)
345 if (UNIT_VTABLE(u)->done)
346 UNIT_VTABLE(u)->done(u);
348 SET_FOREACH(t, u->meta.names, i)
349 hashmap_remove_value(u->meta.manager->units, t, u);
352 job_free(u->meta.job);
354 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
355 bidi_set_free(u, u->meta.dependencies[d]);
357 if (u->meta.type != _UNIT_TYPE_INVALID)
358 LIST_REMOVE(Meta, units_by_type, u->meta.manager->units_by_type[u->meta.type], &u->meta);
360 if (u->meta.in_load_queue)
361 LIST_REMOVE(Meta, load_queue, u->meta.manager->load_queue, &u->meta);
363 if (u->meta.in_dbus_queue)
364 LIST_REMOVE(Meta, dbus_queue, u->meta.manager->dbus_unit_queue, &u->meta);
366 if (u->meta.in_cleanup_queue)
367 LIST_REMOVE(Meta, cleanup_queue, u->meta.manager->cleanup_queue, &u->meta);
369 if (u->meta.in_gc_queue) {
370 LIST_REMOVE(Meta, gc_queue, u->meta.manager->gc_queue, &u->meta);
371 u->meta.manager->n_in_gc_queue--;
374 cgroup_bonding_free_list(u->meta.cgroup_bondings, u->meta.manager->n_reloading <= 0);
376 free(u->meta.description);
377 free(u->meta.fragment_path);
379 set_free_free(u->meta.names);
381 condition_free_list(u->meta.conditions);
383 free(u->meta.instance);
387 UnitActiveState unit_active_state(Unit *u) {
390 if (u->meta.load_state == UNIT_MERGED)
391 return unit_active_state(unit_follow_merge(u));
393 /* After a reload it might happen that a unit is not correctly
394 * loaded but still has a process around. That's why we won't
395 * shortcut failed loading to UNIT_INACTIVE_FAILED. */
397 return UNIT_VTABLE(u)->active_state(u);
400 const char* unit_sub_state_to_string(Unit *u) {
403 return UNIT_VTABLE(u)->sub_state_to_string(u);
406 static void complete_move(Set **s, Set **other) {
414 set_move(*s, *other);
421 static void merge_names(Unit *u, Unit *other) {
428 complete_move(&u->meta.names, &other->meta.names);
430 set_free_free(other->meta.names);
431 other->meta.names = NULL;
432 other->meta.id = NULL;
434 SET_FOREACH(t, u->meta.names, i)
435 assert_se(hashmap_replace(u->meta.manager->units, t, u) == 0);
438 static void merge_dependencies(Unit *u, Unit *other, UnitDependency d) {
445 assert(d < _UNIT_DEPENDENCY_MAX);
447 /* Fix backwards pointers */
448 SET_FOREACH(back, other->meta.dependencies[d], i) {
451 for (k = 0; k < _UNIT_DEPENDENCY_MAX; k++)
452 if ((r = set_remove_and_put(back->meta.dependencies[k], other, u)) < 0) {
455 set_remove(back->meta.dependencies[k], other);
457 assert(r == -ENOENT);
461 complete_move(&u->meta.dependencies[d], &other->meta.dependencies[d]);
463 set_free(other->meta.dependencies[d]);
464 other->meta.dependencies[d] = NULL;
467 int unit_merge(Unit *u, Unit *other) {
472 assert(u->meta.manager == other->meta.manager);
473 assert(u->meta.type != _UNIT_TYPE_INVALID);
475 other = unit_follow_merge(other);
480 if (u->meta.type != other->meta.type)
483 if (!u->meta.instance != !other->meta.instance)
486 if (other->meta.load_state != UNIT_STUB &&
487 other->meta.load_state != UNIT_ERROR)
493 if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other)))
497 merge_names(u, other);
499 /* Merge dependencies */
500 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
501 merge_dependencies(u, other, d);
503 other->meta.load_state = UNIT_MERGED;
504 other->meta.merged_into = u;
506 /* If there is still some data attached to the other node, we
507 * don't need it anymore, and can free it. */
508 if (other->meta.load_state != UNIT_STUB)
509 if (UNIT_VTABLE(other)->done)
510 UNIT_VTABLE(other)->done(other);
512 unit_add_to_dbus_queue(u);
513 unit_add_to_cleanup_queue(other);
518 int unit_merge_by_name(Unit *u, const char *name) {
526 if (unit_name_is_template(name)) {
527 if (!u->meta.instance)
530 if (!(s = unit_name_replace_instance(name, u->meta.instance)))
536 if (!(other = manager_get_unit(u->meta.manager, name)))
537 r = unit_add_name(u, name);
539 r = unit_merge(u, other);
545 Unit* unit_follow_merge(Unit *u) {
548 while (u->meta.load_state == UNIT_MERGED)
549 assert_se(u = u->meta.merged_into);
554 int unit_add_exec_dependencies(Unit *u, ExecContext *c) {
560 if (c->std_output != EXEC_OUTPUT_KMSG &&
561 c->std_output != EXEC_OUTPUT_SYSLOG &&
562 c->std_output != EXEC_OUTPUT_KMSG_AND_CONSOLE &&
563 c->std_output != EXEC_OUTPUT_SYSLOG_AND_CONSOLE &&
564 c->std_error != EXEC_OUTPUT_KMSG &&
565 c->std_error != EXEC_OUTPUT_SYSLOG_AND_CONSOLE &&
566 c->std_error != EXEC_OUTPUT_KMSG &&
567 c->std_error != EXEC_OUTPUT_SYSLOG_AND_CONSOLE)
570 /* If syslog or kernel logging is requested, make sure our own
571 * logging daemon is run first. */
573 if (u->meta.manager->running_as == MANAGER_SYSTEM)
574 if ((r = unit_add_two_dependencies_by_name(u, UNIT_REQUIRES, UNIT_AFTER, SPECIAL_LOGGER_SOCKET, NULL, true)) < 0)
580 const char *unit_description(Unit *u) {
583 if (u->meta.description)
584 return u->meta.description;
586 return strna(u->meta.id);
589 void unit_dump(Unit *u, FILE *f, const char *prefix) {
597 timestamp1[FORMAT_TIMESTAMP_MAX],
598 timestamp2[FORMAT_TIMESTAMP_MAX],
599 timestamp3[FORMAT_TIMESTAMP_MAX],
600 timestamp4[FORMAT_TIMESTAMP_MAX],
601 timespan[FORMAT_TIMESPAN_MAX];
605 assert(u->meta.type >= 0);
609 p2 = strappend(prefix, "\t");
610 prefix2 = p2 ? p2 : prefix;
614 "%s\tDescription: %s\n"
616 "%s\tUnit Load State: %s\n"
617 "%s\tUnit Active State: %s\n"
618 "%s\tInactive Exit Timestamp: %s\n"
619 "%s\tActive Enter Timestamp: %s\n"
620 "%s\tActive Exit Timestamp: %s\n"
621 "%s\tInactive Enter Timestamp: %s\n"
622 "%s\tGC Check Good: %s\n"
623 "%s\tNeed Daemon Reload: %s\n",
625 prefix, unit_description(u),
626 prefix, strna(u->meta.instance),
627 prefix, unit_load_state_to_string(u->meta.load_state),
628 prefix, unit_active_state_to_string(unit_active_state(u)),
629 prefix, strna(format_timestamp(timestamp1, sizeof(timestamp1), u->meta.inactive_exit_timestamp.realtime)),
630 prefix, strna(format_timestamp(timestamp2, sizeof(timestamp2), u->meta.active_enter_timestamp.realtime)),
631 prefix, strna(format_timestamp(timestamp3, sizeof(timestamp3), u->meta.active_exit_timestamp.realtime)),
632 prefix, strna(format_timestamp(timestamp4, sizeof(timestamp4), u->meta.inactive_enter_timestamp.realtime)),
633 prefix, yes_no(unit_check_gc(u)),
634 prefix, yes_no(unit_need_daemon_reload(u)));
636 SET_FOREACH(t, u->meta.names, i)
637 fprintf(f, "%s\tName: %s\n", prefix, t);
639 if ((following = unit_following(u)))
640 fprintf(f, "%s\tFollowing: %s\n", prefix, following->meta.id);
642 if (u->meta.fragment_path)
643 fprintf(f, "%s\tFragment Path: %s\n", prefix, u->meta.fragment_path);
645 if (u->meta.job_timeout > 0)
646 fprintf(f, "%s\tJob Timeout: %s\n", prefix, format_timespan(timespan, sizeof(timespan), u->meta.job_timeout));
648 condition_dump_list(u->meta.conditions, f, prefix);
650 if (dual_timestamp_is_set(&u->meta.condition_timestamp))
652 "%s\tCondition Timestamp: %s\n"
653 "%s\tCondition Result: %s\n",
654 prefix, strna(format_timestamp(timestamp1, sizeof(timestamp1), u->meta.condition_timestamp.realtime)),
655 prefix, yes_no(u->meta.condition_result));
657 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++) {
660 SET_FOREACH(other, u->meta.dependencies[d], i)
661 fprintf(f, "%s\t%s: %s\n", prefix, unit_dependency_to_string(d), other->meta.id);
664 if (u->meta.load_state == UNIT_LOADED) {
666 "%s\tStopWhenUnneeded: %s\n"
667 "%s\tRefuseManualStart: %s\n"
668 "%s\tRefuseManualStop: %s\n"
669 "%s\tDefaultDependencies: %s\n"
670 "%s\tOnFailureIsolate: %s\n"
671 "%s\tIgnoreOnIsolate: %s\n"
672 "%s\tIgnoreOnSnapshot: %s\n",
673 prefix, yes_no(u->meta.stop_when_unneeded),
674 prefix, yes_no(u->meta.refuse_manual_start),
675 prefix, yes_no(u->meta.refuse_manual_stop),
676 prefix, yes_no(u->meta.default_dependencies),
677 prefix, yes_no(u->meta.on_failure_isolate),
678 prefix, yes_no(u->meta.ignore_on_isolate),
679 prefix, yes_no(u->meta.ignore_on_snapshot));
681 LIST_FOREACH(by_unit, b, u->meta.cgroup_bondings)
682 fprintf(f, "%s\tControlGroup: %s:%s\n",
683 prefix, b->controller, b->path);
685 if (UNIT_VTABLE(u)->dump)
686 UNIT_VTABLE(u)->dump(u, f, prefix2);
688 } else if (u->meta.load_state == UNIT_MERGED)
690 "%s\tMerged into: %s\n",
691 prefix, u->meta.merged_into->meta.id);
692 else if (u->meta.load_state == UNIT_ERROR)
693 fprintf(f, "%s\tLoad Error Code: %s\n", prefix, strerror(-u->meta.load_error));
697 job_dump(u->meta.job, f, prefix2);
702 /* Common implementation for multiple backends */
703 int unit_load_fragment_and_dropin(Unit *u) {
708 /* Load a .service file */
709 if ((r = unit_load_fragment(u)) < 0)
712 if (u->meta.load_state == UNIT_STUB)
715 /* Load drop-in directory data */
716 if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
722 /* Common implementation for multiple backends */
723 int unit_load_fragment_and_dropin_optional(Unit *u) {
728 /* Same as unit_load_fragment_and_dropin(), but whether
729 * something can be loaded or not doesn't matter. */
731 /* Load a .service file */
732 if ((r = unit_load_fragment(u)) < 0)
735 if (u->meta.load_state == UNIT_STUB)
736 u->meta.load_state = UNIT_LOADED;
738 /* Load drop-in directory data */
739 if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
745 int unit_add_default_target_dependency(Unit *u, Unit *target) {
749 if (target->meta.type != UNIT_TARGET)
752 /* Only add the dependency if both units are loaded, so that
753 * that loop check below is reliable */
754 if (u->meta.load_state != UNIT_LOADED ||
755 target->meta.load_state != UNIT_LOADED)
758 /* If either side wants no automatic dependencies, then let's
760 if (!u->meta.default_dependencies ||
761 target->meta.default_dependencies)
764 /* Don't create loops */
765 if (set_get(target->meta.dependencies[UNIT_BEFORE], u))
768 return unit_add_dependency(target, UNIT_AFTER, u, true);
771 static int unit_add_default_dependencies(Unit *u) {
772 static const UnitDependency deps[] = {
774 UNIT_REQUIRED_BY_OVERRIDABLE,
786 for (k = 0; k < ELEMENTSOF(deps); k++)
787 SET_FOREACH(target, u->meta.dependencies[deps[k]], i)
788 if ((r = unit_add_default_target_dependency(u, target)) < 0)
794 int unit_load(Unit *u) {
799 if (u->meta.in_load_queue) {
800 LIST_REMOVE(Meta, load_queue, u->meta.manager->load_queue, &u->meta);
801 u->meta.in_load_queue = false;
804 if (u->meta.type == _UNIT_TYPE_INVALID)
807 if (u->meta.load_state != UNIT_STUB)
810 if (UNIT_VTABLE(u)->load)
811 if ((r = UNIT_VTABLE(u)->load(u)) < 0)
814 if (u->meta.load_state == UNIT_STUB) {
819 if (u->meta.load_state == UNIT_LOADED &&
820 u->meta.default_dependencies)
821 if ((r = unit_add_default_dependencies(u)) < 0)
824 if (u->meta.on_failure_isolate &&
825 set_size(u->meta.dependencies[UNIT_ON_FAILURE]) > 1) {
827 log_error("More than one OnFailure= dependencies specified for %s but OnFailureIsolate= enabled. Refusing.",
834 assert((u->meta.load_state != UNIT_MERGED) == !u->meta.merged_into);
836 unit_add_to_dbus_queue(unit_follow_merge(u));
837 unit_add_to_gc_queue(u);
842 u->meta.load_state = UNIT_ERROR;
843 u->meta.load_error = r;
844 unit_add_to_dbus_queue(u);
846 log_debug("Failed to load configuration for %s: %s", u->meta.id, strerror(-r));
851 bool unit_condition_test(Unit *u) {
854 dual_timestamp_get(&u->meta.condition_timestamp);
855 u->meta.condition_result = condition_test_list(u->meta.conditions);
857 return u->meta.condition_result;
861 * -EBADR: This unit type does not support starting.
862 * -EALREADY: Unit is already started.
863 * -EAGAIN: An operation is already in progress. Retry later.
864 * -ECANCELED: Too many requests for now.
866 int unit_start(Unit *u) {
867 UnitActiveState state;
872 if (u->meta.load_state != UNIT_LOADED)
875 /* If this is already (being) started, then this will
876 * succeed. Note that this will even succeed if this unit is
877 * not startable by the user. This is relied on to detect when
878 * we need to wait for units and when waiting is finished. */
879 state = unit_active_state(u);
880 if (UNIT_IS_ACTIVE_OR_RELOADING(state))
883 /* If the conditions failed, don't do anything at all */
884 if (!unit_condition_test(u)) {
885 log_debug("Starting of %s requested but condition failed. Ignoring.", u->meta.id);
889 /* Forward to the main object, if we aren't it. */
890 if ((following = unit_following(u))) {
891 log_debug("Redirecting start request from %s to %s.", u->meta.id, following->meta.id);
892 return unit_start(following);
895 /* If it is stopped, but we cannot start it, then fail */
896 if (!UNIT_VTABLE(u)->start)
899 /* We don't suppress calls to ->start() here when we are
900 * already starting, to allow this request to be used as a
901 * "hurry up" call, for example when the unit is in some "auto
902 * restart" state where it waits for a holdoff timer to elapse
903 * before it will start again. */
905 unit_add_to_dbus_queue(u);
907 unit_status_printf(u, "Starting %s...\n", unit_description(u));
908 return UNIT_VTABLE(u)->start(u);
911 bool unit_can_start(Unit *u) {
914 return !!UNIT_VTABLE(u)->start;
917 bool unit_can_isolate(Unit *u) {
920 return unit_can_start(u) &&
921 u->meta.allow_isolate;
925 * -EBADR: This unit type does not support stopping.
926 * -EALREADY: Unit is already stopped.
927 * -EAGAIN: An operation is already in progress. Retry later.
929 int unit_stop(Unit *u) {
930 UnitActiveState state;
935 state = unit_active_state(u);
936 if (UNIT_IS_INACTIVE_OR_FAILED(state))
939 if ((following = unit_following(u))) {
940 log_debug("Redirecting stop request from %s to %s.", u->meta.id, following->meta.id);
941 return unit_stop(following);
944 if (!UNIT_VTABLE(u)->stop)
947 unit_add_to_dbus_queue(u);
949 unit_status_printf(u, "Stopping %s...\n", unit_description(u));
950 return UNIT_VTABLE(u)->stop(u);
954 * -EBADR: This unit type does not support reloading.
955 * -ENOEXEC: Unit is not started.
956 * -EAGAIN: An operation is already in progress. Retry later.
958 int unit_reload(Unit *u) {
959 UnitActiveState state;
964 if (u->meta.load_state != UNIT_LOADED)
967 if (!unit_can_reload(u))
970 state = unit_active_state(u);
971 if (state == UNIT_RELOADING)
974 if (state != UNIT_ACTIVE)
977 if ((following = unit_following(u))) {
978 log_debug("Redirecting reload request from %s to %s.", u->meta.id, following->meta.id);
979 return unit_reload(following);
982 unit_add_to_dbus_queue(u);
983 return UNIT_VTABLE(u)->reload(u);
986 bool unit_can_reload(Unit *u) {
989 if (!UNIT_VTABLE(u)->reload)
992 if (!UNIT_VTABLE(u)->can_reload)
995 return UNIT_VTABLE(u)->can_reload(u);
998 static void unit_check_unneeded(Unit *u) {
1004 /* If this service shall be shut down when unneeded then do
1007 if (!u->meta.stop_when_unneeded)
1010 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)))
1013 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRED_BY], i)
1014 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1017 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRED_BY_OVERRIDABLE], i)
1018 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1021 SET_FOREACH(other, u->meta.dependencies[UNIT_WANTED_BY], i)
1022 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1025 SET_FOREACH(other, u->meta.dependencies[UNIT_BOUND_BY], i)
1026 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1029 log_info("Service %s is not needed anymore. Stopping.", u->meta.id);
1031 /* Ok, nobody needs us anymore. Sniff. Then let's commit suicide */
1032 manager_add_job(u->meta.manager, JOB_STOP, u, JOB_FAIL, true, NULL, NULL);
1035 static void retroactively_start_dependencies(Unit *u) {
1040 assert(UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)));
1042 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRES], i)
1043 if (!set_get(u->meta.dependencies[UNIT_AFTER], other) &&
1044 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
1045 manager_add_job(u->meta.manager, JOB_START, other, JOB_REPLACE, true, NULL, NULL);
1047 SET_FOREACH(other, u->meta.dependencies[UNIT_BIND_TO], i)
1048 if (!set_get(u->meta.dependencies[UNIT_AFTER], other) &&
1049 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
1050 manager_add_job(u->meta.manager, JOB_START, other, JOB_REPLACE, true, NULL, NULL);
1052 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRES_OVERRIDABLE], i)
1053 if (!set_get(u->meta.dependencies[UNIT_AFTER], other) &&
1054 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
1055 manager_add_job(u->meta.manager, JOB_START, other, JOB_FAIL, false, NULL, NULL);
1057 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUISITE], i)
1058 if (!set_get(u->meta.dependencies[UNIT_AFTER], other) &&
1059 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
1060 manager_add_job(u->meta.manager, JOB_START, other, JOB_REPLACE, true, NULL, NULL);
1062 SET_FOREACH(other, u->meta.dependencies[UNIT_WANTS], i)
1063 if (!set_get(u->meta.dependencies[UNIT_AFTER], other) &&
1064 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
1065 manager_add_job(u->meta.manager, JOB_START, other, JOB_FAIL, false, NULL, NULL);
1067 SET_FOREACH(other, u->meta.dependencies[UNIT_CONFLICTS], i)
1068 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1069 manager_add_job(u->meta.manager, JOB_STOP, other, JOB_REPLACE, true, NULL, NULL);
1071 SET_FOREACH(other, u->meta.dependencies[UNIT_CONFLICTED_BY], i)
1072 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1073 manager_add_job(u->meta.manager, JOB_STOP, other, JOB_REPLACE, true, NULL, NULL);
1076 static void retroactively_stop_dependencies(Unit *u) {
1081 assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)));
1083 /* Pull down units which are bound to us recursively if enabled */
1084 SET_FOREACH(other, u->meta.dependencies[UNIT_BOUND_BY], i)
1085 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1086 manager_add_job(u->meta.manager, JOB_STOP, other, JOB_REPLACE, true, NULL, NULL);
1088 /* Garbage collect services that might not be needed anymore, if enabled */
1089 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRES], i)
1090 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1091 unit_check_unneeded(other);
1092 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRES_OVERRIDABLE], i)
1093 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1094 unit_check_unneeded(other);
1095 SET_FOREACH(other, u->meta.dependencies[UNIT_WANTS], i)
1096 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1097 unit_check_unneeded(other);
1098 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUISITE], i)
1099 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1100 unit_check_unneeded(other);
1101 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUISITE_OVERRIDABLE], i)
1102 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1103 unit_check_unneeded(other);
1104 SET_FOREACH(other, u->meta.dependencies[UNIT_BIND_TO], i)
1105 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1106 unit_check_unneeded(other);
1109 void unit_trigger_on_failure(Unit *u) {
1115 if (set_size(u->meta.dependencies[UNIT_ON_FAILURE]) <= 0)
1118 log_info("Triggering OnFailure= dependencies of %s.", u->meta.id);
1120 SET_FOREACH(other, u->meta.dependencies[UNIT_ON_FAILURE], i) {
1123 if ((r = manager_add_job(u->meta.manager, JOB_START, other, u->meta.on_failure_isolate ? JOB_ISOLATE : JOB_REPLACE, true, NULL, NULL)) < 0)
1124 log_error("Failed to enqueue OnFailure= job: %s", strerror(-r));
1128 void unit_notify(Unit *u, UnitActiveState os, UnitActiveState ns, bool reload_success) {
1132 assert(os < _UNIT_ACTIVE_STATE_MAX);
1133 assert(ns < _UNIT_ACTIVE_STATE_MAX);
1135 /* Note that this is called for all low-level state changes,
1136 * even if they might map to the same high-level
1137 * UnitActiveState! That means that ns == os is OK an expected
1138 * behaviour here. For example: if a mount point is remounted
1139 * this function will be called too! */
1141 if (u->meta.manager->n_reloading <= 0) {
1144 dual_timestamp_get(&ts);
1146 if (UNIT_IS_INACTIVE_OR_FAILED(os) && !UNIT_IS_INACTIVE_OR_FAILED(ns))
1147 u->meta.inactive_exit_timestamp = ts;
1148 else if (!UNIT_IS_INACTIVE_OR_FAILED(os) && UNIT_IS_INACTIVE_OR_FAILED(ns))
1149 u->meta.inactive_enter_timestamp = ts;
1151 if (!UNIT_IS_ACTIVE_OR_RELOADING(os) && UNIT_IS_ACTIVE_OR_RELOADING(ns))
1152 u->meta.active_enter_timestamp = ts;
1153 else if (UNIT_IS_ACTIVE_OR_RELOADING(os) && !UNIT_IS_ACTIVE_OR_RELOADING(ns))
1154 u->meta.active_exit_timestamp = ts;
1156 timer_unit_notify(u, ns);
1157 path_unit_notify(u, ns);
1160 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
1161 cgroup_bonding_trim_list(u->meta.cgroup_bondings, true);
1166 if (u->meta.job->state == JOB_WAITING)
1168 /* So we reached a different state for this
1169 * job. Let's see if we can run it now if it
1170 * failed previously due to EAGAIN. */
1171 job_add_to_run_queue(u->meta.job);
1173 /* Let's check whether this state change constitutes a
1174 * finished job, or maybe contradicts a running job and
1175 * hence needs to invalidate jobs. */
1177 switch (u->meta.job->type) {
1180 case JOB_VERIFY_ACTIVE:
1182 if (UNIT_IS_ACTIVE_OR_RELOADING(ns))
1183 job_finish_and_invalidate(u->meta.job, JOB_DONE);
1184 else if (u->meta.job->state == JOB_RUNNING && ns != UNIT_ACTIVATING) {
1187 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
1188 job_finish_and_invalidate(u->meta.job, ns == UNIT_FAILED ? JOB_FAILED : JOB_DONE);
1194 case JOB_RELOAD_OR_START:
1196 if (u->meta.job->state == JOB_RUNNING) {
1197 if (ns == UNIT_ACTIVE)
1198 job_finish_and_invalidate(u->meta.job, reload_success ? JOB_DONE : JOB_FAILED);
1199 else if (ns != UNIT_ACTIVATING && ns != UNIT_RELOADING) {
1202 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
1203 job_finish_and_invalidate(u->meta.job, ns == UNIT_FAILED ? JOB_FAILED : JOB_DONE);
1211 case JOB_TRY_RESTART:
1213 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
1214 job_finish_and_invalidate(u->meta.job, JOB_DONE);
1215 else if (u->meta.job->state == JOB_RUNNING && ns != UNIT_DEACTIVATING) {
1217 job_finish_and_invalidate(u->meta.job, JOB_FAILED);
1223 assert_not_reached("Job type unknown");
1229 if (u->meta.manager->n_reloading <= 0) {
1231 /* If this state change happened without being
1232 * requested by a job, then let's retroactively start
1233 * or stop dependencies. We skip that step when
1234 * deserializing, since we don't want to create any
1235 * additional jobs just because something is already
1239 if (UNIT_IS_INACTIVE_OR_FAILED(os) && UNIT_IS_ACTIVE_OR_ACTIVATING(ns))
1240 retroactively_start_dependencies(u);
1241 else if (UNIT_IS_ACTIVE_OR_ACTIVATING(os) && UNIT_IS_INACTIVE_OR_DEACTIVATING(ns))
1242 retroactively_stop_dependencies(u);
1245 if (ns != os && ns == UNIT_FAILED) {
1246 log_notice("Unit %s entered failed state.", u->meta.id);
1247 unit_trigger_on_failure(u);
1251 /* Some names are special */
1252 if (UNIT_IS_ACTIVE_OR_RELOADING(ns)) {
1254 if (unit_has_name(u, SPECIAL_DBUS_SERVICE))
1255 /* The bus just might have become available,
1256 * hence try to connect to it, if we aren't
1258 bus_init(u->meta.manager, true);
1260 if (u->meta.type == UNIT_SERVICE &&
1261 !UNIT_IS_ACTIVE_OR_RELOADING(os) &&
1262 u->meta.manager->n_reloading <= 0) {
1263 /* Write audit record if we have just finished starting up */
1264 manager_send_unit_audit(u->meta.manager, u, AUDIT_SERVICE_START, true);
1265 u->meta.in_audit = true;
1268 if (!UNIT_IS_ACTIVE_OR_RELOADING(os))
1269 manager_send_unit_plymouth(u->meta.manager, u);
1273 /* We don't care about D-Bus here, since we'll get an
1274 * asynchronous notification for it anyway. */
1276 if (u->meta.type == UNIT_SERVICE &&
1277 UNIT_IS_INACTIVE_OR_FAILED(ns) &&
1278 !UNIT_IS_INACTIVE_OR_FAILED(os) &&
1279 u->meta.manager->n_reloading <= 0) {
1281 /* Hmm, if there was no start record written
1282 * write it now, so that we always have a nice
1284 if (!u->meta.in_audit) {
1285 manager_send_unit_audit(u->meta.manager, u, AUDIT_SERVICE_START, ns == UNIT_INACTIVE);
1287 if (ns == UNIT_INACTIVE)
1288 manager_send_unit_audit(u->meta.manager, u, AUDIT_SERVICE_STOP, true);
1290 /* Write audit record if we have just finished shutting down */
1291 manager_send_unit_audit(u->meta.manager, u, AUDIT_SERVICE_STOP, ns == UNIT_INACTIVE);
1293 u->meta.in_audit = false;
1297 manager_recheck_syslog(u->meta.manager);
1299 /* Maybe we finished startup and are now ready for being
1300 * stopped because unneeded? */
1301 unit_check_unneeded(u);
1303 unit_add_to_dbus_queue(u);
1304 unit_add_to_gc_queue(u);
1307 int unit_watch_fd(Unit *u, int fd, uint32_t events, Watch *w) {
1308 struct epoll_event ev;
1313 assert(w->type == WATCH_INVALID || (w->type == WATCH_FD && w->fd == fd && w->data.unit == u));
1319 if (epoll_ctl(u->meta.manager->epoll_fd,
1320 w->type == WATCH_INVALID ? EPOLL_CTL_ADD : EPOLL_CTL_MOD,
1332 void unit_unwatch_fd(Unit *u, Watch *w) {
1336 if (w->type == WATCH_INVALID)
1339 assert(w->type == WATCH_FD);
1340 assert(w->data.unit == u);
1341 assert_se(epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_DEL, w->fd, NULL) >= 0);
1344 w->type = WATCH_INVALID;
1345 w->data.unit = NULL;
1348 int unit_watch_pid(Unit *u, pid_t pid) {
1352 /* Watch a specific PID. We only support one unit watching
1353 * each PID for now. */
1355 return hashmap_put(u->meta.manager->watch_pids, LONG_TO_PTR(pid), u);
1358 void unit_unwatch_pid(Unit *u, pid_t pid) {
1362 hashmap_remove_value(u->meta.manager->watch_pids, LONG_TO_PTR(pid), u);
1365 int unit_watch_timer(Unit *u, usec_t delay, Watch *w) {
1366 struct itimerspec its;
1372 assert(w->type == WATCH_INVALID || (w->type == WATCH_UNIT_TIMER && w->data.unit == u));
1374 /* This will try to reuse the old timer if there is one */
1376 if (w->type == WATCH_UNIT_TIMER) {
1377 assert(w->data.unit == u);
1382 } else if (w->type == WATCH_INVALID) {
1385 if ((fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK|TFD_CLOEXEC)) < 0)
1388 assert_not_reached("Invalid watch type");
1393 /* Set absolute time in the past, but not 0, since we
1394 * don't want to disarm the timer */
1395 its.it_value.tv_sec = 0;
1396 its.it_value.tv_nsec = 1;
1398 flags = TFD_TIMER_ABSTIME;
1400 timespec_store(&its.it_value, delay);
1404 /* This will also flush the elapse counter */
1405 if (timerfd_settime(fd, flags, &its, NULL) < 0)
1408 if (w->type == WATCH_INVALID) {
1409 struct epoll_event ev;
1413 ev.events = EPOLLIN;
1415 if (epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0)
1419 w->type = WATCH_UNIT_TIMER;
1427 close_nointr_nofail(fd);
1432 void unit_unwatch_timer(Unit *u, Watch *w) {
1436 if (w->type == WATCH_INVALID)
1439 assert(w->type == WATCH_UNIT_TIMER);
1440 assert(w->data.unit == u);
1443 assert_se(epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_DEL, w->fd, NULL) >= 0);
1444 close_nointr_nofail(w->fd);
1447 w->type = WATCH_INVALID;
1448 w->data.unit = NULL;
1451 bool unit_job_is_applicable(Unit *u, JobType j) {
1453 assert(j >= 0 && j < _JOB_TYPE_MAX);
1457 case JOB_VERIFY_ACTIVE:
1463 case JOB_TRY_RESTART:
1464 return unit_can_start(u);
1467 return unit_can_reload(u);
1469 case JOB_RELOAD_OR_START:
1470 return unit_can_reload(u) && unit_can_start(u);
1473 assert_not_reached("Invalid job type");
1477 int unit_add_dependency(Unit *u, UnitDependency d, Unit *other, bool add_reference) {
1479 static const UnitDependency inverse_table[_UNIT_DEPENDENCY_MAX] = {
1480 [UNIT_REQUIRES] = UNIT_REQUIRED_BY,
1481 [UNIT_REQUIRES_OVERRIDABLE] = UNIT_REQUIRED_BY_OVERRIDABLE,
1482 [UNIT_WANTS] = UNIT_WANTED_BY,
1483 [UNIT_REQUISITE] = UNIT_REQUIRED_BY,
1484 [UNIT_REQUISITE_OVERRIDABLE] = UNIT_REQUIRED_BY_OVERRIDABLE,
1485 [UNIT_BIND_TO] = UNIT_BOUND_BY,
1486 [UNIT_REQUIRED_BY] = _UNIT_DEPENDENCY_INVALID,
1487 [UNIT_REQUIRED_BY_OVERRIDABLE] = _UNIT_DEPENDENCY_INVALID,
1488 [UNIT_WANTED_BY] = _UNIT_DEPENDENCY_INVALID,
1489 [UNIT_BOUND_BY] = UNIT_BIND_TO,
1490 [UNIT_CONFLICTS] = UNIT_CONFLICTED_BY,
1491 [UNIT_CONFLICTED_BY] = UNIT_CONFLICTS,
1492 [UNIT_BEFORE] = UNIT_AFTER,
1493 [UNIT_AFTER] = UNIT_BEFORE,
1494 [UNIT_ON_FAILURE] = _UNIT_DEPENDENCY_INVALID,
1495 [UNIT_REFERENCES] = UNIT_REFERENCED_BY,
1496 [UNIT_REFERENCED_BY] = UNIT_REFERENCES
1498 int r, q = 0, v = 0, w = 0;
1501 assert(d >= 0 && d < _UNIT_DEPENDENCY_MAX);
1504 u = unit_follow_merge(u);
1505 other = unit_follow_merge(other);
1507 /* We won't allow dependencies on ourselves. We will not
1508 * consider them an error however. */
1512 if ((r = set_ensure_allocated(&u->meta.dependencies[d], trivial_hash_func, trivial_compare_func)) < 0)
1515 if (inverse_table[d] != _UNIT_DEPENDENCY_INVALID)
1516 if ((r = set_ensure_allocated(&other->meta.dependencies[inverse_table[d]], trivial_hash_func, trivial_compare_func)) < 0)
1520 if ((r = set_ensure_allocated(&u->meta.dependencies[UNIT_REFERENCES], trivial_hash_func, trivial_compare_func)) < 0 ||
1521 (r = set_ensure_allocated(&other->meta.dependencies[UNIT_REFERENCED_BY], trivial_hash_func, trivial_compare_func)) < 0)
1524 if ((q = set_put(u->meta.dependencies[d], other)) < 0)
1527 if (inverse_table[d] != _UNIT_DEPENDENCY_INVALID)
1528 if ((v = set_put(other->meta.dependencies[inverse_table[d]], u)) < 0) {
1533 if (add_reference) {
1534 if ((w = set_put(u->meta.dependencies[UNIT_REFERENCES], other)) < 0) {
1539 if ((r = set_put(other->meta.dependencies[UNIT_REFERENCED_BY], u)) < 0)
1543 unit_add_to_dbus_queue(u);
1548 set_remove(u->meta.dependencies[d], other);
1551 set_remove(other->meta.dependencies[inverse_table[d]], u);
1554 set_remove(u->meta.dependencies[UNIT_REFERENCES], other);
1559 int unit_add_two_dependencies(Unit *u, UnitDependency d, UnitDependency e, Unit *other, bool add_reference) {
1564 if ((r = unit_add_dependency(u, d, other, add_reference)) < 0)
1567 if ((r = unit_add_dependency(u, e, other, add_reference)) < 0)
1573 static const char *resolve_template(Unit *u, const char *name, const char*path, char **p) {
1577 assert(name || path);
1580 name = file_name_from_path(path);
1582 if (!unit_name_is_template(name)) {
1587 if (u->meta.instance)
1588 s = unit_name_replace_instance(name, u->meta.instance);
1592 if (!(i = unit_name_to_prefix(u->meta.id)))
1595 s = unit_name_replace_instance(name, i);
1606 int unit_add_dependency_by_name(Unit *u, UnitDependency d, const char *name, const char *path, bool add_reference) {
1612 assert(name || path);
1614 if (!(name = resolve_template(u, name, path, &s)))
1617 if ((r = manager_load_unit(u->meta.manager, name, path, NULL, &other)) < 0)
1620 r = unit_add_dependency(u, d, other, add_reference);
1627 int unit_add_two_dependencies_by_name(Unit *u, UnitDependency d, UnitDependency e, const char *name, const char *path, bool add_reference) {
1633 assert(name || path);
1635 if (!(name = resolve_template(u, name, path, &s)))
1638 if ((r = manager_load_unit(u->meta.manager, name, path, NULL, &other)) < 0)
1641 r = unit_add_two_dependencies(u, d, e, other, add_reference);
1648 int unit_add_dependency_by_name_inverse(Unit *u, UnitDependency d, const char *name, const char *path, bool add_reference) {
1654 assert(name || path);
1656 if (!(name = resolve_template(u, name, path, &s)))
1659 if ((r = manager_load_unit(u->meta.manager, name, path, NULL, &other)) < 0)
1662 r = unit_add_dependency(other, d, u, add_reference);
1669 int unit_add_two_dependencies_by_name_inverse(Unit *u, UnitDependency d, UnitDependency e, const char *name, const char *path, bool add_reference) {
1675 assert(name || path);
1677 if (!(name = resolve_template(u, name, path, &s)))
1680 if ((r = manager_load_unit(u->meta.manager, name, path, NULL, &other)) < 0)
1683 if ((r = unit_add_two_dependencies(other, d, e, u, add_reference)) < 0)
1691 int set_unit_path(const char *p) {
1695 /* This is mostly for debug purposes */
1697 if (path_is_absolute(p)) {
1698 if (!(c = strdup(p)))
1701 if (!(cwd = get_current_dir_name()))
1704 r = asprintf(&c, "%s/%s", cwd, p);
1711 if (setenv("SYSTEMD_UNIT_PATH", c, 0) < 0) {
1720 char *unit_dbus_path(Unit *u) {
1728 if (!(e = bus_path_escape(u->meta.id)))
1731 p = strappend("/org/freedesktop/systemd1/unit/", e);
1737 int unit_add_cgroup(Unit *u, CGroupBonding *b) {
1745 if (!b->controller) {
1746 if (!(b->controller = strdup(SYSTEMD_CGROUP_CONTROLLER)))
1752 /* Ensure this hasn't been added yet */
1755 if (streq(b->controller, SYSTEMD_CGROUP_CONTROLLER)) {
1758 l = hashmap_get(u->meta.manager->cgroup_bondings, b->path);
1759 LIST_PREPEND(CGroupBonding, by_path, l, b);
1761 if ((r = hashmap_replace(u->meta.manager->cgroup_bondings, b->path, l)) < 0) {
1762 LIST_REMOVE(CGroupBonding, by_path, l, b);
1767 LIST_PREPEND(CGroupBonding, by_unit, u->meta.cgroup_bondings, b);
1773 static char *default_cgroup_path(Unit *u) {
1779 if (u->meta.instance) {
1782 if (!(t = unit_name_template(u->meta.id)))
1785 r = asprintf(&p, "%s/%s/%s", u->meta.manager->cgroup_hierarchy, t, u->meta.instance);
1788 r = asprintf(&p, "%s/%s", u->meta.manager->cgroup_hierarchy, u->meta.id);
1790 return r < 0 ? NULL : p;
1793 int unit_add_cgroup_from_text(Unit *u, const char *name) {
1794 char *controller = NULL, *path = NULL;
1795 CGroupBonding *b = NULL;
1802 if ((r = cg_split_spec(name, &controller, &path)) < 0)
1806 path = default_cgroup_path(u);
1811 controller = strdup(SYSTEMD_CGROUP_CONTROLLER);
1815 if (!path || !controller) {
1822 if (cgroup_bonding_find_list(u->meta.cgroup_bondings, controller)) {
1827 if (!(b = new0(CGroupBonding, 1))) {
1832 b->controller = controller;
1835 b->essential = streq(controller, SYSTEMD_CGROUP_CONTROLLER);
1837 if ((r = unit_add_cgroup(u, b)) < 0)
1850 static int unit_add_one_default_cgroup(Unit *u, const char *controller) {
1851 CGroupBonding *b = NULL;
1857 controller = SYSTEMD_CGROUP_CONTROLLER;
1859 if (cgroup_bonding_find_list(u->meta.cgroup_bondings, controller))
1862 if (!(b = new0(CGroupBonding, 1)))
1865 if (!(b->controller = strdup(controller)))
1868 if (!(b->path = default_cgroup_path(u)))
1872 b->essential = streq(controller, SYSTEMD_CGROUP_CONTROLLER);
1874 if ((r = unit_add_cgroup(u, b)) < 0)
1881 free(b->controller);
1887 int unit_add_default_cgroups(Unit *u) {
1892 /* Adds in the default cgroups, if they weren't specified
1895 if (!u->meta.manager->cgroup_hierarchy)
1898 if ((r = unit_add_one_default_cgroup(u, NULL)) < 0)
1901 STRV_FOREACH(c, u->meta.manager->default_controllers)
1902 if ((r = unit_add_one_default_cgroup(u, *c)) < 0)
1908 CGroupBonding* unit_get_default_cgroup(Unit *u) {
1911 return cgroup_bonding_find_list(u->meta.cgroup_bondings, SYSTEMD_CGROUP_CONTROLLER);
1914 int unit_load_related_unit(Unit *u, const char *type, Unit **_found) {
1922 if (!(t = unit_name_change_suffix(u->meta.id, type)))
1925 assert(!unit_has_name(u, t));
1927 r = manager_load_unit(u->meta.manager, t, NULL, NULL, _found);
1930 assert(r < 0 || *_found != u);
1935 int unit_get_related_unit(Unit *u, const char *type, Unit **_found) {
1943 if (!(t = unit_name_change_suffix(u->meta.id, type)))
1946 assert(!unit_has_name(u, t));
1948 found = manager_get_unit(u->meta.manager, t);
1958 static char *specifier_prefix_and_instance(char specifier, void *data, void *userdata) {
1962 return unit_name_to_prefix_and_instance(u->meta.id);
1965 static char *specifier_prefix(char specifier, void *data, void *userdata) {
1969 return unit_name_to_prefix(u->meta.id);
1972 static char *specifier_prefix_unescaped(char specifier, void *data, void *userdata) {
1978 if (!(p = unit_name_to_prefix(u->meta.id)))
1981 r = unit_name_unescape(p);
1987 static char *specifier_instance_unescaped(char specifier, void *data, void *userdata) {
1991 if (u->meta.instance)
1992 return unit_name_unescape(u->meta.instance);
1997 static char *specifier_filename(char specifier, void *data, void *userdata) {
2001 if (u->meta.instance)
2002 return unit_name_path_unescape(u->meta.instance);
2004 return unit_name_to_path(u->meta.instance);
2007 static char *specifier_cgroup(char specifier, void *data, void *userdata) {
2011 return default_cgroup_path(u);
2014 static char *specifier_cgroup_root(char specifier, void *data, void *userdata) {
2019 if (specifier == 'r')
2020 return strdup(u->meta.manager->cgroup_hierarchy);
2022 if (parent_of_path(u->meta.manager->cgroup_hierarchy, &p) < 0)
2025 if (streq(p, "/")) {
2033 static char *specifier_runtime(char specifier, void *data, void *userdata) {
2037 if (u->meta.manager->running_as == MANAGER_USER) {
2040 e = getenv("XDG_RUNTIME_DIR");
2045 return strdup("/run");
2048 char *unit_name_printf(Unit *u, const char* format) {
2051 * This will use the passed string as format string and
2052 * replace the following specifiers:
2054 * %n: the full id of the unit (foo@bar.waldo)
2055 * %N: the id of the unit without the suffix (foo@bar)
2056 * %p: the prefix (foo)
2057 * %i: the instance (bar)
2060 const Specifier table[] = {
2061 { 'n', specifier_string, u->meta.id },
2062 { 'N', specifier_prefix_and_instance, NULL },
2063 { 'p', specifier_prefix, NULL },
2064 { 'i', specifier_string, u->meta.instance },
2071 return specifier_printf(format, table, u);
2074 char *unit_full_printf(Unit *u, const char *format) {
2076 /* This is similar to unit_name_printf() but also supports
2077 * unescaping. Also, adds a couple of additional codes:
2079 * %c cgroup path of unit
2080 * %r root cgroup path of this systemd instance (e.g. "/user/lennart/shared/systemd-4711")
2081 * %R parent of root cgroup path (e.g. "/usr/lennart/shared")
2082 * %t the runtime directory to place sockets in (e.g. "/run" or $XDG_RUNTIME_DIR)
2085 const Specifier table[] = {
2086 { 'n', specifier_string, u->meta.id },
2087 { 'N', specifier_prefix_and_instance, NULL },
2088 { 'p', specifier_prefix, NULL },
2089 { 'P', specifier_prefix_unescaped, NULL },
2090 { 'i', specifier_string, u->meta.instance },
2091 { 'I', specifier_instance_unescaped, NULL },
2092 { 'f', specifier_filename, NULL },
2093 { 'c', specifier_cgroup, NULL },
2094 { 'r', specifier_cgroup_root, NULL },
2095 { 'R', specifier_cgroup_root, NULL },
2096 { 't', specifier_runtime, NULL },
2103 return specifier_printf(format, table, u);
2106 char **unit_full_printf_strv(Unit *u, char **l) {
2110 /* Applies unit_full_printf to every entry in l */
2115 if (!(r = new(char*, n+1)))
2118 for (i = l, j = r; *i; i++, j++)
2119 if (!(*j = unit_full_printf(u, *i)))
2126 for (j--; j >= r; j--)
2134 int unit_watch_bus_name(Unit *u, const char *name) {
2138 /* Watch a specific name on the bus. We only support one unit
2139 * watching each name for now. */
2141 return hashmap_put(u->meta.manager->watch_bus, name, u);
2144 void unit_unwatch_bus_name(Unit *u, const char *name) {
2148 hashmap_remove_value(u->meta.manager->watch_bus, name, u);
2151 bool unit_can_serialize(Unit *u) {
2154 return UNIT_VTABLE(u)->serialize && UNIT_VTABLE(u)->deserialize_item;
2157 int unit_serialize(Unit *u, FILE *f, FDSet *fds) {
2164 if (!unit_can_serialize(u))
2167 if ((r = UNIT_VTABLE(u)->serialize(u, f, fds)) < 0)
2171 unit_serialize_item(u, f, "job", job_type_to_string(u->meta.job->type));
2173 dual_timestamp_serialize(f, "inactive-exit-timestamp", &u->meta.inactive_exit_timestamp);
2174 dual_timestamp_serialize(f, "active-enter-timestamp", &u->meta.active_enter_timestamp);
2175 dual_timestamp_serialize(f, "active-exit-timestamp", &u->meta.active_exit_timestamp);
2176 dual_timestamp_serialize(f, "inactive-enter-timestamp", &u->meta.inactive_enter_timestamp);
2177 dual_timestamp_serialize(f, "condition-timestamp", &u->meta.condition_timestamp);
2179 if (dual_timestamp_is_set(&u->meta.condition_timestamp))
2180 unit_serialize_item(u, f, "condition-result", yes_no(u->meta.condition_result));
2187 void unit_serialize_item_format(Unit *u, FILE *f, const char *key, const char *format, ...) {
2198 va_start(ap, format);
2199 vfprintf(f, format, ap);
2205 void unit_serialize_item(Unit *u, FILE *f, const char *key, const char *value) {
2211 fprintf(f, "%s=%s\n", key, value);
2214 int unit_deserialize(Unit *u, FILE *f, FDSet *fds) {
2221 if (!unit_can_serialize(u))
2225 char line[LINE_MAX], *l, *v;
2228 if (!fgets(line, sizeof(line), f)) {
2241 k = strcspn(l, "=");
2249 if (streq(l, "job")) {
2252 if ((type = job_type_from_string(v)) < 0)
2253 log_debug("Failed to parse job type value %s", v);
2255 u->meta.deserialized_job = type;
2258 } else if (streq(l, "inactive-exit-timestamp")) {
2259 dual_timestamp_deserialize(v, &u->meta.inactive_exit_timestamp);
2261 } else if (streq(l, "active-enter-timestamp")) {
2262 dual_timestamp_deserialize(v, &u->meta.active_enter_timestamp);
2264 } else if (streq(l, "active-exit-timestamp")) {
2265 dual_timestamp_deserialize(v, &u->meta.active_exit_timestamp);
2267 } else if (streq(l, "inactive-enter-timestamp")) {
2268 dual_timestamp_deserialize(v, &u->meta.inactive_enter_timestamp);
2270 } else if (streq(l, "condition-timestamp")) {
2271 dual_timestamp_deserialize(v, &u->meta.condition_timestamp);
2273 } else if (streq(l, "condition-result")) {
2276 if ((b = parse_boolean(v)) < 0)
2277 log_debug("Failed to parse condition result value %s", v);
2279 u->meta.condition_result = b;
2284 if ((r = UNIT_VTABLE(u)->deserialize_item(u, l, v, fds)) < 0)
2289 int unit_add_node_link(Unit *u, const char *what, bool wants) {
2299 /* Adds in links to the device node that this unit is based on */
2301 if (!is_device_path(what))
2304 if (!(e = unit_name_build_escape(what+1, NULL, ".device")))
2307 r = manager_load_unit(u->meta.manager, e, NULL, NULL, &device);
2313 if ((r = unit_add_two_dependencies(u, UNIT_AFTER, UNIT_BIND_TO, device, true)) < 0)
2317 if ((r = unit_add_dependency(device, UNIT_WANTS, u, false)) < 0)
2323 int unit_coldplug(Unit *u) {
2328 if (UNIT_VTABLE(u)->coldplug)
2329 if ((r = UNIT_VTABLE(u)->coldplug(u)) < 0)
2332 if (u->meta.deserialized_job >= 0) {
2333 if ((r = manager_add_job(u->meta.manager, u->meta.deserialized_job, u, JOB_IGNORE_REQUIREMENTS, false, NULL, NULL)) < 0)
2336 u->meta.deserialized_job = _JOB_TYPE_INVALID;
2342 void unit_status_printf(Unit *u, const char *format, ...) {
2348 if (!UNIT_VTABLE(u)->show_status)
2351 if (u->meta.manager->running_as != MANAGER_SYSTEM)
2354 /* If Plymouth is running make sure we show the status, so
2355 * that there's something nice to see when people press Esc */
2357 if (!u->meta.manager->show_status && !plymouth_running())
2360 if (!manager_is_booting_or_shutting_down(u->meta.manager))
2363 va_start(ap, format);
2364 status_vprintf(format, ap);
2368 bool unit_need_daemon_reload(Unit *u) {
2371 if (u->meta.fragment_path) {
2375 if (stat(u->meta.fragment_path, &st) < 0)
2376 /* What, cannot access this anymore? */
2379 if (u->meta.fragment_mtime > 0 &&
2380 timespec_load(&st.st_mtim) != u->meta.fragment_mtime)
2384 if (UNIT_VTABLE(u)->need_daemon_reload)
2385 return UNIT_VTABLE(u)->need_daemon_reload(u);
2390 void unit_reset_failed(Unit *u) {
2393 if (UNIT_VTABLE(u)->reset_failed)
2394 UNIT_VTABLE(u)->reset_failed(u);
2397 Unit *unit_following(Unit *u) {
2400 if (UNIT_VTABLE(u)->following)
2401 return UNIT_VTABLE(u)->following(u);
2406 bool unit_pending_inactive(Unit *u) {
2409 /* Returns true if the unit is inactive or going down */
2411 if (UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)))
2414 if (u->meta.job && u->meta.job->type == JOB_STOP)
2420 bool unit_pending_active(Unit *u) {
2423 /* Returns true if the unit is inactive or going down */
2425 if (UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)))
2429 (u->meta.job->type == JOB_START ||
2430 u->meta.job->type == JOB_RELOAD_OR_START ||
2431 u->meta.job->type == JOB_RESTART))
2437 UnitType unit_name_to_type(const char *n) {
2442 for (t = 0; t < _UNIT_TYPE_MAX; t++)
2443 if (endswith(n, unit_vtable[t]->suffix))
2446 return _UNIT_TYPE_INVALID;
2449 bool unit_name_is_valid(const char *n, bool template_ok) {
2452 t = unit_name_to_type(n);
2453 if (t < 0 || t >= _UNIT_TYPE_MAX)
2456 return unit_name_is_valid_no_type(n, template_ok);
2459 int unit_kill(Unit *u, KillWho w, KillMode m, int signo, DBusError *error) {
2461 assert(w >= 0 && w < _KILL_WHO_MAX);
2462 assert(m >= 0 && m < _KILL_MODE_MAX);
2464 assert(signo < _NSIG);
2469 if (!UNIT_VTABLE(u)->kill)
2472 return UNIT_VTABLE(u)->kill(u, w, m, signo, error);
2475 int unit_following_set(Unit *u, Set **s) {
2479 if (UNIT_VTABLE(u)->following_set)
2480 return UNIT_VTABLE(u)->following_set(u, s);
2486 UnitFileState unit_get_unit_file_state(Unit *u) {
2489 if (u->meta.unit_file_state < 0 && u->meta.fragment_path)
2490 u->meta.unit_file_state = unit_file_get_state(
2491 u->meta.manager->running_as == MANAGER_SYSTEM ? UNIT_FILE_SYSTEM : UNIT_FILE_USER,
2492 NULL, file_name_from_path(u->meta.fragment_path));
2494 return u->meta.unit_file_state;
2497 static const char* const unit_load_state_table[_UNIT_LOAD_STATE_MAX] = {
2498 [UNIT_STUB] = "stub",
2499 [UNIT_LOADED] = "loaded",
2500 [UNIT_ERROR] = "error",
2501 [UNIT_MERGED] = "merged",
2502 [UNIT_MASKED] = "masked"
2505 DEFINE_STRING_TABLE_LOOKUP(unit_load_state, UnitLoadState);
2507 static const char* const unit_active_state_table[_UNIT_ACTIVE_STATE_MAX] = {
2508 [UNIT_ACTIVE] = "active",
2509 [UNIT_RELOADING] = "reloading",
2510 [UNIT_INACTIVE] = "inactive",
2511 [UNIT_FAILED] = "failed",
2512 [UNIT_ACTIVATING] = "activating",
2513 [UNIT_DEACTIVATING] = "deactivating"
2516 DEFINE_STRING_TABLE_LOOKUP(unit_active_state, UnitActiveState);
2518 static const char* const unit_dependency_table[_UNIT_DEPENDENCY_MAX] = {
2519 [UNIT_REQUIRES] = "Requires",
2520 [UNIT_REQUIRES_OVERRIDABLE] = "RequiresOverridable",
2521 [UNIT_WANTS] = "Wants",
2522 [UNIT_REQUISITE] = "Requisite",
2523 [UNIT_REQUISITE_OVERRIDABLE] = "RequisiteOverridable",
2524 [UNIT_REQUIRED_BY] = "RequiredBy",
2525 [UNIT_REQUIRED_BY_OVERRIDABLE] = "RequiredByOverridable",
2526 [UNIT_BIND_TO] = "BindTo",
2527 [UNIT_WANTED_BY] = "WantedBy",
2528 [UNIT_CONFLICTS] = "Conflicts",
2529 [UNIT_CONFLICTED_BY] = "ConflictedBy",
2530 [UNIT_BOUND_BY] = "BoundBy",
2531 [UNIT_BEFORE] = "Before",
2532 [UNIT_AFTER] = "After",
2533 [UNIT_REFERENCES] = "References",
2534 [UNIT_REFERENCED_BY] = "ReferencedBy",
2535 [UNIT_ON_FAILURE] = "OnFailure"
2538 DEFINE_STRING_TABLE_LOOKUP(unit_dependency, UnitDependency);