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 */
177 SIGRTMIN+20, /* systemd: enable status messages */
178 SIGRTMIN+21, /* systemd: disable status messages */
180 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
182 m->signal_watch.type = WATCH_SIGNAL;
183 if ((m->signal_watch.fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0)
188 ev.data.ptr = &m->signal_watch;
190 if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->signal_watch.fd, &ev) < 0)
193 if (m->running_as == MANAGER_SYSTEM)
194 return enable_special_signals(m);
199 int manager_new(ManagerRunningAs running_as, Manager **_m) {
204 assert(running_as >= 0);
205 assert(running_as < _MANAGER_RUNNING_AS_MAX);
207 if (!(m = new0(Manager, 1)))
210 dual_timestamp_get(&m->startup_timestamp);
212 m->running_as = running_as;
213 m->name_data_slot = m->subscribed_data_slot = -1;
214 m->exit_code = _MANAGER_EXIT_CODE_INVALID;
215 m->pin_cgroupfs_fd = -1;
217 m->default_std_output = EXEC_OUTPUT_NULL;
223 m->signal_watch.fd = m->mount_watch.fd = m->udev_watch.fd = m->epoll_fd = m->dev_autofs_fd = m->swap_watch.fd = -1;
224 m->current_job_id = 1; /* start as id #1, so that we can leave #0 around as "null-like" value */
226 if (!(m->environment = strv_copy(environ)))
229 if (!(m->default_controllers = strv_new("cpu", NULL)))
232 if (!(m->units = hashmap_new(string_hash_func, string_compare_func)))
235 if (!(m->jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
238 if (!(m->transaction_jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
241 if (!(m->watch_pids = hashmap_new(trivial_hash_func, trivial_compare_func)))
244 if (!(m->cgroup_bondings = hashmap_new(string_hash_func, string_compare_func)))
247 if (!(m->watch_bus = hashmap_new(string_hash_func, string_compare_func)))
250 if ((m->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0)
253 if ((r = lookup_paths_init(&m->lookup_paths, m->running_as)) < 0)
256 if ((r = manager_setup_signals(m)) < 0)
259 if ((r = manager_setup_cgroup(m)) < 0)
262 if ((r = manager_setup_notify(m)) < 0)
265 /* Try to connect to the busses, if possible. */
266 if ((r = bus_init(m, running_as != MANAGER_SYSTEM)) < 0)
270 if ((m->audit_fd = audit_open()) < 0)
271 log_error("Failed to connect to audit log: %m");
282 static unsigned manager_dispatch_cleanup_queue(Manager *m) {
288 while ((meta = m->cleanup_queue)) {
289 assert(meta->in_cleanup_queue);
291 unit_free((Unit*) meta);
299 GC_OFFSET_IN_PATH, /* This one is on the path we were travelling */
300 GC_OFFSET_UNSURE, /* No clue */
301 GC_OFFSET_GOOD, /* We still need this unit */
302 GC_OFFSET_BAD, /* We don't need this unit anymore */
306 static void unit_gc_sweep(Unit *u, unsigned gc_marker) {
313 if (u->meta.gc_marker == gc_marker + GC_OFFSET_GOOD ||
314 u->meta.gc_marker == gc_marker + GC_OFFSET_BAD ||
315 u->meta.gc_marker == gc_marker + GC_OFFSET_IN_PATH)
318 if (u->meta.in_cleanup_queue)
321 if (unit_check_gc(u))
324 u->meta.gc_marker = gc_marker + GC_OFFSET_IN_PATH;
328 SET_FOREACH(other, u->meta.dependencies[UNIT_REFERENCED_BY], i) {
329 unit_gc_sweep(other, gc_marker);
331 if (other->meta.gc_marker == gc_marker + GC_OFFSET_GOOD)
334 if (other->meta.gc_marker != gc_marker + GC_OFFSET_BAD)
341 /* We were unable to find anything out about this entry, so
342 * let's investigate it later */
343 u->meta.gc_marker = gc_marker + GC_OFFSET_UNSURE;
344 unit_add_to_gc_queue(u);
348 /* We definitely know that this one is not useful anymore, so
349 * let's mark it for deletion */
350 u->meta.gc_marker = gc_marker + GC_OFFSET_BAD;
351 unit_add_to_cleanup_queue(u);
355 u->meta.gc_marker = gc_marker + GC_OFFSET_GOOD;
358 static unsigned manager_dispatch_gc_queue(Manager *m) {
365 if ((m->n_in_gc_queue < GC_QUEUE_ENTRIES_MAX) &&
366 (m->gc_queue_timestamp <= 0 ||
367 (m->gc_queue_timestamp + GC_QUEUE_USEC_MAX) > now(CLOCK_MONOTONIC)))
370 log_debug("Running GC...");
372 m->gc_marker += _GC_OFFSET_MAX;
373 if (m->gc_marker + _GC_OFFSET_MAX <= _GC_OFFSET_MAX)
376 gc_marker = m->gc_marker;
378 while ((meta = m->gc_queue)) {
379 assert(meta->in_gc_queue);
381 unit_gc_sweep((Unit*) meta, gc_marker);
383 LIST_REMOVE(Meta, gc_queue, m->gc_queue, meta);
384 meta->in_gc_queue = false;
388 if (meta->gc_marker == gc_marker + GC_OFFSET_BAD ||
389 meta->gc_marker == gc_marker + GC_OFFSET_UNSURE) {
390 log_debug("Collecting %s", meta->id);
391 meta->gc_marker = gc_marker + GC_OFFSET_BAD;
392 unit_add_to_cleanup_queue((Unit*) meta);
396 m->n_in_gc_queue = 0;
397 m->gc_queue_timestamp = 0;
402 static void manager_clear_jobs_and_units(Manager *m) {
408 while ((j = hashmap_first(m->transaction_jobs)))
411 while ((u = hashmap_first(m->units)))
414 manager_dispatch_cleanup_queue(m);
416 assert(!m->load_queue);
417 assert(!m->run_queue);
418 assert(!m->dbus_unit_queue);
419 assert(!m->dbus_job_queue);
420 assert(!m->cleanup_queue);
421 assert(!m->gc_queue);
423 assert(hashmap_isempty(m->transaction_jobs));
424 assert(hashmap_isempty(m->jobs));
425 assert(hashmap_isempty(m->units));
428 void manager_free(Manager *m) {
433 manager_clear_jobs_and_units(m);
435 for (c = 0; c < _UNIT_TYPE_MAX; c++)
436 if (unit_vtable[c]->shutdown)
437 unit_vtable[c]->shutdown(m);
439 /* If we reexecute ourselves, we keep the root cgroup
441 manager_shutdown_cgroup(m, m->exit_code != MANAGER_REEXECUTE);
443 manager_undo_generators(m);
447 hashmap_free(m->units);
448 hashmap_free(m->jobs);
449 hashmap_free(m->transaction_jobs);
450 hashmap_free(m->watch_pids);
451 hashmap_free(m->watch_bus);
453 if (m->epoll_fd >= 0)
454 close_nointr_nofail(m->epoll_fd);
455 if (m->signal_watch.fd >= 0)
456 close_nointr_nofail(m->signal_watch.fd);
457 if (m->notify_watch.fd >= 0)
458 close_nointr_nofail(m->notify_watch.fd);
461 if (m->audit_fd >= 0)
462 audit_close(m->audit_fd);
465 free(m->notify_socket);
467 lookup_paths_free(&m->lookup_paths);
468 strv_free(m->environment);
470 strv_free(m->default_controllers);
472 hashmap_free(m->cgroup_bondings);
473 set_free_free(m->unit_path_cache);
478 int manager_enumerate(Manager *m) {
484 /* Let's ask every type to load all units from disk/kernel
485 * that it might know */
486 for (c = 0; c < _UNIT_TYPE_MAX; c++)
487 if (unit_vtable[c]->enumerate)
488 if ((q = unit_vtable[c]->enumerate(m)) < 0)
491 manager_dispatch_load_queue(m);
495 int manager_coldplug(Manager *m) {
503 /* Then, let's set up their initial state. */
504 HASHMAP_FOREACH_KEY(u, k, m->units, i) {
510 if ((q = unit_coldplug(u)) < 0)
517 static void manager_build_unit_path_cache(Manager *m) {
524 set_free_free(m->unit_path_cache);
526 if (!(m->unit_path_cache = set_new(string_hash_func, string_compare_func))) {
527 log_error("Failed to allocate unit path cache.");
531 /* This simply builds a list of files we know exist, so that
532 * we don't always have to go to disk */
534 STRV_FOREACH(i, m->lookup_paths.unit_path) {
537 if (!(d = opendir(*i))) {
538 log_error("Failed to open directory: %m");
542 while ((de = readdir(d))) {
545 if (ignore_file(de->d_name))
548 if (asprintf(&p, "%s/%s", streq(*i, "/") ? "" : *i, de->d_name) < 0) {
553 if ((r = set_put(m->unit_path_cache, p)) < 0) {
566 log_error("Failed to build unit path cache: %s", strerror(-r));
568 set_free_free(m->unit_path_cache);
569 m->unit_path_cache = NULL;
575 int manager_startup(Manager *m, FILE *serialization, FDSet *fds) {
580 manager_run_generators(m);
582 manager_build_unit_path_cache(m);
584 /* If we will deserialize make sure that during enumeration
585 * this is already known, so we increase the counter here
588 m->n_deserializing ++;
590 /* First, enumerate what we can from all config files */
591 r = manager_enumerate(m);
593 /* Second, deserialize if there is something to deserialize */
595 if ((q = manager_deserialize(m, serialization, fds)) < 0)
598 /* Third, fire things up! */
599 if ((q = manager_coldplug(m)) < 0)
603 assert(m->n_deserializing > 0);
604 m->n_deserializing --;
610 static void transaction_delete_job(Manager *m, Job *j, bool delete_dependencies) {
614 /* Deletes one job from the transaction */
616 manager_transaction_unlink_job(m, j, delete_dependencies);
622 static void transaction_delete_unit(Manager *m, Unit *u) {
625 /* Deletes all jobs associated with a certain unit from the
628 while ((j = hashmap_get(m->transaction_jobs, u)))
629 transaction_delete_job(m, j, true);
632 static void transaction_clean_dependencies(Manager *m) {
638 /* Drops all dependencies of all installed jobs */
640 HASHMAP_FOREACH(j, m->jobs, i) {
641 while (j->subject_list)
642 job_dependency_free(j->subject_list);
643 while (j->object_list)
644 job_dependency_free(j->object_list);
647 assert(!m->transaction_anchor);
650 static void transaction_abort(Manager *m) {
655 while ((j = hashmap_first(m->transaction_jobs)))
657 transaction_delete_job(m, j, true);
661 assert(hashmap_isempty(m->transaction_jobs));
663 transaction_clean_dependencies(m);
666 static void transaction_find_jobs_that_matter_to_anchor(Manager *m, Job *j, unsigned generation) {
671 /* A recursive sweep through the graph that marks all units
672 * that matter to the anchor job, i.e. are directly or
673 * indirectly a dependency of the anchor job via paths that
674 * are fully marked as mattering. */
679 l = m->transaction_anchor;
681 LIST_FOREACH(subject, l, l) {
683 /* This link does not matter */
687 /* This unit has already been marked */
688 if (l->object->generation == generation)
691 l->object->matters_to_anchor = true;
692 l->object->generation = generation;
694 transaction_find_jobs_that_matter_to_anchor(m, l->object, generation);
698 static void transaction_merge_and_delete_job(Manager *m, Job *j, Job *other, JobType t) {
699 JobDependency *l, *last;
703 assert(j->unit == other->unit);
704 assert(!j->installed);
706 /* Merges 'other' into 'j' and then deletes j. */
709 j->state = JOB_WAITING;
710 j->override = j->override || other->override;
712 j->matters_to_anchor = j->matters_to_anchor || other->matters_to_anchor;
714 /* Patch us in as new owner of the JobDependency objects */
716 LIST_FOREACH(subject, l, other->subject_list) {
717 assert(l->subject == other);
722 /* Merge both lists */
724 last->subject_next = j->subject_list;
726 j->subject_list->subject_prev = last;
727 j->subject_list = other->subject_list;
730 /* Patch us in as new owner of the JobDependency objects */
732 LIST_FOREACH(object, l, other->object_list) {
733 assert(l->object == other);
738 /* Merge both lists */
740 last->object_next = j->object_list;
742 j->object_list->object_prev = last;
743 j->object_list = other->object_list;
746 /* Kill the other job */
747 other->subject_list = NULL;
748 other->object_list = NULL;
749 transaction_delete_job(m, other, true);
751 static bool job_is_conflicted_by(Job *j) {
756 /* Returns true if this job is pulled in by a least one
757 * ConflictedBy dependency. */
759 LIST_FOREACH(object, l, j->object_list)
766 static int delete_one_unmergeable_job(Manager *m, Job *j) {
771 /* Tries to delete one item in the linked list
772 * j->transaction_next->transaction_next->... that conflicts
773 * whith another one, in an attempt to make an inconsistent
774 * transaction work. */
776 /* We rely here on the fact that if a merged with b does not
777 * merge with c, either a or b merge with c neither */
778 LIST_FOREACH(transaction, j, j)
779 LIST_FOREACH(transaction, k, j->transaction_next) {
782 /* Is this one mergeable? Then skip it */
783 if (job_type_is_mergeable(j->type, k->type))
786 /* Ok, we found two that conflict, let's see if we can
787 * drop one of them */
788 if (!j->matters_to_anchor && !k->matters_to_anchor) {
790 /* Both jobs don't matter, so let's
791 * find the one that is smarter to
792 * remove. Let's think positive and
793 * rather remove stops then starts --
794 * except if something is being
795 * stopped because it is conflicted by
796 * another unit in which case we
797 * rather remove the start. */
799 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)));
800 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)));
802 if (j->type == JOB_STOP) {
804 if (job_is_conflicted_by(j))
809 } else if (k->type == JOB_STOP) {
811 if (job_is_conflicted_by(k))
818 } else if (!j->matters_to_anchor)
820 else if (!k->matters_to_anchor)
825 /* Ok, we can drop one, so let's do so. */
826 log_debug("Fixing conflicting jobs by deleting job %s/%s", d->unit->meta.id, job_type_to_string(d->type));
827 transaction_delete_job(m, d, true);
834 static int transaction_merge_jobs(Manager *m, DBusError *e) {
841 /* First step, check whether any of the jobs for one specific
842 * task conflict. If so, try to drop one of them. */
843 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
848 LIST_FOREACH(transaction, k, j->transaction_next) {
849 if (job_type_merge(&t, k->type) >= 0)
852 /* OK, we could not merge all jobs for this
853 * action. Let's see if we can get rid of one
856 if ((r = delete_one_unmergeable_job(m, j)) >= 0)
857 /* Ok, we managed to drop one, now
858 * let's ask our callers to call us
859 * again after garbage collecting */
862 /* We couldn't merge anything. Failure */
863 dbus_set_error(e, BUS_ERROR_TRANSACTION_JOBS_CONFLICTING, "Transaction contains conflicting jobs '%s' and '%s' for %s. Probably contradicting requirement dependencies configured.",
864 job_type_to_string(t), job_type_to_string(k->type), k->unit->meta.id);
869 /* Second step, merge the jobs. */
870 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
874 /* Merge all transactions */
875 LIST_FOREACH(transaction, k, j->transaction_next)
876 assert_se(job_type_merge(&t, k->type) == 0);
878 /* If an active job is mergeable, merge it too */
879 if (j->unit->meta.job)
880 job_type_merge(&t, j->unit->meta.job->type); /* Might fail. Which is OK */
882 while ((k = j->transaction_next)) {
884 transaction_merge_and_delete_job(m, k, j, t);
887 transaction_merge_and_delete_job(m, j, k, t);
890 assert(!j->transaction_next);
891 assert(!j->transaction_prev);
897 static void transaction_drop_redundant(Manager *m) {
902 /* Goes through the transaction and removes all jobs that are
911 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
912 bool changes_something = false;
915 LIST_FOREACH(transaction, k, j) {
917 if (!job_is_anchor(k) &&
918 (j->installed || job_type_is_redundant(k->type, unit_active_state(k->unit))))
921 changes_something = true;
925 if (changes_something)
928 /* log_debug("Found redundant job %s/%s, dropping.", j->unit->meta.id, job_type_to_string(j->type)); */
929 transaction_delete_job(m, j, false);
937 static bool unit_matters_to_anchor(Unit *u, Job *j) {
939 assert(!j->transaction_prev);
941 /* Checks whether at least one of the jobs for this unit
942 * matters to the anchor. */
944 LIST_FOREACH(transaction, j, j)
945 if (j->matters_to_anchor)
951 static int transaction_verify_order_one(Manager *m, Job *j, Job *from, unsigned generation, DBusError *e) {
958 assert(!j->transaction_prev);
960 /* Does a recursive sweep through the ordering graph, looking
961 * for a cycle. If we find cycle we try to break it. */
963 /* Have we seen this before? */
964 if (j->generation == generation) {
967 /* If the marker is NULL we have been here already and
968 * decided the job was loop-free from here. Hence
969 * shortcut things and return right-away. */
973 /* So, the marker is not NULL and we already have been
974 * here. We have a cycle. Let's try to break it. We go
975 * backwards in our path and try to find a suitable
976 * job to remove. We use the marker to find our way
977 * back, since smart how we are we stored our way back
979 log_warning("Found ordering cycle on %s/%s", j->unit->meta.id, job_type_to_string(j->type));
982 for (k = from; k; k = ((k->generation == generation && k->marker != k) ? k->marker : NULL)) {
984 log_info("Walked on cycle path to %s/%s", k->unit->meta.id, job_type_to_string(k->type));
988 !unit_matters_to_anchor(k->unit, k)) {
989 /* Ok, we can drop this one, so let's
994 /* Check if this in fact was the beginning of
1002 log_warning("Breaking ordering cycle by deleting job %s/%s", delete->unit->meta.id, job_type_to_string(delete->type));
1003 transaction_delete_unit(m, delete->unit);
1007 log_error("Unable to break cycle");
1009 dbus_set_error(e, BUS_ERROR_TRANSACTION_ORDER_IS_CYCLIC, "Transaction order is cyclic. See system logs for details.");
1013 /* Make the marker point to where we come from, so that we can
1014 * find our way backwards if we want to break a cycle. We use
1015 * a special marker for the beginning: we point to
1017 j->marker = from ? from : j;
1018 j->generation = generation;
1020 /* We assume that the the dependencies are bidirectional, and
1021 * hence can ignore UNIT_AFTER */
1022 SET_FOREACH(u, j->unit->meta.dependencies[UNIT_BEFORE], i) {
1025 /* Is there a job for this unit? */
1026 if (!(o = hashmap_get(m->transaction_jobs, u)))
1028 /* Ok, there is no job for this in the
1029 * transaction, but maybe there is already one
1031 if (!(o = u->meta.job))
1034 if ((r = transaction_verify_order_one(m, o, j, generation, e)) < 0)
1038 /* Ok, let's backtrack, and remember that this entry is not on
1039 * our path anymore. */
1045 static int transaction_verify_order(Manager *m, unsigned *generation, DBusError *e) {
1054 /* Check if the ordering graph is cyclic. If it is, try to fix
1055 * that up by dropping one of the jobs. */
1057 g = (*generation)++;
1059 HASHMAP_FOREACH(j, m->transaction_jobs, i)
1060 if ((r = transaction_verify_order_one(m, j, NULL, g, e)) < 0)
1066 static void transaction_collect_garbage(Manager *m) {
1071 /* Drop jobs that are not required by any other job */
1079 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1080 if (j->object_list) {
1081 /* log_debug("Keeping job %s/%s because of %s/%s", */
1082 /* j->unit->meta.id, job_type_to_string(j->type), */
1083 /* j->object_list->subject ? j->object_list->subject->unit->meta.id : "root", */
1084 /* j->object_list->subject ? job_type_to_string(j->object_list->subject->type) : "root"); */
1088 /* log_debug("Garbage collecting job %s/%s", j->unit->meta.id, job_type_to_string(j->type)); */
1089 transaction_delete_job(m, j, true);
1097 static int transaction_is_destructive(Manager *m, DBusError *e) {
1103 /* Checks whether applying this transaction means that
1104 * existing jobs would be replaced */
1106 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1109 assert(!j->transaction_prev);
1110 assert(!j->transaction_next);
1112 if (j->unit->meta.job &&
1113 j->unit->meta.job != j &&
1114 !job_type_is_superset(j->type, j->unit->meta.job->type)) {
1116 dbus_set_error(e, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE, "Transaction is destructive.");
1124 static void transaction_minimize_impact(Manager *m) {
1128 /* Drops all unnecessary jobs that reverse already active jobs
1129 * or that stop a running service. */
1137 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1138 LIST_FOREACH(transaction, j, j) {
1139 bool stops_running_service, changes_existing_job;
1141 /* If it matters, we shouldn't drop it */
1142 if (j->matters_to_anchor)
1145 /* Would this stop a running service?
1146 * Would this change an existing job?
1147 * If so, let's drop this entry */
1149 stops_running_service =
1150 j->type == JOB_STOP && UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(j->unit));
1152 changes_existing_job =
1153 j->unit->meta.job &&
1154 job_type_is_conflicting(j->type, j->unit->meta.job->type);
1156 if (!stops_running_service && !changes_existing_job)
1159 if (stops_running_service)
1160 log_info("%s/%s would stop a running service.", j->unit->meta.id, job_type_to_string(j->type));
1162 if (changes_existing_job)
1163 log_info("%s/%s would change existing job.", j->unit->meta.id, job_type_to_string(j->type));
1165 /* Ok, let's get rid of this */
1166 log_info("Deleting %s/%s to minimize impact.", j->unit->meta.id, job_type_to_string(j->type));
1168 transaction_delete_job(m, j, true);
1180 static int transaction_apply(Manager *m) {
1185 /* Moves the transaction jobs to the set of active jobs */
1187 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1189 assert(!j->transaction_prev);
1190 assert(!j->transaction_next);
1195 if ((r = hashmap_put(m->jobs, UINT32_TO_PTR(j->id), j)) < 0)
1199 while ((j = hashmap_steal_first(m->transaction_jobs))) {
1201 /* log_debug("Skipping already installed job %s/%s as %u", j->unit->meta.id, job_type_to_string(j->type), (unsigned) j->id); */
1205 if (j->unit->meta.job)
1206 job_free(j->unit->meta.job);
1208 j->unit->meta.job = j;
1209 j->installed = true;
1210 m->n_installed_jobs ++;
1212 /* We're fully installed. Now let's free data we don't
1215 assert(!j->transaction_next);
1216 assert(!j->transaction_prev);
1218 job_add_to_run_queue(j);
1219 job_add_to_dbus_queue(j);
1222 log_debug("Installed new job %s/%s as %u", j->unit->meta.id, job_type_to_string(j->type), (unsigned) j->id);
1225 /* As last step, kill all remaining job dependencies. */
1226 transaction_clean_dependencies(m);
1232 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1236 hashmap_remove(m->jobs, UINT32_TO_PTR(j->id));
1242 static int transaction_activate(Manager *m, JobMode mode, DBusError *e) {
1244 unsigned generation = 1;
1248 /* This applies the changes recorded in transaction_jobs to
1249 * the actual list of jobs, if possible. */
1251 /* First step: figure out which jobs matter */
1252 transaction_find_jobs_that_matter_to_anchor(m, NULL, generation++);
1254 /* Second step: Try not to stop any running services if
1255 * we don't have to. Don't try to reverse running
1256 * jobs if we don't have to. */
1257 if (mode == JOB_FAIL)
1258 transaction_minimize_impact(m);
1260 /* Third step: Drop redundant jobs */
1261 transaction_drop_redundant(m);
1264 /* Fourth step: Let's remove unneeded jobs that might
1266 transaction_collect_garbage(m);
1268 /* Fifth step: verify order makes sense and correct
1269 * cycles if necessary and possible */
1270 if ((r = transaction_verify_order(m, &generation, e)) >= 0)
1274 log_warning("Requested transaction contains an unfixable cyclic ordering dependency: %s", bus_error(e, r));
1278 /* Let's see if the resulting transaction ordering
1279 * graph is still cyclic... */
1283 /* Sixth step: let's drop unmergeable entries if
1284 * necessary and possible, merge entries we can
1286 if ((r = transaction_merge_jobs(m, e)) >= 0)
1290 log_warning("Requested transaction contains unmergable jobs: %s", bus_error(e, r));
1294 /* Seventh step: an entry got dropped, let's garbage
1295 * collect its dependencies. */
1296 transaction_collect_garbage(m);
1298 /* Let's see if the resulting transaction still has
1299 * unmergeable entries ... */
1302 /* Eights step: Drop redundant jobs again, if the merging now allows us to drop more. */
1303 transaction_drop_redundant(m);
1305 /* Ninth step: check whether we can actually apply this */
1306 if (mode == JOB_FAIL)
1307 if ((r = transaction_is_destructive(m, e)) < 0) {
1308 log_notice("Requested transaction contradicts existing jobs: %s", bus_error(e, r));
1312 /* Tenth step: apply changes */
1313 if ((r = transaction_apply(m)) < 0) {
1314 log_warning("Failed to apply transaction: %s", strerror(-r));
1318 assert(hashmap_isempty(m->transaction_jobs));
1319 assert(!m->transaction_anchor);
1324 transaction_abort(m);
1328 static Job* transaction_add_one_job(Manager *m, JobType type, Unit *unit, bool override, bool *is_new) {
1334 /* Looks for an axisting prospective job and returns that. If
1335 * it doesn't exist it is created and added to the prospective
1338 f = hashmap_get(m->transaction_jobs, unit);
1340 LIST_FOREACH(transaction, j, f) {
1341 assert(j->unit == unit);
1343 if (j->type == type) {
1350 if (unit->meta.job && unit->meta.job->type == type)
1352 else if (!(j = job_new(m, type, unit)))
1357 j->matters_to_anchor = false;
1358 j->override = override;
1360 LIST_PREPEND(Job, transaction, f, j);
1362 if (hashmap_replace(m->transaction_jobs, unit, f) < 0) {
1370 /* log_debug("Added job %s/%s to transaction.", unit->meta.id, job_type_to_string(type)); */
1375 void manager_transaction_unlink_job(Manager *m, Job *j, bool delete_dependencies) {
1379 if (j->transaction_prev)
1380 j->transaction_prev->transaction_next = j->transaction_next;
1381 else if (j->transaction_next)
1382 hashmap_replace(m->transaction_jobs, j->unit, j->transaction_next);
1384 hashmap_remove_value(m->transaction_jobs, j->unit, j);
1386 if (j->transaction_next)
1387 j->transaction_next->transaction_prev = j->transaction_prev;
1389 j->transaction_prev = j->transaction_next = NULL;
1391 while (j->subject_list)
1392 job_dependency_free(j->subject_list);
1394 while (j->object_list) {
1395 Job *other = j->object_list->matters ? j->object_list->subject : NULL;
1397 job_dependency_free(j->object_list);
1399 if (other && delete_dependencies) {
1400 log_debug("Deleting job %s/%s as dependency of job %s/%s",
1401 other->unit->meta.id, job_type_to_string(other->type),
1402 j->unit->meta.id, job_type_to_string(j->type));
1403 transaction_delete_job(m, other, delete_dependencies);
1408 static int transaction_add_job_and_dependencies(
1425 assert(type < _JOB_TYPE_MAX);
1428 if (unit->meta.load_state != UNIT_LOADED &&
1429 unit->meta.load_state != UNIT_ERROR &&
1430 unit->meta.load_state != UNIT_MASKED) {
1431 dbus_set_error(e, BUS_ERROR_LOAD_FAILED, "Unit %s is not loaded properly.", unit->meta.id);
1435 if (type != JOB_STOP && unit->meta.load_state == UNIT_ERROR) {
1436 dbus_set_error(e, BUS_ERROR_LOAD_FAILED,
1437 "Unit %s failed to load: %s. "
1438 "See system logs and 'systemctl status' for details.",
1440 strerror(-unit->meta.load_error));
1444 if (type != JOB_STOP && unit->meta.load_state == UNIT_MASKED) {
1445 dbus_set_error(e, BUS_ERROR_MASKED, "Unit %s is masked.", unit->meta.id);
1449 if (!unit_job_is_applicable(unit, type)) {
1450 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);
1454 /* First add the job. */
1455 if (!(ret = transaction_add_one_job(m, type, unit, override, &is_new)))
1458 /* Then, add a link to the job. */
1459 if (!job_dependency_new(by, ret, matters, conflicts))
1465 /* If we are following some other unit, make sure we
1466 * add all dependencies of everybody following. */
1467 if (unit_following_set(ret->unit, &following) > 0) {
1468 SET_FOREACH(dep, following, i)
1469 if ((r = transaction_add_job_and_dependencies(m, type, dep, ret, false, override, false, e, NULL)) < 0) {
1470 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, bus_error(e, r));
1476 set_free(following);
1479 /* Finally, recursively add in all dependencies. */
1480 if (type == JOB_START || type == JOB_RELOAD_OR_START) {
1481 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES], i)
1482 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, true, override, false, e, NULL)) < 0) {
1490 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_BIND_TO], i)
1491 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, true, override, false, e, NULL)) < 0) {
1500 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES_OVERRIDABLE], i)
1501 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, !override, override, false, e, NULL)) < 0) {
1502 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, bus_error(e, r));
1508 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_WANTS], i)
1509 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, false, false, false, e, NULL)) < 0) {
1510 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, bus_error(e, r));
1516 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE], i)
1517 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, true, override, false, e, NULL)) < 0) {
1526 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE_OVERRIDABLE], i)
1527 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, !override, override, false, e, NULL)) < 0) {
1528 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, bus_error(e, r));
1534 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_CONFLICTS], i)
1535 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, dep, ret, true, override, true, e, NULL)) < 0) {
1544 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_CONFLICTED_BY], i)
1545 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, dep, ret, false, override, false, e, NULL)) < 0) {
1546 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, bus_error(e, r));
1552 } else if (type == JOB_STOP || type == JOB_RESTART || type == JOB_TRY_RESTART) {
1554 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRED_BY], i)
1555 if ((r = transaction_add_job_and_dependencies(m, type, dep, ret, true, override, false, e, NULL)) < 0) {
1564 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_BOUND_BY], i)
1565 if ((r = transaction_add_job_and_dependencies(m, type, dep, ret, true, override, false, e, NULL)) < 0) {
1575 /* JOB_VERIFY_STARTED, JOB_RELOAD require no dependency handling */
1587 static int transaction_add_isolate_jobs(Manager *m) {
1595 HASHMAP_FOREACH_KEY(u, k, m->units, i) {
1597 /* ignore aliases */
1598 if (u->meta.id != k)
1601 if (UNIT_VTABLE(u)->no_isolate)
1604 /* No need to stop inactive jobs */
1605 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(u)) && !u->meta.job)
1608 /* Is there already something listed for this? */
1609 if (hashmap_get(m->transaction_jobs, u))
1612 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, u, NULL, true, false, false, NULL, NULL)) < 0)
1613 log_warning("Cannot add isolate job for unit %s, ignoring: %s", u->meta.id, strerror(-r));
1619 int manager_add_job(Manager *m, JobType type, Unit *unit, JobMode mode, bool override, DBusError *e, Job **_ret) {
1624 assert(type < _JOB_TYPE_MAX);
1626 assert(mode < _JOB_MODE_MAX);
1628 if (mode == JOB_ISOLATE && type != JOB_START) {
1629 dbus_set_error(e, BUS_ERROR_INVALID_JOB_MODE, "Isolate is only valid for start.");
1633 if (mode == JOB_ISOLATE && !unit->meta.allow_isolate) {
1634 dbus_set_error(e, BUS_ERROR_NO_ISOLATION, "Operation refused, unit may not be isolated.");
1638 log_debug("Trying to enqueue job %s/%s/%s", unit->meta.id, job_type_to_string(type), job_mode_to_string(mode));
1640 if ((r = transaction_add_job_and_dependencies(m, type, unit, NULL, true, override, false, e, &ret)) < 0) {
1641 transaction_abort(m);
1645 if (mode == JOB_ISOLATE)
1646 if ((r = transaction_add_isolate_jobs(m)) < 0) {
1647 transaction_abort(m);
1651 if ((r = transaction_activate(m, mode, e)) < 0)
1654 log_debug("Enqueued job %s/%s as %u", unit->meta.id, job_type_to_string(type), (unsigned) ret->id);
1662 int manager_add_job_by_name(Manager *m, JobType type, const char *name, JobMode mode, bool override, DBusError *e, Job **_ret) {
1667 assert(type < _JOB_TYPE_MAX);
1669 assert(mode < _JOB_MODE_MAX);
1671 if ((r = manager_load_unit(m, name, NULL, NULL, &unit)) < 0)
1674 return manager_add_job(m, type, unit, mode, override, e, _ret);
1677 Job *manager_get_job(Manager *m, uint32_t id) {
1680 return hashmap_get(m->jobs, UINT32_TO_PTR(id));
1683 Unit *manager_get_unit(Manager *m, const char *name) {
1687 return hashmap_get(m->units, name);
1690 unsigned manager_dispatch_load_queue(Manager *m) {
1696 /* Make sure we are not run recursively */
1697 if (m->dispatching_load_queue)
1700 m->dispatching_load_queue = true;
1702 /* Dispatches the load queue. Takes a unit from the queue and
1703 * tries to load its data until the queue is empty */
1705 while ((meta = m->load_queue)) {
1706 assert(meta->in_load_queue);
1708 unit_load((Unit*) meta);
1712 m->dispatching_load_queue = false;
1716 int manager_load_unit_prepare(Manager *m, const char *name, const char *path, DBusError *e, Unit **_ret) {
1721 assert(name || path);
1723 /* This will prepare the unit for loading, but not actually
1724 * load anything from disk. */
1726 if (path && !is_path(path)) {
1727 dbus_set_error(e, BUS_ERROR_INVALID_PATH, "Path %s is not absolute.", path);
1732 name = file_name_from_path(path);
1734 if (!unit_name_is_valid(name, false)) {
1735 dbus_set_error(e, BUS_ERROR_INVALID_NAME, "Unit name %s is not valid.", name);
1739 if ((ret = manager_get_unit(m, name))) {
1744 if (!(ret = unit_new(m)))
1748 if (!(ret->meta.fragment_path = strdup(path))) {
1753 if ((r = unit_add_name(ret, name)) < 0) {
1758 unit_add_to_load_queue(ret);
1759 unit_add_to_dbus_queue(ret);
1760 unit_add_to_gc_queue(ret);
1768 int manager_load_unit(Manager *m, const char *name, const char *path, DBusError *e, Unit **_ret) {
1773 /* This will load the service information files, but not actually
1774 * start any services or anything. */
1776 if ((r = manager_load_unit_prepare(m, name, path, e, _ret)) != 0)
1779 manager_dispatch_load_queue(m);
1782 *_ret = unit_follow_merge(*_ret);
1787 void manager_dump_jobs(Manager *s, FILE *f, const char *prefix) {
1794 HASHMAP_FOREACH(j, s->jobs, i)
1795 job_dump(j, f, prefix);
1798 void manager_dump_units(Manager *s, FILE *f, const char *prefix) {
1806 HASHMAP_FOREACH_KEY(u, t, s->units, i)
1807 if (u->meta.id == t)
1808 unit_dump(u, f, prefix);
1811 void manager_clear_jobs(Manager *m) {
1816 transaction_abort(m);
1818 while ((j = hashmap_first(m->jobs)))
1822 unsigned manager_dispatch_run_queue(Manager *m) {
1826 if (m->dispatching_run_queue)
1829 m->dispatching_run_queue = true;
1831 while ((j = m->run_queue)) {
1832 assert(j->installed);
1833 assert(j->in_run_queue);
1835 job_run_and_invalidate(j);
1839 m->dispatching_run_queue = false;
1843 unsigned manager_dispatch_dbus_queue(Manager *m) {
1850 if (m->dispatching_dbus_queue)
1853 m->dispatching_dbus_queue = true;
1855 while ((meta = m->dbus_unit_queue)) {
1856 assert(meta->in_dbus_queue);
1858 bus_unit_send_change_signal((Unit*) meta);
1862 while ((j = m->dbus_job_queue)) {
1863 assert(j->in_dbus_queue);
1865 bus_job_send_change_signal(j);
1869 m->dispatching_dbus_queue = false;
1873 static int manager_process_notify_fd(Manager *m) {
1880 struct msghdr msghdr;
1882 struct ucred *ucred;
1884 struct cmsghdr cmsghdr;
1885 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
1891 iovec.iov_base = buf;
1892 iovec.iov_len = sizeof(buf)-1;
1896 msghdr.msg_iov = &iovec;
1897 msghdr.msg_iovlen = 1;
1898 msghdr.msg_control = &control;
1899 msghdr.msg_controllen = sizeof(control);
1901 if ((n = recvmsg(m->notify_watch.fd, &msghdr, MSG_DONTWAIT)) <= 0) {
1905 if (errno == EAGAIN || errno == EINTR)
1911 if (msghdr.msg_controllen < CMSG_LEN(sizeof(struct ucred)) ||
1912 control.cmsghdr.cmsg_level != SOL_SOCKET ||
1913 control.cmsghdr.cmsg_type != SCM_CREDENTIALS ||
1914 control.cmsghdr.cmsg_len != CMSG_LEN(sizeof(struct ucred))) {
1915 log_warning("Received notify message without credentials. Ignoring.");
1919 ucred = (struct ucred*) CMSG_DATA(&control.cmsghdr);
1921 if (!(u = hashmap_get(m->watch_pids, LONG_TO_PTR(ucred->pid))))
1922 if (!(u = cgroup_unit_by_pid(m, ucred->pid))) {
1923 log_warning("Cannot find unit for notify message of PID %lu.", (unsigned long) ucred->pid);
1927 assert((size_t) n < sizeof(buf));
1929 if (!(tags = strv_split(buf, "\n\r")))
1932 log_debug("Got notification message for unit %s", u->meta.id);
1934 if (UNIT_VTABLE(u)->notify_message)
1935 UNIT_VTABLE(u)->notify_message(u, ucred->pid, tags);
1943 static int manager_dispatch_sigchld(Manager *m) {
1953 /* First we call waitd() for a PID and do not reap the
1954 * zombie. That way we can still access /proc/$PID for
1955 * it while it is a zombie. */
1956 if (waitid(P_ALL, 0, &si, WEXITED|WNOHANG|WNOWAIT) < 0) {
1958 if (errno == ECHILD)
1970 if (si.si_code == CLD_EXITED || si.si_code == CLD_KILLED || si.si_code == CLD_DUMPED) {
1973 get_process_name(si.si_pid, &name);
1974 log_debug("Got SIGCHLD for process %lu (%s)", (unsigned long) si.si_pid, strna(name));
1978 /* Let's flush any message the dying child might still
1979 * have queued for us. This ensures that the process
1980 * still exists in /proc so that we can figure out
1981 * which cgroup and hence unit it belongs to. */
1982 if ((r = manager_process_notify_fd(m)) < 0)
1985 /* And now figure out the unit this belongs to */
1986 if (!(u = hashmap_get(m->watch_pids, LONG_TO_PTR(si.si_pid))))
1987 u = cgroup_unit_by_pid(m, si.si_pid);
1989 /* And now, we actually reap the zombie. */
1990 if (waitid(P_PID, si.si_pid, &si, WEXITED) < 0) {
1997 if (si.si_code != CLD_EXITED && si.si_code != CLD_KILLED && si.si_code != CLD_DUMPED)
2000 log_debug("Child %lu died (code=%s, status=%i/%s)",
2001 (long unsigned) si.si_pid,
2002 sigchld_code_to_string(si.si_code),
2004 strna(si.si_code == CLD_EXITED
2005 ? exit_status_to_string(si.si_status, EXIT_STATUS_FULL)
2006 : signal_to_string(si.si_status)));
2011 log_debug("Child %lu belongs to %s", (long unsigned) si.si_pid, u->meta.id);
2013 hashmap_remove(m->watch_pids, LONG_TO_PTR(si.si_pid));
2014 UNIT_VTABLE(u)->sigchld_event(u, si.si_pid, si.si_code, si.si_status);
2020 static int manager_start_target(Manager *m, const char *name, JobMode mode) {
2024 dbus_error_init(&error);
2026 log_debug("Activating special unit %s", name);
2028 if ((r = manager_add_job_by_name(m, JOB_START, name, mode, true, &error, NULL)) < 0)
2029 log_error("Failed to enqueue %s job: %s", name, bus_error(&error, r));
2031 dbus_error_free(&error);
2036 static int manager_process_signal_fd(Manager *m) {
2038 struct signalfd_siginfo sfsi;
2039 bool sigchld = false;
2044 if ((n = read(m->signal_watch.fd, &sfsi, sizeof(sfsi))) != sizeof(sfsi)) {
2049 if (errno == EINTR || errno == EAGAIN)
2055 log_debug("Received SIG%s", strna(signal_to_string(sfsi.ssi_signo)));
2057 switch (sfsi.ssi_signo) {
2064 if (m->running_as == MANAGER_SYSTEM) {
2065 /* This is for compatibility with the
2066 * original sysvinit */
2067 m->exit_code = MANAGER_REEXECUTE;
2074 if (m->running_as == MANAGER_SYSTEM) {
2075 manager_start_target(m, SPECIAL_CTRL_ALT_DEL_TARGET, JOB_REPLACE);
2079 /* Run the exit target if there is one, if not, just exit. */
2080 if (manager_start_target(m, SPECIAL_EXIT_TARGET, JOB_REPLACE) < 0) {
2081 m->exit_code = MANAGER_EXIT;
2088 if (m->running_as == MANAGER_SYSTEM)
2089 manager_start_target(m, SPECIAL_KBREQUEST_TARGET, JOB_REPLACE);
2091 /* This is a nop on non-init */
2095 if (m->running_as == MANAGER_SYSTEM)
2096 manager_start_target(m, SPECIAL_SIGPWR_TARGET, JOB_REPLACE);
2098 /* This is a nop on non-init */
2104 u = manager_get_unit(m, SPECIAL_DBUS_SERVICE);
2106 if (!u || UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u))) {
2107 log_info("Trying to reconnect to bus...");
2111 if (!u || !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u))) {
2112 log_info("Loading D-Bus service...");
2113 manager_start_target(m, SPECIAL_DBUS_SERVICE, JOB_REPLACE);
2124 if (!(f = open_memstream(&dump, &size))) {
2125 log_warning("Failed to allocate memory stream.");
2129 manager_dump_units(m, f, "\t");
2130 manager_dump_jobs(m, f, "\t");
2135 log_warning("Failed to write status stream");
2140 log_dump(LOG_INFO, dump);
2147 m->exit_code = MANAGER_RELOAD;
2151 /* Starting SIGRTMIN+0 */
2152 static const char * const target_table[] = {
2153 [0] = SPECIAL_DEFAULT_TARGET,
2154 [1] = SPECIAL_RESCUE_TARGET,
2155 [2] = SPECIAL_EMERGENCY_TARGET,
2156 [3] = SPECIAL_HALT_TARGET,
2157 [4] = SPECIAL_POWEROFF_TARGET,
2158 [5] = SPECIAL_REBOOT_TARGET,
2159 [6] = SPECIAL_KEXEC_TARGET
2162 /* Starting SIGRTMIN+13, so that target halt and system halt are 10 apart */
2163 static const ManagerExitCode code_table[] = {
2165 [1] = MANAGER_POWEROFF,
2166 [2] = MANAGER_REBOOT,
2170 if ((int) sfsi.ssi_signo >= SIGRTMIN+0 &&
2171 (int) sfsi.ssi_signo < SIGRTMIN+(int) ELEMENTSOF(target_table)) {
2172 manager_start_target(m, target_table[sfsi.ssi_signo - SIGRTMIN],
2173 (sfsi.ssi_signo == 1 || sfsi.ssi_signo == 2) ? JOB_ISOLATE : JOB_REPLACE);
2177 if ((int) sfsi.ssi_signo >= SIGRTMIN+13 &&
2178 (int) sfsi.ssi_signo < SIGRTMIN+13+(int) ELEMENTSOF(code_table)) {
2179 m->exit_code = code_table[sfsi.ssi_signo - SIGRTMIN - 13];
2183 switch (sfsi.ssi_signo - SIGRTMIN) {
2186 log_debug("Enabling showing of status.");
2187 m->show_status = true;
2191 log_debug("Disabling showing of status.");
2192 m->show_status = false;
2196 log_warning("Got unhandled signal <%s>.", strna(signal_to_string(sfsi.ssi_signo)));
2203 return manager_dispatch_sigchld(m);
2208 static int process_event(Manager *m, struct epoll_event *ev) {
2215 assert(w = ev->data.ptr);
2217 if (w->type == WATCH_INVALID)
2224 /* An incoming signal? */
2225 if (ev->events != EPOLLIN)
2228 if ((r = manager_process_signal_fd(m)) < 0)
2235 /* An incoming daemon notification event? */
2236 if (ev->events != EPOLLIN)
2239 if ((r = manager_process_notify_fd(m)) < 0)
2246 /* Some fd event, to be dispatched to the units */
2247 UNIT_VTABLE(w->data.unit)->fd_event(w->data.unit, w->fd, ev->events, w);
2250 case WATCH_UNIT_TIMER:
2251 case WATCH_JOB_TIMER: {
2255 /* Some timer event, to be dispatched to the units */
2256 if ((k = read(w->fd, &v, sizeof(v))) != sizeof(v)) {
2258 if (k < 0 && (errno == EINTR || errno == EAGAIN))
2261 return k < 0 ? -errno : -EIO;
2264 if (w->type == WATCH_UNIT_TIMER)
2265 UNIT_VTABLE(w->data.unit)->timer_event(w->data.unit, v, w);
2267 job_timer_event(w->data.job, v, w);
2272 /* Some mount table change, intended for the mount subsystem */
2273 mount_fd_event(m, ev->events);
2277 /* Some swap table change, intended for the swap subsystem */
2278 swap_fd_event(m, ev->events);
2282 /* Some notification from udev, intended for the device subsystem */
2283 device_fd_event(m, ev->events);
2286 case WATCH_DBUS_WATCH:
2287 bus_watch_event(m, w, ev->events);
2290 case WATCH_DBUS_TIMEOUT:
2291 bus_timeout_event(m, w, ev->events);
2295 log_error("event type=%i", w->type);
2296 assert_not_reached("Unknown epoll event type.");
2302 int manager_loop(Manager *m) {
2305 RATELIMIT_DEFINE(rl, 1*USEC_PER_SEC, 1000);
2308 m->exit_code = MANAGER_RUNNING;
2310 /* Release the path cache */
2311 set_free_free(m->unit_path_cache);
2312 m->unit_path_cache = NULL;
2314 manager_check_finished(m);
2316 /* There might still be some zombies hanging around from
2317 * before we were exec()'ed. Leat's reap them */
2318 if ((r = manager_dispatch_sigchld(m)) < 0)
2321 while (m->exit_code == MANAGER_RUNNING) {
2322 struct epoll_event event;
2325 if (!ratelimit_test(&rl)) {
2326 /* Yay, something is going seriously wrong, pause a little */
2327 log_warning("Looping too fast. Throttling execution a little.");
2331 if (manager_dispatch_load_queue(m) > 0)
2334 if (manager_dispatch_run_queue(m) > 0)
2337 if (bus_dispatch(m) > 0)
2340 if (manager_dispatch_cleanup_queue(m) > 0)
2343 if (manager_dispatch_gc_queue(m) > 0)
2346 if (manager_dispatch_dbus_queue(m) > 0)
2349 if (swap_dispatch_reload(m) > 0)
2352 if ((n = epoll_wait(m->epoll_fd, &event, 1, -1)) < 0) {
2362 if ((r = process_event(m, &event)) < 0)
2366 return m->exit_code;
2369 int manager_get_unit_from_dbus_path(Manager *m, const char *s, Unit **_u) {
2377 if (!startswith(s, "/org/freedesktop/systemd1/unit/"))
2380 if (!(n = bus_path_unescape(s+31)))
2383 u = manager_get_unit(m, n);
2394 int manager_get_job_from_dbus_path(Manager *m, const char *s, Job **_j) {
2403 if (!startswith(s, "/org/freedesktop/systemd1/job/"))
2406 if ((r = safe_atou(s + 30, &id)) < 0)
2409 if (!(j = manager_get_job(m, id)))
2417 void manager_send_unit_audit(Manager *m, Unit *u, int type, bool success) {
2422 if (m->audit_fd < 0)
2425 /* Don't generate audit events if the service was already
2426 * started and we're just deserializing */
2427 if (m->n_deserializing > 0)
2430 if (!(p = unit_name_to_prefix_and_instance(u->meta.id))) {
2431 log_error("Failed to allocate unit name for audit message: %s", strerror(ENOMEM));
2435 if (audit_log_user_comm_message(m->audit_fd, type, "", p, NULL, NULL, NULL, success) < 0)
2436 log_error("Failed to send audit message: %m");
2443 void manager_send_unit_plymouth(Manager *m, Unit *u) {
2445 union sockaddr_union sa;
2447 char *message = NULL;
2449 /* Don't generate plymouth events if the service was already
2450 * started and we're just deserializing */
2451 if (m->n_deserializing > 0)
2454 if (m->running_as != MANAGER_SYSTEM)
2457 if (u->meta.type != UNIT_SERVICE &&
2458 u->meta.type != UNIT_MOUNT &&
2459 u->meta.type != UNIT_SWAP)
2462 /* We set SOCK_NONBLOCK here so that we rather drop the
2463 * message then wait for plymouth */
2464 if ((fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0)) < 0) {
2465 log_error("socket() failed: %m");
2470 sa.sa.sa_family = AF_UNIX;
2471 strncpy(sa.un.sun_path+1, "/org/freedesktop/plymouthd", sizeof(sa.un.sun_path)-1);
2472 if (connect(fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + 1 + strlen(sa.un.sun_path+1)) < 0) {
2474 if (errno != EPIPE &&
2477 errno != ECONNREFUSED &&
2478 errno != ECONNRESET &&
2479 errno != ECONNABORTED)
2480 log_error("connect() failed: %m");
2485 if (asprintf(&message, "U\002%c%s%n", (int) (strlen(u->meta.id) + 1), u->meta.id, &n) < 0) {
2486 log_error("Out of memory");
2491 if (write(fd, message, n + 1) != n + 1) {
2493 if (errno != EPIPE &&
2496 errno != ECONNREFUSED &&
2497 errno != ECONNRESET &&
2498 errno != ECONNABORTED)
2499 log_error("Failed to write Plymouth message: %m");
2506 close_nointr_nofail(fd);
2511 void manager_dispatch_bus_name_owner_changed(
2514 const char* old_owner,
2515 const char *new_owner) {
2522 if (!(u = hashmap_get(m->watch_bus, name)))
2525 UNIT_VTABLE(u)->bus_name_owner_change(u, name, old_owner, new_owner);
2528 void manager_dispatch_bus_query_pid_done(
2539 if (!(u = hashmap_get(m->watch_bus, name)))
2542 UNIT_VTABLE(u)->bus_query_pid_done(u, name, pid);
2545 int manager_open_serialization(Manager *m, FILE **_f) {
2553 if (m->running_as == MANAGER_SYSTEM) {
2554 mkdir_p("/dev/.systemd", 0755);
2556 if (asprintf(&path, "/dev/.systemd/dump-%lu-XXXXXX", (unsigned long) getpid()) < 0)
2559 if (asprintf(&path, "/tmp/systemd-dump-%lu-XXXXXX", (unsigned long) getpid()) < 0)
2563 saved_umask = umask(0077);
2564 fd = mkostemp(path, O_RDWR|O_CLOEXEC);
2574 log_debug("Serializing state to %s", path);
2577 if (!(f = fdopen(fd, "w+")) < 0)
2585 int manager_serialize(Manager *m, FILE *f, FDSet *fds) {
2595 dual_timestamp_serialize(f, "initrd-timestamp", &m->initrd_timestamp);
2596 dual_timestamp_serialize(f, "startup-timestamp", &m->startup_timestamp);
2597 dual_timestamp_serialize(f, "finish-timestamp", &m->finish_timestamp);
2601 HASHMAP_FOREACH_KEY(u, t, m->units, i) {
2602 if (u->meta.id != t)
2605 if (!unit_can_serialize(u))
2609 fputs(u->meta.id, f);
2612 if ((r = unit_serialize(u, f, fds)) < 0)
2622 int manager_deserialize(Manager *m, FILE *f, FDSet *fds) {
2628 log_debug("Deserializing state...");
2630 m->n_deserializing ++;
2633 char line[1024], *l;
2635 if (!fgets(line, sizeof(line), f)) {
2650 if (startswith(l, "initrd-timestamp="))
2651 dual_timestamp_deserialize(l+17, &m->initrd_timestamp);
2652 else if (startswith(l, "startup-timestamp="))
2653 dual_timestamp_deserialize(l+18, &m->startup_timestamp);
2654 else if (startswith(l, "finish-timestamp="))
2655 dual_timestamp_deserialize(l+17, &m->finish_timestamp);
2657 log_debug("Unknown serialization item '%s'", l);
2662 char name[UNIT_NAME_MAX+2];
2665 if (!fgets(name, sizeof(name), f)) {
2676 if ((r = manager_load_unit(m, strstrip(name), NULL, NULL, &u)) < 0)
2679 if ((r = unit_deserialize(u, f, fds)) < 0)
2689 assert(m->n_deserializing > 0);
2690 m->n_deserializing --;
2695 int manager_reload(Manager *m) {
2702 if ((r = manager_open_serialization(m, &f)) < 0)
2705 if (!(fds = fdset_new())) {
2710 if ((r = manager_serialize(m, f, fds)) < 0)
2713 if (fseeko(f, 0, SEEK_SET) < 0) {
2718 /* From here on there is no way back. */
2719 manager_clear_jobs_and_units(m);
2720 manager_undo_generators(m);
2722 /* Find new unit paths */
2723 lookup_paths_free(&m->lookup_paths);
2724 if ((q = lookup_paths_init(&m->lookup_paths, m->running_as)) < 0)
2727 manager_run_generators(m);
2729 manager_build_unit_path_cache(m);
2731 m->n_deserializing ++;
2733 /* First, enumerate what we can from all config files */
2734 if ((q = manager_enumerate(m)) < 0)
2737 /* Second, deserialize our stored data */
2738 if ((q = manager_deserialize(m, f, fds)) < 0)
2744 /* Third, fire things up! */
2745 if ((q = manager_coldplug(m)) < 0)
2748 assert(m->n_deserializing > 0);
2749 m->n_deserializing ++;
2761 bool manager_is_booting_or_shutting_down(Manager *m) {
2766 /* Is the initial job still around? */
2767 if (manager_get_job(m, 1))
2770 /* Is there a job for the shutdown target? */
2771 if (((u = manager_get_unit(m, SPECIAL_SHUTDOWN_TARGET))))
2772 return !!u->meta.job;
2777 void manager_reset_failed(Manager *m) {
2783 HASHMAP_FOREACH(u, m->units, i)
2784 unit_reset_failed(u);
2787 bool manager_unit_pending_inactive(Manager *m, const char *name) {
2793 /* Returns true if the unit is inactive or going down */
2794 if (!(u = manager_get_unit(m, name)))
2797 return unit_pending_inactive(u);
2800 void manager_check_finished(Manager *m) {
2801 char userspace[FORMAT_TIMESPAN_MAX], initrd[FORMAT_TIMESPAN_MAX], kernel[FORMAT_TIMESPAN_MAX], sum[FORMAT_TIMESPAN_MAX];
2805 if (dual_timestamp_is_set(&m->finish_timestamp))
2808 if (hashmap_size(m->jobs) > 0)
2811 dual_timestamp_get(&m->finish_timestamp);
2813 if (m->running_as == MANAGER_SYSTEM) {
2814 if (dual_timestamp_is_set(&m->initrd_timestamp)) {
2815 log_info("Startup finished in %s (kernel) + %s (initrd) + %s (userspace) = %s.",
2816 format_timespan(kernel, sizeof(kernel),
2817 m->initrd_timestamp.monotonic),
2818 format_timespan(initrd, sizeof(initrd),
2819 m->startup_timestamp.monotonic - m->initrd_timestamp.monotonic),
2820 format_timespan(userspace, sizeof(userspace),
2821 m->finish_timestamp.monotonic - m->startup_timestamp.monotonic),
2822 format_timespan(sum, sizeof(sum),
2823 m->finish_timestamp.monotonic));
2825 log_info("Startup finished in %s (kernel) + %s (userspace) = %s.",
2826 format_timespan(kernel, sizeof(kernel),
2827 m->startup_timestamp.monotonic),
2828 format_timespan(userspace, sizeof(userspace),
2829 m->finish_timestamp.monotonic - m->startup_timestamp.monotonic),
2830 format_timespan(sum, sizeof(sum),
2831 m->finish_timestamp.monotonic));
2833 log_debug("Startup finished in %s.",
2834 format_timespan(userspace, sizeof(userspace),
2835 m->finish_timestamp.monotonic - m->startup_timestamp.monotonic));
2839 void manager_run_generators(Manager *m) {
2841 const char *generator_path;
2842 const char *argv[3];
2846 generator_path = m->running_as == MANAGER_SYSTEM ? SYSTEM_GENERATOR_PATH : USER_GENERATOR_PATH;
2847 if (!(d = opendir(generator_path))) {
2849 if (errno == ENOENT)
2852 log_error("Failed to enumerate generator directory: %m");
2856 if (!m->generator_unit_path) {
2858 char system_path[] = "/dev/.systemd/generator-XXXXXX",
2859 user_path[] = "/tmp/systemd-generator-XXXXXX";
2861 if (!(p = mkdtemp(m->running_as == MANAGER_SYSTEM ? system_path : user_path))) {
2862 log_error("Failed to generate generator directory: %m");
2866 if (!(m->generator_unit_path = strdup(p))) {
2867 log_error("Failed to allocate generator unit path.");
2872 argv[0] = NULL; /* Leave this empty, execute_directory() will fill something in */
2873 argv[1] = m->generator_unit_path;
2876 execute_directory(generator_path, d, (char**) argv);
2878 if (rmdir(m->generator_unit_path) >= 0) {
2879 /* Uh? we were able to remove this dir? I guess that
2880 * means the directory was empty, hence let's shortcut
2883 free(m->generator_unit_path);
2884 m->generator_unit_path = NULL;
2888 if (!strv_find(m->lookup_paths.unit_path, m->generator_unit_path)) {
2891 if (!(l = strv_append(m->lookup_paths.unit_path, m->generator_unit_path))) {
2892 log_error("Failed to add generator directory to unit search path: %m");
2896 strv_free(m->lookup_paths.unit_path);
2897 m->lookup_paths.unit_path = l;
2899 log_debug("Added generator unit path %s to search path.", m->generator_unit_path);
2907 void manager_undo_generators(Manager *m) {
2910 if (!m->generator_unit_path)
2913 strv_remove(m->lookup_paths.unit_path, m->generator_unit_path);
2914 rm_rf(m->generator_unit_path, false, true);
2916 free(m->generator_unit_path);
2917 m->generator_unit_path = NULL;
2920 int manager_set_default_controllers(Manager *m, char **controllers) {
2925 if (!(l = strv_copy(controllers)))
2928 strv_free(m->default_controllers);
2929 m->default_controllers = l;
2934 static const char* const manager_running_as_table[_MANAGER_RUNNING_AS_MAX] = {
2935 [MANAGER_SYSTEM] = "system",
2936 [MANAGER_USER] = "user"
2939 DEFINE_STRING_TABLE_LOOKUP(manager_running_as, ManagerRunningAs);