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>
32 #include <sys/reboot.h>
33 #include <sys/ioctl.h>
35 #include <libcgroup.h>
43 #include "ratelimit.h"
45 #include "mount-setup.h"
46 #include "utmp-wtmp.h"
48 static int manager_setup_signals(Manager *m) {
50 struct epoll_event ev;
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, SIGPWR) == 0);
63 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
65 m->signal_watch.type = WATCH_SIGNAL;
66 if ((m->signal_watch.fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0)
71 ev.data.ptr = &m->signal_watch;
73 if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->signal_watch.fd, &ev) < 0)
76 if (m->running_as == MANAGER_INIT) {
77 /* Enable that we get SIGINT on control-alt-del */
78 if (reboot(RB_DISABLE_CAD) < 0)
79 log_warning("Failed to enable ctrl-alt-del handling: %s", strerror(errno));
81 /* Enable that we get SIGWINCH on kbrequest */
82 if (ioctl(0, KDSIGACCEPT, SIGWINCH) < 0)
83 log_warning("Failed to enable kbrequest handling: %s", strerror(errno));
89 static char** session_dirs(void) {
91 char *config_home = NULL, *data_home = NULL;
92 char **config_dirs = NULL, **data_dirs = NULL;
95 /* Implement the mechanisms defined in
97 * http://standards.freedesktop.org/basedir-spec/basedir-spec-0.6.html
99 * We look in both the config and the data dirs because we
100 * want to encourage that distributors ship their unit files
101 * as data, and allow overriding as configuration.
104 home = getenv("HOME");
106 if ((e = getenv("XDG_CONFIG_HOME"))) {
107 if (asprintf(&config_home, "%s/systemd/session", e) < 0)
111 if (asprintf(&config_home, "%s/.config/systemd/session", home) < 0)
115 if ((e = getenv("XDG_CONFIG_DIRS")))
116 config_dirs = strv_split(e, ":");
118 config_dirs = strv_new("/etc/xdg", NULL);
123 if ((e = getenv("XDG_DATA_HOME"))) {
124 if (asprintf(&data_home, "%s/systemd/session", e) < 0)
128 if (asprintf(&data_home, "%s/.local/share/systemd/session", home) < 0)
132 if ((e = getenv("XDG_DATA_DIRS")))
133 data_dirs = strv_split(e, ":");
135 data_dirs = strv_new("/usr/local/share", "/usr/share", NULL);
140 /* Now merge everything we found. */
142 if (!(t = strv_append(r, config_home)))
148 if (!(t = strv_merge_concat(r, config_dirs, "/systemd/session")))
153 if (!(t = strv_append(r, SESSION_CONFIG_UNIT_PATH)))
159 if (!(t = strv_append(r, data_home)))
165 if (!(t = strv_merge_concat(r, data_dirs, "/systemd/session")))
170 if (!(t = strv_append(r, SESSION_DATA_UNIT_PATH)))
175 if (!strv_path_make_absolute_cwd(r))
180 strv_free(config_dirs);
182 strv_free(data_dirs);
192 static int manager_find_paths(Manager *m) {
198 /* First priority is whatever has been passed to us via env
200 if ((e = getenv("SYSTEMD_UNIT_PATH")))
201 if (!(m->unit_path = split_path_and_make_absolute(e)))
204 if (strv_isempty(m->unit_path)) {
206 /* Nothing is set, so let's figure something out. */
207 strv_free(m->unit_path);
209 if (m->running_as == MANAGER_SESSION) {
210 if (!(m->unit_path = session_dirs()))
213 if (!(m->unit_path = strv_new(
214 SYSTEM_CONFIG_UNIT_PATH, /* /etc/systemd/system/ */
215 SYSTEM_DATA_UNIT_PATH, /* /lib/systemd/system/ */
220 if (m->running_as == MANAGER_INIT) {
221 /* /etc/init.d/ compativility does not matter to users */
223 if ((e = getenv("SYSTEMD_SYSVINIT_PATH")))
224 if (!(m->sysvinit_path = split_path_and_make_absolute(e)))
227 if (strv_isempty(m->sysvinit_path)) {
228 strv_free(m->sysvinit_path);
230 if (!(m->sysvinit_path = strv_new(
231 SYSTEM_SYSVINIT_PATH, /* /etc/init.d/ */
236 if ((e = getenv("SYSTEMD_SYSVRCND_PATH")))
237 if (!(m->sysvrcnd_path = split_path_and_make_absolute(e)))
240 if (strv_isempty(m->sysvrcnd_path)) {
241 strv_free(m->sysvrcnd_path);
243 if (!(m->sysvrcnd_path = strv_new(
244 SYSTEM_SYSVRCND_PATH, /* /etc/rcN.d/ */
250 strv_uniq(m->unit_path);
251 strv_uniq(m->sysvinit_path);
252 strv_uniq(m->sysvrcnd_path);
254 assert(!strv_isempty(m->unit_path));
255 if (!(t = strv_join(m->unit_path, "\n\t")))
257 log_debug("Looking for unit files in:\n\t%s", t);
260 if (!strv_isempty(m->sysvinit_path)) {
262 if (!(t = strv_join(m->sysvinit_path, "\n\t")))
265 log_debug("Looking for SysV init scripts in:\n\t%s", t);
268 log_debug("Ignoring SysV init scripts.");
270 if (!strv_isempty(m->sysvrcnd_path)) {
272 if (!(t = strv_join(m->sysvrcnd_path, "\n\t")))
275 log_debug("Looking for SysV rcN.d links in:\n\t%s", t);
278 log_debug("Ignoring SysV rcN.d links.");
283 int manager_new(ManagerRunningAs running_as, Manager **_m) {
288 assert(running_as >= 0);
289 assert(running_as < _MANAGER_RUNNING_AS_MAX);
291 if (!(m = new0(Manager, 1)))
294 m->boot_timestamp = now(CLOCK_REALTIME);
296 m->running_as = running_as;
297 m->signal_watch.fd = m->mount_watch.fd = m->udev_watch.fd = m->epoll_fd = -1;
298 m->current_job_id = 1; /* start as id #1, so that we can leave #0 around as "null-like" value */
300 if (!(m->units = hashmap_new(string_hash_func, string_compare_func)))
303 if (!(m->jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
306 if (!(m->transaction_jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
309 if (!(m->watch_pids = hashmap_new(trivial_hash_func, trivial_compare_func)))
312 if (!(m->cgroup_bondings = hashmap_new(string_hash_func, string_compare_func)))
315 if ((m->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0)
318 if ((r = manager_find_paths(m)) < 0)
321 if ((r = manager_setup_signals(m)) < 0)
324 if ((r = manager_setup_cgroup(m)) < 0)
327 /* Try to connect to the busses, if possible. */
328 if ((r = bus_init_system(m)) < 0 ||
329 (r = bus_init_api(m)) < 0)
340 static unsigned manager_dispatch_cleanup_queue(Manager *m) {
346 while ((meta = m->cleanup_queue)) {
347 assert(meta->in_cleanup_queue);
349 unit_free(UNIT(meta));
356 void manager_free(Manager *m) {
363 while ((j = hashmap_first(m->transaction_jobs)))
366 while ((u = hashmap_first(m->units)))
369 manager_dispatch_cleanup_queue(m);
371 for (c = 0; c < _UNIT_TYPE_MAX; c++)
372 if (unit_vtable[c]->shutdown)
373 unit_vtable[c]->shutdown(m);
375 manager_shutdown_cgroup(m);
380 hashmap_free(m->units);
381 hashmap_free(m->jobs);
382 hashmap_free(m->transaction_jobs);
383 hashmap_free(m->watch_pids);
385 if (m->epoll_fd >= 0)
386 close_nointr(m->epoll_fd);
387 if (m->signal_watch.fd >= 0)
388 close_nointr(m->signal_watch.fd);
390 strv_free(m->unit_path);
391 strv_free(m->sysvinit_path);
392 strv_free(m->sysvrcnd_path);
394 free(m->cgroup_controller);
395 free(m->cgroup_hierarchy);
397 assert(hashmap_isempty(m->cgroup_bondings));
398 hashmap_free(m->cgroup_bondings);
403 int manager_coldplug(Manager *m) {
412 /* First, let's ask every type to load all units from
413 * disk/kernel that it might know */
414 for (c = 0; c < _UNIT_TYPE_MAX; c++)
415 if (unit_vtable[c]->enumerate)
416 if ((r = unit_vtable[c]->enumerate(m)) < 0)
419 manager_dispatch_load_queue(m);
421 /* Then, let's set up their initial state. */
422 HASHMAP_FOREACH_KEY(u, k, m->units, i) {
428 if (UNIT_VTABLE(u)->coldplug)
429 if ((r = UNIT_VTABLE(u)->coldplug(u)) < 0)
433 /* Now that the initial devices are available, let's see if we
434 * can write the utmp file */
435 manager_write_utmp_reboot(m);
440 static void transaction_delete_job(Manager *m, Job *j, bool delete_dependencies) {
444 /* Deletes one job from the transaction */
446 manager_transaction_unlink_job(m, j, delete_dependencies);
452 static void transaction_delete_unit(Manager *m, Unit *u) {
455 /* Deletes all jobs associated with a certain unit from the
458 while ((j = hashmap_get(m->transaction_jobs, u)))
459 transaction_delete_job(m, j, true);
462 static void transaction_clean_dependencies(Manager *m) {
468 /* Drops all dependencies of all installed jobs */
470 HASHMAP_FOREACH(j, m->jobs, i) {
471 while (j->subject_list)
472 job_dependency_free(j->subject_list);
473 while (j->object_list)
474 job_dependency_free(j->object_list);
477 assert(!m->transaction_anchor);
480 static void transaction_abort(Manager *m) {
485 while ((j = hashmap_first(m->transaction_jobs)))
487 transaction_delete_job(m, j, true);
491 assert(hashmap_isempty(m->transaction_jobs));
493 transaction_clean_dependencies(m);
496 static void transaction_find_jobs_that_matter_to_anchor(Manager *m, Job *j, unsigned generation) {
501 /* A recursive sweep through the graph that marks all units
502 * that matter to the anchor job, i.e. are directly or
503 * indirectly a dependency of the anchor job via paths that
504 * are fully marked as mattering. */
509 l = m->transaction_anchor;
511 LIST_FOREACH(subject, l, l) {
513 /* This link does not matter */
517 /* This unit has already been marked */
518 if (l->object->generation == generation)
521 l->object->matters_to_anchor = true;
522 l->object->generation = generation;
524 transaction_find_jobs_that_matter_to_anchor(m, l->object, generation);
528 static void transaction_merge_and_delete_job(Manager *m, Job *j, Job *other, JobType t) {
529 JobDependency *l, *last;
533 assert(j->unit == other->unit);
534 assert(!j->installed);
536 /* Merges 'other' into 'j' and then deletes j. */
539 j->state = JOB_WAITING;
540 j->forced = j->forced || other->forced;
542 j->matters_to_anchor = j->matters_to_anchor || other->matters_to_anchor;
544 /* Patch us in as new owner of the JobDependency objects */
546 LIST_FOREACH(subject, l, other->subject_list) {
547 assert(l->subject == other);
552 /* Merge both lists */
554 last->subject_next = j->subject_list;
556 j->subject_list->subject_prev = last;
557 j->subject_list = other->subject_list;
560 /* Patch us in as new owner of the JobDependency objects */
562 LIST_FOREACH(object, l, other->object_list) {
563 assert(l->object == other);
568 /* Merge both lists */
570 last->object_next = j->object_list;
572 j->object_list->object_prev = last;
573 j->object_list = other->object_list;
576 /* Kill the other job */
577 other->subject_list = NULL;
578 other->object_list = NULL;
579 transaction_delete_job(m, other, true);
582 static int delete_one_unmergeable_job(Manager *m, Job *j) {
587 /* Tries to delete one item in the linked list
588 * j->transaction_next->transaction_next->... that conflicts
589 * whith another one, in an attempt to make an inconsistent
590 * transaction work. */
592 /* We rely here on the fact that if a merged with b does not
593 * merge with c, either a or b merge with c neither */
594 LIST_FOREACH(transaction, j, j)
595 LIST_FOREACH(transaction, k, j->transaction_next) {
598 /* Is this one mergeable? Then skip it */
599 if (job_type_is_mergeable(j->type, k->type))
602 /* Ok, we found two that conflict, let's see if we can
603 * drop one of them */
604 if (!j->matters_to_anchor)
606 else if (!k->matters_to_anchor)
611 /* Ok, we can drop one, so let's do so. */
612 log_debug("Trying to fix job merging by deleting job %s/%s", unit_id(d->unit), job_type_to_string(d->type));
613 transaction_delete_job(m, d, true);
620 static int transaction_merge_jobs(Manager *m) {
627 /* First step, check whether any of the jobs for one specific
628 * task conflict. If so, try to drop one of them. */
629 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
634 LIST_FOREACH(transaction, k, j->transaction_next) {
635 if ((r = job_type_merge(&t, k->type)) >= 0)
638 /* OK, we could not merge all jobs for this
639 * action. Let's see if we can get rid of one
642 if ((r = delete_one_unmergeable_job(m, j)) >= 0)
643 /* Ok, we managed to drop one, now
644 * let's ask our callers to call us
645 * again after garbage collecting */
648 /* We couldn't merge anything. Failure */
653 /* Second step, merge the jobs. */
654 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
658 /* Merge all transactions */
659 LIST_FOREACH(transaction, k, j->transaction_next)
660 assert_se(job_type_merge(&t, k->type) == 0);
662 /* If an active job is mergeable, merge it too */
663 if (j->unit->meta.job)
664 job_type_merge(&t, j->unit->meta.job->type); /* Might fail. Which is OK */
666 while ((k = j->transaction_next)) {
668 transaction_merge_and_delete_job(m, k, j, t);
671 transaction_merge_and_delete_job(m, j, k, t);
674 assert(!j->transaction_next);
675 assert(!j->transaction_prev);
681 static void transaction_drop_redundant(Manager *m) {
686 /* Goes through the transaction and removes all jobs that are
695 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
696 bool changes_something = false;
699 LIST_FOREACH(transaction, k, j) {
701 if (!job_is_anchor(k) &&
702 job_type_is_redundant(k->type, unit_active_state(k->unit)))
705 changes_something = true;
709 if (changes_something)
712 log_debug("Found redundant job %s/%s, dropping.", unit_id(j->unit), job_type_to_string(j->type));
713 transaction_delete_job(m, j, false);
721 static bool unit_matters_to_anchor(Unit *u, Job *j) {
723 assert(!j->transaction_prev);
725 /* Checks whether at least one of the jobs for this unit
726 * matters to the anchor. */
728 LIST_FOREACH(transaction, j, j)
729 if (j->matters_to_anchor)
735 static int transaction_verify_order_one(Manager *m, Job *j, Job *from, unsigned generation) {
742 assert(!j->transaction_prev);
744 /* Does a recursive sweep through the ordering graph, looking
745 * for a cycle. If we find cycle we try to break it. */
747 /* Did we find a cycle? */
748 if (j->marker && j->generation == generation) {
751 /* So, we already have been here. We have a
752 * cycle. Let's try to break it. We go backwards in
753 * our path and try to find a suitable job to
754 * remove. We use the marker to find our way back,
755 * since smart how we are we stored our way back in
758 log_debug("Found ordering cycle on %s/%s", unit_id(j->unit), job_type_to_string(j->type));
760 for (k = from; k; k = (k->generation == generation ? k->marker : NULL)) {
762 log_debug("Walked on cycle path to %s/%s", unit_id(k->unit), job_type_to_string(k->type));
765 !unit_matters_to_anchor(k->unit, k)) {
766 /* Ok, we can drop this one, so let's
768 log_debug("Breaking order cycle by deleting job %s/%s", unit_id(k->unit), job_type_to_string(k->type));
769 transaction_delete_unit(m, k->unit);
773 /* Check if this in fact was the beginning of
779 log_debug("Unable to break cycle");
784 /* Make the marker point to where we come from, so that we can
785 * find our way backwards if we want to break a cycle */
787 j->generation = generation;
789 /* We assume that the the dependencies are bidirectional, and
790 * hence can ignore UNIT_AFTER */
791 SET_FOREACH(u, j->unit->meta.dependencies[UNIT_BEFORE], i) {
794 /* Is there a job for this unit? */
795 if (!(o = hashmap_get(m->transaction_jobs, u)))
797 /* Ok, there is no job for this in the
798 * transaction, but maybe there is already one
800 if (!(o = u->meta.job))
803 if ((r = transaction_verify_order_one(m, o, j, generation)) < 0)
807 /* Ok, let's backtrack, and remember that this entry is not on
808 * our path anymore. */
814 static int transaction_verify_order(Manager *m, unsigned *generation) {
822 /* Check if the ordering graph is cyclic. If it is, try to fix
823 * that up by dropping one of the jobs. */
825 HASHMAP_FOREACH(j, m->transaction_jobs, i)
826 if ((r = transaction_verify_order_one(m, j, NULL, (*generation)++)) < 0)
832 static void transaction_collect_garbage(Manager *m) {
837 /* Drop jobs that are not required by any other job */
845 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
849 log_debug("Garbage collecting job %s/%s", unit_id(j->unit), job_type_to_string(j->type));
850 transaction_delete_job(m, j, true);
858 static int transaction_is_destructive(Manager *m, JobMode mode) {
864 /* Checks whether applying this transaction means that
865 * existing jobs would be replaced */
867 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
870 assert(!j->transaction_prev);
871 assert(!j->transaction_next);
873 if (j->unit->meta.job &&
874 j->unit->meta.job != j &&
875 !job_type_is_superset(j->type, j->unit->meta.job->type))
882 static void transaction_minimize_impact(Manager *m) {
886 /* Drops all unnecessary jobs that reverse already active jobs
887 * or that stop a running service. */
895 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
896 LIST_FOREACH(transaction, j, j) {
897 bool stops_running_service, changes_existing_job;
899 /* If it matters, we shouldn't drop it */
900 if (j->matters_to_anchor)
903 /* Would this stop a running service?
904 * Would this change an existing job?
905 * If so, let's drop this entry */
907 stops_running_service =
908 j->type == JOB_STOP && UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(j->unit));
910 changes_existing_job =
911 j->unit->meta.job && job_type_is_conflicting(j->type, j->unit->meta.job->state);
913 if (!stops_running_service && !changes_existing_job)
916 if (stops_running_service)
917 log_debug("%s/%s would stop a running service.", unit_id(j->unit), job_type_to_string(j->type));
919 if (changes_existing_job)
920 log_debug("%s/%s would change existing job.", unit_id(j->unit), job_type_to_string(j->type));
922 /* Ok, let's get rid of this */
923 log_debug("Deleting %s/%s to minimize impact.", unit_id(j->unit), job_type_to_string(j->type));
925 transaction_delete_job(m, j, true);
937 static int transaction_apply(Manager *m, JobMode mode) {
942 /* Moves the transaction jobs to the set of active jobs */
944 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
946 assert(!j->transaction_prev);
947 assert(!j->transaction_next);
952 if ((r = hashmap_put(m->jobs, UINT32_TO_PTR(j->id), j)) < 0)
956 while ((j = hashmap_steal_first(m->transaction_jobs))) {
960 if (j->unit->meta.job)
961 job_free(j->unit->meta.job);
963 j->unit->meta.job = j;
966 /* We're fully installed. Now let's free data we don't
969 assert(!j->transaction_next);
970 assert(!j->transaction_prev);
972 job_add_to_run_queue(j);
973 job_add_to_dbus_queue(j);
976 /* As last step, kill all remaining job dependencies. */
977 transaction_clean_dependencies(m);
983 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
987 hashmap_remove(m->jobs, UINT32_TO_PTR(j->id));
993 static int transaction_activate(Manager *m, JobMode mode) {
995 unsigned generation = 1;
999 /* This applies the changes recorded in transaction_jobs to
1000 * the actual list of jobs, if possible. */
1002 /* First step: figure out which jobs matter */
1003 transaction_find_jobs_that_matter_to_anchor(m, NULL, generation++);
1005 /* Second step: Try not to stop any running services if
1006 * we don't have to. Don't try to reverse running
1007 * jobs if we don't have to. */
1008 transaction_minimize_impact(m);
1010 /* Third step: Drop redundant jobs */
1011 transaction_drop_redundant(m);
1014 /* Fourth step: Let's remove unneeded jobs that might
1016 transaction_collect_garbage(m);
1018 /* Fifth step: verify order makes sense and correct
1019 * cycles if necessary and possible */
1020 if ((r = transaction_verify_order(m, &generation)) >= 0)
1024 log_debug("Requested transaction contains an unfixable cyclic ordering dependency: %s", strerror(-r));
1028 /* Let's see if the resulting transaction ordering
1029 * graph is still cyclic... */
1033 /* Sixth step: let's drop unmergeable entries if
1034 * necessary and possible, merge entries we can
1036 if ((r = transaction_merge_jobs(m)) >= 0)
1040 log_debug("Requested transaction contains unmergable jobs: %s", strerror(-r));
1044 /* Seventh step: an entry got dropped, let's garbage
1045 * collect its dependencies. */
1046 transaction_collect_garbage(m);
1048 /* Let's see if the resulting transaction still has
1049 * unmergeable entries ... */
1052 /* Eights step: Drop redundant jobs again, if the merging now allows us to drop more. */
1053 transaction_drop_redundant(m);
1055 /* Ninth step: check whether we can actually apply this */
1056 if (mode == JOB_FAIL)
1057 if ((r = transaction_is_destructive(m, mode)) < 0) {
1058 log_debug("Requested transaction contradicts existing jobs: %s", strerror(-r));
1062 /* Tenth step: apply changes */
1063 if ((r = transaction_apply(m, mode)) < 0) {
1064 log_debug("Failed to apply transaction: %s", strerror(-r));
1068 assert(hashmap_isempty(m->transaction_jobs));
1069 assert(!m->transaction_anchor);
1074 transaction_abort(m);
1078 static Job* transaction_add_one_job(Manager *m, JobType type, Unit *unit, bool force, bool *is_new) {
1085 /* Looks for an axisting prospective job and returns that. If
1086 * it doesn't exist it is created and added to the prospective
1089 f = hashmap_get(m->transaction_jobs, unit);
1091 LIST_FOREACH(transaction, j, f) {
1092 assert(j->unit == unit);
1094 if (j->type == type) {
1101 if (unit->meta.job && unit->meta.job->type == type)
1103 else if (!(j = job_new(m, type, unit)))
1108 j->matters_to_anchor = false;
1111 LIST_PREPEND(Job, transaction, f, j);
1113 if ((r = hashmap_replace(m->transaction_jobs, unit, f)) < 0) {
1121 log_debug("Added job %s/%s to transaction.", unit_id(unit), job_type_to_string(type));
1126 void manager_transaction_unlink_job(Manager *m, Job *j, bool delete_dependencies) {
1130 if (j->transaction_prev)
1131 j->transaction_prev->transaction_next = j->transaction_next;
1132 else if (j->transaction_next)
1133 hashmap_replace(m->transaction_jobs, j->unit, j->transaction_next);
1135 hashmap_remove_value(m->transaction_jobs, j->unit, j);
1137 if (j->transaction_next)
1138 j->transaction_next->transaction_prev = j->transaction_prev;
1140 j->transaction_prev = j->transaction_next = NULL;
1142 while (j->subject_list)
1143 job_dependency_free(j->subject_list);
1145 while (j->object_list) {
1146 Job *other = j->object_list->matters ? j->object_list->subject : NULL;
1148 job_dependency_free(j->object_list);
1150 if (other && delete_dependencies) {
1151 log_debug("Deleting job %s/%s as dependency of job %s/%s",
1152 unit_id(other->unit), job_type_to_string(other->type),
1153 unit_id(j->unit), job_type_to_string(j->type));
1154 transaction_delete_job(m, other, delete_dependencies);
1159 static int transaction_add_job_and_dependencies(Manager *m, JobType type, Unit *unit, Job *by, bool matters, bool force, Job **_ret) {
1167 assert(type < _JOB_TYPE_MAX);
1170 if (unit->meta.load_state != UNIT_LOADED)
1173 if (!unit_job_is_applicable(unit, type))
1176 /* First add the job. */
1177 if (!(ret = transaction_add_one_job(m, type, unit, force, &is_new)))
1180 /* Then, add a link to the job. */
1181 if (!job_dependency_new(by, ret, matters))
1185 /* Finally, recursively add in all dependencies. */
1186 if (type == JOB_START || type == JOB_RELOAD_OR_START) {
1187 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES], i)
1188 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, true, force, NULL)) < 0 && r != -EBADR)
1190 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_SOFT_REQUIRES], i)
1191 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, !force, force, NULL)) < 0 && r != -EBADR)
1193 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_WANTS], i)
1194 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, false, force, NULL)) < 0)
1195 log_warning("Cannot add dependency job for unit %s, ignoring: %s", unit_id(dep), strerror(-r));
1196 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE], i)
1197 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, true, force, NULL)) < 0 && r != -EBADR)
1199 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_SOFT_REQUISITE], i)
1200 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, !force, force, NULL)) < 0 && r != -EBADR)
1202 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_CONFLICTS], i)
1203 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, dep, ret, true, force, NULL)) < 0 && r != -EBADR)
1206 } else if (type == JOB_STOP || type == JOB_RESTART || type == JOB_TRY_RESTART) {
1208 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRED_BY], i)
1209 if ((r = transaction_add_job_and_dependencies(m, type, dep, ret, true, force, NULL)) < 0 && r != -EBADR)
1213 /* JOB_VERIFY_STARTED, JOB_RELOAD require no dependency handling */
1225 int manager_add_job(Manager *m, JobType type, Unit *unit, JobMode mode, bool force, Job **_ret) {
1230 assert(type < _JOB_TYPE_MAX);
1232 assert(mode < _JOB_MODE_MAX);
1234 log_debug("Trying to enqueue job %s/%s", unit_id(unit), job_type_to_string(type));
1236 if ((r = transaction_add_job_and_dependencies(m, type, unit, NULL, true, force, &ret)) < 0) {
1237 transaction_abort(m);
1241 if ((r = transaction_activate(m, mode)) < 0)
1244 log_debug("Enqueued job %s/%s as %u", unit_id(unit), job_type_to_string(type), (unsigned) ret->id);
1252 int manager_add_job_by_name(Manager *m, JobType type, const char *name, JobMode mode, bool force, Job **_ret) {
1257 assert(type < _JOB_TYPE_MAX);
1259 assert(mode < _JOB_MODE_MAX);
1261 if ((r = manager_load_unit(m, name, &unit)) < 0)
1264 return manager_add_job(m, type, unit, mode, force, _ret);
1267 Job *manager_get_job(Manager *m, uint32_t id) {
1270 return hashmap_get(m->jobs, UINT32_TO_PTR(id));
1273 Unit *manager_get_unit(Manager *m, const char *name) {
1277 return hashmap_get(m->units, name);
1280 unsigned manager_dispatch_load_queue(Manager *m) {
1286 /* Make sure we are not run recursively */
1287 if (m->dispatching_load_queue)
1290 m->dispatching_load_queue = true;
1292 /* Dispatches the load queue. Takes a unit from the queue and
1293 * tries to load its data until the queue is empty */
1295 while ((meta = m->load_queue)) {
1296 assert(meta->in_load_queue);
1298 unit_load(UNIT(meta));
1302 m->dispatching_load_queue = false;
1306 int manager_load_unit(Manager *m, const char *path, Unit **_ret) {
1315 /* This will load the service information files, but not actually
1316 * start any services or anything. */
1318 name = file_name_from_path(path);
1320 if ((ret = manager_get_unit(m, name))) {
1325 if (!(ret = unit_new(m)))
1328 if (is_path(path)) {
1329 if (!(ret->meta.fragment_path = strdup(path))) {
1335 if ((r = unit_add_name(ret, name)) < 0) {
1340 unit_add_to_load_queue(ret);
1341 unit_add_to_dbus_queue(ret);
1343 manager_dispatch_load_queue(m);
1345 *_ret = unit_follow_merge(ret);
1349 void manager_dump_jobs(Manager *s, FILE *f, const char *prefix) {
1356 HASHMAP_FOREACH(j, s->jobs, i)
1357 job_dump(j, f, prefix);
1360 void manager_dump_units(Manager *s, FILE *f, const char *prefix) {
1368 HASHMAP_FOREACH_KEY(u, t, s->units, i)
1369 if (unit_id(u) == t)
1370 unit_dump(u, f, prefix);
1373 void manager_clear_jobs(Manager *m) {
1378 transaction_abort(m);
1380 while ((j = hashmap_first(m->jobs)))
1384 unsigned manager_dispatch_run_queue(Manager *m) {
1388 if (m->dispatching_run_queue)
1391 m->dispatching_run_queue = true;
1393 while ((j = m->run_queue)) {
1394 assert(j->installed);
1395 assert(j->in_run_queue);
1397 job_run_and_invalidate(j);
1401 m->dispatching_run_queue = false;
1405 unsigned manager_dispatch_dbus_queue(Manager *m) {
1412 if (m->dispatching_dbus_queue)
1415 m->dispatching_dbus_queue = true;
1417 while ((meta = m->dbus_unit_queue)) {
1418 assert(meta->in_dbus_queue);
1420 bus_unit_send_change_signal(UNIT(meta));
1424 while ((j = m->dbus_job_queue)) {
1425 assert(j->in_dbus_queue);
1427 bus_job_send_change_signal(j);
1431 m->dispatching_dbus_queue = false;
1435 static int manager_dispatch_sigchld(Manager *m) {
1443 if (waitid(P_ALL, 0, &si, WEXITED|WNOHANG) < 0) {
1445 if (errno == ECHILD)
1454 if (si.si_code != CLD_EXITED && si.si_code != CLD_KILLED && si.si_code != CLD_DUMPED)
1457 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);
1459 if (!(u = hashmap_remove(m->watch_pids, UINT32_TO_PTR(si.si_pid))))
1462 log_debug("child %llu belongs to %s", (long long unsigned) si.si_pid, unit_id(u));
1464 UNIT_VTABLE(u)->sigchld_event(u, si.si_pid, si.si_code, si.si_status);
1470 static void manager_start_target(Manager *m, const char *name) {
1473 if ((r = manager_add_job_by_name(m, JOB_START, name, JOB_REPLACE, true, NULL)) < 0)
1474 log_error("Failed to enqueue %s job: %s", name, strerror(-r));
1477 static int manager_process_signal_fd(Manager *m, bool *quit) {
1479 struct signalfd_siginfo sfsi;
1480 bool sigchld = false;
1485 if ((n = read(m->signal_watch.fd, &sfsi, sizeof(sfsi))) != sizeof(sfsi)) {
1490 if (errno == EAGAIN)
1496 switch (sfsi.ssi_signo) {
1501 get_process_name(sfsi.ssi_pid, &name);
1502 log_debug("Got SIGCHLD for process %llu (%s)", (unsigned long long) sfsi.ssi_pid, strna(name));
1512 if (m->running_as == MANAGER_INIT) {
1513 manager_start_target(m, SPECIAL_CTRL_ALT_DEL_TARGET);
1522 if (m->running_as == MANAGER_INIT)
1523 manager_start_target(m, SPECIAL_KBREQUEST_TARGET);
1525 /* This is a nop on non-init */
1529 if (m->running_as == MANAGER_INIT)
1530 manager_start_target(m, SPECIAL_SIGPWR_TARGET);
1532 /* This is a nop on non-init */
1537 printf("→ By units:\n");
1538 manager_dump_units(m, stdout, "\t");
1540 printf("→ By jobs:\n");
1541 manager_dump_jobs(m, stdout, "\t");
1546 log_info("Got unhandled signal <%s>.", strsignal(sfsi.ssi_signo));
1551 return manager_dispatch_sigchld(m);
1556 static int process_event(Manager *m, struct epoll_event *ev, bool *quit) {
1563 assert(w = ev->data.ptr);
1569 /* An incoming signal? */
1570 if (ev->events != EPOLLIN)
1573 if ((r = manager_process_signal_fd(m, quit)) < 0)
1580 /* Some fd event, to be dispatched to the units */
1581 UNIT_VTABLE(w->data.unit)->fd_event(w->data.unit, w->fd, ev->events, w);
1588 /* Some timer event, to be dispatched to the units */
1589 if ((k = read(w->fd, &v, sizeof(v))) != sizeof(v)) {
1591 if (k < 0 && (errno == EINTR || errno == EAGAIN))
1594 return k < 0 ? -errno : -EIO;
1597 UNIT_VTABLE(w->data.unit)->timer_event(w->data.unit, v, w);
1602 /* Some mount table change, intended for the mount subsystem */
1603 mount_fd_event(m, ev->events);
1607 /* Some notification from udev, intended for the device subsystem */
1608 device_fd_event(m, ev->events);
1611 case WATCH_DBUS_WATCH:
1612 bus_watch_event(m, w, ev->events);
1615 case WATCH_DBUS_TIMEOUT:
1616 bus_timeout_event(m, w, ev->events);
1620 assert_not_reached("Unknown epoll event type.");
1626 int manager_loop(Manager *m) {
1630 RATELIMIT_DEFINE(rl, 1*USEC_PER_SEC, 1000);
1635 struct epoll_event event;
1638 if (!ratelimit_test(&rl)) {
1639 /* Yay, something is going seriously wrong, pause a little */
1640 log_warning("Looping too fast. Throttling execution a little.");
1644 if (manager_dispatch_cleanup_queue(m) > 0)
1647 if (manager_dispatch_load_queue(m) > 0)
1650 if (manager_dispatch_run_queue(m) > 0)
1653 if (bus_dispatch(m) > 0)
1656 if (manager_dispatch_dbus_queue(m) > 0)
1659 if ((n = epoll_wait(m->epoll_fd, &event, 1, -1)) < 0) {
1661 if (errno == -EINTR)
1669 if ((r = process_event(m, &event, &quit)) < 0)
1676 int manager_get_unit_from_dbus_path(Manager *m, const char *s, Unit **_u) {
1684 if (!startswith(s, "/org/freedesktop/systemd1/unit/"))
1687 if (!(n = bus_path_unescape(s+31)))
1690 u = manager_get_unit(m, n);
1701 int manager_get_job_from_dbus_path(Manager *m, const char *s, Job **_j) {
1710 if (!startswith(s, "/org/freedesktop/systemd1/job/"))
1713 if ((r = safe_atou(s + 30, &id)) < 0)
1716 if (!(j = manager_get_job(m, id)))
1724 static bool manager_utmp_good(Manager *m) {
1729 if ((r = mount_path_is_mounted(m, _PATH_UTMPX)) <= 0) {
1732 log_warning("Failed to determine whether " _PATH_UTMPX " is mounted: %s", strerror(-r));
1740 void manager_write_utmp_reboot(Manager *m) {
1745 if (m->utmp_reboot_written)
1748 if (m->running_as != MANAGER_INIT)
1751 if (!manager_utmp_good(m))
1754 if ((r = utmp_put_reboot(m->boot_timestamp)) < 0) {
1756 if (r != -ENOENT && r != -EROFS)
1757 log_warning("Failed to write utmp/wtmp: %s", strerror(-r));
1762 m->utmp_reboot_written = true;
1765 void manager_write_utmp_runlevel(Manager *m, Unit *u) {
1771 if (u->meta.type != UNIT_TARGET)
1774 if (m->running_as != MANAGER_INIT)
1777 if (!manager_utmp_good(m))
1780 if ((runlevel = target_get_runlevel(TARGET(u))) <= 0)
1783 if ((r = utmp_put_runlevel(0, runlevel, 0)) < 0) {
1785 if (r != -ENOENT && r != -EROFS)
1786 log_warning("Failed to write utmp/wtmp: %s", strerror(-r));
1790 static const char* const manager_running_as_table[_MANAGER_RUNNING_AS_MAX] = {
1791 [MANAGER_INIT] = "init",
1792 [MANAGER_SYSTEM] = "system",
1793 [MANAGER_SESSION] = "session"
1796 DEFINE_STRING_TABLE_LOOKUP(manager_running_as, ManagerRunningAs);