1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
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"
60 #include "exit-status.h"
62 /* As soon as 16 units are in our GC queue, make sure to run a gc sweep */
63 #define GC_QUEUE_ENTRIES_MAX 16
65 /* As soon as 5s passed since a unit was added to our GC queue, make sure to run a gc sweep */
66 #define GC_QUEUE_USEC_MAX (10*USEC_PER_SEC)
68 /* Where clients shall send notification messages to */
69 #define NOTIFY_SOCKET "/org/freedesktop/systemd1/notify"
71 static int manager_setup_notify(Manager *m) {
74 struct sockaddr_un un;
76 struct epoll_event ev;
81 m->notify_watch.type = WATCH_NOTIFY;
82 if ((m->notify_watch.fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0)) < 0) {
83 log_error("Failed to allocate notification socket: %m");
88 sa.sa.sa_family = AF_UNIX;
91 snprintf(sa.un.sun_path+1, sizeof(sa.un.sun_path)-1, NOTIFY_SOCKET "/%llu", random_ull());
93 strncpy(sa.un.sun_path+1, NOTIFY_SOCKET, sizeof(sa.un.sun_path)-1);
95 if (bind(m->notify_watch.fd, &sa.sa, sizeof(sa_family_t) + 1 + strlen(sa.un.sun_path+1)) < 0) {
96 log_error("bind() failed: %m");
100 if (setsockopt(m->notify_watch.fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one)) < 0) {
101 log_error("SO_PASSCRED failed: %m");
107 ev.data.ptr = &m->notify_watch;
109 if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->notify_watch.fd, &ev) < 0)
112 if (!(m->notify_socket = strdup(sa.un.sun_path+1)))
118 static int enable_special_signals(Manager *m) {
123 /* Enable that we get SIGINT on control-alt-del */
124 if (reboot(RB_DISABLE_CAD) < 0)
125 log_warning("Failed to enable ctrl-alt-del handling: %m");
127 if ((fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY)) < 0)
128 log_warning("Failed to open /dev/tty0: %m");
130 /* Enable that we get SIGWINCH on kbrequest */
131 if (ioctl(fd, KDSIGACCEPT, SIGWINCH) < 0)
132 log_warning("Failed to enable kbrequest handling: %s", strerror(errno));
134 close_nointr_nofail(fd);
140 static int manager_setup_signals(Manager *m) {
142 struct epoll_event ev;
147 /* We are not interested in SIGSTOP and friends. */
149 sa.sa_handler = SIG_DFL;
150 sa.sa_flags = SA_NOCLDSTOP|SA_RESTART;
151 assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);
153 assert_se(sigemptyset(&mask) == 0);
155 sigset_add_many(&mask,
156 SIGCHLD, /* Child died */
157 SIGTERM, /* Reexecute daemon */
158 SIGHUP, /* Reload configuration */
159 SIGUSR1, /* systemd/upstart: reconnect to D-Bus */
160 SIGUSR2, /* systemd: dump status */
161 SIGINT, /* Kernel sends us this on control-alt-del */
162 SIGWINCH, /* Kernel sends us this on kbrequest (alt-arrowup) */
163 SIGPWR, /* Some kernel drivers and upsd send us this on power failure */
164 SIGRTMIN+0, /* systemd: start default.target */
165 SIGRTMIN+1, /* systemd: start rescue.target */
166 SIGRTMIN+2, /* systemd: isolate emergency.target */
167 SIGRTMIN+3, /* systemd: start halt.target */
168 SIGRTMIN+4, /* systemd: start poweroff.target */
169 SIGRTMIN+5, /* systemd: start reboot.target */
171 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
173 m->signal_watch.type = WATCH_SIGNAL;
174 if ((m->signal_watch.fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0)
179 ev.data.ptr = &m->signal_watch;
181 if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->signal_watch.fd, &ev) < 0)
184 if (m->running_as == MANAGER_SYSTEM)
185 return enable_special_signals(m);
190 int manager_new(ManagerRunningAs running_as, Manager **_m) {
195 assert(running_as >= 0);
196 assert(running_as < _MANAGER_RUNNING_AS_MAX);
198 if (!(m = new0(Manager, 1)))
201 dual_timestamp_get(&m->startup_timestamp);
203 m->running_as = running_as;
204 m->name_data_slot = m->subscribed_data_slot = -1;
205 m->exit_code = _MANAGER_EXIT_CODE_INVALID;
206 m->pin_cgroupfs_fd = -1;
212 m->signal_watch.fd = m->mount_watch.fd = m->udev_watch.fd = m->epoll_fd = m->dev_autofs_fd = -1;
213 m->current_job_id = 1; /* start as id #1, so that we can leave #0 around as "null-like" value */
215 if (!(m->environment = strv_copy(environ)))
218 if (!(m->units = hashmap_new(string_hash_func, string_compare_func)))
221 if (!(m->jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
224 if (!(m->transaction_jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
227 if (!(m->watch_pids = hashmap_new(trivial_hash_func, trivial_compare_func)))
230 if (!(m->cgroup_bondings = hashmap_new(string_hash_func, string_compare_func)))
233 if (!(m->watch_bus = hashmap_new(string_hash_func, string_compare_func)))
236 if ((m->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0)
239 if ((r = lookup_paths_init(&m->lookup_paths, m->running_as)) < 0)
242 if ((r = manager_setup_signals(m)) < 0)
245 if ((r = manager_setup_cgroup(m)) < 0)
248 if ((r = manager_setup_notify(m)) < 0)
251 /* Try to connect to the busses, if possible. */
252 if ((r = bus_init(m)) < 0)
256 if ((m->audit_fd = audit_open()) < 0)
257 log_error("Failed to connect to audit log: %m");
268 static unsigned manager_dispatch_cleanup_queue(Manager *m) {
274 while ((meta = m->cleanup_queue)) {
275 assert(meta->in_cleanup_queue);
277 unit_free((Unit*) meta);
285 GC_OFFSET_IN_PATH, /* This one is on the path we were travelling */
286 GC_OFFSET_UNSURE, /* No clue */
287 GC_OFFSET_GOOD, /* We still need this unit */
288 GC_OFFSET_BAD, /* We don't need this unit anymore */
292 static void unit_gc_sweep(Unit *u, unsigned gc_marker) {
299 if (u->meta.gc_marker == gc_marker + GC_OFFSET_GOOD ||
300 u->meta.gc_marker == gc_marker + GC_OFFSET_BAD ||
301 u->meta.gc_marker == gc_marker + GC_OFFSET_IN_PATH)
304 if (u->meta.in_cleanup_queue)
307 if (unit_check_gc(u))
310 u->meta.gc_marker = gc_marker + GC_OFFSET_IN_PATH;
314 SET_FOREACH(other, u->meta.dependencies[UNIT_REFERENCED_BY], i) {
315 unit_gc_sweep(other, gc_marker);
317 if (other->meta.gc_marker == gc_marker + GC_OFFSET_GOOD)
320 if (other->meta.gc_marker != gc_marker + GC_OFFSET_BAD)
327 /* We were unable to find anything out about this entry, so
328 * let's investigate it later */
329 u->meta.gc_marker = gc_marker + GC_OFFSET_UNSURE;
330 unit_add_to_gc_queue(u);
334 /* We definitely know that this one is not useful anymore, so
335 * let's mark it for deletion */
336 u->meta.gc_marker = gc_marker + GC_OFFSET_BAD;
337 unit_add_to_cleanup_queue(u);
341 u->meta.gc_marker = gc_marker + GC_OFFSET_GOOD;
344 static unsigned manager_dispatch_gc_queue(Manager *m) {
351 if ((m->n_in_gc_queue < GC_QUEUE_ENTRIES_MAX) &&
352 (m->gc_queue_timestamp <= 0 ||
353 (m->gc_queue_timestamp + GC_QUEUE_USEC_MAX) > now(CLOCK_MONOTONIC)))
356 log_debug("Running GC...");
358 m->gc_marker += _GC_OFFSET_MAX;
359 if (m->gc_marker + _GC_OFFSET_MAX <= _GC_OFFSET_MAX)
362 gc_marker = m->gc_marker;
364 while ((meta = m->gc_queue)) {
365 assert(meta->in_gc_queue);
367 unit_gc_sweep((Unit*) meta, gc_marker);
369 LIST_REMOVE(Meta, gc_queue, m->gc_queue, meta);
370 meta->in_gc_queue = false;
374 if (meta->gc_marker == gc_marker + GC_OFFSET_BAD ||
375 meta->gc_marker == gc_marker + GC_OFFSET_UNSURE) {
376 log_debug("Collecting %s", meta->id);
377 meta->gc_marker = gc_marker + GC_OFFSET_BAD;
378 unit_add_to_cleanup_queue((Unit*) meta);
382 m->n_in_gc_queue = 0;
383 m->gc_queue_timestamp = 0;
388 static void manager_clear_jobs_and_units(Manager *m) {
394 while ((j = hashmap_first(m->transaction_jobs)))
397 while ((u = hashmap_first(m->units)))
400 manager_dispatch_cleanup_queue(m);
402 assert(!m->load_queue);
403 assert(!m->run_queue);
404 assert(!m->dbus_unit_queue);
405 assert(!m->dbus_job_queue);
406 assert(!m->cleanup_queue);
407 assert(!m->gc_queue);
409 assert(hashmap_isempty(m->transaction_jobs));
410 assert(hashmap_isempty(m->jobs));
411 assert(hashmap_isempty(m->units));
414 void manager_free(Manager *m) {
419 manager_clear_jobs_and_units(m);
421 for (c = 0; c < _UNIT_TYPE_MAX; c++)
422 if (unit_vtable[c]->shutdown)
423 unit_vtable[c]->shutdown(m);
425 /* If we reexecute ourselves, we keep the root cgroup
427 manager_shutdown_cgroup(m, m->exit_code != MANAGER_REEXECUTE);
431 hashmap_free(m->units);
432 hashmap_free(m->jobs);
433 hashmap_free(m->transaction_jobs);
434 hashmap_free(m->watch_pids);
435 hashmap_free(m->watch_bus);
437 if (m->epoll_fd >= 0)
438 close_nointr_nofail(m->epoll_fd);
439 if (m->signal_watch.fd >= 0)
440 close_nointr_nofail(m->signal_watch.fd);
441 if (m->notify_watch.fd >= 0)
442 close_nointr_nofail(m->notify_watch.fd);
445 if (m->audit_fd >= 0)
446 audit_close(m->audit_fd);
449 free(m->notify_socket);
451 lookup_paths_free(&m->lookup_paths);
452 strv_free(m->environment);
454 hashmap_free(m->cgroup_bondings);
455 set_free_free(m->unit_path_cache);
460 int manager_enumerate(Manager *m) {
466 /* Let's ask every type to load all units from disk/kernel
467 * that it might know */
468 for (c = 0; c < _UNIT_TYPE_MAX; c++)
469 if (unit_vtable[c]->enumerate)
470 if ((q = unit_vtable[c]->enumerate(m)) < 0)
473 manager_dispatch_load_queue(m);
477 int manager_coldplug(Manager *m) {
485 /* Then, let's set up their initial state. */
486 HASHMAP_FOREACH_KEY(u, k, m->units, i) {
492 if ((q = unit_coldplug(u)) < 0)
499 static void manager_build_unit_path_cache(Manager *m) {
506 set_free_free(m->unit_path_cache);
508 if (!(m->unit_path_cache = set_new(string_hash_func, string_compare_func))) {
509 log_error("Failed to allocate unit path cache.");
513 /* This simply builds a list of files we know exist, so that
514 * we don't always have to go to disk */
516 STRV_FOREACH(i, m->lookup_paths.unit_path) {
519 if (!(d = opendir(*i))) {
520 log_error("Failed to open directory: %m");
524 while ((de = readdir(d))) {
527 if (ignore_file(de->d_name))
530 if (asprintf(&p, "%s/%s", streq(*i, "/") ? "" : *i, de->d_name) < 0) {
535 if ((r = set_put(m->unit_path_cache, p)) < 0) {
548 log_error("Failed to build unit path cache: %s", strerror(-r));
550 set_free_free(m->unit_path_cache);
551 m->unit_path_cache = NULL;
557 int manager_startup(Manager *m, FILE *serialization, FDSet *fds) {
562 manager_build_unit_path_cache(m);
564 /* If we will deserialize make sure that during enumeration
565 * this is already known, so we increase the counter here
568 m->n_deserializing ++;
570 /* First, enumerate what we can from all config files */
571 r = manager_enumerate(m);
573 /* Second, deserialize if there is something to deserialize */
575 if ((q = manager_deserialize(m, serialization, fds)) < 0)
578 /* Third, fire things up! */
579 if ((q = manager_coldplug(m)) < 0)
583 assert(m->n_deserializing > 0);
584 m->n_deserializing --;
590 static void transaction_delete_job(Manager *m, Job *j, bool delete_dependencies) {
594 /* Deletes one job from the transaction */
596 manager_transaction_unlink_job(m, j, delete_dependencies);
602 static void transaction_delete_unit(Manager *m, Unit *u) {
605 /* Deletes all jobs associated with a certain unit from the
608 while ((j = hashmap_get(m->transaction_jobs, u)))
609 transaction_delete_job(m, j, true);
612 static void transaction_clean_dependencies(Manager *m) {
618 /* Drops all dependencies of all installed jobs */
620 HASHMAP_FOREACH(j, m->jobs, i) {
621 while (j->subject_list)
622 job_dependency_free(j->subject_list);
623 while (j->object_list)
624 job_dependency_free(j->object_list);
627 assert(!m->transaction_anchor);
630 static void transaction_abort(Manager *m) {
635 while ((j = hashmap_first(m->transaction_jobs)))
637 transaction_delete_job(m, j, true);
641 assert(hashmap_isempty(m->transaction_jobs));
643 transaction_clean_dependencies(m);
646 static void transaction_find_jobs_that_matter_to_anchor(Manager *m, Job *j, unsigned generation) {
651 /* A recursive sweep through the graph that marks all units
652 * that matter to the anchor job, i.e. are directly or
653 * indirectly a dependency of the anchor job via paths that
654 * are fully marked as mattering. */
659 l = m->transaction_anchor;
661 LIST_FOREACH(subject, l, l) {
663 /* This link does not matter */
667 /* This unit has already been marked */
668 if (l->object->generation == generation)
671 l->object->matters_to_anchor = true;
672 l->object->generation = generation;
674 transaction_find_jobs_that_matter_to_anchor(m, l->object, generation);
678 static void transaction_merge_and_delete_job(Manager *m, Job *j, Job *other, JobType t) {
679 JobDependency *l, *last;
683 assert(j->unit == other->unit);
684 assert(!j->installed);
686 /* Merges 'other' into 'j' and then deletes j. */
689 j->state = JOB_WAITING;
690 j->override = j->override || other->override;
692 j->matters_to_anchor = j->matters_to_anchor || other->matters_to_anchor;
694 /* Patch us in as new owner of the JobDependency objects */
696 LIST_FOREACH(subject, l, other->subject_list) {
697 assert(l->subject == other);
702 /* Merge both lists */
704 last->subject_next = j->subject_list;
706 j->subject_list->subject_prev = last;
707 j->subject_list = other->subject_list;
710 /* Patch us in as new owner of the JobDependency objects */
712 LIST_FOREACH(object, l, other->object_list) {
713 assert(l->object == other);
718 /* Merge both lists */
720 last->object_next = j->object_list;
722 j->object_list->object_prev = last;
723 j->object_list = other->object_list;
726 /* Kill the other job */
727 other->subject_list = NULL;
728 other->object_list = NULL;
729 transaction_delete_job(m, other, true);
731 static bool job_is_conflicted_by(Job *j) {
736 /* Returns true if this job is pulled in by a least one
737 * ConflictedBy dependency. */
739 LIST_FOREACH(object, l, j->object_list)
746 static int delete_one_unmergeable_job(Manager *m, Job *j) {
751 /* Tries to delete one item in the linked list
752 * j->transaction_next->transaction_next->... that conflicts
753 * whith another one, in an attempt to make an inconsistent
754 * transaction work. */
756 /* We rely here on the fact that if a merged with b does not
757 * merge with c, either a or b merge with c neither */
758 LIST_FOREACH(transaction, j, j)
759 LIST_FOREACH(transaction, k, j->transaction_next) {
762 /* Is this one mergeable? Then skip it */
763 if (job_type_is_mergeable(j->type, k->type))
766 /* Ok, we found two that conflict, let's see if we can
767 * drop one of them */
768 if (!j->matters_to_anchor && !k->matters_to_anchor) {
770 /* Both jobs don't matter, so let's
771 * find the one that is smarter to
772 * remove. Let's think positive and
773 * rather remove stops then starts --
774 * except if something is being
775 * stopped because it is conflicted by
776 * another unit in which case we
777 * rather remove the start. */
779 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)));
780 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)));
782 if (j->type == JOB_STOP) {
784 if (job_is_conflicted_by(j))
789 } else if (k->type == JOB_STOP) {
791 if (job_is_conflicted_by(k))
798 } else if (!j->matters_to_anchor)
800 else if (!k->matters_to_anchor)
805 /* Ok, we can drop one, so let's do so. */
806 log_debug("Fixing conflicting jobs by deleting job %s/%s", d->unit->meta.id, job_type_to_string(d->type));
807 transaction_delete_job(m, d, true);
814 static int transaction_merge_jobs(Manager *m, DBusError *e) {
821 /* First step, check whether any of the jobs for one specific
822 * task conflict. If so, try to drop one of them. */
823 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
828 LIST_FOREACH(transaction, k, j->transaction_next) {
829 if (job_type_merge(&t, k->type) >= 0)
832 /* OK, we could not merge all jobs for this
833 * action. Let's see if we can get rid of one
836 if ((r = delete_one_unmergeable_job(m, j)) >= 0)
837 /* Ok, we managed to drop one, now
838 * let's ask our callers to call us
839 * again after garbage collecting */
842 /* We couldn't merge anything. Failure */
843 dbus_set_error(e, BUS_ERROR_TRANSACTION_JOBS_CONFLICTING, "Transaction contains conflicting jobs '%s' and '%s' for %s. Probably contradicting requirement dependencies configured.",
844 job_type_to_string(t), job_type_to_string(k->type), k->unit->meta.id);
849 /* Second step, merge the jobs. */
850 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
854 /* Merge all transactions */
855 LIST_FOREACH(transaction, k, j->transaction_next)
856 assert_se(job_type_merge(&t, k->type) == 0);
858 /* If an active job is mergeable, merge it too */
859 if (j->unit->meta.job)
860 job_type_merge(&t, j->unit->meta.job->type); /* Might fail. Which is OK */
862 while ((k = j->transaction_next)) {
864 transaction_merge_and_delete_job(m, k, j, t);
867 transaction_merge_and_delete_job(m, j, k, t);
870 assert(!j->transaction_next);
871 assert(!j->transaction_prev);
877 static void transaction_drop_redundant(Manager *m) {
882 /* Goes through the transaction and removes all jobs that are
891 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
892 bool changes_something = false;
895 LIST_FOREACH(transaction, k, j) {
897 if (!job_is_anchor(k) &&
898 job_type_is_redundant(k->type, unit_active_state(k->unit)))
901 changes_something = true;
905 if (changes_something)
908 log_debug("Found redundant job %s/%s, dropping.", j->unit->meta.id, job_type_to_string(j->type));
909 transaction_delete_job(m, j, false);
917 static bool unit_matters_to_anchor(Unit *u, Job *j) {
919 assert(!j->transaction_prev);
921 /* Checks whether at least one of the jobs for this unit
922 * matters to the anchor. */
924 LIST_FOREACH(transaction, j, j)
925 if (j->matters_to_anchor)
931 static int transaction_verify_order_one(Manager *m, Job *j, Job *from, unsigned generation, DBusError *e) {
938 assert(!j->transaction_prev);
940 /* Does a recursive sweep through the ordering graph, looking
941 * for a cycle. If we find cycle we try to break it. */
943 /* Have we seen this before? */
944 if (j->generation == generation) {
947 /* If the marker is NULL we have been here already and
948 * decided the job was loop-free from here. Hence
949 * shortcut things and return right-away. */
953 /* So, the marker is not NULL and we already have been
954 * here. We have a cycle. Let's try to break it. We go
955 * backwards in our path and try to find a suitable
956 * job to remove. We use the marker to find our way
957 * back, since smart how we are we stored our way back
959 log_warning("Found ordering cycle on %s/%s", j->unit->meta.id, job_type_to_string(j->type));
962 for (k = from; k; k = ((k->generation == generation && k->marker != k) ? k->marker : NULL)) {
964 log_info("Walked on cycle path to %s/%s", k->unit->meta.id, job_type_to_string(k->type));
968 !unit_matters_to_anchor(k->unit, k)) {
969 /* Ok, we can drop this one, so let's
974 /* Check if this in fact was the beginning of
982 log_warning("Breaking ordering cycle by deleting job %s/%s", k->unit->meta.id, job_type_to_string(k->type));
983 transaction_delete_unit(m, delete->unit);
987 log_error("Unable to break cycle");
989 dbus_set_error(e, BUS_ERROR_TRANSACTION_ORDER_IS_CYCLIC, "Transaction order is cyclic. See logs for details.");
993 /* Make the marker point to where we come from, so that we can
994 * find our way backwards if we want to break a cycle. We use
995 * a special marker for the beginning: we point to
997 j->marker = from ? from : j;
998 j->generation = generation;
1000 /* We assume that the the dependencies are bidirectional, and
1001 * hence can ignore UNIT_AFTER */
1002 SET_FOREACH(u, j->unit->meta.dependencies[UNIT_BEFORE], i) {
1005 /* Is there a job for this unit? */
1006 if (!(o = hashmap_get(m->transaction_jobs, u)))
1008 /* Ok, there is no job for this in the
1009 * transaction, but maybe there is already one
1011 if (!(o = u->meta.job))
1014 if ((r = transaction_verify_order_one(m, o, j, generation, e)) < 0)
1018 /* Ok, let's backtrack, and remember that this entry is not on
1019 * our path anymore. */
1025 static int transaction_verify_order(Manager *m, unsigned *generation, DBusError *e) {
1034 /* Check if the ordering graph is cyclic. If it is, try to fix
1035 * that up by dropping one of the jobs. */
1037 g = (*generation)++;
1039 HASHMAP_FOREACH(j, m->transaction_jobs, i)
1040 if ((r = transaction_verify_order_one(m, j, NULL, g, e)) < 0)
1046 static void transaction_collect_garbage(Manager *m) {
1051 /* Drop jobs that are not required by any other job */
1059 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1063 log_debug("Garbage collecting job %s/%s", j->unit->meta.id, job_type_to_string(j->type));
1064 transaction_delete_job(m, j, true);
1072 static int transaction_is_destructive(Manager *m, DBusError *e) {
1078 /* Checks whether applying this transaction means that
1079 * existing jobs would be replaced */
1081 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1084 assert(!j->transaction_prev);
1085 assert(!j->transaction_next);
1087 if (j->unit->meta.job &&
1088 j->unit->meta.job != j &&
1089 !job_type_is_superset(j->type, j->unit->meta.job->type)) {
1091 dbus_set_error(e, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE, "Transaction is destructive.");
1099 static void transaction_minimize_impact(Manager *m) {
1103 /* Drops all unnecessary jobs that reverse already active jobs
1104 * or that stop a running service. */
1112 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1113 LIST_FOREACH(transaction, j, j) {
1114 bool stops_running_service, changes_existing_job;
1116 /* If it matters, we shouldn't drop it */
1117 if (j->matters_to_anchor)
1120 /* Would this stop a running service?
1121 * Would this change an existing job?
1122 * If so, let's drop this entry */
1124 stops_running_service =
1125 j->type == JOB_STOP && UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(j->unit));
1127 changes_existing_job =
1128 j->unit->meta.job && job_type_is_conflicting(j->type, j->unit->meta.job->type);
1130 if (!stops_running_service && !changes_existing_job)
1133 if (stops_running_service)
1134 log_info("%s/%s would stop a running service.", j->unit->meta.id, job_type_to_string(j->type));
1136 if (changes_existing_job)
1137 log_info("%s/%s would change existing job.", j->unit->meta.id, job_type_to_string(j->type));
1139 /* Ok, let's get rid of this */
1140 log_info("Deleting %s/%s to minimize impact.", j->unit->meta.id, job_type_to_string(j->type));
1142 transaction_delete_job(m, j, true);
1154 static int transaction_apply(Manager *m) {
1159 /* Moves the transaction jobs to the set of active jobs */
1161 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1163 assert(!j->transaction_prev);
1164 assert(!j->transaction_next);
1169 if ((r = hashmap_put(m->jobs, UINT32_TO_PTR(j->id), j)) < 0)
1173 while ((j = hashmap_steal_first(m->transaction_jobs))) {
1177 if (j->unit->meta.job)
1178 job_free(j->unit->meta.job);
1180 j->unit->meta.job = j;
1181 j->installed = true;
1183 /* We're fully installed. Now let's free data we don't
1186 assert(!j->transaction_next);
1187 assert(!j->transaction_prev);
1189 job_add_to_run_queue(j);
1190 job_add_to_dbus_queue(j);
1194 /* As last step, kill all remaining job dependencies. */
1195 transaction_clean_dependencies(m);
1201 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1205 hashmap_remove(m->jobs, UINT32_TO_PTR(j->id));
1211 static int transaction_activate(Manager *m, JobMode mode, DBusError *e) {
1213 unsigned generation = 1;
1217 /* This applies the changes recorded in transaction_jobs to
1218 * the actual list of jobs, if possible. */
1220 /* First step: figure out which jobs matter */
1221 transaction_find_jobs_that_matter_to_anchor(m, NULL, generation++);
1223 /* Second step: Try not to stop any running services if
1224 * we don't have to. Don't try to reverse running
1225 * jobs if we don't have to. */
1226 transaction_minimize_impact(m);
1228 /* Third step: Drop redundant jobs */
1229 transaction_drop_redundant(m);
1232 /* Fourth step: Let's remove unneeded jobs that might
1234 transaction_collect_garbage(m);
1236 /* Fifth step: verify order makes sense and correct
1237 * cycles if necessary and possible */
1238 if ((r = transaction_verify_order(m, &generation, e)) >= 0)
1242 log_warning("Requested transaction contains an unfixable cyclic ordering dependency: %s", bus_error(e, r));
1246 /* Let's see if the resulting transaction ordering
1247 * graph is still cyclic... */
1251 /* Sixth step: let's drop unmergeable entries if
1252 * necessary and possible, merge entries we can
1254 if ((r = transaction_merge_jobs(m, e)) >= 0)
1258 log_warning("Requested transaction contains unmergable jobs: %s", bus_error(e, r));
1262 /* Seventh step: an entry got dropped, let's garbage
1263 * collect its dependencies. */
1264 transaction_collect_garbage(m);
1266 /* Let's see if the resulting transaction still has
1267 * unmergeable entries ... */
1270 /* Eights step: Drop redundant jobs again, if the merging now allows us to drop more. */
1271 transaction_drop_redundant(m);
1273 /* Ninth step: check whether we can actually apply this */
1274 if (mode == JOB_FAIL)
1275 if ((r = transaction_is_destructive(m, e)) < 0) {
1276 log_notice("Requested transaction contradicts existing jobs: %s", bus_error(e, r));
1280 /* Tenth step: apply changes */
1281 if ((r = transaction_apply(m)) < 0) {
1282 log_warning("Failed to apply transaction: %s", strerror(-r));
1286 assert(hashmap_isempty(m->transaction_jobs));
1287 assert(!m->transaction_anchor);
1292 transaction_abort(m);
1296 static Job* transaction_add_one_job(Manager *m, JobType type, Unit *unit, bool override, bool *is_new) {
1302 /* Looks for an axisting prospective job and returns that. If
1303 * it doesn't exist it is created and added to the prospective
1306 f = hashmap_get(m->transaction_jobs, unit);
1308 LIST_FOREACH(transaction, j, f) {
1309 assert(j->unit == unit);
1311 if (j->type == type) {
1318 if (unit->meta.job && unit->meta.job->type == type)
1320 else if (!(j = job_new(m, type, unit)))
1325 j->matters_to_anchor = false;
1326 j->override = override;
1328 LIST_PREPEND(Job, transaction, f, j);
1330 if (hashmap_replace(m->transaction_jobs, unit, f) < 0) {
1338 log_debug("Added job %s/%s to transaction.", unit->meta.id, job_type_to_string(type));
1343 void manager_transaction_unlink_job(Manager *m, Job *j, bool delete_dependencies) {
1347 if (j->transaction_prev)
1348 j->transaction_prev->transaction_next = j->transaction_next;
1349 else if (j->transaction_next)
1350 hashmap_replace(m->transaction_jobs, j->unit, j->transaction_next);
1352 hashmap_remove_value(m->transaction_jobs, j->unit, j);
1354 if (j->transaction_next)
1355 j->transaction_next->transaction_prev = j->transaction_prev;
1357 j->transaction_prev = j->transaction_next = NULL;
1359 while (j->subject_list)
1360 job_dependency_free(j->subject_list);
1362 while (j->object_list) {
1363 Job *other = j->object_list->matters ? j->object_list->subject : NULL;
1365 job_dependency_free(j->object_list);
1367 if (other && delete_dependencies) {
1368 log_debug("Deleting job %s/%s as dependency of job %s/%s",
1369 other->unit->meta.id, job_type_to_string(other->type),
1370 j->unit->meta.id, job_type_to_string(j->type));
1371 transaction_delete_job(m, other, delete_dependencies);
1376 static int transaction_add_job_and_dependencies(
1393 assert(type < _JOB_TYPE_MAX);
1396 if (unit->meta.load_state != UNIT_LOADED && unit->meta.load_state != UNIT_FAILED) {
1397 dbus_set_error(e, BUS_ERROR_LOAD_FAILED, "Unit %s is not loaded properly.", unit->meta.id);
1401 if (type != JOB_STOP && unit->meta.load_state == UNIT_FAILED) {
1402 dbus_set_error(e, BUS_ERROR_LOAD_FAILED, "Unit %s failed to load: %s. You might find more information in the logs.",
1404 strerror(-unit->meta.load_error));
1408 if (!unit_job_is_applicable(unit, type)) {
1409 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);
1413 /* First add the job. */
1414 if (!(ret = transaction_add_one_job(m, type, unit, override, &is_new)))
1417 /* Then, add a link to the job. */
1418 if (!job_dependency_new(by, ret, matters, conflicts))
1422 /* Finally, recursively add in all dependencies. */
1423 if (type == JOB_START || type == JOB_RELOAD_OR_START) {
1424 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES], i)
1425 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, true, override, false, e, NULL)) < 0 && r != -EBADR)
1428 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES_OVERRIDABLE], i)
1429 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, !override, override, false, e, NULL)) < 0 && r != -EBADR) {
1430 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, bus_error(e, r));
1434 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_WANTS], i)
1435 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, false, false, false, e, NULL)) < 0) {
1436 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, bus_error(e, r));
1440 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE], i)
1441 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, true, override, false, e, NULL)) < 0 && r != -EBADR)
1444 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE_OVERRIDABLE], i)
1445 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, !override, override, false, e, NULL)) < 0 && r != -EBADR) {
1446 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, bus_error(e, r));
1450 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_CONFLICTS], i)
1451 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, dep, ret, true, override, true, e, NULL)) < 0 && r != -EBADR)
1454 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_CONFLICTED_BY], i)
1455 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, dep, ret, true, override, false, e, NULL)) < 0 && r != -EBADR)
1458 } else if (type == JOB_STOP || type == JOB_RESTART || type == JOB_TRY_RESTART) {
1460 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRED_BY], i)
1461 if ((r = transaction_add_job_and_dependencies(m, type, dep, ret, true, override, false, e, NULL)) < 0 && r != -EBADR)
1465 /* JOB_VERIFY_STARTED, JOB_RELOAD require no dependency handling */
1477 static int transaction_add_isolate_jobs(Manager *m) {
1485 HASHMAP_FOREACH_KEY(u, k, m->units, i) {
1487 /* ignore aliases */
1488 if (u->meta.id != k)
1491 if (UNIT_VTABLE(u)->no_isolate)
1494 /* No need to stop inactive jobs */
1495 if (UNIT_IS_INACTIVE_OR_MAINTENANCE(unit_active_state(u)))
1498 /* Is there already something listed for this? */
1499 if (hashmap_get(m->transaction_jobs, u))
1502 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, u, NULL, true, false, false, NULL, NULL)) < 0)
1503 log_warning("Cannot add isolate job for unit %s, ignoring: %s", u->meta.id, strerror(-r));
1509 int manager_add_job(Manager *m, JobType type, Unit *unit, JobMode mode, bool override, DBusError *e, Job **_ret) {
1514 assert(type < _JOB_TYPE_MAX);
1516 assert(mode < _JOB_MODE_MAX);
1518 if (mode == JOB_ISOLATE && type != JOB_START) {
1519 dbus_set_error(e, BUS_ERROR_INVALID_JOB_MODE, "Isolate is only valid for start.");
1523 log_debug("Trying to enqueue job %s/%s", unit->meta.id, job_type_to_string(type));
1525 if ((r = transaction_add_job_and_dependencies(m, type, unit, NULL, true, override, false, e, &ret)) < 0) {
1526 transaction_abort(m);
1530 if (mode == JOB_ISOLATE)
1531 if ((r = transaction_add_isolate_jobs(m)) < 0) {
1532 transaction_abort(m);
1536 if ((r = transaction_activate(m, mode, e)) < 0)
1539 log_debug("Enqueued job %s/%s as %u", unit->meta.id, job_type_to_string(type), (unsigned) ret->id);
1547 int manager_add_job_by_name(Manager *m, JobType type, const char *name, JobMode mode, bool override, DBusError *e, Job **_ret) {
1552 assert(type < _JOB_TYPE_MAX);
1554 assert(mode < _JOB_MODE_MAX);
1556 if ((r = manager_load_unit(m, name, NULL, NULL, &unit)) < 0)
1559 return manager_add_job(m, type, unit, mode, override, e, _ret);
1562 Job *manager_get_job(Manager *m, uint32_t id) {
1565 return hashmap_get(m->jobs, UINT32_TO_PTR(id));
1568 Unit *manager_get_unit(Manager *m, const char *name) {
1572 return hashmap_get(m->units, name);
1575 unsigned manager_dispatch_load_queue(Manager *m) {
1581 /* Make sure we are not run recursively */
1582 if (m->dispatching_load_queue)
1585 m->dispatching_load_queue = true;
1587 /* Dispatches the load queue. Takes a unit from the queue and
1588 * tries to load its data until the queue is empty */
1590 while ((meta = m->load_queue)) {
1591 assert(meta->in_load_queue);
1593 unit_load((Unit*) meta);
1597 m->dispatching_load_queue = false;
1601 int manager_load_unit_prepare(Manager *m, const char *name, const char *path, DBusError *e, Unit **_ret) {
1606 assert(name || path);
1608 /* This will prepare the unit for loading, but not actually
1609 * load anything from disk. */
1611 if (path && !is_path(path)) {
1612 dbus_set_error(e, BUS_ERROR_INVALID_PATH, "Path %s is not absolute.", path);
1617 name = file_name_from_path(path);
1619 if (!unit_name_is_valid(name)) {
1620 dbus_set_error(e, BUS_ERROR_INVALID_NAME, "Unit name %s is not valid.", name);
1624 if ((ret = manager_get_unit(m, name))) {
1629 if (!(ret = unit_new(m)))
1633 if (!(ret->meta.fragment_path = strdup(path))) {
1638 if ((r = unit_add_name(ret, name)) < 0) {
1643 unit_add_to_load_queue(ret);
1644 unit_add_to_dbus_queue(ret);
1645 unit_add_to_gc_queue(ret);
1653 int manager_load_unit(Manager *m, const char *name, const char *path, DBusError *e, Unit **_ret) {
1658 /* This will load the service information files, but not actually
1659 * start any services or anything. */
1661 if ((r = manager_load_unit_prepare(m, name, path, e, _ret)) != 0)
1664 manager_dispatch_load_queue(m);
1667 *_ret = unit_follow_merge(*_ret);
1672 void manager_dump_jobs(Manager *s, FILE *f, const char *prefix) {
1679 HASHMAP_FOREACH(j, s->jobs, i)
1680 job_dump(j, f, prefix);
1683 void manager_dump_units(Manager *s, FILE *f, const char *prefix) {
1691 HASHMAP_FOREACH_KEY(u, t, s->units, i)
1692 if (u->meta.id == t)
1693 unit_dump(u, f, prefix);
1696 void manager_clear_jobs(Manager *m) {
1701 transaction_abort(m);
1703 while ((j = hashmap_first(m->jobs)))
1707 unsigned manager_dispatch_run_queue(Manager *m) {
1711 if (m->dispatching_run_queue)
1714 m->dispatching_run_queue = true;
1716 while ((j = m->run_queue)) {
1717 assert(j->installed);
1718 assert(j->in_run_queue);
1720 job_run_and_invalidate(j);
1724 m->dispatching_run_queue = false;
1728 unsigned manager_dispatch_dbus_queue(Manager *m) {
1735 if (m->dispatching_dbus_queue)
1738 m->dispatching_dbus_queue = true;
1740 while ((meta = m->dbus_unit_queue)) {
1741 assert(meta->in_dbus_queue);
1743 bus_unit_send_change_signal((Unit*) meta);
1747 while ((j = m->dbus_job_queue)) {
1748 assert(j->in_dbus_queue);
1750 bus_job_send_change_signal(j);
1754 m->dispatching_dbus_queue = false;
1758 static int manager_process_notify_fd(Manager *m) {
1765 struct msghdr msghdr;
1767 struct ucred *ucred;
1769 struct cmsghdr cmsghdr;
1770 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
1776 iovec.iov_base = buf;
1777 iovec.iov_len = sizeof(buf)-1;
1781 msghdr.msg_iov = &iovec;
1782 msghdr.msg_iovlen = 1;
1783 msghdr.msg_control = &control;
1784 msghdr.msg_controllen = sizeof(control);
1786 if ((n = recvmsg(m->notify_watch.fd, &msghdr, MSG_DONTWAIT)) <= 0) {
1790 if (errno == EAGAIN || errno == EINTR)
1796 if (msghdr.msg_controllen < CMSG_LEN(sizeof(struct ucred)) ||
1797 control.cmsghdr.cmsg_level != SOL_SOCKET ||
1798 control.cmsghdr.cmsg_type != SCM_CREDENTIALS ||
1799 control.cmsghdr.cmsg_len != CMSG_LEN(sizeof(struct ucred))) {
1800 log_warning("Received notify message without credentials. Ignoring.");
1804 ucred = (struct ucred*) CMSG_DATA(&control.cmsghdr);
1806 if (!(u = hashmap_get(m->watch_pids, LONG_TO_PTR(ucred->pid))))
1807 if (!(u = cgroup_unit_by_pid(m, ucred->pid))) {
1808 log_warning("Cannot find unit for notify message of PID %lu.", (unsigned long) ucred->pid);
1812 assert((size_t) n < sizeof(buf));
1814 if (!(tags = strv_split(buf, "\n\r")))
1817 log_debug("Got notification message for unit %s", u->meta.id);
1819 if (UNIT_VTABLE(u)->notify_message)
1820 UNIT_VTABLE(u)->notify_message(u, ucred->pid, tags);
1828 static int manager_dispatch_sigchld(Manager *m) {
1838 /* First we call waitd() for a PID and do not reap the
1839 * zombie. That way we can still access /proc/$PID for
1840 * it while it is a zombie. */
1841 if (waitid(P_ALL, 0, &si, WEXITED|WNOHANG|WNOWAIT) < 0) {
1843 if (errno == ECHILD)
1855 if (si.si_code == CLD_EXITED || si.si_code == CLD_KILLED || si.si_code == CLD_DUMPED) {
1858 get_process_name(si.si_pid, &name);
1859 log_debug("Got SIGCHLD for process %lu (%s)", (unsigned long) si.si_pid, strna(name));
1863 /* Let's flush any message the dying child might still
1864 * have queued for us. This ensures that the process
1865 * still exists in /proc so that we can figure out
1866 * which cgroup and hence unit it belongs to. */
1867 if ((r = manager_process_notify_fd(m)) < 0)
1870 /* And now figure out the unit this belongs to */
1871 if (!(u = hashmap_get(m->watch_pids, LONG_TO_PTR(si.si_pid))))
1872 u = cgroup_unit_by_pid(m, si.si_pid);
1874 /* And now, we actually reap the zombie. */
1875 if (waitid(P_PID, si.si_pid, &si, WEXITED) < 0) {
1882 if (si.si_code != CLD_EXITED && si.si_code != CLD_KILLED && si.si_code != CLD_DUMPED)
1885 log_debug("Child %lu died (code=%s, status=%i/%s)",
1886 (long unsigned) si.si_pid,
1887 sigchld_code_to_string(si.si_code),
1889 strna(si.si_code == CLD_EXITED
1890 ? exit_status_to_string(si.si_status, EXIT_STATUS_FULL)
1891 : signal_to_string(si.si_status)));
1896 log_debug("Child %lu belongs to %s", (long unsigned) si.si_pid, u->meta.id);
1898 hashmap_remove(m->watch_pids, LONG_TO_PTR(si.si_pid));
1899 UNIT_VTABLE(u)->sigchld_event(u, si.si_pid, si.si_code, si.si_status);
1905 static int manager_start_target(Manager *m, const char *name, JobMode mode) {
1909 dbus_error_init(&error);
1911 log_info("Activating special unit %s", name);
1913 if ((r = manager_add_job_by_name(m, JOB_START, name, mode, true, &error, NULL)) < 0)
1914 log_error("Failed to enqueue %s job: %s", name, bus_error(&error, r));
1916 dbus_error_free(&error);
1921 static int manager_process_signal_fd(Manager *m) {
1923 struct signalfd_siginfo sfsi;
1924 bool sigchld = false;
1929 if ((n = read(m->signal_watch.fd, &sfsi, sizeof(sfsi))) != sizeof(sfsi)) {
1934 if (errno == EINTR || errno == EAGAIN)
1940 log_debug("Received SIG%s", strna(signal_to_string(sfsi.ssi_signo)));
1942 switch (sfsi.ssi_signo) {
1949 if (m->running_as == MANAGER_SYSTEM) {
1950 /* This is for compatibility with the
1951 * original sysvinit */
1952 m->exit_code = MANAGER_REEXECUTE;
1959 if (m->running_as == MANAGER_SYSTEM) {
1960 manager_start_target(m, SPECIAL_CTRL_ALT_DEL_TARGET, JOB_REPLACE);
1964 /* Run the exit target if there is one, if not, just exit. */
1965 if (manager_start_target(m, SPECIAL_EXIT_SERVICE, JOB_REPLACE) < 0) {
1966 m->exit_code = MANAGER_EXIT;
1973 if (m->running_as == MANAGER_SYSTEM)
1974 manager_start_target(m, SPECIAL_KBREQUEST_TARGET, JOB_REPLACE);
1976 /* This is a nop on non-init */
1980 if (m->running_as == MANAGER_SYSTEM)
1981 manager_start_target(m, SPECIAL_SIGPWR_TARGET, JOB_REPLACE);
1983 /* This is a nop on non-init */
1989 u = manager_get_unit(m, SPECIAL_DBUS_SERVICE);
1991 if (!u || UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u))) {
1992 log_info("Trying to reconnect to bus...");
1996 if (!u || !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u))) {
1997 log_info("Loading D-Bus service...");
1998 manager_start_target(m, SPECIAL_DBUS_SERVICE, JOB_REPLACE);
2009 if (!(f = open_memstream(&dump, &size))) {
2010 log_warning("Failed to allocate memory stream.");
2014 manager_dump_units(m, f, "\t");
2015 manager_dump_jobs(m, f, "\t");
2020 log_warning("Failed to write status stream");
2025 log_dump(LOG_INFO, dump);
2032 m->exit_code = MANAGER_RELOAD;
2036 static const char * const table[] = {
2037 [0] = SPECIAL_DEFAULT_TARGET,
2038 [1] = SPECIAL_RESCUE_TARGET,
2039 [2] = SPECIAL_EMERGENCY_TARGET,
2040 [3] = SPECIAL_HALT_TARGET,
2041 [4] = SPECIAL_POWEROFF_TARGET,
2042 [5] = SPECIAL_REBOOT_TARGET
2045 if ((int) sfsi.ssi_signo >= SIGRTMIN+0 &&
2046 (int) sfsi.ssi_signo < SIGRTMIN+(int) ELEMENTSOF(table)) {
2047 manager_start_target(m, table[sfsi.ssi_signo - SIGRTMIN],
2048 (sfsi.ssi_signo == 1 || sfsi.ssi_signo == 2) ? JOB_ISOLATE : JOB_REPLACE);
2052 log_warning("Got unhandled signal <%s>.", strna(signal_to_string(sfsi.ssi_signo)));
2058 return manager_dispatch_sigchld(m);
2063 static int process_event(Manager *m, struct epoll_event *ev) {
2070 assert(w = ev->data.ptr);
2076 /* An incoming signal? */
2077 if (ev->events != EPOLLIN)
2080 if ((r = manager_process_signal_fd(m)) < 0)
2087 /* An incoming daemon notification event? */
2088 if (ev->events != EPOLLIN)
2091 if ((r = manager_process_notify_fd(m)) < 0)
2098 /* Some fd event, to be dispatched to the units */
2099 UNIT_VTABLE(w->data.unit)->fd_event(w->data.unit, w->fd, ev->events, w);
2102 case WATCH_UNIT_TIMER:
2103 case WATCH_JOB_TIMER: {
2107 /* Some timer event, to be dispatched to the units */
2108 if ((k = read(w->fd, &v, sizeof(v))) != sizeof(v)) {
2110 if (k < 0 && (errno == EINTR || errno == EAGAIN))
2113 return k < 0 ? -errno : -EIO;
2116 if (w->type == WATCH_UNIT_TIMER)
2117 UNIT_VTABLE(w->data.unit)->timer_event(w->data.unit, v, w);
2119 job_timer_event(w->data.job, v, w);
2124 /* Some mount table change, intended for the mount subsystem */
2125 mount_fd_event(m, ev->events);
2129 /* Some notification from udev, intended for the device subsystem */
2130 device_fd_event(m, ev->events);
2133 case WATCH_DBUS_WATCH:
2134 bus_watch_event(m, w, ev->events);
2137 case WATCH_DBUS_TIMEOUT:
2138 bus_timeout_event(m, w, ev->events);
2142 assert_not_reached("Unknown epoll event type.");
2148 int manager_loop(Manager *m) {
2151 RATELIMIT_DEFINE(rl, 1*USEC_PER_SEC, 1000);
2154 m->exit_code = MANAGER_RUNNING;
2156 /* Release the path cache */
2157 set_free_free(m->unit_path_cache);
2158 m->unit_path_cache = NULL;
2160 /* There might still be some zombies hanging around from
2161 * before we were exec()'ed. Leat's reap them */
2162 if ((r = manager_dispatch_sigchld(m)) < 0)
2165 while (m->exit_code == MANAGER_RUNNING) {
2166 struct epoll_event event;
2169 if (!ratelimit_test(&rl)) {
2170 /* Yay, something is going seriously wrong, pause a little */
2171 log_warning("Looping too fast. Throttling execution a little.");
2175 if (manager_dispatch_load_queue(m) > 0)
2178 if (manager_dispatch_run_queue(m) > 0)
2181 if (bus_dispatch(m) > 0)
2184 if (manager_dispatch_cleanup_queue(m) > 0)
2187 if (manager_dispatch_gc_queue(m) > 0)
2190 if (manager_dispatch_dbus_queue(m) > 0)
2193 if ((n = epoll_wait(m->epoll_fd, &event, 1, -1)) < 0) {
2203 if ((r = process_event(m, &event)) < 0)
2207 return m->exit_code;
2210 int manager_get_unit_from_dbus_path(Manager *m, const char *s, Unit **_u) {
2218 if (!startswith(s, "/org/freedesktop/systemd1/unit/"))
2221 if (!(n = bus_path_unescape(s+31)))
2224 u = manager_get_unit(m, n);
2235 int manager_get_job_from_dbus_path(Manager *m, const char *s, Job **_j) {
2244 if (!startswith(s, "/org/freedesktop/systemd1/job/"))
2247 if ((r = safe_atou(s + 30, &id)) < 0)
2250 if (!(j = manager_get_job(m, id)))
2258 void manager_send_unit_audit(Manager *m, Unit *u, int type, bool success) {
2263 if (m->audit_fd < 0)
2266 /* Don't generate audit events if the service was already
2267 * started and we're just deserializing */
2268 if (m->n_deserializing > 0)
2271 if (!(p = unit_name_to_prefix_and_instance(u->meta.id))) {
2272 log_error("Failed to allocate unit name for audit message: %s", strerror(ENOMEM));
2276 if (audit_log_user_comm_message(m->audit_fd, type, "", p, NULL, NULL, NULL, success) < 0)
2277 log_error("Failed to send audit message: %m");
2284 void manager_dispatch_bus_name_owner_changed(
2287 const char* old_owner,
2288 const char *new_owner) {
2295 if (!(u = hashmap_get(m->watch_bus, name)))
2298 UNIT_VTABLE(u)->bus_name_owner_change(u, name, old_owner, new_owner);
2301 void manager_dispatch_bus_query_pid_done(
2312 if (!(u = hashmap_get(m->watch_bus, name)))
2315 UNIT_VTABLE(u)->bus_query_pid_done(u, name, pid);
2318 int manager_open_serialization(Manager *m, FILE **_f) {
2326 if (m->running_as == MANAGER_SYSTEM) {
2327 mkdir_p("/dev/.systemd", 0755);
2329 if (asprintf(&path, "/dev/.systemd/dump-%lu-XXXXXX", (unsigned long) getpid()) < 0)
2332 if (asprintf(&path, "/tmp/systemd-dump-%lu-XXXXXX", (unsigned long) getpid()) < 0)
2336 saved_umask = umask(0077);
2337 fd = mkostemp(path, O_RDWR|O_CLOEXEC);
2347 log_debug("Serializing state to %s", path);
2350 if (!(f = fdopen(fd, "w+")) < 0)
2358 int manager_serialize(Manager *m, FILE *f, FDSet *fds) {
2368 fprintf(f, "startup-timestamp=%llu %llu\n\n",
2369 (unsigned long long) m->startup_timestamp.realtime,
2370 (unsigned long long) m->startup_timestamp.monotonic);
2372 HASHMAP_FOREACH_KEY(u, t, m->units, i) {
2373 if (u->meta.id != t)
2376 if (!unit_can_serialize(u))
2380 fputs(u->meta.id, f);
2383 if ((r = unit_serialize(u, f, fds)) < 0)
2393 int manager_deserialize(Manager *m, FILE *f, FDSet *fds) {
2399 log_debug("Deserializing state...");
2401 m->n_deserializing ++;
2404 char line[1024], *l;
2406 if (!fgets(line, sizeof(line), f)) {
2421 if (startswith(l, "startup-timestamp=")) {
2422 unsigned long long a, b;
2424 if (sscanf(l+18, "%lli %llu", &a, &b) != 2)
2425 log_debug("Failed to parse startup timestamp value %s", l+18);
2427 m->startup_timestamp.realtime = a;
2428 m->startup_timestamp.monotonic = b;
2431 log_debug("Unknown serialization item '%s'", l);
2436 char name[UNIT_NAME_MAX+2];
2439 if (!fgets(name, sizeof(name), f)) {
2450 if ((r = manager_load_unit(m, strstrip(name), NULL, NULL, &u)) < 0)
2453 if ((r = unit_deserialize(u, f, fds)) < 0)
2463 assert(m->n_deserializing > 0);
2464 m->n_deserializing --;
2469 int manager_reload(Manager *m) {
2476 if ((r = manager_open_serialization(m, &f)) < 0)
2479 if (!(fds = fdset_new())) {
2484 if ((r = manager_serialize(m, f, fds)) < 0)
2487 if (fseeko(f, 0, SEEK_SET) < 0) {
2492 /* From here on there is no way back. */
2493 manager_clear_jobs_and_units(m);
2495 /* Find new unit paths */
2496 lookup_paths_free(&m->lookup_paths);
2497 if ((q = lookup_paths_init(&m->lookup_paths, m->running_as)) < 0)
2500 m->n_deserializing ++;
2502 /* First, enumerate what we can from all config files */
2503 if ((q = manager_enumerate(m)) < 0)
2506 /* Second, deserialize our stored data */
2507 if ((q = manager_deserialize(m, f, fds)) < 0)
2513 /* Third, fire things up! */
2514 if ((q = manager_coldplug(m)) < 0)
2517 assert(m->n_deserializing > 0);
2518 m->n_deserializing ++;
2530 bool manager_is_booting_or_shutting_down(Manager *m) {
2535 /* Is the initial job still around? */
2536 if (manager_get_job(m, 1))
2539 /* Is there a job for the shutdown target? */
2540 if (((u = manager_get_unit(m, SPECIAL_SHUTDOWN_TARGET))))
2541 return !!u->meta.job;
2546 void manager_reset_maintenance(Manager *m) {
2552 HASHMAP_FOREACH(u, m->units, i)
2553 unit_reset_maintenance(u);
2556 static const char* const manager_running_as_table[_MANAGER_RUNNING_AS_MAX] = {
2557 [MANAGER_SYSTEM] = "system",
2558 [MANAGER_SESSION] = "session"
2561 DEFINE_STRING_TABLE_LOOKUP(manager_running_as, ManagerRunningAs);