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>
50 #include "ratelimit.h"
52 #include "mount-setup.h"
53 #include "unit-name.h"
54 #include "dbus-unit.h"
57 #include "path-lookup.h"
59 #include "bus-errors.h"
61 /* As soon as 16 units are in our GC queue, make sure to run a gc sweep */
62 #define GC_QUEUE_ENTRIES_MAX 16
64 /* As soon as 5s passed since a unit was added to our GC queue, make sure to run a gc sweep */
65 #define GC_QUEUE_USEC_MAX (10*USEC_PER_SEC)
67 /* Where clients shall send notification messages to */
68 #define NOTIFY_SOCKET "/org/freedesktop/systemd1/notify"
70 static int manager_setup_notify(Manager *m) {
73 struct sockaddr_un un;
75 struct epoll_event ev;
80 m->notify_watch.type = WATCH_NOTIFY;
81 if ((m->notify_watch.fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0)) < 0) {
82 log_error("Failed to allocate notification socket: %m");
87 sa.sa.sa_family = AF_UNIX;
90 snprintf(sa.un.sun_path+1, sizeof(sa.un.sun_path)-1, NOTIFY_SOCKET "/%llu", random_ull());
92 strncpy(sa.un.sun_path+1, NOTIFY_SOCKET, sizeof(sa.un.sun_path)-1);
94 if (bind(m->notify_watch.fd, &sa.sa, sizeof(sa_family_t) + 1 + strlen(sa.un.sun_path+1)) < 0) {
95 log_error("bind() failed: %m");
99 if (setsockopt(m->notify_watch.fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one)) < 0) {
100 log_error("SO_PASSCRED failed: %m");
106 ev.data.ptr = &m->notify_watch;
108 if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->notify_watch.fd, &ev) < 0)
111 if (!(m->notify_socket = strdup(sa.un.sun_path+1)))
117 static int enable_special_signals(Manager *m) {
122 /* Enable that we get SIGINT on control-alt-del */
123 if (reboot(RB_DISABLE_CAD) < 0)
124 log_warning("Failed to enable ctrl-alt-del handling: %m");
126 if ((fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY)) < 0)
127 log_warning("Failed to open /dev/tty0: %m");
129 /* Enable that we get SIGWINCH on kbrequest */
130 if (ioctl(fd, KDSIGACCEPT, SIGWINCH) < 0)
131 log_warning("Failed to enable kbrequest handling: %s", strerror(errno));
133 close_nointr_nofail(fd);
139 static int manager_setup_signals(Manager *m) {
141 struct epoll_event ev;
146 /* We are not interested in SIGSTOP and friends. */
148 sa.sa_handler = SIG_DFL;
149 sa.sa_flags = SA_NOCLDSTOP|SA_RESTART;
150 assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);
152 assert_se(sigemptyset(&mask) == 0);
154 sigset_add_many(&mask,
155 SIGCHLD, /* Child died */
156 SIGTERM, /* Reexecute daemon */
157 SIGHUP, /* Reload configuration */
158 SIGUSR1, /* systemd/upstart: reconnect to D-Bus */
159 SIGUSR2, /* systemd: dump status */
160 SIGINT, /* Kernel sends us this on control-alt-del */
161 SIGWINCH, /* Kernel sends us this on kbrequest (alt-arrowup) */
162 SIGPWR, /* Some kernel drivers and upsd send us this on power failure */
163 SIGRTMIN+0, /* systemd: start default.target */
164 SIGRTMIN+1, /* systemd: start rescue.target */
165 SIGRTMIN+2, /* systemd: isolate emergency.target */
166 SIGRTMIN+3, /* systemd: start halt.target */
167 SIGRTMIN+4, /* systemd: start poweroff.target */
168 SIGRTMIN+5, /* systemd: start reboot.target */
170 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
172 m->signal_watch.type = WATCH_SIGNAL;
173 if ((m->signal_watch.fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0)
178 ev.data.ptr = &m->signal_watch;
180 if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->signal_watch.fd, &ev) < 0)
183 if (m->running_as == MANAGER_SYSTEM)
184 return enable_special_signals(m);
189 int manager_new(ManagerRunningAs running_as, Manager **_m) {
194 assert(running_as >= 0);
195 assert(running_as < _MANAGER_RUNNING_AS_MAX);
197 if (!(m = new0(Manager, 1)))
200 dual_timestamp_get(&m->startup_timestamp);
202 m->running_as = running_as;
203 m->name_data_slot = m->subscribed_data_slot = -1;
204 m->exit_code = _MANAGER_EXIT_CODE_INVALID;
205 m->pin_cgroupfs_fd = -1;
211 m->signal_watch.fd = m->mount_watch.fd = m->udev_watch.fd = m->epoll_fd = m->dev_autofs_fd = -1;
212 m->current_job_id = 1; /* start as id #1, so that we can leave #0 around as "null-like" value */
214 if (!(m->environment = strv_copy(environ)))
217 if (!(m->units = hashmap_new(string_hash_func, string_compare_func)))
220 if (!(m->jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
223 if (!(m->transaction_jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
226 if (!(m->watch_pids = hashmap_new(trivial_hash_func, trivial_compare_func)))
229 if (!(m->cgroup_bondings = hashmap_new(string_hash_func, string_compare_func)))
232 if (!(m->watch_bus = hashmap_new(string_hash_func, string_compare_func)))
235 if ((m->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0)
238 if ((r = lookup_paths_init(&m->lookup_paths, m->running_as)) < 0)
241 if ((r = manager_setup_signals(m)) < 0)
244 if ((r = manager_setup_cgroup(m)) < 0)
247 if ((r = manager_setup_notify(m)) < 0)
250 /* Try to connect to the busses, if possible. */
251 if ((r = bus_init(m)) < 0)
254 if ((m->audit_fd = audit_open()) < 0)
255 log_error("Failed to connect to audit log: %m");
265 static unsigned manager_dispatch_cleanup_queue(Manager *m) {
271 while ((meta = m->cleanup_queue)) {
272 assert(meta->in_cleanup_queue);
274 unit_free((Unit*) meta);
282 GC_OFFSET_IN_PATH, /* This one is on the path we were travelling */
283 GC_OFFSET_UNSURE, /* No clue */
284 GC_OFFSET_GOOD, /* We still need this unit */
285 GC_OFFSET_BAD, /* We don't need this unit anymore */
289 static void unit_gc_sweep(Unit *u, unsigned gc_marker) {
296 if (u->meta.gc_marker == gc_marker + GC_OFFSET_GOOD ||
297 u->meta.gc_marker == gc_marker + GC_OFFSET_BAD ||
298 u->meta.gc_marker == gc_marker + GC_OFFSET_IN_PATH)
301 if (u->meta.in_cleanup_queue)
304 if (unit_check_gc(u))
307 u->meta.gc_marker = gc_marker + GC_OFFSET_IN_PATH;
311 SET_FOREACH(other, u->meta.dependencies[UNIT_REFERENCED_BY], i) {
312 unit_gc_sweep(other, gc_marker);
314 if (other->meta.gc_marker == gc_marker + GC_OFFSET_GOOD)
317 if (other->meta.gc_marker != gc_marker + GC_OFFSET_BAD)
324 /* We were unable to find anything out about this entry, so
325 * let's investigate it later */
326 u->meta.gc_marker = gc_marker + GC_OFFSET_UNSURE;
327 unit_add_to_gc_queue(u);
331 /* We definitely know that this one is not useful anymore, so
332 * let's mark it for deletion */
333 u->meta.gc_marker = gc_marker + GC_OFFSET_BAD;
334 unit_add_to_cleanup_queue(u);
338 u->meta.gc_marker = gc_marker + GC_OFFSET_GOOD;
341 static unsigned manager_dispatch_gc_queue(Manager *m) {
348 if ((m->n_in_gc_queue < GC_QUEUE_ENTRIES_MAX) &&
349 (m->gc_queue_timestamp <= 0 ||
350 (m->gc_queue_timestamp + GC_QUEUE_USEC_MAX) > now(CLOCK_MONOTONIC)))
353 log_debug("Running GC...");
355 m->gc_marker += _GC_OFFSET_MAX;
356 if (m->gc_marker + _GC_OFFSET_MAX <= _GC_OFFSET_MAX)
359 gc_marker = m->gc_marker;
361 while ((meta = m->gc_queue)) {
362 assert(meta->in_gc_queue);
364 unit_gc_sweep((Unit*) meta, gc_marker);
366 LIST_REMOVE(Meta, gc_queue, m->gc_queue, meta);
367 meta->in_gc_queue = false;
371 if (meta->gc_marker == gc_marker + GC_OFFSET_BAD ||
372 meta->gc_marker == gc_marker + GC_OFFSET_UNSURE) {
373 log_debug("Collecting %s", meta->id);
374 meta->gc_marker = gc_marker + GC_OFFSET_BAD;
375 unit_add_to_cleanup_queue((Unit*) meta);
379 m->n_in_gc_queue = 0;
380 m->gc_queue_timestamp = 0;
385 static void manager_clear_jobs_and_units(Manager *m) {
391 while ((j = hashmap_first(m->transaction_jobs)))
394 while ((u = hashmap_first(m->units)))
397 manager_dispatch_cleanup_queue(m);
399 assert(!m->load_queue);
400 assert(!m->run_queue);
401 assert(!m->dbus_unit_queue);
402 assert(!m->dbus_job_queue);
403 assert(!m->cleanup_queue);
404 assert(!m->gc_queue);
406 assert(hashmap_isempty(m->transaction_jobs));
407 assert(hashmap_isempty(m->jobs));
408 assert(hashmap_isempty(m->units));
411 void manager_free(Manager *m) {
416 manager_clear_jobs_and_units(m);
418 for (c = 0; c < _UNIT_TYPE_MAX; c++)
419 if (unit_vtable[c]->shutdown)
420 unit_vtable[c]->shutdown(m);
422 /* If we reexecute ourselves, we keep the root cgroup
424 manager_shutdown_cgroup(m, m->exit_code != MANAGER_REEXECUTE);
428 hashmap_free(m->units);
429 hashmap_free(m->jobs);
430 hashmap_free(m->transaction_jobs);
431 hashmap_free(m->watch_pids);
432 hashmap_free(m->watch_bus);
434 if (m->epoll_fd >= 0)
435 close_nointr_nofail(m->epoll_fd);
436 if (m->signal_watch.fd >= 0)
437 close_nointr_nofail(m->signal_watch.fd);
438 if (m->notify_watch.fd >= 0)
439 close_nointr_nofail(m->notify_watch.fd);
442 if (m->audit_fd >= 0)
443 audit_close(m->audit_fd);
446 free(m->notify_socket);
448 lookup_paths_free(&m->lookup_paths);
449 strv_free(m->environment);
451 hashmap_free(m->cgroup_bondings);
452 set_free_free(m->unit_path_cache);
457 int manager_enumerate(Manager *m) {
463 /* Let's ask every type to load all units from disk/kernel
464 * that it might know */
465 for (c = 0; c < _UNIT_TYPE_MAX; c++)
466 if (unit_vtable[c]->enumerate)
467 if ((q = unit_vtable[c]->enumerate(m)) < 0)
470 manager_dispatch_load_queue(m);
474 int manager_coldplug(Manager *m) {
482 /* Then, let's set up their initial state. */
483 HASHMAP_FOREACH_KEY(u, k, m->units, i) {
489 if ((q = unit_coldplug(u)) < 0)
496 static void manager_build_unit_path_cache(Manager *m) {
503 set_free_free(m->unit_path_cache);
505 if (!(m->unit_path_cache = set_new(string_hash_func, string_compare_func))) {
506 log_error("Failed to allocate unit path cache.");
510 /* This simply builds a list of files we know exist, so that
511 * we don't always have to go to disk */
513 STRV_FOREACH(i, m->lookup_paths.unit_path) {
516 if (!(d = opendir(*i))) {
517 log_error("Failed to open directory: %m");
521 while ((de = readdir(d))) {
524 if (ignore_file(de->d_name))
527 if (asprintf(&p, "%s/%s", streq(*i, "/") ? "" : *i, de->d_name) < 0) {
532 if ((r = set_put(m->unit_path_cache, p)) < 0) {
545 log_error("Failed to build unit path cache: %s", strerror(-r));
547 set_free_free(m->unit_path_cache);
548 m->unit_path_cache = NULL;
554 int manager_startup(Manager *m, FILE *serialization, FDSet *fds) {
559 manager_build_unit_path_cache(m);
561 /* If we will deserialize make sure that during enumeration
562 * this is already known, so we increase the counter here
565 m->n_deserializing ++;
567 /* First, enumerate what we can from all config files */
568 r = manager_enumerate(m);
570 /* Second, deserialize if there is something to deserialize */
572 if ((q = manager_deserialize(m, serialization, fds)) < 0)
575 /* Third, fire things up! */
576 if ((q = manager_coldplug(m)) < 0)
580 assert(m->n_deserializing > 0);
581 m->n_deserializing --;
587 static void transaction_delete_job(Manager *m, Job *j, bool delete_dependencies) {
591 /* Deletes one job from the transaction */
593 manager_transaction_unlink_job(m, j, delete_dependencies);
599 static void transaction_delete_unit(Manager *m, Unit *u) {
602 /* Deletes all jobs associated with a certain unit from the
605 while ((j = hashmap_get(m->transaction_jobs, u)))
606 transaction_delete_job(m, j, true);
609 static void transaction_clean_dependencies(Manager *m) {
615 /* Drops all dependencies of all installed jobs */
617 HASHMAP_FOREACH(j, m->jobs, i) {
618 while (j->subject_list)
619 job_dependency_free(j->subject_list);
620 while (j->object_list)
621 job_dependency_free(j->object_list);
624 assert(!m->transaction_anchor);
627 static void transaction_abort(Manager *m) {
632 while ((j = hashmap_first(m->transaction_jobs)))
634 transaction_delete_job(m, j, true);
638 assert(hashmap_isempty(m->transaction_jobs));
640 transaction_clean_dependencies(m);
643 static void transaction_find_jobs_that_matter_to_anchor(Manager *m, Job *j, unsigned generation) {
648 /* A recursive sweep through the graph that marks all units
649 * that matter to the anchor job, i.e. are directly or
650 * indirectly a dependency of the anchor job via paths that
651 * are fully marked as mattering. */
656 l = m->transaction_anchor;
658 LIST_FOREACH(subject, l, l) {
660 /* This link does not matter */
664 /* This unit has already been marked */
665 if (l->object->generation == generation)
668 l->object->matters_to_anchor = true;
669 l->object->generation = generation;
671 transaction_find_jobs_that_matter_to_anchor(m, l->object, generation);
675 static void transaction_merge_and_delete_job(Manager *m, Job *j, Job *other, JobType t) {
676 JobDependency *l, *last;
680 assert(j->unit == other->unit);
681 assert(!j->installed);
683 /* Merges 'other' into 'j' and then deletes j. */
686 j->state = JOB_WAITING;
687 j->override = j->override || other->override;
689 j->matters_to_anchor = j->matters_to_anchor || other->matters_to_anchor;
691 /* Patch us in as new owner of the JobDependency objects */
693 LIST_FOREACH(subject, l, other->subject_list) {
694 assert(l->subject == other);
699 /* Merge both lists */
701 last->subject_next = j->subject_list;
703 j->subject_list->subject_prev = last;
704 j->subject_list = other->subject_list;
707 /* Patch us in as new owner of the JobDependency objects */
709 LIST_FOREACH(object, l, other->object_list) {
710 assert(l->object == other);
715 /* Merge both lists */
717 last->object_next = j->object_list;
719 j->object_list->object_prev = last;
720 j->object_list = other->object_list;
723 /* Kill the other job */
724 other->subject_list = NULL;
725 other->object_list = NULL;
726 transaction_delete_job(m, other, true);
728 static bool job_is_conflicted_by(Job *j) {
733 /* Returns true if this job is pulled in by a least one
734 * ConflictedBy dependency. */
736 LIST_FOREACH(object, l, j->object_list)
743 static int delete_one_unmergeable_job(Manager *m, Job *j) {
748 /* Tries to delete one item in the linked list
749 * j->transaction_next->transaction_next->... that conflicts
750 * whith another one, in an attempt to make an inconsistent
751 * transaction work. */
753 /* We rely here on the fact that if a merged with b does not
754 * merge with c, either a or b merge with c neither */
755 LIST_FOREACH(transaction, j, j)
756 LIST_FOREACH(transaction, k, j->transaction_next) {
759 /* Is this one mergeable? Then skip it */
760 if (job_type_is_mergeable(j->type, k->type))
763 /* Ok, we found two that conflict, let's see if we can
764 * drop one of them */
765 if (!j->matters_to_anchor && !k->matters_to_anchor) {
767 /* Both jobs don't matter, so let's
768 * find the one that is smarter to
769 * remove. Let's think positive and
770 * rather remove stops then starts --
771 * except if something is being
772 * stopped because it is conflicted by
773 * another unit in which case we
774 * rather remove the start. */
776 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)));
777 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)));
779 if (j->type == JOB_STOP) {
781 if (job_is_conflicted_by(j))
786 } else if (k->type == JOB_STOP) {
788 if (job_is_conflicted_by(k))
794 } else if (!j->matters_to_anchor)
796 else if (!k->matters_to_anchor)
801 /* Ok, we can drop one, so let's do so. */
802 log_debug("Fixing conflicting jobs by deleting job %s/%s", d->unit->meta.id, job_type_to_string(d->type));
803 transaction_delete_job(m, d, true);
810 static int transaction_merge_jobs(Manager *m, DBusError *e) {
817 /* First step, check whether any of the jobs for one specific
818 * task conflict. If so, try to drop one of them. */
819 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
824 LIST_FOREACH(transaction, k, j->transaction_next) {
825 if ((r = job_type_merge(&t, k->type)) >= 0)
828 /* OK, we could not merge all jobs for this
829 * action. Let's see if we can get rid of one
832 if ((r = delete_one_unmergeable_job(m, j)) >= 0)
833 /* Ok, we managed to drop one, now
834 * let's ask our callers to call us
835 * again after garbage collecting */
838 /* We couldn't merge anything. Failure */
839 dbus_set_error(e, BUS_ERROR_TRANSACTION_JOBS_CONFLICTING, "Transaction contains conflicting jobs '%s' and '%s' for %s. Probably contradicting requirement dependencies configured.",
840 job_type_to_string(t), job_type_to_string(k->type), k->unit->meta.id);
845 /* Second step, merge the jobs. */
846 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
850 /* Merge all transactions */
851 LIST_FOREACH(transaction, k, j->transaction_next)
852 assert_se(job_type_merge(&t, k->type) == 0);
854 /* If an active job is mergeable, merge it too */
855 if (j->unit->meta.job)
856 job_type_merge(&t, j->unit->meta.job->type); /* Might fail. Which is OK */
858 while ((k = j->transaction_next)) {
860 transaction_merge_and_delete_job(m, k, j, t);
863 transaction_merge_and_delete_job(m, j, k, t);
866 assert(!j->transaction_next);
867 assert(!j->transaction_prev);
873 static void transaction_drop_redundant(Manager *m) {
878 /* Goes through the transaction and removes all jobs that are
887 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
888 bool changes_something = false;
891 LIST_FOREACH(transaction, k, j) {
893 if (!job_is_anchor(k) &&
894 job_type_is_redundant(k->type, unit_active_state(k->unit)))
897 changes_something = true;
901 if (changes_something)
904 log_debug("Found redundant job %s/%s, dropping.", j->unit->meta.id, job_type_to_string(j->type));
905 transaction_delete_job(m, j, false);
913 static bool unit_matters_to_anchor(Unit *u, Job *j) {
915 assert(!j->transaction_prev);
917 /* Checks whether at least one of the jobs for this unit
918 * matters to the anchor. */
920 LIST_FOREACH(transaction, j, j)
921 if (j->matters_to_anchor)
927 static int transaction_verify_order_one(Manager *m, Job *j, Job *from, unsigned generation, DBusError *e) {
934 assert(!j->transaction_prev);
936 /* Does a recursive sweep through the ordering graph, looking
937 * for a cycle. If we find cycle we try to break it. */
939 /* Have we seen this before? */
940 if (j->generation == generation) {
943 /* If the marker is NULL we have been here already and
944 * decided the job was loop-free from here. Hence
945 * shortcut things and return right-away. */
949 /* So, the marker is not NULL and we already have been
950 * here. We have a cycle. Let's try to break it. We go
951 * backwards in our path and try to find a suitable
952 * job to remove. We use the marker to find our way
953 * back, since smart how we are we stored our way back
955 log_warning("Found ordering cycle on %s/%s", j->unit->meta.id, job_type_to_string(j->type));
958 for (k = from; k; k = ((k->generation == generation && k->marker != k) ? k->marker : NULL)) {
960 log_info("Walked on cycle path to %s/%s", k->unit->meta.id, job_type_to_string(k->type));
964 !unit_matters_to_anchor(k->unit, k)) {
965 /* Ok, we can drop this one, so let's
970 /* Check if this in fact was the beginning of
978 log_warning("Breaking ordering cycle by deleting job %s/%s", k->unit->meta.id, job_type_to_string(k->type));
979 transaction_delete_unit(m, delete->unit);
983 log_error("Unable to break cycle");
985 dbus_set_error(e, BUS_ERROR_TRANSACTION_ORDER_IS_CYCLIC, "Transaction order is cyclic. See logs for details.");
989 /* Make the marker point to where we come from, so that we can
990 * find our way backwards if we want to break a cycle. We use
991 * a special marker for the beginning: we point to
993 j->marker = from ? from : j;
994 j->generation = generation;
996 /* We assume that the the dependencies are bidirectional, and
997 * hence can ignore UNIT_AFTER */
998 SET_FOREACH(u, j->unit->meta.dependencies[UNIT_BEFORE], i) {
1001 /* Is there a job for this unit? */
1002 if (!(o = hashmap_get(m->transaction_jobs, u)))
1004 /* Ok, there is no job for this in the
1005 * transaction, but maybe there is already one
1007 if (!(o = u->meta.job))
1010 if ((r = transaction_verify_order_one(m, o, j, generation, e)) < 0)
1014 /* Ok, let's backtrack, and remember that this entry is not on
1015 * our path anymore. */
1021 static int transaction_verify_order(Manager *m, unsigned *generation, DBusError *e) {
1030 /* Check if the ordering graph is cyclic. If it is, try to fix
1031 * that up by dropping one of the jobs. */
1033 g = (*generation)++;
1035 HASHMAP_FOREACH(j, m->transaction_jobs, i)
1036 if ((r = transaction_verify_order_one(m, j, NULL, g, e)) < 0)
1042 static void transaction_collect_garbage(Manager *m) {
1047 /* Drop jobs that are not required by any other job */
1055 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1059 log_debug("Garbage collecting job %s/%s", j->unit->meta.id, job_type_to_string(j->type));
1060 transaction_delete_job(m, j, true);
1068 static int transaction_is_destructive(Manager *m, DBusError *e) {
1074 /* Checks whether applying this transaction means that
1075 * existing jobs would be replaced */
1077 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1080 assert(!j->transaction_prev);
1081 assert(!j->transaction_next);
1083 if (j->unit->meta.job &&
1084 j->unit->meta.job != j &&
1085 !job_type_is_superset(j->type, j->unit->meta.job->type)) {
1087 dbus_set_error(e, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE, "Transaction is destructive.");
1095 static void transaction_minimize_impact(Manager *m) {
1099 /* Drops all unnecessary jobs that reverse already active jobs
1100 * or that stop a running service. */
1108 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1109 LIST_FOREACH(transaction, j, j) {
1110 bool stops_running_service, changes_existing_job;
1112 /* If it matters, we shouldn't drop it */
1113 if (j->matters_to_anchor)
1116 /* Would this stop a running service?
1117 * Would this change an existing job?
1118 * If so, let's drop this entry */
1120 stops_running_service =
1121 j->type == JOB_STOP && UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(j->unit));
1123 changes_existing_job =
1124 j->unit->meta.job && job_type_is_conflicting(j->type, j->unit->meta.job->type);
1126 if (!stops_running_service && !changes_existing_job)
1129 if (stops_running_service)
1130 log_info("%s/%s would stop a running service.", j->unit->meta.id, job_type_to_string(j->type));
1132 if (changes_existing_job)
1133 log_info("%s/%s would change existing job.", j->unit->meta.id, job_type_to_string(j->type));
1135 /* Ok, let's get rid of this */
1136 log_info("Deleting %s/%s to minimize impact.", j->unit->meta.id, job_type_to_string(j->type));
1138 transaction_delete_job(m, j, true);
1150 static int transaction_apply(Manager *m) {
1155 /* Moves the transaction jobs to the set of active jobs */
1157 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1159 assert(!j->transaction_prev);
1160 assert(!j->transaction_next);
1165 if ((r = hashmap_put(m->jobs, UINT32_TO_PTR(j->id), j)) < 0)
1169 while ((j = hashmap_steal_first(m->transaction_jobs))) {
1173 if (j->unit->meta.job)
1174 job_free(j->unit->meta.job);
1176 j->unit->meta.job = j;
1177 j->installed = true;
1179 /* We're fully installed. Now let's free data we don't
1182 assert(!j->transaction_next);
1183 assert(!j->transaction_prev);
1185 job_add_to_run_queue(j);
1186 job_add_to_dbus_queue(j);
1190 /* As last step, kill all remaining job dependencies. */
1191 transaction_clean_dependencies(m);
1197 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1201 hashmap_remove(m->jobs, UINT32_TO_PTR(j->id));
1207 static int transaction_activate(Manager *m, JobMode mode, DBusError *e) {
1209 unsigned generation = 1;
1213 /* This applies the changes recorded in transaction_jobs to
1214 * the actual list of jobs, if possible. */
1216 /* First step: figure out which jobs matter */
1217 transaction_find_jobs_that_matter_to_anchor(m, NULL, generation++);
1219 /* Second step: Try not to stop any running services if
1220 * we don't have to. Don't try to reverse running
1221 * jobs if we don't have to. */
1222 transaction_minimize_impact(m);
1224 /* Third step: Drop redundant jobs */
1225 transaction_drop_redundant(m);
1228 /* Fourth step: Let's remove unneeded jobs that might
1230 transaction_collect_garbage(m);
1232 /* Fifth step: verify order makes sense and correct
1233 * cycles if necessary and possible */
1234 if ((r = transaction_verify_order(m, &generation, e)) >= 0)
1238 log_warning("Requested transaction contains an unfixable cyclic ordering dependency: %s", bus_error(e, r));
1242 /* Let's see if the resulting transaction ordering
1243 * graph is still cyclic... */
1247 /* Sixth step: let's drop unmergeable entries if
1248 * necessary and possible, merge entries we can
1250 if ((r = transaction_merge_jobs(m, e)) >= 0)
1254 log_warning("Requested transaction contains unmergable jobs: %s", bus_error(e, r));
1258 /* Seventh step: an entry got dropped, let's garbage
1259 * collect its dependencies. */
1260 transaction_collect_garbage(m);
1262 /* Let's see if the resulting transaction still has
1263 * unmergeable entries ... */
1266 /* Eights step: Drop redundant jobs again, if the merging now allows us to drop more. */
1267 transaction_drop_redundant(m);
1269 /* Ninth step: check whether we can actually apply this */
1270 if (mode == JOB_FAIL)
1271 if ((r = transaction_is_destructive(m, e)) < 0) {
1272 log_notice("Requested transaction contradicts existing jobs: %s", bus_error(e, r));
1276 /* Tenth step: apply changes */
1277 if ((r = transaction_apply(m)) < 0) {
1278 log_warning("Failed to apply transaction: %s", strerror(-r));
1282 assert(hashmap_isempty(m->transaction_jobs));
1283 assert(!m->transaction_anchor);
1288 transaction_abort(m);
1292 static Job* transaction_add_one_job(Manager *m, JobType type, Unit *unit, bool override, bool *is_new) {
1299 /* Looks for an axisting prospective job and returns that. If
1300 * it doesn't exist it is created and added to the prospective
1303 f = hashmap_get(m->transaction_jobs, unit);
1305 LIST_FOREACH(transaction, j, f) {
1306 assert(j->unit == unit);
1308 if (j->type == type) {
1315 if (unit->meta.job && unit->meta.job->type == type)
1317 else if (!(j = job_new(m, type, unit)))
1322 j->matters_to_anchor = false;
1323 j->override = override;
1325 LIST_PREPEND(Job, transaction, f, j);
1327 if ((r = hashmap_replace(m->transaction_jobs, unit, f)) < 0) {
1335 log_debug("Added job %s/%s to transaction.", unit->meta.id, job_type_to_string(type));
1340 void manager_transaction_unlink_job(Manager *m, Job *j, bool delete_dependencies) {
1344 if (j->transaction_prev)
1345 j->transaction_prev->transaction_next = j->transaction_next;
1346 else if (j->transaction_next)
1347 hashmap_replace(m->transaction_jobs, j->unit, j->transaction_next);
1349 hashmap_remove_value(m->transaction_jobs, j->unit, j);
1351 if (j->transaction_next)
1352 j->transaction_next->transaction_prev = j->transaction_prev;
1354 j->transaction_prev = j->transaction_next = NULL;
1356 while (j->subject_list)
1357 job_dependency_free(j->subject_list);
1359 while (j->object_list) {
1360 Job *other = j->object_list->matters ? j->object_list->subject : NULL;
1362 job_dependency_free(j->object_list);
1364 if (other && delete_dependencies) {
1365 log_debug("Deleting job %s/%s as dependency of job %s/%s",
1366 other->unit->meta.id, job_type_to_string(other->type),
1367 j->unit->meta.id, job_type_to_string(j->type));
1368 transaction_delete_job(m, other, delete_dependencies);
1373 static int transaction_add_job_and_dependencies(
1390 assert(type < _JOB_TYPE_MAX);
1393 if (type != JOB_STOP &&
1394 unit->meta.load_state != UNIT_LOADED) {
1395 dbus_set_error(e, BUS_ERROR_LOAD_FAILED, "Unit %s failed to load. See logs for details.", unit->meta.id);
1399 if (!unit_job_is_applicable(unit, type)) {
1400 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);
1404 /* First add the job. */
1405 if (!(ret = transaction_add_one_job(m, type, unit, override, &is_new)))
1408 /* Then, add a link to the job. */
1409 if (!job_dependency_new(by, ret, matters, conflicts))
1413 /* Finally, recursively add in all dependencies. */
1414 if (type == JOB_START || type == JOB_RELOAD_OR_START) {
1415 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES], i)
1416 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, true, override, false, e, NULL)) < 0 && r != -EBADR)
1419 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES_OVERRIDABLE], i)
1420 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, !override, override, false, e, NULL)) < 0 && r != -EBADR) {
1421 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, bus_error(e, r));
1425 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_WANTS], i)
1426 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, false, false, false, e, NULL)) < 0) {
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_REQUISITE], i)
1432 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, true, override, false, e, NULL)) < 0 && r != -EBADR)
1435 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE_OVERRIDABLE], i)
1436 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, !override, override, false, e, NULL)) < 0 && r != -EBADR) {
1437 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, bus_error(e, r));
1441 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_CONFLICTS], i)
1442 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, dep, ret, true, override, true, e, NULL)) < 0 && r != -EBADR)
1445 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_CONFLICTED_BY], i)
1446 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, dep, ret, true, override, false, e, NULL)) < 0 && r != -EBADR)
1449 } else if (type == JOB_STOP || type == JOB_RESTART || type == JOB_TRY_RESTART) {
1451 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRED_BY], i)
1452 if ((r = transaction_add_job_and_dependencies(m, type, dep, ret, true, override, false, e, NULL)) < 0 && r != -EBADR)
1456 /* JOB_VERIFY_STARTED, JOB_RELOAD require no dependency handling */
1468 static int transaction_add_isolate_jobs(Manager *m) {
1476 HASHMAP_FOREACH_KEY(u, k, m->units, i) {
1478 /* ignore aliases */
1479 if (u->meta.id != k)
1482 if (UNIT_VTABLE(u)->no_isolate)
1485 /* No need to stop inactive jobs */
1486 if (UNIT_IS_INACTIVE_OR_MAINTENANCE(unit_active_state(u)))
1489 /* Is there already something listed for this? */
1490 if (hashmap_get(m->transaction_jobs, u))
1493 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, u, NULL, true, false, false, NULL, NULL)) < 0)
1494 log_warning("Cannot add isolate job for unit %s, ignoring: %s", u->meta.id, strerror(-r));
1500 int manager_add_job(Manager *m, JobType type, Unit *unit, JobMode mode, bool override, DBusError *e, Job **_ret) {
1505 assert(type < _JOB_TYPE_MAX);
1507 assert(mode < _JOB_MODE_MAX);
1509 if (mode == JOB_ISOLATE && type != JOB_START) {
1510 dbus_set_error(e, BUS_ERROR_INVALID_JOB_MODE, "Isolate is only valid for start.");
1514 log_debug("Trying to enqueue job %s/%s", unit->meta.id, job_type_to_string(type));
1516 if ((r = transaction_add_job_and_dependencies(m, type, unit, NULL, true, override, false, e, &ret)) < 0) {
1517 transaction_abort(m);
1521 if (mode == JOB_ISOLATE)
1522 if ((r = transaction_add_isolate_jobs(m)) < 0) {
1523 transaction_abort(m);
1527 if ((r = transaction_activate(m, mode, e)) < 0)
1530 log_debug("Enqueued job %s/%s as %u", unit->meta.id, job_type_to_string(type), (unsigned) ret->id);
1538 int manager_add_job_by_name(Manager *m, JobType type, const char *name, JobMode mode, bool override, DBusError *e, Job **_ret) {
1543 assert(type < _JOB_TYPE_MAX);
1545 assert(mode < _JOB_MODE_MAX);
1547 if ((r = manager_load_unit(m, name, NULL, NULL, &unit)) < 0)
1550 return manager_add_job(m, type, unit, mode, override, e, _ret);
1553 Job *manager_get_job(Manager *m, uint32_t id) {
1556 return hashmap_get(m->jobs, UINT32_TO_PTR(id));
1559 Unit *manager_get_unit(Manager *m, const char *name) {
1563 return hashmap_get(m->units, name);
1566 unsigned manager_dispatch_load_queue(Manager *m) {
1572 /* Make sure we are not run recursively */
1573 if (m->dispatching_load_queue)
1576 m->dispatching_load_queue = true;
1578 /* Dispatches the load queue. Takes a unit from the queue and
1579 * tries to load its data until the queue is empty */
1581 while ((meta = m->load_queue)) {
1582 assert(meta->in_load_queue);
1584 unit_load((Unit*) meta);
1588 m->dispatching_load_queue = false;
1592 int manager_load_unit_prepare(Manager *m, const char *name, const char *path, DBusError *e, Unit **_ret) {
1597 assert(name || path);
1599 /* This will prepare the unit for loading, but not actually
1600 * load anything from disk. */
1602 if (path && !is_path(path)) {
1603 dbus_set_error(e, BUS_ERROR_INVALID_PATH, "Path %s is not absolute.", path);
1608 name = file_name_from_path(path);
1610 if (!unit_name_is_valid(name)) {
1611 dbus_set_error(e, BUS_ERROR_INVALID_NAME, "Unit name %s is not valid.", name);
1615 if ((ret = manager_get_unit(m, name))) {
1620 if (!(ret = unit_new(m)))
1624 if (!(ret->meta.fragment_path = strdup(path))) {
1629 if ((r = unit_add_name(ret, name)) < 0) {
1634 unit_add_to_load_queue(ret);
1635 unit_add_to_dbus_queue(ret);
1636 unit_add_to_gc_queue(ret);
1644 int manager_load_unit(Manager *m, const char *name, const char *path, DBusError *e, Unit **_ret) {
1649 /* This will load the service information files, but not actually
1650 * start any services or anything. */
1652 if ((r = manager_load_unit_prepare(m, name, path, e, _ret)) != 0)
1655 manager_dispatch_load_queue(m);
1658 *_ret = unit_follow_merge(*_ret);
1663 void manager_dump_jobs(Manager *s, FILE *f, const char *prefix) {
1670 HASHMAP_FOREACH(j, s->jobs, i)
1671 job_dump(j, f, prefix);
1674 void manager_dump_units(Manager *s, FILE *f, const char *prefix) {
1682 HASHMAP_FOREACH_KEY(u, t, s->units, i)
1683 if (u->meta.id == t)
1684 unit_dump(u, f, prefix);
1687 void manager_clear_jobs(Manager *m) {
1692 transaction_abort(m);
1694 while ((j = hashmap_first(m->jobs)))
1698 unsigned manager_dispatch_run_queue(Manager *m) {
1702 if (m->dispatching_run_queue)
1705 m->dispatching_run_queue = true;
1707 while ((j = m->run_queue)) {
1708 assert(j->installed);
1709 assert(j->in_run_queue);
1711 job_run_and_invalidate(j);
1715 m->dispatching_run_queue = false;
1719 unsigned manager_dispatch_dbus_queue(Manager *m) {
1726 if (m->dispatching_dbus_queue)
1729 m->dispatching_dbus_queue = true;
1731 while ((meta = m->dbus_unit_queue)) {
1732 assert(meta->in_dbus_queue);
1734 bus_unit_send_change_signal((Unit*) meta);
1738 while ((j = m->dbus_job_queue)) {
1739 assert(j->in_dbus_queue);
1741 bus_job_send_change_signal(j);
1745 m->dispatching_dbus_queue = false;
1749 static int manager_process_notify_fd(Manager *m) {
1756 struct msghdr msghdr;
1758 struct ucred *ucred;
1760 struct cmsghdr cmsghdr;
1761 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
1767 iovec.iov_base = buf;
1768 iovec.iov_len = sizeof(buf)-1;
1772 msghdr.msg_iov = &iovec;
1773 msghdr.msg_iovlen = 1;
1774 msghdr.msg_control = &control;
1775 msghdr.msg_controllen = sizeof(control);
1777 if ((n = recvmsg(m->notify_watch.fd, &msghdr, MSG_DONTWAIT)) <= 0) {
1781 if (errno == EAGAIN)
1787 if (msghdr.msg_controllen < CMSG_LEN(sizeof(struct ucred)) ||
1788 control.cmsghdr.cmsg_level != SOL_SOCKET ||
1789 control.cmsghdr.cmsg_type != SCM_CREDENTIALS ||
1790 control.cmsghdr.cmsg_len != CMSG_LEN(sizeof(struct ucred))) {
1791 log_warning("Received notify message without credentials. Ignoring.");
1795 ucred = (struct ucred*) CMSG_DATA(&control.cmsghdr);
1797 if (!(u = hashmap_get(m->watch_pids, LONG_TO_PTR(ucred->pid))))
1798 if (!(u = cgroup_unit_by_pid(m, ucred->pid))) {
1799 log_warning("Cannot find unit for notify message of PID %lu.", (unsigned long) ucred->pid);
1803 assert((size_t) n < sizeof(buf));
1805 if (!(tags = strv_split(buf, "\n\r")))
1808 log_debug("Got notification message for unit %s", u->meta.id);
1810 if (UNIT_VTABLE(u)->notify_message)
1811 UNIT_VTABLE(u)->notify_message(u, ucred->pid, tags);
1819 static int manager_dispatch_sigchld(Manager *m) {
1829 /* First we call waitd() for a PID and do not reap the
1830 * zombie. That way we can still access /proc/$PID for
1831 * it while it is a zombie. */
1832 if (waitid(P_ALL, 0, &si, WEXITED|WNOHANG|WNOWAIT) < 0) {
1834 if (errno == ECHILD)
1846 if (si.si_code == CLD_EXITED || si.si_code == CLD_KILLED || si.si_code == CLD_DUMPED) {
1849 get_process_name(si.si_pid, &name);
1850 log_debug("Got SIGCHLD for process %lu (%s)", (unsigned long) si.si_pid, strna(name));
1854 /* Let's flush any message the dying child might still
1855 * have queued for us. This ensures that the process
1856 * still exists in /proc so that we can figure out
1857 * which cgroup and hence unit it belongs to. */
1858 if ((r = manager_process_notify_fd(m)) < 0)
1861 /* And now figure out the unit this belongs to */
1862 if (!(u = hashmap_get(m->watch_pids, LONG_TO_PTR(si.si_pid))))
1863 u = cgroup_unit_by_pid(m, si.si_pid);
1865 /* And now, we actually reap the zombie. */
1866 if (waitid(P_PID, si.si_pid, &si, WEXITED) < 0) {
1873 if (si.si_code != CLD_EXITED && si.si_code != CLD_KILLED && si.si_code != CLD_DUMPED)
1876 log_debug("Child %lu died (code=%s, status=%i/%s)",
1877 (long unsigned) si.si_pid,
1878 sigchld_code_to_string(si.si_code),
1880 strna(si.si_code == CLD_EXITED ? exit_status_to_string(si.si_status) : signal_to_string(si.si_status)));
1885 log_debug("Child %lu belongs to %s", (long unsigned) si.si_pid, u->meta.id);
1887 hashmap_remove(m->watch_pids, LONG_TO_PTR(si.si_pid));
1888 UNIT_VTABLE(u)->sigchld_event(u, si.si_pid, si.si_code, si.si_status);
1894 static int manager_start_target(Manager *m, const char *name, JobMode mode) {
1898 dbus_error_init(&error);
1900 log_info("Activating special unit %s", name);
1902 if ((r = manager_add_job_by_name(m, JOB_START, name, mode, true, &error, NULL)) < 0)
1903 log_error("Failed to enqueue %s job: %s", name, bus_error(&error, r));
1905 dbus_error_free(&error);
1910 static int manager_process_signal_fd(Manager *m) {
1912 struct signalfd_siginfo sfsi;
1913 bool sigchld = false;
1918 if ((n = read(m->signal_watch.fd, &sfsi, sizeof(sfsi))) != sizeof(sfsi)) {
1923 if (errno == EAGAIN)
1929 log_debug("Received SIG%s", strna(signal_to_string(sfsi.ssi_signo)));
1931 switch (sfsi.ssi_signo) {
1938 if (m->running_as == MANAGER_SYSTEM) {
1939 /* This is for compatibility with the
1940 * original sysvinit */
1941 m->exit_code = MANAGER_REEXECUTE;
1948 if (m->running_as == MANAGER_SYSTEM) {
1949 manager_start_target(m, SPECIAL_CTRL_ALT_DEL_TARGET, JOB_REPLACE);
1953 /* Run the exit target if there is one, if not, just exit. */
1954 if (manager_start_target(m, SPECIAL_EXIT_SERVICE, JOB_REPLACE) < 0) {
1955 m->exit_code = MANAGER_EXIT;
1962 if (m->running_as == MANAGER_SYSTEM)
1963 manager_start_target(m, SPECIAL_KBREQUEST_TARGET, JOB_REPLACE);
1965 /* This is a nop on non-init */
1969 if (m->running_as == MANAGER_SYSTEM)
1970 manager_start_target(m, SPECIAL_SIGPWR_TARGET, JOB_REPLACE);
1972 /* This is a nop on non-init */
1978 u = manager_get_unit(m, SPECIAL_DBUS_SERVICE);
1980 if (!u || UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u))) {
1981 log_info("Trying to reconnect to bus...");
1985 if (!u || !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u))) {
1986 log_info("Loading D-Bus service...");
1987 manager_start_target(m, SPECIAL_DBUS_SERVICE, JOB_REPLACE);
1998 if (!(f = open_memstream(&dump, &size))) {
1999 log_warning("Failed to allocate memory stream.");
2003 manager_dump_units(m, f, "\t");
2004 manager_dump_jobs(m, f, "\t");
2009 log_warning("Failed to write status stream");
2014 log_dump(LOG_INFO, dump);
2021 m->exit_code = MANAGER_RELOAD;
2025 static const char * const table[] = {
2026 [0] = SPECIAL_DEFAULT_TARGET,
2027 [1] = SPECIAL_RESCUE_TARGET,
2028 [2] = SPECIAL_EMERGENCY_TARGET,
2029 [3] = SPECIAL_HALT_TARGET,
2030 [4] = SPECIAL_POWEROFF_TARGET,
2031 [5] = SPECIAL_REBOOT_TARGET
2034 if ((int) sfsi.ssi_signo >= SIGRTMIN+0 &&
2035 (int) sfsi.ssi_signo < SIGRTMIN+(int) ELEMENTSOF(table)) {
2036 manager_start_target(m, table[sfsi.ssi_signo - SIGRTMIN],
2037 (sfsi.ssi_signo == 1 || sfsi.ssi_signo == 2) ? JOB_ISOLATE : JOB_REPLACE);
2041 log_warning("Got unhandled signal <%s>.", strna(signal_to_string(sfsi.ssi_signo)));
2047 return manager_dispatch_sigchld(m);
2052 static int process_event(Manager *m, struct epoll_event *ev) {
2059 assert(w = ev->data.ptr);
2065 /* An incoming signal? */
2066 if (ev->events != EPOLLIN)
2069 if ((r = manager_process_signal_fd(m)) < 0)
2076 /* An incoming daemon notification event? */
2077 if (ev->events != EPOLLIN)
2080 if ((r = manager_process_notify_fd(m)) < 0)
2087 /* Some fd event, to be dispatched to the units */
2088 UNIT_VTABLE(w->data.unit)->fd_event(w->data.unit, w->fd, ev->events, w);
2091 case WATCH_UNIT_TIMER:
2092 case WATCH_JOB_TIMER: {
2096 /* Some timer event, to be dispatched to the units */
2097 if ((k = read(w->fd, &v, sizeof(v))) != sizeof(v)) {
2099 if (k < 0 && (errno == EINTR || errno == EAGAIN))
2102 return k < 0 ? -errno : -EIO;
2105 if (w->type == WATCH_UNIT_TIMER)
2106 UNIT_VTABLE(w->data.unit)->timer_event(w->data.unit, v, w);
2108 job_timer_event(w->data.job, v, w);
2113 /* Some mount table change, intended for the mount subsystem */
2114 mount_fd_event(m, ev->events);
2118 /* Some notification from udev, intended for the device subsystem */
2119 device_fd_event(m, ev->events);
2122 case WATCH_DBUS_WATCH:
2123 bus_watch_event(m, w, ev->events);
2126 case WATCH_DBUS_TIMEOUT:
2127 bus_timeout_event(m, w, ev->events);
2131 assert_not_reached("Unknown epoll event type.");
2137 int manager_loop(Manager *m) {
2140 RATELIMIT_DEFINE(rl, 1*USEC_PER_SEC, 1000);
2143 m->exit_code = MANAGER_RUNNING;
2145 /* Release the path cache */
2146 set_free_free(m->unit_path_cache);
2147 m->unit_path_cache = NULL;
2149 /* There might still be some zombies hanging around from
2150 * before we were exec()'ed. Leat's reap them */
2151 if ((r = manager_dispatch_sigchld(m)) < 0)
2154 while (m->exit_code == MANAGER_RUNNING) {
2155 struct epoll_event event;
2158 if (!ratelimit_test(&rl)) {
2159 /* Yay, something is going seriously wrong, pause a little */
2160 log_warning("Looping too fast. Throttling execution a little.");
2164 if (manager_dispatch_load_queue(m) > 0)
2167 if (manager_dispatch_run_queue(m) > 0)
2170 if (bus_dispatch(m) > 0)
2173 if (manager_dispatch_cleanup_queue(m) > 0)
2176 if (manager_dispatch_gc_queue(m) > 0)
2179 if (manager_dispatch_dbus_queue(m) > 0)
2182 if ((n = epoll_wait(m->epoll_fd, &event, 1, -1)) < 0) {
2192 if ((r = process_event(m, &event)) < 0)
2196 return m->exit_code;
2199 int manager_get_unit_from_dbus_path(Manager *m, const char *s, Unit **_u) {
2207 if (!startswith(s, "/org/freedesktop/systemd1/unit/"))
2210 if (!(n = bus_path_unescape(s+31)))
2213 u = manager_get_unit(m, n);
2224 int manager_get_job_from_dbus_path(Manager *m, const char *s, Job **_j) {
2233 if (!startswith(s, "/org/freedesktop/systemd1/job/"))
2236 if ((r = safe_atou(s + 30, &id)) < 0)
2239 if (!(j = manager_get_job(m, id)))
2247 void manager_send_unit_audit(Manager *m, Unit *u, int type, bool success) {
2252 if (m->audit_fd < 0)
2255 if (!(p = unit_name_to_prefix_and_instance(u->meta.id))) {
2256 log_error("Failed to allocate unit name for audit message: %s", strerror(ENOMEM));
2260 if (audit_log_user_comm_message(m->audit_fd, type, "", p, NULL, NULL, NULL, success) < 0)
2261 log_error("Failed to send audit message: %m");
2268 void manager_dispatch_bus_name_owner_changed(
2271 const char* old_owner,
2272 const char *new_owner) {
2279 if (!(u = hashmap_get(m->watch_bus, name)))
2282 UNIT_VTABLE(u)->bus_name_owner_change(u, name, old_owner, new_owner);
2285 void manager_dispatch_bus_query_pid_done(
2296 if (!(u = hashmap_get(m->watch_bus, name)))
2299 UNIT_VTABLE(u)->bus_query_pid_done(u, name, pid);
2302 int manager_open_serialization(Manager *m, FILE **_f) {
2310 if (m->running_as == MANAGER_SYSTEM) {
2311 mkdir_p("/dev/.systemd", 0755);
2313 if (asprintf(&path, "/dev/.systemd/dump-%lu-XXXXXX", (unsigned long) getpid()) < 0)
2316 if (asprintf(&path, "/tmp/systemd-dump-%lu-XXXXXX", (unsigned long) getpid()) < 0)
2320 saved_umask = umask(0077);
2321 fd = mkostemp(path, O_RDWR|O_CLOEXEC);
2331 log_debug("Serializing state to %s", path);
2334 if (!(f = fdopen(fd, "w+")) < 0)
2342 int manager_serialize(Manager *m, FILE *f, FDSet *fds) {
2352 HASHMAP_FOREACH_KEY(u, t, m->units, i) {
2353 if (u->meta.id != t)
2356 if (!unit_can_serialize(u))
2360 fputs(u->meta.id, f);
2363 if ((r = unit_serialize(u, f, fds)) < 0)
2373 int manager_deserialize(Manager *m, FILE *f, FDSet *fds) {
2379 log_debug("Deserializing state...");
2381 m->n_deserializing ++;
2385 char name[UNIT_NAME_MAX+2];
2388 if (!fgets(name, sizeof(name), f)) {
2398 if ((r = manager_load_unit(m, strstrip(name), NULL, NULL, &u)) < 0)
2401 if ((r = unit_deserialize(u, f, fds)) < 0)
2413 assert(m->n_deserializing > 0);
2414 m->n_deserializing --;
2419 int manager_reload(Manager *m) {
2426 if ((r = manager_open_serialization(m, &f)) < 0)
2429 if (!(fds = fdset_new())) {
2434 if ((r = manager_serialize(m, f, fds)) < 0)
2437 if (fseeko(f, 0, SEEK_SET) < 0) {
2442 /* From here on there is no way back. */
2443 manager_clear_jobs_and_units(m);
2445 /* Find new unit paths */
2446 lookup_paths_free(&m->lookup_paths);
2447 if ((q = lookup_paths_init(&m->lookup_paths, m->running_as)) < 0)
2450 m->n_deserializing ++;
2452 /* First, enumerate what we can from all config files */
2453 if ((q = manager_enumerate(m)) < 0)
2456 /* Second, deserialize our stored data */
2457 if ((q = manager_deserialize(m, f, fds)) < 0)
2463 /* Third, fire things up! */
2464 if ((q = manager_coldplug(m)) < 0)
2467 assert(m->n_deserializing > 0);
2468 m->n_deserializing ++;
2480 bool manager_is_booting_or_shutting_down(Manager *m) {
2485 /* Is the initial job still around? */
2486 if (manager_get_job(m, 1))
2489 /* Is there a job for the shutdown target? */
2490 if (((u = manager_get_unit(m, SPECIAL_SHUTDOWN_TARGET))))
2491 return !!u->meta.job;
2496 void manager_reset_maintenance(Manager *m) {
2502 HASHMAP_FOREACH(u, m->units, i)
2503 unit_reset_maintenance(u);
2506 static const char* const manager_running_as_table[_MANAGER_RUNNING_AS_MAX] = {
2507 [MANAGER_SYSTEM] = "system",
2508 [MANAGER_SESSION] = "session"
2511 DEFINE_STRING_TABLE_LOOKUP(manager_running_as, ManagerRunningAs);