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)))
115 log_debug("Using notification socket %s", m->notify_socket);
120 static int enable_special_signals(Manager *m) {
125 /* Enable that we get SIGINT on control-alt-del */
126 if (reboot(RB_DISABLE_CAD) < 0)
127 log_warning("Failed to enable ctrl-alt-del handling: %m");
129 if ((fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY)) < 0)
130 log_warning("Failed to open /dev/tty0: %m");
132 /* Enable that we get SIGWINCH on kbrequest */
133 if (ioctl(fd, KDSIGACCEPT, SIGWINCH) < 0)
134 log_warning("Failed to enable kbrequest handling: %s", strerror(errno));
136 close_nointr_nofail(fd);
142 static int manager_setup_signals(Manager *m) {
144 struct epoll_event ev;
149 /* We are not interested in SIGSTOP and friends. */
151 sa.sa_handler = SIG_DFL;
152 sa.sa_flags = SA_NOCLDSTOP|SA_RESTART;
153 assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);
155 assert_se(sigemptyset(&mask) == 0);
157 sigset_add_many(&mask,
158 SIGCHLD, /* Child died */
159 SIGTERM, /* Reexecute daemon */
160 SIGHUP, /* Reload configuration */
161 SIGUSR1, /* systemd/upstart: reconnect to D-Bus */
162 SIGUSR2, /* systemd: dump status */
163 SIGINT, /* Kernel sends us this on control-alt-del */
164 SIGWINCH, /* Kernel sends us this on kbrequest (alt-arrowup) */
165 SIGPWR, /* Some kernel drivers and upsd send us this on power failure */
166 SIGRTMIN+0, /* systemd: start default.target */
167 SIGRTMIN+1, /* systemd: start rescue.target */
168 SIGRTMIN+2, /* systemd: isolate emergency.target */
169 SIGRTMIN+3, /* systemd: start halt.target */
170 SIGRTMIN+4, /* systemd: start poweroff.target */
171 SIGRTMIN+5, /* systemd: start reboot.target */
173 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
175 m->signal_watch.type = WATCH_SIGNAL;
176 if ((m->signal_watch.fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0)
181 ev.data.ptr = &m->signal_watch;
183 if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->signal_watch.fd, &ev) < 0)
186 if (m->running_as == MANAGER_SYSTEM)
187 return enable_special_signals(m);
192 int manager_new(ManagerRunningAs running_as, Manager **_m) {
197 assert(running_as >= 0);
198 assert(running_as < _MANAGER_RUNNING_AS_MAX);
200 if (!(m = new0(Manager, 1)))
203 dual_timestamp_get(&m->startup_timestamp);
205 m->running_as = running_as;
206 m->name_data_slot = m->subscribed_data_slot = -1;
207 m->exit_code = _MANAGER_EXIT_CODE_INVALID;
208 m->pin_cgroupfs_fd = -1;
214 m->signal_watch.fd = m->mount_watch.fd = m->udev_watch.fd = m->epoll_fd = m->dev_autofs_fd = -1;
215 m->current_job_id = 1; /* start as id #1, so that we can leave #0 around as "null-like" value */
217 if (!(m->environment = strv_copy(environ)))
220 if (!(m->units = hashmap_new(string_hash_func, string_compare_func)))
223 if (!(m->jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
226 if (!(m->transaction_jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
229 if (!(m->watch_pids = hashmap_new(trivial_hash_func, trivial_compare_func)))
232 if (!(m->cgroup_bondings = hashmap_new(string_hash_func, string_compare_func)))
235 if (!(m->watch_bus = hashmap_new(string_hash_func, string_compare_func)))
238 if ((m->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0)
241 if ((r = lookup_paths_init(&m->lookup_paths, m->running_as)) < 0)
244 if ((r = manager_setup_signals(m)) < 0)
247 if ((r = manager_setup_cgroup(m)) < 0)
250 if ((r = manager_setup_notify(m)) < 0)
253 /* Try to connect to the busses, if possible. */
254 if ((r = bus_init(m)) < 0)
258 if ((m->audit_fd = audit_open()) < 0)
259 log_error("Failed to connect to audit log: %m");
270 static unsigned manager_dispatch_cleanup_queue(Manager *m) {
276 while ((meta = m->cleanup_queue)) {
277 assert(meta->in_cleanup_queue);
279 unit_free((Unit*) meta);
287 GC_OFFSET_IN_PATH, /* This one is on the path we were travelling */
288 GC_OFFSET_UNSURE, /* No clue */
289 GC_OFFSET_GOOD, /* We still need this unit */
290 GC_OFFSET_BAD, /* We don't need this unit anymore */
294 static void unit_gc_sweep(Unit *u, unsigned gc_marker) {
301 if (u->meta.gc_marker == gc_marker + GC_OFFSET_GOOD ||
302 u->meta.gc_marker == gc_marker + GC_OFFSET_BAD ||
303 u->meta.gc_marker == gc_marker + GC_OFFSET_IN_PATH)
306 if (u->meta.in_cleanup_queue)
309 if (unit_check_gc(u))
312 u->meta.gc_marker = gc_marker + GC_OFFSET_IN_PATH;
316 SET_FOREACH(other, u->meta.dependencies[UNIT_REFERENCED_BY], i) {
317 unit_gc_sweep(other, gc_marker);
319 if (other->meta.gc_marker == gc_marker + GC_OFFSET_GOOD)
322 if (other->meta.gc_marker != gc_marker + GC_OFFSET_BAD)
329 /* We were unable to find anything out about this entry, so
330 * let's investigate it later */
331 u->meta.gc_marker = gc_marker + GC_OFFSET_UNSURE;
332 unit_add_to_gc_queue(u);
336 /* We definitely know that this one is not useful anymore, so
337 * let's mark it for deletion */
338 u->meta.gc_marker = gc_marker + GC_OFFSET_BAD;
339 unit_add_to_cleanup_queue(u);
343 u->meta.gc_marker = gc_marker + GC_OFFSET_GOOD;
346 static unsigned manager_dispatch_gc_queue(Manager *m) {
353 if ((m->n_in_gc_queue < GC_QUEUE_ENTRIES_MAX) &&
354 (m->gc_queue_timestamp <= 0 ||
355 (m->gc_queue_timestamp + GC_QUEUE_USEC_MAX) > now(CLOCK_MONOTONIC)))
358 log_debug("Running GC...");
360 m->gc_marker += _GC_OFFSET_MAX;
361 if (m->gc_marker + _GC_OFFSET_MAX <= _GC_OFFSET_MAX)
364 gc_marker = m->gc_marker;
366 while ((meta = m->gc_queue)) {
367 assert(meta->in_gc_queue);
369 unit_gc_sweep((Unit*) meta, gc_marker);
371 LIST_REMOVE(Meta, gc_queue, m->gc_queue, meta);
372 meta->in_gc_queue = false;
376 if (meta->gc_marker == gc_marker + GC_OFFSET_BAD ||
377 meta->gc_marker == gc_marker + GC_OFFSET_UNSURE) {
378 log_debug("Collecting %s", meta->id);
379 meta->gc_marker = gc_marker + GC_OFFSET_BAD;
380 unit_add_to_cleanup_queue((Unit*) meta);
384 m->n_in_gc_queue = 0;
385 m->gc_queue_timestamp = 0;
390 static void manager_clear_jobs_and_units(Manager *m) {
396 while ((j = hashmap_first(m->transaction_jobs)))
399 while ((u = hashmap_first(m->units)))
402 manager_dispatch_cleanup_queue(m);
404 assert(!m->load_queue);
405 assert(!m->run_queue);
406 assert(!m->dbus_unit_queue);
407 assert(!m->dbus_job_queue);
408 assert(!m->cleanup_queue);
409 assert(!m->gc_queue);
411 assert(hashmap_isempty(m->transaction_jobs));
412 assert(hashmap_isempty(m->jobs));
413 assert(hashmap_isempty(m->units));
416 void manager_free(Manager *m) {
421 manager_clear_jobs_and_units(m);
423 for (c = 0; c < _UNIT_TYPE_MAX; c++)
424 if (unit_vtable[c]->shutdown)
425 unit_vtable[c]->shutdown(m);
427 /* If we reexecute ourselves, we keep the root cgroup
429 manager_shutdown_cgroup(m, m->exit_code != MANAGER_REEXECUTE);
433 hashmap_free(m->units);
434 hashmap_free(m->jobs);
435 hashmap_free(m->transaction_jobs);
436 hashmap_free(m->watch_pids);
437 hashmap_free(m->watch_bus);
439 if (m->epoll_fd >= 0)
440 close_nointr_nofail(m->epoll_fd);
441 if (m->signal_watch.fd >= 0)
442 close_nointr_nofail(m->signal_watch.fd);
443 if (m->notify_watch.fd >= 0)
444 close_nointr_nofail(m->notify_watch.fd);
447 if (m->audit_fd >= 0)
448 audit_close(m->audit_fd);
451 free(m->notify_socket);
454 lookup_paths_free(&m->lookup_paths);
455 strv_free(m->environment);
457 hashmap_free(m->cgroup_bondings);
458 set_free_free(m->unit_path_cache);
463 int manager_enumerate(Manager *m) {
469 /* Let's ask every type to load all units from disk/kernel
470 * that it might know */
471 for (c = 0; c < _UNIT_TYPE_MAX; c++)
472 if (unit_vtable[c]->enumerate)
473 if ((q = unit_vtable[c]->enumerate(m)) < 0)
476 manager_dispatch_load_queue(m);
480 int manager_coldplug(Manager *m) {
488 /* Then, let's set up their initial state. */
489 HASHMAP_FOREACH_KEY(u, k, m->units, i) {
495 if ((q = unit_coldplug(u)) < 0)
502 static void manager_build_unit_path_cache(Manager *m) {
509 set_free_free(m->unit_path_cache);
511 if (!(m->unit_path_cache = set_new(string_hash_func, string_compare_func))) {
512 log_error("Failed to allocate unit path cache.");
516 /* This simply builds a list of files we know exist, so that
517 * we don't always have to go to disk */
519 STRV_FOREACH(i, m->lookup_paths.unit_path) {
522 if (!(d = opendir(*i))) {
523 log_error("Failed to open directory: %m");
527 while ((de = readdir(d))) {
530 if (ignore_file(de->d_name))
533 if (asprintf(&p, "%s/%s", streq(*i, "/") ? "" : *i, de->d_name) < 0) {
538 if ((r = set_put(m->unit_path_cache, p)) < 0) {
551 log_error("Failed to build unit path cache: %s", strerror(-r));
553 set_free_free(m->unit_path_cache);
554 m->unit_path_cache = NULL;
560 int manager_startup(Manager *m, FILE *serialization, FDSet *fds) {
565 manager_build_unit_path_cache(m);
567 /* If we will deserialize make sure that during enumeration
568 * this is already known, so we increase the counter here
571 m->n_deserializing ++;
573 /* First, enumerate what we can from all config files */
574 r = manager_enumerate(m);
576 /* Second, deserialize if there is something to deserialize */
578 if ((q = manager_deserialize(m, serialization, fds)) < 0)
581 /* Third, fire things up! */
582 if ((q = manager_coldplug(m)) < 0)
586 assert(m->n_deserializing > 0);
587 m->n_deserializing --;
593 static void transaction_delete_job(Manager *m, Job *j, bool delete_dependencies) {
597 /* Deletes one job from the transaction */
599 manager_transaction_unlink_job(m, j, delete_dependencies);
605 static void transaction_delete_unit(Manager *m, Unit *u) {
608 /* Deletes all jobs associated with a certain unit from the
611 while ((j = hashmap_get(m->transaction_jobs, u)))
612 transaction_delete_job(m, j, true);
615 static void transaction_clean_dependencies(Manager *m) {
621 /* Drops all dependencies of all installed jobs */
623 HASHMAP_FOREACH(j, m->jobs, i) {
624 while (j->subject_list)
625 job_dependency_free(j->subject_list);
626 while (j->object_list)
627 job_dependency_free(j->object_list);
630 assert(!m->transaction_anchor);
633 static void transaction_abort(Manager *m) {
638 while ((j = hashmap_first(m->transaction_jobs)))
640 transaction_delete_job(m, j, true);
644 assert(hashmap_isempty(m->transaction_jobs));
646 transaction_clean_dependencies(m);
649 static void transaction_find_jobs_that_matter_to_anchor(Manager *m, Job *j, unsigned generation) {
654 /* A recursive sweep through the graph that marks all units
655 * that matter to the anchor job, i.e. are directly or
656 * indirectly a dependency of the anchor job via paths that
657 * are fully marked as mattering. */
662 l = m->transaction_anchor;
664 LIST_FOREACH(subject, l, l) {
666 /* This link does not matter */
670 /* This unit has already been marked */
671 if (l->object->generation == generation)
674 l->object->matters_to_anchor = true;
675 l->object->generation = generation;
677 transaction_find_jobs_that_matter_to_anchor(m, l->object, generation);
681 static void transaction_merge_and_delete_job(Manager *m, Job *j, Job *other, JobType t) {
682 JobDependency *l, *last;
686 assert(j->unit == other->unit);
687 assert(!j->installed);
689 /* Merges 'other' into 'j' and then deletes j. */
692 j->state = JOB_WAITING;
693 j->override = j->override || other->override;
695 j->matters_to_anchor = j->matters_to_anchor || other->matters_to_anchor;
697 /* Patch us in as new owner of the JobDependency objects */
699 LIST_FOREACH(subject, l, other->subject_list) {
700 assert(l->subject == other);
705 /* Merge both lists */
707 last->subject_next = j->subject_list;
709 j->subject_list->subject_prev = last;
710 j->subject_list = other->subject_list;
713 /* Patch us in as new owner of the JobDependency objects */
715 LIST_FOREACH(object, l, other->object_list) {
716 assert(l->object == other);
721 /* Merge both lists */
723 last->object_next = j->object_list;
725 j->object_list->object_prev = last;
726 j->object_list = other->object_list;
729 /* Kill the other job */
730 other->subject_list = NULL;
731 other->object_list = NULL;
732 transaction_delete_job(m, other, true);
734 static bool job_is_conflicted_by(Job *j) {
739 /* Returns true if this job is pulled in by a least one
740 * ConflictedBy dependency. */
742 LIST_FOREACH(object, l, j->object_list)
749 static int delete_one_unmergeable_job(Manager *m, Job *j) {
754 /* Tries to delete one item in the linked list
755 * j->transaction_next->transaction_next->... that conflicts
756 * whith another one, in an attempt to make an inconsistent
757 * transaction work. */
759 /* We rely here on the fact that if a merged with b does not
760 * merge with c, either a or b merge with c neither */
761 LIST_FOREACH(transaction, j, j)
762 LIST_FOREACH(transaction, k, j->transaction_next) {
765 /* Is this one mergeable? Then skip it */
766 if (job_type_is_mergeable(j->type, k->type))
769 /* Ok, we found two that conflict, let's see if we can
770 * drop one of them */
771 if (!j->matters_to_anchor && !k->matters_to_anchor) {
773 /* Both jobs don't matter, so let's
774 * find the one that is smarter to
775 * remove. Let's think positive and
776 * rather remove stops then starts --
777 * except if something is being
778 * stopped because it is conflicted by
779 * another unit in which case we
780 * rather remove the start. */
782 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)));
783 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)));
785 if (j->type == JOB_STOP) {
787 if (job_is_conflicted_by(j))
792 } else if (k->type == JOB_STOP) {
794 if (job_is_conflicted_by(k))
801 } else if (!j->matters_to_anchor)
803 else if (!k->matters_to_anchor)
808 /* Ok, we can drop one, so let's do so. */
809 log_debug("Fixing conflicting jobs by deleting job %s/%s", d->unit->meta.id, job_type_to_string(d->type));
810 transaction_delete_job(m, d, true);
817 static int transaction_merge_jobs(Manager *m, DBusError *e) {
824 /* First step, check whether any of the jobs for one specific
825 * task conflict. If so, try to drop one of them. */
826 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
831 LIST_FOREACH(transaction, k, j->transaction_next) {
832 if (job_type_merge(&t, k->type) >= 0)
835 /* OK, we could not merge all jobs for this
836 * action. Let's see if we can get rid of one
839 if ((r = delete_one_unmergeable_job(m, j)) >= 0)
840 /* Ok, we managed to drop one, now
841 * let's ask our callers to call us
842 * again after garbage collecting */
845 /* We couldn't merge anything. Failure */
846 dbus_set_error(e, BUS_ERROR_TRANSACTION_JOBS_CONFLICTING, "Transaction contains conflicting jobs '%s' and '%s' for %s. Probably contradicting requirement dependencies configured.",
847 job_type_to_string(t), job_type_to_string(k->type), k->unit->meta.id);
852 /* Second step, merge the jobs. */
853 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
857 /* Merge all transactions */
858 LIST_FOREACH(transaction, k, j->transaction_next)
859 assert_se(job_type_merge(&t, k->type) == 0);
861 /* If an active job is mergeable, merge it too */
862 if (j->unit->meta.job)
863 job_type_merge(&t, j->unit->meta.job->type); /* Might fail. Which is OK */
865 while ((k = j->transaction_next)) {
867 transaction_merge_and_delete_job(m, k, j, t);
870 transaction_merge_and_delete_job(m, j, k, t);
873 assert(!j->transaction_next);
874 assert(!j->transaction_prev);
880 static void transaction_drop_redundant(Manager *m) {
885 /* Goes through the transaction and removes all jobs that are
894 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
895 bool changes_something = false;
898 LIST_FOREACH(transaction, k, j) {
900 if (!job_is_anchor(k) &&
901 job_type_is_redundant(k->type, unit_active_state(k->unit)))
904 changes_something = true;
908 if (changes_something)
911 log_debug("Found redundant job %s/%s, dropping.", j->unit->meta.id, job_type_to_string(j->type));
912 transaction_delete_job(m, j, false);
920 static bool unit_matters_to_anchor(Unit *u, Job *j) {
922 assert(!j->transaction_prev);
924 /* Checks whether at least one of the jobs for this unit
925 * matters to the anchor. */
927 LIST_FOREACH(transaction, j, j)
928 if (j->matters_to_anchor)
934 static int transaction_verify_order_one(Manager *m, Job *j, Job *from, unsigned generation, DBusError *e) {
941 assert(!j->transaction_prev);
943 /* Does a recursive sweep through the ordering graph, looking
944 * for a cycle. If we find cycle we try to break it. */
946 /* Have we seen this before? */
947 if (j->generation == generation) {
950 /* If the marker is NULL we have been here already and
951 * decided the job was loop-free from here. Hence
952 * shortcut things and return right-away. */
956 /* So, the marker is not NULL and we already have been
957 * here. We have a cycle. Let's try to break it. We go
958 * backwards in our path and try to find a suitable
959 * job to remove. We use the marker to find our way
960 * back, since smart how we are we stored our way back
962 log_warning("Found ordering cycle on %s/%s", j->unit->meta.id, job_type_to_string(j->type));
965 for (k = from; k; k = ((k->generation == generation && k->marker != k) ? k->marker : NULL)) {
967 log_info("Walked on cycle path to %s/%s", k->unit->meta.id, job_type_to_string(k->type));
971 !unit_matters_to_anchor(k->unit, k)) {
972 /* Ok, we can drop this one, so let's
977 /* Check if this in fact was the beginning of
985 log_warning("Breaking ordering cycle by deleting job %s/%s", delete->unit->meta.id, job_type_to_string(delete->type));
986 transaction_delete_unit(m, delete->unit);
990 log_error("Unable to break cycle");
992 dbus_set_error(e, BUS_ERROR_TRANSACTION_ORDER_IS_CYCLIC, "Transaction order is cyclic. See system logs for details.");
996 /* Make the marker point to where we come from, so that we can
997 * find our way backwards if we want to break a cycle. We use
998 * a special marker for the beginning: we point to
1000 j->marker = from ? from : j;
1001 j->generation = generation;
1003 /* We assume that the the dependencies are bidirectional, and
1004 * hence can ignore UNIT_AFTER */
1005 SET_FOREACH(u, j->unit->meta.dependencies[UNIT_BEFORE], i) {
1008 /* Is there a job for this unit? */
1009 if (!(o = hashmap_get(m->transaction_jobs, u)))
1011 /* Ok, there is no job for this in the
1012 * transaction, but maybe there is already one
1014 if (!(o = u->meta.job))
1017 if ((r = transaction_verify_order_one(m, o, j, generation, e)) < 0)
1021 /* Ok, let's backtrack, and remember that this entry is not on
1022 * our path anymore. */
1028 static int transaction_verify_order(Manager *m, unsigned *generation, DBusError *e) {
1037 /* Check if the ordering graph is cyclic. If it is, try to fix
1038 * that up by dropping one of the jobs. */
1040 g = (*generation)++;
1042 HASHMAP_FOREACH(j, m->transaction_jobs, i)
1043 if ((r = transaction_verify_order_one(m, j, NULL, g, e)) < 0)
1049 static void transaction_collect_garbage(Manager *m) {
1054 /* Drop jobs that are not required by any other job */
1062 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1066 log_debug("Garbage collecting job %s/%s", j->unit->meta.id, job_type_to_string(j->type));
1067 transaction_delete_job(m, j, true);
1075 static int transaction_is_destructive(Manager *m, DBusError *e) {
1081 /* Checks whether applying this transaction means that
1082 * existing jobs would be replaced */
1084 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1087 assert(!j->transaction_prev);
1088 assert(!j->transaction_next);
1090 if (j->unit->meta.job &&
1091 j->unit->meta.job != j &&
1092 !job_type_is_superset(j->type, j->unit->meta.job->type)) {
1094 dbus_set_error(e, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE, "Transaction is destructive.");
1102 static void transaction_minimize_impact(Manager *m) {
1106 /* Drops all unnecessary jobs that reverse already active jobs
1107 * or that stop a running service. */
1115 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1116 LIST_FOREACH(transaction, j, j) {
1117 bool stops_running_service, changes_existing_job;
1119 /* If it matters, we shouldn't drop it */
1120 if (j->matters_to_anchor)
1123 /* Would this stop a running service?
1124 * Would this change an existing job?
1125 * If so, let's drop this entry */
1127 stops_running_service =
1128 j->type == JOB_STOP && UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(j->unit));
1130 changes_existing_job =
1131 j->unit->meta.job && job_type_is_conflicting(j->type, j->unit->meta.job->type);
1133 if (!stops_running_service && !changes_existing_job)
1136 if (stops_running_service)
1137 log_info("%s/%s would stop a running service.", j->unit->meta.id, job_type_to_string(j->type));
1139 if (changes_existing_job)
1140 log_info("%s/%s would change existing job.", j->unit->meta.id, job_type_to_string(j->type));
1142 /* Ok, let's get rid of this */
1143 log_info("Deleting %s/%s to minimize impact.", j->unit->meta.id, job_type_to_string(j->type));
1145 transaction_delete_job(m, j, true);
1157 static int transaction_apply(Manager *m) {
1162 /* Moves the transaction jobs to the set of active jobs */
1164 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1166 assert(!j->transaction_prev);
1167 assert(!j->transaction_next);
1172 if ((r = hashmap_put(m->jobs, UINT32_TO_PTR(j->id), j)) < 0)
1176 while ((j = hashmap_steal_first(m->transaction_jobs))) {
1180 if (j->unit->meta.job)
1181 job_free(j->unit->meta.job);
1183 j->unit->meta.job = j;
1184 j->installed = true;
1185 m->n_installed_jobs ++;
1187 /* We're fully installed. Now let's free data we don't
1190 assert(!j->transaction_next);
1191 assert(!j->transaction_prev);
1193 job_add_to_run_queue(j);
1194 job_add_to_dbus_queue(j);
1198 /* As last step, kill all remaining job dependencies. */
1199 transaction_clean_dependencies(m);
1205 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1209 hashmap_remove(m->jobs, UINT32_TO_PTR(j->id));
1215 static int transaction_activate(Manager *m, JobMode mode, DBusError *e) {
1217 unsigned generation = 1;
1221 /* This applies the changes recorded in transaction_jobs to
1222 * the actual list of jobs, if possible. */
1224 /* First step: figure out which jobs matter */
1225 transaction_find_jobs_that_matter_to_anchor(m, NULL, generation++);
1227 /* Second step: Try not to stop any running services if
1228 * we don't have to. Don't try to reverse running
1229 * jobs if we don't have to. */
1230 if (mode != JOB_ISOLATE)
1231 transaction_minimize_impact(m);
1233 /* Third step: Drop redundant jobs */
1234 transaction_drop_redundant(m);
1237 /* Fourth step: Let's remove unneeded jobs that might
1239 transaction_collect_garbage(m);
1241 /* Fifth step: verify order makes sense and correct
1242 * cycles if necessary and possible */
1243 if ((r = transaction_verify_order(m, &generation, e)) >= 0)
1247 log_warning("Requested transaction contains an unfixable cyclic ordering dependency: %s", bus_error(e, r));
1251 /* Let's see if the resulting transaction ordering
1252 * graph is still cyclic... */
1256 /* Sixth step: let's drop unmergeable entries if
1257 * necessary and possible, merge entries we can
1259 if ((r = transaction_merge_jobs(m, e)) >= 0)
1263 log_warning("Requested transaction contains unmergable jobs: %s", bus_error(e, r));
1267 /* Seventh step: an entry got dropped, let's garbage
1268 * collect its dependencies. */
1269 transaction_collect_garbage(m);
1271 /* Let's see if the resulting transaction still has
1272 * unmergeable entries ... */
1275 /* Eights step: Drop redundant jobs again, if the merging now allows us to drop more. */
1276 transaction_drop_redundant(m);
1278 /* Ninth step: check whether we can actually apply this */
1279 if (mode == JOB_FAIL)
1280 if ((r = transaction_is_destructive(m, e)) < 0) {
1281 log_notice("Requested transaction contradicts existing jobs: %s", bus_error(e, r));
1285 /* Tenth step: apply changes */
1286 if ((r = transaction_apply(m)) < 0) {
1287 log_warning("Failed to apply transaction: %s", strerror(-r));
1291 assert(hashmap_isempty(m->transaction_jobs));
1292 assert(!m->transaction_anchor);
1297 transaction_abort(m);
1301 static Job* transaction_add_one_job(Manager *m, JobType type, Unit *unit, bool override, bool *is_new) {
1307 /* Looks for an axisting prospective job and returns that. If
1308 * it doesn't exist it is created and added to the prospective
1311 f = hashmap_get(m->transaction_jobs, unit);
1313 LIST_FOREACH(transaction, j, f) {
1314 assert(j->unit == unit);
1316 if (j->type == type) {
1323 if (unit->meta.job && unit->meta.job->type == type)
1325 else if (!(j = job_new(m, type, unit)))
1330 j->matters_to_anchor = false;
1331 j->override = override;
1333 LIST_PREPEND(Job, transaction, f, j);
1335 if (hashmap_replace(m->transaction_jobs, unit, f) < 0) {
1343 log_debug("Added job %s/%s to transaction.", unit->meta.id, job_type_to_string(type));
1348 void manager_transaction_unlink_job(Manager *m, Job *j, bool delete_dependencies) {
1352 if (j->transaction_prev)
1353 j->transaction_prev->transaction_next = j->transaction_next;
1354 else if (j->transaction_next)
1355 hashmap_replace(m->transaction_jobs, j->unit, j->transaction_next);
1357 hashmap_remove_value(m->transaction_jobs, j->unit, j);
1359 if (j->transaction_next)
1360 j->transaction_next->transaction_prev = j->transaction_prev;
1362 j->transaction_prev = j->transaction_next = NULL;
1364 while (j->subject_list)
1365 job_dependency_free(j->subject_list);
1367 while (j->object_list) {
1368 Job *other = j->object_list->matters ? j->object_list->subject : NULL;
1370 job_dependency_free(j->object_list);
1372 if (other && delete_dependencies) {
1373 log_debug("Deleting job %s/%s as dependency of job %s/%s",
1374 other->unit->meta.id, job_type_to_string(other->type),
1375 j->unit->meta.id, job_type_to_string(j->type));
1376 transaction_delete_job(m, other, delete_dependencies);
1381 static int transaction_add_job_and_dependencies(
1398 assert(type < _JOB_TYPE_MAX);
1401 if (unit->meta.load_state != UNIT_LOADED && unit->meta.load_state != UNIT_ERROR) {
1402 dbus_set_error(e, BUS_ERROR_LOAD_FAILED, "Unit %s is not loaded properly.", unit->meta.id);
1406 if (type != JOB_STOP && unit->meta.load_state == UNIT_ERROR) {
1407 dbus_set_error(e, BUS_ERROR_LOAD_FAILED, "Unit %s failed to load: %s. You might find more information in the system logs.",
1409 strerror(-unit->meta.load_error));
1413 if (!unit_job_is_applicable(unit, type)) {
1414 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);
1418 /* First add the job. */
1419 if (!(ret = transaction_add_one_job(m, type, unit, override, &is_new)))
1422 /* Then, add a link to the job. */
1423 if (!job_dependency_new(by, ret, matters, conflicts))
1427 /* Finally, recursively add in all dependencies. */
1428 if (type == JOB_START || type == JOB_RELOAD_OR_START) {
1429 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES], i)
1430 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, true, override, false, e, NULL)) < 0 && r != -EBADR)
1433 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES_OVERRIDABLE], i)
1434 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, !override, override, false, e, NULL)) < 0 && r != -EBADR) {
1435 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_WANTS], i)
1442 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, false, false, false, e, NULL)) < 0) {
1443 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, bus_error(e, r));
1449 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE], i)
1450 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, true, override, false, e, NULL)) < 0 && r != -EBADR)
1453 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE_OVERRIDABLE], i)
1454 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, !override, override, false, e, NULL)) < 0 && r != -EBADR) {
1455 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, bus_error(e, r));
1461 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_CONFLICTS], i)
1462 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, dep, ret, true, override, true, e, NULL)) < 0 && r != -EBADR)
1465 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_CONFLICTED_BY], i)
1466 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, dep, ret, true, override, false, e, NULL)) < 0 && r != -EBADR)
1469 } else if (type == JOB_STOP || type == JOB_RESTART || type == JOB_TRY_RESTART) {
1471 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRED_BY], i)
1472 if ((r = transaction_add_job_and_dependencies(m, type, dep, ret, true, override, false, e, NULL)) < 0 && r != -EBADR)
1476 /* JOB_VERIFY_STARTED, JOB_RELOAD require no dependency handling */
1488 static int transaction_add_isolate_jobs(Manager *m) {
1496 HASHMAP_FOREACH_KEY(u, k, m->units, i) {
1498 /* ignore aliases */
1499 if (u->meta.id != k)
1502 if (UNIT_VTABLE(u)->no_isolate)
1505 /* No need to stop inactive jobs */
1506 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(u)))
1509 /* Is there already something listed for this? */
1510 if (hashmap_get(m->transaction_jobs, u))
1513 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, u, NULL, true, false, false, NULL, NULL)) < 0)
1514 log_warning("Cannot add isolate job for unit %s, ignoring: %s", u->meta.id, strerror(-r));
1520 int manager_add_job(Manager *m, JobType type, Unit *unit, JobMode mode, bool override, DBusError *e, Job **_ret) {
1525 assert(type < _JOB_TYPE_MAX);
1527 assert(mode < _JOB_MODE_MAX);
1529 if (mode == JOB_ISOLATE && type != JOB_START) {
1530 dbus_set_error(e, BUS_ERROR_INVALID_JOB_MODE, "Isolate is only valid for start.");
1534 if (mode == JOB_ISOLATE && !unit->meta.allow_isolate) {
1535 dbus_set_error(e, BUS_ERROR_NO_ISOLATION, "Operation refused, unit may not be isolated.");
1539 log_debug("Trying to enqueue job %s/%s/%s", unit->meta.id, job_type_to_string(type), job_mode_to_string(mode));
1541 if ((r = transaction_add_job_and_dependencies(m, type, unit, NULL, true, override, false, e, &ret)) < 0) {
1542 transaction_abort(m);
1546 if (mode == JOB_ISOLATE)
1547 if ((r = transaction_add_isolate_jobs(m)) < 0) {
1548 transaction_abort(m);
1552 if ((r = transaction_activate(m, mode, e)) < 0)
1555 log_debug("Enqueued job %s/%s as %u", unit->meta.id, job_type_to_string(type), (unsigned) ret->id);
1563 int manager_add_job_by_name(Manager *m, JobType type, const char *name, JobMode mode, bool override, DBusError *e, Job **_ret) {
1568 assert(type < _JOB_TYPE_MAX);
1570 assert(mode < _JOB_MODE_MAX);
1572 if ((r = manager_load_unit(m, name, NULL, NULL, &unit)) < 0)
1575 return manager_add_job(m, type, unit, mode, override, e, _ret);
1578 Job *manager_get_job(Manager *m, uint32_t id) {
1581 return hashmap_get(m->jobs, UINT32_TO_PTR(id));
1584 Unit *manager_get_unit(Manager *m, const char *name) {
1588 return hashmap_get(m->units, name);
1591 unsigned manager_dispatch_load_queue(Manager *m) {
1597 /* Make sure we are not run recursively */
1598 if (m->dispatching_load_queue)
1601 m->dispatching_load_queue = true;
1603 /* Dispatches the load queue. Takes a unit from the queue and
1604 * tries to load its data until the queue is empty */
1606 while ((meta = m->load_queue)) {
1607 assert(meta->in_load_queue);
1609 unit_load((Unit*) meta);
1613 m->dispatching_load_queue = false;
1617 int manager_load_unit_prepare(Manager *m, const char *name, const char *path, DBusError *e, Unit **_ret) {
1622 assert(name || path);
1624 /* This will prepare the unit for loading, but not actually
1625 * load anything from disk. */
1627 if (path && !is_path(path)) {
1628 dbus_set_error(e, BUS_ERROR_INVALID_PATH, "Path %s is not absolute.", path);
1633 name = file_name_from_path(path);
1635 if (!unit_name_is_valid(name)) {
1636 dbus_set_error(e, BUS_ERROR_INVALID_NAME, "Unit name %s is not valid.", name);
1640 if ((ret = manager_get_unit(m, name))) {
1645 if (!(ret = unit_new(m)))
1649 if (!(ret->meta.fragment_path = strdup(path))) {
1654 if ((r = unit_add_name(ret, name)) < 0) {
1659 unit_add_to_load_queue(ret);
1660 unit_add_to_dbus_queue(ret);
1661 unit_add_to_gc_queue(ret);
1669 int manager_load_unit(Manager *m, const char *name, const char *path, DBusError *e, Unit **_ret) {
1674 /* This will load the service information files, but not actually
1675 * start any services or anything. */
1677 if ((r = manager_load_unit_prepare(m, name, path, e, _ret)) != 0)
1680 manager_dispatch_load_queue(m);
1683 *_ret = unit_follow_merge(*_ret);
1688 void manager_dump_jobs(Manager *s, FILE *f, const char *prefix) {
1695 HASHMAP_FOREACH(j, s->jobs, i)
1696 job_dump(j, f, prefix);
1699 void manager_dump_units(Manager *s, FILE *f, const char *prefix) {
1707 HASHMAP_FOREACH_KEY(u, t, s->units, i)
1708 if (u->meta.id == t)
1709 unit_dump(u, f, prefix);
1712 void manager_clear_jobs(Manager *m) {
1717 transaction_abort(m);
1719 while ((j = hashmap_first(m->jobs)))
1723 unsigned manager_dispatch_run_queue(Manager *m) {
1727 if (m->dispatching_run_queue)
1730 m->dispatching_run_queue = true;
1732 while ((j = m->run_queue)) {
1733 assert(j->installed);
1734 assert(j->in_run_queue);
1736 job_run_and_invalidate(j);
1740 m->dispatching_run_queue = false;
1744 unsigned manager_dispatch_dbus_queue(Manager *m) {
1751 if (m->dispatching_dbus_queue)
1754 m->dispatching_dbus_queue = true;
1756 while ((meta = m->dbus_unit_queue)) {
1757 assert(meta->in_dbus_queue);
1759 bus_unit_send_change_signal((Unit*) meta);
1763 while ((j = m->dbus_job_queue)) {
1764 assert(j->in_dbus_queue);
1766 bus_job_send_change_signal(j);
1770 m->dispatching_dbus_queue = false;
1774 static int manager_process_notify_fd(Manager *m) {
1781 struct msghdr msghdr;
1783 struct ucred *ucred;
1785 struct cmsghdr cmsghdr;
1786 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
1792 iovec.iov_base = buf;
1793 iovec.iov_len = sizeof(buf)-1;
1797 msghdr.msg_iov = &iovec;
1798 msghdr.msg_iovlen = 1;
1799 msghdr.msg_control = &control;
1800 msghdr.msg_controllen = sizeof(control);
1802 if ((n = recvmsg(m->notify_watch.fd, &msghdr, MSG_DONTWAIT)) <= 0) {
1806 if (errno == EAGAIN || errno == EINTR)
1812 if (msghdr.msg_controllen < CMSG_LEN(sizeof(struct ucred)) ||
1813 control.cmsghdr.cmsg_level != SOL_SOCKET ||
1814 control.cmsghdr.cmsg_type != SCM_CREDENTIALS ||
1815 control.cmsghdr.cmsg_len != CMSG_LEN(sizeof(struct ucred))) {
1816 log_warning("Received notify message without credentials. Ignoring.");
1820 ucred = (struct ucred*) CMSG_DATA(&control.cmsghdr);
1822 if (!(u = hashmap_get(m->watch_pids, LONG_TO_PTR(ucred->pid))))
1823 if (!(u = cgroup_unit_by_pid(m, ucred->pid))) {
1824 log_warning("Cannot find unit for notify message of PID %lu.", (unsigned long) ucred->pid);
1828 assert((size_t) n < sizeof(buf));
1830 if (!(tags = strv_split(buf, "\n\r")))
1833 log_debug("Got notification message for unit %s", u->meta.id);
1835 if (UNIT_VTABLE(u)->notify_message)
1836 UNIT_VTABLE(u)->notify_message(u, ucred->pid, tags);
1844 static int manager_dispatch_sigchld(Manager *m) {
1854 /* First we call waitd() for a PID and do not reap the
1855 * zombie. That way we can still access /proc/$PID for
1856 * it while it is a zombie. */
1857 if (waitid(P_ALL, 0, &si, WEXITED|WNOHANG|WNOWAIT) < 0) {
1859 if (errno == ECHILD)
1871 if (si.si_code == CLD_EXITED || si.si_code == CLD_KILLED || si.si_code == CLD_DUMPED) {
1874 get_process_name(si.si_pid, &name);
1875 log_debug("Got SIGCHLD for process %lu (%s)", (unsigned long) si.si_pid, strna(name));
1879 /* Let's flush any message the dying child might still
1880 * have queued for us. This ensures that the process
1881 * still exists in /proc so that we can figure out
1882 * which cgroup and hence unit it belongs to. */
1883 if ((r = manager_process_notify_fd(m)) < 0)
1886 /* And now figure out the unit this belongs to */
1887 if (!(u = hashmap_get(m->watch_pids, LONG_TO_PTR(si.si_pid))))
1888 u = cgroup_unit_by_pid(m, si.si_pid);
1890 /* And now, we actually reap the zombie. */
1891 if (waitid(P_PID, si.si_pid, &si, WEXITED) < 0) {
1898 if (si.si_code != CLD_EXITED && si.si_code != CLD_KILLED && si.si_code != CLD_DUMPED)
1901 log_debug("Child %lu died (code=%s, status=%i/%s)",
1902 (long unsigned) si.si_pid,
1903 sigchld_code_to_string(si.si_code),
1905 strna(si.si_code == CLD_EXITED
1906 ? exit_status_to_string(si.si_status, EXIT_STATUS_FULL)
1907 : signal_to_string(si.si_status)));
1912 log_debug("Child %lu belongs to %s", (long unsigned) si.si_pid, u->meta.id);
1914 hashmap_remove(m->watch_pids, LONG_TO_PTR(si.si_pid));
1915 UNIT_VTABLE(u)->sigchld_event(u, si.si_pid, si.si_code, si.si_status);
1921 static int manager_start_target(Manager *m, const char *name, JobMode mode) {
1925 dbus_error_init(&error);
1927 log_info("Activating special unit %s", name);
1929 if ((r = manager_add_job_by_name(m, JOB_START, name, mode, true, &error, NULL)) < 0)
1930 log_error("Failed to enqueue %s job: %s", name, bus_error(&error, r));
1932 dbus_error_free(&error);
1937 static int manager_process_signal_fd(Manager *m) {
1939 struct signalfd_siginfo sfsi;
1940 bool sigchld = false;
1945 if ((n = read(m->signal_watch.fd, &sfsi, sizeof(sfsi))) != sizeof(sfsi)) {
1950 if (errno == EINTR || errno == EAGAIN)
1956 log_debug("Received SIG%s", strna(signal_to_string(sfsi.ssi_signo)));
1958 switch (sfsi.ssi_signo) {
1965 if (m->running_as == MANAGER_SYSTEM) {
1966 /* This is for compatibility with the
1967 * original sysvinit */
1968 m->exit_code = MANAGER_REEXECUTE;
1975 if (m->running_as == MANAGER_SYSTEM) {
1976 manager_start_target(m, SPECIAL_CTRL_ALT_DEL_TARGET, JOB_REPLACE);
1980 /* Run the exit target if there is one, if not, just exit. */
1981 if (manager_start_target(m, SPECIAL_EXIT_SERVICE, JOB_REPLACE) < 0) {
1982 m->exit_code = MANAGER_EXIT;
1989 if (m->running_as == MANAGER_SYSTEM)
1990 manager_start_target(m, SPECIAL_KBREQUEST_TARGET, JOB_REPLACE);
1992 /* This is a nop on non-init */
1996 if (m->running_as == MANAGER_SYSTEM)
1997 manager_start_target(m, SPECIAL_SIGPWR_TARGET, JOB_REPLACE);
1999 /* This is a nop on non-init */
2005 u = manager_get_unit(m, SPECIAL_DBUS_SERVICE);
2007 if (!u || UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u))) {
2008 log_info("Trying to reconnect to bus...");
2012 if (!u || !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u))) {
2013 log_info("Loading D-Bus service...");
2014 manager_start_target(m, SPECIAL_DBUS_SERVICE, JOB_REPLACE);
2025 if (!(f = open_memstream(&dump, &size))) {
2026 log_warning("Failed to allocate memory stream.");
2030 manager_dump_units(m, f, "\t");
2031 manager_dump_jobs(m, f, "\t");
2036 log_warning("Failed to write status stream");
2041 log_dump(LOG_INFO, dump);
2048 m->exit_code = MANAGER_RELOAD;
2052 static const char * const table[] = {
2053 [0] = SPECIAL_DEFAULT_TARGET,
2054 [1] = SPECIAL_RESCUE_TARGET,
2055 [2] = SPECIAL_EMERGENCY_TARGET,
2056 [3] = SPECIAL_HALT_TARGET,
2057 [4] = SPECIAL_POWEROFF_TARGET,
2058 [5] = SPECIAL_REBOOT_TARGET
2061 if ((int) sfsi.ssi_signo >= SIGRTMIN+0 &&
2062 (int) sfsi.ssi_signo < SIGRTMIN+(int) ELEMENTSOF(table)) {
2063 manager_start_target(m, table[sfsi.ssi_signo - SIGRTMIN],
2064 (sfsi.ssi_signo == 1 || sfsi.ssi_signo == 2) ? JOB_ISOLATE : JOB_REPLACE);
2068 log_warning("Got unhandled signal <%s>.", strna(signal_to_string(sfsi.ssi_signo)));
2074 return manager_dispatch_sigchld(m);
2079 static int process_event(Manager *m, struct epoll_event *ev) {
2086 assert(w = ev->data.ptr);
2092 /* An incoming signal? */
2093 if (ev->events != EPOLLIN)
2096 if ((r = manager_process_signal_fd(m)) < 0)
2103 /* An incoming daemon notification event? */
2104 if (ev->events != EPOLLIN)
2107 if ((r = manager_process_notify_fd(m)) < 0)
2114 /* Some fd event, to be dispatched to the units */
2115 UNIT_VTABLE(w->data.unit)->fd_event(w->data.unit, w->fd, ev->events, w);
2118 case WATCH_UNIT_TIMER:
2119 case WATCH_JOB_TIMER: {
2123 /* Some timer event, to be dispatched to the units */
2124 if ((k = read(w->fd, &v, sizeof(v))) != sizeof(v)) {
2126 if (k < 0 && (errno == EINTR || errno == EAGAIN))
2129 return k < 0 ? -errno : -EIO;
2132 if (w->type == WATCH_UNIT_TIMER)
2133 UNIT_VTABLE(w->data.unit)->timer_event(w->data.unit, v, w);
2135 job_timer_event(w->data.job, v, w);
2140 /* Some mount table change, intended for the mount subsystem */
2141 mount_fd_event(m, ev->events);
2145 /* Some notification from udev, intended for the device subsystem */
2146 device_fd_event(m, ev->events);
2149 case WATCH_DBUS_WATCH:
2150 bus_watch_event(m, w, ev->events);
2153 case WATCH_DBUS_TIMEOUT:
2154 bus_timeout_event(m, w, ev->events);
2158 assert_not_reached("Unknown epoll event type.");
2164 int manager_loop(Manager *m) {
2167 RATELIMIT_DEFINE(rl, 1*USEC_PER_SEC, 1000);
2170 m->exit_code = MANAGER_RUNNING;
2172 /* Release the path cache */
2173 set_free_free(m->unit_path_cache);
2174 m->unit_path_cache = NULL;
2176 manager_check_finished(m);
2178 /* There might still be some zombies hanging around from
2179 * before we were exec()'ed. Leat's reap them */
2180 if ((r = manager_dispatch_sigchld(m)) < 0)
2183 while (m->exit_code == MANAGER_RUNNING) {
2184 struct epoll_event event;
2187 if (!ratelimit_test(&rl)) {
2188 /* Yay, something is going seriously wrong, pause a little */
2189 log_warning("Looping too fast. Throttling execution a little.");
2193 if (manager_dispatch_load_queue(m) > 0)
2196 if (manager_dispatch_run_queue(m) > 0)
2199 if (bus_dispatch(m) > 0)
2202 if (manager_dispatch_cleanup_queue(m) > 0)
2205 if (manager_dispatch_gc_queue(m) > 0)
2208 if (manager_dispatch_dbus_queue(m) > 0)
2211 if ((n = epoll_wait(m->epoll_fd, &event, 1, -1)) < 0) {
2221 if ((r = process_event(m, &event)) < 0)
2225 return m->exit_code;
2228 int manager_get_unit_from_dbus_path(Manager *m, const char *s, Unit **_u) {
2236 if (!startswith(s, "/org/freedesktop/systemd1/unit/"))
2239 if (!(n = bus_path_unescape(s+31)))
2242 u = manager_get_unit(m, n);
2253 int manager_get_job_from_dbus_path(Manager *m, const char *s, Job **_j) {
2262 if (!startswith(s, "/org/freedesktop/systemd1/job/"))
2265 if ((r = safe_atou(s + 30, &id)) < 0)
2268 if (!(j = manager_get_job(m, id)))
2276 void manager_send_unit_audit(Manager *m, Unit *u, int type, bool success) {
2281 if (m->audit_fd < 0)
2284 /* Don't generate audit events if the service was already
2285 * started and we're just deserializing */
2286 if (m->n_deserializing > 0)
2289 if (!(p = unit_name_to_prefix_and_instance(u->meta.id))) {
2290 log_error("Failed to allocate unit name for audit message: %s", strerror(ENOMEM));
2294 if (audit_log_user_comm_message(m->audit_fd, type, "", p, NULL, NULL, NULL, success) < 0)
2295 log_error("Failed to send audit message: %m");
2302 void manager_dispatch_bus_name_owner_changed(
2305 const char* old_owner,
2306 const char *new_owner) {
2313 if (!(u = hashmap_get(m->watch_bus, name)))
2316 UNIT_VTABLE(u)->bus_name_owner_change(u, name, old_owner, new_owner);
2319 void manager_dispatch_bus_query_pid_done(
2330 if (!(u = hashmap_get(m->watch_bus, name)))
2333 UNIT_VTABLE(u)->bus_query_pid_done(u, name, pid);
2336 int manager_open_serialization(Manager *m, FILE **_f) {
2344 if (m->running_as == MANAGER_SYSTEM) {
2345 mkdir_p("/dev/.systemd", 0755);
2347 if (asprintf(&path, "/dev/.systemd/dump-%lu-XXXXXX", (unsigned long) getpid()) < 0)
2350 if (asprintf(&path, "/tmp/systemd-dump-%lu-XXXXXX", (unsigned long) getpid()) < 0)
2354 saved_umask = umask(0077);
2355 fd = mkostemp(path, O_RDWR|O_CLOEXEC);
2365 log_debug("Serializing state to %s", path);
2368 if (!(f = fdopen(fd, "w+")) < 0)
2376 int manager_serialize(Manager *m, FILE *f, FDSet *fds) {
2386 fprintf(f, "startup-timestamp=%llu %llu\n\n",
2387 (unsigned long long) m->startup_timestamp.realtime,
2388 (unsigned long long) m->startup_timestamp.monotonic);
2390 HASHMAP_FOREACH_KEY(u, t, m->units, i) {
2391 if (u->meta.id != t)
2394 if (!unit_can_serialize(u))
2398 fputs(u->meta.id, f);
2401 if ((r = unit_serialize(u, f, fds)) < 0)
2411 int manager_deserialize(Manager *m, FILE *f, FDSet *fds) {
2417 log_debug("Deserializing state...");
2419 m->n_deserializing ++;
2422 char line[1024], *l;
2424 if (!fgets(line, sizeof(line), f)) {
2439 if (startswith(l, "startup-timestamp=")) {
2440 unsigned long long a, b;
2442 if (sscanf(l+18, "%lli %llu", &a, &b) != 2)
2443 log_debug("Failed to parse startup timestamp value %s", l+18);
2445 m->startup_timestamp.realtime = a;
2446 m->startup_timestamp.monotonic = b;
2449 log_debug("Unknown serialization item '%s'", l);
2454 char name[UNIT_NAME_MAX+2];
2457 if (!fgets(name, sizeof(name), f)) {
2468 if ((r = manager_load_unit(m, strstrip(name), NULL, NULL, &u)) < 0)
2471 if ((r = unit_deserialize(u, f, fds)) < 0)
2481 assert(m->n_deserializing > 0);
2482 m->n_deserializing --;
2487 int manager_reload(Manager *m) {
2494 if ((r = manager_open_serialization(m, &f)) < 0)
2497 if (!(fds = fdset_new())) {
2502 if ((r = manager_serialize(m, f, fds)) < 0)
2505 if (fseeko(f, 0, SEEK_SET) < 0) {
2510 /* From here on there is no way back. */
2511 manager_clear_jobs_and_units(m);
2513 /* Find new unit paths */
2514 lookup_paths_free(&m->lookup_paths);
2515 if ((q = lookup_paths_init(&m->lookup_paths, m->running_as)) < 0)
2518 m->n_deserializing ++;
2520 /* First, enumerate what we can from all config files */
2521 if ((q = manager_enumerate(m)) < 0)
2524 /* Second, deserialize our stored data */
2525 if ((q = manager_deserialize(m, f, fds)) < 0)
2531 /* Third, fire things up! */
2532 if ((q = manager_coldplug(m)) < 0)
2535 assert(m->n_deserializing > 0);
2536 m->n_deserializing ++;
2548 bool manager_is_booting_or_shutting_down(Manager *m) {
2553 /* Is the initial job still around? */
2554 if (manager_get_job(m, 1))
2557 /* Is there a job for the shutdown target? */
2558 if (((u = manager_get_unit(m, SPECIAL_SHUTDOWN_TARGET))))
2559 return !!u->meta.job;
2564 void manager_reset_failed(Manager *m) {
2570 HASHMAP_FOREACH(u, m->units, i)
2571 unit_reset_failed(u);
2574 int manager_set_console(Manager *m, const char *console) {
2579 if (!(c = strdup(console)))
2585 log_debug("Using kernel console %s", c);
2590 bool manager_unit_pending_inactive(Manager *m, const char *name) {
2596 /* Returns true if the unit is inactive or going down */
2597 if (!(u = manager_get_unit(m, name)))
2600 return unit_pending_inactive(u);
2603 void manager_check_finished(Manager *m) {
2604 char userspace[FORMAT_TIMESPAN_MAX], kernel[FORMAT_TIMESPAN_MAX], sum[FORMAT_TIMESPAN_MAX];
2608 if (dual_timestamp_is_set(&m->finish_timestamp))
2611 if (hashmap_size(m->jobs) > 0)
2614 dual_timestamp_get(&m->finish_timestamp);
2616 if (m->running_as == MANAGER_SYSTEM)
2617 log_info("Startup finished in %s (kernel) + %s (userspace) = %s.",
2618 format_timespan(kernel, sizeof(kernel),
2619 m->startup_timestamp.monotonic),
2620 format_timespan(userspace, sizeof(userspace),
2621 m->finish_timestamp.monotonic - m->startup_timestamp.monotonic),
2622 format_timespan(sum, sizeof(sum),
2623 m->finish_timestamp.monotonic));
2625 log_debug("Startup finished in %s.",
2626 format_timespan(userspace, sizeof(userspace),
2627 m->finish_timestamp.monotonic - m->startup_timestamp.monotonic));
2631 static const char* const manager_running_as_table[_MANAGER_RUNNING_AS_MAX] = {
2632 [MANAGER_SYSTEM] = "system",
2633 [MANAGER_SESSION] = "session"
2636 DEFINE_STRING_TABLE_LOOKUP(manager_running_as, ManagerRunningAs);