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, offsetof(struct sockaddr_un, sun_path) + 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: isolate 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 */
172 SIGRTMIN+6, /* systemd: start kexec.target */
173 SIGRTMIN+13, /* systemd: Immediate halt */
174 SIGRTMIN+14, /* systemd: Immediate poweroff */
175 SIGRTMIN+15, /* systemd: Immediate reboot */
176 SIGRTMIN+16, /* systemd: Immediate kexec */
178 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
180 m->signal_watch.type = WATCH_SIGNAL;
181 if ((m->signal_watch.fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0)
186 ev.data.ptr = &m->signal_watch;
188 if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->signal_watch.fd, &ev) < 0)
191 if (m->running_as == MANAGER_SYSTEM)
192 return enable_special_signals(m);
197 int manager_new(ManagerRunningAs running_as, Manager **_m) {
202 assert(running_as >= 0);
203 assert(running_as < _MANAGER_RUNNING_AS_MAX);
205 if (!(m = new0(Manager, 1)))
208 dual_timestamp_get(&m->startup_timestamp);
210 m->running_as = running_as;
211 m->name_data_slot = m->subscribed_data_slot = -1;
212 m->exit_code = _MANAGER_EXIT_CODE_INVALID;
213 m->pin_cgroupfs_fd = -1;
219 m->signal_watch.fd = m->mount_watch.fd = m->udev_watch.fd = m->epoll_fd = m->dev_autofs_fd = m->swap_watch.fd = -1;
220 m->current_job_id = 1; /* start as id #1, so that we can leave #0 around as "null-like" value */
222 if (!(m->environment = strv_copy(environ)))
225 if (!(m->units = hashmap_new(string_hash_func, string_compare_func)))
228 if (!(m->jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
231 if (!(m->transaction_jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
234 if (!(m->watch_pids = hashmap_new(trivial_hash_func, trivial_compare_func)))
237 if (!(m->cgroup_bondings = hashmap_new(string_hash_func, string_compare_func)))
240 if (!(m->watch_bus = hashmap_new(string_hash_func, string_compare_func)))
243 if ((m->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0)
246 if ((r = lookup_paths_init(&m->lookup_paths, m->running_as)) < 0)
249 if ((r = manager_setup_signals(m)) < 0)
252 if ((r = manager_setup_cgroup(m)) < 0)
255 if ((r = manager_setup_notify(m)) < 0)
258 /* Try to connect to the busses, if possible. */
259 if ((r = bus_init(m)) < 0)
263 if ((m->audit_fd = audit_open()) < 0)
264 log_error("Failed to connect to audit log: %m");
275 static unsigned manager_dispatch_cleanup_queue(Manager *m) {
281 while ((meta = m->cleanup_queue)) {
282 assert(meta->in_cleanup_queue);
284 unit_free((Unit*) meta);
292 GC_OFFSET_IN_PATH, /* This one is on the path we were travelling */
293 GC_OFFSET_UNSURE, /* No clue */
294 GC_OFFSET_GOOD, /* We still need this unit */
295 GC_OFFSET_BAD, /* We don't need this unit anymore */
299 static void unit_gc_sweep(Unit *u, unsigned gc_marker) {
306 if (u->meta.gc_marker == gc_marker + GC_OFFSET_GOOD ||
307 u->meta.gc_marker == gc_marker + GC_OFFSET_BAD ||
308 u->meta.gc_marker == gc_marker + GC_OFFSET_IN_PATH)
311 if (u->meta.in_cleanup_queue)
314 if (unit_check_gc(u))
317 u->meta.gc_marker = gc_marker + GC_OFFSET_IN_PATH;
321 SET_FOREACH(other, u->meta.dependencies[UNIT_REFERENCED_BY], i) {
322 unit_gc_sweep(other, gc_marker);
324 if (other->meta.gc_marker == gc_marker + GC_OFFSET_GOOD)
327 if (other->meta.gc_marker != gc_marker + GC_OFFSET_BAD)
334 /* We were unable to find anything out about this entry, so
335 * let's investigate it later */
336 u->meta.gc_marker = gc_marker + GC_OFFSET_UNSURE;
337 unit_add_to_gc_queue(u);
341 /* We definitely know that this one is not useful anymore, so
342 * let's mark it for deletion */
343 u->meta.gc_marker = gc_marker + GC_OFFSET_BAD;
344 unit_add_to_cleanup_queue(u);
348 u->meta.gc_marker = gc_marker + GC_OFFSET_GOOD;
351 static unsigned manager_dispatch_gc_queue(Manager *m) {
358 if ((m->n_in_gc_queue < GC_QUEUE_ENTRIES_MAX) &&
359 (m->gc_queue_timestamp <= 0 ||
360 (m->gc_queue_timestamp + GC_QUEUE_USEC_MAX) > now(CLOCK_MONOTONIC)))
363 log_debug("Running GC...");
365 m->gc_marker += _GC_OFFSET_MAX;
366 if (m->gc_marker + _GC_OFFSET_MAX <= _GC_OFFSET_MAX)
369 gc_marker = m->gc_marker;
371 while ((meta = m->gc_queue)) {
372 assert(meta->in_gc_queue);
374 unit_gc_sweep((Unit*) meta, gc_marker);
376 LIST_REMOVE(Meta, gc_queue, m->gc_queue, meta);
377 meta->in_gc_queue = false;
381 if (meta->gc_marker == gc_marker + GC_OFFSET_BAD ||
382 meta->gc_marker == gc_marker + GC_OFFSET_UNSURE) {
383 log_debug("Collecting %s", meta->id);
384 meta->gc_marker = gc_marker + GC_OFFSET_BAD;
385 unit_add_to_cleanup_queue((Unit*) meta);
389 m->n_in_gc_queue = 0;
390 m->gc_queue_timestamp = 0;
395 static void manager_clear_jobs_and_units(Manager *m) {
401 while ((j = hashmap_first(m->transaction_jobs)))
404 while ((u = hashmap_first(m->units)))
407 manager_dispatch_cleanup_queue(m);
409 assert(!m->load_queue);
410 assert(!m->run_queue);
411 assert(!m->dbus_unit_queue);
412 assert(!m->dbus_job_queue);
413 assert(!m->cleanup_queue);
414 assert(!m->gc_queue);
416 assert(hashmap_isempty(m->transaction_jobs));
417 assert(hashmap_isempty(m->jobs));
418 assert(hashmap_isempty(m->units));
421 void manager_free(Manager *m) {
426 manager_clear_jobs_and_units(m);
428 for (c = 0; c < _UNIT_TYPE_MAX; c++)
429 if (unit_vtable[c]->shutdown)
430 unit_vtable[c]->shutdown(m);
432 /* If we reexecute ourselves, we keep the root cgroup
434 manager_shutdown_cgroup(m, m->exit_code != MANAGER_REEXECUTE);
436 manager_undo_generators(m);
440 hashmap_free(m->units);
441 hashmap_free(m->jobs);
442 hashmap_free(m->transaction_jobs);
443 hashmap_free(m->watch_pids);
444 hashmap_free(m->watch_bus);
446 if (m->epoll_fd >= 0)
447 close_nointr_nofail(m->epoll_fd);
448 if (m->signal_watch.fd >= 0)
449 close_nointr_nofail(m->signal_watch.fd);
450 if (m->notify_watch.fd >= 0)
451 close_nointr_nofail(m->notify_watch.fd);
454 if (m->audit_fd >= 0)
455 audit_close(m->audit_fd);
458 free(m->notify_socket);
461 lookup_paths_free(&m->lookup_paths);
462 strv_free(m->environment);
464 hashmap_free(m->cgroup_bondings);
465 set_free_free(m->unit_path_cache);
470 int manager_enumerate(Manager *m) {
476 /* Let's ask every type to load all units from disk/kernel
477 * that it might know */
478 for (c = 0; c < _UNIT_TYPE_MAX; c++)
479 if (unit_vtable[c]->enumerate)
480 if ((q = unit_vtable[c]->enumerate(m)) < 0)
483 manager_dispatch_load_queue(m);
487 int manager_coldplug(Manager *m) {
495 /* Then, let's set up their initial state. */
496 HASHMAP_FOREACH_KEY(u, k, m->units, i) {
502 if ((q = unit_coldplug(u)) < 0)
509 static void manager_build_unit_path_cache(Manager *m) {
516 set_free_free(m->unit_path_cache);
518 if (!(m->unit_path_cache = set_new(string_hash_func, string_compare_func))) {
519 log_error("Failed to allocate unit path cache.");
523 /* This simply builds a list of files we know exist, so that
524 * we don't always have to go to disk */
526 STRV_FOREACH(i, m->lookup_paths.unit_path) {
529 if (!(d = opendir(*i))) {
530 log_error("Failed to open directory: %m");
534 while ((de = readdir(d))) {
537 if (ignore_file(de->d_name))
540 if (asprintf(&p, "%s/%s", streq(*i, "/") ? "" : *i, de->d_name) < 0) {
545 if ((r = set_put(m->unit_path_cache, p)) < 0) {
558 log_error("Failed to build unit path cache: %s", strerror(-r));
560 set_free_free(m->unit_path_cache);
561 m->unit_path_cache = NULL;
567 int manager_startup(Manager *m, FILE *serialization, FDSet *fds) {
572 manager_run_generators(m);
574 manager_build_unit_path_cache(m);
576 /* If we will deserialize make sure that during enumeration
577 * this is already known, so we increase the counter here
580 m->n_deserializing ++;
582 /* First, enumerate what we can from all config files */
583 r = manager_enumerate(m);
585 /* Second, deserialize if there is something to deserialize */
587 if ((q = manager_deserialize(m, serialization, fds)) < 0)
590 /* Third, fire things up! */
591 if ((q = manager_coldplug(m)) < 0)
595 assert(m->n_deserializing > 0);
596 m->n_deserializing --;
602 static void transaction_delete_job(Manager *m, Job *j, bool delete_dependencies) {
606 /* Deletes one job from the transaction */
608 manager_transaction_unlink_job(m, j, delete_dependencies);
614 static void transaction_delete_unit(Manager *m, Unit *u) {
617 /* Deletes all jobs associated with a certain unit from the
620 while ((j = hashmap_get(m->transaction_jobs, u)))
621 transaction_delete_job(m, j, true);
624 static void transaction_clean_dependencies(Manager *m) {
630 /* Drops all dependencies of all installed jobs */
632 HASHMAP_FOREACH(j, m->jobs, i) {
633 while (j->subject_list)
634 job_dependency_free(j->subject_list);
635 while (j->object_list)
636 job_dependency_free(j->object_list);
639 assert(!m->transaction_anchor);
642 static void transaction_abort(Manager *m) {
647 while ((j = hashmap_first(m->transaction_jobs)))
649 transaction_delete_job(m, j, true);
653 assert(hashmap_isempty(m->transaction_jobs));
655 transaction_clean_dependencies(m);
658 static void transaction_find_jobs_that_matter_to_anchor(Manager *m, Job *j, unsigned generation) {
663 /* A recursive sweep through the graph that marks all units
664 * that matter to the anchor job, i.e. are directly or
665 * indirectly a dependency of the anchor job via paths that
666 * are fully marked as mattering. */
671 l = m->transaction_anchor;
673 LIST_FOREACH(subject, l, l) {
675 /* This link does not matter */
679 /* This unit has already been marked */
680 if (l->object->generation == generation)
683 l->object->matters_to_anchor = true;
684 l->object->generation = generation;
686 transaction_find_jobs_that_matter_to_anchor(m, l->object, generation);
690 static void transaction_merge_and_delete_job(Manager *m, Job *j, Job *other, JobType t) {
691 JobDependency *l, *last;
695 assert(j->unit == other->unit);
696 assert(!j->installed);
698 /* Merges 'other' into 'j' and then deletes j. */
701 j->state = JOB_WAITING;
702 j->override = j->override || other->override;
704 j->matters_to_anchor = j->matters_to_anchor || other->matters_to_anchor;
706 /* Patch us in as new owner of the JobDependency objects */
708 LIST_FOREACH(subject, l, other->subject_list) {
709 assert(l->subject == other);
714 /* Merge both lists */
716 last->subject_next = j->subject_list;
718 j->subject_list->subject_prev = last;
719 j->subject_list = other->subject_list;
722 /* Patch us in as new owner of the JobDependency objects */
724 LIST_FOREACH(object, l, other->object_list) {
725 assert(l->object == other);
730 /* Merge both lists */
732 last->object_next = j->object_list;
734 j->object_list->object_prev = last;
735 j->object_list = other->object_list;
738 /* Kill the other job */
739 other->subject_list = NULL;
740 other->object_list = NULL;
741 transaction_delete_job(m, other, true);
743 static bool job_is_conflicted_by(Job *j) {
748 /* Returns true if this job is pulled in by a least one
749 * ConflictedBy dependency. */
751 LIST_FOREACH(object, l, j->object_list)
758 static int delete_one_unmergeable_job(Manager *m, Job *j) {
763 /* Tries to delete one item in the linked list
764 * j->transaction_next->transaction_next->... that conflicts
765 * whith another one, in an attempt to make an inconsistent
766 * transaction work. */
768 /* We rely here on the fact that if a merged with b does not
769 * merge with c, either a or b merge with c neither */
770 LIST_FOREACH(transaction, j, j)
771 LIST_FOREACH(transaction, k, j->transaction_next) {
774 /* Is this one mergeable? Then skip it */
775 if (job_type_is_mergeable(j->type, k->type))
778 /* Ok, we found two that conflict, let's see if we can
779 * drop one of them */
780 if (!j->matters_to_anchor && !k->matters_to_anchor) {
782 /* Both jobs don't matter, so let's
783 * find the one that is smarter to
784 * remove. Let's think positive and
785 * rather remove stops then starts --
786 * except if something is being
787 * stopped because it is conflicted by
788 * another unit in which case we
789 * rather remove the start. */
791 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)));
792 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)));
794 if (j->type == JOB_STOP) {
796 if (job_is_conflicted_by(j))
801 } else if (k->type == JOB_STOP) {
803 if (job_is_conflicted_by(k))
810 } else if (!j->matters_to_anchor)
812 else if (!k->matters_to_anchor)
817 /* Ok, we can drop one, so let's do so. */
818 log_debug("Fixing conflicting jobs by deleting job %s/%s", d->unit->meta.id, job_type_to_string(d->type));
819 transaction_delete_job(m, d, true);
826 static int transaction_merge_jobs(Manager *m, DBusError *e) {
833 /* First step, check whether any of the jobs for one specific
834 * task conflict. If so, try to drop one of them. */
835 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
840 LIST_FOREACH(transaction, k, j->transaction_next) {
841 if (job_type_merge(&t, k->type) >= 0)
844 /* OK, we could not merge all jobs for this
845 * action. Let's see if we can get rid of one
848 if ((r = delete_one_unmergeable_job(m, j)) >= 0)
849 /* Ok, we managed to drop one, now
850 * let's ask our callers to call us
851 * again after garbage collecting */
854 /* We couldn't merge anything. Failure */
855 dbus_set_error(e, BUS_ERROR_TRANSACTION_JOBS_CONFLICTING, "Transaction contains conflicting jobs '%s' and '%s' for %s. Probably contradicting requirement dependencies configured.",
856 job_type_to_string(t), job_type_to_string(k->type), k->unit->meta.id);
861 /* Second step, merge the jobs. */
862 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
866 /* Merge all transactions */
867 LIST_FOREACH(transaction, k, j->transaction_next)
868 assert_se(job_type_merge(&t, k->type) == 0);
870 /* If an active job is mergeable, merge it too */
871 if (j->unit->meta.job)
872 job_type_merge(&t, j->unit->meta.job->type); /* Might fail. Which is OK */
874 while ((k = j->transaction_next)) {
876 transaction_merge_and_delete_job(m, k, j, t);
879 transaction_merge_and_delete_job(m, j, k, t);
882 assert(!j->transaction_next);
883 assert(!j->transaction_prev);
889 static void transaction_drop_redundant(Manager *m) {
894 /* Goes through the transaction and removes all jobs that are
903 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
904 bool changes_something = false;
907 LIST_FOREACH(transaction, k, j) {
909 if (!job_is_anchor(k) &&
910 job_type_is_redundant(k->type, unit_active_state(k->unit)))
913 changes_something = true;
917 if (changes_something)
920 log_debug("Found redundant job %s/%s, dropping.", j->unit->meta.id, job_type_to_string(j->type));
921 transaction_delete_job(m, j, false);
929 static bool unit_matters_to_anchor(Unit *u, Job *j) {
931 assert(!j->transaction_prev);
933 /* Checks whether at least one of the jobs for this unit
934 * matters to the anchor. */
936 LIST_FOREACH(transaction, j, j)
937 if (j->matters_to_anchor)
943 static int transaction_verify_order_one(Manager *m, Job *j, Job *from, unsigned generation, DBusError *e) {
950 assert(!j->transaction_prev);
952 /* Does a recursive sweep through the ordering graph, looking
953 * for a cycle. If we find cycle we try to break it. */
955 /* Have we seen this before? */
956 if (j->generation == generation) {
959 /* If the marker is NULL we have been here already and
960 * decided the job was loop-free from here. Hence
961 * shortcut things and return right-away. */
965 /* So, the marker is not NULL and we already have been
966 * here. We have a cycle. Let's try to break it. We go
967 * backwards in our path and try to find a suitable
968 * job to remove. We use the marker to find our way
969 * back, since smart how we are we stored our way back
971 log_warning("Found ordering cycle on %s/%s", j->unit->meta.id, job_type_to_string(j->type));
974 for (k = from; k; k = ((k->generation == generation && k->marker != k) ? k->marker : NULL)) {
976 log_info("Walked on cycle path to %s/%s", k->unit->meta.id, job_type_to_string(k->type));
980 !unit_matters_to_anchor(k->unit, k)) {
981 /* Ok, we can drop this one, so let's
986 /* Check if this in fact was the beginning of
994 log_warning("Breaking ordering cycle by deleting job %s/%s", delete->unit->meta.id, job_type_to_string(delete->type));
995 transaction_delete_unit(m, delete->unit);
999 log_error("Unable to break cycle");
1001 dbus_set_error(e, BUS_ERROR_TRANSACTION_ORDER_IS_CYCLIC, "Transaction order is cyclic. See system logs for details.");
1005 /* Make the marker point to where we come from, so that we can
1006 * find our way backwards if we want to break a cycle. We use
1007 * a special marker for the beginning: we point to
1009 j->marker = from ? from : j;
1010 j->generation = generation;
1012 /* We assume that the the dependencies are bidirectional, and
1013 * hence can ignore UNIT_AFTER */
1014 SET_FOREACH(u, j->unit->meta.dependencies[UNIT_BEFORE], i) {
1017 /* Is there a job for this unit? */
1018 if (!(o = hashmap_get(m->transaction_jobs, u)))
1020 /* Ok, there is no job for this in the
1021 * transaction, but maybe there is already one
1023 if (!(o = u->meta.job))
1026 if ((r = transaction_verify_order_one(m, o, j, generation, e)) < 0)
1030 /* Ok, let's backtrack, and remember that this entry is not on
1031 * our path anymore. */
1037 static int transaction_verify_order(Manager *m, unsigned *generation, DBusError *e) {
1046 /* Check if the ordering graph is cyclic. If it is, try to fix
1047 * that up by dropping one of the jobs. */
1049 g = (*generation)++;
1051 HASHMAP_FOREACH(j, m->transaction_jobs, i)
1052 if ((r = transaction_verify_order_one(m, j, NULL, g, e)) < 0)
1058 static void transaction_collect_garbage(Manager *m) {
1063 /* Drop jobs that are not required by any other job */
1071 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1075 log_debug("Garbage collecting job %s/%s", j->unit->meta.id, job_type_to_string(j->type));
1076 transaction_delete_job(m, j, true);
1084 static int transaction_is_destructive(Manager *m, DBusError *e) {
1090 /* Checks whether applying this transaction means that
1091 * existing jobs would be replaced */
1093 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1096 assert(!j->transaction_prev);
1097 assert(!j->transaction_next);
1099 if (j->unit->meta.job &&
1100 j->unit->meta.job != j &&
1101 !job_type_is_superset(j->type, j->unit->meta.job->type)) {
1103 dbus_set_error(e, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE, "Transaction is destructive.");
1111 static void transaction_minimize_impact(Manager *m) {
1115 /* Drops all unnecessary jobs that reverse already active jobs
1116 * or that stop a running service. */
1124 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1125 LIST_FOREACH(transaction, j, j) {
1126 bool stops_running_service, changes_existing_job;
1128 /* If it matters, we shouldn't drop it */
1129 if (j->matters_to_anchor)
1132 /* Would this stop a running service?
1133 * Would this change an existing job?
1134 * If so, let's drop this entry */
1136 stops_running_service =
1137 j->type == JOB_STOP && UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(j->unit));
1139 changes_existing_job =
1140 j->unit->meta.job &&
1141 job_type_is_conflicting(j->type, j->unit->meta.job->type);
1143 if (!stops_running_service && !changes_existing_job)
1146 if (stops_running_service)
1147 log_info("%s/%s would stop a running service.", j->unit->meta.id, job_type_to_string(j->type));
1149 if (changes_existing_job)
1150 log_info("%s/%s would change existing job.", j->unit->meta.id, job_type_to_string(j->type));
1152 /* Ok, let's get rid of this */
1153 log_info("Deleting %s/%s to minimize impact.", j->unit->meta.id, job_type_to_string(j->type));
1155 transaction_delete_job(m, j, true);
1167 static int transaction_apply(Manager *m) {
1172 /* Moves the transaction jobs to the set of active jobs */
1174 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1176 assert(!j->transaction_prev);
1177 assert(!j->transaction_next);
1182 if ((r = hashmap_put(m->jobs, UINT32_TO_PTR(j->id), j)) < 0)
1186 while ((j = hashmap_steal_first(m->transaction_jobs))) {
1190 if (j->unit->meta.job)
1191 job_free(j->unit->meta.job);
1193 j->unit->meta.job = j;
1194 j->installed = true;
1195 m->n_installed_jobs ++;
1197 /* We're fully installed. Now let's free data we don't
1200 assert(!j->transaction_next);
1201 assert(!j->transaction_prev);
1203 job_add_to_run_queue(j);
1204 job_add_to_dbus_queue(j);
1207 log_debug("Installed new job %s/%s as %u", j->unit->meta.id, job_type_to_string(j->type), (unsigned) j->id);
1210 /* As last step, kill all remaining job dependencies. */
1211 transaction_clean_dependencies(m);
1217 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1221 hashmap_remove(m->jobs, UINT32_TO_PTR(j->id));
1227 static int transaction_activate(Manager *m, JobMode mode, DBusError *e) {
1229 unsigned generation = 1;
1233 /* This applies the changes recorded in transaction_jobs to
1234 * the actual list of jobs, if possible. */
1236 /* First step: figure out which jobs matter */
1237 transaction_find_jobs_that_matter_to_anchor(m, NULL, generation++);
1239 /* Second step: Try not to stop any running services if
1240 * we don't have to. Don't try to reverse running
1241 * jobs if we don't have to. */
1242 if (mode == JOB_FAIL)
1243 transaction_minimize_impact(m);
1245 /* Third step: Drop redundant jobs */
1246 transaction_drop_redundant(m);
1249 /* Fourth step: Let's remove unneeded jobs that might
1251 transaction_collect_garbage(m);
1253 /* Fifth step: verify order makes sense and correct
1254 * cycles if necessary and possible */
1255 if ((r = transaction_verify_order(m, &generation, e)) >= 0)
1259 log_warning("Requested transaction contains an unfixable cyclic ordering dependency: %s", bus_error(e, r));
1263 /* Let's see if the resulting transaction ordering
1264 * graph is still cyclic... */
1268 /* Sixth step: let's drop unmergeable entries if
1269 * necessary and possible, merge entries we can
1271 if ((r = transaction_merge_jobs(m, e)) >= 0)
1275 log_warning("Requested transaction contains unmergable jobs: %s", bus_error(e, r));
1279 /* Seventh step: an entry got dropped, let's garbage
1280 * collect its dependencies. */
1281 transaction_collect_garbage(m);
1283 /* Let's see if the resulting transaction still has
1284 * unmergeable entries ... */
1287 /* Eights step: Drop redundant jobs again, if the merging now allows us to drop more. */
1288 transaction_drop_redundant(m);
1290 /* Ninth step: check whether we can actually apply this */
1291 if (mode == JOB_FAIL)
1292 if ((r = transaction_is_destructive(m, e)) < 0) {
1293 log_notice("Requested transaction contradicts existing jobs: %s", bus_error(e, r));
1297 /* Tenth step: apply changes */
1298 if ((r = transaction_apply(m)) < 0) {
1299 log_warning("Failed to apply transaction: %s", strerror(-r));
1303 assert(hashmap_isempty(m->transaction_jobs));
1304 assert(!m->transaction_anchor);
1309 transaction_abort(m);
1313 static Job* transaction_add_one_job(Manager *m, JobType type, Unit *unit, bool override, bool *is_new) {
1319 /* Looks for an axisting prospective job and returns that. If
1320 * it doesn't exist it is created and added to the prospective
1323 f = hashmap_get(m->transaction_jobs, unit);
1325 LIST_FOREACH(transaction, j, f) {
1326 assert(j->unit == unit);
1328 if (j->type == type) {
1335 if (unit->meta.job && unit->meta.job->type == type)
1337 else if (!(j = job_new(m, type, unit)))
1342 j->matters_to_anchor = false;
1343 j->override = override;
1345 LIST_PREPEND(Job, transaction, f, j);
1347 if (hashmap_replace(m->transaction_jobs, unit, f) < 0) {
1355 log_debug("Added job %s/%s to transaction.", unit->meta.id, job_type_to_string(type));
1360 void manager_transaction_unlink_job(Manager *m, Job *j, bool delete_dependencies) {
1364 if (j->transaction_prev)
1365 j->transaction_prev->transaction_next = j->transaction_next;
1366 else if (j->transaction_next)
1367 hashmap_replace(m->transaction_jobs, j->unit, j->transaction_next);
1369 hashmap_remove_value(m->transaction_jobs, j->unit, j);
1371 if (j->transaction_next)
1372 j->transaction_next->transaction_prev = j->transaction_prev;
1374 j->transaction_prev = j->transaction_next = NULL;
1376 while (j->subject_list)
1377 job_dependency_free(j->subject_list);
1379 while (j->object_list) {
1380 Job *other = j->object_list->matters ? j->object_list->subject : NULL;
1382 job_dependency_free(j->object_list);
1384 if (other && delete_dependencies) {
1385 log_debug("Deleting job %s/%s as dependency of job %s/%s",
1386 other->unit->meta.id, job_type_to_string(other->type),
1387 j->unit->meta.id, job_type_to_string(j->type));
1388 transaction_delete_job(m, other, delete_dependencies);
1393 static int transaction_add_job_and_dependencies(
1410 assert(type < _JOB_TYPE_MAX);
1413 if (unit->meta.load_state != UNIT_LOADED &&
1414 unit->meta.load_state != UNIT_ERROR &&
1415 unit->meta.load_state != UNIT_MASKED) {
1416 dbus_set_error(e, BUS_ERROR_LOAD_FAILED, "Unit %s is not loaded properly.", unit->meta.id);
1420 if (type != JOB_STOP && unit->meta.load_state == UNIT_ERROR) {
1421 dbus_set_error(e, BUS_ERROR_LOAD_FAILED,
1422 "Unit %s failed to load: %s. "
1423 "See system logs and 'systemctl status' for details.",
1425 strerror(-unit->meta.load_error));
1429 if (type != JOB_STOP && unit->meta.load_state == UNIT_MASKED) {
1430 dbus_set_error(e, BUS_ERROR_MASKED, "Unit %s is masked.", unit->meta.id);
1434 if (!unit_job_is_applicable(unit, type)) {
1435 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);
1439 /* First add the job. */
1440 if (!(ret = transaction_add_one_job(m, type, unit, override, &is_new)))
1443 /* Then, add a link to the job. */
1444 if (!job_dependency_new(by, ret, matters, conflicts))
1450 /* If we are following some other unit, make sure we
1451 * add all dependencies of everybody following. */
1452 if (unit_following_set(ret->unit, &following) > 0) {
1453 SET_FOREACH(dep, following, i)
1454 if ((r = transaction_add_job_and_dependencies(m, type, dep, ret, false, override, false, e, NULL)) < 0) {
1455 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, bus_error(e, r));
1461 set_free(following);
1464 /* Finally, recursively add in all dependencies. */
1465 if (type == JOB_START || type == JOB_RELOAD_OR_START) {
1466 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES], i)
1467 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, true, override, false, e, NULL)) < 0) {
1475 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_BIND_TO], i)
1476 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, true, override, false, e, NULL)) < 0) {
1485 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES_OVERRIDABLE], i)
1486 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, !override, override, false, e, NULL)) < 0) {
1487 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, bus_error(e, r));
1493 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_WANTS], i)
1494 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, false, false, false, e, NULL)) < 0) {
1495 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, bus_error(e, r));
1501 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE], i)
1502 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, true, override, false, e, NULL)) < 0) {
1511 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE_OVERRIDABLE], i)
1512 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, !override, override, false, e, NULL)) < 0) {
1513 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, bus_error(e, r));
1519 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_CONFLICTS], i)
1520 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, dep, ret, true, override, true, e, NULL)) < 0) {
1529 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_CONFLICTED_BY], i)
1530 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, dep, ret, false, override, false, e, NULL)) < 0) {
1531 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, bus_error(e, r));
1537 } else if (type == JOB_STOP || type == JOB_RESTART || type == JOB_TRY_RESTART) {
1539 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRED_BY], i)
1540 if ((r = transaction_add_job_and_dependencies(m, type, dep, ret, true, override, false, e, NULL)) < 0) {
1549 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_BOUND_BY], i)
1550 if ((r = transaction_add_job_and_dependencies(m, type, dep, ret, true, override, false, e, NULL)) < 0) {
1560 /* JOB_VERIFY_STARTED, JOB_RELOAD require no dependency handling */
1572 static int transaction_add_isolate_jobs(Manager *m) {
1580 HASHMAP_FOREACH_KEY(u, k, m->units, i) {
1582 /* ignore aliases */
1583 if (u->meta.id != k)
1586 if (UNIT_VTABLE(u)->no_isolate)
1589 /* No need to stop inactive jobs */
1590 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(u)) && !u->meta.job)
1593 /* Is there already something listed for this? */
1594 if (hashmap_get(m->transaction_jobs, u))
1597 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, u, NULL, true, false, false, NULL, NULL)) < 0)
1598 log_warning("Cannot add isolate job for unit %s, ignoring: %s", u->meta.id, strerror(-r));
1604 int manager_add_job(Manager *m, JobType type, Unit *unit, JobMode mode, bool override, DBusError *e, Job **_ret) {
1609 assert(type < _JOB_TYPE_MAX);
1611 assert(mode < _JOB_MODE_MAX);
1613 if (mode == JOB_ISOLATE && type != JOB_START) {
1614 dbus_set_error(e, BUS_ERROR_INVALID_JOB_MODE, "Isolate is only valid for start.");
1618 if (mode == JOB_ISOLATE && !unit->meta.allow_isolate) {
1619 dbus_set_error(e, BUS_ERROR_NO_ISOLATION, "Operation refused, unit may not be isolated.");
1623 log_debug("Trying to enqueue job %s/%s/%s", unit->meta.id, job_type_to_string(type), job_mode_to_string(mode));
1625 if ((r = transaction_add_job_and_dependencies(m, type, unit, NULL, true, override, false, e, &ret)) < 0) {
1626 transaction_abort(m);
1630 if (mode == JOB_ISOLATE)
1631 if ((r = transaction_add_isolate_jobs(m)) < 0) {
1632 transaction_abort(m);
1636 if ((r = transaction_activate(m, mode, e)) < 0)
1639 log_debug("Enqueued job %s/%s as %u", unit->meta.id, job_type_to_string(type), (unsigned) ret->id);
1647 int manager_add_job_by_name(Manager *m, JobType type, const char *name, JobMode mode, bool override, DBusError *e, Job **_ret) {
1652 assert(type < _JOB_TYPE_MAX);
1654 assert(mode < _JOB_MODE_MAX);
1656 if ((r = manager_load_unit(m, name, NULL, NULL, &unit)) < 0)
1659 return manager_add_job(m, type, unit, mode, override, e, _ret);
1662 Job *manager_get_job(Manager *m, uint32_t id) {
1665 return hashmap_get(m->jobs, UINT32_TO_PTR(id));
1668 Unit *manager_get_unit(Manager *m, const char *name) {
1672 return hashmap_get(m->units, name);
1675 unsigned manager_dispatch_load_queue(Manager *m) {
1681 /* Make sure we are not run recursively */
1682 if (m->dispatching_load_queue)
1685 m->dispatching_load_queue = true;
1687 /* Dispatches the load queue. Takes a unit from the queue and
1688 * tries to load its data until the queue is empty */
1690 while ((meta = m->load_queue)) {
1691 assert(meta->in_load_queue);
1693 unit_load((Unit*) meta);
1697 m->dispatching_load_queue = false;
1701 int manager_load_unit_prepare(Manager *m, const char *name, const char *path, DBusError *e, Unit **_ret) {
1706 assert(name || path);
1708 /* This will prepare the unit for loading, but not actually
1709 * load anything from disk. */
1711 if (path && !is_path(path)) {
1712 dbus_set_error(e, BUS_ERROR_INVALID_PATH, "Path %s is not absolute.", path);
1717 name = file_name_from_path(path);
1719 if (!unit_name_is_valid(name, false)) {
1720 dbus_set_error(e, BUS_ERROR_INVALID_NAME, "Unit name %s is not valid.", name);
1724 if ((ret = manager_get_unit(m, name))) {
1729 if (!(ret = unit_new(m)))
1733 if (!(ret->meta.fragment_path = strdup(path))) {
1738 if ((r = unit_add_name(ret, name)) < 0) {
1743 unit_add_to_load_queue(ret);
1744 unit_add_to_dbus_queue(ret);
1745 unit_add_to_gc_queue(ret);
1753 int manager_load_unit(Manager *m, const char *name, const char *path, DBusError *e, Unit **_ret) {
1758 /* This will load the service information files, but not actually
1759 * start any services or anything. */
1761 if ((r = manager_load_unit_prepare(m, name, path, e, _ret)) != 0)
1764 manager_dispatch_load_queue(m);
1767 *_ret = unit_follow_merge(*_ret);
1772 void manager_dump_jobs(Manager *s, FILE *f, const char *prefix) {
1779 HASHMAP_FOREACH(j, s->jobs, i)
1780 job_dump(j, f, prefix);
1783 void manager_dump_units(Manager *s, FILE *f, const char *prefix) {
1791 HASHMAP_FOREACH_KEY(u, t, s->units, i)
1792 if (u->meta.id == t)
1793 unit_dump(u, f, prefix);
1796 void manager_clear_jobs(Manager *m) {
1801 transaction_abort(m);
1803 while ((j = hashmap_first(m->jobs)))
1807 unsigned manager_dispatch_run_queue(Manager *m) {
1811 if (m->dispatching_run_queue)
1814 m->dispatching_run_queue = true;
1816 while ((j = m->run_queue)) {
1817 assert(j->installed);
1818 assert(j->in_run_queue);
1820 job_run_and_invalidate(j);
1824 m->dispatching_run_queue = false;
1828 unsigned manager_dispatch_dbus_queue(Manager *m) {
1835 if (m->dispatching_dbus_queue)
1838 m->dispatching_dbus_queue = true;
1840 while ((meta = m->dbus_unit_queue)) {
1841 assert(meta->in_dbus_queue);
1843 bus_unit_send_change_signal((Unit*) meta);
1847 while ((j = m->dbus_job_queue)) {
1848 assert(j->in_dbus_queue);
1850 bus_job_send_change_signal(j);
1854 m->dispatching_dbus_queue = false;
1858 static int manager_process_notify_fd(Manager *m) {
1865 struct msghdr msghdr;
1867 struct ucred *ucred;
1869 struct cmsghdr cmsghdr;
1870 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
1876 iovec.iov_base = buf;
1877 iovec.iov_len = sizeof(buf)-1;
1881 msghdr.msg_iov = &iovec;
1882 msghdr.msg_iovlen = 1;
1883 msghdr.msg_control = &control;
1884 msghdr.msg_controllen = sizeof(control);
1886 if ((n = recvmsg(m->notify_watch.fd, &msghdr, MSG_DONTWAIT)) <= 0) {
1890 if (errno == EAGAIN || errno == EINTR)
1896 if (msghdr.msg_controllen < CMSG_LEN(sizeof(struct ucred)) ||
1897 control.cmsghdr.cmsg_level != SOL_SOCKET ||
1898 control.cmsghdr.cmsg_type != SCM_CREDENTIALS ||
1899 control.cmsghdr.cmsg_len != CMSG_LEN(sizeof(struct ucred))) {
1900 log_warning("Received notify message without credentials. Ignoring.");
1904 ucred = (struct ucred*) CMSG_DATA(&control.cmsghdr);
1906 if (!(u = hashmap_get(m->watch_pids, LONG_TO_PTR(ucred->pid))))
1907 if (!(u = cgroup_unit_by_pid(m, ucred->pid))) {
1908 log_warning("Cannot find unit for notify message of PID %lu.", (unsigned long) ucred->pid);
1912 assert((size_t) n < sizeof(buf));
1914 if (!(tags = strv_split(buf, "\n\r")))
1917 log_debug("Got notification message for unit %s", u->meta.id);
1919 if (UNIT_VTABLE(u)->notify_message)
1920 UNIT_VTABLE(u)->notify_message(u, ucred->pid, tags);
1928 static int manager_dispatch_sigchld(Manager *m) {
1938 /* First we call waitd() for a PID and do not reap the
1939 * zombie. That way we can still access /proc/$PID for
1940 * it while it is a zombie. */
1941 if (waitid(P_ALL, 0, &si, WEXITED|WNOHANG|WNOWAIT) < 0) {
1943 if (errno == ECHILD)
1955 if (si.si_code == CLD_EXITED || si.si_code == CLD_KILLED || si.si_code == CLD_DUMPED) {
1958 get_process_name(si.si_pid, &name);
1959 log_debug("Got SIGCHLD for process %lu (%s)", (unsigned long) si.si_pid, strna(name));
1963 /* Let's flush any message the dying child might still
1964 * have queued for us. This ensures that the process
1965 * still exists in /proc so that we can figure out
1966 * which cgroup and hence unit it belongs to. */
1967 if ((r = manager_process_notify_fd(m)) < 0)
1970 /* And now figure out the unit this belongs to */
1971 if (!(u = hashmap_get(m->watch_pids, LONG_TO_PTR(si.si_pid))))
1972 u = cgroup_unit_by_pid(m, si.si_pid);
1974 /* And now, we actually reap the zombie. */
1975 if (waitid(P_PID, si.si_pid, &si, WEXITED) < 0) {
1982 if (si.si_code != CLD_EXITED && si.si_code != CLD_KILLED && si.si_code != CLD_DUMPED)
1985 log_debug("Child %lu died (code=%s, status=%i/%s)",
1986 (long unsigned) si.si_pid,
1987 sigchld_code_to_string(si.si_code),
1989 strna(si.si_code == CLD_EXITED
1990 ? exit_status_to_string(si.si_status, EXIT_STATUS_FULL)
1991 : signal_to_string(si.si_status)));
1996 log_debug("Child %lu belongs to %s", (long unsigned) si.si_pid, u->meta.id);
1998 hashmap_remove(m->watch_pids, LONG_TO_PTR(si.si_pid));
1999 UNIT_VTABLE(u)->sigchld_event(u, si.si_pid, si.si_code, si.si_status);
2005 static int manager_start_target(Manager *m, const char *name, JobMode mode) {
2009 dbus_error_init(&error);
2011 log_info("Activating special unit %s", name);
2013 if ((r = manager_add_job_by_name(m, JOB_START, name, mode, true, &error, NULL)) < 0)
2014 log_error("Failed to enqueue %s job: %s", name, bus_error(&error, r));
2016 dbus_error_free(&error);
2021 static int manager_process_signal_fd(Manager *m) {
2023 struct signalfd_siginfo sfsi;
2024 bool sigchld = false;
2029 if ((n = read(m->signal_watch.fd, &sfsi, sizeof(sfsi))) != sizeof(sfsi)) {
2034 if (errno == EINTR || errno == EAGAIN)
2040 log_debug("Received SIG%s", strna(signal_to_string(sfsi.ssi_signo)));
2042 switch (sfsi.ssi_signo) {
2049 if (m->running_as == MANAGER_SYSTEM) {
2050 /* This is for compatibility with the
2051 * original sysvinit */
2052 m->exit_code = MANAGER_REEXECUTE;
2059 if (m->running_as == MANAGER_SYSTEM) {
2060 manager_start_target(m, SPECIAL_CTRL_ALT_DEL_TARGET, JOB_REPLACE);
2064 /* Run the exit target if there is one, if not, just exit. */
2065 if (manager_start_target(m, SPECIAL_EXIT_TARGET, JOB_REPLACE) < 0) {
2066 m->exit_code = MANAGER_EXIT;
2073 if (m->running_as == MANAGER_SYSTEM)
2074 manager_start_target(m, SPECIAL_KBREQUEST_TARGET, JOB_REPLACE);
2076 /* This is a nop on non-init */
2080 if (m->running_as == MANAGER_SYSTEM)
2081 manager_start_target(m, SPECIAL_SIGPWR_TARGET, JOB_REPLACE);
2083 /* This is a nop on non-init */
2089 u = manager_get_unit(m, SPECIAL_DBUS_SERVICE);
2091 if (!u || UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u))) {
2092 log_info("Trying to reconnect to bus...");
2096 if (!u || !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u))) {
2097 log_info("Loading D-Bus service...");
2098 manager_start_target(m, SPECIAL_DBUS_SERVICE, JOB_REPLACE);
2109 if (!(f = open_memstream(&dump, &size))) {
2110 log_warning("Failed to allocate memory stream.");
2114 manager_dump_units(m, f, "\t");
2115 manager_dump_jobs(m, f, "\t");
2120 log_warning("Failed to write status stream");
2125 log_dump(LOG_INFO, dump);
2132 m->exit_code = MANAGER_RELOAD;
2136 /* Starting SIGRTMIN+0 */
2137 static const char * const target_table[] = {
2138 [0] = SPECIAL_DEFAULT_TARGET,
2139 [1] = SPECIAL_RESCUE_TARGET,
2140 [2] = SPECIAL_EMERGENCY_TARGET,
2141 [3] = SPECIAL_HALT_TARGET,
2142 [4] = SPECIAL_POWEROFF_TARGET,
2143 [5] = SPECIAL_REBOOT_TARGET,
2144 [6] = SPECIAL_KEXEC_TARGET
2147 /* Starting SIGRTMIN+13, so that target halt and system halt are 10 apart */
2148 static const ManagerExitCode code_table[] = {
2150 [1] = MANAGER_POWEROFF,
2151 [2] = MANAGER_REBOOT,
2155 if ((int) sfsi.ssi_signo >= SIGRTMIN+0 &&
2156 (int) sfsi.ssi_signo < SIGRTMIN+(int) ELEMENTSOF(target_table)) {
2157 manager_start_target(m, target_table[sfsi.ssi_signo - SIGRTMIN],
2158 (sfsi.ssi_signo == 1 || sfsi.ssi_signo == 2) ? JOB_ISOLATE : JOB_REPLACE);
2162 if ((int) sfsi.ssi_signo >= SIGRTMIN+13 &&
2163 (int) sfsi.ssi_signo < SIGRTMIN+13+(int) ELEMENTSOF(code_table)) {
2164 m->exit_code = code_table[sfsi.ssi_signo - SIGRTMIN - 13];
2168 log_warning("Got unhandled signal <%s>.", strna(signal_to_string(sfsi.ssi_signo)));
2174 return manager_dispatch_sigchld(m);
2179 static int process_event(Manager *m, struct epoll_event *ev) {
2186 assert(w = ev->data.ptr);
2192 /* An incoming signal? */
2193 if (ev->events != EPOLLIN)
2196 if ((r = manager_process_signal_fd(m)) < 0)
2203 /* An incoming daemon notification event? */
2204 if (ev->events != EPOLLIN)
2207 if ((r = manager_process_notify_fd(m)) < 0)
2214 /* Some fd event, to be dispatched to the units */
2215 UNIT_VTABLE(w->data.unit)->fd_event(w->data.unit, w->fd, ev->events, w);
2218 case WATCH_UNIT_TIMER:
2219 case WATCH_JOB_TIMER: {
2223 /* Some timer event, to be dispatched to the units */
2224 if ((k = read(w->fd, &v, sizeof(v))) != sizeof(v)) {
2226 if (k < 0 && (errno == EINTR || errno == EAGAIN))
2229 return k < 0 ? -errno : -EIO;
2232 if (w->type == WATCH_UNIT_TIMER)
2233 UNIT_VTABLE(w->data.unit)->timer_event(w->data.unit, v, w);
2235 job_timer_event(w->data.job, v, w);
2240 /* Some mount table change, intended for the mount subsystem */
2241 mount_fd_event(m, ev->events);
2245 /* Some swap table change, intended for the swap subsystem */
2246 swap_fd_event(m, ev->events);
2250 /* Some notification from udev, intended for the device subsystem */
2251 device_fd_event(m, ev->events);
2254 case WATCH_DBUS_WATCH:
2255 bus_watch_event(m, w, ev->events);
2258 case WATCH_DBUS_TIMEOUT:
2259 bus_timeout_event(m, w, ev->events);
2263 log_error("event type=%i", w->type);
2264 assert_not_reached("Unknown epoll event type.");
2270 int manager_loop(Manager *m) {
2273 RATELIMIT_DEFINE(rl, 1*USEC_PER_SEC, 1000);
2276 m->exit_code = MANAGER_RUNNING;
2278 /* Release the path cache */
2279 set_free_free(m->unit_path_cache);
2280 m->unit_path_cache = NULL;
2282 manager_check_finished(m);
2284 /* There might still be some zombies hanging around from
2285 * before we were exec()'ed. Leat's reap them */
2286 if ((r = manager_dispatch_sigchld(m)) < 0)
2289 while (m->exit_code == MANAGER_RUNNING) {
2290 struct epoll_event event;
2293 if (!ratelimit_test(&rl)) {
2294 /* Yay, something is going seriously wrong, pause a little */
2295 log_warning("Looping too fast. Throttling execution a little.");
2299 if (manager_dispatch_load_queue(m) > 0)
2302 if (manager_dispatch_run_queue(m) > 0)
2305 if (bus_dispatch(m) > 0)
2308 if (manager_dispatch_cleanup_queue(m) > 0)
2311 if (manager_dispatch_gc_queue(m) > 0)
2314 if (manager_dispatch_dbus_queue(m) > 0)
2317 if (swap_dispatch_reload(m) > 0)
2320 if ((n = epoll_wait(m->epoll_fd, &event, 1, -1)) < 0) {
2330 if ((r = process_event(m, &event)) < 0)
2334 return m->exit_code;
2337 int manager_get_unit_from_dbus_path(Manager *m, const char *s, Unit **_u) {
2345 if (!startswith(s, "/org/freedesktop/systemd1/unit/"))
2348 if (!(n = bus_path_unescape(s+31)))
2351 u = manager_get_unit(m, n);
2362 int manager_get_job_from_dbus_path(Manager *m, const char *s, Job **_j) {
2371 if (!startswith(s, "/org/freedesktop/systemd1/job/"))
2374 if ((r = safe_atou(s + 30, &id)) < 0)
2377 if (!(j = manager_get_job(m, id)))
2385 void manager_send_unit_audit(Manager *m, Unit *u, int type, bool success) {
2390 if (m->audit_fd < 0)
2393 /* Don't generate audit events if the service was already
2394 * started and we're just deserializing */
2395 if (m->n_deserializing > 0)
2398 if (!(p = unit_name_to_prefix_and_instance(u->meta.id))) {
2399 log_error("Failed to allocate unit name for audit message: %s", strerror(ENOMEM));
2403 if (audit_log_user_comm_message(m->audit_fd, type, "", p, NULL, NULL, NULL, success) < 0)
2404 log_error("Failed to send audit message: %m");
2411 void manager_send_unit_plymouth(Manager *m, Unit *u) {
2413 union sockaddr_union sa;
2415 char *message = NULL;
2418 /* Don't generate plymouth events if the service was already
2419 * started and we're just deserializing */
2420 if (m->n_deserializing > 0)
2423 if (m->running_as != MANAGER_SYSTEM)
2426 if (u->meta.type != UNIT_SERVICE &&
2427 u->meta.type != UNIT_MOUNT &&
2428 u->meta.type != UNIT_SWAP)
2431 /* We set SOCK_NONBLOCK here so that we rather drop the
2432 * message then wait for plymouth */
2433 if ((fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0)) < 0) {
2434 log_error("socket() failed: %m");
2439 sa.sa.sa_family = AF_UNIX;
2440 strncpy(sa.un.sun_path+1, "/ply-boot-protocol", sizeof(sa.un.sun_path)-1);
2441 if (connect(fd, &sa.sa, sizeof(sa.un)) < 0) {
2443 if (errno != EPIPE &&
2446 errno != ECONNREFUSED &&
2447 errno != ECONNRESET &&
2448 errno != ECONNABORTED)
2449 log_error("connect() failed: %m");
2454 if (asprintf(&message, "U\002%c%s%n", (int) (strlen(u->meta.id) + 1), u->meta.id, &n) < 0) {
2455 log_error("Out of memory");
2460 if ((r = write(fd, message, n + 1)) != n + 1) {
2462 if (errno != EPIPE &&
2465 errno != ECONNREFUSED &&
2466 errno != ECONNRESET &&
2467 errno != ECONNABORTED)
2468 log_error("Failed to write Plymouth message: %m");
2475 close_nointr_nofail(fd);
2480 void manager_dispatch_bus_name_owner_changed(
2483 const char* old_owner,
2484 const char *new_owner) {
2491 if (!(u = hashmap_get(m->watch_bus, name)))
2494 UNIT_VTABLE(u)->bus_name_owner_change(u, name, old_owner, new_owner);
2497 void manager_dispatch_bus_query_pid_done(
2508 if (!(u = hashmap_get(m->watch_bus, name)))
2511 UNIT_VTABLE(u)->bus_query_pid_done(u, name, pid);
2514 int manager_open_serialization(Manager *m, FILE **_f) {
2522 if (m->running_as == MANAGER_SYSTEM) {
2523 mkdir_p("/dev/.systemd", 0755);
2525 if (asprintf(&path, "/dev/.systemd/dump-%lu-XXXXXX", (unsigned long) getpid()) < 0)
2528 if (asprintf(&path, "/tmp/systemd-dump-%lu-XXXXXX", (unsigned long) getpid()) < 0)
2532 saved_umask = umask(0077);
2533 fd = mkostemp(path, O_RDWR|O_CLOEXEC);
2543 log_debug("Serializing state to %s", path);
2546 if (!(f = fdopen(fd, "w+")) < 0)
2554 int manager_serialize(Manager *m, FILE *f, FDSet *fds) {
2564 dual_timestamp_serialize(f, "initrd-timestamp", &m->initrd_timestamp);
2565 dual_timestamp_serialize(f, "startup-timestamp", &m->startup_timestamp);
2566 dual_timestamp_serialize(f, "finish-timestamp", &m->finish_timestamp);
2570 HASHMAP_FOREACH_KEY(u, t, m->units, i) {
2571 if (u->meta.id != t)
2574 if (!unit_can_serialize(u))
2578 fputs(u->meta.id, f);
2581 if ((r = unit_serialize(u, f, fds)) < 0)
2591 int manager_deserialize(Manager *m, FILE *f, FDSet *fds) {
2597 log_debug("Deserializing state...");
2599 m->n_deserializing ++;
2602 char line[1024], *l;
2604 if (!fgets(line, sizeof(line), f)) {
2619 if (startswith(l, "initrd-timestamp="))
2620 dual_timestamp_deserialize(l+17, &m->initrd_timestamp);
2621 else if (startswith(l, "startup-timestamp="))
2622 dual_timestamp_deserialize(l+18, &m->startup_timestamp);
2623 else if (startswith(l, "finish-timestamp="))
2624 dual_timestamp_deserialize(l+17, &m->finish_timestamp);
2626 log_debug("Unknown serialization item '%s'", l);
2631 char name[UNIT_NAME_MAX+2];
2634 if (!fgets(name, sizeof(name), f)) {
2645 if ((r = manager_load_unit(m, strstrip(name), NULL, NULL, &u)) < 0)
2648 if ((r = unit_deserialize(u, f, fds)) < 0)
2658 assert(m->n_deserializing > 0);
2659 m->n_deserializing --;
2664 int manager_reload(Manager *m) {
2671 if ((r = manager_open_serialization(m, &f)) < 0)
2674 if (!(fds = fdset_new())) {
2679 if ((r = manager_serialize(m, f, fds)) < 0)
2682 if (fseeko(f, 0, SEEK_SET) < 0) {
2687 /* From here on there is no way back. */
2688 manager_clear_jobs_and_units(m);
2689 manager_undo_generators(m);
2691 /* Find new unit paths */
2692 lookup_paths_free(&m->lookup_paths);
2693 if ((q = lookup_paths_init(&m->lookup_paths, m->running_as)) < 0)
2696 manager_run_generators(m);
2698 manager_build_unit_path_cache(m);
2700 m->n_deserializing ++;
2702 /* First, enumerate what we can from all config files */
2703 if ((q = manager_enumerate(m)) < 0)
2706 /* Second, deserialize our stored data */
2707 if ((q = manager_deserialize(m, f, fds)) < 0)
2713 /* Third, fire things up! */
2714 if ((q = manager_coldplug(m)) < 0)
2717 assert(m->n_deserializing > 0);
2718 m->n_deserializing ++;
2730 bool manager_is_booting_or_shutting_down(Manager *m) {
2735 /* Is the initial job still around? */
2736 if (manager_get_job(m, 1))
2739 /* Is there a job for the shutdown target? */
2740 if (((u = manager_get_unit(m, SPECIAL_SHUTDOWN_TARGET))))
2741 return !!u->meta.job;
2746 void manager_reset_failed(Manager *m) {
2752 HASHMAP_FOREACH(u, m->units, i)
2753 unit_reset_failed(u);
2756 int manager_set_console(Manager *m, const char *console) {
2761 if (!(c = strdup(console)))
2767 log_debug("Using kernel console %s", c);
2772 bool manager_unit_pending_inactive(Manager *m, const char *name) {
2778 /* Returns true if the unit is inactive or going down */
2779 if (!(u = manager_get_unit(m, name)))
2782 return unit_pending_inactive(u);
2785 void manager_check_finished(Manager *m) {
2786 char userspace[FORMAT_TIMESPAN_MAX], initrd[FORMAT_TIMESPAN_MAX], kernel[FORMAT_TIMESPAN_MAX], sum[FORMAT_TIMESPAN_MAX];
2790 if (dual_timestamp_is_set(&m->finish_timestamp))
2793 if (hashmap_size(m->jobs) > 0)
2796 dual_timestamp_get(&m->finish_timestamp);
2798 if (m->running_as == MANAGER_SYSTEM) {
2799 if (dual_timestamp_is_set(&m->initrd_timestamp)) {
2800 log_info("Startup finished in %s (kernel) + %s (initrd) + %s (userspace) = %s.",
2801 format_timespan(kernel, sizeof(kernel),
2802 m->initrd_timestamp.monotonic),
2803 format_timespan(initrd, sizeof(initrd),
2804 m->startup_timestamp.monotonic - m->initrd_timestamp.monotonic),
2805 format_timespan(userspace, sizeof(userspace),
2806 m->finish_timestamp.monotonic - m->startup_timestamp.monotonic),
2807 format_timespan(sum, sizeof(sum),
2808 m->finish_timestamp.monotonic));
2810 log_info("Startup finished in %s (kernel) + %s (userspace) = %s.",
2811 format_timespan(kernel, sizeof(kernel),
2812 m->startup_timestamp.monotonic),
2813 format_timespan(userspace, sizeof(userspace),
2814 m->finish_timestamp.monotonic - m->startup_timestamp.monotonic),
2815 format_timespan(sum, sizeof(sum),
2816 m->finish_timestamp.monotonic));
2818 log_debug("Startup finished in %s.",
2819 format_timespan(userspace, sizeof(userspace),
2820 m->finish_timestamp.monotonic - m->startup_timestamp.monotonic));
2824 void manager_run_generators(Manager *m) {
2827 Hashmap *pids = NULL;
2828 const char *generator_path;
2832 generator_path = m->running_as == MANAGER_SYSTEM ? SYSTEM_GENERATOR_PATH : SESSION_GENERATOR_PATH;
2833 if (!(d = opendir(generator_path))) {
2835 if (errno == ENOENT)
2838 log_error("Failed to enumerate generator directory: %m");
2842 if (!m->generator_unit_path) {
2844 char system_path[] = "/dev/.systemd/generator-XXXXXX",
2845 session_path[] = "/tmp/systemd-generator-XXXXXX";
2847 if (!(p = mkdtemp(m->running_as == MANAGER_SYSTEM ? system_path : session_path))) {
2848 log_error("Failed to generate generator directory: %m");
2852 if (!(m->generator_unit_path = strdup(p))) {
2853 log_error("Failed to allocate generator unit path.");
2858 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
2859 log_error("Failed to allocate set.");
2863 while ((de = readdir(d))) {
2868 if (ignore_file(de->d_name))
2871 if (de->d_type != DT_REG &&
2872 de->d_type != DT_LNK &&
2873 de->d_type != DT_UNKNOWN)
2876 if (asprintf(&path, "%s/%s", generator_path, de->d_name) < 0) {
2877 log_error("Out of memory");
2881 if ((pid = fork()) < 0) {
2882 log_error("Failed to fork: %m");
2888 const char *arguments[5];
2891 arguments[0] = path;
2892 arguments[1] = m->generator_unit_path;
2893 arguments[2] = NULL;
2895 execv(path, (char **) arguments);
2897 log_error("Failed to execute %s: %m", path);
2898 _exit(EXIT_FAILURE);
2901 log_debug("Spawned generator %s as %lu", path, (unsigned long) pid);
2903 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
2904 log_error("Failed to add PID to set: %s", strerror(-k));
2909 while (!hashmap_isempty(pids)) {
2914 if (waitid(P_ALL, 0, &si, WEXITED) < 0) {
2919 log_error("waitid() failed: %m");
2923 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
2924 if (!is_clean_exit(si.si_code, si.si_status)) {
2925 if (si.si_code == CLD_EXITED)
2926 log_error("%s exited with exit status %i.", path, si.si_status);
2928 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
2930 log_debug("Generator %s exited successfully.", path);
2936 if (rmdir(m->generator_unit_path) >= 0) {
2937 /* Uh? we were able to remove this dir? I guess that
2938 * means the directory was empty, hence let's shortcut
2941 free(m->generator_unit_path);
2942 m->generator_unit_path = NULL;
2946 if (!strv_find(m->lookup_paths.unit_path, m->generator_unit_path)) {
2949 if (!(l = strv_append(m->lookup_paths.unit_path, m->generator_unit_path))) {
2950 log_error("Failed to add generator directory to unit search path: %m");
2954 strv_free(m->lookup_paths.unit_path);
2955 m->lookup_paths.unit_path = l;
2957 log_debug("Added generator unit path %s to search path.", m->generator_unit_path);
2965 hashmap_free_free(pids);
2968 void manager_undo_generators(Manager *m) {
2971 if (!m->generator_unit_path)
2974 strv_remove(m->lookup_paths.unit_path, m->generator_unit_path);
2975 rm_rf(m->generator_unit_path, false, true);
2977 free(m->generator_unit_path);
2978 m->generator_unit_path = NULL;
2981 static const char* const manager_running_as_table[_MANAGER_RUNNING_AS_MAX] = {
2982 [MANAGER_SYSTEM] = "system",
2983 [MANAGER_SESSION] = "session"
2986 DEFINE_STRING_TABLE_LOOKUP(manager_running_as, ManagerRunningAs);