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>
38 #include <sys/types.h>
47 #include "ratelimit.h"
49 #include "mount-setup.h"
50 #include "utmp-wtmp.h"
51 #include "unit-name.h"
52 #include "dbus-unit.h"
55 /* As soon as 16 units are in our GC queue, make sure to run a gc sweep */
56 #define GC_QUEUE_ENTRIES_MAX 16
58 /* As soon as 5s passed since a unit was added to our GC queue, make sure to run a gc sweep */
59 #define GC_QUEUE_USEC_MAX (5*USEC_PER_SEC)
61 static int enable_special_signals(Manager *m) {
66 /* Enable that we get SIGINT on control-alt-del */
67 if (reboot(RB_DISABLE_CAD) < 0)
68 log_warning("Failed to enable ctrl-alt-del handling: %m");
70 if ((fd = open_terminal("/dev/tty0", O_RDWR)) < 0)
71 log_warning("Failed to open /dev/tty0: %m");
73 /* Enable that we get SIGWINCH on kbrequest */
74 if (ioctl(fd, KDSIGACCEPT, SIGWINCH) < 0)
75 log_warning("Failed to enable kbrequest handling: %s", strerror(errno));
77 close_nointr_nofail(fd);
83 static int manager_setup_signals(Manager *m) {
85 struct epoll_event ev;
90 /* We are not interested in SIGSTOP and friends. */
92 sa.sa_handler = SIG_DFL;
93 sa.sa_flags = SA_NOCLDSTOP|SA_RESTART;
94 assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);
96 assert_se(sigemptyset(&mask) == 0);
97 assert_se(sigaddset(&mask, SIGCHLD) == 0);
98 assert_se(sigaddset(&mask, SIGTERM) == 0);
99 assert_se(sigaddset(&mask, SIGHUP) == 0);
100 assert_se(sigaddset(&mask, SIGUSR1) == 0);
101 assert_se(sigaddset(&mask, SIGUSR2) == 0);
102 assert_se(sigaddset(&mask, SIGINT) == 0); /* Kernel sends us this on control-alt-del */
103 assert_se(sigaddset(&mask, SIGWINCH) == 0); /* Kernel sends us this on kbrequest (alt-arrowup) */
104 assert_se(sigaddset(&mask, SIGPWR) == 0); /* Some kernel drivers and upsd send us this on power failure */
105 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
107 m->signal_watch.type = WATCH_SIGNAL;
108 if ((m->signal_watch.fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0)
113 ev.data.ptr = &m->signal_watch;
115 if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->signal_watch.fd, &ev) < 0)
118 if (m->running_as == MANAGER_INIT)
119 return enable_special_signals(m);
124 static char** session_dirs(void) {
125 const char *home, *e;
126 char *config_home = NULL, *data_home = NULL;
127 char **config_dirs = NULL, **data_dirs = NULL;
128 char **r = NULL, **t;
130 /* Implement the mechanisms defined in
132 * http://standards.freedesktop.org/basedir-spec/basedir-spec-0.6.html
134 * We look in both the config and the data dirs because we
135 * want to encourage that distributors ship their unit files
136 * as data, and allow overriding as configuration.
139 home = getenv("HOME");
141 if ((e = getenv("XDG_CONFIG_HOME"))) {
142 if (asprintf(&config_home, "%s/systemd/session", e) < 0)
146 if (asprintf(&config_home, "%s/.config/systemd/session", home) < 0)
150 if ((e = getenv("XDG_CONFIG_DIRS")))
151 config_dirs = strv_split(e, ":");
153 config_dirs = strv_new("/etc/xdg", NULL);
158 if ((e = getenv("XDG_DATA_HOME"))) {
159 if (asprintf(&data_home, "%s/systemd/session", e) < 0)
163 if (asprintf(&data_home, "%s/.local/share/systemd/session", home) < 0)
167 if ((e = getenv("XDG_DATA_DIRS")))
168 data_dirs = strv_split(e, ":");
170 data_dirs = strv_new("/usr/local/share", "/usr/share", NULL);
175 /* Now merge everything we found. */
177 if (!(t = strv_append(r, config_home)))
183 if (!(t = strv_merge_concat(r, config_dirs, "/systemd/session")))
188 if (!(t = strv_append(r, SESSION_CONFIG_UNIT_PATH)))
194 if (!(t = strv_append(r, data_home)))
200 if (!(t = strv_merge_concat(r, data_dirs, "/systemd/session")))
205 if (!(t = strv_append(r, SESSION_DATA_UNIT_PATH)))
210 if (!strv_path_make_absolute_cwd(r))
215 strv_free(config_dirs);
217 strv_free(data_dirs);
227 static int manager_find_paths(Manager *m) {
233 /* First priority is whatever has been passed to us via env
235 if ((e = getenv("SYSTEMD_UNIT_PATH")))
236 if (!(m->unit_path = split_path_and_make_absolute(e)))
239 if (strv_isempty(m->unit_path)) {
241 /* Nothing is set, so let's figure something out. */
242 strv_free(m->unit_path);
244 if (m->running_as == MANAGER_SESSION) {
245 if (!(m->unit_path = session_dirs()))
248 if (!(m->unit_path = strv_new(
249 SYSTEM_CONFIG_UNIT_PATH, /* /etc/systemd/system/ */
250 SYSTEM_DATA_UNIT_PATH, /* /lib/systemd/system/ */
255 if (m->running_as == MANAGER_INIT) {
256 /* /etc/init.d/ compativility does not matter to users */
258 if ((e = getenv("SYSTEMD_SYSVINIT_PATH")))
259 if (!(m->sysvinit_path = split_path_and_make_absolute(e)))
262 if (strv_isempty(m->sysvinit_path)) {
263 strv_free(m->sysvinit_path);
265 if (!(m->sysvinit_path = strv_new(
266 SYSTEM_SYSVINIT_PATH, /* /etc/init.d/ */
271 if ((e = getenv("SYSTEMD_SYSVRCND_PATH")))
272 if (!(m->sysvrcnd_path = split_path_and_make_absolute(e)))
275 if (strv_isempty(m->sysvrcnd_path)) {
276 strv_free(m->sysvrcnd_path);
278 if (!(m->sysvrcnd_path = strv_new(
279 SYSTEM_SYSVRCND_PATH, /* /etc/rcN.d/ */
285 strv_uniq(m->unit_path);
286 strv_uniq(m->sysvinit_path);
287 strv_uniq(m->sysvrcnd_path);
289 assert(!strv_isempty(m->unit_path));
290 if (!(t = strv_join(m->unit_path, "\n\t")))
292 log_debug("Looking for unit files in:\n\t%s", t);
295 if (!strv_isempty(m->sysvinit_path)) {
297 if (!(t = strv_join(m->sysvinit_path, "\n\t")))
300 log_debug("Looking for SysV init scripts in:\n\t%s", t);
303 log_debug("Ignoring SysV init scripts.");
305 if (!strv_isempty(m->sysvrcnd_path)) {
307 if (!(t = strv_join(m->sysvrcnd_path, "\n\t")))
310 log_debug("Looking for SysV rcN.d links in:\n\t%s", t);
313 log_debug("Ignoring SysV rcN.d links.");
318 int manager_new(ManagerRunningAs running_as, bool confirm_spawn, Manager **_m) {
323 assert(running_as >= 0);
324 assert(running_as < _MANAGER_RUNNING_AS_MAX);
326 if (!(m = new0(Manager, 1)))
329 m->boot_timestamp = now(CLOCK_REALTIME);
331 m->running_as = running_as;
332 m->confirm_spawn = confirm_spawn;
333 m->name_data_slot = -1;
334 m->exit_code = _MANAGER_EXIT_CODE_INVALID;
336 m->signal_watch.fd = m->mount_watch.fd = m->udev_watch.fd = m->epoll_fd = m->dev_autofs_fd = -1;
337 m->current_job_id = 1; /* start as id #1, so that we can leave #0 around as "null-like" value */
339 if (!(m->units = hashmap_new(string_hash_func, string_compare_func)))
342 if (!(m->jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
345 if (!(m->transaction_jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
348 if (!(m->watch_pids = hashmap_new(trivial_hash_func, trivial_compare_func)))
351 if (!(m->cgroup_bondings = hashmap_new(string_hash_func, string_compare_func)))
354 if (!(m->watch_bus = hashmap_new(string_hash_func, string_compare_func)))
357 if ((m->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0)
360 if ((r = manager_find_paths(m)) < 0)
363 if ((r = manager_setup_signals(m)) < 0)
366 if ((r = manager_setup_cgroup(m)) < 0)
369 /* Try to connect to the busses, if possible. */
370 if ((r = bus_init_system(m)) < 0 ||
371 (r = bus_init_api(m)) < 0)
382 static unsigned manager_dispatch_cleanup_queue(Manager *m) {
388 while ((meta = m->cleanup_queue)) {
389 assert(meta->in_cleanup_queue);
391 unit_free(UNIT(meta));
398 static void unit_gc_sweep(Unit *u, int gc_marker) {
404 if (u->meta.gc_marker == gc_marker ||
405 u->meta.gc_marker == -gc_marker)
408 if (u->meta.in_cleanup_queue)
411 if (unit_check_gc(u))
414 SET_FOREACH(other, u->meta.dependencies[UNIT_REFERENCED_BY], i) {
415 unit_gc_sweep(other, gc_marker);
417 if (other->meta.gc_marker == gc_marker)
422 /* So there is no reason to keep this unit around, hence let's get rid of it */
423 u->meta.gc_marker = -gc_marker;
427 u->meta.gc_marker = gc_marker;
430 static unsigned manager_dispatch_gc_queue(Manager *m) {
437 if ((m->n_in_gc_queue < GC_QUEUE_ENTRIES_MAX) &&
438 (m->gc_queue_timestamp <= 0 ||
439 (m->gc_queue_timestamp + GC_QUEUE_USEC_MAX) > now(CLOCK_MONOTONIC)))
442 log_debug("Running GC...");
444 gc_marker = ++m->gc_marker;
446 if (m->gc_marker < 0)
449 while ((meta = m->gc_queue)) {
450 assert(meta->in_gc_queue);
452 LIST_REMOVE(Meta, gc_queue, m->gc_queue, meta);
453 meta->in_gc_queue = false;
457 unit_gc_sweep(UNIT(meta), gc_marker);
459 if (meta->gc_marker == -gc_marker) {
460 log_debug("Collecting %s", meta->id);
461 unit_add_to_cleanup_queue(UNIT(meta));
465 m->n_in_gc_queue = 0;
466 m->gc_queue_timestamp = 0;
471 static void manager_clear_jobs_and_units(Manager *m) {
477 while ((j = hashmap_first(m->transaction_jobs)))
480 while ((u = hashmap_first(m->units)))
484 void manager_free(Manager *m) {
489 manager_clear_jobs_and_units(m);
491 for (c = 0; c < _UNIT_TYPE_MAX; c++)
492 if (unit_vtable[c]->shutdown)
493 unit_vtable[c]->shutdown(m);
495 /* If we reexecute ourselves, we keep the root cgroup
497 manager_shutdown_cgroup(m, m->exit_code != MANAGER_REEXECUTE);
502 hashmap_free(m->units);
503 hashmap_free(m->jobs);
504 hashmap_free(m->transaction_jobs);
505 hashmap_free(m->watch_pids);
506 hashmap_free(m->watch_bus);
508 if (m->epoll_fd >= 0)
509 close_nointr_nofail(m->epoll_fd);
510 if (m->signal_watch.fd >= 0)
511 close_nointr_nofail(m->signal_watch.fd);
513 strv_free(m->unit_path);
514 strv_free(m->sysvinit_path);
515 strv_free(m->sysvrcnd_path);
517 free(m->cgroup_controller);
518 free(m->cgroup_hierarchy);
520 hashmap_free(m->cgroup_bondings);
525 int manager_enumerate(Manager *m) {
531 /* Let's ask every type to load all units from disk/kernel
532 * that it might know */
533 for (c = 0; c < _UNIT_TYPE_MAX; c++)
534 if (unit_vtable[c]->enumerate)
535 if ((q = unit_vtable[c]->enumerate(m)) < 0)
538 manager_dispatch_load_queue(m);
542 int manager_coldplug(Manager *m) {
550 /* Then, let's set up their initial state. */
551 HASHMAP_FOREACH_KEY(u, k, m->units, i) {
557 if (UNIT_VTABLE(u)->coldplug)
558 if ((q = UNIT_VTABLE(u)->coldplug(u)) < 0)
565 int manager_startup(Manager *m, FILE *serialization, FDSet *fds) {
570 /* First, enumerate what we can from all config files */
571 r = manager_enumerate(m);
573 /* Second, deserialize if there is something to deserialize */
575 if ((q = manager_deserialize(m, serialization, fds)) < 0)
578 /* Third, fire things up! */
579 if ((q = manager_coldplug(m)) < 0)
582 /* Now that the initial devices are available, let's see if we
583 * can write the utmp file */
584 manager_write_utmp_reboot(m);
589 static void transaction_delete_job(Manager *m, Job *j, bool delete_dependencies) {
593 /* Deletes one job from the transaction */
595 manager_transaction_unlink_job(m, j, delete_dependencies);
601 static void transaction_delete_unit(Manager *m, Unit *u) {
604 /* Deletes all jobs associated with a certain unit from the
607 while ((j = hashmap_get(m->transaction_jobs, u)))
608 transaction_delete_job(m, j, true);
611 static void transaction_clean_dependencies(Manager *m) {
617 /* Drops all dependencies of all installed jobs */
619 HASHMAP_FOREACH(j, m->jobs, i) {
620 while (j->subject_list)
621 job_dependency_free(j->subject_list);
622 while (j->object_list)
623 job_dependency_free(j->object_list);
626 assert(!m->transaction_anchor);
629 static void transaction_abort(Manager *m) {
634 while ((j = hashmap_first(m->transaction_jobs)))
636 transaction_delete_job(m, j, true);
640 assert(hashmap_isempty(m->transaction_jobs));
642 transaction_clean_dependencies(m);
645 static void transaction_find_jobs_that_matter_to_anchor(Manager *m, Job *j, unsigned generation) {
650 /* A recursive sweep through the graph that marks all units
651 * that matter to the anchor job, i.e. are directly or
652 * indirectly a dependency of the anchor job via paths that
653 * are fully marked as mattering. */
658 l = m->transaction_anchor;
660 LIST_FOREACH(subject, l, l) {
662 /* This link does not matter */
666 /* This unit has already been marked */
667 if (l->object->generation == generation)
670 l->object->matters_to_anchor = true;
671 l->object->generation = generation;
673 transaction_find_jobs_that_matter_to_anchor(m, l->object, generation);
677 static void transaction_merge_and_delete_job(Manager *m, Job *j, Job *other, JobType t) {
678 JobDependency *l, *last;
682 assert(j->unit == other->unit);
683 assert(!j->installed);
685 /* Merges 'other' into 'j' and then deletes j. */
688 j->state = JOB_WAITING;
689 j->override = j->override || other->override;
691 j->matters_to_anchor = j->matters_to_anchor || other->matters_to_anchor;
693 /* Patch us in as new owner of the JobDependency objects */
695 LIST_FOREACH(subject, l, other->subject_list) {
696 assert(l->subject == other);
701 /* Merge both lists */
703 last->subject_next = j->subject_list;
705 j->subject_list->subject_prev = last;
706 j->subject_list = other->subject_list;
709 /* Patch us in as new owner of the JobDependency objects */
711 LIST_FOREACH(object, l, other->object_list) {
712 assert(l->object == other);
717 /* Merge both lists */
719 last->object_next = j->object_list;
721 j->object_list->object_prev = last;
722 j->object_list = other->object_list;
725 /* Kill the other job */
726 other->subject_list = NULL;
727 other->object_list = NULL;
728 transaction_delete_job(m, other, true);
731 static int delete_one_unmergeable_job(Manager *m, Job *j) {
736 /* Tries to delete one item in the linked list
737 * j->transaction_next->transaction_next->... that conflicts
738 * whith another one, in an attempt to make an inconsistent
739 * transaction work. */
741 /* We rely here on the fact that if a merged with b does not
742 * merge with c, either a or b merge with c neither */
743 LIST_FOREACH(transaction, j, j)
744 LIST_FOREACH(transaction, k, j->transaction_next) {
747 /* Is this one mergeable? Then skip it */
748 if (job_type_is_mergeable(j->type, k->type))
751 /* Ok, we found two that conflict, let's see if we can
752 * drop one of them */
753 if (!j->matters_to_anchor)
755 else if (!k->matters_to_anchor)
760 /* Ok, we can drop one, so let's do so. */
761 log_debug("Trying to fix job merging by deleting job %s/%s", d->unit->meta.id, job_type_to_string(d->type));
762 transaction_delete_job(m, d, true);
769 static int transaction_merge_jobs(Manager *m) {
776 /* First step, check whether any of the jobs for one specific
777 * task conflict. If so, try to drop one of them. */
778 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
783 LIST_FOREACH(transaction, k, j->transaction_next) {
784 if ((r = job_type_merge(&t, k->type)) >= 0)
787 /* OK, we could not merge all jobs for this
788 * action. Let's see if we can get rid of one
791 if ((r = delete_one_unmergeable_job(m, j)) >= 0)
792 /* Ok, we managed to drop one, now
793 * let's ask our callers to call us
794 * again after garbage collecting */
797 /* We couldn't merge anything. Failure */
802 /* Second step, merge the jobs. */
803 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
807 /* Merge all transactions */
808 LIST_FOREACH(transaction, k, j->transaction_next)
809 assert_se(job_type_merge(&t, k->type) == 0);
811 /* If an active job is mergeable, merge it too */
812 if (j->unit->meta.job)
813 job_type_merge(&t, j->unit->meta.job->type); /* Might fail. Which is OK */
815 while ((k = j->transaction_next)) {
817 transaction_merge_and_delete_job(m, k, j, t);
820 transaction_merge_and_delete_job(m, j, k, t);
823 assert(!j->transaction_next);
824 assert(!j->transaction_prev);
830 static void transaction_drop_redundant(Manager *m) {
835 /* Goes through the transaction and removes all jobs that are
844 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
845 bool changes_something = false;
848 LIST_FOREACH(transaction, k, j) {
850 if (!job_is_anchor(k) &&
851 job_type_is_redundant(k->type, unit_active_state(k->unit)))
854 changes_something = true;
858 if (changes_something)
861 log_debug("Found redundant job %s/%s, dropping.", j->unit->meta.id, job_type_to_string(j->type));
862 transaction_delete_job(m, j, false);
870 static bool unit_matters_to_anchor(Unit *u, Job *j) {
872 assert(!j->transaction_prev);
874 /* Checks whether at least one of the jobs for this unit
875 * matters to the anchor. */
877 LIST_FOREACH(transaction, j, j)
878 if (j->matters_to_anchor)
884 static int transaction_verify_order_one(Manager *m, Job *j, Job *from, unsigned generation) {
891 assert(!j->transaction_prev);
893 /* Does a recursive sweep through the ordering graph, looking
894 * for a cycle. If we find cycle we try to break it. */
896 /* Did we find a cycle? */
897 if (j->marker && j->generation == generation) {
900 /* So, we already have been here. We have a
901 * cycle. Let's try to break it. We go backwards in
902 * our path and try to find a suitable job to
903 * remove. We use the marker to find our way back,
904 * since smart how we are we stored our way back in
907 log_debug("Found ordering cycle on %s/%s", j->unit->meta.id, job_type_to_string(j->type));
909 for (k = from; k; k = (k->generation == generation ? k->marker : NULL)) {
911 log_debug("Walked on cycle path to %s/%s", k->unit->meta.id, job_type_to_string(k->type));
914 !unit_matters_to_anchor(k->unit, k)) {
915 /* Ok, we can drop this one, so let's
917 log_debug("Breaking order cycle by deleting job %s/%s", k->unit->meta.id, job_type_to_string(k->type));
918 transaction_delete_unit(m, k->unit);
922 /* Check if this in fact was the beginning of
928 log_debug("Unable to break cycle");
933 /* Make the marker point to where we come from, so that we can
934 * find our way backwards if we want to break a cycle */
936 j->generation = generation;
938 /* We assume that the the dependencies are bidirectional, and
939 * hence can ignore UNIT_AFTER */
940 SET_FOREACH(u, j->unit->meta.dependencies[UNIT_BEFORE], i) {
943 /* Is there a job for this unit? */
944 if (!(o = hashmap_get(m->transaction_jobs, u)))
946 /* Ok, there is no job for this in the
947 * transaction, but maybe there is already one
949 if (!(o = u->meta.job))
952 if ((r = transaction_verify_order_one(m, o, j, generation)) < 0)
956 /* Ok, let's backtrack, and remember that this entry is not on
957 * our path anymore. */
963 static int transaction_verify_order(Manager *m, unsigned *generation) {
971 /* Check if the ordering graph is cyclic. If it is, try to fix
972 * that up by dropping one of the jobs. */
974 HASHMAP_FOREACH(j, m->transaction_jobs, i)
975 if ((r = transaction_verify_order_one(m, j, NULL, (*generation)++)) < 0)
981 static void transaction_collect_garbage(Manager *m) {
986 /* Drop jobs that are not required by any other job */
994 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
998 log_debug("Garbage collecting job %s/%s", j->unit->meta.id, job_type_to_string(j->type));
999 transaction_delete_job(m, j, true);
1007 static int transaction_is_destructive(Manager *m) {
1013 /* Checks whether applying this transaction means that
1014 * existing jobs would be replaced */
1016 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1019 assert(!j->transaction_prev);
1020 assert(!j->transaction_next);
1022 if (j->unit->meta.job &&
1023 j->unit->meta.job != j &&
1024 !job_type_is_superset(j->type, j->unit->meta.job->type))
1031 static void transaction_minimize_impact(Manager *m) {
1035 /* Drops all unnecessary jobs that reverse already active jobs
1036 * or that stop a running service. */
1044 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1045 LIST_FOREACH(transaction, j, j) {
1046 bool stops_running_service, changes_existing_job;
1048 /* If it matters, we shouldn't drop it */
1049 if (j->matters_to_anchor)
1052 /* Would this stop a running service?
1053 * Would this change an existing job?
1054 * If so, let's drop this entry */
1056 stops_running_service =
1057 j->type == JOB_STOP && UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(j->unit));
1059 changes_existing_job =
1060 j->unit->meta.job && job_type_is_conflicting(j->type, j->unit->meta.job->state);
1062 if (!stops_running_service && !changes_existing_job)
1065 if (stops_running_service)
1066 log_debug("%s/%s would stop a running service.", j->unit->meta.id, job_type_to_string(j->type));
1068 if (changes_existing_job)
1069 log_debug("%s/%s would change existing job.", j->unit->meta.id, job_type_to_string(j->type));
1071 /* Ok, let's get rid of this */
1072 log_debug("Deleting %s/%s to minimize impact.", j->unit->meta.id, job_type_to_string(j->type));
1074 transaction_delete_job(m, j, true);
1086 static int transaction_apply(Manager *m) {
1091 /* Moves the transaction jobs to the set of active jobs */
1093 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1095 assert(!j->transaction_prev);
1096 assert(!j->transaction_next);
1101 if ((r = hashmap_put(m->jobs, UINT32_TO_PTR(j->id), j)) < 0)
1105 while ((j = hashmap_steal_first(m->transaction_jobs))) {
1109 if (j->unit->meta.job)
1110 job_free(j->unit->meta.job);
1112 j->unit->meta.job = j;
1113 j->installed = true;
1115 /* We're fully installed. Now let's free data we don't
1118 assert(!j->transaction_next);
1119 assert(!j->transaction_prev);
1121 job_add_to_run_queue(j);
1122 job_add_to_dbus_queue(j);
1125 /* As last step, kill all remaining job dependencies. */
1126 transaction_clean_dependencies(m);
1132 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1136 hashmap_remove(m->jobs, UINT32_TO_PTR(j->id));
1142 static int transaction_activate(Manager *m, JobMode mode) {
1144 unsigned generation = 1;
1148 /* This applies the changes recorded in transaction_jobs to
1149 * the actual list of jobs, if possible. */
1151 /* First step: figure out which jobs matter */
1152 transaction_find_jobs_that_matter_to_anchor(m, NULL, generation++);
1154 /* Second step: Try not to stop any running services if
1155 * we don't have to. Don't try to reverse running
1156 * jobs if we don't have to. */
1157 transaction_minimize_impact(m);
1159 /* Third step: Drop redundant jobs */
1160 transaction_drop_redundant(m);
1163 /* Fourth step: Let's remove unneeded jobs that might
1165 transaction_collect_garbage(m);
1167 /* Fifth step: verify order makes sense and correct
1168 * cycles if necessary and possible */
1169 if ((r = transaction_verify_order(m, &generation)) >= 0)
1173 log_debug("Requested transaction contains an unfixable cyclic ordering dependency: %s", strerror(-r));
1177 /* Let's see if the resulting transaction ordering
1178 * graph is still cyclic... */
1182 /* Sixth step: let's drop unmergeable entries if
1183 * necessary and possible, merge entries we can
1185 if ((r = transaction_merge_jobs(m)) >= 0)
1189 log_debug("Requested transaction contains unmergable jobs: %s", strerror(-r));
1193 /* Seventh step: an entry got dropped, let's garbage
1194 * collect its dependencies. */
1195 transaction_collect_garbage(m);
1197 /* Let's see if the resulting transaction still has
1198 * unmergeable entries ... */
1201 /* Eights step: Drop redundant jobs again, if the merging now allows us to drop more. */
1202 transaction_drop_redundant(m);
1204 /* Ninth step: check whether we can actually apply this */
1205 if (mode == JOB_FAIL)
1206 if ((r = transaction_is_destructive(m)) < 0) {
1207 log_debug("Requested transaction contradicts existing jobs: %s", strerror(-r));
1211 /* Tenth step: apply changes */
1212 if ((r = transaction_apply(m)) < 0) {
1213 log_debug("Failed to apply transaction: %s", strerror(-r));
1217 assert(hashmap_isempty(m->transaction_jobs));
1218 assert(!m->transaction_anchor);
1223 transaction_abort(m);
1227 static Job* transaction_add_one_job(Manager *m, JobType type, Unit *unit, bool override, bool *is_new) {
1234 /* Looks for an axisting prospective job and returns that. If
1235 * it doesn't exist it is created and added to the prospective
1238 f = hashmap_get(m->transaction_jobs, unit);
1240 LIST_FOREACH(transaction, j, f) {
1241 assert(j->unit == unit);
1243 if (j->type == type) {
1250 if (unit->meta.job && unit->meta.job->type == type)
1252 else if (!(j = job_new(m, type, unit)))
1257 j->matters_to_anchor = false;
1258 j->override = override;
1260 LIST_PREPEND(Job, transaction, f, j);
1262 if ((r = hashmap_replace(m->transaction_jobs, unit, f)) < 0) {
1270 log_debug("Added job %s/%s to transaction.", unit->meta.id, job_type_to_string(type));
1275 void manager_transaction_unlink_job(Manager *m, Job *j, bool delete_dependencies) {
1279 if (j->transaction_prev)
1280 j->transaction_prev->transaction_next = j->transaction_next;
1281 else if (j->transaction_next)
1282 hashmap_replace(m->transaction_jobs, j->unit, j->transaction_next);
1284 hashmap_remove_value(m->transaction_jobs, j->unit, j);
1286 if (j->transaction_next)
1287 j->transaction_next->transaction_prev = j->transaction_prev;
1289 j->transaction_prev = j->transaction_next = NULL;
1291 while (j->subject_list)
1292 job_dependency_free(j->subject_list);
1294 while (j->object_list) {
1295 Job *other = j->object_list->matters ? j->object_list->subject : NULL;
1297 job_dependency_free(j->object_list);
1299 if (other && delete_dependencies) {
1300 log_debug("Deleting job %s/%s as dependency of job %s/%s",
1301 other->unit->meta.id, job_type_to_string(other->type),
1302 j->unit->meta.id, job_type_to_string(j->type));
1303 transaction_delete_job(m, other, delete_dependencies);
1308 static int transaction_add_job_and_dependencies(
1323 assert(type < _JOB_TYPE_MAX);
1326 if (unit->meta.load_state != UNIT_LOADED)
1329 if (!unit_job_is_applicable(unit, type))
1332 /* First add the job. */
1333 if (!(ret = transaction_add_one_job(m, type, unit, override, &is_new)))
1336 /* Then, add a link to the job. */
1337 if (!job_dependency_new(by, ret, matters))
1341 /* Finally, recursively add in all dependencies. */
1342 if (type == JOB_START || type == JOB_RELOAD_OR_START) {
1343 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES], i)
1344 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, true, override, NULL)) < 0 && r != -EBADR)
1347 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES_OVERRIDABLE], i)
1348 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, !override, override, NULL)) < 0 && r != -EBADR)
1349 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, strerror(-r));
1351 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_WANTS], i)
1352 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, false, false, NULL)) < 0)
1353 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, strerror(-r));
1355 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE], i)
1356 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, true, override, NULL)) < 0 && r != -EBADR)
1359 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE_OVERRIDABLE], i)
1360 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, !override, override, NULL)) < 0 && r != -EBADR)
1361 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, strerror(-r));
1363 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_CONFLICTS], i)
1364 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, dep, ret, true, override, NULL)) < 0 && r != -EBADR)
1367 } else if (type == JOB_STOP || type == JOB_RESTART || type == JOB_TRY_RESTART) {
1369 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRED_BY], i)
1370 if ((r = transaction_add_job_and_dependencies(m, type, dep, ret, true, override, NULL)) < 0 && r != -EBADR)
1374 /* JOB_VERIFY_STARTED, JOB_RELOAD require no dependency handling */
1386 static int transaction_add_isolate_jobs(Manager *m) {
1394 HASHMAP_FOREACH_KEY(u, k, m->units, i) {
1396 /* ignore aliases */
1397 if (u->meta.id != k)
1400 if (UNIT_VTABLE(u)->no_isolate)
1403 /* No need to stop inactive jobs */
1404 if (unit_active_state(u) == UNIT_INACTIVE)
1407 /* Is there already something listed for this? */
1408 if (hashmap_get(m->transaction_jobs, u))
1411 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, u, NULL, true, false, NULL)) < 0)
1412 log_warning("Cannot add isolate job for unit %s, ignoring: %s", u->meta.id, strerror(-r));
1418 int manager_add_job(Manager *m, JobType type, Unit *unit, JobMode mode, bool override, Job **_ret) {
1423 assert(type < _JOB_TYPE_MAX);
1425 assert(mode < _JOB_MODE_MAX);
1427 if (mode == JOB_ISOLATE && type != JOB_START)
1430 log_debug("Trying to enqueue job %s/%s", unit->meta.id, job_type_to_string(type));
1432 if ((r = transaction_add_job_and_dependencies(m, type, unit, NULL, true, override, &ret)) < 0) {
1433 transaction_abort(m);
1437 if (mode == JOB_ISOLATE)
1438 if ((r = transaction_add_isolate_jobs(m)) < 0) {
1439 transaction_abort(m);
1443 if ((r = transaction_activate(m, mode)) < 0)
1446 log_debug("Enqueued job %s/%s as %u", unit->meta.id, job_type_to_string(type), (unsigned) ret->id);
1454 int manager_add_job_by_name(Manager *m, JobType type, const char *name, JobMode mode, bool override, Job **_ret) {
1459 assert(type < _JOB_TYPE_MAX);
1461 assert(mode < _JOB_MODE_MAX);
1463 if ((r = manager_load_unit(m, name, NULL, &unit)) < 0)
1466 return manager_add_job(m, type, unit, mode, override, _ret);
1469 Job *manager_get_job(Manager *m, uint32_t id) {
1472 return hashmap_get(m->jobs, UINT32_TO_PTR(id));
1475 Unit *manager_get_unit(Manager *m, const char *name) {
1479 return hashmap_get(m->units, name);
1482 unsigned manager_dispatch_load_queue(Manager *m) {
1488 /* Make sure we are not run recursively */
1489 if (m->dispatching_load_queue)
1492 m->dispatching_load_queue = true;
1494 /* Dispatches the load queue. Takes a unit from the queue and
1495 * tries to load its data until the queue is empty */
1497 while ((meta = m->load_queue)) {
1498 assert(meta->in_load_queue);
1500 unit_load(UNIT(meta));
1504 m->dispatching_load_queue = false;
1508 int manager_load_unit(Manager *m, const char *name, const char *path, Unit **_ret) {
1513 assert(name || path);
1515 /* This will load the service information files, but not actually
1516 * start any services or anything. */
1518 if (path && !is_path(path))
1522 name = file_name_from_path(path);
1524 if (!unit_name_is_valid(name))
1527 if ((ret = manager_get_unit(m, name))) {
1532 if (!(ret = unit_new(m)))
1536 if (!(ret->meta.fragment_path = strdup(path))) {
1541 if ((r = unit_add_name(ret, name)) < 0) {
1546 unit_add_to_load_queue(ret);
1547 unit_add_to_dbus_queue(ret);
1549 manager_dispatch_load_queue(m);
1552 *_ret = unit_follow_merge(ret);
1557 void manager_dump_jobs(Manager *s, FILE *f, const char *prefix) {
1564 HASHMAP_FOREACH(j, s->jobs, i)
1565 job_dump(j, f, prefix);
1568 void manager_dump_units(Manager *s, FILE *f, const char *prefix) {
1576 HASHMAP_FOREACH_KEY(u, t, s->units, i)
1577 if (u->meta.id == t)
1578 unit_dump(u, f, prefix);
1581 void manager_clear_jobs(Manager *m) {
1586 transaction_abort(m);
1588 while ((j = hashmap_first(m->jobs)))
1592 unsigned manager_dispatch_run_queue(Manager *m) {
1596 if (m->dispatching_run_queue)
1599 m->dispatching_run_queue = true;
1601 while ((j = m->run_queue)) {
1602 assert(j->installed);
1603 assert(j->in_run_queue);
1605 job_run_and_invalidate(j);
1609 m->dispatching_run_queue = false;
1613 unsigned manager_dispatch_dbus_queue(Manager *m) {
1620 if (m->dispatching_dbus_queue)
1623 m->dispatching_dbus_queue = true;
1625 while ((meta = m->dbus_unit_queue)) {
1626 assert(meta->in_dbus_queue);
1628 bus_unit_send_change_signal(UNIT(meta));
1632 while ((j = m->dbus_job_queue)) {
1633 assert(j->in_dbus_queue);
1635 bus_job_send_change_signal(j);
1639 m->dispatching_dbus_queue = false;
1643 static int manager_dispatch_sigchld(Manager *m) {
1652 /* First we call waitd() for a PID and do not reap the
1653 * zombie. That way we can still access /proc/$PID for
1654 * it while it is a zombie. */
1655 if (waitid(P_ALL, 0, &si, WEXITED|WNOHANG|WNOWAIT) < 0) {
1657 if (errno == ECHILD)
1669 if (si.si_code == CLD_EXITED || si.si_code == CLD_KILLED || si.si_code == CLD_DUMPED) {
1672 get_process_name(si.si_pid, &name);
1673 log_debug("Got SIGCHLD for process %llu (%s)", (unsigned long long) si.si_pid, strna(name));
1677 /* And now, we actually reap the zombie. */
1678 if (waitid(P_PID, si.si_pid, &si, WEXITED) < 0) {
1685 if (si.si_code != CLD_EXITED && si.si_code != CLD_KILLED && si.si_code != CLD_DUMPED)
1688 log_debug("Child %llu died (code=%s, status=%i/%s)",
1689 (long long unsigned) si.si_pid,
1690 sigchld_code_to_string(si.si_code),
1692 strna(si.si_code == CLD_EXITED ? exit_status_to_string(si.si_status) : strsignal(si.si_status)));
1694 if (!(u = hashmap_remove(m->watch_pids, UINT32_TO_PTR(si.si_pid))))
1697 log_debug("Child %llu belongs to %s", (long long unsigned) si.si_pid, u->meta.id);
1699 UNIT_VTABLE(u)->sigchld_event(u, si.si_pid, si.si_code, si.si_status);
1705 static void manager_start_target(Manager *m, const char *name) {
1708 if ((r = manager_add_job_by_name(m, JOB_START, name, JOB_REPLACE, true, NULL)) < 0)
1709 log_error("Failed to enqueue %s job: %s", name, strerror(-r));
1712 static int manager_process_signal_fd(Manager *m) {
1714 struct signalfd_siginfo sfsi;
1715 bool sigchld = false;
1720 if ((n = read(m->signal_watch.fd, &sfsi, sizeof(sfsi))) != sizeof(sfsi)) {
1725 if (errno == EAGAIN)
1731 switch (sfsi.ssi_signo) {
1740 if (m->running_as == MANAGER_INIT) {
1741 manager_start_target(m, SPECIAL_CTRL_ALT_DEL_TARGET);
1745 m->exit_code = MANAGER_EXIT;
1750 if (m->running_as == MANAGER_INIT)
1751 manager_start_target(m, SPECIAL_KBREQUEST_TARGET);
1753 /* This is a nop on non-init */
1757 if (m->running_as == MANAGER_INIT)
1758 manager_start_target(m, SPECIAL_SIGPWR_TARGET);
1760 /* This is a nop on non-init */
1764 manager_dump_units(m, stdout, "\t");
1765 manager_dump_jobs(m, stdout, "\t");
1771 u = manager_get_unit(m, SPECIAL_DBUS_SERVICE);
1773 if (!u || UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u))) {
1774 log_info("Trying to reconnect to bus...");
1779 if (!u || !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u))) {
1780 log_info("Loading D-Bus service...");
1781 manager_start_target(m, SPECIAL_DBUS_SERVICE);
1788 m->exit_code = MANAGER_RELOAD;
1792 log_info("Got unhandled signal <%s>.", strsignal(sfsi.ssi_signo));
1797 return manager_dispatch_sigchld(m);
1802 static int process_event(Manager *m, struct epoll_event *ev) {
1809 assert(w = ev->data.ptr);
1815 /* An incoming signal? */
1816 if (ev->events != EPOLLIN)
1819 if ((r = manager_process_signal_fd(m)) < 0)
1826 /* Some fd event, to be dispatched to the units */
1827 UNIT_VTABLE(w->data.unit)->fd_event(w->data.unit, w->fd, ev->events, w);
1834 /* Some timer event, to be dispatched to the units */
1835 if ((k = read(w->fd, &v, sizeof(v))) != sizeof(v)) {
1837 if (k < 0 && (errno == EINTR || errno == EAGAIN))
1840 return k < 0 ? -errno : -EIO;
1843 UNIT_VTABLE(w->data.unit)->timer_event(w->data.unit, v, w);
1848 /* Some mount table change, intended for the mount subsystem */
1849 mount_fd_event(m, ev->events);
1853 /* Some notification from udev, intended for the device subsystem */
1854 device_fd_event(m, ev->events);
1857 case WATCH_DBUS_WATCH:
1858 bus_watch_event(m, w, ev->events);
1861 case WATCH_DBUS_TIMEOUT:
1862 bus_timeout_event(m, w, ev->events);
1866 assert_not_reached("Unknown epoll event type.");
1872 int manager_loop(Manager *m) {
1875 RATELIMIT_DEFINE(rl, 1*USEC_PER_SEC, 1000);
1878 m->exit_code = MANAGER_RUNNING;
1880 while (m->exit_code == MANAGER_RUNNING) {
1881 struct epoll_event event;
1884 if (!ratelimit_test(&rl)) {
1885 /* Yay, something is going seriously wrong, pause a little */
1886 log_warning("Looping too fast. Throttling execution a little.");
1890 if (manager_dispatch_cleanup_queue(m) > 0)
1893 if (manager_dispatch_gc_queue(m) > 0)
1896 if (manager_dispatch_load_queue(m) > 0)
1899 if (manager_dispatch_run_queue(m) > 0)
1902 if (bus_dispatch(m) > 0)
1905 if (manager_dispatch_dbus_queue(m) > 0)
1908 if ((n = epoll_wait(m->epoll_fd, &event, 1, -1)) < 0) {
1910 if (errno == -EINTR)
1918 if ((r = process_event(m, &event)) < 0)
1922 return m->exit_code;
1925 int manager_get_unit_from_dbus_path(Manager *m, const char *s, Unit **_u) {
1933 if (!startswith(s, "/org/freedesktop/systemd1/unit/"))
1936 if (!(n = bus_path_unescape(s+31)))
1939 u = manager_get_unit(m, n);
1950 int manager_get_job_from_dbus_path(Manager *m, const char *s, Job **_j) {
1959 if (!startswith(s, "/org/freedesktop/systemd1/job/"))
1962 if ((r = safe_atou(s + 30, &id)) < 0)
1965 if (!(j = manager_get_job(m, id)))
1973 static bool manager_utmp_good(Manager *m) {
1978 if ((r = mount_path_is_mounted(m, _PATH_UTMPX)) <= 0) {
1981 log_warning("Failed to determine whether " _PATH_UTMPX " is mounted: %s", strerror(-r));
1989 void manager_write_utmp_reboot(Manager *m) {
1994 if (m->utmp_reboot_written)
1997 if (m->running_as != MANAGER_INIT)
2000 if (!manager_utmp_good(m))
2003 if ((r = utmp_put_reboot(m->boot_timestamp)) < 0) {
2005 if (r != -ENOENT && r != -EROFS)
2006 log_warning("Failed to write utmp/wtmp: %s", strerror(-r));
2011 m->utmp_reboot_written = true;
2014 void manager_write_utmp_runlevel(Manager *m, Unit *u) {
2020 if (u->meta.type != UNIT_TARGET)
2023 if (m->running_as != MANAGER_INIT)
2026 if (!manager_utmp_good(m))
2029 if ((runlevel = target_get_runlevel(TARGET(u))) <= 0)
2032 if ((r = utmp_put_runlevel(0, runlevel, 0)) < 0) {
2034 if (r != -ENOENT && r != -EROFS)
2035 log_warning("Failed to write utmp/wtmp: %s", strerror(-r));
2039 void manager_dispatch_bus_name_owner_changed(
2042 const char* old_owner,
2043 const char *new_owner) {
2050 if (!(u = hashmap_get(m->watch_bus, name)))
2053 UNIT_VTABLE(u)->bus_name_owner_change(u, name, old_owner, new_owner);
2056 void manager_dispatch_bus_query_pid_done(
2067 if (!(u = hashmap_get(m->watch_bus, name)))
2070 UNIT_VTABLE(u)->bus_query_pid_done(u, name, pid);
2073 int manager_open_serialization(FILE **_f) {
2081 if (asprintf(&path, "/dev/shm/systemd-%u.dump-XXXXXX", (unsigned) getpid()) < 0)
2084 saved_umask = umask(0077);
2085 fd = mkostemp(path, O_RDWR|O_CLOEXEC);
2095 log_debug("Serializing state to %s", path);
2098 if (!(f = fdopen(fd, "w+")) < 0)
2106 int manager_serialize(Manager *m, FILE *f, FDSet *fds) {
2116 HASHMAP_FOREACH_KEY(u, t, m->units, i) {
2117 if (u->meta.id != t)
2120 if (!unit_can_serialize(u))
2124 fputs(u->meta.id, f);
2127 if ((r = unit_serialize(u, f, fds)) < 0)
2137 int manager_deserialize(Manager *m, FILE *f, FDSet *fds) {
2143 log_debug("Deserializing state...");
2147 char name[UNIT_NAME_MAX+2];
2150 if (!fgets(name, sizeof(name), f)) {
2159 if ((r = manager_load_unit(m, strstrip(name), NULL, &u)) < 0)
2162 if ((r = unit_deserialize(u, f, fds)) < 0)
2172 int manager_reload(Manager *m) {
2179 if ((r = manager_open_serialization(&f)) < 0)
2182 if (!(fds = fdset_new())) {
2187 if ((r = manager_serialize(m, f, fds)) < 0)
2190 if (fseeko(f, 0, SEEK_SET) < 0) {
2195 /* From here on there is no way back. */
2196 manager_clear_jobs_and_units(m);
2198 /* First, enumerate what we can from all config files */
2199 if ((q = manager_enumerate(m)) < 0)
2202 /* Second, deserialize our stored data */
2203 if ((q = manager_deserialize(m, f, fds)) < 0)
2209 /* Third, fire things up! */
2210 if ((q = manager_coldplug(m)) < 0)
2223 static const char* const manager_running_as_table[_MANAGER_RUNNING_AS_MAX] = {
2224 [MANAGER_INIT] = "init",
2225 [MANAGER_SYSTEM] = "system",
2226 [MANAGER_SESSION] = "session"
2229 DEFINE_STRING_TABLE_LOOKUP(manager_running_as, ManagerRunningAs);