1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
25 #include <sys/epoll.h>
27 #include <sys/signalfd.h>
31 #include <sys/reboot.h>
32 #include <sys/ioctl.h>
36 #include <sys/types.h>
47 #include "ratelimit.h"
49 #include "mount-setup.h"
50 #include "unit-name.h"
51 #include "dbus-unit.h"
54 #include "path-lookup.h"
56 #include "bus-errors.h"
58 /* As soon as 16 units are in our GC queue, make sure to run a gc sweep */
59 #define GC_QUEUE_ENTRIES_MAX 16
61 /* As soon as 5s passed since a unit was added to our GC queue, make sure to run a gc sweep */
62 #define GC_QUEUE_USEC_MAX (10*USEC_PER_SEC)
64 /* Where clients shall send notification messages to */
65 #define NOTIFY_SOCKET "/org/freedesktop/systemd1/notify"
67 static int manager_setup_notify(Manager *m) {
70 struct sockaddr_un un;
72 struct epoll_event ev;
77 m->notify_watch.type = WATCH_NOTIFY;
78 if ((m->notify_watch.fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0)) < 0) {
79 log_error("Failed to allocate notification socket: %m");
84 sa.sa.sa_family = AF_UNIX;
87 snprintf(sa.un.sun_path+1, sizeof(sa.un.sun_path)-1, NOTIFY_SOCKET "/%llu", random_ull());
89 strncpy(sa.un.sun_path+1, NOTIFY_SOCKET, sizeof(sa.un.sun_path)-1);
91 if (bind(m->notify_watch.fd, &sa.sa, sizeof(sa_family_t) + 1 + strlen(sa.un.sun_path+1)) < 0) {
92 log_error("bind() failed: %m");
96 if (setsockopt(m->notify_watch.fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one)) < 0) {
97 log_error("SO_PASSCRED failed: %m");
103 ev.data.ptr = &m->notify_watch;
105 if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->notify_watch.fd, &ev) < 0)
108 if (!(m->notify_socket = strdup(sa.un.sun_path+1)))
114 static int enable_special_signals(Manager *m) {
119 /* Enable that we get SIGINT on control-alt-del */
120 if (reboot(RB_DISABLE_CAD) < 0)
121 log_warning("Failed to enable ctrl-alt-del handling: %m");
123 if ((fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY)) < 0)
124 log_warning("Failed to open /dev/tty0: %m");
126 /* Enable that we get SIGWINCH on kbrequest */
127 if (ioctl(fd, KDSIGACCEPT, SIGWINCH) < 0)
128 log_warning("Failed to enable kbrequest handling: %s", strerror(errno));
130 close_nointr_nofail(fd);
136 static int manager_setup_signals(Manager *m) {
138 struct epoll_event ev;
143 /* We are not interested in SIGSTOP and friends. */
145 sa.sa_handler = SIG_DFL;
146 sa.sa_flags = SA_NOCLDSTOP|SA_RESTART;
147 assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);
149 assert_se(sigemptyset(&mask) == 0);
151 sigset_add_many(&mask,
152 SIGCHLD, /* Child died */
153 SIGTERM, /* Reexecute daemon */
154 SIGHUP, /* Reload configuration */
155 SIGUSR1, /* systemd/upstart: reconnect to D-Bus */
156 SIGUSR2, /* systemd: dump status */
157 SIGINT, /* Kernel sends us this on control-alt-del */
158 SIGWINCH, /* Kernel sends us this on kbrequest (alt-arrowup) */
159 SIGPWR, /* Some kernel drivers and upsd send us this on power failure */
160 SIGRTMIN+0, /* systemd: start default.target */
161 SIGRTMIN+1, /* systemd: start rescue.target */
162 SIGRTMIN+2, /* systemd: isolate emergency.target */
163 SIGRTMIN+3, /* systemd: start halt.target */
164 SIGRTMIN+4, /* systemd: start poweroff.target */
165 SIGRTMIN+5, /* systemd: start reboot.target */
167 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
169 m->signal_watch.type = WATCH_SIGNAL;
170 if ((m->signal_watch.fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0)
175 ev.data.ptr = &m->signal_watch;
177 if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->signal_watch.fd, &ev) < 0)
180 if (m->running_as == MANAGER_SYSTEM)
181 return enable_special_signals(m);
186 int manager_new(ManagerRunningAs running_as, Manager **_m) {
191 assert(running_as >= 0);
192 assert(running_as < _MANAGER_RUNNING_AS_MAX);
194 if (!(m = new0(Manager, 1)))
197 dual_timestamp_get(&m->startup_timestamp);
199 m->running_as = running_as;
200 m->name_data_slot = m->subscribed_data_slot = -1;
201 m->exit_code = _MANAGER_EXIT_CODE_INVALID;
202 m->pin_cgroupfs_fd = -1;
208 m->signal_watch.fd = m->mount_watch.fd = m->udev_watch.fd = m->epoll_fd = m->dev_autofs_fd = -1;
209 m->current_job_id = 1; /* start as id #1, so that we can leave #0 around as "null-like" value */
211 if (!(m->environment = strv_copy(environ)))
214 if (!(m->units = hashmap_new(string_hash_func, string_compare_func)))
217 if (!(m->jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
220 if (!(m->transaction_jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
223 if (!(m->watch_pids = hashmap_new(trivial_hash_func, trivial_compare_func)))
226 if (!(m->cgroup_bondings = hashmap_new(string_hash_func, string_compare_func)))
229 if (!(m->watch_bus = hashmap_new(string_hash_func, string_compare_func)))
232 if ((m->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0)
235 if ((r = lookup_paths_init(&m->lookup_paths, m->running_as)) < 0)
238 if ((r = manager_setup_signals(m)) < 0)
241 if ((r = manager_setup_cgroup(m)) < 0)
244 if ((r = manager_setup_notify(m)) < 0)
247 /* Try to connect to the busses, if possible. */
248 if ((r = bus_init(m)) < 0)
251 if ((m->audit_fd = audit_open()) < 0)
252 log_error("Failed to connect to audit log: %m");
262 static unsigned manager_dispatch_cleanup_queue(Manager *m) {
268 while ((meta = m->cleanup_queue)) {
269 assert(meta->in_cleanup_queue);
271 unit_free((Unit*) meta);
279 GC_OFFSET_IN_PATH, /* This one is on the path we were travelling */
280 GC_OFFSET_UNSURE, /* No clue */
281 GC_OFFSET_GOOD, /* We still need this unit */
282 GC_OFFSET_BAD, /* We don't need this unit anymore */
286 static void unit_gc_sweep(Unit *u, unsigned gc_marker) {
293 if (u->meta.gc_marker == gc_marker + GC_OFFSET_GOOD ||
294 u->meta.gc_marker == gc_marker + GC_OFFSET_BAD ||
295 u->meta.gc_marker == gc_marker + GC_OFFSET_IN_PATH)
298 if (u->meta.in_cleanup_queue)
301 if (unit_check_gc(u))
304 u->meta.gc_marker = gc_marker + GC_OFFSET_IN_PATH;
308 SET_FOREACH(other, u->meta.dependencies[UNIT_REFERENCED_BY], i) {
309 unit_gc_sweep(other, gc_marker);
311 if (other->meta.gc_marker == gc_marker + GC_OFFSET_GOOD)
314 if (other->meta.gc_marker != gc_marker + GC_OFFSET_BAD)
321 /* We were unable to find anything out about this entry, so
322 * let's investigate it later */
323 u->meta.gc_marker = gc_marker + GC_OFFSET_UNSURE;
324 unit_add_to_gc_queue(u);
328 /* We definitely know that this one is not useful anymore, so
329 * let's mark it for deletion */
330 u->meta.gc_marker = gc_marker + GC_OFFSET_BAD;
331 unit_add_to_cleanup_queue(u);
335 u->meta.gc_marker = gc_marker + GC_OFFSET_GOOD;
338 static unsigned manager_dispatch_gc_queue(Manager *m) {
345 if ((m->n_in_gc_queue < GC_QUEUE_ENTRIES_MAX) &&
346 (m->gc_queue_timestamp <= 0 ||
347 (m->gc_queue_timestamp + GC_QUEUE_USEC_MAX) > now(CLOCK_MONOTONIC)))
350 log_debug("Running GC...");
352 m->gc_marker += _GC_OFFSET_MAX;
353 if (m->gc_marker + _GC_OFFSET_MAX <= _GC_OFFSET_MAX)
356 gc_marker = m->gc_marker;
358 while ((meta = m->gc_queue)) {
359 assert(meta->in_gc_queue);
361 unit_gc_sweep((Unit*) meta, gc_marker);
363 LIST_REMOVE(Meta, gc_queue, m->gc_queue, meta);
364 meta->in_gc_queue = false;
368 if (meta->gc_marker == gc_marker + GC_OFFSET_BAD ||
369 meta->gc_marker == gc_marker + GC_OFFSET_UNSURE) {
370 log_debug("Collecting %s", meta->id);
371 meta->gc_marker = gc_marker + GC_OFFSET_BAD;
372 unit_add_to_cleanup_queue((Unit*) meta);
376 m->n_in_gc_queue = 0;
377 m->gc_queue_timestamp = 0;
382 static void manager_clear_jobs_and_units(Manager *m) {
388 while ((j = hashmap_first(m->transaction_jobs)))
391 while ((u = hashmap_first(m->units)))
394 manager_dispatch_cleanup_queue(m);
396 assert(!m->load_queue);
397 assert(!m->run_queue);
398 assert(!m->dbus_unit_queue);
399 assert(!m->dbus_job_queue);
400 assert(!m->cleanup_queue);
401 assert(!m->gc_queue);
403 assert(hashmap_isempty(m->transaction_jobs));
404 assert(hashmap_isempty(m->jobs));
405 assert(hashmap_isempty(m->units));
408 void manager_free(Manager *m) {
413 manager_clear_jobs_and_units(m);
415 for (c = 0; c < _UNIT_TYPE_MAX; c++)
416 if (unit_vtable[c]->shutdown)
417 unit_vtable[c]->shutdown(m);
419 /* If we reexecute ourselves, we keep the root cgroup
421 manager_shutdown_cgroup(m, m->exit_code != MANAGER_REEXECUTE);
425 hashmap_free(m->units);
426 hashmap_free(m->jobs);
427 hashmap_free(m->transaction_jobs);
428 hashmap_free(m->watch_pids);
429 hashmap_free(m->watch_bus);
431 if (m->epoll_fd >= 0)
432 close_nointr_nofail(m->epoll_fd);
433 if (m->signal_watch.fd >= 0)
434 close_nointr_nofail(m->signal_watch.fd);
435 if (m->notify_watch.fd >= 0)
436 close_nointr_nofail(m->notify_watch.fd);
439 if (m->audit_fd >= 0)
440 audit_close(m->audit_fd);
443 free(m->notify_socket);
445 lookup_paths_free(&m->lookup_paths);
446 strv_free(m->environment);
448 hashmap_free(m->cgroup_bondings);
449 set_free_free(m->unit_path_cache);
454 int manager_enumerate(Manager *m) {
460 /* Let's ask every type to load all units from disk/kernel
461 * that it might know */
462 for (c = 0; c < _UNIT_TYPE_MAX; c++)
463 if (unit_vtable[c]->enumerate)
464 if ((q = unit_vtable[c]->enumerate(m)) < 0)
467 manager_dispatch_load_queue(m);
471 int manager_coldplug(Manager *m) {
479 /* Then, let's set up their initial state. */
480 HASHMAP_FOREACH_KEY(u, k, m->units, i) {
486 if ((q = unit_coldplug(u)) < 0)
493 static void manager_build_unit_path_cache(Manager *m) {
500 set_free_free(m->unit_path_cache);
502 if (!(m->unit_path_cache = set_new(string_hash_func, string_compare_func))) {
503 log_error("Failed to allocate unit path cache.");
507 /* This simply builds a list of files we know exist, so that
508 * we don't always have to go to disk */
510 STRV_FOREACH(i, m->lookup_paths.unit_path) {
513 if (!(d = opendir(*i))) {
514 log_error("Failed to open directory: %m");
518 while ((de = readdir(d))) {
521 if (ignore_file(de->d_name))
524 if (asprintf(&p, "%s/%s", streq(*i, "/") ? "" : *i, de->d_name) < 0) {
529 if ((r = set_put(m->unit_path_cache, p)) < 0) {
542 log_error("Failed to build unit path cache: %s", strerror(-r));
544 set_free_free(m->unit_path_cache);
545 m->unit_path_cache = NULL;
551 int manager_startup(Manager *m, FILE *serialization, FDSet *fds) {
556 manager_build_unit_path_cache(m);
558 /* If we will deserialize make sure that during enumeration
559 * this is already known, so we increase the counter here
562 m->n_deserializing ++;
564 /* First, enumerate what we can from all config files */
565 r = manager_enumerate(m);
567 /* Second, deserialize if there is something to deserialize */
569 if ((q = manager_deserialize(m, serialization, fds)) < 0)
572 /* Third, fire things up! */
573 if ((q = manager_coldplug(m)) < 0)
577 assert(m->n_deserializing > 0);
578 m->n_deserializing --;
584 static void transaction_delete_job(Manager *m, Job *j, bool delete_dependencies) {
588 /* Deletes one job from the transaction */
590 manager_transaction_unlink_job(m, j, delete_dependencies);
596 static void transaction_delete_unit(Manager *m, Unit *u) {
599 /* Deletes all jobs associated with a certain unit from the
602 while ((j = hashmap_get(m->transaction_jobs, u)))
603 transaction_delete_job(m, j, true);
606 static void transaction_clean_dependencies(Manager *m) {
612 /* Drops all dependencies of all installed jobs */
614 HASHMAP_FOREACH(j, m->jobs, i) {
615 while (j->subject_list)
616 job_dependency_free(j->subject_list);
617 while (j->object_list)
618 job_dependency_free(j->object_list);
621 assert(!m->transaction_anchor);
624 static void transaction_abort(Manager *m) {
629 while ((j = hashmap_first(m->transaction_jobs)))
631 transaction_delete_job(m, j, true);
635 assert(hashmap_isempty(m->transaction_jobs));
637 transaction_clean_dependencies(m);
640 static void transaction_find_jobs_that_matter_to_anchor(Manager *m, Job *j, unsigned generation) {
645 /* A recursive sweep through the graph that marks all units
646 * that matter to the anchor job, i.e. are directly or
647 * indirectly a dependency of the anchor job via paths that
648 * are fully marked as mattering. */
653 l = m->transaction_anchor;
655 LIST_FOREACH(subject, l, l) {
657 /* This link does not matter */
661 /* This unit has already been marked */
662 if (l->object->generation == generation)
665 l->object->matters_to_anchor = true;
666 l->object->generation = generation;
668 transaction_find_jobs_that_matter_to_anchor(m, l->object, generation);
672 static void transaction_merge_and_delete_job(Manager *m, Job *j, Job *other, JobType t) {
673 JobDependency *l, *last;
677 assert(j->unit == other->unit);
678 assert(!j->installed);
680 /* Merges 'other' into 'j' and then deletes j. */
683 j->state = JOB_WAITING;
684 j->override = j->override || other->override;
686 j->matters_to_anchor = j->matters_to_anchor || other->matters_to_anchor;
688 /* Patch us in as new owner of the JobDependency objects */
690 LIST_FOREACH(subject, l, other->subject_list) {
691 assert(l->subject == other);
696 /* Merge both lists */
698 last->subject_next = j->subject_list;
700 j->subject_list->subject_prev = last;
701 j->subject_list = other->subject_list;
704 /* Patch us in as new owner of the JobDependency objects */
706 LIST_FOREACH(object, l, other->object_list) {
707 assert(l->object == other);
712 /* Merge both lists */
714 last->object_next = j->object_list;
716 j->object_list->object_prev = last;
717 j->object_list = other->object_list;
720 /* Kill the other job */
721 other->subject_list = NULL;
722 other->object_list = NULL;
723 transaction_delete_job(m, other, true);
725 static bool job_is_conflicted_by(Job *j) {
730 /* Returns true if this job is pulled in by a least one
731 * ConflictedBy dependency. */
733 LIST_FOREACH(object, l, j->object_list)
740 static int delete_one_unmergeable_job(Manager *m, Job *j) {
745 /* Tries to delete one item in the linked list
746 * j->transaction_next->transaction_next->... that conflicts
747 * whith another one, in an attempt to make an inconsistent
748 * transaction work. */
750 /* We rely here on the fact that if a merged with b does not
751 * merge with c, either a or b merge with c neither */
752 LIST_FOREACH(transaction, j, j)
753 LIST_FOREACH(transaction, k, j->transaction_next) {
756 /* Is this one mergeable? Then skip it */
757 if (job_type_is_mergeable(j->type, k->type))
760 /* Ok, we found two that conflict, let's see if we can
761 * drop one of them */
762 if (!j->matters_to_anchor && !k->matters_to_anchor) {
764 /* Both jobs don't matter, so let's
765 * find the one that is smarter to
766 * remove. Let's think positive and
767 * rather remove stops then starts --
768 * except if something is being
769 * stopped because it is conflicted by
770 * another unit in which case we
771 * rather remove the start. */
773 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)));
774 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)));
776 if (j->type == JOB_STOP) {
778 if (job_is_conflicted_by(j))
783 } else if (k->type == JOB_STOP) {
785 if (job_is_conflicted_by(k))
791 } else if (!j->matters_to_anchor)
793 else if (!k->matters_to_anchor)
798 /* Ok, we can drop one, so let's do so. */
799 log_debug("Fixing conflicting jobs by deleting job %s/%s", d->unit->meta.id, job_type_to_string(d->type));
800 transaction_delete_job(m, d, true);
807 static int transaction_merge_jobs(Manager *m, DBusError *e) {
814 /* First step, check whether any of the jobs for one specific
815 * task conflict. If so, try to drop one of them. */
816 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
821 LIST_FOREACH(transaction, k, j->transaction_next) {
822 if ((r = job_type_merge(&t, k->type)) >= 0)
825 /* OK, we could not merge all jobs for this
826 * action. Let's see if we can get rid of one
829 if ((r = delete_one_unmergeable_job(m, j)) >= 0)
830 /* Ok, we managed to drop one, now
831 * let's ask our callers to call us
832 * again after garbage collecting */
835 /* We couldn't merge anything. Failure */
836 dbus_set_error(e, BUS_ERROR_TRANSACTION_JOBS_CONFLICTING, "Transaction contains conflicting jobs '%s' and '%s' for %s. Probably contradicting requirement dependencies configured.",
837 job_type_to_string(t), job_type_to_string(k->type), k->unit->meta.id);
842 /* Second step, merge the jobs. */
843 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
847 /* Merge all transactions */
848 LIST_FOREACH(transaction, k, j->transaction_next)
849 assert_se(job_type_merge(&t, k->type) == 0);
851 /* If an active job is mergeable, merge it too */
852 if (j->unit->meta.job)
853 job_type_merge(&t, j->unit->meta.job->type); /* Might fail. Which is OK */
855 while ((k = j->transaction_next)) {
857 transaction_merge_and_delete_job(m, k, j, t);
860 transaction_merge_and_delete_job(m, j, k, t);
863 assert(!j->transaction_next);
864 assert(!j->transaction_prev);
870 static void transaction_drop_redundant(Manager *m) {
875 /* Goes through the transaction and removes all jobs that are
884 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
885 bool changes_something = false;
888 LIST_FOREACH(transaction, k, j) {
890 if (!job_is_anchor(k) &&
891 job_type_is_redundant(k->type, unit_active_state(k->unit)))
894 changes_something = true;
898 if (changes_something)
901 log_debug("Found redundant job %s/%s, dropping.", j->unit->meta.id, job_type_to_string(j->type));
902 transaction_delete_job(m, j, false);
910 static bool unit_matters_to_anchor(Unit *u, Job *j) {
912 assert(!j->transaction_prev);
914 /* Checks whether at least one of the jobs for this unit
915 * matters to the anchor. */
917 LIST_FOREACH(transaction, j, j)
918 if (j->matters_to_anchor)
924 static int transaction_verify_order_one(Manager *m, Job *j, Job *from, unsigned generation, DBusError *e) {
931 assert(!j->transaction_prev);
933 /* Does a recursive sweep through the ordering graph, looking
934 * for a cycle. If we find cycle we try to break it. */
936 /* Have we seen this before? */
937 if (j->generation == generation) {
940 /* If the marker is NULL we have been here already and
941 * decided the job was loop-free from here. Hence
942 * shortcut things and return right-away. */
946 /* So, the marker is not NULL and we already have been
947 * here. We have a cycle. Let's try to break it. We go
948 * backwards in our path and try to find a suitable
949 * job to remove. We use the marker to find our way
950 * back, since smart how we are we stored our way back
952 log_warning("Found ordering cycle on %s/%s", j->unit->meta.id, job_type_to_string(j->type));
955 for (k = from; k; k = ((k->generation == generation && k->marker != k) ? k->marker : NULL)) {
957 log_info("Walked on cycle path to %s/%s", k->unit->meta.id, job_type_to_string(k->type));
961 !unit_matters_to_anchor(k->unit, k)) {
962 /* Ok, we can drop this one, so let's
967 /* Check if this in fact was the beginning of
975 log_warning("Breaking ordering cycle by deleting job %s/%s", k->unit->meta.id, job_type_to_string(k->type));
976 transaction_delete_unit(m, delete->unit);
980 log_error("Unable to break cycle");
982 dbus_set_error(e, BUS_ERROR_TRANSACTION_ORDER_IS_CYCLIC, "Transaction order is cyclic. See logs for details.");
986 /* Make the marker point to where we come from, so that we can
987 * find our way backwards if we want to break a cycle. We use
988 * a special marker for the beginning: we point to
990 j->marker = from ? from : j;
991 j->generation = generation;
993 /* We assume that the the dependencies are bidirectional, and
994 * hence can ignore UNIT_AFTER */
995 SET_FOREACH(u, j->unit->meta.dependencies[UNIT_BEFORE], i) {
998 /* Is there a job for this unit? */
999 if (!(o = hashmap_get(m->transaction_jobs, u)))
1001 /* Ok, there is no job for this in the
1002 * transaction, but maybe there is already one
1004 if (!(o = u->meta.job))
1007 if ((r = transaction_verify_order_one(m, o, j, generation, e)) < 0)
1011 /* Ok, let's backtrack, and remember that this entry is not on
1012 * our path anymore. */
1018 static int transaction_verify_order(Manager *m, unsigned *generation, DBusError *e) {
1027 /* Check if the ordering graph is cyclic. If it is, try to fix
1028 * that up by dropping one of the jobs. */
1030 g = (*generation)++;
1032 HASHMAP_FOREACH(j, m->transaction_jobs, i)
1033 if ((r = transaction_verify_order_one(m, j, NULL, g, e)) < 0)
1039 static void transaction_collect_garbage(Manager *m) {
1044 /* Drop jobs that are not required by any other job */
1052 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1056 log_debug("Garbage collecting job %s/%s", j->unit->meta.id, job_type_to_string(j->type));
1057 transaction_delete_job(m, j, true);
1065 static int transaction_is_destructive(Manager *m, DBusError *e) {
1071 /* Checks whether applying this transaction means that
1072 * existing jobs would be replaced */
1074 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1077 assert(!j->transaction_prev);
1078 assert(!j->transaction_next);
1080 if (j->unit->meta.job &&
1081 j->unit->meta.job != j &&
1082 !job_type_is_superset(j->type, j->unit->meta.job->type)) {
1084 dbus_set_error(e, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE, "Transaction is destructive.");
1092 static void transaction_minimize_impact(Manager *m) {
1096 /* Drops all unnecessary jobs that reverse already active jobs
1097 * or that stop a running service. */
1105 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1106 LIST_FOREACH(transaction, j, j) {
1107 bool stops_running_service, changes_existing_job;
1109 /* If it matters, we shouldn't drop it */
1110 if (j->matters_to_anchor)
1113 /* Would this stop a running service?
1114 * Would this change an existing job?
1115 * If so, let's drop this entry */
1117 stops_running_service =
1118 j->type == JOB_STOP && UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(j->unit));
1120 changes_existing_job =
1121 j->unit->meta.job && job_type_is_conflicting(j->type, j->unit->meta.job->type);
1123 if (!stops_running_service && !changes_existing_job)
1126 if (stops_running_service)
1127 log_info("%s/%s would stop a running service.", j->unit->meta.id, job_type_to_string(j->type));
1129 if (changes_existing_job)
1130 log_info("%s/%s would change existing job.", j->unit->meta.id, job_type_to_string(j->type));
1132 /* Ok, let's get rid of this */
1133 log_info("Deleting %s/%s to minimize impact.", j->unit->meta.id, job_type_to_string(j->type));
1135 transaction_delete_job(m, j, true);
1147 static int transaction_apply(Manager *m) {
1152 /* Moves the transaction jobs to the set of active jobs */
1154 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1156 assert(!j->transaction_prev);
1157 assert(!j->transaction_next);
1162 if ((r = hashmap_put(m->jobs, UINT32_TO_PTR(j->id), j)) < 0)
1166 while ((j = hashmap_steal_first(m->transaction_jobs))) {
1170 if (j->unit->meta.job)
1171 job_free(j->unit->meta.job);
1173 j->unit->meta.job = j;
1174 j->installed = true;
1176 /* We're fully installed. Now let's free data we don't
1179 assert(!j->transaction_next);
1180 assert(!j->transaction_prev);
1182 job_add_to_run_queue(j);
1183 job_add_to_dbus_queue(j);
1187 /* As last step, kill all remaining job dependencies. */
1188 transaction_clean_dependencies(m);
1194 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1198 hashmap_remove(m->jobs, UINT32_TO_PTR(j->id));
1204 static int transaction_activate(Manager *m, JobMode mode, DBusError *e) {
1206 unsigned generation = 1;
1210 /* This applies the changes recorded in transaction_jobs to
1211 * the actual list of jobs, if possible. */
1213 /* First step: figure out which jobs matter */
1214 transaction_find_jobs_that_matter_to_anchor(m, NULL, generation++);
1216 /* Second step: Try not to stop any running services if
1217 * we don't have to. Don't try to reverse running
1218 * jobs if we don't have to. */
1219 transaction_minimize_impact(m);
1221 /* Third step: Drop redundant jobs */
1222 transaction_drop_redundant(m);
1225 /* Fourth step: Let's remove unneeded jobs that might
1227 transaction_collect_garbage(m);
1229 /* Fifth step: verify order makes sense and correct
1230 * cycles if necessary and possible */
1231 if ((r = transaction_verify_order(m, &generation, e)) >= 0)
1235 log_warning("Requested transaction contains an unfixable cyclic ordering dependency: %s", bus_error(e, r));
1239 /* Let's see if the resulting transaction ordering
1240 * graph is still cyclic... */
1244 /* Sixth step: let's drop unmergeable entries if
1245 * necessary and possible, merge entries we can
1247 if ((r = transaction_merge_jobs(m, e)) >= 0)
1251 log_warning("Requested transaction contains unmergable jobs: %s", bus_error(e, r));
1255 /* Seventh step: an entry got dropped, let's garbage
1256 * collect its dependencies. */
1257 transaction_collect_garbage(m);
1259 /* Let's see if the resulting transaction still has
1260 * unmergeable entries ... */
1263 /* Eights step: Drop redundant jobs again, if the merging now allows us to drop more. */
1264 transaction_drop_redundant(m);
1266 /* Ninth step: check whether we can actually apply this */
1267 if (mode == JOB_FAIL)
1268 if ((r = transaction_is_destructive(m, e)) < 0) {
1269 log_notice("Requested transaction contradicts existing jobs: %s", bus_error(e, r));
1273 /* Tenth step: apply changes */
1274 if ((r = transaction_apply(m)) < 0) {
1275 log_warning("Failed to apply transaction: %s", strerror(-r));
1279 assert(hashmap_isempty(m->transaction_jobs));
1280 assert(!m->transaction_anchor);
1285 transaction_abort(m);
1289 static Job* transaction_add_one_job(Manager *m, JobType type, Unit *unit, bool override, bool *is_new) {
1296 /* Looks for an axisting prospective job and returns that. If
1297 * it doesn't exist it is created and added to the prospective
1300 f = hashmap_get(m->transaction_jobs, unit);
1302 LIST_FOREACH(transaction, j, f) {
1303 assert(j->unit == unit);
1305 if (j->type == type) {
1312 if (unit->meta.job && unit->meta.job->type == type)
1314 else if (!(j = job_new(m, type, unit)))
1319 j->matters_to_anchor = false;
1320 j->override = override;
1322 LIST_PREPEND(Job, transaction, f, j);
1324 if ((r = hashmap_replace(m->transaction_jobs, unit, f)) < 0) {
1332 log_debug("Added job %s/%s to transaction.", unit->meta.id, job_type_to_string(type));
1337 void manager_transaction_unlink_job(Manager *m, Job *j, bool delete_dependencies) {
1341 if (j->transaction_prev)
1342 j->transaction_prev->transaction_next = j->transaction_next;
1343 else if (j->transaction_next)
1344 hashmap_replace(m->transaction_jobs, j->unit, j->transaction_next);
1346 hashmap_remove_value(m->transaction_jobs, j->unit, j);
1348 if (j->transaction_next)
1349 j->transaction_next->transaction_prev = j->transaction_prev;
1351 j->transaction_prev = j->transaction_next = NULL;
1353 while (j->subject_list)
1354 job_dependency_free(j->subject_list);
1356 while (j->object_list) {
1357 Job *other = j->object_list->matters ? j->object_list->subject : NULL;
1359 job_dependency_free(j->object_list);
1361 if (other && delete_dependencies) {
1362 log_debug("Deleting job %s/%s as dependency of job %s/%s",
1363 other->unit->meta.id, job_type_to_string(other->type),
1364 j->unit->meta.id, job_type_to_string(j->type));
1365 transaction_delete_job(m, other, delete_dependencies);
1370 static int transaction_add_job_and_dependencies(
1387 assert(type < _JOB_TYPE_MAX);
1390 if (type != JOB_STOP &&
1391 unit->meta.load_state != UNIT_LOADED) {
1392 dbus_set_error(e, BUS_ERROR_LOAD_FAILED, "Unit %s failed to load. See logs for details.", unit->meta.id);
1396 if (!unit_job_is_applicable(unit, type)) {
1397 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);
1401 /* First add the job. */
1402 if (!(ret = transaction_add_one_job(m, type, unit, override, &is_new)))
1405 /* Then, add a link to the job. */
1406 if (!job_dependency_new(by, ret, matters, conflicts))
1410 /* Finally, recursively add in all dependencies. */
1411 if (type == JOB_START || type == JOB_RELOAD_OR_START) {
1412 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES], i)
1413 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, true, override, false, e, NULL)) < 0 && r != -EBADR)
1416 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES_OVERRIDABLE], i)
1417 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, !override, override, false, e, NULL)) < 0 && r != -EBADR) {
1418 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, bus_error(e, r));
1422 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_WANTS], i)
1423 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, false, false, false, e, NULL)) < 0) {
1424 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, bus_error(e, r));
1428 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE], i)
1429 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, true, override, false, e, NULL)) < 0 && r != -EBADR)
1432 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE_OVERRIDABLE], i)
1433 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, !override, override, false, e, NULL)) < 0 && r != -EBADR) {
1434 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, bus_error(e, r));
1438 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_CONFLICTS], i)
1439 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, dep, ret, true, override, true, e, NULL)) < 0 && r != -EBADR)
1442 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_CONFLICTED_BY], i)
1443 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, dep, ret, true, override, false, e, NULL)) < 0 && r != -EBADR)
1446 } else if (type == JOB_STOP || type == JOB_RESTART || type == JOB_TRY_RESTART) {
1448 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRED_BY], i)
1449 if ((r = transaction_add_job_and_dependencies(m, type, dep, ret, true, override, false, e, NULL)) < 0 && r != -EBADR)
1453 /* JOB_VERIFY_STARTED, JOB_RELOAD require no dependency handling */
1465 static int transaction_add_isolate_jobs(Manager *m) {
1473 HASHMAP_FOREACH_KEY(u, k, m->units, i) {
1475 /* ignore aliases */
1476 if (u->meta.id != k)
1479 if (UNIT_VTABLE(u)->no_isolate)
1482 /* No need to stop inactive jobs */
1483 if (UNIT_IS_INACTIVE_OR_MAINTENANCE(unit_active_state(u)))
1486 /* Is there already something listed for this? */
1487 if (hashmap_get(m->transaction_jobs, u))
1490 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, u, NULL, true, false, false, NULL, NULL)) < 0)
1491 log_warning("Cannot add isolate job for unit %s, ignoring: %s", u->meta.id, strerror(-r));
1497 int manager_add_job(Manager *m, JobType type, Unit *unit, JobMode mode, bool override, DBusError *e, Job **_ret) {
1502 assert(type < _JOB_TYPE_MAX);
1504 assert(mode < _JOB_MODE_MAX);
1506 if (mode == JOB_ISOLATE && type != JOB_START) {
1507 dbus_set_error(e, BUS_ERROR_INVALID_JOB_MODE, "Isolate is only valid for start.");
1511 log_debug("Trying to enqueue job %s/%s", unit->meta.id, job_type_to_string(type));
1513 if ((r = transaction_add_job_and_dependencies(m, type, unit, NULL, true, override, false, e, &ret)) < 0) {
1514 transaction_abort(m);
1518 if (mode == JOB_ISOLATE)
1519 if ((r = transaction_add_isolate_jobs(m)) < 0) {
1520 transaction_abort(m);
1524 if ((r = transaction_activate(m, mode, e)) < 0)
1527 log_debug("Enqueued job %s/%s as %u", unit->meta.id, job_type_to_string(type), (unsigned) ret->id);
1535 int manager_add_job_by_name(Manager *m, JobType type, const char *name, JobMode mode, bool override, DBusError *e, Job **_ret) {
1540 assert(type < _JOB_TYPE_MAX);
1542 assert(mode < _JOB_MODE_MAX);
1544 if ((r = manager_load_unit(m, name, NULL, NULL, &unit)) < 0)
1547 return manager_add_job(m, type, unit, mode, override, e, _ret);
1550 Job *manager_get_job(Manager *m, uint32_t id) {
1553 return hashmap_get(m->jobs, UINT32_TO_PTR(id));
1556 Unit *manager_get_unit(Manager *m, const char *name) {
1560 return hashmap_get(m->units, name);
1563 unsigned manager_dispatch_load_queue(Manager *m) {
1569 /* Make sure we are not run recursively */
1570 if (m->dispatching_load_queue)
1573 m->dispatching_load_queue = true;
1575 /* Dispatches the load queue. Takes a unit from the queue and
1576 * tries to load its data until the queue is empty */
1578 while ((meta = m->load_queue)) {
1579 assert(meta->in_load_queue);
1581 unit_load((Unit*) meta);
1585 m->dispatching_load_queue = false;
1589 int manager_load_unit_prepare(Manager *m, const char *name, const char *path, DBusError *e, Unit **_ret) {
1594 assert(name || path);
1596 /* This will prepare the unit for loading, but not actually
1597 * load anything from disk. */
1599 if (path && !is_path(path)) {
1600 dbus_set_error(e, BUS_ERROR_INVALID_PATH, "Path %s is not absolute.", path);
1605 name = file_name_from_path(path);
1607 if (!unit_name_is_valid(name)) {
1608 dbus_set_error(e, BUS_ERROR_INVALID_NAME, "Unit name %s is not valid.", name);
1612 if ((ret = manager_get_unit(m, name))) {
1617 if (!(ret = unit_new(m)))
1621 if (!(ret->meta.fragment_path = strdup(path))) {
1626 if ((r = unit_add_name(ret, name)) < 0) {
1631 unit_add_to_load_queue(ret);
1632 unit_add_to_dbus_queue(ret);
1633 unit_add_to_gc_queue(ret);
1641 int manager_load_unit(Manager *m, const char *name, const char *path, DBusError *e, Unit **_ret) {
1646 /* This will load the service information files, but not actually
1647 * start any services or anything. */
1649 if ((r = manager_load_unit_prepare(m, name, path, e, _ret)) != 0)
1652 manager_dispatch_load_queue(m);
1655 *_ret = unit_follow_merge(*_ret);
1660 void manager_dump_jobs(Manager *s, FILE *f, const char *prefix) {
1667 HASHMAP_FOREACH(j, s->jobs, i)
1668 job_dump(j, f, prefix);
1671 void manager_dump_units(Manager *s, FILE *f, const char *prefix) {
1679 HASHMAP_FOREACH_KEY(u, t, s->units, i)
1680 if (u->meta.id == t)
1681 unit_dump(u, f, prefix);
1684 void manager_clear_jobs(Manager *m) {
1689 transaction_abort(m);
1691 while ((j = hashmap_first(m->jobs)))
1695 unsigned manager_dispatch_run_queue(Manager *m) {
1699 if (m->dispatching_run_queue)
1702 m->dispatching_run_queue = true;
1704 while ((j = m->run_queue)) {
1705 assert(j->installed);
1706 assert(j->in_run_queue);
1708 job_run_and_invalidate(j);
1712 m->dispatching_run_queue = false;
1716 unsigned manager_dispatch_dbus_queue(Manager *m) {
1723 if (m->dispatching_dbus_queue)
1726 m->dispatching_dbus_queue = true;
1728 while ((meta = m->dbus_unit_queue)) {
1729 assert(meta->in_dbus_queue);
1731 bus_unit_send_change_signal((Unit*) meta);
1735 while ((j = m->dbus_job_queue)) {
1736 assert(j->in_dbus_queue);
1738 bus_job_send_change_signal(j);
1742 m->dispatching_dbus_queue = false;
1746 static int manager_process_notify_fd(Manager *m) {
1753 struct msghdr msghdr;
1755 struct ucred *ucred;
1757 struct cmsghdr cmsghdr;
1758 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
1764 iovec.iov_base = buf;
1765 iovec.iov_len = sizeof(buf)-1;
1769 msghdr.msg_iov = &iovec;
1770 msghdr.msg_iovlen = 1;
1771 msghdr.msg_control = &control;
1772 msghdr.msg_controllen = sizeof(control);
1774 if ((n = recvmsg(m->notify_watch.fd, &msghdr, MSG_DONTWAIT)) <= 0) {
1778 if (errno == EAGAIN)
1784 if (msghdr.msg_controllen < CMSG_LEN(sizeof(struct ucred)) ||
1785 control.cmsghdr.cmsg_level != SOL_SOCKET ||
1786 control.cmsghdr.cmsg_type != SCM_CREDENTIALS ||
1787 control.cmsghdr.cmsg_len != CMSG_LEN(sizeof(struct ucred))) {
1788 log_warning("Received notify message without credentials. Ignoring.");
1792 ucred = (struct ucred*) CMSG_DATA(&control.cmsghdr);
1794 if (!(u = hashmap_get(m->watch_pids, LONG_TO_PTR(ucred->pid))))
1795 if (!(u = cgroup_unit_by_pid(m, ucred->pid))) {
1796 log_warning("Cannot find unit for notify message of PID %lu.", (unsigned long) ucred->pid);
1800 assert((size_t) n < sizeof(buf));
1802 if (!(tags = strv_split(buf, "\n\r")))
1805 log_debug("Got notification message for unit %s", u->meta.id);
1807 if (UNIT_VTABLE(u)->notify_message)
1808 UNIT_VTABLE(u)->notify_message(u, ucred->pid, tags);
1816 static int manager_dispatch_sigchld(Manager *m) {
1826 /* First we call waitd() for a PID and do not reap the
1827 * zombie. That way we can still access /proc/$PID for
1828 * it while it is a zombie. */
1829 if (waitid(P_ALL, 0, &si, WEXITED|WNOHANG|WNOWAIT) < 0) {
1831 if (errno == ECHILD)
1843 if (si.si_code == CLD_EXITED || si.si_code == CLD_KILLED || si.si_code == CLD_DUMPED) {
1846 get_process_name(si.si_pid, &name);
1847 log_debug("Got SIGCHLD for process %lu (%s)", (unsigned long) si.si_pid, strna(name));
1851 /* Let's flush any message the dying child might still
1852 * have queued for us. This ensures that the process
1853 * still exists in /proc so that we can figure out
1854 * which cgroup and hence unit it belongs to. */
1855 if ((r = manager_process_notify_fd(m)) < 0)
1858 /* And now figure out the unit this belongs to */
1859 if (!(u = hashmap_get(m->watch_pids, LONG_TO_PTR(si.si_pid))))
1860 u = cgroup_unit_by_pid(m, si.si_pid);
1862 /* And now, we actually reap the zombie. */
1863 if (waitid(P_PID, si.si_pid, &si, WEXITED) < 0) {
1870 if (si.si_code != CLD_EXITED && si.si_code != CLD_KILLED && si.si_code != CLD_DUMPED)
1873 log_debug("Child %lu died (code=%s, status=%i/%s)",
1874 (long unsigned) si.si_pid,
1875 sigchld_code_to_string(si.si_code),
1877 strna(si.si_code == CLD_EXITED ? exit_status_to_string(si.si_status) : signal_to_string(si.si_status)));
1882 log_debug("Child %lu belongs to %s", (long unsigned) si.si_pid, u->meta.id);
1884 hashmap_remove(m->watch_pids, LONG_TO_PTR(si.si_pid));
1885 UNIT_VTABLE(u)->sigchld_event(u, si.si_pid, si.si_code, si.si_status);
1891 static int manager_start_target(Manager *m, const char *name, JobMode mode) {
1895 dbus_error_init(&error);
1897 log_info("Activating special unit %s", name);
1899 if ((r = manager_add_job_by_name(m, JOB_START, name, mode, true, &error, NULL)) < 0)
1900 log_error("Failed to enqueue %s job: %s", name, bus_error(&error, r));
1902 dbus_error_free(&error);
1907 static int manager_process_signal_fd(Manager *m) {
1909 struct signalfd_siginfo sfsi;
1910 bool sigchld = false;
1915 if ((n = read(m->signal_watch.fd, &sfsi, sizeof(sfsi))) != sizeof(sfsi)) {
1920 if (errno == EAGAIN)
1926 log_debug("Received SIG%s", strna(signal_to_string(sfsi.ssi_signo)));
1928 switch (sfsi.ssi_signo) {
1935 if (m->running_as == MANAGER_SYSTEM) {
1936 /* This is for compatibility with the
1937 * original sysvinit */
1938 m->exit_code = MANAGER_REEXECUTE;
1945 if (m->running_as == MANAGER_SYSTEM) {
1946 manager_start_target(m, SPECIAL_CTRL_ALT_DEL_TARGET, JOB_REPLACE);
1950 /* Run the exit target if there is one, if not, just exit. */
1951 if (manager_start_target(m, SPECIAL_EXIT_SERVICE, JOB_REPLACE) < 0) {
1952 m->exit_code = MANAGER_EXIT;
1959 if (m->running_as == MANAGER_SYSTEM)
1960 manager_start_target(m, SPECIAL_KBREQUEST_TARGET, JOB_REPLACE);
1962 /* This is a nop on non-init */
1966 if (m->running_as == MANAGER_SYSTEM)
1967 manager_start_target(m, SPECIAL_SIGPWR_TARGET, JOB_REPLACE);
1969 /* This is a nop on non-init */
1975 u = manager_get_unit(m, SPECIAL_DBUS_SERVICE);
1977 if (!u || UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u))) {
1978 log_info("Trying to reconnect to bus...");
1982 if (!u || !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u))) {
1983 log_info("Loading D-Bus service...");
1984 manager_start_target(m, SPECIAL_DBUS_SERVICE, JOB_REPLACE);
1995 if (!(f = open_memstream(&dump, &size))) {
1996 log_warning("Failed to allocate memory stream.");
2000 manager_dump_units(m, f, "\t");
2001 manager_dump_jobs(m, f, "\t");
2006 log_warning("Failed to write status stream");
2011 log_dump(LOG_INFO, dump);
2018 m->exit_code = MANAGER_RELOAD;
2022 static const char * const table[] = {
2023 [0] = SPECIAL_DEFAULT_TARGET,
2024 [1] = SPECIAL_RESCUE_TARGET,
2025 [2] = SPECIAL_EMERGENCY_TARGET,
2026 [3] = SPECIAL_HALT_TARGET,
2027 [4] = SPECIAL_POWEROFF_TARGET,
2028 [5] = SPECIAL_REBOOT_TARGET
2031 if ((int) sfsi.ssi_signo >= SIGRTMIN+0 &&
2032 (int) sfsi.ssi_signo < SIGRTMIN+(int) ELEMENTSOF(table)) {
2033 manager_start_target(m, table[sfsi.ssi_signo - SIGRTMIN],
2034 (sfsi.ssi_signo == 1 || sfsi.ssi_signo == 2) ? JOB_ISOLATE : JOB_REPLACE);
2038 log_warning("Got unhandled signal <%s>.", strna(signal_to_string(sfsi.ssi_signo)));
2044 return manager_dispatch_sigchld(m);
2049 static int process_event(Manager *m, struct epoll_event *ev) {
2056 assert(w = ev->data.ptr);
2062 /* An incoming signal? */
2063 if (ev->events != EPOLLIN)
2066 if ((r = manager_process_signal_fd(m)) < 0)
2073 /* An incoming daemon notification event? */
2074 if (ev->events != EPOLLIN)
2077 if ((r = manager_process_notify_fd(m)) < 0)
2084 /* Some fd event, to be dispatched to the units */
2085 UNIT_VTABLE(w->data.unit)->fd_event(w->data.unit, w->fd, ev->events, w);
2088 case WATCH_UNIT_TIMER:
2089 case WATCH_JOB_TIMER: {
2093 /* Some timer event, to be dispatched to the units */
2094 if ((k = read(w->fd, &v, sizeof(v))) != sizeof(v)) {
2096 if (k < 0 && (errno == EINTR || errno == EAGAIN))
2099 return k < 0 ? -errno : -EIO;
2102 if (w->type == WATCH_UNIT_TIMER)
2103 UNIT_VTABLE(w->data.unit)->timer_event(w->data.unit, v, w);
2105 job_timer_event(w->data.job, v, w);
2110 /* Some mount table change, intended for the mount subsystem */
2111 mount_fd_event(m, ev->events);
2115 /* Some notification from udev, intended for the device subsystem */
2116 device_fd_event(m, ev->events);
2119 case WATCH_DBUS_WATCH:
2120 bus_watch_event(m, w, ev->events);
2123 case WATCH_DBUS_TIMEOUT:
2124 bus_timeout_event(m, w, ev->events);
2128 assert_not_reached("Unknown epoll event type.");
2134 int manager_loop(Manager *m) {
2137 RATELIMIT_DEFINE(rl, 1*USEC_PER_SEC, 1000);
2140 m->exit_code = MANAGER_RUNNING;
2142 /* Release the path cache */
2143 set_free_free(m->unit_path_cache);
2144 m->unit_path_cache = NULL;
2146 /* There might still be some zombies hanging around from
2147 * before we were exec()'ed. Leat's reap them */
2148 if ((r = manager_dispatch_sigchld(m)) < 0)
2151 while (m->exit_code == MANAGER_RUNNING) {
2152 struct epoll_event event;
2155 if (!ratelimit_test(&rl)) {
2156 /* Yay, something is going seriously wrong, pause a little */
2157 log_warning("Looping too fast. Throttling execution a little.");
2161 if (manager_dispatch_load_queue(m) > 0)
2164 if (manager_dispatch_run_queue(m) > 0)
2167 if (bus_dispatch(m) > 0)
2170 if (manager_dispatch_cleanup_queue(m) > 0)
2173 if (manager_dispatch_gc_queue(m) > 0)
2176 if (manager_dispatch_dbus_queue(m) > 0)
2179 if ((n = epoll_wait(m->epoll_fd, &event, 1, -1)) < 0) {
2189 if ((r = process_event(m, &event)) < 0)
2193 return m->exit_code;
2196 int manager_get_unit_from_dbus_path(Manager *m, const char *s, Unit **_u) {
2204 if (!startswith(s, "/org/freedesktop/systemd1/unit/"))
2207 if (!(n = bus_path_unescape(s+31)))
2210 u = manager_get_unit(m, n);
2221 int manager_get_job_from_dbus_path(Manager *m, const char *s, Job **_j) {
2230 if (!startswith(s, "/org/freedesktop/systemd1/job/"))
2233 if ((r = safe_atou(s + 30, &id)) < 0)
2236 if (!(j = manager_get_job(m, id)))
2244 void manager_send_unit_audit(Manager *m, Unit *u, int type, bool success) {
2249 if (m->audit_fd < 0)
2252 if (!(p = unit_name_to_prefix_and_instance(u->meta.id))) {
2253 log_error("Failed to allocate unit name for audit message: %s", strerror(ENOMEM));
2257 if (audit_log_user_comm_message(m->audit_fd, type, "", p, NULL, NULL, NULL, success) < 0)
2258 log_error("Failed to send audit message: %m");
2265 void manager_dispatch_bus_name_owner_changed(
2268 const char* old_owner,
2269 const char *new_owner) {
2276 if (!(u = hashmap_get(m->watch_bus, name)))
2279 UNIT_VTABLE(u)->bus_name_owner_change(u, name, old_owner, new_owner);
2282 void manager_dispatch_bus_query_pid_done(
2293 if (!(u = hashmap_get(m->watch_bus, name)))
2296 UNIT_VTABLE(u)->bus_query_pid_done(u, name, pid);
2299 int manager_open_serialization(Manager *m, FILE **_f) {
2307 if (m->running_as == MANAGER_SYSTEM) {
2308 mkdir_p("/dev/.systemd", 0755);
2310 if (asprintf(&path, "/dev/.systemd/dump-%lu-XXXXXX", (unsigned long) getpid()) < 0)
2313 if (asprintf(&path, "/tmp/systemd-dump-%lu-XXXXXX", (unsigned long) getpid()) < 0)
2317 saved_umask = umask(0077);
2318 fd = mkostemp(path, O_RDWR|O_CLOEXEC);
2328 log_debug("Serializing state to %s", path);
2331 if (!(f = fdopen(fd, "w+")) < 0)
2339 int manager_serialize(Manager *m, FILE *f, FDSet *fds) {
2349 HASHMAP_FOREACH_KEY(u, t, m->units, i) {
2350 if (u->meta.id != t)
2353 if (!unit_can_serialize(u))
2357 fputs(u->meta.id, f);
2360 if ((r = unit_serialize(u, f, fds)) < 0)
2370 int manager_deserialize(Manager *m, FILE *f, FDSet *fds) {
2376 log_debug("Deserializing state...");
2378 m->n_deserializing ++;
2382 char name[UNIT_NAME_MAX+2];
2385 if (!fgets(name, sizeof(name), f)) {
2395 if ((r = manager_load_unit(m, strstrip(name), NULL, NULL, &u)) < 0)
2398 if ((r = unit_deserialize(u, f, fds)) < 0)
2410 assert(m->n_deserializing > 0);
2411 m->n_deserializing --;
2416 int manager_reload(Manager *m) {
2423 if ((r = manager_open_serialization(m, &f)) < 0)
2426 if (!(fds = fdset_new())) {
2431 if ((r = manager_serialize(m, f, fds)) < 0)
2434 if (fseeko(f, 0, SEEK_SET) < 0) {
2439 /* From here on there is no way back. */
2440 manager_clear_jobs_and_units(m);
2442 /* Find new unit paths */
2443 lookup_paths_free(&m->lookup_paths);
2444 if ((q = lookup_paths_init(&m->lookup_paths, m->running_as)) < 0)
2447 m->n_deserializing ++;
2449 /* First, enumerate what we can from all config files */
2450 if ((q = manager_enumerate(m)) < 0)
2453 /* Second, deserialize our stored data */
2454 if ((q = manager_deserialize(m, f, fds)) < 0)
2460 /* Third, fire things up! */
2461 if ((q = manager_coldplug(m)) < 0)
2464 assert(m->n_deserializing > 0);
2465 m->n_deserializing ++;
2477 bool manager_is_booting_or_shutting_down(Manager *m) {
2482 /* Is the initial job still around? */
2483 if (manager_get_job(m, 1))
2486 /* Is there a job for the shutdown target? */
2487 if (((u = manager_get_unit(m, SPECIAL_SHUTDOWN_TARGET))))
2488 return !!u->meta.job;
2493 void manager_reset_maintenance(Manager *m) {
2499 HASHMAP_FOREACH(u, m->units, i)
2500 unit_reset_maintenance(u);
2503 static const char* const manager_running_as_table[_MANAGER_RUNNING_AS_MAX] = {
2504 [MANAGER_SYSTEM] = "system",
2505 [MANAGER_SESSION] = "session"
2508 DEFINE_STRING_TABLE_LOOKUP(manager_running_as, ManagerRunningAs);