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) {
199 /* First priority is whatever has been passed to us via env
201 if ((e = getenv("SYSTEMD_UNIT_PATH")))
202 if (!(m->unit_path = split_path_and_make_absolute(e)))
205 if (strv_isempty(m->unit_path)) {
207 /* Nothing is set, so let's figure something out. */
208 strv_free(m->unit_path);
210 if (m->running_as == MANAGER_SESSION) {
211 if (!(m->unit_path = session_dirs()))
214 if (!(m->unit_path = strv_new(
215 SYSTEM_CONFIG_UNIT_PATH, /* /etc/systemd/system/ */
216 SYSTEM_DATA_UNIT_PATH, /* /lib/systemd/system/ */
221 if (m->running_as == MANAGER_INIT) {
222 /* /etc/init.d/ compativility does not matter to users */
224 if ((e = getenv("SYSTEMD_SYSVINIT_PATH")))
225 if (!(m->sysvinit_path = split_path_and_make_absolute(e)))
228 if (strv_isempty(m->sysvinit_path)) {
229 strv_free(m->sysvinit_path);
231 if (!(m->sysvinit_path = strv_new(
232 SYSTEM_SYSVINIT_PATH, /* /etc/init.d/ */
238 strv_uniq(m->unit_path);
239 strv_uniq(m->sysvinit_path);
241 assert(!strv_isempty(m->unit_path));
242 if (!(t = strv_join(m->unit_path, "\n\t")))
244 log_debug("Looking for unit files in:\n\t%s", t);
247 if (!strv_isempty(m->sysvinit_path)) {
249 if (!(t = strv_join(m->sysvinit_path, "\n\t")))
252 log_debug("Looking for SysV init scripts in:\n\t%s", t);
255 log_debug("Ignoring SysV init scripts.");
260 int manager_new(Manager **_m) {
266 if (!(m = new0(Manager, 1)))
269 m->signal_watch.fd = m->mount_watch.fd = m->udev_watch.fd = m->epoll_fd = -1;
270 m->current_job_id = 1; /* start as id #1, so that we can leave #0 around as "null-like" value */
272 if (!(m->units = hashmap_new(string_hash_func, string_compare_func)))
275 if (!(m->jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
278 if (!(m->transaction_jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
281 if (!(m->watch_pids = hashmap_new(trivial_hash_func, trivial_compare_func)))
284 if (!(m->cgroup_bondings = hashmap_new(string_hash_func, string_compare_func)))
287 if ((m->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0)
291 m->running_as = MANAGER_INIT;
292 else if (getuid() == 0)
293 m->running_as = MANAGER_SYSTEM;
295 m->running_as = MANAGER_SESSION;
297 log_debug("systemd running in %s mode.", manager_running_as_to_string(m->running_as));
299 if ((r = manager_find_paths(m)) < 0)
303 log_warning("Failed to chdir to /: %s", strerror(errno));
305 /* Become a session leader if we aren't one yet. */
308 if ((r = manager_setup_signals(m)) < 0)
311 if ((r = mount_setup()) < 0)
314 if ((r = manager_setup_cgroup(m)) < 0)
317 /* FIXME: this should be called only when the D-Bus bus daemon is running */
318 if ((r = bus_init(m)) < 0)
329 void manager_free(Manager *m) {
336 while ((j = hashmap_first(m->transaction_jobs)))
339 while ((u = hashmap_first(m->units)))
342 for (c = 0; c < _UNIT_TYPE_MAX; c++)
343 if (unit_vtable[c]->shutdown)
344 unit_vtable[c]->shutdown(m);
346 manager_shutdown_cgroup(m);
350 hashmap_free(m->units);
351 hashmap_free(m->jobs);
352 hashmap_free(m->transaction_jobs);
353 hashmap_free(m->watch_pids);
355 if (m->epoll_fd >= 0)
356 close_nointr(m->epoll_fd);
357 if (m->signal_watch.fd >= 0)
358 close_nointr(m->signal_watch.fd);
360 strv_free(m->unit_path);
361 strv_free(m->sysvinit_path);
363 free(m->cgroup_controller);
364 free(m->cgroup_hierarchy);
366 assert(hashmap_isempty(m->cgroup_bondings));
367 hashmap_free(m->cgroup_bondings);
372 int manager_coldplug(Manager *m) {
381 /* First, let's ask every type to load all units from
382 * disk/kernel that it might know */
383 for (c = 0; c < _UNIT_TYPE_MAX; c++)
384 if (unit_vtable[c]->enumerate)
385 if ((r = unit_vtable[c]->enumerate(m)) < 0)
388 manager_dispatch_load_queue(m);
390 /* Then, let's set up their initial state. */
391 HASHMAP_FOREACH_KEY(u, k, m->units, i) {
397 if (UNIT_VTABLE(u)->coldplug)
398 if ((r = UNIT_VTABLE(u)->coldplug(u)) < 0)
405 static void transaction_delete_job(Manager *m, Job *j) {
409 /* Deletes one job from the transaction */
411 manager_transaction_unlink_job(m, j);
417 static void transaction_delete_unit(Manager *m, Unit *u) {
420 /* Deletes all jobs associated with a certain unit from the
423 while ((j = hashmap_get(m->transaction_jobs, u)))
424 transaction_delete_job(m, j);
427 static void transaction_clean_dependencies(Manager *m) {
433 /* Drops all dependencies of all installed jobs */
435 HASHMAP_FOREACH(j, m->jobs, i) {
436 while (j->subject_list)
437 job_dependency_free(j->subject_list);
438 while (j->object_list)
439 job_dependency_free(j->object_list);
442 assert(!m->transaction_anchor);
445 static void transaction_abort(Manager *m) {
450 while ((j = hashmap_first(m->transaction_jobs)))
452 transaction_delete_job(m, j);
456 assert(hashmap_isempty(m->transaction_jobs));
458 transaction_clean_dependencies(m);
461 static void transaction_find_jobs_that_matter_to_anchor(Manager *m, Job *j, unsigned generation) {
466 /* A recursive sweep through the graph that marks all units
467 * that matter to the anchor job, i.e. are directly or
468 * indirectly a dependency of the anchor job via paths that
469 * are fully marked as mattering. */
474 l = m->transaction_anchor;
476 LIST_FOREACH(subject, l, l) {
478 /* This link does not matter */
482 /* This unit has already been marked */
483 if (l->object->generation == generation)
486 l->object->matters_to_anchor = true;
487 l->object->generation = generation;
489 transaction_find_jobs_that_matter_to_anchor(m, l->object, generation);
493 static void transaction_merge_and_delete_job(Manager *m, Job *j, Job *other, JobType t) {
494 JobDependency *l, *last;
498 assert(j->unit == other->unit);
499 assert(!j->installed);
501 /* Merges 'other' into 'j' and then deletes j. */
504 j->state = JOB_WAITING;
505 j->forced = j->forced || other->forced;
507 j->matters_to_anchor = j->matters_to_anchor || other->matters_to_anchor;
509 /* Patch us in as new owner of the JobDependency objects */
511 LIST_FOREACH(subject, l, other->subject_list) {
512 assert(l->subject == other);
517 /* Merge both lists */
519 last->subject_next = j->subject_list;
521 j->subject_list->subject_prev = last;
522 j->subject_list = other->subject_list;
525 /* Patch us in as new owner of the JobDependency objects */
527 LIST_FOREACH(object, l, other->object_list) {
528 assert(l->object == other);
533 /* Merge both lists */
535 last->object_next = j->object_list;
537 j->object_list->object_prev = last;
538 j->object_list = other->object_list;
541 /* Kill the other job */
542 other->subject_list = NULL;
543 other->object_list = NULL;
544 transaction_delete_job(m, other);
547 static int delete_one_unmergeable_job(Manager *m, Job *j) {
552 /* Tries to delete one item in the linked list
553 * j->transaction_next->transaction_next->... that conflicts
554 * whith another one, in an attempt to make an inconsistent
555 * transaction work. */
557 /* We rely here on the fact that if a merged with b does not
558 * merge with c, either a or b merge with c neither */
559 LIST_FOREACH(transaction, j, j)
560 LIST_FOREACH(transaction, k, j->transaction_next) {
563 /* Is this one mergeable? Then skip it */
564 if (job_type_is_mergeable(j->type, k->type))
567 /* Ok, we found two that conflict, let's see if we can
568 * drop one of them */
569 if (!j->matters_to_anchor)
571 else if (!k->matters_to_anchor)
576 /* Ok, we can drop one, so let's do so. */
577 log_debug("Try to fix job merging by deleting job %s/%s", unit_id(d->unit), job_type_to_string(d->type));
578 transaction_delete_job(m, d);
585 static int transaction_merge_jobs(Manager *m) {
592 /* First step, check whether any of the jobs for one specific
593 * task conflict. If so, try to drop one of them. */
594 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
599 LIST_FOREACH(transaction, k, j->transaction_next) {
600 if ((r = job_type_merge(&t, k->type)) >= 0)
603 /* OK, we could not merge all jobs for this
604 * action. Let's see if we can get rid of one
607 if ((r = delete_one_unmergeable_job(m, j)) >= 0)
608 /* Ok, we managed to drop one, now
609 * let's ask our callers to call us
610 * again after garbage collecting */
613 /* We couldn't merge anything. Failure */
618 /* Second step, merge the jobs. */
619 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
623 /* Merge all transactions */
624 LIST_FOREACH(transaction, k, j->transaction_next)
625 assert_se(job_type_merge(&t, k->type) == 0);
627 /* If an active job is mergeable, merge it too */
628 if (j->unit->meta.job)
629 job_type_merge(&t, j->unit->meta.job->type); /* Might fail. Which is OK */
631 while ((k = j->transaction_next)) {
633 transaction_merge_and_delete_job(m, k, j, t);
636 transaction_merge_and_delete_job(m, j, k, t);
639 assert(!j->transaction_next);
640 assert(!j->transaction_prev);
646 static bool unit_matters_to_anchor(Unit *u, Job *j) {
648 assert(!j->transaction_prev);
650 /* Checks whether at least one of the jobs for this unit
651 * matters to the anchor. */
653 LIST_FOREACH(transaction, j, j)
654 if (j->matters_to_anchor)
660 static int transaction_verify_order_one(Manager *m, Job *j, Job *from, unsigned generation) {
667 assert(!j->transaction_prev);
669 /* Does a recursive sweep through the ordering graph, looking
670 * for a cycle. If we find cycle we try to break it. */
672 /* Did we find a cycle? */
673 if (j->marker && j->generation == generation) {
676 /* So, we already have been here. We have a
677 * cycle. Let's try to break it. We go backwards in
678 * our path and try to find a suitable job to
679 * remove. We use the marker to find our way back,
680 * since smart how we are we stored our way back in
683 log_debug("Found cycle on %s/%s", unit_id(j->unit), job_type_to_string(j->type));
685 for (k = from; k; k = (k->generation == generation ? k->marker : NULL)) {
687 log_debug("Walked on cycle path to %s/%s", unit_id(j->unit), job_type_to_string(j->type));
690 !unit_matters_to_anchor(k->unit, k)) {
691 /* Ok, we can drop this one, so let's
693 log_debug("Breaking order cycle by deleting job %s/%s", unit_id(k->unit), job_type_to_string(k->type));
694 transaction_delete_unit(m, k->unit);
698 /* Check if this in fact was the beginning of
704 log_debug("Unable to break cycle");
709 /* Make the marker point to where we come from, so that we can
710 * find our way backwards if we want to break a cycle */
712 j->generation = generation;
714 /* We assume that the the dependencies are bidirectional, and
715 * hence can ignore UNIT_AFTER */
716 SET_FOREACH(u, j->unit->meta.dependencies[UNIT_BEFORE], i) {
719 /* Is there a job for this unit? */
720 if (!(o = hashmap_get(m->transaction_jobs, u)))
722 /* Ok, there is no job for this in the
723 * transaction, but maybe there is already one
725 if (!(o = u->meta.job))
728 if ((r = transaction_verify_order_one(m, o, j, generation)) < 0)
732 /* Ok, let's backtrack, and remember that this entry is not on
733 * our path anymore. */
739 static int transaction_verify_order(Manager *m, unsigned *generation) {
747 /* Check if the ordering graph is cyclic. If it is, try to fix
748 * that up by dropping one of the jobs. */
750 HASHMAP_FOREACH(j, m->transaction_jobs, i)
751 if ((r = transaction_verify_order_one(m, j, NULL, (*generation)++)) < 0)
757 static void transaction_collect_garbage(Manager *m) {
762 /* Drop jobs that are not required by any other job */
770 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
774 log_debug("Garbage collecting job %s/%s", unit_id(j->unit), job_type_to_string(j->type));
775 transaction_delete_job(m, j);
783 static int transaction_is_destructive(Manager *m, JobMode mode) {
789 /* Checks whether applying this transaction means that
790 * existing jobs would be replaced */
792 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
795 assert(!j->transaction_prev);
796 assert(!j->transaction_next);
798 if (j->unit->meta.job &&
799 j->unit->meta.job != j &&
800 !job_type_is_superset(j->type, j->unit->meta.job->type))
807 static void transaction_minimize_impact(Manager *m) {
811 /* Drops all unnecessary jobs that reverse already active jobs
812 * or that stop a running service. */
820 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
821 LIST_FOREACH(transaction, j, j) {
822 bool stops_running_service, changes_existing_job;
824 /* If it matters, we shouldn't drop it */
825 if (j->matters_to_anchor)
828 /* Would this stop a running service?
829 * Would this change an existing job?
830 * If so, let's drop this entry */
832 stops_running_service =
833 j->type == JOB_STOP && UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(j->unit));
835 changes_existing_job =
836 j->unit->meta.job && job_type_is_conflicting(j->type, j->unit->meta.job->state);
838 if (!stops_running_service && !changes_existing_job)
841 if (stops_running_service)
842 log_debug("%s/%s would stop a running service.", unit_id(j->unit), job_type_to_string(j->type));
844 if (changes_existing_job)
845 log_debug("%s/%s would change existing job.", unit_id(j->unit), job_type_to_string(j->type));
847 /* Ok, let's get rid of this */
848 log_debug("Deleting %s/%s to minimize impact.", unit_id(j->unit), job_type_to_string(j->type));
850 transaction_delete_job(m, j);
862 static int transaction_apply(Manager *m, JobMode mode) {
867 /* Moves the transaction jobs to the set of active jobs */
869 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
871 assert(!j->transaction_prev);
872 assert(!j->transaction_next);
877 if ((r = hashmap_put(m->jobs, UINT32_TO_PTR(j->id), j)) < 0)
881 while ((j = hashmap_steal_first(m->transaction_jobs))) {
885 if (j->unit->meta.job)
886 job_free(j->unit->meta.job);
888 j->unit->meta.job = j;
891 /* We're fully installed. Now let's free data we don't
894 assert(!j->transaction_next);
895 assert(!j->transaction_prev);
897 job_add_to_run_queue(j);
898 job_add_to_dbus_queue(j);
901 /* As last step, kill all remaining job dependencies. */
902 transaction_clean_dependencies(m);
908 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
912 hashmap_remove(m->jobs, UINT32_TO_PTR(j->id));
918 static int transaction_activate(Manager *m, JobMode mode) {
920 unsigned generation = 1;
924 /* This applies the changes recorded in transaction_jobs to
925 * the actual list of jobs, if possible. */
927 /* First step: figure out which jobs matter */
928 transaction_find_jobs_that_matter_to_anchor(m, NULL, generation++);
930 /* Second step: Try not to stop any running services if
931 * we don't have to. Don't try to reverse running
932 * jobs if we don't have to. */
933 transaction_minimize_impact(m);
936 /* Third step: Let's remove unneeded jobs that might
938 transaction_collect_garbage(m);
940 /* Fourth step: verify order makes sense and correct
941 * cycles if necessary and possible */
942 if ((r = transaction_verify_order(m, &generation)) >= 0)
946 log_debug("Requested transaction contains an unfixable cyclic ordering dependency: %s", strerror(-r));
950 /* Let's see if the resulting transaction ordering
951 * graph is still cyclic... */
955 /* Fifth step: let's drop unmergeable entries if
956 * necessary and possible, merge entries we can
958 if ((r = transaction_merge_jobs(m)) >= 0)
962 log_debug("Requested transaction contains unmergable jobs: %s", strerror(-r));
966 /* Sixth step: an entry got dropped, let's garbage
967 * collect its dependencies. */
968 transaction_collect_garbage(m);
970 /* Let's see if the resulting transaction still has
971 * unmergeable entries ... */
974 /* Seventh step: check whether we can actually apply this */
975 if (mode == JOB_FAIL)
976 if ((r = transaction_is_destructive(m, mode)) < 0) {
977 log_debug("Requested transaction contradicts existing jobs: %s", strerror(-r));
981 /* Eights step: apply changes */
982 if ((r = transaction_apply(m, mode)) < 0) {
983 log_debug("Failed to apply transaction: %s", strerror(-r));
987 assert(hashmap_isempty(m->transaction_jobs));
988 assert(!m->transaction_anchor);
993 transaction_abort(m);
997 static Job* transaction_add_one_job(Manager *m, JobType type, Unit *unit, bool force, bool *is_new) {
1004 /* Looks for an axisting prospective job and returns that. If
1005 * it doesn't exist it is created and added to the prospective
1008 f = hashmap_get(m->transaction_jobs, unit);
1010 LIST_FOREACH(transaction, j, f) {
1011 assert(j->unit == unit);
1013 if (j->type == type) {
1020 if (unit->meta.job && unit->meta.job->type == type)
1022 else if (!(j = job_new(m, type, unit)))
1027 j->matters_to_anchor = false;
1030 LIST_PREPEND(Job, transaction, f, j);
1032 if ((r = hashmap_replace(m->transaction_jobs, unit, f)) < 0) {
1043 void manager_transaction_unlink_job(Manager *m, Job *j) {
1047 if (j->transaction_prev)
1048 j->transaction_prev->transaction_next = j->transaction_next;
1049 else if (j->transaction_next)
1050 hashmap_replace(m->transaction_jobs, j->unit, j->transaction_next);
1052 hashmap_remove_value(m->transaction_jobs, j->unit, j);
1054 if (j->transaction_next)
1055 j->transaction_next->transaction_prev = j->transaction_prev;
1057 j->transaction_prev = j->transaction_next = NULL;
1059 while (j->subject_list)
1060 job_dependency_free(j->subject_list);
1062 while (j->object_list) {
1063 Job *other = j->object_list->matters ? j->object_list->subject : NULL;
1065 job_dependency_free(j->object_list);
1068 log_debug("Deleting job %s/%s as dependency of job %s/%s",
1069 unit_id(other->unit), job_type_to_string(other->type),
1070 unit_id(j->unit), job_type_to_string(j->type));
1071 transaction_delete_job(m, other);
1076 static int transaction_add_job_and_dependencies(Manager *m, JobType type, Unit *unit, Job *by, bool matters, bool force, Job **_ret) {
1084 assert(type < _JOB_TYPE_MAX);
1087 if (unit->meta.load_state != UNIT_LOADED)
1090 if (!unit_job_is_applicable(unit, type))
1093 /* First add the job. */
1094 if (!(ret = transaction_add_one_job(m, type, unit, force, &is_new)))
1097 /* Then, add a link to the job. */
1098 if (!job_dependency_new(by, ret, matters))
1102 /* Finally, recursively add in all dependencies. */
1103 if (type == JOB_START || type == JOB_RELOAD_OR_START) {
1104 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES], i)
1105 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, true, force, NULL)) < 0 && r != -EBADR)
1107 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_SOFT_REQUIRES], i)
1108 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, !force, force, NULL)) < 0 && r != -EBADR)
1110 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_WANTS], i)
1111 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, false, force, NULL)) < 0 && r != -EBADR)
1113 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE], i)
1114 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, true, force, NULL)) < 0 && r != -EBADR)
1116 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_SOFT_REQUISITE], i)
1117 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, !force, force, NULL)) < 0 && r != -EBADR)
1119 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_CONFLICTS], i)
1120 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, dep, ret, true, force, NULL)) < 0 && r != -EBADR)
1123 } else if (type == JOB_STOP || type == JOB_RESTART || type == JOB_TRY_RESTART) {
1125 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRED_BY], i)
1126 if ((r = transaction_add_job_and_dependencies(m, type, dep, ret, true, force, NULL)) < 0 && r != -EBADR)
1130 /* JOB_VERIFY_STARTED, JOB_RELOAD require no dependency handling */
1142 int manager_add_job(Manager *m, JobType type, Unit *unit, JobMode mode, bool force, Job **_ret) {
1147 assert(type < _JOB_TYPE_MAX);
1149 assert(mode < _JOB_MODE_MAX);
1151 log_debug("Trying to enqueue job %s/%s", unit_id(unit), job_type_to_string(type));
1153 if ((r = transaction_add_job_and_dependencies(m, type, unit, NULL, true, force, &ret)) < 0) {
1154 transaction_abort(m);
1158 if ((r = transaction_activate(m, mode)) < 0)
1161 log_debug("Enqueued job %s/%s as %u", unit_id(unit), job_type_to_string(type), (unsigned) ret->id);
1169 Job *manager_get_job(Manager *m, uint32_t id) {
1172 return hashmap_get(m->jobs, UINT32_TO_PTR(id));
1175 Unit *manager_get_unit(Manager *m, const char *name) {
1179 return hashmap_get(m->units, name);
1182 unsigned manager_dispatch_load_queue(Manager *m) {
1188 /* Make sure we are not run recursively */
1189 if (m->dispatching_load_queue)
1192 m->dispatching_load_queue = true;
1194 /* Dispatches the load queue. Takes a unit from the queue and
1195 * tries to load its data until the queue is empty */
1197 while ((meta = m->load_queue)) {
1198 assert(meta->in_load_queue);
1200 unit_load(UNIT(meta));
1204 m->dispatching_load_queue = false;
1208 int manager_load_unit(Manager *m, const char *path, Unit **_ret) {
1217 /* This will load the service information files, but not actually
1218 * start any services or anything. */
1220 name = file_name_from_path(path);
1222 if ((ret = manager_get_unit(m, name))) {
1227 if (!(ret = unit_new(m)))
1230 if (is_path(path)) {
1231 if (!(ret->meta.fragment_path = strdup(path))) {
1237 if ((r = unit_add_name(ret, name)) < 0) {
1242 unit_add_to_load_queue(ret);
1243 unit_add_to_dbus_queue(ret);
1245 manager_dispatch_load_queue(m);
1251 void manager_dump_jobs(Manager *s, FILE *f, const char *prefix) {
1258 HASHMAP_FOREACH(j, s->jobs, i)
1259 job_dump(j, f, prefix);
1262 void manager_dump_units(Manager *s, FILE *f, const char *prefix) {
1270 HASHMAP_FOREACH_KEY(u, t, s->units, i)
1271 if (unit_id(u) == t)
1272 unit_dump(u, f, prefix);
1275 void manager_clear_jobs(Manager *m) {
1280 transaction_abort(m);
1282 while ((j = hashmap_first(m->jobs)))
1286 unsigned manager_dispatch_run_queue(Manager *m) {
1290 if (m->dispatching_run_queue)
1293 m->dispatching_run_queue = true;
1295 while ((j = m->run_queue)) {
1296 assert(j->installed);
1297 assert(j->in_run_queue);
1299 job_run_and_invalidate(j);
1303 m->dispatching_run_queue = false;
1307 unsigned manager_dispatch_dbus_queue(Manager *m) {
1314 if (m->dispatching_dbus_queue)
1317 m->dispatching_dbus_queue = true;
1319 while ((meta = m->dbus_unit_queue)) {
1320 Unit *u = (Unit*) meta;
1321 assert(u->meta.in_dbus_queue);
1323 bus_unit_send_change_signal(u);
1327 while ((j = m->dbus_job_queue)) {
1328 assert(j->in_dbus_queue);
1330 bus_job_send_change_signal(j);
1334 m->dispatching_dbus_queue = false;
1338 static int manager_dispatch_sigchld(Manager *m) {
1341 log_debug("dispatching SIGCHLD");
1348 if (waitid(P_ALL, 0, &si, WEXITED|WNOHANG) < 0) {
1350 if (errno == ECHILD)
1359 if (si.si_code != CLD_EXITED && si.si_code != CLD_KILLED && si.si_code != CLD_DUMPED)
1362 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);
1364 if (!(u = hashmap_remove(m->watch_pids, UINT32_TO_PTR(si.si_pid))))
1367 UNIT_VTABLE(u)->sigchld_event(u, si.si_pid, si.si_code, si.si_status);
1373 static int manager_process_signal_fd(Manager *m, bool *quit) {
1375 struct signalfd_siginfo sfsi;
1376 bool sigchld = false;
1381 if ((n = read(m->signal_watch.fd, &sfsi, sizeof(sfsi))) != sizeof(sfsi)) {
1386 if (errno == EAGAIN)
1392 switch (sfsi.ssi_signo) {
1401 if (m->running_as != MANAGER_INIT) {
1409 if ((r = manager_load_unit(m, SPECIAL_CTRL_ALT_DEL_TARGET, &target)) < 0)
1410 log_error("Failed to load ctrl-alt-del target: %s", strerror(-r));
1411 else if ((r = manager_add_job(m, JOB_START, target, JOB_REPLACE, true, NULL)) < 0)
1412 log_error("Failed to enqueue ctrl-alt-del job: %s", strerror(-r));
1419 if (m->running_as == MANAGER_INIT) {
1423 if ((r = manager_load_unit(m, SPECIAL_KBREQUEST_TARGET, &target)) < 0)
1424 log_error("Failed to load kbrequest target: %s", strerror(-r));
1425 else if ((r = manager_add_job(m, JOB_START, target, JOB_REPLACE, true, NULL)) < 0)
1426 log_error("Failed to enqueue kbrequest job: %s", strerror(-r));
1431 /* This is a nop on non-init systemd's */
1436 log_info("Got unhandled signal <%s>.", strsignal(sfsi.ssi_signo));
1441 return manager_dispatch_sigchld(m);
1446 static int process_event(Manager *m, struct epoll_event *ev, bool *quit) {
1453 assert(w = ev->data.ptr);
1459 /* An incoming signal? */
1460 if (ev->events != EPOLLIN)
1463 if ((r = manager_process_signal_fd(m, quit)) < 0)
1470 /* Some fd event, to be dispatched to the units */
1471 UNIT_VTABLE(w->data.unit)->fd_event(w->data.unit, w->fd, ev->events, w);
1478 /* Some timer event, to be dispatched to the units */
1479 if ((k = read(w->fd, &v, sizeof(v))) != sizeof(v)) {
1481 if (k < 0 && (errno == EINTR || errno == EAGAIN))
1484 return k < 0 ? -errno : -EIO;
1487 UNIT_VTABLE(w->data.unit)->timer_event(w->data.unit, v, w);
1492 /* Some mount table change, intended for the mount subsystem */
1493 mount_fd_event(m, ev->events);
1497 /* Some notification from udev, intended for the device subsystem */
1498 device_fd_event(m, ev->events);
1501 case WATCH_DBUS_WATCH:
1502 bus_watch_event(m, w, ev->events);
1505 case WATCH_DBUS_TIMEOUT:
1506 bus_timeout_event(m, w, ev->events);
1510 assert_not_reached("Unknown epoll event type.");
1516 int manager_loop(Manager *m) {
1520 RATELIMIT_DEFINE(rl, 1*USEC_PER_SEC, 1000);
1525 struct epoll_event event;
1528 if (!ratelimit_test(&rl)) {
1529 /* Yay, something is going seriously wrong, pause a little */
1530 log_warning("Looping too fast. Throttling execution a little.");
1534 if (manager_dispatch_load_queue(m) > 0)
1537 if (manager_dispatch_run_queue(m) > 0)
1540 if (bus_dispatch(m) > 0)
1543 if (manager_dispatch_dbus_queue(m) > 0)
1546 if ((n = epoll_wait(m->epoll_fd, &event, 1, -1)) < 0) {
1548 if (errno == -EINTR)
1556 if ((r = process_event(m, &event, &quit)) < 0)
1564 int manager_get_unit_from_dbus_path(Manager *m, const char *s, Unit **_u) {
1572 if (!startswith(s, "/org/freedesktop/systemd1/unit/"))
1575 if (!(n = bus_path_unescape(s+31)))
1578 u = manager_get_unit(m, n);
1589 int manager_get_job_from_dbus_path(Manager *m, const char *s, Job **_j) {
1598 if (!startswith(s, "/org/freedesktop/systemd1/job/"))
1601 if ((r = safe_atou(s + 30, &id)) < 0)
1604 if (!(j = manager_get_job(m, id)))
1612 static const char* const manager_running_as_table[_MANAGER_RUNNING_AS_MAX] = {
1613 [MANAGER_INIT] = "init",
1614 [MANAGER_SYSTEM] = "system",
1615 [MANAGER_SESSION] = "session"
1618 DEFINE_STRING_TABLE_LOOKUP(manager_running_as, ManagerRunningAs);