1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
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>
27 #include <sys/signalfd.h>
31 #include <sys/reboot.h>
32 #include <sys/ioctl.h>
34 #include <libcgroup.h>
42 #include "ratelimit.h"
44 #include "mount-setup.h"
46 static int manager_setup_signals(Manager *m) {
48 struct epoll_event ev;
52 assert_se(reset_all_signal_handlers() == 0);
54 assert_se(sigemptyset(&mask) == 0);
55 assert_se(sigaddset(&mask, SIGCHLD) == 0);
56 assert_se(sigaddset(&mask, SIGINT) == 0); /* Kernel sends us this on control-alt-del */
57 assert_se(sigaddset(&mask, SIGWINCH) == 0); /* Kernel sends us this on kbrequest (alt-arrowup) */
58 assert_se(sigaddset(&mask, SIGTERM) == 0);
59 assert_se(sigaddset(&mask, SIGHUP) == 0);
60 assert_se(sigaddset(&mask, SIGUSR1) == 0);
61 assert_se(sigaddset(&mask, SIGUSR2) == 0);
62 assert_se(sigaddset(&mask, SIGPIPE) == 0);
63 assert_se(sigaddset(&mask, SIGPWR) == 0);
64 assert_se(sigaddset(&mask, SIGTTIN) == 0);
65 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
67 m->signal_watch.type = WATCH_SIGNAL;
68 if ((m->signal_watch.fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0)
73 ev.data.ptr = &m->signal_watch;
75 if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->signal_watch.fd, &ev) < 0)
78 if (m->running_as == MANAGER_INIT) {
79 /* Enable that we get SIGINT on control-alt-del */
80 if (reboot(RB_DISABLE_CAD) < 0)
81 log_warning("Failed to enable ctrl-alt-del handling: %s", strerror(errno));
83 /* Enable that we get SIGWINCH on kbrequest */
84 if (ioctl(0, KDSIGACCEPT, SIGWINCH) < 0)
85 log_warning("Failed to enable kbrequest handling: %s", strerror(errno));
91 static char** session_dirs(void) {
93 char *config_home = NULL, *data_home = NULL;
94 char **config_dirs = NULL, **data_dirs = NULL;
97 /* Implement the mechanisms defined in
99 * http://standards.freedesktop.org/basedir-spec/basedir-spec-0.6.html
101 * We look in both the config and the data dirs because we
102 * want to encourage that distributors ship their unit files
103 * as data, and allow overriding as configuration.
106 home = getenv("HOME");
108 if ((e = getenv("XDG_CONFIG_HOME"))) {
109 if (asprintf(&config_home, "%s/systemd/session", e) < 0)
113 if (asprintf(&config_home, "%s/.config/systemd/session", home) < 0)
117 if ((e = getenv("XDG_CONFIG_DIRS")))
118 config_dirs = strv_split(e, ":");
120 config_dirs = strv_new("/etc/xdg", NULL);
125 if ((e = getenv("XDG_DATA_HOME"))) {
126 if (asprintf(&data_home, "%s/systemd/session", e) < 0)
130 if (asprintf(&data_home, "%s/.local/share/systemd/session", home) < 0)
134 if ((e = getenv("XDG_DATA_DIRS")))
135 data_dirs = strv_split(e, ":");
137 data_dirs = strv_new("/usr/local/share", "/usr/share", NULL);
142 /* Now merge everything we found. */
144 if (!(t = strv_append(r, config_home)))
150 if (!(t = strv_merge_concat(r, config_dirs, "/systemd/session")))
155 if (!(t = strv_append(r, SESSION_CONFIG_UNIT_PATH)))
161 if (!(t = strv_append(r, data_home)))
167 if (!(t = strv_merge_concat(r, data_dirs, "/systemd/session")))
172 if (!(t = strv_append(r, SESSION_DATA_UNIT_PATH)))
177 if (!strv_path_make_absolute_cwd(r))
182 strv_free(config_dirs);
184 strv_free(data_dirs);
194 static int manager_find_paths(Manager *m) {
200 /* First priority is whatever has been passed to us via env
202 if ((e = getenv("SYSTEMD_UNIT_PATH")))
203 if (!(m->unit_path = split_path_and_make_absolute(e)))
206 if (strv_isempty(m->unit_path)) {
208 /* Nothing is set, so let's figure something out. */
209 strv_free(m->unit_path);
211 if (m->running_as == MANAGER_SESSION) {
212 if (!(m->unit_path = session_dirs()))
215 if (!(m->unit_path = strv_new(
216 SYSTEM_CONFIG_UNIT_PATH, /* /etc/systemd/system/ */
217 SYSTEM_DATA_UNIT_PATH, /* /lib/systemd/system/ */
222 if (m->running_as == MANAGER_INIT) {
223 /* /etc/init.d/ compativility does not matter to users */
225 if ((e = getenv("SYSTEMD_SYSVINIT_PATH")))
226 if (!(m->sysvinit_path = split_path_and_make_absolute(e)))
229 if (strv_isempty(m->sysvinit_path)) {
230 strv_free(m->sysvinit_path);
232 if (!(m->sysvinit_path = strv_new(
233 SYSTEM_SYSVINIT_PATH, /* /etc/init.d/ */
239 strv_uniq(m->unit_path);
240 strv_uniq(m->sysvinit_path);
242 assert(!strv_isempty(m->unit_path));
243 if (!(t = strv_join(m->unit_path, "\n\t")))
245 log_debug("Looking for unit files in:\n\t%s", t);
248 if (!strv_isempty(m->sysvinit_path)) {
250 if (!(t = strv_join(m->sysvinit_path, "\n\t")))
253 log_debug("Looking for SysV init scripts in:\n\t%s", t);
256 log_debug("Ignoring SysV init scripts.");
261 int manager_new(Manager **_m) {
267 if (!(m = new0(Manager, 1)))
270 m->signal_watch.fd = m->mount_watch.fd = m->udev_watch.fd = m->epoll_fd = -1;
271 m->current_job_id = 1; /* start as id #1, so that we can leave #0 around as "null-like" value */
273 if (!(m->units = hashmap_new(string_hash_func, string_compare_func)))
276 if (!(m->jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
279 if (!(m->transaction_jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
282 if (!(m->watch_pids = hashmap_new(trivial_hash_func, trivial_compare_func)))
285 if (!(m->cgroup_bondings = hashmap_new(string_hash_func, string_compare_func)))
288 if ((m->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0)
292 m->running_as = MANAGER_INIT;
293 else if (getuid() == 0)
294 m->running_as = MANAGER_SYSTEM;
296 m->running_as = MANAGER_SESSION;
298 log_debug("systemd running in %s mode.", manager_running_as_to_string(m->running_as));
300 if ((r = manager_find_paths(m)) < 0)
304 log_warning("Failed to chdir to /: %s", strerror(errno));
306 /* Become a session leader if we aren't one yet. */
309 if ((r = manager_setup_signals(m)) < 0)
312 if ((r = mount_setup()) < 0)
315 if ((r = manager_setup_cgroup(m)) < 0)
318 dbus_connection_set_change_sigpipe(FALSE);
320 /* Try to connect to the busses, if possible. */
321 if ((r = bus_init_system(m)) < 0 ||
322 (r = bus_init_api(m)) < 0)
333 static unsigned manager_dispatch_cleanup_queue(Manager *m) {
339 while ((meta = m->cleanup_queue)) {
340 assert(meta->in_cleanup_queue);
342 unit_free(UNIT(meta));
349 void manager_free(Manager *m) {
356 while ((j = hashmap_first(m->transaction_jobs)))
359 while ((u = hashmap_first(m->units)))
362 manager_dispatch_cleanup_queue(m);
364 for (c = 0; c < _UNIT_TYPE_MAX; c++)
365 if (unit_vtable[c]->shutdown)
366 unit_vtable[c]->shutdown(m);
368 manager_shutdown_cgroup(m);
373 hashmap_free(m->units);
374 hashmap_free(m->jobs);
375 hashmap_free(m->transaction_jobs);
376 hashmap_free(m->watch_pids);
378 if (m->epoll_fd >= 0)
379 close_nointr(m->epoll_fd);
380 if (m->signal_watch.fd >= 0)
381 close_nointr(m->signal_watch.fd);
383 strv_free(m->unit_path);
384 strv_free(m->sysvinit_path);
386 free(m->cgroup_controller);
387 free(m->cgroup_hierarchy);
389 assert(hashmap_isempty(m->cgroup_bondings));
390 hashmap_free(m->cgroup_bondings);
395 int manager_coldplug(Manager *m) {
404 /* First, let's ask every type to load all units from
405 * disk/kernel that it might know */
406 for (c = 0; c < _UNIT_TYPE_MAX; c++)
407 if (unit_vtable[c]->enumerate)
408 if ((r = unit_vtable[c]->enumerate(m)) < 0)
411 manager_dispatch_load_queue(m);
413 /* Then, let's set up their initial state. */
414 HASHMAP_FOREACH_KEY(u, k, m->units, i) {
420 if (UNIT_VTABLE(u)->coldplug)
421 if ((r = UNIT_VTABLE(u)->coldplug(u)) < 0)
428 static void transaction_delete_job(Manager *m, Job *j, bool delete_dependencies) {
432 /* Deletes one job from the transaction */
434 manager_transaction_unlink_job(m, j, delete_dependencies);
440 static void transaction_delete_unit(Manager *m, Unit *u) {
443 /* Deletes all jobs associated with a certain unit from the
446 while ((j = hashmap_get(m->transaction_jobs, u)))
447 transaction_delete_job(m, j, true);
450 static void transaction_clean_dependencies(Manager *m) {
456 /* Drops all dependencies of all installed jobs */
458 HASHMAP_FOREACH(j, m->jobs, i) {
459 while (j->subject_list)
460 job_dependency_free(j->subject_list);
461 while (j->object_list)
462 job_dependency_free(j->object_list);
465 assert(!m->transaction_anchor);
468 static void transaction_abort(Manager *m) {
473 while ((j = hashmap_first(m->transaction_jobs)))
475 transaction_delete_job(m, j, true);
479 assert(hashmap_isempty(m->transaction_jobs));
481 transaction_clean_dependencies(m);
484 static void transaction_find_jobs_that_matter_to_anchor(Manager *m, Job *j, unsigned generation) {
489 /* A recursive sweep through the graph that marks all units
490 * that matter to the anchor job, i.e. are directly or
491 * indirectly a dependency of the anchor job via paths that
492 * are fully marked as mattering. */
497 l = m->transaction_anchor;
499 LIST_FOREACH(subject, l, l) {
501 /* This link does not matter */
505 /* This unit has already been marked */
506 if (l->object->generation == generation)
509 l->object->matters_to_anchor = true;
510 l->object->generation = generation;
512 transaction_find_jobs_that_matter_to_anchor(m, l->object, generation);
516 static void transaction_merge_and_delete_job(Manager *m, Job *j, Job *other, JobType t) {
517 JobDependency *l, *last;
521 assert(j->unit == other->unit);
522 assert(!j->installed);
524 /* Merges 'other' into 'j' and then deletes j. */
527 j->state = JOB_WAITING;
528 j->forced = j->forced || other->forced;
530 j->matters_to_anchor = j->matters_to_anchor || other->matters_to_anchor;
532 /* Patch us in as new owner of the JobDependency objects */
534 LIST_FOREACH(subject, l, other->subject_list) {
535 assert(l->subject == other);
540 /* Merge both lists */
542 last->subject_next = j->subject_list;
544 j->subject_list->subject_prev = last;
545 j->subject_list = other->subject_list;
548 /* Patch us in as new owner of the JobDependency objects */
550 LIST_FOREACH(object, l, other->object_list) {
551 assert(l->object == other);
556 /* Merge both lists */
558 last->object_next = j->object_list;
560 j->object_list->object_prev = last;
561 j->object_list = other->object_list;
564 /* Kill the other job */
565 other->subject_list = NULL;
566 other->object_list = NULL;
567 transaction_delete_job(m, other, true);
570 static int delete_one_unmergeable_job(Manager *m, Job *j) {
575 /* Tries to delete one item in the linked list
576 * j->transaction_next->transaction_next->... that conflicts
577 * whith another one, in an attempt to make an inconsistent
578 * transaction work. */
580 /* We rely here on the fact that if a merged with b does not
581 * merge with c, either a or b merge with c neither */
582 LIST_FOREACH(transaction, j, j)
583 LIST_FOREACH(transaction, k, j->transaction_next) {
586 /* Is this one mergeable? Then skip it */
587 if (job_type_is_mergeable(j->type, k->type))
590 /* Ok, we found two that conflict, let's see if we can
591 * drop one of them */
592 if (!j->matters_to_anchor)
594 else if (!k->matters_to_anchor)
599 /* Ok, we can drop one, so let's do so. */
600 log_debug("Trying to fix job merging by deleting job %s/%s", unit_id(d->unit), job_type_to_string(d->type));
601 transaction_delete_job(m, d, true);
608 static int transaction_merge_jobs(Manager *m) {
615 /* First step, check whether any of the jobs for one specific
616 * task conflict. If so, try to drop one of them. */
617 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
622 LIST_FOREACH(transaction, k, j->transaction_next) {
623 if ((r = job_type_merge(&t, k->type)) >= 0)
626 /* OK, we could not merge all jobs for this
627 * action. Let's see if we can get rid of one
630 if ((r = delete_one_unmergeable_job(m, j)) >= 0)
631 /* Ok, we managed to drop one, now
632 * let's ask our callers to call us
633 * again after garbage collecting */
636 /* We couldn't merge anything. Failure */
641 /* Second step, merge the jobs. */
642 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
646 /* Merge all transactions */
647 LIST_FOREACH(transaction, k, j->transaction_next)
648 assert_se(job_type_merge(&t, k->type) == 0);
650 /* If an active job is mergeable, merge it too */
651 if (j->unit->meta.job)
652 job_type_merge(&t, j->unit->meta.job->type); /* Might fail. Which is OK */
654 while ((k = j->transaction_next)) {
656 transaction_merge_and_delete_job(m, k, j, t);
659 transaction_merge_and_delete_job(m, j, k, t);
662 assert(!j->transaction_next);
663 assert(!j->transaction_prev);
669 static void transaction_drop_redundant(Manager *m) {
674 /* Goes through the transaction and removes all jobs that are
683 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
684 bool changes_something = false;
687 LIST_FOREACH(transaction, k, j) {
689 if (!job_is_anchor(k) &&
690 job_type_is_redundant(k->type, unit_active_state(k->unit)))
693 changes_something = true;
697 if (changes_something)
700 log_debug("Found redundant job %s/%s, dropping.", unit_id(j->unit), job_type_to_string(j->type));
701 transaction_delete_job(m, j, false);
709 static bool unit_matters_to_anchor(Unit *u, Job *j) {
711 assert(!j->transaction_prev);
713 /* Checks whether at least one of the jobs for this unit
714 * matters to the anchor. */
716 LIST_FOREACH(transaction, j, j)
717 if (j->matters_to_anchor)
723 static int transaction_verify_order_one(Manager *m, Job *j, Job *from, unsigned generation) {
730 assert(!j->transaction_prev);
732 /* Does a recursive sweep through the ordering graph, looking
733 * for a cycle. If we find cycle we try to break it. */
735 /* Did we find a cycle? */
736 if (j->marker && j->generation == generation) {
739 /* So, we already have been here. We have a
740 * cycle. Let's try to break it. We go backwards in
741 * our path and try to find a suitable job to
742 * remove. We use the marker to find our way back,
743 * since smart how we are we stored our way back in
746 log_debug("Found ordering cycle on %s/%s", unit_id(j->unit), job_type_to_string(j->type));
748 for (k = from; k; k = (k->generation == generation ? k->marker : NULL)) {
750 log_debug("Walked on cycle path to %s/%s", unit_id(k->unit), job_type_to_string(k->type));
753 !unit_matters_to_anchor(k->unit, k)) {
754 /* Ok, we can drop this one, so let's
756 log_debug("Breaking order cycle by deleting job %s/%s", unit_id(k->unit), job_type_to_string(k->type));
757 transaction_delete_unit(m, k->unit);
761 /* Check if this in fact was the beginning of
767 log_debug("Unable to break cycle");
772 /* Make the marker point to where we come from, so that we can
773 * find our way backwards if we want to break a cycle */
775 j->generation = generation;
777 /* We assume that the the dependencies are bidirectional, and
778 * hence can ignore UNIT_AFTER */
779 SET_FOREACH(u, j->unit->meta.dependencies[UNIT_BEFORE], i) {
782 /* Is there a job for this unit? */
783 if (!(o = hashmap_get(m->transaction_jobs, u)))
785 /* Ok, there is no job for this in the
786 * transaction, but maybe there is already one
788 if (!(o = u->meta.job))
791 if ((r = transaction_verify_order_one(m, o, j, generation)) < 0)
795 /* Ok, let's backtrack, and remember that this entry is not on
796 * our path anymore. */
802 static int transaction_verify_order(Manager *m, unsigned *generation) {
810 /* Check if the ordering graph is cyclic. If it is, try to fix
811 * that up by dropping one of the jobs. */
813 HASHMAP_FOREACH(j, m->transaction_jobs, i)
814 if ((r = transaction_verify_order_one(m, j, NULL, (*generation)++)) < 0)
820 static void transaction_collect_garbage(Manager *m) {
825 /* Drop jobs that are not required by any other job */
833 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
837 log_debug("Garbage collecting job %s/%s", unit_id(j->unit), job_type_to_string(j->type));
838 transaction_delete_job(m, j, true);
846 static int transaction_is_destructive(Manager *m, JobMode mode) {
852 /* Checks whether applying this transaction means that
853 * existing jobs would be replaced */
855 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
858 assert(!j->transaction_prev);
859 assert(!j->transaction_next);
861 if (j->unit->meta.job &&
862 j->unit->meta.job != j &&
863 !job_type_is_superset(j->type, j->unit->meta.job->type))
870 static void transaction_minimize_impact(Manager *m) {
874 /* Drops all unnecessary jobs that reverse already active jobs
875 * or that stop a running service. */
883 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
884 LIST_FOREACH(transaction, j, j) {
885 bool stops_running_service, changes_existing_job;
887 /* If it matters, we shouldn't drop it */
888 if (j->matters_to_anchor)
891 /* Would this stop a running service?
892 * Would this change an existing job?
893 * If so, let's drop this entry */
895 stops_running_service =
896 j->type == JOB_STOP && UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(j->unit));
898 changes_existing_job =
899 j->unit->meta.job && job_type_is_conflicting(j->type, j->unit->meta.job->state);
901 if (!stops_running_service && !changes_existing_job)
904 if (stops_running_service)
905 log_debug("%s/%s would stop a running service.", unit_id(j->unit), job_type_to_string(j->type));
907 if (changes_existing_job)
908 log_debug("%s/%s would change existing job.", unit_id(j->unit), job_type_to_string(j->type));
910 /* Ok, let's get rid of this */
911 log_debug("Deleting %s/%s to minimize impact.", unit_id(j->unit), job_type_to_string(j->type));
913 transaction_delete_job(m, j, true);
925 static int transaction_apply(Manager *m, JobMode mode) {
930 /* Moves the transaction jobs to the set of active jobs */
932 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
934 assert(!j->transaction_prev);
935 assert(!j->transaction_next);
940 if ((r = hashmap_put(m->jobs, UINT32_TO_PTR(j->id), j)) < 0)
944 while ((j = hashmap_steal_first(m->transaction_jobs))) {
948 if (j->unit->meta.job)
949 job_free(j->unit->meta.job);
951 j->unit->meta.job = j;
954 /* We're fully installed. Now let's free data we don't
957 assert(!j->transaction_next);
958 assert(!j->transaction_prev);
960 job_add_to_run_queue(j);
961 job_add_to_dbus_queue(j);
964 /* As last step, kill all remaining job dependencies. */
965 transaction_clean_dependencies(m);
971 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
975 hashmap_remove(m->jobs, UINT32_TO_PTR(j->id));
981 static int transaction_activate(Manager *m, JobMode mode) {
983 unsigned generation = 1;
987 /* This applies the changes recorded in transaction_jobs to
988 * the actual list of jobs, if possible. */
990 /* First step: figure out which jobs matter */
991 transaction_find_jobs_that_matter_to_anchor(m, NULL, generation++);
993 /* Second step: Try not to stop any running services if
994 * we don't have to. Don't try to reverse running
995 * jobs if we don't have to. */
996 transaction_minimize_impact(m);
998 /* Third step: Drop redundant jobs */
999 transaction_drop_redundant(m);
1002 /* Fourth step: Let's remove unneeded jobs that might
1004 transaction_collect_garbage(m);
1006 /* Fifth step: verify order makes sense and correct
1007 * cycles if necessary and possible */
1008 if ((r = transaction_verify_order(m, &generation)) >= 0)
1012 log_debug("Requested transaction contains an unfixable cyclic ordering dependency: %s", strerror(-r));
1016 /* Let's see if the resulting transaction ordering
1017 * graph is still cyclic... */
1021 /* Sixth step: let's drop unmergeable entries if
1022 * necessary and possible, merge entries we can
1024 if ((r = transaction_merge_jobs(m)) >= 0)
1028 log_debug("Requested transaction contains unmergable jobs: %s", strerror(-r));
1032 /* Seventh step: an entry got dropped, let's garbage
1033 * collect its dependencies. */
1034 transaction_collect_garbage(m);
1036 /* Let's see if the resulting transaction still has
1037 * unmergeable entries ... */
1040 /* Eights step: Drop redundant jobs again, if the merging now allows us to drop more. */
1041 transaction_drop_redundant(m);
1043 /* Ninth step: check whether we can actually apply this */
1044 if (mode == JOB_FAIL)
1045 if ((r = transaction_is_destructive(m, mode)) < 0) {
1046 log_debug("Requested transaction contradicts existing jobs: %s", strerror(-r));
1050 /* Tenth step: apply changes */
1051 if ((r = transaction_apply(m, mode)) < 0) {
1052 log_debug("Failed to apply transaction: %s", strerror(-r));
1056 assert(hashmap_isempty(m->transaction_jobs));
1057 assert(!m->transaction_anchor);
1062 transaction_abort(m);
1066 static Job* transaction_add_one_job(Manager *m, JobType type, Unit *unit, bool force, bool *is_new) {
1073 /* Looks for an axisting prospective job and returns that. If
1074 * it doesn't exist it is created and added to the prospective
1077 f = hashmap_get(m->transaction_jobs, unit);
1079 LIST_FOREACH(transaction, j, f) {
1080 assert(j->unit == unit);
1082 if (j->type == type) {
1089 if (unit->meta.job && unit->meta.job->type == type)
1091 else if (!(j = job_new(m, type, unit)))
1096 j->matters_to_anchor = false;
1099 LIST_PREPEND(Job, transaction, f, j);
1101 if ((r = hashmap_replace(m->transaction_jobs, unit, f)) < 0) {
1109 log_debug("Added job %s/%s to transaction.", unit_id(unit), job_type_to_string(type));
1114 void manager_transaction_unlink_job(Manager *m, Job *j, bool delete_dependencies) {
1118 if (j->transaction_prev)
1119 j->transaction_prev->transaction_next = j->transaction_next;
1120 else if (j->transaction_next)
1121 hashmap_replace(m->transaction_jobs, j->unit, j->transaction_next);
1123 hashmap_remove_value(m->transaction_jobs, j->unit, j);
1125 if (j->transaction_next)
1126 j->transaction_next->transaction_prev = j->transaction_prev;
1128 j->transaction_prev = j->transaction_next = NULL;
1130 while (j->subject_list)
1131 job_dependency_free(j->subject_list);
1133 while (j->object_list) {
1134 Job *other = j->object_list->matters ? j->object_list->subject : NULL;
1136 job_dependency_free(j->object_list);
1138 if (other && delete_dependencies) {
1139 log_debug("Deleting job %s/%s as dependency of job %s/%s",
1140 unit_id(other->unit), job_type_to_string(other->type),
1141 unit_id(j->unit), job_type_to_string(j->type));
1142 transaction_delete_job(m, other, delete_dependencies);
1147 static int transaction_add_job_and_dependencies(Manager *m, JobType type, Unit *unit, Job *by, bool matters, bool force, Job **_ret) {
1155 assert(type < _JOB_TYPE_MAX);
1158 if (unit->meta.load_state != UNIT_LOADED)
1161 if (!unit_job_is_applicable(unit, type))
1164 /* First add the job. */
1165 if (!(ret = transaction_add_one_job(m, type, unit, force, &is_new)))
1168 /* Then, add a link to the job. */
1169 if (!job_dependency_new(by, ret, matters))
1173 /* Finally, recursively add in all dependencies. */
1174 if (type == JOB_START || type == JOB_RELOAD_OR_START) {
1175 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES], i)
1176 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, true, force, NULL)) < 0 && r != -EBADR)
1178 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_SOFT_REQUIRES], i)
1179 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, !force, force, NULL)) < 0 && r != -EBADR)
1181 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_WANTS], i)
1182 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, false, force, NULL)) < 0)
1183 log_warning("Cannot add dependency job for unit %s, ignoring: %s", unit_id(dep), strerror(-r));
1184 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE], i)
1185 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, true, force, NULL)) < 0 && r != -EBADR)
1187 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_SOFT_REQUISITE], i)
1188 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, !force, force, NULL)) < 0 && r != -EBADR)
1190 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_CONFLICTS], i)
1191 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, dep, ret, true, force, NULL)) < 0 && r != -EBADR)
1194 } else if (type == JOB_STOP || type == JOB_RESTART || type == JOB_TRY_RESTART) {
1196 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRED_BY], i)
1197 if ((r = transaction_add_job_and_dependencies(m, type, dep, ret, true, force, NULL)) < 0 && r != -EBADR)
1201 /* JOB_VERIFY_STARTED, JOB_RELOAD require no dependency handling */
1213 int manager_add_job(Manager *m, JobType type, Unit *unit, JobMode mode, bool force, Job **_ret) {
1218 assert(type < _JOB_TYPE_MAX);
1220 assert(mode < _JOB_MODE_MAX);
1222 log_debug("Trying to enqueue job %s/%s", unit_id(unit), job_type_to_string(type));
1224 if ((r = transaction_add_job_and_dependencies(m, type, unit, NULL, true, force, &ret)) < 0) {
1225 transaction_abort(m);
1229 if ((r = transaction_activate(m, mode)) < 0)
1232 log_debug("Enqueued job %s/%s as %u", unit_id(unit), job_type_to_string(type), (unsigned) ret->id);
1240 Job *manager_get_job(Manager *m, uint32_t id) {
1243 return hashmap_get(m->jobs, UINT32_TO_PTR(id));
1246 Unit *manager_get_unit(Manager *m, const char *name) {
1250 return hashmap_get(m->units, name);
1253 unsigned manager_dispatch_load_queue(Manager *m) {
1259 /* Make sure we are not run recursively */
1260 if (m->dispatching_load_queue)
1263 m->dispatching_load_queue = true;
1265 /* Dispatches the load queue. Takes a unit from the queue and
1266 * tries to load its data until the queue is empty */
1268 while ((meta = m->load_queue)) {
1269 assert(meta->in_load_queue);
1271 unit_load(UNIT(meta));
1275 m->dispatching_load_queue = false;
1279 int manager_load_unit(Manager *m, const char *path, Unit **_ret) {
1288 /* This will load the service information files, but not actually
1289 * start any services or anything. */
1291 name = file_name_from_path(path);
1293 if ((ret = manager_get_unit(m, name))) {
1298 if (!(ret = unit_new(m)))
1301 if (is_path(path)) {
1302 if (!(ret->meta.fragment_path = strdup(path))) {
1308 if ((r = unit_add_name(ret, name)) < 0) {
1313 unit_add_to_load_queue(ret);
1314 unit_add_to_dbus_queue(ret);
1316 manager_dispatch_load_queue(m);
1318 *_ret = unit_follow_merge(ret);
1322 void manager_dump_jobs(Manager *s, FILE *f, const char *prefix) {
1329 HASHMAP_FOREACH(j, s->jobs, i)
1330 job_dump(j, f, prefix);
1333 void manager_dump_units(Manager *s, FILE *f, const char *prefix) {
1341 HASHMAP_FOREACH_KEY(u, t, s->units, i)
1342 if (unit_id(u) == t)
1343 unit_dump(u, f, prefix);
1346 void manager_clear_jobs(Manager *m) {
1351 transaction_abort(m);
1353 while ((j = hashmap_first(m->jobs)))
1357 unsigned manager_dispatch_run_queue(Manager *m) {
1361 if (m->dispatching_run_queue)
1364 m->dispatching_run_queue = true;
1366 while ((j = m->run_queue)) {
1367 assert(j->installed);
1368 assert(j->in_run_queue);
1370 job_run_and_invalidate(j);
1374 m->dispatching_run_queue = false;
1378 unsigned manager_dispatch_dbus_queue(Manager *m) {
1385 if (m->dispatching_dbus_queue)
1388 m->dispatching_dbus_queue = true;
1390 while ((meta = m->dbus_unit_queue)) {
1391 assert(meta->in_dbus_queue);
1393 bus_unit_send_change_signal(UNIT(meta));
1397 while ((j = m->dbus_job_queue)) {
1398 assert(j->in_dbus_queue);
1400 bus_job_send_change_signal(j);
1404 m->dispatching_dbus_queue = false;
1408 static int manager_dispatch_sigchld(Manager *m) {
1411 log_debug("dispatching SIGCHLD");
1418 if (waitid(P_ALL, 0, &si, WEXITED|WNOHANG) < 0) {
1420 if (errno == ECHILD)
1429 if (si.si_code != CLD_EXITED && si.si_code != CLD_KILLED && si.si_code != CLD_DUMPED)
1432 log_debug("child %llu died (code=%s, status=%i)", (long long unsigned) si.si_pid, sigchld_code_to_string(si.si_code), si.si_status);
1434 if (!(u = hashmap_remove(m->watch_pids, UINT32_TO_PTR(si.si_pid))))
1437 UNIT_VTABLE(u)->sigchld_event(u, si.si_pid, si.si_code, si.si_status);
1443 static int manager_process_signal_fd(Manager *m, bool *quit) {
1445 struct signalfd_siginfo sfsi;
1446 bool sigchld = false;
1451 if ((n = read(m->signal_watch.fd, &sfsi, sizeof(sfsi))) != sizeof(sfsi)) {
1456 if (errno == EAGAIN)
1462 switch (sfsi.ssi_signo) {
1471 if (m->running_as != MANAGER_INIT) {
1479 if ((r = manager_load_unit(m, SPECIAL_CTRL_ALT_DEL_TARGET, &target)) < 0)
1480 log_error("Failed to load ctrl-alt-del target: %s", strerror(-r));
1481 else if ((r = manager_add_job(m, JOB_START, target, JOB_REPLACE, true, NULL)) < 0)
1482 log_error("Failed to enqueue ctrl-alt-del job: %s", strerror(-r));
1489 if (m->running_as == MANAGER_INIT) {
1493 if ((r = manager_load_unit(m, SPECIAL_KBREQUEST_TARGET, &target)) < 0)
1494 log_error("Failed to load kbrequest target: %s", strerror(-r));
1495 else if ((r = manager_add_job(m, JOB_START, target, JOB_REPLACE, true, NULL)) < 0)
1496 log_error("Failed to enqueue kbrequest job: %s", strerror(-r));
1501 /* This is a nop on non-init systemd's */
1507 printf("→ By units:\n");
1508 manager_dump_units(m, stdout, "\t");
1510 printf("→ By jobs:\n");
1511 manager_dump_jobs(m, stdout, "\t");
1516 log_info("Got unhandled signal <%s>.", strsignal(sfsi.ssi_signo));
1521 return manager_dispatch_sigchld(m);
1526 static int process_event(Manager *m, struct epoll_event *ev, bool *quit) {
1533 assert(w = ev->data.ptr);
1539 /* An incoming signal? */
1540 if (ev->events != EPOLLIN)
1543 if ((r = manager_process_signal_fd(m, quit)) < 0)
1550 /* Some fd event, to be dispatched to the units */
1551 UNIT_VTABLE(w->data.unit)->fd_event(w->data.unit, w->fd, ev->events, w);
1558 /* Some timer event, to be dispatched to the units */
1559 if ((k = read(w->fd, &v, sizeof(v))) != sizeof(v)) {
1561 if (k < 0 && (errno == EINTR || errno == EAGAIN))
1564 return k < 0 ? -errno : -EIO;
1567 UNIT_VTABLE(w->data.unit)->timer_event(w->data.unit, v, w);
1572 /* Some mount table change, intended for the mount subsystem */
1573 mount_fd_event(m, ev->events);
1577 /* Some notification from udev, intended for the device subsystem */
1578 device_fd_event(m, ev->events);
1581 case WATCH_DBUS_WATCH:
1582 bus_watch_event(m, w, ev->events);
1585 case WATCH_DBUS_TIMEOUT:
1586 bus_timeout_event(m, w, ev->events);
1590 assert_not_reached("Unknown epoll event type.");
1596 int manager_loop(Manager *m) {
1600 RATELIMIT_DEFINE(rl, 1*USEC_PER_SEC, 1000);
1605 struct epoll_event event;
1608 if (!ratelimit_test(&rl)) {
1609 /* Yay, something is going seriously wrong, pause a little */
1610 log_warning("Looping too fast. Throttling execution a little.");
1614 if (manager_dispatch_cleanup_queue(m) > 0)
1617 if (manager_dispatch_load_queue(m) > 0)
1620 if (manager_dispatch_run_queue(m) > 0)
1623 if (bus_dispatch(m) > 0)
1626 if (manager_dispatch_dbus_queue(m) > 0)
1629 if ((n = epoll_wait(m->epoll_fd, &event, 1, -1)) < 0) {
1631 if (errno == -EINTR)
1639 if ((r = process_event(m, &event, &quit)) < 0)
1646 int manager_get_unit_from_dbus_path(Manager *m, const char *s, Unit **_u) {
1654 if (!startswith(s, "/org/freedesktop/systemd1/unit/"))
1657 if (!(n = bus_path_unescape(s+31)))
1660 u = manager_get_unit(m, n);
1671 int manager_get_job_from_dbus_path(Manager *m, const char *s, Job **_j) {
1680 if (!startswith(s, "/org/freedesktop/systemd1/job/"))
1683 if ((r = safe_atou(s + 30, &id)) < 0)
1686 if (!(j = manager_get_job(m, id)))
1694 static const char* const manager_running_as_table[_MANAGER_RUNNING_AS_MAX] = {
1695 [MANAGER_INIT] = "init",
1696 [MANAGER_SYSTEM] = "system",
1697 [MANAGER_SESSION] = "session"
1700 DEFINE_STRING_TABLE_LOOKUP(manager_running_as, ManagerRunningAs);