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>
37 #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 #include "path-lookup.h"
57 #include "bus-errors.h"
59 /* As soon as 16 units are in our GC queue, make sure to run a gc sweep */
60 #define GC_QUEUE_ENTRIES_MAX 16
62 /* As soon as 5s passed since a unit was added to our GC queue, make sure to run a gc sweep */
63 #define GC_QUEUE_USEC_MAX (10*USEC_PER_SEC)
65 /* Where clients shall send notification messages to */
66 #define NOTIFY_SOCKET "/org/freedesktop/systemd1/notify"
68 static int manager_setup_notify(Manager *m) {
71 struct sockaddr_un un;
73 struct epoll_event ev;
78 m->notify_watch.type = WATCH_NOTIFY;
79 if ((m->notify_watch.fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0)) < 0) {
80 log_error("Failed to allocate notification socket: %m");
85 sa.sa.sa_family = AF_UNIX;
88 snprintf(sa.un.sun_path+1, sizeof(sa.un.sun_path)-1, NOTIFY_SOCKET "/%llu", random_ull());
90 strncpy(sa.un.sun_path+1, NOTIFY_SOCKET, sizeof(sa.un.sun_path)-1);
92 if (bind(m->notify_watch.fd, &sa.sa, sizeof(sa_family_t) + 1 + strlen(sa.un.sun_path+1)) < 0) {
93 log_error("bind() failed: %m");
97 if (setsockopt(m->notify_watch.fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one)) < 0) {
98 log_error("SO_PASSCRED failed: %m");
104 ev.data.ptr = &m->notify_watch;
106 if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->notify_watch.fd, &ev) < 0)
109 if (!(m->notify_socket = strdup(sa.un.sun_path+1)))
115 static int enable_special_signals(Manager *m) {
120 /* Enable that we get SIGINT on control-alt-del */
121 if (reboot(RB_DISABLE_CAD) < 0)
122 log_warning("Failed to enable ctrl-alt-del handling: %m");
124 if ((fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY)) < 0)
125 log_warning("Failed to open /dev/tty0: %m");
127 /* Enable that we get SIGWINCH on kbrequest */
128 if (ioctl(fd, KDSIGACCEPT, SIGWINCH) < 0)
129 log_warning("Failed to enable kbrequest handling: %s", strerror(errno));
131 close_nointr_nofail(fd);
137 static int manager_setup_signals(Manager *m) {
139 struct epoll_event ev;
144 /* We are not interested in SIGSTOP and friends. */
146 sa.sa_handler = SIG_DFL;
147 sa.sa_flags = SA_NOCLDSTOP|SA_RESTART;
148 assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);
150 assert_se(sigemptyset(&mask) == 0);
152 sigset_add_many(&mask,
153 SIGCHLD, /* Child died */
154 SIGTERM, /* Reexecute daemon */
155 SIGHUP, /* Reload configuration */
156 SIGUSR1, /* systemd/upstart: reconnect to D-Bus */
157 SIGUSR2, /* systemd: dump status */
158 SIGINT, /* Kernel sends us this on control-alt-del */
159 SIGWINCH, /* Kernel sends us this on kbrequest (alt-arrowup) */
160 SIGPWR, /* Some kernel drivers and upsd send us this on power failure */
161 SIGRTMIN+0, /* systemd: start default.target */
162 SIGRTMIN+1, /* systemd: start rescue.target */
163 SIGRTMIN+2, /* systemd: isolate emergency.target */
164 SIGRTMIN+3, /* systemd: start halt.target */
165 SIGRTMIN+4, /* systemd: start poweroff.target */
166 SIGRTMIN+5, /* systemd: start reboot.target */
168 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
170 m->signal_watch.type = WATCH_SIGNAL;
171 if ((m->signal_watch.fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0)
176 ev.data.ptr = &m->signal_watch;
178 if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->signal_watch.fd, &ev) < 0)
181 if (m->running_as == MANAGER_SYSTEM)
182 return enable_special_signals(m);
187 int manager_new(ManagerRunningAs running_as, Manager **_m) {
192 assert(running_as >= 0);
193 assert(running_as < _MANAGER_RUNNING_AS_MAX);
195 if (!(m = new0(Manager, 1)))
198 dual_timestamp_get(&m->startup_timestamp);
200 m->running_as = running_as;
201 m->name_data_slot = m->subscribed_data_slot = -1;
202 m->exit_code = _MANAGER_EXIT_CODE_INVALID;
203 m->pin_cgroupfs_fd = -1;
205 m->signal_watch.fd = m->mount_watch.fd = m->udev_watch.fd = m->epoll_fd = m->dev_autofs_fd = -1;
206 m->current_job_id = 1; /* start as id #1, so that we can leave #0 around as "null-like" value */
208 if (!(m->environment = strv_copy(environ)))
211 if (!(m->units = hashmap_new(string_hash_func, string_compare_func)))
214 if (!(m->jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
217 if (!(m->transaction_jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
220 if (!(m->watch_pids = hashmap_new(trivial_hash_func, trivial_compare_func)))
223 if (!(m->cgroup_bondings = hashmap_new(string_hash_func, string_compare_func)))
226 if (!(m->watch_bus = hashmap_new(string_hash_func, string_compare_func)))
229 if ((m->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0)
232 if ((r = lookup_paths_init(&m->lookup_paths, m->running_as)) < 0)
235 if ((r = manager_setup_signals(m)) < 0)
238 if ((r = manager_setup_cgroup(m)) < 0)
241 if ((r = manager_setup_notify(m)) < 0)
244 /* Try to connect to the busses, if possible. */
245 if ((r = bus_init(m)) < 0)
256 static unsigned manager_dispatch_cleanup_queue(Manager *m) {
262 while ((meta = m->cleanup_queue)) {
263 assert(meta->in_cleanup_queue);
265 unit_free((Unit*) meta);
273 GC_OFFSET_IN_PATH, /* This one is on the path we were travelling */
274 GC_OFFSET_UNSURE, /* No clue */
275 GC_OFFSET_GOOD, /* We still need this unit */
276 GC_OFFSET_BAD, /* We don't need this unit anymore */
280 static void unit_gc_sweep(Unit *u, unsigned gc_marker) {
287 if (u->meta.gc_marker == gc_marker + GC_OFFSET_GOOD ||
288 u->meta.gc_marker == gc_marker + GC_OFFSET_BAD ||
289 u->meta.gc_marker == gc_marker + GC_OFFSET_IN_PATH)
292 if (u->meta.in_cleanup_queue)
295 if (unit_check_gc(u))
298 u->meta.gc_marker = gc_marker + GC_OFFSET_IN_PATH;
302 SET_FOREACH(other, u->meta.dependencies[UNIT_REFERENCED_BY], i) {
303 unit_gc_sweep(other, gc_marker);
305 if (other->meta.gc_marker == gc_marker + GC_OFFSET_GOOD)
308 if (other->meta.gc_marker != gc_marker + GC_OFFSET_BAD)
315 /* We were unable to find anything out about this entry, so
316 * let's investigate it later */
317 u->meta.gc_marker = gc_marker + GC_OFFSET_UNSURE;
318 unit_add_to_gc_queue(u);
322 /* We definitely know that this one is not useful anymore, so
323 * let's mark it for deletion */
324 u->meta.gc_marker = gc_marker + GC_OFFSET_BAD;
325 unit_add_to_cleanup_queue(u);
329 u->meta.gc_marker = gc_marker + GC_OFFSET_GOOD;
332 static unsigned manager_dispatch_gc_queue(Manager *m) {
339 if ((m->n_in_gc_queue < GC_QUEUE_ENTRIES_MAX) &&
340 (m->gc_queue_timestamp <= 0 ||
341 (m->gc_queue_timestamp + GC_QUEUE_USEC_MAX) > now(CLOCK_MONOTONIC)))
344 log_debug("Running GC...");
346 m->gc_marker += _GC_OFFSET_MAX;
347 if (m->gc_marker + _GC_OFFSET_MAX <= _GC_OFFSET_MAX)
350 gc_marker = m->gc_marker;
352 while ((meta = m->gc_queue)) {
353 assert(meta->in_gc_queue);
355 unit_gc_sweep((Unit*) meta, gc_marker);
357 LIST_REMOVE(Meta, gc_queue, m->gc_queue, meta);
358 meta->in_gc_queue = false;
362 if (meta->gc_marker == gc_marker + GC_OFFSET_BAD ||
363 meta->gc_marker == gc_marker + GC_OFFSET_UNSURE) {
364 log_debug("Collecting %s", meta->id);
365 meta->gc_marker = gc_marker + GC_OFFSET_BAD;
366 unit_add_to_cleanup_queue((Unit*) meta);
370 m->n_in_gc_queue = 0;
371 m->gc_queue_timestamp = 0;
376 static void manager_clear_jobs_and_units(Manager *m) {
382 while ((j = hashmap_first(m->transaction_jobs)))
385 while ((u = hashmap_first(m->units)))
388 manager_dispatch_cleanup_queue(m);
390 assert(!m->load_queue);
391 assert(!m->run_queue);
392 assert(!m->dbus_unit_queue);
393 assert(!m->dbus_job_queue);
394 assert(!m->cleanup_queue);
395 assert(!m->gc_queue);
397 assert(hashmap_isempty(m->transaction_jobs));
398 assert(hashmap_isempty(m->jobs));
399 assert(hashmap_isempty(m->units));
402 void manager_free(Manager *m) {
407 manager_clear_jobs_and_units(m);
409 for (c = 0; c < _UNIT_TYPE_MAX; c++)
410 if (unit_vtable[c]->shutdown)
411 unit_vtable[c]->shutdown(m);
413 /* If we reexecute ourselves, we keep the root cgroup
415 manager_shutdown_cgroup(m, m->exit_code != MANAGER_REEXECUTE);
419 hashmap_free(m->units);
420 hashmap_free(m->jobs);
421 hashmap_free(m->transaction_jobs);
422 hashmap_free(m->watch_pids);
423 hashmap_free(m->watch_bus);
425 if (m->epoll_fd >= 0)
426 close_nointr_nofail(m->epoll_fd);
427 if (m->signal_watch.fd >= 0)
428 close_nointr_nofail(m->signal_watch.fd);
429 if (m->notify_watch.fd >= 0)
430 close_nointr_nofail(m->notify_watch.fd);
432 free(m->notify_socket);
434 lookup_paths_free(&m->lookup_paths);
435 strv_free(m->environment);
437 hashmap_free(m->cgroup_bondings);
438 set_free_free(m->unit_path_cache);
443 int manager_enumerate(Manager *m) {
449 /* Let's ask every type to load all units from disk/kernel
450 * that it might know */
451 for (c = 0; c < _UNIT_TYPE_MAX; c++)
452 if (unit_vtable[c]->enumerate)
453 if ((q = unit_vtable[c]->enumerate(m)) < 0)
456 manager_dispatch_load_queue(m);
460 int manager_coldplug(Manager *m) {
468 /* Then, let's set up their initial state. */
469 HASHMAP_FOREACH_KEY(u, k, m->units, i) {
475 if ((q = unit_coldplug(u)) < 0)
482 static void manager_build_unit_path_cache(Manager *m) {
489 set_free_free(m->unit_path_cache);
491 if (!(m->unit_path_cache = set_new(string_hash_func, string_compare_func))) {
492 log_error("Failed to allocate unit path cache.");
496 /* This simply builds a list of files we know exist, so that
497 * we don't always have to go to disk */
499 STRV_FOREACH(i, m->lookup_paths.unit_path) {
502 if (!(d = opendir(*i))) {
503 log_error("Failed to open directory: %m");
507 while ((de = readdir(d))) {
510 if (ignore_file(de->d_name))
513 if (asprintf(&p, "%s/%s", streq(*i, "/") ? "" : *i, de->d_name) < 0) {
518 if ((r = set_put(m->unit_path_cache, p)) < 0) {
531 log_error("Failed to build unit path cache: %s", strerror(-r));
533 set_free_free(m->unit_path_cache);
534 m->unit_path_cache = NULL;
540 int manager_startup(Manager *m, FILE *serialization, FDSet *fds) {
545 manager_build_unit_path_cache(m);
547 /* First, enumerate what we can from all config files */
548 r = manager_enumerate(m);
550 /* Second, deserialize if there is something to deserialize */
552 if ((q = manager_deserialize(m, serialization, fds)) < 0)
555 /* Third, fire things up! */
556 if ((q = manager_coldplug(m)) < 0)
559 /* Now that the initial devices are available, let's see if we
560 * can write the utmp file */
561 manager_write_utmp_reboot(m);
566 static void transaction_delete_job(Manager *m, Job *j, bool delete_dependencies) {
570 /* Deletes one job from the transaction */
572 manager_transaction_unlink_job(m, j, delete_dependencies);
578 static void transaction_delete_unit(Manager *m, Unit *u) {
581 /* Deletes all jobs associated with a certain unit from the
584 while ((j = hashmap_get(m->transaction_jobs, u)))
585 transaction_delete_job(m, j, true);
588 static void transaction_clean_dependencies(Manager *m) {
594 /* Drops all dependencies of all installed jobs */
596 HASHMAP_FOREACH(j, m->jobs, i) {
597 while (j->subject_list)
598 job_dependency_free(j->subject_list);
599 while (j->object_list)
600 job_dependency_free(j->object_list);
603 assert(!m->transaction_anchor);
606 static void transaction_abort(Manager *m) {
611 while ((j = hashmap_first(m->transaction_jobs)))
613 transaction_delete_job(m, j, true);
617 assert(hashmap_isempty(m->transaction_jobs));
619 transaction_clean_dependencies(m);
622 static void transaction_find_jobs_that_matter_to_anchor(Manager *m, Job *j, unsigned generation) {
627 /* A recursive sweep through the graph that marks all units
628 * that matter to the anchor job, i.e. are directly or
629 * indirectly a dependency of the anchor job via paths that
630 * are fully marked as mattering. */
635 l = m->transaction_anchor;
637 LIST_FOREACH(subject, l, l) {
639 /* This link does not matter */
643 /* This unit has already been marked */
644 if (l->object->generation == generation)
647 l->object->matters_to_anchor = true;
648 l->object->generation = generation;
650 transaction_find_jobs_that_matter_to_anchor(m, l->object, generation);
654 static void transaction_merge_and_delete_job(Manager *m, Job *j, Job *other, JobType t) {
655 JobDependency *l, *last;
659 assert(j->unit == other->unit);
660 assert(!j->installed);
662 /* Merges 'other' into 'j' and then deletes j. */
665 j->state = JOB_WAITING;
666 j->override = j->override || other->override;
668 j->matters_to_anchor = j->matters_to_anchor || other->matters_to_anchor;
670 /* Patch us in as new owner of the JobDependency objects */
672 LIST_FOREACH(subject, l, other->subject_list) {
673 assert(l->subject == other);
678 /* Merge both lists */
680 last->subject_next = j->subject_list;
682 j->subject_list->subject_prev = last;
683 j->subject_list = other->subject_list;
686 /* Patch us in as new owner of the JobDependency objects */
688 LIST_FOREACH(object, l, other->object_list) {
689 assert(l->object == other);
694 /* Merge both lists */
696 last->object_next = j->object_list;
698 j->object_list->object_prev = last;
699 j->object_list = other->object_list;
702 /* Kill the other job */
703 other->subject_list = NULL;
704 other->object_list = NULL;
705 transaction_delete_job(m, other, true);
708 static int delete_one_unmergeable_job(Manager *m, Job *j) {
713 /* Tries to delete one item in the linked list
714 * j->transaction_next->transaction_next->... that conflicts
715 * whith another one, in an attempt to make an inconsistent
716 * transaction work. */
718 /* We rely here on the fact that if a merged with b does not
719 * merge with c, either a or b merge with c neither */
720 LIST_FOREACH(transaction, j, j)
721 LIST_FOREACH(transaction, k, j->transaction_next) {
724 /* Is this one mergeable? Then skip it */
725 if (job_type_is_mergeable(j->type, k->type))
728 /* Ok, we found two that conflict, let's see if we can
729 * drop one of them */
730 if (!j->matters_to_anchor)
732 else if (!k->matters_to_anchor)
737 /* Ok, we can drop one, so let's do so. */
738 log_notice("Trying to fix job merging by deleting job %s/%s", d->unit->meta.id, job_type_to_string(d->type));
739 transaction_delete_job(m, d, true);
746 static int transaction_merge_jobs(Manager *m, DBusError *e) {
753 /* First step, check whether any of the jobs for one specific
754 * task conflict. If so, try to drop one of them. */
755 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
760 LIST_FOREACH(transaction, k, j->transaction_next) {
761 if ((r = job_type_merge(&t, k->type)) >= 0)
764 /* OK, we could not merge all jobs for this
765 * action. Let's see if we can get rid of one
768 if ((r = delete_one_unmergeable_job(m, j)) >= 0)
769 /* Ok, we managed to drop one, now
770 * let's ask our callers to call us
771 * again after garbage collecting */
774 /* We couldn't merge anything. Failure */
775 dbus_set_error(e, BUS_ERROR_TRANSACTION_JOBS_CONFLICTING, "Transaction contains conflicting jobs '%s' and '%s' for %s. Probably contradicting requirement dependencies configured.",
776 job_type_to_string(t), job_type_to_string(k->type), k->unit->meta.id);
781 /* Second step, merge the jobs. */
782 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
786 /* Merge all transactions */
787 LIST_FOREACH(transaction, k, j->transaction_next)
788 assert_se(job_type_merge(&t, k->type) == 0);
790 /* If an active job is mergeable, merge it too */
791 if (j->unit->meta.job)
792 job_type_merge(&t, j->unit->meta.job->type); /* Might fail. Which is OK */
794 while ((k = j->transaction_next)) {
796 transaction_merge_and_delete_job(m, k, j, t);
799 transaction_merge_and_delete_job(m, j, k, t);
802 assert(!j->transaction_next);
803 assert(!j->transaction_prev);
809 static void transaction_drop_redundant(Manager *m) {
814 /* Goes through the transaction and removes all jobs that are
823 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
824 bool changes_something = false;
827 LIST_FOREACH(transaction, k, j) {
829 if (!job_is_anchor(k) &&
830 job_type_is_redundant(k->type, unit_active_state(k->unit)))
833 changes_something = true;
837 if (changes_something)
840 log_debug("Found redundant job %s/%s, dropping.", j->unit->meta.id, job_type_to_string(j->type));
841 transaction_delete_job(m, j, false);
849 static bool unit_matters_to_anchor(Unit *u, Job *j) {
851 assert(!j->transaction_prev);
853 /* Checks whether at least one of the jobs for this unit
854 * matters to the anchor. */
856 LIST_FOREACH(transaction, j, j)
857 if (j->matters_to_anchor)
863 static int transaction_verify_order_one(Manager *m, Job *j, Job *from, unsigned generation, DBusError *e) {
870 assert(!j->transaction_prev);
872 /* Does a recursive sweep through the ordering graph, looking
873 * for a cycle. If we find cycle we try to break it. */
875 /* Have we seen this before? */
876 if (j->generation == generation) {
879 /* If the marker is NULL we have been here already and
880 * decided the job was loop-free from here. Hence
881 * shortcut things and return right-away. */
885 /* So, the marker is not NULL and we already have been
886 * here. We have a cycle. Let's try to break it. We go
887 * backwards in our path and try to find a suitable
888 * job to remove. We use the marker to find our way
889 * back, since smart how we are we stored our way back
891 log_warning("Found ordering cycle on %s/%s", j->unit->meta.id, job_type_to_string(j->type));
893 for (k = from; k; k = ((k->generation == generation && k->marker != k) ? k->marker : NULL)) {
895 log_info("Walked on cycle path to %s/%s", k->unit->meta.id, job_type_to_string(k->type));
898 !unit_matters_to_anchor(k->unit, k)) {
899 /* Ok, we can drop this one, so let's
901 log_warning("Breaking order cycle by deleting job %s/%s", k->unit->meta.id, job_type_to_string(k->type));
902 transaction_delete_unit(m, k->unit);
906 /* Check if this in fact was the beginning of
912 log_error("Unable to break cycle");
914 dbus_set_error(e, BUS_ERROR_TRANSACTION_ORDER_IS_CYCLIC, "Transaction order is cyclic. See logs for details.");
918 /* Make the marker point to where we come from, so that we can
919 * find our way backwards if we want to break a cycle. We use
920 * a special marker for the beginning: we point to
922 j->marker = from ? from : j;
923 j->generation = generation;
925 /* We assume that the the dependencies are bidirectional, and
926 * hence can ignore UNIT_AFTER */
927 SET_FOREACH(u, j->unit->meta.dependencies[UNIT_BEFORE], i) {
930 /* Is there a job for this unit? */
931 if (!(o = hashmap_get(m->transaction_jobs, u)))
933 /* Ok, there is no job for this in the
934 * transaction, but maybe there is already one
936 if (!(o = u->meta.job))
939 if ((r = transaction_verify_order_one(m, o, j, generation, e)) < 0)
943 /* Ok, let's backtrack, and remember that this entry is not on
944 * our path anymore. */
950 static int transaction_verify_order(Manager *m, unsigned *generation, DBusError *e) {
959 /* Check if the ordering graph is cyclic. If it is, try to fix
960 * that up by dropping one of the jobs. */
964 HASHMAP_FOREACH(j, m->transaction_jobs, i)
965 if ((r = transaction_verify_order_one(m, j, NULL, g, e)) < 0)
971 static void transaction_collect_garbage(Manager *m) {
976 /* Drop jobs that are not required by any other job */
984 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
988 log_debug("Garbage collecting job %s/%s", j->unit->meta.id, job_type_to_string(j->type));
989 transaction_delete_job(m, j, true);
997 static int transaction_is_destructive(Manager *m, DBusError *e) {
1003 /* Checks whether applying this transaction means that
1004 * existing jobs would be replaced */
1006 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1009 assert(!j->transaction_prev);
1010 assert(!j->transaction_next);
1012 if (j->unit->meta.job &&
1013 j->unit->meta.job != j &&
1014 !job_type_is_superset(j->type, j->unit->meta.job->type)) {
1016 dbus_set_error(e, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE, "Transaction is destructive.");
1024 static void transaction_minimize_impact(Manager *m) {
1028 /* Drops all unnecessary jobs that reverse already active jobs
1029 * or that stop a running service. */
1037 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1038 LIST_FOREACH(transaction, j, j) {
1039 bool stops_running_service, changes_existing_job;
1041 /* If it matters, we shouldn't drop it */
1042 if (j->matters_to_anchor)
1045 /* Would this stop a running service?
1046 * Would this change an existing job?
1047 * If so, let's drop this entry */
1049 stops_running_service =
1050 j->type == JOB_STOP && UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(j->unit));
1052 changes_existing_job =
1053 j->unit->meta.job && job_type_is_conflicting(j->type, j->unit->meta.job->state);
1055 if (!stops_running_service && !changes_existing_job)
1058 if (stops_running_service)
1059 log_info("%s/%s would stop a running service.", j->unit->meta.id, job_type_to_string(j->type));
1061 if (changes_existing_job)
1062 log_info("%s/%s would change existing job.", j->unit->meta.id, job_type_to_string(j->type));
1064 /* Ok, let's get rid of this */
1065 log_info("Deleting %s/%s to minimize impact.", j->unit->meta.id, job_type_to_string(j->type));
1067 transaction_delete_job(m, j, true);
1079 static int transaction_apply(Manager *m) {
1084 /* Moves the transaction jobs to the set of active jobs */
1086 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1088 assert(!j->transaction_prev);
1089 assert(!j->transaction_next);
1094 if ((r = hashmap_put(m->jobs, UINT32_TO_PTR(j->id), j)) < 0)
1098 while ((j = hashmap_steal_first(m->transaction_jobs))) {
1102 if (j->unit->meta.job)
1103 job_free(j->unit->meta.job);
1105 j->unit->meta.job = j;
1106 j->installed = true;
1108 /* We're fully installed. Now let's free data we don't
1111 assert(!j->transaction_next);
1112 assert(!j->transaction_prev);
1114 job_add_to_run_queue(j);
1115 job_add_to_dbus_queue(j);
1118 /* As last step, kill all remaining job dependencies. */
1119 transaction_clean_dependencies(m);
1125 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1129 hashmap_remove(m->jobs, UINT32_TO_PTR(j->id));
1135 static int transaction_activate(Manager *m, JobMode mode, DBusError *e) {
1137 unsigned generation = 1;
1141 /* This applies the changes recorded in transaction_jobs to
1142 * the actual list of jobs, if possible. */
1144 /* First step: figure out which jobs matter */
1145 transaction_find_jobs_that_matter_to_anchor(m, NULL, generation++);
1147 /* Second step: Try not to stop any running services if
1148 * we don't have to. Don't try to reverse running
1149 * jobs if we don't have to. */
1150 transaction_minimize_impact(m);
1152 /* Third step: Drop redundant jobs */
1153 transaction_drop_redundant(m);
1156 /* Fourth step: Let's remove unneeded jobs that might
1158 transaction_collect_garbage(m);
1160 /* Fifth step: verify order makes sense and correct
1161 * cycles if necessary and possible */
1162 if ((r = transaction_verify_order(m, &generation, e)) >= 0)
1166 log_warning("Requested transaction contains an unfixable cyclic ordering dependency: %s", bus_error(e, r));
1170 /* Let's see if the resulting transaction ordering
1171 * graph is still cyclic... */
1175 /* Sixth step: let's drop unmergeable entries if
1176 * necessary and possible, merge entries we can
1178 if ((r = transaction_merge_jobs(m, e)) >= 0)
1182 log_warning("Requested transaction contains unmergable jobs: %s", bus_error(e, r));
1186 /* Seventh step: an entry got dropped, let's garbage
1187 * collect its dependencies. */
1188 transaction_collect_garbage(m);
1190 /* Let's see if the resulting transaction still has
1191 * unmergeable entries ... */
1194 /* Eights step: Drop redundant jobs again, if the merging now allows us to drop more. */
1195 transaction_drop_redundant(m);
1197 /* Ninth step: check whether we can actually apply this */
1198 if (mode == JOB_FAIL)
1199 if ((r = transaction_is_destructive(m, e)) < 0) {
1200 log_notice("Requested transaction contradicts existing jobs: %s", bus_error(e, r));
1204 /* Tenth step: apply changes */
1205 if ((r = transaction_apply(m)) < 0) {
1206 log_warning("Failed to apply transaction: %s", strerror(-r));
1210 assert(hashmap_isempty(m->transaction_jobs));
1211 assert(!m->transaction_anchor);
1216 transaction_abort(m);
1220 static Job* transaction_add_one_job(Manager *m, JobType type, Unit *unit, bool override, bool *is_new) {
1227 /* Looks for an axisting prospective job and returns that. If
1228 * it doesn't exist it is created and added to the prospective
1231 f = hashmap_get(m->transaction_jobs, unit);
1233 LIST_FOREACH(transaction, j, f) {
1234 assert(j->unit == unit);
1236 if (j->type == type) {
1243 if (unit->meta.job && unit->meta.job->type == type)
1245 else if (!(j = job_new(m, type, unit)))
1250 j->matters_to_anchor = false;
1251 j->override = override;
1253 LIST_PREPEND(Job, transaction, f, j);
1255 if ((r = hashmap_replace(m->transaction_jobs, unit, f)) < 0) {
1263 log_debug("Added job %s/%s to transaction.", unit->meta.id, job_type_to_string(type));
1268 void manager_transaction_unlink_job(Manager *m, Job *j, bool delete_dependencies) {
1272 if (j->transaction_prev)
1273 j->transaction_prev->transaction_next = j->transaction_next;
1274 else if (j->transaction_next)
1275 hashmap_replace(m->transaction_jobs, j->unit, j->transaction_next);
1277 hashmap_remove_value(m->transaction_jobs, j->unit, j);
1279 if (j->transaction_next)
1280 j->transaction_next->transaction_prev = j->transaction_prev;
1282 j->transaction_prev = j->transaction_next = NULL;
1284 while (j->subject_list)
1285 job_dependency_free(j->subject_list);
1287 while (j->object_list) {
1288 Job *other = j->object_list->matters ? j->object_list->subject : NULL;
1290 job_dependency_free(j->object_list);
1292 if (other && delete_dependencies) {
1293 log_info("Deleting job %s/%s as dependency of job %s/%s",
1294 other->unit->meta.id, job_type_to_string(other->type),
1295 j->unit->meta.id, job_type_to_string(j->type));
1296 transaction_delete_job(m, other, delete_dependencies);
1301 static int transaction_add_job_and_dependencies(
1317 assert(type < _JOB_TYPE_MAX);
1320 if (unit->meta.load_state != UNIT_LOADED) {
1321 dbus_set_error(e, BUS_ERROR_LOAD_FAILED, "Unit %s failed to load. See logs for details.", unit->meta.id);
1325 if (!unit_job_is_applicable(unit, type)) {
1326 dbus_set_error(e, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE, "Job type %s is not applicable for unit %s.", job_type_to_string(type), unit->meta.id);
1330 /* First add the job. */
1331 if (!(ret = transaction_add_one_job(m, type, unit, override, &is_new)))
1334 /* Then, add a link to the job. */
1335 if (!job_dependency_new(by, ret, matters))
1339 /* Finally, recursively add in all dependencies. */
1340 if (type == JOB_START || type == JOB_RELOAD_OR_START) {
1341 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES], i)
1342 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, true, override, e, NULL)) < 0 && r != -EBADR)
1345 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES_OVERRIDABLE], i)
1346 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, !override, override, e, NULL)) < 0 && r != -EBADR) {
1347 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, bus_error(e, 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, e, NULL)) < 0) {
1353 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, bus_error(e, r));
1357 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE], i)
1358 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, true, override, e, NULL)) < 0 && r != -EBADR)
1361 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE_OVERRIDABLE], i)
1362 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, !override, override, e, NULL)) < 0 && r != -EBADR) {
1363 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, bus_error(e, r));
1367 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_CONFLICTS], i)
1368 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, dep, ret, true, override, e, NULL)) < 0 && r != -EBADR)
1371 } else if (type == JOB_STOP || type == JOB_RESTART || type == JOB_TRY_RESTART) {
1373 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRED_BY], i)
1374 if ((r = transaction_add_job_and_dependencies(m, type, dep, ret, true, override, e, NULL)) < 0 && r != -EBADR)
1378 /* JOB_VERIFY_STARTED, JOB_RELOAD require no dependency handling */
1390 static int transaction_add_isolate_jobs(Manager *m) {
1398 HASHMAP_FOREACH_KEY(u, k, m->units, i) {
1400 /* ignore aliases */
1401 if (u->meta.id != k)
1404 if (UNIT_VTABLE(u)->no_isolate)
1407 /* No need to stop inactive jobs */
1408 if (UNIT_IS_INACTIVE_OR_MAINTENANCE(unit_active_state(u)))
1411 /* Is there already something listed for this? */
1412 if (hashmap_get(m->transaction_jobs, u))
1415 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, u, NULL, true, false, NULL, NULL)) < 0)
1416 log_warning("Cannot add isolate job for unit %s, ignoring: %s", u->meta.id, strerror(-r));
1422 int manager_add_job(Manager *m, JobType type, Unit *unit, JobMode mode, bool override, DBusError *e, Job **_ret) {
1427 assert(type < _JOB_TYPE_MAX);
1429 assert(mode < _JOB_MODE_MAX);
1431 if (mode == JOB_ISOLATE && type != JOB_START) {
1432 dbus_set_error(e, BUS_ERROR_INVALID_JOB_MODE, "Isolate is only valid for start.");
1436 log_debug("Trying to enqueue job %s/%s", unit->meta.id, job_type_to_string(type));
1438 if ((r = transaction_add_job_and_dependencies(m, type, unit, NULL, true, override, e, &ret)) < 0) {
1439 transaction_abort(m);
1443 if (mode == JOB_ISOLATE)
1444 if ((r = transaction_add_isolate_jobs(m)) < 0) {
1445 transaction_abort(m);
1449 if ((r = transaction_activate(m, mode, e)) < 0)
1452 log_debug("Enqueued job %s/%s as %u", unit->meta.id, job_type_to_string(type), (unsigned) ret->id);
1460 int manager_add_job_by_name(Manager *m, JobType type, const char *name, JobMode mode, bool override, DBusError *e, Job **_ret) {
1465 assert(type < _JOB_TYPE_MAX);
1467 assert(mode < _JOB_MODE_MAX);
1469 if ((r = manager_load_unit(m, name, NULL, NULL, &unit)) < 0)
1472 return manager_add_job(m, type, unit, mode, override, e, _ret);
1475 Job *manager_get_job(Manager *m, uint32_t id) {
1478 return hashmap_get(m->jobs, UINT32_TO_PTR(id));
1481 Unit *manager_get_unit(Manager *m, const char *name) {
1485 return hashmap_get(m->units, name);
1488 unsigned manager_dispatch_load_queue(Manager *m) {
1494 /* Make sure we are not run recursively */
1495 if (m->dispatching_load_queue)
1498 m->dispatching_load_queue = true;
1500 /* Dispatches the load queue. Takes a unit from the queue and
1501 * tries to load its data until the queue is empty */
1503 while ((meta = m->load_queue)) {
1504 assert(meta->in_load_queue);
1506 unit_load((Unit*) meta);
1510 m->dispatching_load_queue = false;
1514 int manager_load_unit_prepare(Manager *m, const char *name, const char *path, DBusError *e, Unit **_ret) {
1519 assert(name || path);
1521 /* This will prepare the unit for loading, but not actually
1522 * load anything from disk. */
1524 if (path && !is_path(path)) {
1525 dbus_set_error(e, BUS_ERROR_INVALID_PATH, "Path %s is not absolute.", path);
1530 name = file_name_from_path(path);
1532 if (!unit_name_is_valid(name)) {
1533 dbus_set_error(e, BUS_ERROR_INVALID_NAME, "Unit name %s is not valid.", name);
1537 if ((ret = manager_get_unit(m, name))) {
1542 if (!(ret = unit_new(m)))
1546 if (!(ret->meta.fragment_path = strdup(path))) {
1551 if ((r = unit_add_name(ret, name)) < 0) {
1556 unit_add_to_load_queue(ret);
1557 unit_add_to_dbus_queue(ret);
1558 unit_add_to_gc_queue(ret);
1566 int manager_load_unit(Manager *m, const char *name, const char *path, DBusError *e, Unit **_ret) {
1571 /* This will load the service information files, but not actually
1572 * start any services or anything. */
1574 if ((r = manager_load_unit_prepare(m, name, path, e, _ret)) != 0)
1577 manager_dispatch_load_queue(m);
1580 *_ret = unit_follow_merge(*_ret);
1585 void manager_dump_jobs(Manager *s, FILE *f, const char *prefix) {
1592 HASHMAP_FOREACH(j, s->jobs, i)
1593 job_dump(j, f, prefix);
1596 void manager_dump_units(Manager *s, FILE *f, const char *prefix) {
1604 HASHMAP_FOREACH_KEY(u, t, s->units, i)
1605 if (u->meta.id == t)
1606 unit_dump(u, f, prefix);
1609 void manager_clear_jobs(Manager *m) {
1614 transaction_abort(m);
1616 while ((j = hashmap_first(m->jobs)))
1620 unsigned manager_dispatch_run_queue(Manager *m) {
1624 if (m->dispatching_run_queue)
1627 m->dispatching_run_queue = true;
1629 while ((j = m->run_queue)) {
1630 assert(j->installed);
1631 assert(j->in_run_queue);
1633 job_run_and_invalidate(j);
1637 m->dispatching_run_queue = false;
1641 unsigned manager_dispatch_dbus_queue(Manager *m) {
1648 if (m->dispatching_dbus_queue)
1651 m->dispatching_dbus_queue = true;
1653 while ((meta = m->dbus_unit_queue)) {
1654 assert(meta->in_dbus_queue);
1656 bus_unit_send_change_signal((Unit*) meta);
1660 while ((j = m->dbus_job_queue)) {
1661 assert(j->in_dbus_queue);
1663 bus_job_send_change_signal(j);
1667 m->dispatching_dbus_queue = false;
1671 static int manager_process_notify_fd(Manager *m) {
1678 struct msghdr msghdr;
1680 struct ucred *ucred;
1682 struct cmsghdr cmsghdr;
1683 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
1689 iovec.iov_base = buf;
1690 iovec.iov_len = sizeof(buf)-1;
1694 msghdr.msg_iov = &iovec;
1695 msghdr.msg_iovlen = 1;
1696 msghdr.msg_control = &control;
1697 msghdr.msg_controllen = sizeof(control);
1699 if ((n = recvmsg(m->notify_watch.fd, &msghdr, MSG_DONTWAIT)) <= 0) {
1703 if (errno == EAGAIN)
1709 if (msghdr.msg_controllen < CMSG_LEN(sizeof(struct ucred)) ||
1710 control.cmsghdr.cmsg_level != SOL_SOCKET ||
1711 control.cmsghdr.cmsg_type != SCM_CREDENTIALS ||
1712 control.cmsghdr.cmsg_len != CMSG_LEN(sizeof(struct ucred))) {
1713 log_warning("Received notify message without credentials. Ignoring.");
1717 ucred = (struct ucred*) CMSG_DATA(&control.cmsghdr);
1719 if (!(u = hashmap_get(m->watch_pids, LONG_TO_PTR(ucred->pid))))
1720 if (!(u = cgroup_unit_by_pid(m, ucred->pid))) {
1721 log_warning("Cannot find unit for notify message of PID %lu.", (unsigned long) ucred->pid);
1725 assert((size_t) n < sizeof(buf));
1727 if (!(tags = strv_split(buf, "\n\r")))
1730 log_debug("Got notification message for unit %s", u->meta.id);
1732 if (UNIT_VTABLE(u)->notify_message)
1733 UNIT_VTABLE(u)->notify_message(u, ucred->pid, tags);
1741 static int manager_dispatch_sigchld(Manager *m) {
1751 /* First we call waitd() for a PID and do not reap the
1752 * zombie. That way we can still access /proc/$PID for
1753 * it while it is a zombie. */
1754 if (waitid(P_ALL, 0, &si, WEXITED|WNOHANG|WNOWAIT) < 0) {
1756 if (errno == ECHILD)
1768 if (si.si_code == CLD_EXITED || si.si_code == CLD_KILLED || si.si_code == CLD_DUMPED) {
1771 get_process_name(si.si_pid, &name);
1772 log_debug("Got SIGCHLD for process %lu (%s)", (unsigned long) si.si_pid, strna(name));
1776 /* Let's flush any message the dying child might still
1777 * have queued for us. This ensures that the process
1778 * still exists in /proc so that we can figure out
1779 * which cgroup and hence unit it belongs to. */
1780 if ((r = manager_process_notify_fd(m)) < 0)
1783 /* And now figure out the unit this belongs to */
1784 if (!(u = hashmap_get(m->watch_pids, LONG_TO_PTR(si.si_pid))))
1785 u = cgroup_unit_by_pid(m, si.si_pid);
1787 /* And now, we actually reap the zombie. */
1788 if (waitid(P_PID, si.si_pid, &si, WEXITED) < 0) {
1795 if (si.si_code != CLD_EXITED && si.si_code != CLD_KILLED && si.si_code != CLD_DUMPED)
1798 log_debug("Child %lu died (code=%s, status=%i/%s)",
1799 (long unsigned) si.si_pid,
1800 sigchld_code_to_string(si.si_code),
1802 strna(si.si_code == CLD_EXITED ? exit_status_to_string(si.si_status) : signal_to_string(si.si_status)));
1807 log_debug("Child %lu belongs to %s", (long unsigned) si.si_pid, u->meta.id);
1809 hashmap_remove(m->watch_pids, LONG_TO_PTR(si.si_pid));
1810 UNIT_VTABLE(u)->sigchld_event(u, si.si_pid, si.si_code, si.si_status);
1816 static int manager_start_target(Manager *m, const char *name, JobMode mode) {
1820 dbus_error_init(&error);
1822 log_info("Activating special unit %s", name);
1824 if ((r = manager_add_job_by_name(m, JOB_START, name, mode, true, &error, NULL)) < 0)
1825 log_error("Failed to enqueue %s job: %s", name, bus_error(&error, r));
1827 dbus_error_free(&error);
1832 static int manager_process_signal_fd(Manager *m) {
1834 struct signalfd_siginfo sfsi;
1835 bool sigchld = false;
1840 if ((n = read(m->signal_watch.fd, &sfsi, sizeof(sfsi))) != sizeof(sfsi)) {
1845 if (errno == EAGAIN)
1851 log_debug("Received SIG%s", strna(signal_to_string(sfsi.ssi_signo)));
1853 switch (sfsi.ssi_signo) {
1860 if (m->running_as == MANAGER_SYSTEM) {
1861 /* This is for compatibility with the
1862 * original sysvinit */
1863 m->exit_code = MANAGER_REEXECUTE;
1870 if (m->running_as == MANAGER_SYSTEM) {
1871 manager_start_target(m, SPECIAL_CTRL_ALT_DEL_TARGET, JOB_REPLACE);
1875 /* Run the exit target if there is one, if not, just exit. */
1876 if (manager_start_target(m, SPECIAL_EXIT_SERVICE, JOB_REPLACE) < 0) {
1877 m->exit_code = MANAGER_EXIT;
1884 if (m->running_as == MANAGER_SYSTEM)
1885 manager_start_target(m, SPECIAL_KBREQUEST_TARGET, JOB_REPLACE);
1887 /* This is a nop on non-init */
1891 if (m->running_as == MANAGER_SYSTEM)
1892 manager_start_target(m, SPECIAL_SIGPWR_TARGET, JOB_REPLACE);
1894 /* This is a nop on non-init */
1900 u = manager_get_unit(m, SPECIAL_DBUS_SERVICE);
1902 if (!u || UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u))) {
1903 log_info("Trying to reconnect to bus...");
1907 if (!u || !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u))) {
1908 log_info("Loading D-Bus service...");
1909 manager_start_target(m, SPECIAL_DBUS_SERVICE, JOB_REPLACE);
1920 if (!(f = open_memstream(&dump, &size))) {
1921 log_warning("Failed to allocate memory stream.");
1925 manager_dump_units(m, f, "\t");
1926 manager_dump_jobs(m, f, "\t");
1931 log_warning("Failed to write status stream");
1936 log_dump(LOG_INFO, dump);
1943 m->exit_code = MANAGER_RELOAD;
1947 static const char * const table[] = {
1948 [0] = SPECIAL_DEFAULT_TARGET,
1949 [1] = SPECIAL_RESCUE_TARGET,
1950 [2] = SPECIAL_EMERGENCY_SERVICE,
1951 [3] = SPECIAL_HALT_TARGET,
1952 [4] = SPECIAL_POWEROFF_TARGET,
1953 [5] = SPECIAL_REBOOT_TARGET
1956 if ((int) sfsi.ssi_signo >= SIGRTMIN+0 &&
1957 (int) sfsi.ssi_signo < SIGRTMIN+(int) ELEMENTSOF(table)) {
1958 manager_start_target(m, table[sfsi.ssi_signo - SIGRTMIN],
1959 (sfsi.ssi_signo == 1 || sfsi.ssi_signo == 2) ? JOB_ISOLATE : JOB_REPLACE);
1963 log_warning("Got unhandled signal <%s>.", strna(signal_to_string(sfsi.ssi_signo)));
1969 return manager_dispatch_sigchld(m);
1974 static int process_event(Manager *m, struct epoll_event *ev) {
1981 assert(w = ev->data.ptr);
1987 /* An incoming signal? */
1988 if (ev->events != EPOLLIN)
1991 if ((r = manager_process_signal_fd(m)) < 0)
1998 /* An incoming daemon notification event? */
1999 if (ev->events != EPOLLIN)
2002 if ((r = manager_process_notify_fd(m)) < 0)
2009 /* Some fd event, to be dispatched to the units */
2010 UNIT_VTABLE(w->data.unit)->fd_event(w->data.unit, w->fd, ev->events, w);
2017 /* Some timer event, to be dispatched to the units */
2018 if ((k = read(w->fd, &v, sizeof(v))) != sizeof(v)) {
2020 if (k < 0 && (errno == EINTR || errno == EAGAIN))
2023 return k < 0 ? -errno : -EIO;
2026 UNIT_VTABLE(w->data.unit)->timer_event(w->data.unit, v, w);
2031 /* Some mount table change, intended for the mount subsystem */
2032 mount_fd_event(m, ev->events);
2036 /* Some notification from udev, intended for the device subsystem */
2037 device_fd_event(m, ev->events);
2040 case WATCH_DBUS_WATCH:
2041 bus_watch_event(m, w, ev->events);
2044 case WATCH_DBUS_TIMEOUT:
2045 bus_timeout_event(m, w, ev->events);
2049 assert_not_reached("Unknown epoll event type.");
2055 int manager_loop(Manager *m) {
2058 RATELIMIT_DEFINE(rl, 1*USEC_PER_SEC, 1000);
2061 m->exit_code = MANAGER_RUNNING;
2063 /* Release the path cache */
2064 set_free_free(m->unit_path_cache);
2065 m->unit_path_cache = NULL;
2067 /* There might still be some zombies hanging around from
2068 * before we were exec()'ed. Leat's reap them */
2069 if ((r = manager_dispatch_sigchld(m)) < 0)
2072 while (m->exit_code == MANAGER_RUNNING) {
2073 struct epoll_event event;
2076 if (!ratelimit_test(&rl)) {
2077 /* Yay, something is going seriously wrong, pause a little */
2078 log_warning("Looping too fast. Throttling execution a little.");
2082 if (manager_dispatch_load_queue(m) > 0)
2085 if (manager_dispatch_run_queue(m) > 0)
2088 if (bus_dispatch(m) > 0)
2091 if (manager_dispatch_cleanup_queue(m) > 0)
2094 if (manager_dispatch_gc_queue(m) > 0)
2097 if (manager_dispatch_dbus_queue(m) > 0)
2100 if ((n = epoll_wait(m->epoll_fd, &event, 1, -1)) < 0) {
2110 if ((r = process_event(m, &event)) < 0)
2114 return m->exit_code;
2117 int manager_get_unit_from_dbus_path(Manager *m, const char *s, Unit **_u) {
2125 if (!startswith(s, "/org/freedesktop/systemd1/unit/"))
2128 if (!(n = bus_path_unescape(s+31)))
2131 u = manager_get_unit(m, n);
2142 int manager_get_job_from_dbus_path(Manager *m, const char *s, Job **_j) {
2151 if (!startswith(s, "/org/freedesktop/systemd1/job/"))
2154 if ((r = safe_atou(s + 30, &id)) < 0)
2157 if (!(j = manager_get_job(m, id)))
2165 static bool manager_utmp_good(Manager *m) {
2170 if ((r = mount_path_is_mounted(m, _PATH_UTMPX)) <= 0) {
2173 log_warning("Failed to determine whether " _PATH_UTMPX " is mounted: %s", strerror(-r));
2181 void manager_write_utmp_reboot(Manager *m) {
2186 if (m->utmp_reboot_written)
2189 if (m->running_as != MANAGER_SYSTEM)
2192 if (!manager_utmp_good(m))
2195 if ((r = utmp_put_reboot(m->startup_timestamp.realtime)) < 0) {
2197 if (r != -ENOENT && r != -EROFS)
2198 log_warning("Failed to write utmp/wtmp: %s", strerror(-r));
2203 m->utmp_reboot_written = true;
2206 void manager_write_utmp_runlevel(Manager *m, Unit *u) {
2212 if (u->meta.type != UNIT_TARGET)
2215 if (m->running_as != MANAGER_SYSTEM)
2218 if (!manager_utmp_good(m))
2221 if ((runlevel = target_get_runlevel(TARGET(u))) <= 0)
2224 if ((r = utmp_put_runlevel(0, runlevel, 0)) < 0) {
2226 if (r != -ENOENT && r != -EROFS)
2227 log_warning("Failed to write utmp/wtmp: %s", strerror(-r));
2231 void manager_dispatch_bus_name_owner_changed(
2234 const char* old_owner,
2235 const char *new_owner) {
2242 if (!(u = hashmap_get(m->watch_bus, name)))
2245 UNIT_VTABLE(u)->bus_name_owner_change(u, name, old_owner, new_owner);
2248 void manager_dispatch_bus_query_pid_done(
2259 if (!(u = hashmap_get(m->watch_bus, name)))
2262 UNIT_VTABLE(u)->bus_query_pid_done(u, name, pid);
2265 int manager_open_serialization(FILE **_f) {
2273 if (asprintf(&path, "/dev/shm/systemd-%u.dump-XXXXXX", (unsigned) getpid()) < 0)
2276 saved_umask = umask(0077);
2277 fd = mkostemp(path, O_RDWR|O_CLOEXEC);
2287 log_debug("Serializing state to %s", path);
2290 if (!(f = fdopen(fd, "w+")) < 0)
2298 int manager_serialize(Manager *m, FILE *f, FDSet *fds) {
2308 HASHMAP_FOREACH_KEY(u, t, m->units, i) {
2309 if (u->meta.id != t)
2312 if (!unit_can_serialize(u))
2316 fputs(u->meta.id, f);
2319 if ((r = unit_serialize(u, f, fds)) < 0)
2329 int manager_deserialize(Manager *m, FILE *f, FDSet *fds) {
2335 log_debug("Deserializing state...");
2337 m->deserializing = true;
2341 char name[UNIT_NAME_MAX+2];
2344 if (!fgets(name, sizeof(name), f)) {
2354 if ((r = manager_load_unit(m, strstrip(name), NULL, NULL, &u)) < 0)
2357 if ((r = unit_deserialize(u, f, fds)) < 0)
2369 m->deserializing = false;
2374 int manager_reload(Manager *m) {
2381 if ((r = manager_open_serialization(&f)) < 0)
2384 if (!(fds = fdset_new())) {
2389 if ((r = manager_serialize(m, f, fds)) < 0)
2392 if (fseeko(f, 0, SEEK_SET) < 0) {
2397 /* From here on there is no way back. */
2398 manager_clear_jobs_and_units(m);
2400 /* Find new unit paths */
2401 lookup_paths_free(&m->lookup_paths);
2402 if ((q = lookup_paths_init(&m->lookup_paths, m->running_as)) < 0)
2405 /* First, enumerate what we can from all config files */
2406 if ((q = manager_enumerate(m)) < 0)
2409 /* Second, deserialize our stored data */
2410 if ((q = manager_deserialize(m, f, fds)) < 0)
2416 /* Third, fire things up! */
2417 if ((q = manager_coldplug(m)) < 0)
2430 bool manager_is_booting_or_shutting_down(Manager *m) {
2435 /* Is the initial job still around? */
2436 if (manager_get_job(m, 1))
2439 /* Is there a job for the shutdown target? */
2440 if (((u = manager_get_unit(m, SPECIAL_SHUTDOWN_TARGET))))
2441 return !!u->meta.job;
2446 static const char* const manager_running_as_table[_MANAGER_RUNNING_AS_MAX] = {
2447 [MANAGER_SYSTEM] = "system",
2448 [MANAGER_SESSION] = "session"
2451 DEFINE_STRING_TABLE_LOOKUP(manager_running_as, ManagerRunningAs);