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 /* If we will deserialize make sure that during enumeration
548 * this is already known, so we increase the counter here
551 m->n_deserializing ++;
553 /* First, enumerate what we can from all config files */
554 r = manager_enumerate(m);
556 /* Second, deserialize if there is something to deserialize */
558 if ((q = manager_deserialize(m, serialization, fds)) < 0)
561 /* Third, fire things up! */
562 if ((q = manager_coldplug(m)) < 0)
566 assert(m->n_deserializing > 0);
567 m->n_deserializing --;
570 /* Now that the initial devices are available, let's see if we
571 * can write the utmp file */
572 manager_write_utmp_reboot(m);
577 static void transaction_delete_job(Manager *m, Job *j, bool delete_dependencies) {
581 /* Deletes one job from the transaction */
583 manager_transaction_unlink_job(m, j, delete_dependencies);
589 static void transaction_delete_unit(Manager *m, Unit *u) {
592 /* Deletes all jobs associated with a certain unit from the
595 while ((j = hashmap_get(m->transaction_jobs, u)))
596 transaction_delete_job(m, j, true);
599 static void transaction_clean_dependencies(Manager *m) {
605 /* Drops all dependencies of all installed jobs */
607 HASHMAP_FOREACH(j, m->jobs, i) {
608 while (j->subject_list)
609 job_dependency_free(j->subject_list);
610 while (j->object_list)
611 job_dependency_free(j->object_list);
614 assert(!m->transaction_anchor);
617 static void transaction_abort(Manager *m) {
622 while ((j = hashmap_first(m->transaction_jobs)))
624 transaction_delete_job(m, j, true);
628 assert(hashmap_isempty(m->transaction_jobs));
630 transaction_clean_dependencies(m);
633 static void transaction_find_jobs_that_matter_to_anchor(Manager *m, Job *j, unsigned generation) {
638 /* A recursive sweep through the graph that marks all units
639 * that matter to the anchor job, i.e. are directly or
640 * indirectly a dependency of the anchor job via paths that
641 * are fully marked as mattering. */
646 l = m->transaction_anchor;
648 LIST_FOREACH(subject, l, l) {
650 /* This link does not matter */
654 /* This unit has already been marked */
655 if (l->object->generation == generation)
658 l->object->matters_to_anchor = true;
659 l->object->generation = generation;
661 transaction_find_jobs_that_matter_to_anchor(m, l->object, generation);
665 static void transaction_merge_and_delete_job(Manager *m, Job *j, Job *other, JobType t) {
666 JobDependency *l, *last;
670 assert(j->unit == other->unit);
671 assert(!j->installed);
673 /* Merges 'other' into 'j' and then deletes j. */
676 j->state = JOB_WAITING;
677 j->override = j->override || other->override;
679 j->matters_to_anchor = j->matters_to_anchor || other->matters_to_anchor;
681 /* Patch us in as new owner of the JobDependency objects */
683 LIST_FOREACH(subject, l, other->subject_list) {
684 assert(l->subject == other);
689 /* Merge both lists */
691 last->subject_next = j->subject_list;
693 j->subject_list->subject_prev = last;
694 j->subject_list = other->subject_list;
697 /* Patch us in as new owner of the JobDependency objects */
699 LIST_FOREACH(object, l, other->object_list) {
700 assert(l->object == other);
705 /* Merge both lists */
707 last->object_next = j->object_list;
709 j->object_list->object_prev = last;
710 j->object_list = other->object_list;
713 /* Kill the other job */
714 other->subject_list = NULL;
715 other->object_list = NULL;
716 transaction_delete_job(m, other, true);
718 static bool job_is_conflicted_by(Job *j) {
723 /* Returns true if this job is pulled in by a least one
724 * ConflictedBy dependency. */
726 LIST_FOREACH(object, l, j->object_list)
733 static int delete_one_unmergeable_job(Manager *m, Job *j) {
738 /* Tries to delete one item in the linked list
739 * j->transaction_next->transaction_next->... that conflicts
740 * whith another one, in an attempt to make an inconsistent
741 * transaction work. */
743 /* We rely here on the fact that if a merged with b does not
744 * merge with c, either a or b merge with c neither */
745 LIST_FOREACH(transaction, j, j)
746 LIST_FOREACH(transaction, k, j->transaction_next) {
749 /* Is this one mergeable? Then skip it */
750 if (job_type_is_mergeable(j->type, k->type))
753 /* Ok, we found two that conflict, let's see if we can
754 * drop one of them */
755 if (!j->matters_to_anchor && !k->matters_to_anchor) {
757 /* Both jobs don't matter, so let's
758 * find the one that is smarter to
759 * remove. Let's think positive and
760 * rather remove stops then starts --
761 * except if something is being
762 * stopped because it is conflicted by
763 * another unit in which case we
764 * rather remove the start. */
766 log_debug("Looking at job %s/%s conflicted_by=%s", j->unit->meta.id, job_type_to_string(j->type), yes_no(j->type == JOB_STOP && job_is_conflicted_by(j)));
767 log_debug("Looking at job %s/%s conflicted_by=%s", k->unit->meta.id, job_type_to_string(k->type), yes_no(k->type == JOB_STOP && job_is_conflicted_by(k)));
769 if (j->type == JOB_STOP) {
771 if (job_is_conflicted_by(j))
776 } else if (k->type == JOB_STOP) {
778 if (job_is_conflicted_by(k))
784 } else if (!j->matters_to_anchor)
786 else if (!k->matters_to_anchor)
791 /* Ok, we can drop one, so let's do so. */
792 log_debug("Fixing conflicting jobs by deleting job %s/%s", d->unit->meta.id, job_type_to_string(d->type));
793 transaction_delete_job(m, d, true);
800 static int transaction_merge_jobs(Manager *m, DBusError *e) {
807 /* First step, check whether any of the jobs for one specific
808 * task conflict. If so, try to drop one of them. */
809 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
814 LIST_FOREACH(transaction, k, j->transaction_next) {
815 if ((r = job_type_merge(&t, k->type)) >= 0)
818 /* OK, we could not merge all jobs for this
819 * action. Let's see if we can get rid of one
822 if ((r = delete_one_unmergeable_job(m, j)) >= 0)
823 /* Ok, we managed to drop one, now
824 * let's ask our callers to call us
825 * again after garbage collecting */
828 /* We couldn't merge anything. Failure */
829 dbus_set_error(e, BUS_ERROR_TRANSACTION_JOBS_CONFLICTING, "Transaction contains conflicting jobs '%s' and '%s' for %s. Probably contradicting requirement dependencies configured.",
830 job_type_to_string(t), job_type_to_string(k->type), k->unit->meta.id);
835 /* Second step, merge the jobs. */
836 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
840 /* Merge all transactions */
841 LIST_FOREACH(transaction, k, j->transaction_next)
842 assert_se(job_type_merge(&t, k->type) == 0);
844 /* If an active job is mergeable, merge it too */
845 if (j->unit->meta.job)
846 job_type_merge(&t, j->unit->meta.job->type); /* Might fail. Which is OK */
848 while ((k = j->transaction_next)) {
850 transaction_merge_and_delete_job(m, k, j, t);
853 transaction_merge_and_delete_job(m, j, k, t);
856 assert(!j->transaction_next);
857 assert(!j->transaction_prev);
863 static void transaction_drop_redundant(Manager *m) {
868 /* Goes through the transaction and removes all jobs that are
877 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
878 bool changes_something = false;
881 LIST_FOREACH(transaction, k, j) {
883 if (!job_is_anchor(k) &&
884 job_type_is_redundant(k->type, unit_active_state(k->unit)))
887 changes_something = true;
891 if (changes_something)
894 log_debug("Found redundant job %s/%s, dropping.", j->unit->meta.id, job_type_to_string(j->type));
895 transaction_delete_job(m, j, false);
903 static bool unit_matters_to_anchor(Unit *u, Job *j) {
905 assert(!j->transaction_prev);
907 /* Checks whether at least one of the jobs for this unit
908 * matters to the anchor. */
910 LIST_FOREACH(transaction, j, j)
911 if (j->matters_to_anchor)
917 static int transaction_verify_order_one(Manager *m, Job *j, Job *from, unsigned generation, DBusError *e) {
924 assert(!j->transaction_prev);
926 /* Does a recursive sweep through the ordering graph, looking
927 * for a cycle. If we find cycle we try to break it. */
929 /* Have we seen this before? */
930 if (j->generation == generation) {
933 /* If the marker is NULL we have been here already and
934 * decided the job was loop-free from here. Hence
935 * shortcut things and return right-away. */
939 /* So, the marker is not NULL and we already have been
940 * here. We have a cycle. Let's try to break it. We go
941 * backwards in our path and try to find a suitable
942 * job to remove. We use the marker to find our way
943 * back, since smart how we are we stored our way back
945 log_warning("Found ordering cycle on %s/%s", j->unit->meta.id, job_type_to_string(j->type));
948 for (k = from; k; k = ((k->generation == generation && k->marker != k) ? k->marker : NULL)) {
950 log_info("Walked on cycle path to %s/%s", k->unit->meta.id, job_type_to_string(k->type));
954 !unit_matters_to_anchor(k->unit, k)) {
955 /* Ok, we can drop this one, so let's
960 /* Check if this in fact was the beginning of
968 log_warning("Breaking ordering cycle by deleting job %s/%s", k->unit->meta.id, job_type_to_string(k->type));
969 transaction_delete_unit(m, delete->unit);
973 log_error("Unable to break cycle");
975 dbus_set_error(e, BUS_ERROR_TRANSACTION_ORDER_IS_CYCLIC, "Transaction order is cyclic. See logs for details.");
979 /* Make the marker point to where we come from, so that we can
980 * find our way backwards if we want to break a cycle. We use
981 * a special marker for the beginning: we point to
983 j->marker = from ? from : j;
984 j->generation = generation;
986 /* We assume that the the dependencies are bidirectional, and
987 * hence can ignore UNIT_AFTER */
988 SET_FOREACH(u, j->unit->meta.dependencies[UNIT_BEFORE], i) {
991 /* Is there a job for this unit? */
992 if (!(o = hashmap_get(m->transaction_jobs, u)))
994 /* Ok, there is no job for this in the
995 * transaction, but maybe there is already one
997 if (!(o = u->meta.job))
1000 if ((r = transaction_verify_order_one(m, o, j, generation, e)) < 0)
1004 /* Ok, let's backtrack, and remember that this entry is not on
1005 * our path anymore. */
1011 static int transaction_verify_order(Manager *m, unsigned *generation, DBusError *e) {
1020 /* Check if the ordering graph is cyclic. If it is, try to fix
1021 * that up by dropping one of the jobs. */
1023 g = (*generation)++;
1025 HASHMAP_FOREACH(j, m->transaction_jobs, i)
1026 if ((r = transaction_verify_order_one(m, j, NULL, g, e)) < 0)
1032 static void transaction_collect_garbage(Manager *m) {
1037 /* Drop jobs that are not required by any other job */
1045 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1049 log_debug("Garbage collecting job %s/%s", j->unit->meta.id, job_type_to_string(j->type));
1050 transaction_delete_job(m, j, true);
1058 static int transaction_is_destructive(Manager *m, DBusError *e) {
1064 /* Checks whether applying this transaction means that
1065 * existing jobs would be replaced */
1067 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1070 assert(!j->transaction_prev);
1071 assert(!j->transaction_next);
1073 if (j->unit->meta.job &&
1074 j->unit->meta.job != j &&
1075 !job_type_is_superset(j->type, j->unit->meta.job->type)) {
1077 dbus_set_error(e, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE, "Transaction is destructive.");
1085 static void transaction_minimize_impact(Manager *m) {
1089 /* Drops all unnecessary jobs that reverse already active jobs
1090 * or that stop a running service. */
1098 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1099 LIST_FOREACH(transaction, j, j) {
1100 bool stops_running_service, changes_existing_job;
1102 /* If it matters, we shouldn't drop it */
1103 if (j->matters_to_anchor)
1106 /* Would this stop a running service?
1107 * Would this change an existing job?
1108 * If so, let's drop this entry */
1110 stops_running_service =
1111 j->type == JOB_STOP && UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(j->unit));
1113 changes_existing_job =
1114 j->unit->meta.job && job_type_is_conflicting(j->type, j->unit->meta.job->type);
1116 if (!stops_running_service && !changes_existing_job)
1119 if (stops_running_service)
1120 log_info("%s/%s would stop a running service.", j->unit->meta.id, job_type_to_string(j->type));
1122 if (changes_existing_job)
1123 log_info("%s/%s would change existing job.", j->unit->meta.id, job_type_to_string(j->type));
1125 /* Ok, let's get rid of this */
1126 log_info("Deleting %s/%s to minimize impact.", j->unit->meta.id, job_type_to_string(j->type));
1128 transaction_delete_job(m, j, true);
1140 static int transaction_apply(Manager *m) {
1145 /* Moves the transaction jobs to the set of active jobs */
1147 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1149 assert(!j->transaction_prev);
1150 assert(!j->transaction_next);
1155 if ((r = hashmap_put(m->jobs, UINT32_TO_PTR(j->id), j)) < 0)
1159 while ((j = hashmap_steal_first(m->transaction_jobs))) {
1163 if (j->unit->meta.job)
1164 job_free(j->unit->meta.job);
1166 j->unit->meta.job = j;
1167 j->installed = true;
1169 /* We're fully installed. Now let's free data we don't
1172 assert(!j->transaction_next);
1173 assert(!j->transaction_prev);
1175 job_add_to_run_queue(j);
1176 job_add_to_dbus_queue(j);
1180 /* As last step, kill all remaining job dependencies. */
1181 transaction_clean_dependencies(m);
1187 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1191 hashmap_remove(m->jobs, UINT32_TO_PTR(j->id));
1197 static int transaction_activate(Manager *m, JobMode mode, DBusError *e) {
1199 unsigned generation = 1;
1203 /* This applies the changes recorded in transaction_jobs to
1204 * the actual list of jobs, if possible. */
1206 /* First step: figure out which jobs matter */
1207 transaction_find_jobs_that_matter_to_anchor(m, NULL, generation++);
1209 /* Second step: Try not to stop any running services if
1210 * we don't have to. Don't try to reverse running
1211 * jobs if we don't have to. */
1212 transaction_minimize_impact(m);
1214 /* Third step: Drop redundant jobs */
1215 transaction_drop_redundant(m);
1218 /* Fourth step: Let's remove unneeded jobs that might
1220 transaction_collect_garbage(m);
1222 /* Fifth step: verify order makes sense and correct
1223 * cycles if necessary and possible */
1224 if ((r = transaction_verify_order(m, &generation, e)) >= 0)
1228 log_warning("Requested transaction contains an unfixable cyclic ordering dependency: %s", bus_error(e, r));
1232 /* Let's see if the resulting transaction ordering
1233 * graph is still cyclic... */
1237 /* Sixth step: let's drop unmergeable entries if
1238 * necessary and possible, merge entries we can
1240 if ((r = transaction_merge_jobs(m, e)) >= 0)
1244 log_warning("Requested transaction contains unmergable jobs: %s", bus_error(e, r));
1248 /* Seventh step: an entry got dropped, let's garbage
1249 * collect its dependencies. */
1250 transaction_collect_garbage(m);
1252 /* Let's see if the resulting transaction still has
1253 * unmergeable entries ... */
1256 /* Eights step: Drop redundant jobs again, if the merging now allows us to drop more. */
1257 transaction_drop_redundant(m);
1259 /* Ninth step: check whether we can actually apply this */
1260 if (mode == JOB_FAIL)
1261 if ((r = transaction_is_destructive(m, e)) < 0) {
1262 log_notice("Requested transaction contradicts existing jobs: %s", bus_error(e, r));
1266 /* Tenth step: apply changes */
1267 if ((r = transaction_apply(m)) < 0) {
1268 log_warning("Failed to apply transaction: %s", strerror(-r));
1272 assert(hashmap_isempty(m->transaction_jobs));
1273 assert(!m->transaction_anchor);
1278 transaction_abort(m);
1282 static Job* transaction_add_one_job(Manager *m, JobType type, Unit *unit, bool override, bool *is_new) {
1289 /* Looks for an axisting prospective job and returns that. If
1290 * it doesn't exist it is created and added to the prospective
1293 f = hashmap_get(m->transaction_jobs, unit);
1295 LIST_FOREACH(transaction, j, f) {
1296 assert(j->unit == unit);
1298 if (j->type == type) {
1305 if (unit->meta.job && unit->meta.job->type == type)
1307 else if (!(j = job_new(m, type, unit)))
1312 j->matters_to_anchor = false;
1313 j->override = override;
1315 LIST_PREPEND(Job, transaction, f, j);
1317 if ((r = hashmap_replace(m->transaction_jobs, unit, f)) < 0) {
1325 log_debug("Added job %s/%s to transaction.", unit->meta.id, job_type_to_string(type));
1330 void manager_transaction_unlink_job(Manager *m, Job *j, bool delete_dependencies) {
1334 if (j->transaction_prev)
1335 j->transaction_prev->transaction_next = j->transaction_next;
1336 else if (j->transaction_next)
1337 hashmap_replace(m->transaction_jobs, j->unit, j->transaction_next);
1339 hashmap_remove_value(m->transaction_jobs, j->unit, j);
1341 if (j->transaction_next)
1342 j->transaction_next->transaction_prev = j->transaction_prev;
1344 j->transaction_prev = j->transaction_next = NULL;
1346 while (j->subject_list)
1347 job_dependency_free(j->subject_list);
1349 while (j->object_list) {
1350 Job *other = j->object_list->matters ? j->object_list->subject : NULL;
1352 job_dependency_free(j->object_list);
1354 if (other && delete_dependencies) {
1355 log_debug("Deleting job %s/%s as dependency of job %s/%s",
1356 other->unit->meta.id, job_type_to_string(other->type),
1357 j->unit->meta.id, job_type_to_string(j->type));
1358 transaction_delete_job(m, other, delete_dependencies);
1363 static int transaction_add_job_and_dependencies(
1380 assert(type < _JOB_TYPE_MAX);
1383 if (type != JOB_STOP &&
1384 unit->meta.load_state != UNIT_LOADED) {
1385 dbus_set_error(e, BUS_ERROR_LOAD_FAILED, "Unit %s failed to load. See logs for details.", unit->meta.id);
1389 if (!unit_job_is_applicable(unit, type)) {
1390 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);
1394 /* First add the job. */
1395 if (!(ret = transaction_add_one_job(m, type, unit, override, &is_new)))
1398 /* Then, add a link to the job. */
1399 if (!job_dependency_new(by, ret, matters, conflicts))
1403 /* Finally, recursively add in all dependencies. */
1404 if (type == JOB_START || type == JOB_RELOAD_OR_START) {
1405 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES], i)
1406 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, true, override, false, e, NULL)) < 0 && r != -EBADR)
1409 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES_OVERRIDABLE], i)
1410 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, !override, override, false, e, NULL)) < 0 && r != -EBADR) {
1411 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, bus_error(e, r));
1415 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_WANTS], i)
1416 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, false, false, false, e, NULL)) < 0) {
1417 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, bus_error(e, r));
1421 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE], i)
1422 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, true, override, false, e, NULL)) < 0 && r != -EBADR)
1425 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE_OVERRIDABLE], i)
1426 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, !override, override, false, e, NULL)) < 0 && r != -EBADR) {
1427 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, bus_error(e, r));
1431 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_CONFLICTS], i)
1432 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, dep, ret, true, override, true, e, NULL)) < 0 && r != -EBADR)
1435 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_CONFLICTED_BY], i)
1436 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, dep, ret, true, override, false, e, NULL)) < 0 && r != -EBADR)
1439 } else if (type == JOB_STOP || type == JOB_RESTART || type == JOB_TRY_RESTART) {
1441 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRED_BY], i)
1442 if ((r = transaction_add_job_and_dependencies(m, type, dep, ret, true, override, false, e, NULL)) < 0 && r != -EBADR)
1446 /* JOB_VERIFY_STARTED, JOB_RELOAD require no dependency handling */
1458 static int transaction_add_isolate_jobs(Manager *m) {
1466 HASHMAP_FOREACH_KEY(u, k, m->units, i) {
1468 /* ignore aliases */
1469 if (u->meta.id != k)
1472 if (UNIT_VTABLE(u)->no_isolate)
1475 /* No need to stop inactive jobs */
1476 if (UNIT_IS_INACTIVE_OR_MAINTENANCE(unit_active_state(u)))
1479 /* Is there already something listed for this? */
1480 if (hashmap_get(m->transaction_jobs, u))
1483 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, u, NULL, true, false, false, NULL, NULL)) < 0)
1484 log_warning("Cannot add isolate job for unit %s, ignoring: %s", u->meta.id, strerror(-r));
1490 int manager_add_job(Manager *m, JobType type, Unit *unit, JobMode mode, bool override, DBusError *e, Job **_ret) {
1495 assert(type < _JOB_TYPE_MAX);
1497 assert(mode < _JOB_MODE_MAX);
1499 if (mode == JOB_ISOLATE && type != JOB_START) {
1500 dbus_set_error(e, BUS_ERROR_INVALID_JOB_MODE, "Isolate is only valid for start.");
1504 log_debug("Trying to enqueue job %s/%s", unit->meta.id, job_type_to_string(type));
1506 if ((r = transaction_add_job_and_dependencies(m, type, unit, NULL, true, override, false, e, &ret)) < 0) {
1507 transaction_abort(m);
1511 if (mode == JOB_ISOLATE)
1512 if ((r = transaction_add_isolate_jobs(m)) < 0) {
1513 transaction_abort(m);
1517 if ((r = transaction_activate(m, mode, e)) < 0)
1520 log_debug("Enqueued job %s/%s as %u", unit->meta.id, job_type_to_string(type), (unsigned) ret->id);
1528 int manager_add_job_by_name(Manager *m, JobType type, const char *name, JobMode mode, bool override, DBusError *e, Job **_ret) {
1533 assert(type < _JOB_TYPE_MAX);
1535 assert(mode < _JOB_MODE_MAX);
1537 if ((r = manager_load_unit(m, name, NULL, NULL, &unit)) < 0)
1540 return manager_add_job(m, type, unit, mode, override, e, _ret);
1543 Job *manager_get_job(Manager *m, uint32_t id) {
1546 return hashmap_get(m->jobs, UINT32_TO_PTR(id));
1549 Unit *manager_get_unit(Manager *m, const char *name) {
1553 return hashmap_get(m->units, name);
1556 unsigned manager_dispatch_load_queue(Manager *m) {
1562 /* Make sure we are not run recursively */
1563 if (m->dispatching_load_queue)
1566 m->dispatching_load_queue = true;
1568 /* Dispatches the load queue. Takes a unit from the queue and
1569 * tries to load its data until the queue is empty */
1571 while ((meta = m->load_queue)) {
1572 assert(meta->in_load_queue);
1574 unit_load((Unit*) meta);
1578 m->dispatching_load_queue = false;
1582 int manager_load_unit_prepare(Manager *m, const char *name, const char *path, DBusError *e, Unit **_ret) {
1587 assert(name || path);
1589 /* This will prepare the unit for loading, but not actually
1590 * load anything from disk. */
1592 if (path && !is_path(path)) {
1593 dbus_set_error(e, BUS_ERROR_INVALID_PATH, "Path %s is not absolute.", path);
1598 name = file_name_from_path(path);
1600 if (!unit_name_is_valid(name)) {
1601 dbus_set_error(e, BUS_ERROR_INVALID_NAME, "Unit name %s is not valid.", name);
1605 if ((ret = manager_get_unit(m, name))) {
1610 if (!(ret = unit_new(m)))
1614 if (!(ret->meta.fragment_path = strdup(path))) {
1619 if ((r = unit_add_name(ret, name)) < 0) {
1624 unit_add_to_load_queue(ret);
1625 unit_add_to_dbus_queue(ret);
1626 unit_add_to_gc_queue(ret);
1634 int manager_load_unit(Manager *m, const char *name, const char *path, DBusError *e, Unit **_ret) {
1639 /* This will load the service information files, but not actually
1640 * start any services or anything. */
1642 if ((r = manager_load_unit_prepare(m, name, path, e, _ret)) != 0)
1645 manager_dispatch_load_queue(m);
1648 *_ret = unit_follow_merge(*_ret);
1653 void manager_dump_jobs(Manager *s, FILE *f, const char *prefix) {
1660 HASHMAP_FOREACH(j, s->jobs, i)
1661 job_dump(j, f, prefix);
1664 void manager_dump_units(Manager *s, FILE *f, const char *prefix) {
1672 HASHMAP_FOREACH_KEY(u, t, s->units, i)
1673 if (u->meta.id == t)
1674 unit_dump(u, f, prefix);
1677 void manager_clear_jobs(Manager *m) {
1682 transaction_abort(m);
1684 while ((j = hashmap_first(m->jobs)))
1688 unsigned manager_dispatch_run_queue(Manager *m) {
1692 if (m->dispatching_run_queue)
1695 m->dispatching_run_queue = true;
1697 while ((j = m->run_queue)) {
1698 assert(j->installed);
1699 assert(j->in_run_queue);
1701 job_run_and_invalidate(j);
1705 m->dispatching_run_queue = false;
1709 unsigned manager_dispatch_dbus_queue(Manager *m) {
1716 if (m->dispatching_dbus_queue)
1719 m->dispatching_dbus_queue = true;
1721 while ((meta = m->dbus_unit_queue)) {
1722 assert(meta->in_dbus_queue);
1724 bus_unit_send_change_signal((Unit*) meta);
1728 while ((j = m->dbus_job_queue)) {
1729 assert(j->in_dbus_queue);
1731 bus_job_send_change_signal(j);
1735 m->dispatching_dbus_queue = false;
1739 static int manager_process_notify_fd(Manager *m) {
1746 struct msghdr msghdr;
1748 struct ucred *ucred;
1750 struct cmsghdr cmsghdr;
1751 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
1757 iovec.iov_base = buf;
1758 iovec.iov_len = sizeof(buf)-1;
1762 msghdr.msg_iov = &iovec;
1763 msghdr.msg_iovlen = 1;
1764 msghdr.msg_control = &control;
1765 msghdr.msg_controllen = sizeof(control);
1767 if ((n = recvmsg(m->notify_watch.fd, &msghdr, MSG_DONTWAIT)) <= 0) {
1771 if (errno == EAGAIN)
1777 if (msghdr.msg_controllen < CMSG_LEN(sizeof(struct ucred)) ||
1778 control.cmsghdr.cmsg_level != SOL_SOCKET ||
1779 control.cmsghdr.cmsg_type != SCM_CREDENTIALS ||
1780 control.cmsghdr.cmsg_len != CMSG_LEN(sizeof(struct ucred))) {
1781 log_warning("Received notify message without credentials. Ignoring.");
1785 ucred = (struct ucred*) CMSG_DATA(&control.cmsghdr);
1787 if (!(u = hashmap_get(m->watch_pids, LONG_TO_PTR(ucred->pid))))
1788 if (!(u = cgroup_unit_by_pid(m, ucred->pid))) {
1789 log_warning("Cannot find unit for notify message of PID %lu.", (unsigned long) ucred->pid);
1793 assert((size_t) n < sizeof(buf));
1795 if (!(tags = strv_split(buf, "\n\r")))
1798 log_debug("Got notification message for unit %s", u->meta.id);
1800 if (UNIT_VTABLE(u)->notify_message)
1801 UNIT_VTABLE(u)->notify_message(u, ucred->pid, tags);
1809 static int manager_dispatch_sigchld(Manager *m) {
1819 /* First we call waitd() for a PID and do not reap the
1820 * zombie. That way we can still access /proc/$PID for
1821 * it while it is a zombie. */
1822 if (waitid(P_ALL, 0, &si, WEXITED|WNOHANG|WNOWAIT) < 0) {
1824 if (errno == ECHILD)
1836 if (si.si_code == CLD_EXITED || si.si_code == CLD_KILLED || si.si_code == CLD_DUMPED) {
1839 get_process_name(si.si_pid, &name);
1840 log_debug("Got SIGCHLD for process %lu (%s)", (unsigned long) si.si_pid, strna(name));
1844 /* Let's flush any message the dying child might still
1845 * have queued for us. This ensures that the process
1846 * still exists in /proc so that we can figure out
1847 * which cgroup and hence unit it belongs to. */
1848 if ((r = manager_process_notify_fd(m)) < 0)
1851 /* And now figure out the unit this belongs to */
1852 if (!(u = hashmap_get(m->watch_pids, LONG_TO_PTR(si.si_pid))))
1853 u = cgroup_unit_by_pid(m, si.si_pid);
1855 /* And now, we actually reap the zombie. */
1856 if (waitid(P_PID, si.si_pid, &si, WEXITED) < 0) {
1863 if (si.si_code != CLD_EXITED && si.si_code != CLD_KILLED && si.si_code != CLD_DUMPED)
1866 log_debug("Child %lu died (code=%s, status=%i/%s)",
1867 (long unsigned) si.si_pid,
1868 sigchld_code_to_string(si.si_code),
1870 strna(si.si_code == CLD_EXITED ? exit_status_to_string(si.si_status) : signal_to_string(si.si_status)));
1875 log_debug("Child %lu belongs to %s", (long unsigned) si.si_pid, u->meta.id);
1877 hashmap_remove(m->watch_pids, LONG_TO_PTR(si.si_pid));
1878 UNIT_VTABLE(u)->sigchld_event(u, si.si_pid, si.si_code, si.si_status);
1884 static int manager_start_target(Manager *m, const char *name, JobMode mode) {
1888 dbus_error_init(&error);
1890 log_info("Activating special unit %s", name);
1892 if ((r = manager_add_job_by_name(m, JOB_START, name, mode, true, &error, NULL)) < 0)
1893 log_error("Failed to enqueue %s job: %s", name, bus_error(&error, r));
1895 dbus_error_free(&error);
1900 static int manager_process_signal_fd(Manager *m) {
1902 struct signalfd_siginfo sfsi;
1903 bool sigchld = false;
1908 if ((n = read(m->signal_watch.fd, &sfsi, sizeof(sfsi))) != sizeof(sfsi)) {
1913 if (errno == EAGAIN)
1919 log_debug("Received SIG%s", strna(signal_to_string(sfsi.ssi_signo)));
1921 switch (sfsi.ssi_signo) {
1928 if (m->running_as == MANAGER_SYSTEM) {
1929 /* This is for compatibility with the
1930 * original sysvinit */
1931 m->exit_code = MANAGER_REEXECUTE;
1938 if (m->running_as == MANAGER_SYSTEM) {
1939 manager_start_target(m, SPECIAL_CTRL_ALT_DEL_TARGET, JOB_REPLACE);
1943 /* Run the exit target if there is one, if not, just exit. */
1944 if (manager_start_target(m, SPECIAL_EXIT_SERVICE, JOB_REPLACE) < 0) {
1945 m->exit_code = MANAGER_EXIT;
1952 if (m->running_as == MANAGER_SYSTEM)
1953 manager_start_target(m, SPECIAL_KBREQUEST_TARGET, JOB_REPLACE);
1955 /* This is a nop on non-init */
1959 if (m->running_as == MANAGER_SYSTEM)
1960 manager_start_target(m, SPECIAL_SIGPWR_TARGET, JOB_REPLACE);
1962 /* This is a nop on non-init */
1968 u = manager_get_unit(m, SPECIAL_DBUS_SERVICE);
1970 if (!u || UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u))) {
1971 log_info("Trying to reconnect to bus...");
1975 if (!u || !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u))) {
1976 log_info("Loading D-Bus service...");
1977 manager_start_target(m, SPECIAL_DBUS_SERVICE, JOB_REPLACE);
1988 if (!(f = open_memstream(&dump, &size))) {
1989 log_warning("Failed to allocate memory stream.");
1993 manager_dump_units(m, f, "\t");
1994 manager_dump_jobs(m, f, "\t");
1999 log_warning("Failed to write status stream");
2004 log_dump(LOG_INFO, dump);
2011 m->exit_code = MANAGER_RELOAD;
2015 static const char * const table[] = {
2016 [0] = SPECIAL_DEFAULT_TARGET,
2017 [1] = SPECIAL_RESCUE_TARGET,
2018 [2] = SPECIAL_EMERGENCY_TARGET,
2019 [3] = SPECIAL_HALT_TARGET,
2020 [4] = SPECIAL_POWEROFF_TARGET,
2021 [5] = SPECIAL_REBOOT_TARGET
2024 if ((int) sfsi.ssi_signo >= SIGRTMIN+0 &&
2025 (int) sfsi.ssi_signo < SIGRTMIN+(int) ELEMENTSOF(table)) {
2026 manager_start_target(m, table[sfsi.ssi_signo - SIGRTMIN],
2027 (sfsi.ssi_signo == 1 || sfsi.ssi_signo == 2) ? JOB_ISOLATE : JOB_REPLACE);
2031 log_warning("Got unhandled signal <%s>.", strna(signal_to_string(sfsi.ssi_signo)));
2037 return manager_dispatch_sigchld(m);
2042 static int process_event(Manager *m, struct epoll_event *ev) {
2049 assert(w = ev->data.ptr);
2055 /* An incoming signal? */
2056 if (ev->events != EPOLLIN)
2059 if ((r = manager_process_signal_fd(m)) < 0)
2066 /* An incoming daemon notification event? */
2067 if (ev->events != EPOLLIN)
2070 if ((r = manager_process_notify_fd(m)) < 0)
2077 /* Some fd event, to be dispatched to the units */
2078 UNIT_VTABLE(w->data.unit)->fd_event(w->data.unit, w->fd, ev->events, w);
2081 case WATCH_UNIT_TIMER:
2082 case WATCH_JOB_TIMER: {
2086 /* Some timer event, to be dispatched to the units */
2087 if ((k = read(w->fd, &v, sizeof(v))) != sizeof(v)) {
2089 if (k < 0 && (errno == EINTR || errno == EAGAIN))
2092 return k < 0 ? -errno : -EIO;
2095 if (w->type == WATCH_UNIT_TIMER)
2096 UNIT_VTABLE(w->data.unit)->timer_event(w->data.unit, v, w);
2098 job_timer_event(w->data.job, v, w);
2103 /* Some mount table change, intended for the mount subsystem */
2104 mount_fd_event(m, ev->events);
2108 /* Some notification from udev, intended for the device subsystem */
2109 device_fd_event(m, ev->events);
2112 case WATCH_DBUS_WATCH:
2113 bus_watch_event(m, w, ev->events);
2116 case WATCH_DBUS_TIMEOUT:
2117 bus_timeout_event(m, w, ev->events);
2121 assert_not_reached("Unknown epoll event type.");
2127 int manager_loop(Manager *m) {
2130 RATELIMIT_DEFINE(rl, 1*USEC_PER_SEC, 1000);
2133 m->exit_code = MANAGER_RUNNING;
2135 /* Release the path cache */
2136 set_free_free(m->unit_path_cache);
2137 m->unit_path_cache = NULL;
2139 /* There might still be some zombies hanging around from
2140 * before we were exec()'ed. Leat's reap them */
2141 if ((r = manager_dispatch_sigchld(m)) < 0)
2144 while (m->exit_code == MANAGER_RUNNING) {
2145 struct epoll_event event;
2148 if (!ratelimit_test(&rl)) {
2149 /* Yay, something is going seriously wrong, pause a little */
2150 log_warning("Looping too fast. Throttling execution a little.");
2154 if (manager_dispatch_load_queue(m) > 0)
2157 if (manager_dispatch_run_queue(m) > 0)
2160 if (bus_dispatch(m) > 0)
2163 if (manager_dispatch_cleanup_queue(m) > 0)
2166 if (manager_dispatch_gc_queue(m) > 0)
2169 if (manager_dispatch_dbus_queue(m) > 0)
2172 if ((n = epoll_wait(m->epoll_fd, &event, 1, -1)) < 0) {
2182 if ((r = process_event(m, &event)) < 0)
2186 return m->exit_code;
2189 int manager_get_unit_from_dbus_path(Manager *m, const char *s, Unit **_u) {
2197 if (!startswith(s, "/org/freedesktop/systemd1/unit/"))
2200 if (!(n = bus_path_unescape(s+31)))
2203 u = manager_get_unit(m, n);
2214 int manager_get_job_from_dbus_path(Manager *m, const char *s, Job **_j) {
2223 if (!startswith(s, "/org/freedesktop/systemd1/job/"))
2226 if ((r = safe_atou(s + 30, &id)) < 0)
2229 if (!(j = manager_get_job(m, id)))
2237 static bool manager_utmp_good(Manager *m) {
2242 if ((r = mount_path_is_mounted(m, _PATH_UTMPX)) <= 0) {
2245 log_warning("Failed to determine whether " _PATH_UTMPX " is mounted: %s", strerror(-r));
2253 void manager_write_utmp_reboot(Manager *m) {
2258 if (m->utmp_reboot_written)
2261 if (m->running_as != MANAGER_SYSTEM)
2264 if (!manager_utmp_good(m))
2267 if ((r = utmp_put_reboot(m->startup_timestamp.realtime)) < 0) {
2269 if (r != -ENOENT && r != -EROFS)
2270 log_warning("Failed to write utmp/wtmp: %s", strerror(-r));
2275 m->utmp_reboot_written = true;
2278 void manager_write_utmp_runlevel(Manager *m, Unit *u) {
2284 if (u->meta.type != UNIT_TARGET)
2287 if (m->running_as != MANAGER_SYSTEM)
2290 if (!manager_utmp_good(m))
2293 if ((runlevel = target_get_runlevel(TARGET(u))) <= 0)
2296 if ((r = utmp_put_runlevel(0, runlevel, 0)) < 0) {
2298 if (r != -ENOENT && r != -EROFS)
2299 log_warning("Failed to write utmp/wtmp: %s", strerror(-r));
2303 void manager_dispatch_bus_name_owner_changed(
2306 const char* old_owner,
2307 const char *new_owner) {
2314 if (!(u = hashmap_get(m->watch_bus, name)))
2317 UNIT_VTABLE(u)->bus_name_owner_change(u, name, old_owner, new_owner);
2320 void manager_dispatch_bus_query_pid_done(
2331 if (!(u = hashmap_get(m->watch_bus, name)))
2334 UNIT_VTABLE(u)->bus_query_pid_done(u, name, pid);
2337 int manager_open_serialization(Manager *m, FILE **_f) {
2345 if (m->running_as == MANAGER_SYSTEM) {
2346 mkdir_p("/dev/.systemd", 0755);
2348 if (asprintf(&path, "/dev/.systemd/dump-%lu-XXXXXX", (unsigned long) getpid()) < 0)
2351 if (asprintf(&path, "/tmp/systemd-dump-%lu-XXXXXX", (unsigned long) getpid()) < 0)
2355 saved_umask = umask(0077);
2356 fd = mkostemp(path, O_RDWR|O_CLOEXEC);
2366 log_debug("Serializing state to %s", path);
2369 if (!(f = fdopen(fd, "w+")) < 0)
2377 int manager_serialize(Manager *m, FILE *f, FDSet *fds) {
2387 HASHMAP_FOREACH_KEY(u, t, m->units, i) {
2388 if (u->meta.id != t)
2391 if (!unit_can_serialize(u))
2395 fputs(u->meta.id, f);
2398 if ((r = unit_serialize(u, f, fds)) < 0)
2408 int manager_deserialize(Manager *m, FILE *f, FDSet *fds) {
2414 log_debug("Deserializing state...");
2416 m->n_deserializing ++;
2420 char name[UNIT_NAME_MAX+2];
2423 if (!fgets(name, sizeof(name), f)) {
2433 if ((r = manager_load_unit(m, strstrip(name), NULL, NULL, &u)) < 0)
2436 if ((r = unit_deserialize(u, f, fds)) < 0)
2448 assert(m->n_deserializing > 0);
2449 m->n_deserializing --;
2454 int manager_reload(Manager *m) {
2461 if ((r = manager_open_serialization(m, &f)) < 0)
2464 if (!(fds = fdset_new())) {
2469 if ((r = manager_serialize(m, f, fds)) < 0)
2472 if (fseeko(f, 0, SEEK_SET) < 0) {
2477 /* From here on there is no way back. */
2478 manager_clear_jobs_and_units(m);
2480 /* Find new unit paths */
2481 lookup_paths_free(&m->lookup_paths);
2482 if ((q = lookup_paths_init(&m->lookup_paths, m->running_as)) < 0)
2485 m->n_deserializing ++;
2487 /* First, enumerate what we can from all config files */
2488 if ((q = manager_enumerate(m)) < 0)
2491 /* Second, deserialize our stored data */
2492 if ((q = manager_deserialize(m, f, fds)) < 0)
2498 /* Third, fire things up! */
2499 if ((q = manager_coldplug(m)) < 0)
2502 assert(m->n_deserializing > 0);
2503 m->n_deserializing ++;
2515 bool manager_is_booting_or_shutting_down(Manager *m) {
2520 /* Is the initial job still around? */
2521 if (manager_get_job(m, 1))
2524 /* Is there a job for the shutdown target? */
2525 if (((u = manager_get_unit(m, SPECIAL_SHUTDOWN_TARGET))))
2526 return !!u->meta.job;
2531 void manager_reset_maintenance(Manager *m) {
2537 HASHMAP_FOREACH(u, m->units, i)
2538 unit_reset_maintenance(u);
2541 static const char* const manager_running_as_table[_MANAGER_RUNNING_AS_MAX] = {
2542 [MANAGER_SYSTEM] = "system",
2543 [MANAGER_SESSION] = "session"
2546 DEFINE_STRING_TABLE_LOOKUP(manager_running_as, ManagerRunningAs);