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->default_controllers = strv_new("cpu", NULL)))
228 if (!(m->units = hashmap_new(string_hash_func, string_compare_func)))
231 if (!(m->jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
234 if (!(m->transaction_jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
237 if (!(m->watch_pids = hashmap_new(trivial_hash_func, trivial_compare_func)))
240 if (!(m->cgroup_bondings = hashmap_new(string_hash_func, string_compare_func)))
243 if (!(m->watch_bus = hashmap_new(string_hash_func, string_compare_func)))
246 if ((m->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0)
249 if ((r = lookup_paths_init(&m->lookup_paths, m->running_as)) < 0)
252 if ((r = manager_setup_signals(m)) < 0)
255 if ((r = manager_setup_cgroup(m)) < 0)
258 if ((r = manager_setup_notify(m)) < 0)
261 /* Try to connect to the busses, if possible. */
262 if ((r = bus_init(m)) < 0)
266 if ((m->audit_fd = audit_open()) < 0)
267 log_error("Failed to connect to audit log: %m");
278 static unsigned manager_dispatch_cleanup_queue(Manager *m) {
284 while ((meta = m->cleanup_queue)) {
285 assert(meta->in_cleanup_queue);
287 unit_free((Unit*) meta);
295 GC_OFFSET_IN_PATH, /* This one is on the path we were travelling */
296 GC_OFFSET_UNSURE, /* No clue */
297 GC_OFFSET_GOOD, /* We still need this unit */
298 GC_OFFSET_BAD, /* We don't need this unit anymore */
302 static void unit_gc_sweep(Unit *u, unsigned gc_marker) {
309 if (u->meta.gc_marker == gc_marker + GC_OFFSET_GOOD ||
310 u->meta.gc_marker == gc_marker + GC_OFFSET_BAD ||
311 u->meta.gc_marker == gc_marker + GC_OFFSET_IN_PATH)
314 if (u->meta.in_cleanup_queue)
317 if (unit_check_gc(u))
320 u->meta.gc_marker = gc_marker + GC_OFFSET_IN_PATH;
324 SET_FOREACH(other, u->meta.dependencies[UNIT_REFERENCED_BY], i) {
325 unit_gc_sweep(other, gc_marker);
327 if (other->meta.gc_marker == gc_marker + GC_OFFSET_GOOD)
330 if (other->meta.gc_marker != gc_marker + GC_OFFSET_BAD)
337 /* We were unable to find anything out about this entry, so
338 * let's investigate it later */
339 u->meta.gc_marker = gc_marker + GC_OFFSET_UNSURE;
340 unit_add_to_gc_queue(u);
344 /* We definitely know that this one is not useful anymore, so
345 * let's mark it for deletion */
346 u->meta.gc_marker = gc_marker + GC_OFFSET_BAD;
347 unit_add_to_cleanup_queue(u);
351 u->meta.gc_marker = gc_marker + GC_OFFSET_GOOD;
354 static unsigned manager_dispatch_gc_queue(Manager *m) {
361 if ((m->n_in_gc_queue < GC_QUEUE_ENTRIES_MAX) &&
362 (m->gc_queue_timestamp <= 0 ||
363 (m->gc_queue_timestamp + GC_QUEUE_USEC_MAX) > now(CLOCK_MONOTONIC)))
366 log_debug("Running GC...");
368 m->gc_marker += _GC_OFFSET_MAX;
369 if (m->gc_marker + _GC_OFFSET_MAX <= _GC_OFFSET_MAX)
372 gc_marker = m->gc_marker;
374 while ((meta = m->gc_queue)) {
375 assert(meta->in_gc_queue);
377 unit_gc_sweep((Unit*) meta, gc_marker);
379 LIST_REMOVE(Meta, gc_queue, m->gc_queue, meta);
380 meta->in_gc_queue = false;
384 if (meta->gc_marker == gc_marker + GC_OFFSET_BAD ||
385 meta->gc_marker == gc_marker + GC_OFFSET_UNSURE) {
386 log_debug("Collecting %s", meta->id);
387 meta->gc_marker = gc_marker + GC_OFFSET_BAD;
388 unit_add_to_cleanup_queue((Unit*) meta);
392 m->n_in_gc_queue = 0;
393 m->gc_queue_timestamp = 0;
398 static void manager_clear_jobs_and_units(Manager *m) {
404 while ((j = hashmap_first(m->transaction_jobs)))
407 while ((u = hashmap_first(m->units)))
410 manager_dispatch_cleanup_queue(m);
412 assert(!m->load_queue);
413 assert(!m->run_queue);
414 assert(!m->dbus_unit_queue);
415 assert(!m->dbus_job_queue);
416 assert(!m->cleanup_queue);
417 assert(!m->gc_queue);
419 assert(hashmap_isempty(m->transaction_jobs));
420 assert(hashmap_isempty(m->jobs));
421 assert(hashmap_isempty(m->units));
424 void manager_free(Manager *m) {
429 manager_clear_jobs_and_units(m);
431 for (c = 0; c < _UNIT_TYPE_MAX; c++)
432 if (unit_vtable[c]->shutdown)
433 unit_vtable[c]->shutdown(m);
435 /* If we reexecute ourselves, we keep the root cgroup
437 manager_shutdown_cgroup(m, m->exit_code != MANAGER_REEXECUTE);
439 manager_undo_generators(m);
443 hashmap_free(m->units);
444 hashmap_free(m->jobs);
445 hashmap_free(m->transaction_jobs);
446 hashmap_free(m->watch_pids);
447 hashmap_free(m->watch_bus);
449 if (m->epoll_fd >= 0)
450 close_nointr_nofail(m->epoll_fd);
451 if (m->signal_watch.fd >= 0)
452 close_nointr_nofail(m->signal_watch.fd);
453 if (m->notify_watch.fd >= 0)
454 close_nointr_nofail(m->notify_watch.fd);
457 if (m->audit_fd >= 0)
458 audit_close(m->audit_fd);
461 free(m->notify_socket);
464 lookup_paths_free(&m->lookup_paths);
465 strv_free(m->environment);
467 strv_free(m->default_controllers);
469 hashmap_free(m->cgroup_bondings);
470 set_free_free(m->unit_path_cache);
475 int manager_enumerate(Manager *m) {
481 /* Let's ask every type to load all units from disk/kernel
482 * that it might know */
483 for (c = 0; c < _UNIT_TYPE_MAX; c++)
484 if (unit_vtable[c]->enumerate)
485 if ((q = unit_vtable[c]->enumerate(m)) < 0)
488 manager_dispatch_load_queue(m);
492 int manager_coldplug(Manager *m) {
500 /* Then, let's set up their initial state. */
501 HASHMAP_FOREACH_KEY(u, k, m->units, i) {
507 if ((q = unit_coldplug(u)) < 0)
514 static void manager_build_unit_path_cache(Manager *m) {
521 set_free_free(m->unit_path_cache);
523 if (!(m->unit_path_cache = set_new(string_hash_func, string_compare_func))) {
524 log_error("Failed to allocate unit path cache.");
528 /* This simply builds a list of files we know exist, so that
529 * we don't always have to go to disk */
531 STRV_FOREACH(i, m->lookup_paths.unit_path) {
534 if (!(d = opendir(*i))) {
535 log_error("Failed to open directory: %m");
539 while ((de = readdir(d))) {
542 if (ignore_file(de->d_name))
545 if (asprintf(&p, "%s/%s", streq(*i, "/") ? "" : *i, de->d_name) < 0) {
550 if ((r = set_put(m->unit_path_cache, p)) < 0) {
563 log_error("Failed to build unit path cache: %s", strerror(-r));
565 set_free_free(m->unit_path_cache);
566 m->unit_path_cache = NULL;
572 int manager_startup(Manager *m, FILE *serialization, FDSet *fds) {
577 manager_run_generators(m);
579 manager_build_unit_path_cache(m);
581 /* If we will deserialize make sure that during enumeration
582 * this is already known, so we increase the counter here
585 m->n_deserializing ++;
587 /* First, enumerate what we can from all config files */
588 r = manager_enumerate(m);
590 /* Second, deserialize if there is something to deserialize */
592 if ((q = manager_deserialize(m, serialization, fds)) < 0)
595 /* Third, fire things up! */
596 if ((q = manager_coldplug(m)) < 0)
600 assert(m->n_deserializing > 0);
601 m->n_deserializing --;
607 static void transaction_delete_job(Manager *m, Job *j, bool delete_dependencies) {
611 /* Deletes one job from the transaction */
613 manager_transaction_unlink_job(m, j, delete_dependencies);
619 static void transaction_delete_unit(Manager *m, Unit *u) {
622 /* Deletes all jobs associated with a certain unit from the
625 while ((j = hashmap_get(m->transaction_jobs, u)))
626 transaction_delete_job(m, j, true);
629 static void transaction_clean_dependencies(Manager *m) {
635 /* Drops all dependencies of all installed jobs */
637 HASHMAP_FOREACH(j, m->jobs, i) {
638 while (j->subject_list)
639 job_dependency_free(j->subject_list);
640 while (j->object_list)
641 job_dependency_free(j->object_list);
644 assert(!m->transaction_anchor);
647 static void transaction_abort(Manager *m) {
652 while ((j = hashmap_first(m->transaction_jobs)))
654 transaction_delete_job(m, j, true);
658 assert(hashmap_isempty(m->transaction_jobs));
660 transaction_clean_dependencies(m);
663 static void transaction_find_jobs_that_matter_to_anchor(Manager *m, Job *j, unsigned generation) {
668 /* A recursive sweep through the graph that marks all units
669 * that matter to the anchor job, i.e. are directly or
670 * indirectly a dependency of the anchor job via paths that
671 * are fully marked as mattering. */
676 l = m->transaction_anchor;
678 LIST_FOREACH(subject, l, l) {
680 /* This link does not matter */
684 /* This unit has already been marked */
685 if (l->object->generation == generation)
688 l->object->matters_to_anchor = true;
689 l->object->generation = generation;
691 transaction_find_jobs_that_matter_to_anchor(m, l->object, generation);
695 static void transaction_merge_and_delete_job(Manager *m, Job *j, Job *other, JobType t) {
696 JobDependency *l, *last;
700 assert(j->unit == other->unit);
701 assert(!j->installed);
703 /* Merges 'other' into 'j' and then deletes j. */
706 j->state = JOB_WAITING;
707 j->override = j->override || other->override;
709 j->matters_to_anchor = j->matters_to_anchor || other->matters_to_anchor;
711 /* Patch us in as new owner of the JobDependency objects */
713 LIST_FOREACH(subject, l, other->subject_list) {
714 assert(l->subject == other);
719 /* Merge both lists */
721 last->subject_next = j->subject_list;
723 j->subject_list->subject_prev = last;
724 j->subject_list = other->subject_list;
727 /* Patch us in as new owner of the JobDependency objects */
729 LIST_FOREACH(object, l, other->object_list) {
730 assert(l->object == other);
735 /* Merge both lists */
737 last->object_next = j->object_list;
739 j->object_list->object_prev = last;
740 j->object_list = other->object_list;
743 /* Kill the other job */
744 other->subject_list = NULL;
745 other->object_list = NULL;
746 transaction_delete_job(m, other, true);
748 static bool job_is_conflicted_by(Job *j) {
753 /* Returns true if this job is pulled in by a least one
754 * ConflictedBy dependency. */
756 LIST_FOREACH(object, l, j->object_list)
763 static int delete_one_unmergeable_job(Manager *m, Job *j) {
768 /* Tries to delete one item in the linked list
769 * j->transaction_next->transaction_next->... that conflicts
770 * whith another one, in an attempt to make an inconsistent
771 * transaction work. */
773 /* We rely here on the fact that if a merged with b does not
774 * merge with c, either a or b merge with c neither */
775 LIST_FOREACH(transaction, j, j)
776 LIST_FOREACH(transaction, k, j->transaction_next) {
779 /* Is this one mergeable? Then skip it */
780 if (job_type_is_mergeable(j->type, k->type))
783 /* Ok, we found two that conflict, let's see if we can
784 * drop one of them */
785 if (!j->matters_to_anchor && !k->matters_to_anchor) {
787 /* Both jobs don't matter, so let's
788 * find the one that is smarter to
789 * remove. Let's think positive and
790 * rather remove stops then starts --
791 * except if something is being
792 * stopped because it is conflicted by
793 * another unit in which case we
794 * rather remove the start. */
796 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)));
797 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)));
799 if (j->type == JOB_STOP) {
801 if (job_is_conflicted_by(j))
806 } else if (k->type == JOB_STOP) {
808 if (job_is_conflicted_by(k))
815 } else if (!j->matters_to_anchor)
817 else if (!k->matters_to_anchor)
822 /* Ok, we can drop one, so let's do so. */
823 log_debug("Fixing conflicting jobs by deleting job %s/%s", d->unit->meta.id, job_type_to_string(d->type));
824 transaction_delete_job(m, d, true);
831 static int transaction_merge_jobs(Manager *m, DBusError *e) {
838 /* First step, check whether any of the jobs for one specific
839 * task conflict. If so, try to drop one of them. */
840 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
845 LIST_FOREACH(transaction, k, j->transaction_next) {
846 if (job_type_merge(&t, k->type) >= 0)
849 /* OK, we could not merge all jobs for this
850 * action. Let's see if we can get rid of one
853 if ((r = delete_one_unmergeable_job(m, j)) >= 0)
854 /* Ok, we managed to drop one, now
855 * let's ask our callers to call us
856 * again after garbage collecting */
859 /* We couldn't merge anything. Failure */
860 dbus_set_error(e, BUS_ERROR_TRANSACTION_JOBS_CONFLICTING, "Transaction contains conflicting jobs '%s' and '%s' for %s. Probably contradicting requirement dependencies configured.",
861 job_type_to_string(t), job_type_to_string(k->type), k->unit->meta.id);
866 /* Second step, merge the jobs. */
867 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
871 /* Merge all transactions */
872 LIST_FOREACH(transaction, k, j->transaction_next)
873 assert_se(job_type_merge(&t, k->type) == 0);
875 /* If an active job is mergeable, merge it too */
876 if (j->unit->meta.job)
877 job_type_merge(&t, j->unit->meta.job->type); /* Might fail. Which is OK */
879 while ((k = j->transaction_next)) {
881 transaction_merge_and_delete_job(m, k, j, t);
884 transaction_merge_and_delete_job(m, j, k, t);
887 assert(!j->transaction_next);
888 assert(!j->transaction_prev);
894 static void transaction_drop_redundant(Manager *m) {
899 /* Goes through the transaction and removes all jobs that are
908 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
909 bool changes_something = false;
912 LIST_FOREACH(transaction, k, j) {
914 if (!job_is_anchor(k) &&
915 (j->installed || job_type_is_redundant(k->type, unit_active_state(k->unit))))
918 changes_something = true;
922 if (changes_something)
925 /* log_debug("Found redundant job %s/%s, dropping.", j->unit->meta.id, job_type_to_string(j->type)); */
926 transaction_delete_job(m, j, false);
934 static bool unit_matters_to_anchor(Unit *u, Job *j) {
936 assert(!j->transaction_prev);
938 /* Checks whether at least one of the jobs for this unit
939 * matters to the anchor. */
941 LIST_FOREACH(transaction, j, j)
942 if (j->matters_to_anchor)
948 static int transaction_verify_order_one(Manager *m, Job *j, Job *from, unsigned generation, DBusError *e) {
955 assert(!j->transaction_prev);
957 /* Does a recursive sweep through the ordering graph, looking
958 * for a cycle. If we find cycle we try to break it. */
960 /* Have we seen this before? */
961 if (j->generation == generation) {
964 /* If the marker is NULL we have been here already and
965 * decided the job was loop-free from here. Hence
966 * shortcut things and return right-away. */
970 /* So, the marker is not NULL and we already have been
971 * here. We have a cycle. Let's try to break it. We go
972 * backwards in our path and try to find a suitable
973 * job to remove. We use the marker to find our way
974 * back, since smart how we are we stored our way back
976 log_warning("Found ordering cycle on %s/%s", j->unit->meta.id, job_type_to_string(j->type));
979 for (k = from; k; k = ((k->generation == generation && k->marker != k) ? k->marker : NULL)) {
981 log_info("Walked on cycle path to %s/%s", k->unit->meta.id, job_type_to_string(k->type));
985 !unit_matters_to_anchor(k->unit, k)) {
986 /* Ok, we can drop this one, so let's
991 /* Check if this in fact was the beginning of
999 log_warning("Breaking ordering cycle by deleting job %s/%s", delete->unit->meta.id, job_type_to_string(delete->type));
1000 transaction_delete_unit(m, delete->unit);
1004 log_error("Unable to break cycle");
1006 dbus_set_error(e, BUS_ERROR_TRANSACTION_ORDER_IS_CYCLIC, "Transaction order is cyclic. See system logs for details.");
1010 /* Make the marker point to where we come from, so that we can
1011 * find our way backwards if we want to break a cycle. We use
1012 * a special marker for the beginning: we point to
1014 j->marker = from ? from : j;
1015 j->generation = generation;
1017 /* We assume that the the dependencies are bidirectional, and
1018 * hence can ignore UNIT_AFTER */
1019 SET_FOREACH(u, j->unit->meta.dependencies[UNIT_BEFORE], i) {
1022 /* Is there a job for this unit? */
1023 if (!(o = hashmap_get(m->transaction_jobs, u)))
1025 /* Ok, there is no job for this in the
1026 * transaction, but maybe there is already one
1028 if (!(o = u->meta.job))
1031 if ((r = transaction_verify_order_one(m, o, j, generation, e)) < 0)
1035 /* Ok, let's backtrack, and remember that this entry is not on
1036 * our path anymore. */
1042 static int transaction_verify_order(Manager *m, unsigned *generation, DBusError *e) {
1051 /* Check if the ordering graph is cyclic. If it is, try to fix
1052 * that up by dropping one of the jobs. */
1054 g = (*generation)++;
1056 HASHMAP_FOREACH(j, m->transaction_jobs, i)
1057 if ((r = transaction_verify_order_one(m, j, NULL, g, e)) < 0)
1063 static void transaction_collect_garbage(Manager *m) {
1068 /* Drop jobs that are not required by any other job */
1076 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1077 if (j->object_list) {
1078 /* log_debug("Keeping job %s/%s because of %s/%s", */
1079 /* j->unit->meta.id, job_type_to_string(j->type), */
1080 /* j->object_list->subject ? j->object_list->subject->unit->meta.id : "root", */
1081 /* j->object_list->subject ? job_type_to_string(j->object_list->subject->type) : "root"); */
1085 /* log_debug("Garbage collecting job %s/%s", j->unit->meta.id, job_type_to_string(j->type)); */
1086 transaction_delete_job(m, j, true);
1094 static int transaction_is_destructive(Manager *m, DBusError *e) {
1100 /* Checks whether applying this transaction means that
1101 * existing jobs would be replaced */
1103 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1106 assert(!j->transaction_prev);
1107 assert(!j->transaction_next);
1109 if (j->unit->meta.job &&
1110 j->unit->meta.job != j &&
1111 !job_type_is_superset(j->type, j->unit->meta.job->type)) {
1113 dbus_set_error(e, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE, "Transaction is destructive.");
1121 static void transaction_minimize_impact(Manager *m) {
1125 /* Drops all unnecessary jobs that reverse already active jobs
1126 * or that stop a running service. */
1134 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1135 LIST_FOREACH(transaction, j, j) {
1136 bool stops_running_service, changes_existing_job;
1138 /* If it matters, we shouldn't drop it */
1139 if (j->matters_to_anchor)
1142 /* Would this stop a running service?
1143 * Would this change an existing job?
1144 * If so, let's drop this entry */
1146 stops_running_service =
1147 j->type == JOB_STOP && UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(j->unit));
1149 changes_existing_job =
1150 j->unit->meta.job &&
1151 job_type_is_conflicting(j->type, j->unit->meta.job->type);
1153 if (!stops_running_service && !changes_existing_job)
1156 if (stops_running_service)
1157 log_info("%s/%s would stop a running service.", j->unit->meta.id, job_type_to_string(j->type));
1159 if (changes_existing_job)
1160 log_info("%s/%s would change existing job.", j->unit->meta.id, job_type_to_string(j->type));
1162 /* Ok, let's get rid of this */
1163 log_info("Deleting %s/%s to minimize impact.", j->unit->meta.id, job_type_to_string(j->type));
1165 transaction_delete_job(m, j, true);
1177 static int transaction_apply(Manager *m) {
1182 /* Moves the transaction jobs to the set of active jobs */
1184 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1186 assert(!j->transaction_prev);
1187 assert(!j->transaction_next);
1192 if ((r = hashmap_put(m->jobs, UINT32_TO_PTR(j->id), j)) < 0)
1196 while ((j = hashmap_steal_first(m->transaction_jobs))) {
1198 /* log_debug("Skipping already installed job %s/%s as %u", j->unit->meta.id, job_type_to_string(j->type), (unsigned) j->id); */
1202 if (j->unit->meta.job)
1203 job_free(j->unit->meta.job);
1205 j->unit->meta.job = j;
1206 j->installed = true;
1207 m->n_installed_jobs ++;
1209 /* We're fully installed. Now let's free data we don't
1212 assert(!j->transaction_next);
1213 assert(!j->transaction_prev);
1215 job_add_to_run_queue(j);
1216 job_add_to_dbus_queue(j);
1219 log_debug("Installed new job %s/%s as %u", j->unit->meta.id, job_type_to_string(j->type), (unsigned) j->id);
1222 /* As last step, kill all remaining job dependencies. */
1223 transaction_clean_dependencies(m);
1229 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1233 hashmap_remove(m->jobs, UINT32_TO_PTR(j->id));
1239 static int transaction_activate(Manager *m, JobMode mode, DBusError *e) {
1241 unsigned generation = 1;
1245 /* This applies the changes recorded in transaction_jobs to
1246 * the actual list of jobs, if possible. */
1248 /* First step: figure out which jobs matter */
1249 transaction_find_jobs_that_matter_to_anchor(m, NULL, generation++);
1251 /* Second step: Try not to stop any running services if
1252 * we don't have to. Don't try to reverse running
1253 * jobs if we don't have to. */
1254 if (mode == JOB_FAIL)
1255 transaction_minimize_impact(m);
1257 /* Third step: Drop redundant jobs */
1258 transaction_drop_redundant(m);
1261 /* Fourth step: Let's remove unneeded jobs that might
1263 transaction_collect_garbage(m);
1265 /* Fifth step: verify order makes sense and correct
1266 * cycles if necessary and possible */
1267 if ((r = transaction_verify_order(m, &generation, e)) >= 0)
1271 log_warning("Requested transaction contains an unfixable cyclic ordering dependency: %s", bus_error(e, r));
1275 /* Let's see if the resulting transaction ordering
1276 * graph is still cyclic... */
1280 /* Sixth step: let's drop unmergeable entries if
1281 * necessary and possible, merge entries we can
1283 if ((r = transaction_merge_jobs(m, e)) >= 0)
1287 log_warning("Requested transaction contains unmergable jobs: %s", bus_error(e, r));
1291 /* Seventh step: an entry got dropped, let's garbage
1292 * collect its dependencies. */
1293 transaction_collect_garbage(m);
1295 /* Let's see if the resulting transaction still has
1296 * unmergeable entries ... */
1299 /* Eights step: Drop redundant jobs again, if the merging now allows us to drop more. */
1300 transaction_drop_redundant(m);
1302 /* Ninth step: check whether we can actually apply this */
1303 if (mode == JOB_FAIL)
1304 if ((r = transaction_is_destructive(m, e)) < 0) {
1305 log_notice("Requested transaction contradicts existing jobs: %s", bus_error(e, r));
1309 /* Tenth step: apply changes */
1310 if ((r = transaction_apply(m)) < 0) {
1311 log_warning("Failed to apply transaction: %s", strerror(-r));
1315 assert(hashmap_isempty(m->transaction_jobs));
1316 assert(!m->transaction_anchor);
1321 transaction_abort(m);
1325 static Job* transaction_add_one_job(Manager *m, JobType type, Unit *unit, bool override, bool *is_new) {
1331 /* Looks for an axisting prospective job and returns that. If
1332 * it doesn't exist it is created and added to the prospective
1335 f = hashmap_get(m->transaction_jobs, unit);
1337 LIST_FOREACH(transaction, j, f) {
1338 assert(j->unit == unit);
1340 if (j->type == type) {
1347 if (unit->meta.job && unit->meta.job->type == type)
1349 else if (!(j = job_new(m, type, unit)))
1354 j->matters_to_anchor = false;
1355 j->override = override;
1357 LIST_PREPEND(Job, transaction, f, j);
1359 if (hashmap_replace(m->transaction_jobs, unit, f) < 0) {
1367 /* log_debug("Added job %s/%s to transaction.", unit->meta.id, job_type_to_string(type)); */
1372 void manager_transaction_unlink_job(Manager *m, Job *j, bool delete_dependencies) {
1376 if (j->transaction_prev)
1377 j->transaction_prev->transaction_next = j->transaction_next;
1378 else if (j->transaction_next)
1379 hashmap_replace(m->transaction_jobs, j->unit, j->transaction_next);
1381 hashmap_remove_value(m->transaction_jobs, j->unit, j);
1383 if (j->transaction_next)
1384 j->transaction_next->transaction_prev = j->transaction_prev;
1386 j->transaction_prev = j->transaction_next = NULL;
1388 while (j->subject_list)
1389 job_dependency_free(j->subject_list);
1391 while (j->object_list) {
1392 Job *other = j->object_list->matters ? j->object_list->subject : NULL;
1394 job_dependency_free(j->object_list);
1396 if (other && delete_dependencies) {
1397 log_debug("Deleting job %s/%s as dependency of job %s/%s",
1398 other->unit->meta.id, job_type_to_string(other->type),
1399 j->unit->meta.id, job_type_to_string(j->type));
1400 transaction_delete_job(m, other, delete_dependencies);
1405 static int transaction_add_job_and_dependencies(
1422 assert(type < _JOB_TYPE_MAX);
1425 if (unit->meta.load_state != UNIT_LOADED &&
1426 unit->meta.load_state != UNIT_ERROR &&
1427 unit->meta.load_state != UNIT_MASKED) {
1428 dbus_set_error(e, BUS_ERROR_LOAD_FAILED, "Unit %s is not loaded properly.", unit->meta.id);
1432 if (type != JOB_STOP && unit->meta.load_state == UNIT_ERROR) {
1433 dbus_set_error(e, BUS_ERROR_LOAD_FAILED,
1434 "Unit %s failed to load: %s. "
1435 "See system logs and 'systemctl status' for details.",
1437 strerror(-unit->meta.load_error));
1441 if (type != JOB_STOP && unit->meta.load_state == UNIT_MASKED) {
1442 dbus_set_error(e, BUS_ERROR_MASKED, "Unit %s is masked.", unit->meta.id);
1446 if (!unit_job_is_applicable(unit, type)) {
1447 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);
1451 /* First add the job. */
1452 if (!(ret = transaction_add_one_job(m, type, unit, override, &is_new)))
1455 /* Then, add a link to the job. */
1456 if (!job_dependency_new(by, ret, matters, conflicts))
1462 /* If we are following some other unit, make sure we
1463 * add all dependencies of everybody following. */
1464 if (unit_following_set(ret->unit, &following) > 0) {
1465 SET_FOREACH(dep, following, i)
1466 if ((r = transaction_add_job_and_dependencies(m, type, dep, ret, false, override, false, e, NULL)) < 0) {
1467 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, bus_error(e, r));
1473 set_free(following);
1476 /* Finally, recursively add in all dependencies. */
1477 if (type == JOB_START || type == JOB_RELOAD_OR_START) {
1478 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES], i)
1479 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, true, override, false, e, NULL)) < 0) {
1487 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_BIND_TO], i)
1488 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, true, override, false, e, NULL)) < 0) {
1497 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES_OVERRIDABLE], i)
1498 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, !override, override, false, e, NULL)) < 0) {
1499 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, bus_error(e, r));
1505 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_WANTS], i)
1506 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, false, false, false, e, NULL)) < 0) {
1507 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, bus_error(e, r));
1513 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE], i)
1514 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, true, override, false, e, NULL)) < 0) {
1523 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE_OVERRIDABLE], i)
1524 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, !override, override, false, e, NULL)) < 0) {
1525 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, bus_error(e, r));
1531 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_CONFLICTS], i)
1532 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, dep, ret, true, override, true, e, NULL)) < 0) {
1541 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_CONFLICTED_BY], i)
1542 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, dep, ret, false, override, false, e, NULL)) < 0) {
1543 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, bus_error(e, r));
1549 } else if (type == JOB_STOP || type == JOB_RESTART || type == JOB_TRY_RESTART) {
1551 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRED_BY], i)
1552 if ((r = transaction_add_job_and_dependencies(m, type, dep, ret, true, override, false, e, NULL)) < 0) {
1561 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_BOUND_BY], i)
1562 if ((r = transaction_add_job_and_dependencies(m, type, dep, ret, true, override, false, e, NULL)) < 0) {
1572 /* JOB_VERIFY_STARTED, JOB_RELOAD require no dependency handling */
1584 static int transaction_add_isolate_jobs(Manager *m) {
1592 HASHMAP_FOREACH_KEY(u, k, m->units, i) {
1594 /* ignore aliases */
1595 if (u->meta.id != k)
1598 if (UNIT_VTABLE(u)->no_isolate)
1601 /* No need to stop inactive jobs */
1602 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(u)) && !u->meta.job)
1605 /* Is there already something listed for this? */
1606 if (hashmap_get(m->transaction_jobs, u))
1609 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, u, NULL, true, false, false, NULL, NULL)) < 0)
1610 log_warning("Cannot add isolate job for unit %s, ignoring: %s", u->meta.id, strerror(-r));
1616 int manager_add_job(Manager *m, JobType type, Unit *unit, JobMode mode, bool override, DBusError *e, Job **_ret) {
1621 assert(type < _JOB_TYPE_MAX);
1623 assert(mode < _JOB_MODE_MAX);
1625 if (mode == JOB_ISOLATE && type != JOB_START) {
1626 dbus_set_error(e, BUS_ERROR_INVALID_JOB_MODE, "Isolate is only valid for start.");
1630 if (mode == JOB_ISOLATE && !unit->meta.allow_isolate) {
1631 dbus_set_error(e, BUS_ERROR_NO_ISOLATION, "Operation refused, unit may not be isolated.");
1635 log_debug("Trying to enqueue job %s/%s/%s", unit->meta.id, job_type_to_string(type), job_mode_to_string(mode));
1637 if ((r = transaction_add_job_and_dependencies(m, type, unit, NULL, true, override, false, e, &ret)) < 0) {
1638 transaction_abort(m);
1642 if (mode == JOB_ISOLATE)
1643 if ((r = transaction_add_isolate_jobs(m)) < 0) {
1644 transaction_abort(m);
1648 if ((r = transaction_activate(m, mode, e)) < 0)
1651 log_debug("Enqueued job %s/%s as %u", unit->meta.id, job_type_to_string(type), (unsigned) ret->id);
1659 int manager_add_job_by_name(Manager *m, JobType type, const char *name, JobMode mode, bool override, DBusError *e, Job **_ret) {
1664 assert(type < _JOB_TYPE_MAX);
1666 assert(mode < _JOB_MODE_MAX);
1668 if ((r = manager_load_unit(m, name, NULL, NULL, &unit)) < 0)
1671 return manager_add_job(m, type, unit, mode, override, e, _ret);
1674 Job *manager_get_job(Manager *m, uint32_t id) {
1677 return hashmap_get(m->jobs, UINT32_TO_PTR(id));
1680 Unit *manager_get_unit(Manager *m, const char *name) {
1684 return hashmap_get(m->units, name);
1687 unsigned manager_dispatch_load_queue(Manager *m) {
1693 /* Make sure we are not run recursively */
1694 if (m->dispatching_load_queue)
1697 m->dispatching_load_queue = true;
1699 /* Dispatches the load queue. Takes a unit from the queue and
1700 * tries to load its data until the queue is empty */
1702 while ((meta = m->load_queue)) {
1703 assert(meta->in_load_queue);
1705 unit_load((Unit*) meta);
1709 m->dispatching_load_queue = false;
1713 int manager_load_unit_prepare(Manager *m, const char *name, const char *path, DBusError *e, Unit **_ret) {
1718 assert(name || path);
1720 /* This will prepare the unit for loading, but not actually
1721 * load anything from disk. */
1723 if (path && !is_path(path)) {
1724 dbus_set_error(e, BUS_ERROR_INVALID_PATH, "Path %s is not absolute.", path);
1729 name = file_name_from_path(path);
1731 if (!unit_name_is_valid(name, false)) {
1732 dbus_set_error(e, BUS_ERROR_INVALID_NAME, "Unit name %s is not valid.", name);
1736 if ((ret = manager_get_unit(m, name))) {
1741 if (!(ret = unit_new(m)))
1745 if (!(ret->meta.fragment_path = strdup(path))) {
1750 if ((r = unit_add_name(ret, name)) < 0) {
1755 unit_add_to_load_queue(ret);
1756 unit_add_to_dbus_queue(ret);
1757 unit_add_to_gc_queue(ret);
1765 int manager_load_unit(Manager *m, const char *name, const char *path, DBusError *e, Unit **_ret) {
1770 /* This will load the service information files, but not actually
1771 * start any services or anything. */
1773 if ((r = manager_load_unit_prepare(m, name, path, e, _ret)) != 0)
1776 manager_dispatch_load_queue(m);
1779 *_ret = unit_follow_merge(*_ret);
1784 void manager_dump_jobs(Manager *s, FILE *f, const char *prefix) {
1791 HASHMAP_FOREACH(j, s->jobs, i)
1792 job_dump(j, f, prefix);
1795 void manager_dump_units(Manager *s, FILE *f, const char *prefix) {
1803 HASHMAP_FOREACH_KEY(u, t, s->units, i)
1804 if (u->meta.id == t)
1805 unit_dump(u, f, prefix);
1808 void manager_clear_jobs(Manager *m) {
1813 transaction_abort(m);
1815 while ((j = hashmap_first(m->jobs)))
1819 unsigned manager_dispatch_run_queue(Manager *m) {
1823 if (m->dispatching_run_queue)
1826 m->dispatching_run_queue = true;
1828 while ((j = m->run_queue)) {
1829 assert(j->installed);
1830 assert(j->in_run_queue);
1832 job_run_and_invalidate(j);
1836 m->dispatching_run_queue = false;
1840 unsigned manager_dispatch_dbus_queue(Manager *m) {
1847 if (m->dispatching_dbus_queue)
1850 m->dispatching_dbus_queue = true;
1852 while ((meta = m->dbus_unit_queue)) {
1853 assert(meta->in_dbus_queue);
1855 bus_unit_send_change_signal((Unit*) meta);
1859 while ((j = m->dbus_job_queue)) {
1860 assert(j->in_dbus_queue);
1862 bus_job_send_change_signal(j);
1866 m->dispatching_dbus_queue = false;
1870 static int manager_process_notify_fd(Manager *m) {
1877 struct msghdr msghdr;
1879 struct ucred *ucred;
1881 struct cmsghdr cmsghdr;
1882 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
1888 iovec.iov_base = buf;
1889 iovec.iov_len = sizeof(buf)-1;
1893 msghdr.msg_iov = &iovec;
1894 msghdr.msg_iovlen = 1;
1895 msghdr.msg_control = &control;
1896 msghdr.msg_controllen = sizeof(control);
1898 if ((n = recvmsg(m->notify_watch.fd, &msghdr, MSG_DONTWAIT)) <= 0) {
1902 if (errno == EAGAIN || errno == EINTR)
1908 if (msghdr.msg_controllen < CMSG_LEN(sizeof(struct ucred)) ||
1909 control.cmsghdr.cmsg_level != SOL_SOCKET ||
1910 control.cmsghdr.cmsg_type != SCM_CREDENTIALS ||
1911 control.cmsghdr.cmsg_len != CMSG_LEN(sizeof(struct ucred))) {
1912 log_warning("Received notify message without credentials. Ignoring.");
1916 ucred = (struct ucred*) CMSG_DATA(&control.cmsghdr);
1918 if (!(u = hashmap_get(m->watch_pids, LONG_TO_PTR(ucred->pid))))
1919 if (!(u = cgroup_unit_by_pid(m, ucred->pid))) {
1920 log_warning("Cannot find unit for notify message of PID %lu.", (unsigned long) ucred->pid);
1924 assert((size_t) n < sizeof(buf));
1926 if (!(tags = strv_split(buf, "\n\r")))
1929 log_debug("Got notification message for unit %s", u->meta.id);
1931 if (UNIT_VTABLE(u)->notify_message)
1932 UNIT_VTABLE(u)->notify_message(u, ucred->pid, tags);
1940 static int manager_dispatch_sigchld(Manager *m) {
1950 /* First we call waitd() for a PID and do not reap the
1951 * zombie. That way we can still access /proc/$PID for
1952 * it while it is a zombie. */
1953 if (waitid(P_ALL, 0, &si, WEXITED|WNOHANG|WNOWAIT) < 0) {
1955 if (errno == ECHILD)
1967 if (si.si_code == CLD_EXITED || si.si_code == CLD_KILLED || si.si_code == CLD_DUMPED) {
1970 get_process_name(si.si_pid, &name);
1971 log_debug("Got SIGCHLD for process %lu (%s)", (unsigned long) si.si_pid, strna(name));
1975 /* Let's flush any message the dying child might still
1976 * have queued for us. This ensures that the process
1977 * still exists in /proc so that we can figure out
1978 * which cgroup and hence unit it belongs to. */
1979 if ((r = manager_process_notify_fd(m)) < 0)
1982 /* And now figure out the unit this belongs to */
1983 if (!(u = hashmap_get(m->watch_pids, LONG_TO_PTR(si.si_pid))))
1984 u = cgroup_unit_by_pid(m, si.si_pid);
1986 /* And now, we actually reap the zombie. */
1987 if (waitid(P_PID, si.si_pid, &si, WEXITED) < 0) {
1994 if (si.si_code != CLD_EXITED && si.si_code != CLD_KILLED && si.si_code != CLD_DUMPED)
1997 log_debug("Child %lu died (code=%s, status=%i/%s)",
1998 (long unsigned) si.si_pid,
1999 sigchld_code_to_string(si.si_code),
2001 strna(si.si_code == CLD_EXITED
2002 ? exit_status_to_string(si.si_status, EXIT_STATUS_FULL)
2003 : signal_to_string(si.si_status)));
2008 log_debug("Child %lu belongs to %s", (long unsigned) si.si_pid, u->meta.id);
2010 hashmap_remove(m->watch_pids, LONG_TO_PTR(si.si_pid));
2011 UNIT_VTABLE(u)->sigchld_event(u, si.si_pid, si.si_code, si.si_status);
2017 static int manager_start_target(Manager *m, const char *name, JobMode mode) {
2021 dbus_error_init(&error);
2023 log_debug("Activating special unit %s", name);
2025 if ((r = manager_add_job_by_name(m, JOB_START, name, mode, true, &error, NULL)) < 0)
2026 log_error("Failed to enqueue %s job: %s", name, bus_error(&error, r));
2028 dbus_error_free(&error);
2033 static int manager_process_signal_fd(Manager *m) {
2035 struct signalfd_siginfo sfsi;
2036 bool sigchld = false;
2041 if ((n = read(m->signal_watch.fd, &sfsi, sizeof(sfsi))) != sizeof(sfsi)) {
2046 if (errno == EINTR || errno == EAGAIN)
2052 log_debug("Received SIG%s", strna(signal_to_string(sfsi.ssi_signo)));
2054 switch (sfsi.ssi_signo) {
2061 if (m->running_as == MANAGER_SYSTEM) {
2062 /* This is for compatibility with the
2063 * original sysvinit */
2064 m->exit_code = MANAGER_REEXECUTE;
2071 if (m->running_as == MANAGER_SYSTEM) {
2072 manager_start_target(m, SPECIAL_CTRL_ALT_DEL_TARGET, JOB_REPLACE);
2076 /* Run the exit target if there is one, if not, just exit. */
2077 if (manager_start_target(m, SPECIAL_EXIT_TARGET, JOB_REPLACE) < 0) {
2078 m->exit_code = MANAGER_EXIT;
2085 if (m->running_as == MANAGER_SYSTEM)
2086 manager_start_target(m, SPECIAL_KBREQUEST_TARGET, JOB_REPLACE);
2088 /* This is a nop on non-init */
2092 if (m->running_as == MANAGER_SYSTEM)
2093 manager_start_target(m, SPECIAL_SIGPWR_TARGET, JOB_REPLACE);
2095 /* This is a nop on non-init */
2101 u = manager_get_unit(m, SPECIAL_DBUS_SERVICE);
2103 if (!u || UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u))) {
2104 log_info("Trying to reconnect to bus...");
2108 if (!u || !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u))) {
2109 log_info("Loading D-Bus service...");
2110 manager_start_target(m, SPECIAL_DBUS_SERVICE, JOB_REPLACE);
2121 if (!(f = open_memstream(&dump, &size))) {
2122 log_warning("Failed to allocate memory stream.");
2126 manager_dump_units(m, f, "\t");
2127 manager_dump_jobs(m, f, "\t");
2132 log_warning("Failed to write status stream");
2137 log_dump(LOG_INFO, dump);
2144 m->exit_code = MANAGER_RELOAD;
2148 /* Starting SIGRTMIN+0 */
2149 static const char * const target_table[] = {
2150 [0] = SPECIAL_DEFAULT_TARGET,
2151 [1] = SPECIAL_RESCUE_TARGET,
2152 [2] = SPECIAL_EMERGENCY_TARGET,
2153 [3] = SPECIAL_HALT_TARGET,
2154 [4] = SPECIAL_POWEROFF_TARGET,
2155 [5] = SPECIAL_REBOOT_TARGET,
2156 [6] = SPECIAL_KEXEC_TARGET
2159 /* Starting SIGRTMIN+13, so that target halt and system halt are 10 apart */
2160 static const ManagerExitCode code_table[] = {
2162 [1] = MANAGER_POWEROFF,
2163 [2] = MANAGER_REBOOT,
2167 if ((int) sfsi.ssi_signo >= SIGRTMIN+0 &&
2168 (int) sfsi.ssi_signo < SIGRTMIN+(int) ELEMENTSOF(target_table)) {
2169 manager_start_target(m, target_table[sfsi.ssi_signo - SIGRTMIN],
2170 (sfsi.ssi_signo == 1 || sfsi.ssi_signo == 2) ? JOB_ISOLATE : JOB_REPLACE);
2174 if ((int) sfsi.ssi_signo >= SIGRTMIN+13 &&
2175 (int) sfsi.ssi_signo < SIGRTMIN+13+(int) ELEMENTSOF(code_table)) {
2176 m->exit_code = code_table[sfsi.ssi_signo - SIGRTMIN - 13];
2180 log_warning("Got unhandled signal <%s>.", strna(signal_to_string(sfsi.ssi_signo)));
2186 return manager_dispatch_sigchld(m);
2191 static int process_event(Manager *m, struct epoll_event *ev) {
2198 assert(w = ev->data.ptr);
2200 if (w->type == WATCH_INVALID)
2207 /* An incoming signal? */
2208 if (ev->events != EPOLLIN)
2211 if ((r = manager_process_signal_fd(m)) < 0)
2218 /* An incoming daemon notification event? */
2219 if (ev->events != EPOLLIN)
2222 if ((r = manager_process_notify_fd(m)) < 0)
2229 /* Some fd event, to be dispatched to the units */
2230 UNIT_VTABLE(w->data.unit)->fd_event(w->data.unit, w->fd, ev->events, w);
2233 case WATCH_UNIT_TIMER:
2234 case WATCH_JOB_TIMER: {
2238 /* Some timer event, to be dispatched to the units */
2239 if ((k = read(w->fd, &v, sizeof(v))) != sizeof(v)) {
2241 if (k < 0 && (errno == EINTR || errno == EAGAIN))
2244 return k < 0 ? -errno : -EIO;
2247 if (w->type == WATCH_UNIT_TIMER)
2248 UNIT_VTABLE(w->data.unit)->timer_event(w->data.unit, v, w);
2250 job_timer_event(w->data.job, v, w);
2255 /* Some mount table change, intended for the mount subsystem */
2256 mount_fd_event(m, ev->events);
2260 /* Some swap table change, intended for the swap subsystem */
2261 swap_fd_event(m, ev->events);
2265 /* Some notification from udev, intended for the device subsystem */
2266 device_fd_event(m, ev->events);
2269 case WATCH_DBUS_WATCH:
2270 bus_watch_event(m, w, ev->events);
2273 case WATCH_DBUS_TIMEOUT:
2274 bus_timeout_event(m, w, ev->events);
2278 log_error("event type=%i", w->type);
2279 assert_not_reached("Unknown epoll event type.");
2285 int manager_loop(Manager *m) {
2288 RATELIMIT_DEFINE(rl, 1*USEC_PER_SEC, 1000);
2291 m->exit_code = MANAGER_RUNNING;
2293 /* Release the path cache */
2294 set_free_free(m->unit_path_cache);
2295 m->unit_path_cache = NULL;
2297 manager_check_finished(m);
2299 /* There might still be some zombies hanging around from
2300 * before we were exec()'ed. Leat's reap them */
2301 if ((r = manager_dispatch_sigchld(m)) < 0)
2304 while (m->exit_code == MANAGER_RUNNING) {
2305 struct epoll_event event;
2308 if (!ratelimit_test(&rl)) {
2309 /* Yay, something is going seriously wrong, pause a little */
2310 log_warning("Looping too fast. Throttling execution a little.");
2314 if (manager_dispatch_load_queue(m) > 0)
2317 if (manager_dispatch_run_queue(m) > 0)
2320 if (bus_dispatch(m) > 0)
2323 if (manager_dispatch_cleanup_queue(m) > 0)
2326 if (manager_dispatch_gc_queue(m) > 0)
2329 if (manager_dispatch_dbus_queue(m) > 0)
2332 if (swap_dispatch_reload(m) > 0)
2335 if ((n = epoll_wait(m->epoll_fd, &event, 1, -1)) < 0) {
2345 if ((r = process_event(m, &event)) < 0)
2349 return m->exit_code;
2352 int manager_get_unit_from_dbus_path(Manager *m, const char *s, Unit **_u) {
2360 if (!startswith(s, "/org/freedesktop/systemd1/unit/"))
2363 if (!(n = bus_path_unescape(s+31)))
2366 u = manager_get_unit(m, n);
2377 int manager_get_job_from_dbus_path(Manager *m, const char *s, Job **_j) {
2386 if (!startswith(s, "/org/freedesktop/systemd1/job/"))
2389 if ((r = safe_atou(s + 30, &id)) < 0)
2392 if (!(j = manager_get_job(m, id)))
2400 void manager_send_unit_audit(Manager *m, Unit *u, int type, bool success) {
2405 if (m->audit_fd < 0)
2408 /* Don't generate audit events if the service was already
2409 * started and we're just deserializing */
2410 if (m->n_deserializing > 0)
2413 if (!(p = unit_name_to_prefix_and_instance(u->meta.id))) {
2414 log_error("Failed to allocate unit name for audit message: %s", strerror(ENOMEM));
2418 if (audit_log_user_comm_message(m->audit_fd, type, "", p, NULL, NULL, NULL, success) < 0)
2419 log_error("Failed to send audit message: %m");
2426 void manager_send_unit_plymouth(Manager *m, Unit *u) {
2428 union sockaddr_union sa;
2430 char *message = NULL;
2433 /* Don't generate plymouth events if the service was already
2434 * started and we're just deserializing */
2435 if (m->n_deserializing > 0)
2438 if (m->running_as != MANAGER_SYSTEM)
2441 if (u->meta.type != UNIT_SERVICE &&
2442 u->meta.type != UNIT_MOUNT &&
2443 u->meta.type != UNIT_SWAP)
2446 /* We set SOCK_NONBLOCK here so that we rather drop the
2447 * message then wait for plymouth */
2448 if ((fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0)) < 0) {
2449 log_error("socket() failed: %m");
2454 sa.sa.sa_family = AF_UNIX;
2455 strncpy(sa.un.sun_path+1, "/org/freedesktop/plymouthd", sizeof(sa.un.sun_path)-1);
2456 if (connect(fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + 1 + strlen(sa.un.sun_path+1)) < 0) {
2458 if (errno != EPIPE &&
2461 errno != ECONNREFUSED &&
2462 errno != ECONNRESET &&
2463 errno != ECONNABORTED)
2464 log_error("connect() failed: %m");
2469 if (asprintf(&message, "U\002%c%s%n", (int) (strlen(u->meta.id) + 1), u->meta.id, &n) < 0) {
2470 log_error("Out of memory");
2475 if ((r = write(fd, message, n + 1)) != n + 1) {
2477 if (errno != EPIPE &&
2480 errno != ECONNREFUSED &&
2481 errno != ECONNRESET &&
2482 errno != ECONNABORTED)
2483 log_error("Failed to write Plymouth message: %m");
2490 close_nointr_nofail(fd);
2495 void manager_dispatch_bus_name_owner_changed(
2498 const char* old_owner,
2499 const char *new_owner) {
2506 if (!(u = hashmap_get(m->watch_bus, name)))
2509 UNIT_VTABLE(u)->bus_name_owner_change(u, name, old_owner, new_owner);
2512 void manager_dispatch_bus_query_pid_done(
2523 if (!(u = hashmap_get(m->watch_bus, name)))
2526 UNIT_VTABLE(u)->bus_query_pid_done(u, name, pid);
2529 int manager_open_serialization(Manager *m, FILE **_f) {
2537 if (m->running_as == MANAGER_SYSTEM) {
2538 mkdir_p("/dev/.systemd", 0755);
2540 if (asprintf(&path, "/dev/.systemd/dump-%lu-XXXXXX", (unsigned long) getpid()) < 0)
2543 if (asprintf(&path, "/tmp/systemd-dump-%lu-XXXXXX", (unsigned long) getpid()) < 0)
2547 saved_umask = umask(0077);
2548 fd = mkostemp(path, O_RDWR|O_CLOEXEC);
2558 log_debug("Serializing state to %s", path);
2561 if (!(f = fdopen(fd, "w+")) < 0)
2569 int manager_serialize(Manager *m, FILE *f, FDSet *fds) {
2579 dual_timestamp_serialize(f, "initrd-timestamp", &m->initrd_timestamp);
2580 dual_timestamp_serialize(f, "startup-timestamp", &m->startup_timestamp);
2581 dual_timestamp_serialize(f, "finish-timestamp", &m->finish_timestamp);
2585 HASHMAP_FOREACH_KEY(u, t, m->units, i) {
2586 if (u->meta.id != t)
2589 if (!unit_can_serialize(u))
2593 fputs(u->meta.id, f);
2596 if ((r = unit_serialize(u, f, fds)) < 0)
2606 int manager_deserialize(Manager *m, FILE *f, FDSet *fds) {
2612 log_debug("Deserializing state...");
2614 m->n_deserializing ++;
2617 char line[1024], *l;
2619 if (!fgets(line, sizeof(line), f)) {
2634 if (startswith(l, "initrd-timestamp="))
2635 dual_timestamp_deserialize(l+17, &m->initrd_timestamp);
2636 else if (startswith(l, "startup-timestamp="))
2637 dual_timestamp_deserialize(l+18, &m->startup_timestamp);
2638 else if (startswith(l, "finish-timestamp="))
2639 dual_timestamp_deserialize(l+17, &m->finish_timestamp);
2641 log_debug("Unknown serialization item '%s'", l);
2646 char name[UNIT_NAME_MAX+2];
2649 if (!fgets(name, sizeof(name), f)) {
2660 if ((r = manager_load_unit(m, strstrip(name), NULL, NULL, &u)) < 0)
2663 if ((r = unit_deserialize(u, f, fds)) < 0)
2673 assert(m->n_deserializing > 0);
2674 m->n_deserializing --;
2679 int manager_reload(Manager *m) {
2686 if ((r = manager_open_serialization(m, &f)) < 0)
2689 if (!(fds = fdset_new())) {
2694 if ((r = manager_serialize(m, f, fds)) < 0)
2697 if (fseeko(f, 0, SEEK_SET) < 0) {
2702 /* From here on there is no way back. */
2703 manager_clear_jobs_and_units(m);
2704 manager_undo_generators(m);
2706 /* Find new unit paths */
2707 lookup_paths_free(&m->lookup_paths);
2708 if ((q = lookup_paths_init(&m->lookup_paths, m->running_as)) < 0)
2711 manager_run_generators(m);
2713 manager_build_unit_path_cache(m);
2715 m->n_deserializing ++;
2717 /* First, enumerate what we can from all config files */
2718 if ((q = manager_enumerate(m)) < 0)
2721 /* Second, deserialize our stored data */
2722 if ((q = manager_deserialize(m, f, fds)) < 0)
2728 /* Third, fire things up! */
2729 if ((q = manager_coldplug(m)) < 0)
2732 assert(m->n_deserializing > 0);
2733 m->n_deserializing ++;
2745 bool manager_is_booting_or_shutting_down(Manager *m) {
2750 /* Is the initial job still around? */
2751 if (manager_get_job(m, 1))
2754 /* Is there a job for the shutdown target? */
2755 if (((u = manager_get_unit(m, SPECIAL_SHUTDOWN_TARGET))))
2756 return !!u->meta.job;
2761 void manager_reset_failed(Manager *m) {
2767 HASHMAP_FOREACH(u, m->units, i)
2768 unit_reset_failed(u);
2771 int manager_set_console(Manager *m, const char *console) {
2776 if (!(c = strdup(console)))
2782 log_debug("Using kernel console %s", c);
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) {
2842 Hashmap *pids = NULL;
2843 const char *generator_path;
2847 generator_path = m->running_as == MANAGER_SYSTEM ? SYSTEM_GENERATOR_PATH : USER_GENERATOR_PATH;
2848 if (!(d = opendir(generator_path))) {
2850 if (errno == ENOENT)
2853 log_error("Failed to enumerate generator directory: %m");
2857 if (!m->generator_unit_path) {
2859 char system_path[] = "/dev/.systemd/generator-XXXXXX",
2860 user_path[] = "/tmp/systemd-generator-XXXXXX";
2862 if (!(p = mkdtemp(m->running_as == MANAGER_SYSTEM ? system_path : user_path))) {
2863 log_error("Failed to generate generator directory: %m");
2867 if (!(m->generator_unit_path = strdup(p))) {
2868 log_error("Failed to allocate generator unit path.");
2873 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
2874 log_error("Failed to allocate set.");
2878 while ((de = readdir(d))) {
2883 if (ignore_file(de->d_name))
2886 if (de->d_type != DT_REG &&
2887 de->d_type != DT_LNK &&
2888 de->d_type != DT_UNKNOWN)
2891 if (asprintf(&path, "%s/%s", generator_path, de->d_name) < 0) {
2892 log_error("Out of memory");
2896 if ((pid = fork()) < 0) {
2897 log_error("Failed to fork: %m");
2903 const char *arguments[5];
2906 arguments[0] = path;
2907 arguments[1] = m->generator_unit_path;
2908 arguments[2] = NULL;
2910 execv(path, (char **) arguments);
2912 log_error("Failed to execute %s: %m", path);
2913 _exit(EXIT_FAILURE);
2916 log_debug("Spawned generator %s as %lu", path, (unsigned long) pid);
2918 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
2919 log_error("Failed to add PID to set: %s", strerror(-k));
2924 while (!hashmap_isempty(pids)) {
2929 if (waitid(P_ALL, 0, &si, WEXITED) < 0) {
2934 log_error("waitid() failed: %m");
2938 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
2939 if (!is_clean_exit(si.si_code, si.si_status)) {
2940 if (si.si_code == CLD_EXITED)
2941 log_error("%s exited with exit status %i.", path, si.si_status);
2943 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
2945 log_debug("Generator %s exited successfully.", path);
2951 if (rmdir(m->generator_unit_path) >= 0) {
2952 /* Uh? we were able to remove this dir? I guess that
2953 * means the directory was empty, hence let's shortcut
2956 free(m->generator_unit_path);
2957 m->generator_unit_path = NULL;
2961 if (!strv_find(m->lookup_paths.unit_path, m->generator_unit_path)) {
2964 if (!(l = strv_append(m->lookup_paths.unit_path, m->generator_unit_path))) {
2965 log_error("Failed to add generator directory to unit search path: %m");
2969 strv_free(m->lookup_paths.unit_path);
2970 m->lookup_paths.unit_path = l;
2972 log_debug("Added generator unit path %s to search path.", m->generator_unit_path);
2980 hashmap_free_free(pids);
2983 void manager_undo_generators(Manager *m) {
2986 if (!m->generator_unit_path)
2989 strv_remove(m->lookup_paths.unit_path, m->generator_unit_path);
2990 rm_rf(m->generator_unit_path, false, true);
2992 free(m->generator_unit_path);
2993 m->generator_unit_path = NULL;
2996 int manager_set_default_controllers(Manager *m, char **controllers) {
3001 if (!(l = strv_copy(controllers)))
3004 strv_free(m->default_controllers);
3005 m->default_controllers = l;
3010 static const char* const manager_running_as_table[_MANAGER_RUNNING_AS_MAX] = {
3011 [MANAGER_SYSTEM] = "system",
3012 [MANAGER_USER] = "user"
3015 DEFINE_STRING_TABLE_LOOKUP(manager_running_as, ManagerRunningAs);