1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
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>
32 #include <sys/reboot.h>
33 #include <sys/ioctl.h>
37 #include <sys/types.h>
48 #include "ratelimit.h"
50 #include "mount-setup.h"
51 #include "utmp-wtmp.h"
52 #include "unit-name.h"
53 #include "dbus-unit.h"
56 #include "path-lookup.h"
58 #include "bus-errors.h"
60 /* As soon as 16 units are in our GC queue, make sure to run a gc sweep */
61 #define GC_QUEUE_ENTRIES_MAX 16
63 /* As soon as 5s passed since a unit was added to our GC queue, make sure to run a gc sweep */
64 #define GC_QUEUE_USEC_MAX (10*USEC_PER_SEC)
66 /* Where clients shall send notification messages to */
67 #define NOTIFY_SOCKET "/org/freedesktop/systemd1/notify"
69 static int manager_setup_notify(Manager *m) {
72 struct sockaddr_un un;
74 struct epoll_event ev;
79 m->notify_watch.type = WATCH_NOTIFY;
80 if ((m->notify_watch.fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0)) < 0) {
81 log_error("Failed to allocate notification socket: %m");
86 sa.sa.sa_family = AF_UNIX;
89 snprintf(sa.un.sun_path+1, sizeof(sa.un.sun_path)-1, NOTIFY_SOCKET "/%llu", random_ull());
91 strncpy(sa.un.sun_path+1, NOTIFY_SOCKET, sizeof(sa.un.sun_path)-1);
93 if (bind(m->notify_watch.fd, &sa.sa, sizeof(sa_family_t) + 1 + strlen(sa.un.sun_path+1)) < 0) {
94 log_error("bind() failed: %m");
98 if (setsockopt(m->notify_watch.fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one)) < 0) {
99 log_error("SO_PASSCRED failed: %m");
105 ev.data.ptr = &m->notify_watch;
107 if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->notify_watch.fd, &ev) < 0)
110 if (!(m->notify_socket = strdup(sa.un.sun_path+1)))
116 static int enable_special_signals(Manager *m) {
121 /* Enable that we get SIGINT on control-alt-del */
122 if (reboot(RB_DISABLE_CAD) < 0)
123 log_warning("Failed to enable ctrl-alt-del handling: %m");
125 if ((fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY)) < 0)
126 log_warning("Failed to open /dev/tty0: %m");
128 /* Enable that we get SIGWINCH on kbrequest */
129 if (ioctl(fd, KDSIGACCEPT, SIGWINCH) < 0)
130 log_warning("Failed to enable kbrequest handling: %s", strerror(errno));
132 close_nointr_nofail(fd);
138 static int manager_setup_signals(Manager *m) {
140 struct epoll_event ev;
145 /* We are not interested in SIGSTOP and friends. */
147 sa.sa_handler = SIG_DFL;
148 sa.sa_flags = SA_NOCLDSTOP|SA_RESTART;
149 assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);
151 assert_se(sigemptyset(&mask) == 0);
153 sigset_add_many(&mask,
154 SIGCHLD, /* Child died */
155 SIGTERM, /* Reexecute daemon */
156 SIGHUP, /* Reload configuration */
157 SIGUSR1, /* systemd/upstart: reconnect to D-Bus */
158 SIGUSR2, /* systemd: dump status */
159 SIGINT, /* Kernel sends us this on control-alt-del */
160 SIGWINCH, /* Kernel sends us this on kbrequest (alt-arrowup) */
161 SIGPWR, /* Some kernel drivers and upsd send us this on power failure */
162 SIGRTMIN+0, /* systemd: start default.target */
163 SIGRTMIN+1, /* systemd: start rescue.target */
164 SIGRTMIN+2, /* systemd: isolate emergency.target */
165 SIGRTMIN+3, /* systemd: start halt.target */
166 SIGRTMIN+4, /* systemd: start poweroff.target */
167 SIGRTMIN+5, /* systemd: start reboot.target */
169 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
171 m->signal_watch.type = WATCH_SIGNAL;
172 if ((m->signal_watch.fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0)
177 ev.data.ptr = &m->signal_watch;
179 if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->signal_watch.fd, &ev) < 0)
182 if (m->running_as == MANAGER_SYSTEM)
183 return enable_special_signals(m);
188 int manager_new(ManagerRunningAs running_as, Manager **_m) {
193 assert(running_as >= 0);
194 assert(running_as < _MANAGER_RUNNING_AS_MAX);
196 if (!(m = new0(Manager, 1)))
199 dual_timestamp_get(&m->startup_timestamp);
201 m->running_as = running_as;
202 m->name_data_slot = m->subscribed_data_slot = -1;
203 m->exit_code = _MANAGER_EXIT_CODE_INVALID;
204 m->pin_cgroupfs_fd = -1;
210 m->signal_watch.fd = m->mount_watch.fd = m->udev_watch.fd = m->epoll_fd = m->dev_autofs_fd = -1;
211 m->current_job_id = 1; /* start as id #1, so that we can leave #0 around as "null-like" value */
213 if (!(m->environment = strv_copy(environ)))
216 if (!(m->units = hashmap_new(string_hash_func, string_compare_func)))
219 if (!(m->jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
222 if (!(m->transaction_jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
225 if (!(m->watch_pids = hashmap_new(trivial_hash_func, trivial_compare_func)))
228 if (!(m->cgroup_bondings = hashmap_new(string_hash_func, string_compare_func)))
231 if (!(m->watch_bus = hashmap_new(string_hash_func, string_compare_func)))
234 if ((m->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0)
237 if ((r = lookup_paths_init(&m->lookup_paths, m->running_as)) < 0)
240 if ((r = manager_setup_signals(m)) < 0)
243 if ((r = manager_setup_cgroup(m)) < 0)
246 if ((r = manager_setup_notify(m)) < 0)
249 /* Try to connect to the busses, if possible. */
250 if ((r = bus_init(m)) < 0)
253 if ((m->audit_fd = audit_open()) < 0)
254 log_error("Failed to connect to audit log: %m");
264 static unsigned manager_dispatch_cleanup_queue(Manager *m) {
270 while ((meta = m->cleanup_queue)) {
271 assert(meta->in_cleanup_queue);
273 unit_free((Unit*) meta);
281 GC_OFFSET_IN_PATH, /* This one is on the path we were travelling */
282 GC_OFFSET_UNSURE, /* No clue */
283 GC_OFFSET_GOOD, /* We still need this unit */
284 GC_OFFSET_BAD, /* We don't need this unit anymore */
288 static void unit_gc_sweep(Unit *u, unsigned gc_marker) {
295 if (u->meta.gc_marker == gc_marker + GC_OFFSET_GOOD ||
296 u->meta.gc_marker == gc_marker + GC_OFFSET_BAD ||
297 u->meta.gc_marker == gc_marker + GC_OFFSET_IN_PATH)
300 if (u->meta.in_cleanup_queue)
303 if (unit_check_gc(u))
306 u->meta.gc_marker = gc_marker + GC_OFFSET_IN_PATH;
310 SET_FOREACH(other, u->meta.dependencies[UNIT_REFERENCED_BY], i) {
311 unit_gc_sweep(other, gc_marker);
313 if (other->meta.gc_marker == gc_marker + GC_OFFSET_GOOD)
316 if (other->meta.gc_marker != gc_marker + GC_OFFSET_BAD)
323 /* We were unable to find anything out about this entry, so
324 * let's investigate it later */
325 u->meta.gc_marker = gc_marker + GC_OFFSET_UNSURE;
326 unit_add_to_gc_queue(u);
330 /* We definitely know that this one is not useful anymore, so
331 * let's mark it for deletion */
332 u->meta.gc_marker = gc_marker + GC_OFFSET_BAD;
333 unit_add_to_cleanup_queue(u);
337 u->meta.gc_marker = gc_marker + GC_OFFSET_GOOD;
340 static unsigned manager_dispatch_gc_queue(Manager *m) {
347 if ((m->n_in_gc_queue < GC_QUEUE_ENTRIES_MAX) &&
348 (m->gc_queue_timestamp <= 0 ||
349 (m->gc_queue_timestamp + GC_QUEUE_USEC_MAX) > now(CLOCK_MONOTONIC)))
352 log_debug("Running GC...");
354 m->gc_marker += _GC_OFFSET_MAX;
355 if (m->gc_marker + _GC_OFFSET_MAX <= _GC_OFFSET_MAX)
358 gc_marker = m->gc_marker;
360 while ((meta = m->gc_queue)) {
361 assert(meta->in_gc_queue);
363 unit_gc_sweep((Unit*) meta, gc_marker);
365 LIST_REMOVE(Meta, gc_queue, m->gc_queue, meta);
366 meta->in_gc_queue = false;
370 if (meta->gc_marker == gc_marker + GC_OFFSET_BAD ||
371 meta->gc_marker == gc_marker + GC_OFFSET_UNSURE) {
372 log_debug("Collecting %s", meta->id);
373 meta->gc_marker = gc_marker + GC_OFFSET_BAD;
374 unit_add_to_cleanup_queue((Unit*) meta);
378 m->n_in_gc_queue = 0;
379 m->gc_queue_timestamp = 0;
384 static void manager_clear_jobs_and_units(Manager *m) {
390 while ((j = hashmap_first(m->transaction_jobs)))
393 while ((u = hashmap_first(m->units)))
396 manager_dispatch_cleanup_queue(m);
398 assert(!m->load_queue);
399 assert(!m->run_queue);
400 assert(!m->dbus_unit_queue);
401 assert(!m->dbus_job_queue);
402 assert(!m->cleanup_queue);
403 assert(!m->gc_queue);
405 assert(hashmap_isempty(m->transaction_jobs));
406 assert(hashmap_isempty(m->jobs));
407 assert(hashmap_isempty(m->units));
410 void manager_free(Manager *m) {
415 manager_clear_jobs_and_units(m);
417 for (c = 0; c < _UNIT_TYPE_MAX; c++)
418 if (unit_vtable[c]->shutdown)
419 unit_vtable[c]->shutdown(m);
421 /* If we reexecute ourselves, we keep the root cgroup
423 manager_shutdown_cgroup(m, m->exit_code != MANAGER_REEXECUTE);
427 hashmap_free(m->units);
428 hashmap_free(m->jobs);
429 hashmap_free(m->transaction_jobs);
430 hashmap_free(m->watch_pids);
431 hashmap_free(m->watch_bus);
433 if (m->epoll_fd >= 0)
434 close_nointr_nofail(m->epoll_fd);
435 if (m->signal_watch.fd >= 0)
436 close_nointr_nofail(m->signal_watch.fd);
437 if (m->notify_watch.fd >= 0)
438 close_nointr_nofail(m->notify_watch.fd);
441 if (m->audit_fd >= 0)
442 audit_close(m->audit_fd);
445 free(m->notify_socket);
447 lookup_paths_free(&m->lookup_paths);
448 strv_free(m->environment);
450 hashmap_free(m->cgroup_bondings);
451 set_free_free(m->unit_path_cache);
456 int manager_enumerate(Manager *m) {
462 /* Let's ask every type to load all units from disk/kernel
463 * that it might know */
464 for (c = 0; c < _UNIT_TYPE_MAX; c++)
465 if (unit_vtable[c]->enumerate)
466 if ((q = unit_vtable[c]->enumerate(m)) < 0)
469 manager_dispatch_load_queue(m);
473 int manager_coldplug(Manager *m) {
481 /* Then, let's set up their initial state. */
482 HASHMAP_FOREACH_KEY(u, k, m->units, i) {
488 if ((q = unit_coldplug(u)) < 0)
495 static void manager_build_unit_path_cache(Manager *m) {
502 set_free_free(m->unit_path_cache);
504 if (!(m->unit_path_cache = set_new(string_hash_func, string_compare_func))) {
505 log_error("Failed to allocate unit path cache.");
509 /* This simply builds a list of files we know exist, so that
510 * we don't always have to go to disk */
512 STRV_FOREACH(i, m->lookup_paths.unit_path) {
515 if (!(d = opendir(*i))) {
516 log_error("Failed to open directory: %m");
520 while ((de = readdir(d))) {
523 if (ignore_file(de->d_name))
526 if (asprintf(&p, "%s/%s", streq(*i, "/") ? "" : *i, de->d_name) < 0) {
531 if ((r = set_put(m->unit_path_cache, p)) < 0) {
544 log_error("Failed to build unit path cache: %s", strerror(-r));
546 set_free_free(m->unit_path_cache);
547 m->unit_path_cache = NULL;
553 int manager_startup(Manager *m, FILE *serialization, FDSet *fds) {
558 manager_build_unit_path_cache(m);
560 /* If we will deserialize make sure that during enumeration
561 * this is already known, so we increase the counter here
564 m->n_deserializing ++;
566 /* First, enumerate what we can from all config files */
567 r = manager_enumerate(m);
569 /* Second, deserialize if there is something to deserialize */
571 if ((q = manager_deserialize(m, serialization, fds)) < 0)
574 /* Third, fire things up! */
575 if ((q = manager_coldplug(m)) < 0)
579 assert(m->n_deserializing > 0);
580 m->n_deserializing --;
586 static void transaction_delete_job(Manager *m, Job *j, bool delete_dependencies) {
590 /* Deletes one job from the transaction */
592 manager_transaction_unlink_job(m, j, delete_dependencies);
598 static void transaction_delete_unit(Manager *m, Unit *u) {
601 /* Deletes all jobs associated with a certain unit from the
604 while ((j = hashmap_get(m->transaction_jobs, u)))
605 transaction_delete_job(m, j, true);
608 static void transaction_clean_dependencies(Manager *m) {
614 /* Drops all dependencies of all installed jobs */
616 HASHMAP_FOREACH(j, m->jobs, i) {
617 while (j->subject_list)
618 job_dependency_free(j->subject_list);
619 while (j->object_list)
620 job_dependency_free(j->object_list);
623 assert(!m->transaction_anchor);
626 static void transaction_abort(Manager *m) {
631 while ((j = hashmap_first(m->transaction_jobs)))
633 transaction_delete_job(m, j, true);
637 assert(hashmap_isempty(m->transaction_jobs));
639 transaction_clean_dependencies(m);
642 static void transaction_find_jobs_that_matter_to_anchor(Manager *m, Job *j, unsigned generation) {
647 /* A recursive sweep through the graph that marks all units
648 * that matter to the anchor job, i.e. are directly or
649 * indirectly a dependency of the anchor job via paths that
650 * are fully marked as mattering. */
655 l = m->transaction_anchor;
657 LIST_FOREACH(subject, l, l) {
659 /* This link does not matter */
663 /* This unit has already been marked */
664 if (l->object->generation == generation)
667 l->object->matters_to_anchor = true;
668 l->object->generation = generation;
670 transaction_find_jobs_that_matter_to_anchor(m, l->object, generation);
674 static void transaction_merge_and_delete_job(Manager *m, Job *j, Job *other, JobType t) {
675 JobDependency *l, *last;
679 assert(j->unit == other->unit);
680 assert(!j->installed);
682 /* Merges 'other' into 'j' and then deletes j. */
685 j->state = JOB_WAITING;
686 j->override = j->override || other->override;
688 j->matters_to_anchor = j->matters_to_anchor || other->matters_to_anchor;
690 /* Patch us in as new owner of the JobDependency objects */
692 LIST_FOREACH(subject, l, other->subject_list) {
693 assert(l->subject == other);
698 /* Merge both lists */
700 last->subject_next = j->subject_list;
702 j->subject_list->subject_prev = last;
703 j->subject_list = other->subject_list;
706 /* Patch us in as new owner of the JobDependency objects */
708 LIST_FOREACH(object, l, other->object_list) {
709 assert(l->object == other);
714 /* Merge both lists */
716 last->object_next = j->object_list;
718 j->object_list->object_prev = last;
719 j->object_list = other->object_list;
722 /* Kill the other job */
723 other->subject_list = NULL;
724 other->object_list = NULL;
725 transaction_delete_job(m, other, true);
727 static bool job_is_conflicted_by(Job *j) {
732 /* Returns true if this job is pulled in by a least one
733 * ConflictedBy dependency. */
735 LIST_FOREACH(object, l, j->object_list)
742 static int delete_one_unmergeable_job(Manager *m, Job *j) {
747 /* Tries to delete one item in the linked list
748 * j->transaction_next->transaction_next->... that conflicts
749 * whith another one, in an attempt to make an inconsistent
750 * transaction work. */
752 /* We rely here on the fact that if a merged with b does not
753 * merge with c, either a or b merge with c neither */
754 LIST_FOREACH(transaction, j, j)
755 LIST_FOREACH(transaction, k, j->transaction_next) {
758 /* Is this one mergeable? Then skip it */
759 if (job_type_is_mergeable(j->type, k->type))
762 /* Ok, we found two that conflict, let's see if we can
763 * drop one of them */
764 if (!j->matters_to_anchor && !k->matters_to_anchor) {
766 /* Both jobs don't matter, so let's
767 * find the one that is smarter to
768 * remove. Let's think positive and
769 * rather remove stops then starts --
770 * except if something is being
771 * stopped because it is conflicted by
772 * another unit in which case we
773 * rather remove the start. */
775 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)));
776 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)));
778 if (j->type == JOB_STOP) {
780 if (job_is_conflicted_by(j))
785 } else if (k->type == JOB_STOP) {
787 if (job_is_conflicted_by(k))
793 } else if (!j->matters_to_anchor)
795 else if (!k->matters_to_anchor)
800 /* Ok, we can drop one, so let's do so. */
801 log_debug("Fixing conflicting jobs by deleting job %s/%s", d->unit->meta.id, job_type_to_string(d->type));
802 transaction_delete_job(m, d, true);
809 static int transaction_merge_jobs(Manager *m, DBusError *e) {
816 /* First step, check whether any of the jobs for one specific
817 * task conflict. If so, try to drop one of them. */
818 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
823 LIST_FOREACH(transaction, k, j->transaction_next) {
824 if ((r = job_type_merge(&t, k->type)) >= 0)
827 /* OK, we could not merge all jobs for this
828 * action. Let's see if we can get rid of one
831 if ((r = delete_one_unmergeable_job(m, j)) >= 0)
832 /* Ok, we managed to drop one, now
833 * let's ask our callers to call us
834 * again after garbage collecting */
837 /* We couldn't merge anything. Failure */
838 dbus_set_error(e, BUS_ERROR_TRANSACTION_JOBS_CONFLICTING, "Transaction contains conflicting jobs '%s' and '%s' for %s. Probably contradicting requirement dependencies configured.",
839 job_type_to_string(t), job_type_to_string(k->type), k->unit->meta.id);
844 /* Second step, merge the jobs. */
845 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
849 /* Merge all transactions */
850 LIST_FOREACH(transaction, k, j->transaction_next)
851 assert_se(job_type_merge(&t, k->type) == 0);
853 /* If an active job is mergeable, merge it too */
854 if (j->unit->meta.job)
855 job_type_merge(&t, j->unit->meta.job->type); /* Might fail. Which is OK */
857 while ((k = j->transaction_next)) {
859 transaction_merge_and_delete_job(m, k, j, t);
862 transaction_merge_and_delete_job(m, j, k, t);
865 assert(!j->transaction_next);
866 assert(!j->transaction_prev);
872 static void transaction_drop_redundant(Manager *m) {
877 /* Goes through the transaction and removes all jobs that are
886 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
887 bool changes_something = false;
890 LIST_FOREACH(transaction, k, j) {
892 if (!job_is_anchor(k) &&
893 job_type_is_redundant(k->type, unit_active_state(k->unit)))
896 changes_something = true;
900 if (changes_something)
903 log_debug("Found redundant job %s/%s, dropping.", j->unit->meta.id, job_type_to_string(j->type));
904 transaction_delete_job(m, j, false);
912 static bool unit_matters_to_anchor(Unit *u, Job *j) {
914 assert(!j->transaction_prev);
916 /* Checks whether at least one of the jobs for this unit
917 * matters to the anchor. */
919 LIST_FOREACH(transaction, j, j)
920 if (j->matters_to_anchor)
926 static int transaction_verify_order_one(Manager *m, Job *j, Job *from, unsigned generation, DBusError *e) {
933 assert(!j->transaction_prev);
935 /* Does a recursive sweep through the ordering graph, looking
936 * for a cycle. If we find cycle we try to break it. */
938 /* Have we seen this before? */
939 if (j->generation == generation) {
942 /* If the marker is NULL we have been here already and
943 * decided the job was loop-free from here. Hence
944 * shortcut things and return right-away. */
948 /* So, the marker is not NULL and we already have been
949 * here. We have a cycle. Let's try to break it. We go
950 * backwards in our path and try to find a suitable
951 * job to remove. We use the marker to find our way
952 * back, since smart how we are we stored our way back
954 log_warning("Found ordering cycle on %s/%s", j->unit->meta.id, job_type_to_string(j->type));
957 for (k = from; k; k = ((k->generation == generation && k->marker != k) ? k->marker : NULL)) {
959 log_info("Walked on cycle path to %s/%s", k->unit->meta.id, job_type_to_string(k->type));
963 !unit_matters_to_anchor(k->unit, k)) {
964 /* Ok, we can drop this one, so let's
969 /* Check if this in fact was the beginning of
977 log_warning("Breaking ordering cycle by deleting job %s/%s", k->unit->meta.id, job_type_to_string(k->type));
978 transaction_delete_unit(m, delete->unit);
982 log_error("Unable to break cycle");
984 dbus_set_error(e, BUS_ERROR_TRANSACTION_ORDER_IS_CYCLIC, "Transaction order is cyclic. See logs for details.");
988 /* Make the marker point to where we come from, so that we can
989 * find our way backwards if we want to break a cycle. We use
990 * a special marker for the beginning: we point to
992 j->marker = from ? from : j;
993 j->generation = generation;
995 /* We assume that the the dependencies are bidirectional, and
996 * hence can ignore UNIT_AFTER */
997 SET_FOREACH(u, j->unit->meta.dependencies[UNIT_BEFORE], i) {
1000 /* Is there a job for this unit? */
1001 if (!(o = hashmap_get(m->transaction_jobs, u)))
1003 /* Ok, there is no job for this in the
1004 * transaction, but maybe there is already one
1006 if (!(o = u->meta.job))
1009 if ((r = transaction_verify_order_one(m, o, j, generation, e)) < 0)
1013 /* Ok, let's backtrack, and remember that this entry is not on
1014 * our path anymore. */
1020 static int transaction_verify_order(Manager *m, unsigned *generation, DBusError *e) {
1029 /* Check if the ordering graph is cyclic. If it is, try to fix
1030 * that up by dropping one of the jobs. */
1032 g = (*generation)++;
1034 HASHMAP_FOREACH(j, m->transaction_jobs, i)
1035 if ((r = transaction_verify_order_one(m, j, NULL, g, e)) < 0)
1041 static void transaction_collect_garbage(Manager *m) {
1046 /* Drop jobs that are not required by any other job */
1054 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1058 log_debug("Garbage collecting job %s/%s", j->unit->meta.id, job_type_to_string(j->type));
1059 transaction_delete_job(m, j, true);
1067 static int transaction_is_destructive(Manager *m, DBusError *e) {
1073 /* Checks whether applying this transaction means that
1074 * existing jobs would be replaced */
1076 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1079 assert(!j->transaction_prev);
1080 assert(!j->transaction_next);
1082 if (j->unit->meta.job &&
1083 j->unit->meta.job != j &&
1084 !job_type_is_superset(j->type, j->unit->meta.job->type)) {
1086 dbus_set_error(e, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE, "Transaction is destructive.");
1094 static void transaction_minimize_impact(Manager *m) {
1098 /* Drops all unnecessary jobs that reverse already active jobs
1099 * or that stop a running service. */
1107 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1108 LIST_FOREACH(transaction, j, j) {
1109 bool stops_running_service, changes_existing_job;
1111 /* If it matters, we shouldn't drop it */
1112 if (j->matters_to_anchor)
1115 /* Would this stop a running service?
1116 * Would this change an existing job?
1117 * If so, let's drop this entry */
1119 stops_running_service =
1120 j->type == JOB_STOP && UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(j->unit));
1122 changes_existing_job =
1123 j->unit->meta.job && job_type_is_conflicting(j->type, j->unit->meta.job->type);
1125 if (!stops_running_service && !changes_existing_job)
1128 if (stops_running_service)
1129 log_info("%s/%s would stop a running service.", j->unit->meta.id, job_type_to_string(j->type));
1131 if (changes_existing_job)
1132 log_info("%s/%s would change existing job.", j->unit->meta.id, job_type_to_string(j->type));
1134 /* Ok, let's get rid of this */
1135 log_info("Deleting %s/%s to minimize impact.", j->unit->meta.id, job_type_to_string(j->type));
1137 transaction_delete_job(m, j, true);
1149 static int transaction_apply(Manager *m) {
1154 /* Moves the transaction jobs to the set of active jobs */
1156 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1158 assert(!j->transaction_prev);
1159 assert(!j->transaction_next);
1164 if ((r = hashmap_put(m->jobs, UINT32_TO_PTR(j->id), j)) < 0)
1168 while ((j = hashmap_steal_first(m->transaction_jobs))) {
1172 if (j->unit->meta.job)
1173 job_free(j->unit->meta.job);
1175 j->unit->meta.job = j;
1176 j->installed = true;
1178 /* We're fully installed. Now let's free data we don't
1181 assert(!j->transaction_next);
1182 assert(!j->transaction_prev);
1184 job_add_to_run_queue(j);
1185 job_add_to_dbus_queue(j);
1189 /* As last step, kill all remaining job dependencies. */
1190 transaction_clean_dependencies(m);
1196 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1200 hashmap_remove(m->jobs, UINT32_TO_PTR(j->id));
1206 static int transaction_activate(Manager *m, JobMode mode, DBusError *e) {
1208 unsigned generation = 1;
1212 /* This applies the changes recorded in transaction_jobs to
1213 * the actual list of jobs, if possible. */
1215 /* First step: figure out which jobs matter */
1216 transaction_find_jobs_that_matter_to_anchor(m, NULL, generation++);
1218 /* Second step: Try not to stop any running services if
1219 * we don't have to. Don't try to reverse running
1220 * jobs if we don't have to. */
1221 transaction_minimize_impact(m);
1223 /* Third step: Drop redundant jobs */
1224 transaction_drop_redundant(m);
1227 /* Fourth step: Let's remove unneeded jobs that might
1229 transaction_collect_garbage(m);
1231 /* Fifth step: verify order makes sense and correct
1232 * cycles if necessary and possible */
1233 if ((r = transaction_verify_order(m, &generation, e)) >= 0)
1237 log_warning("Requested transaction contains an unfixable cyclic ordering dependency: %s", bus_error(e, r));
1241 /* Let's see if the resulting transaction ordering
1242 * graph is still cyclic... */
1246 /* Sixth step: let's drop unmergeable entries if
1247 * necessary and possible, merge entries we can
1249 if ((r = transaction_merge_jobs(m, e)) >= 0)
1253 log_warning("Requested transaction contains unmergable jobs: %s", bus_error(e, r));
1257 /* Seventh step: an entry got dropped, let's garbage
1258 * collect its dependencies. */
1259 transaction_collect_garbage(m);
1261 /* Let's see if the resulting transaction still has
1262 * unmergeable entries ... */
1265 /* Eights step: Drop redundant jobs again, if the merging now allows us to drop more. */
1266 transaction_drop_redundant(m);
1268 /* Ninth step: check whether we can actually apply this */
1269 if (mode == JOB_FAIL)
1270 if ((r = transaction_is_destructive(m, e)) < 0) {
1271 log_notice("Requested transaction contradicts existing jobs: %s", bus_error(e, r));
1275 /* Tenth step: apply changes */
1276 if ((r = transaction_apply(m)) < 0) {
1277 log_warning("Failed to apply transaction: %s", strerror(-r));
1281 assert(hashmap_isempty(m->transaction_jobs));
1282 assert(!m->transaction_anchor);
1287 transaction_abort(m);
1291 static Job* transaction_add_one_job(Manager *m, JobType type, Unit *unit, bool override, bool *is_new) {
1298 /* Looks for an axisting prospective job and returns that. If
1299 * it doesn't exist it is created and added to the prospective
1302 f = hashmap_get(m->transaction_jobs, unit);
1304 LIST_FOREACH(transaction, j, f) {
1305 assert(j->unit == unit);
1307 if (j->type == type) {
1314 if (unit->meta.job && unit->meta.job->type == type)
1316 else if (!(j = job_new(m, type, unit)))
1321 j->matters_to_anchor = false;
1322 j->override = override;
1324 LIST_PREPEND(Job, transaction, f, j);
1326 if ((r = hashmap_replace(m->transaction_jobs, unit, f)) < 0) {
1334 log_debug("Added job %s/%s to transaction.", unit->meta.id, job_type_to_string(type));
1339 void manager_transaction_unlink_job(Manager *m, Job *j, bool delete_dependencies) {
1343 if (j->transaction_prev)
1344 j->transaction_prev->transaction_next = j->transaction_next;
1345 else if (j->transaction_next)
1346 hashmap_replace(m->transaction_jobs, j->unit, j->transaction_next);
1348 hashmap_remove_value(m->transaction_jobs, j->unit, j);
1350 if (j->transaction_next)
1351 j->transaction_next->transaction_prev = j->transaction_prev;
1353 j->transaction_prev = j->transaction_next = NULL;
1355 while (j->subject_list)
1356 job_dependency_free(j->subject_list);
1358 while (j->object_list) {
1359 Job *other = j->object_list->matters ? j->object_list->subject : NULL;
1361 job_dependency_free(j->object_list);
1363 if (other && delete_dependencies) {
1364 log_debug("Deleting job %s/%s as dependency of job %s/%s",
1365 other->unit->meta.id, job_type_to_string(other->type),
1366 j->unit->meta.id, job_type_to_string(j->type));
1367 transaction_delete_job(m, other, delete_dependencies);
1372 static int transaction_add_job_and_dependencies(
1389 assert(type < _JOB_TYPE_MAX);
1392 if (type != JOB_STOP &&
1393 unit->meta.load_state != UNIT_LOADED) {
1394 dbus_set_error(e, BUS_ERROR_LOAD_FAILED, "Unit %s failed to load. See logs for details.", unit->meta.id);
1398 if (!unit_job_is_applicable(unit, type)) {
1399 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);
1403 /* First add the job. */
1404 if (!(ret = transaction_add_one_job(m, type, unit, override, &is_new)))
1407 /* Then, add a link to the job. */
1408 if (!job_dependency_new(by, ret, matters, conflicts))
1412 /* Finally, recursively add in all dependencies. */
1413 if (type == JOB_START || type == JOB_RELOAD_OR_START) {
1414 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES], i)
1415 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, true, override, false, e, NULL)) < 0 && r != -EBADR)
1418 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES_OVERRIDABLE], i)
1419 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, !override, override, false, e, NULL)) < 0 && r != -EBADR) {
1420 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, bus_error(e, r));
1424 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_WANTS], i)
1425 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, false, false, false, e, NULL)) < 0) {
1426 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, bus_error(e, r));
1430 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE], i)
1431 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, true, override, false, e, NULL)) < 0 && r != -EBADR)
1434 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE_OVERRIDABLE], i)
1435 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, !override, override, false, e, NULL)) < 0 && r != -EBADR) {
1436 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, bus_error(e, r));
1440 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_CONFLICTS], i)
1441 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, dep, ret, true, override, true, e, NULL)) < 0 && r != -EBADR)
1444 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_CONFLICTED_BY], i)
1445 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, dep, ret, true, override, false, e, NULL)) < 0 && r != -EBADR)
1448 } else if (type == JOB_STOP || type == JOB_RESTART || type == JOB_TRY_RESTART) {
1450 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRED_BY], i)
1451 if ((r = transaction_add_job_and_dependencies(m, type, dep, ret, true, override, false, e, NULL)) < 0 && r != -EBADR)
1455 /* JOB_VERIFY_STARTED, JOB_RELOAD require no dependency handling */
1467 static int transaction_add_isolate_jobs(Manager *m) {
1475 HASHMAP_FOREACH_KEY(u, k, m->units, i) {
1477 /* ignore aliases */
1478 if (u->meta.id != k)
1481 if (UNIT_VTABLE(u)->no_isolate)
1484 /* No need to stop inactive jobs */
1485 if (UNIT_IS_INACTIVE_OR_MAINTENANCE(unit_active_state(u)))
1488 /* Is there already something listed for this? */
1489 if (hashmap_get(m->transaction_jobs, u))
1492 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, u, NULL, true, false, false, NULL, NULL)) < 0)
1493 log_warning("Cannot add isolate job for unit %s, ignoring: %s", u->meta.id, strerror(-r));
1499 int manager_add_job(Manager *m, JobType type, Unit *unit, JobMode mode, bool override, DBusError *e, Job **_ret) {
1504 assert(type < _JOB_TYPE_MAX);
1506 assert(mode < _JOB_MODE_MAX);
1508 if (mode == JOB_ISOLATE && type != JOB_START) {
1509 dbus_set_error(e, BUS_ERROR_INVALID_JOB_MODE, "Isolate is only valid for start.");
1513 log_debug("Trying to enqueue job %s/%s", unit->meta.id, job_type_to_string(type));
1515 if ((r = transaction_add_job_and_dependencies(m, type, unit, NULL, true, override, false, e, &ret)) < 0) {
1516 transaction_abort(m);
1520 if (mode == JOB_ISOLATE)
1521 if ((r = transaction_add_isolate_jobs(m)) < 0) {
1522 transaction_abort(m);
1526 if ((r = transaction_activate(m, mode, e)) < 0)
1529 log_debug("Enqueued job %s/%s as %u", unit->meta.id, job_type_to_string(type), (unsigned) ret->id);
1537 int manager_add_job_by_name(Manager *m, JobType type, const char *name, JobMode mode, bool override, DBusError *e, Job **_ret) {
1542 assert(type < _JOB_TYPE_MAX);
1544 assert(mode < _JOB_MODE_MAX);
1546 if ((r = manager_load_unit(m, name, NULL, NULL, &unit)) < 0)
1549 return manager_add_job(m, type, unit, mode, override, e, _ret);
1552 Job *manager_get_job(Manager *m, uint32_t id) {
1555 return hashmap_get(m->jobs, UINT32_TO_PTR(id));
1558 Unit *manager_get_unit(Manager *m, const char *name) {
1562 return hashmap_get(m->units, name);
1565 unsigned manager_dispatch_load_queue(Manager *m) {
1571 /* Make sure we are not run recursively */
1572 if (m->dispatching_load_queue)
1575 m->dispatching_load_queue = true;
1577 /* Dispatches the load queue. Takes a unit from the queue and
1578 * tries to load its data until the queue is empty */
1580 while ((meta = m->load_queue)) {
1581 assert(meta->in_load_queue);
1583 unit_load((Unit*) meta);
1587 m->dispatching_load_queue = false;
1591 int manager_load_unit_prepare(Manager *m, const char *name, const char *path, DBusError *e, Unit **_ret) {
1596 assert(name || path);
1598 /* This will prepare the unit for loading, but not actually
1599 * load anything from disk. */
1601 if (path && !is_path(path)) {
1602 dbus_set_error(e, BUS_ERROR_INVALID_PATH, "Path %s is not absolute.", path);
1607 name = file_name_from_path(path);
1609 if (!unit_name_is_valid(name)) {
1610 dbus_set_error(e, BUS_ERROR_INVALID_NAME, "Unit name %s is not valid.", name);
1614 if ((ret = manager_get_unit(m, name))) {
1619 if (!(ret = unit_new(m)))
1623 if (!(ret->meta.fragment_path = strdup(path))) {
1628 if ((r = unit_add_name(ret, name)) < 0) {
1633 unit_add_to_load_queue(ret);
1634 unit_add_to_dbus_queue(ret);
1635 unit_add_to_gc_queue(ret);
1643 int manager_load_unit(Manager *m, const char *name, const char *path, DBusError *e, Unit **_ret) {
1648 /* This will load the service information files, but not actually
1649 * start any services or anything. */
1651 if ((r = manager_load_unit_prepare(m, name, path, e, _ret)) != 0)
1654 manager_dispatch_load_queue(m);
1657 *_ret = unit_follow_merge(*_ret);
1662 void manager_dump_jobs(Manager *s, FILE *f, const char *prefix) {
1669 HASHMAP_FOREACH(j, s->jobs, i)
1670 job_dump(j, f, prefix);
1673 void manager_dump_units(Manager *s, FILE *f, const char *prefix) {
1681 HASHMAP_FOREACH_KEY(u, t, s->units, i)
1682 if (u->meta.id == t)
1683 unit_dump(u, f, prefix);
1686 void manager_clear_jobs(Manager *m) {
1691 transaction_abort(m);
1693 while ((j = hashmap_first(m->jobs)))
1697 unsigned manager_dispatch_run_queue(Manager *m) {
1701 if (m->dispatching_run_queue)
1704 m->dispatching_run_queue = true;
1706 while ((j = m->run_queue)) {
1707 assert(j->installed);
1708 assert(j->in_run_queue);
1710 job_run_and_invalidate(j);
1714 m->dispatching_run_queue = false;
1718 unsigned manager_dispatch_dbus_queue(Manager *m) {
1725 if (m->dispatching_dbus_queue)
1728 m->dispatching_dbus_queue = true;
1730 while ((meta = m->dbus_unit_queue)) {
1731 assert(meta->in_dbus_queue);
1733 bus_unit_send_change_signal((Unit*) meta);
1737 while ((j = m->dbus_job_queue)) {
1738 assert(j->in_dbus_queue);
1740 bus_job_send_change_signal(j);
1744 m->dispatching_dbus_queue = false;
1748 static int manager_process_notify_fd(Manager *m) {
1755 struct msghdr msghdr;
1757 struct ucred *ucred;
1759 struct cmsghdr cmsghdr;
1760 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
1766 iovec.iov_base = buf;
1767 iovec.iov_len = sizeof(buf)-1;
1771 msghdr.msg_iov = &iovec;
1772 msghdr.msg_iovlen = 1;
1773 msghdr.msg_control = &control;
1774 msghdr.msg_controllen = sizeof(control);
1776 if ((n = recvmsg(m->notify_watch.fd, &msghdr, MSG_DONTWAIT)) <= 0) {
1780 if (errno == EAGAIN)
1786 if (msghdr.msg_controllen < CMSG_LEN(sizeof(struct ucred)) ||
1787 control.cmsghdr.cmsg_level != SOL_SOCKET ||
1788 control.cmsghdr.cmsg_type != SCM_CREDENTIALS ||
1789 control.cmsghdr.cmsg_len != CMSG_LEN(sizeof(struct ucred))) {
1790 log_warning("Received notify message without credentials. Ignoring.");
1794 ucred = (struct ucred*) CMSG_DATA(&control.cmsghdr);
1796 if (!(u = hashmap_get(m->watch_pids, LONG_TO_PTR(ucred->pid))))
1797 if (!(u = cgroup_unit_by_pid(m, ucred->pid))) {
1798 log_warning("Cannot find unit for notify message of PID %lu.", (unsigned long) ucred->pid);
1802 assert((size_t) n < sizeof(buf));
1804 if (!(tags = strv_split(buf, "\n\r")))
1807 log_debug("Got notification message for unit %s", u->meta.id);
1809 if (UNIT_VTABLE(u)->notify_message)
1810 UNIT_VTABLE(u)->notify_message(u, ucred->pid, tags);
1818 static int manager_dispatch_sigchld(Manager *m) {
1828 /* First we call waitd() for a PID and do not reap the
1829 * zombie. That way we can still access /proc/$PID for
1830 * it while it is a zombie. */
1831 if (waitid(P_ALL, 0, &si, WEXITED|WNOHANG|WNOWAIT) < 0) {
1833 if (errno == ECHILD)
1845 if (si.si_code == CLD_EXITED || si.si_code == CLD_KILLED || si.si_code == CLD_DUMPED) {
1848 get_process_name(si.si_pid, &name);
1849 log_debug("Got SIGCHLD for process %lu (%s)", (unsigned long) si.si_pid, strna(name));
1853 /* Let's flush any message the dying child might still
1854 * have queued for us. This ensures that the process
1855 * still exists in /proc so that we can figure out
1856 * which cgroup and hence unit it belongs to. */
1857 if ((r = manager_process_notify_fd(m)) < 0)
1860 /* And now figure out the unit this belongs to */
1861 if (!(u = hashmap_get(m->watch_pids, LONG_TO_PTR(si.si_pid))))
1862 u = cgroup_unit_by_pid(m, si.si_pid);
1864 /* And now, we actually reap the zombie. */
1865 if (waitid(P_PID, si.si_pid, &si, WEXITED) < 0) {
1872 if (si.si_code != CLD_EXITED && si.si_code != CLD_KILLED && si.si_code != CLD_DUMPED)
1875 log_debug("Child %lu died (code=%s, status=%i/%s)",
1876 (long unsigned) si.si_pid,
1877 sigchld_code_to_string(si.si_code),
1879 strna(si.si_code == CLD_EXITED ? exit_status_to_string(si.si_status) : signal_to_string(si.si_status)));
1884 log_debug("Child %lu belongs to %s", (long unsigned) si.si_pid, u->meta.id);
1886 hashmap_remove(m->watch_pids, LONG_TO_PTR(si.si_pid));
1887 UNIT_VTABLE(u)->sigchld_event(u, si.si_pid, si.si_code, si.si_status);
1893 static int manager_start_target(Manager *m, const char *name, JobMode mode) {
1897 dbus_error_init(&error);
1899 log_info("Activating special unit %s", name);
1901 if ((r = manager_add_job_by_name(m, JOB_START, name, mode, true, &error, NULL)) < 0)
1902 log_error("Failed to enqueue %s job: %s", name, bus_error(&error, r));
1904 dbus_error_free(&error);
1909 static int manager_process_signal_fd(Manager *m) {
1911 struct signalfd_siginfo sfsi;
1912 bool sigchld = false;
1917 if ((n = read(m->signal_watch.fd, &sfsi, sizeof(sfsi))) != sizeof(sfsi)) {
1922 if (errno == EAGAIN)
1928 log_debug("Received SIG%s", strna(signal_to_string(sfsi.ssi_signo)));
1930 switch (sfsi.ssi_signo) {
1937 if (m->running_as == MANAGER_SYSTEM) {
1938 /* This is for compatibility with the
1939 * original sysvinit */
1940 m->exit_code = MANAGER_REEXECUTE;
1947 if (m->running_as == MANAGER_SYSTEM) {
1948 manager_start_target(m, SPECIAL_CTRL_ALT_DEL_TARGET, JOB_REPLACE);
1952 /* Run the exit target if there is one, if not, just exit. */
1953 if (manager_start_target(m, SPECIAL_EXIT_SERVICE, JOB_REPLACE) < 0) {
1954 m->exit_code = MANAGER_EXIT;
1961 if (m->running_as == MANAGER_SYSTEM)
1962 manager_start_target(m, SPECIAL_KBREQUEST_TARGET, JOB_REPLACE);
1964 /* This is a nop on non-init */
1968 if (m->running_as == MANAGER_SYSTEM)
1969 manager_start_target(m, SPECIAL_SIGPWR_TARGET, JOB_REPLACE);
1971 /* This is a nop on non-init */
1977 u = manager_get_unit(m, SPECIAL_DBUS_SERVICE);
1979 if (!u || UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u))) {
1980 log_info("Trying to reconnect to bus...");
1984 if (!u || !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u))) {
1985 log_info("Loading D-Bus service...");
1986 manager_start_target(m, SPECIAL_DBUS_SERVICE, JOB_REPLACE);
1997 if (!(f = open_memstream(&dump, &size))) {
1998 log_warning("Failed to allocate memory stream.");
2002 manager_dump_units(m, f, "\t");
2003 manager_dump_jobs(m, f, "\t");
2008 log_warning("Failed to write status stream");
2013 log_dump(LOG_INFO, dump);
2020 m->exit_code = MANAGER_RELOAD;
2024 static const char * const table[] = {
2025 [0] = SPECIAL_DEFAULT_TARGET,
2026 [1] = SPECIAL_RESCUE_TARGET,
2027 [2] = SPECIAL_EMERGENCY_TARGET,
2028 [3] = SPECIAL_HALT_TARGET,
2029 [4] = SPECIAL_POWEROFF_TARGET,
2030 [5] = SPECIAL_REBOOT_TARGET
2033 if ((int) sfsi.ssi_signo >= SIGRTMIN+0 &&
2034 (int) sfsi.ssi_signo < SIGRTMIN+(int) ELEMENTSOF(table)) {
2035 manager_start_target(m, table[sfsi.ssi_signo - SIGRTMIN],
2036 (sfsi.ssi_signo == 1 || sfsi.ssi_signo == 2) ? JOB_ISOLATE : JOB_REPLACE);
2040 log_warning("Got unhandled signal <%s>.", strna(signal_to_string(sfsi.ssi_signo)));
2046 return manager_dispatch_sigchld(m);
2051 static int process_event(Manager *m, struct epoll_event *ev) {
2058 assert(w = ev->data.ptr);
2064 /* An incoming signal? */
2065 if (ev->events != EPOLLIN)
2068 if ((r = manager_process_signal_fd(m)) < 0)
2075 /* An incoming daemon notification event? */
2076 if (ev->events != EPOLLIN)
2079 if ((r = manager_process_notify_fd(m)) < 0)
2086 /* Some fd event, to be dispatched to the units */
2087 UNIT_VTABLE(w->data.unit)->fd_event(w->data.unit, w->fd, ev->events, w);
2090 case WATCH_UNIT_TIMER:
2091 case WATCH_JOB_TIMER: {
2095 /* Some timer event, to be dispatched to the units */
2096 if ((k = read(w->fd, &v, sizeof(v))) != sizeof(v)) {
2098 if (k < 0 && (errno == EINTR || errno == EAGAIN))
2101 return k < 0 ? -errno : -EIO;
2104 if (w->type == WATCH_UNIT_TIMER)
2105 UNIT_VTABLE(w->data.unit)->timer_event(w->data.unit, v, w);
2107 job_timer_event(w->data.job, v, w);
2112 /* Some mount table change, intended for the mount subsystem */
2113 mount_fd_event(m, ev->events);
2117 /* Some notification from udev, intended for the device subsystem */
2118 device_fd_event(m, ev->events);
2121 case WATCH_DBUS_WATCH:
2122 bus_watch_event(m, w, ev->events);
2125 case WATCH_DBUS_TIMEOUT:
2126 bus_timeout_event(m, w, ev->events);
2130 assert_not_reached("Unknown epoll event type.");
2136 int manager_loop(Manager *m) {
2139 RATELIMIT_DEFINE(rl, 1*USEC_PER_SEC, 1000);
2142 m->exit_code = MANAGER_RUNNING;
2144 /* Release the path cache */
2145 set_free_free(m->unit_path_cache);
2146 m->unit_path_cache = NULL;
2148 /* There might still be some zombies hanging around from
2149 * before we were exec()'ed. Leat's reap them */
2150 if ((r = manager_dispatch_sigchld(m)) < 0)
2153 while (m->exit_code == MANAGER_RUNNING) {
2154 struct epoll_event event;
2157 if (!ratelimit_test(&rl)) {
2158 /* Yay, something is going seriously wrong, pause a little */
2159 log_warning("Looping too fast. Throttling execution a little.");
2163 if (manager_dispatch_load_queue(m) > 0)
2166 if (manager_dispatch_run_queue(m) > 0)
2169 if (bus_dispatch(m) > 0)
2172 if (manager_dispatch_cleanup_queue(m) > 0)
2175 if (manager_dispatch_gc_queue(m) > 0)
2178 if (manager_dispatch_dbus_queue(m) > 0)
2181 if ((n = epoll_wait(m->epoll_fd, &event, 1, -1)) < 0) {
2191 if ((r = process_event(m, &event)) < 0)
2195 return m->exit_code;
2198 int manager_get_unit_from_dbus_path(Manager *m, const char *s, Unit **_u) {
2206 if (!startswith(s, "/org/freedesktop/systemd1/unit/"))
2209 if (!(n = bus_path_unescape(s+31)))
2212 u = manager_get_unit(m, n);
2223 int manager_get_job_from_dbus_path(Manager *m, const char *s, Job **_j) {
2232 if (!startswith(s, "/org/freedesktop/systemd1/job/"))
2235 if ((r = safe_atou(s + 30, &id)) < 0)
2238 if (!(j = manager_get_job(m, id)))
2246 void manager_send_unit_audit(Manager *m, Unit *u, int type, bool success) {
2251 if (m->audit_fd < 0)
2254 if (!(p = unit_name_to_prefix_and_instance(u->meta.id))) {
2255 log_error("Failed to allocate unit name for audit message: %s", strerror(ENOMEM));
2259 if (audit_log_user_comm_message(m->audit_fd, type, "", p, NULL, NULL, NULL, success) < 0)
2260 log_error("Failed to send audit message: %m");
2267 void manager_dispatch_bus_name_owner_changed(
2270 const char* old_owner,
2271 const char *new_owner) {
2278 if (!(u = hashmap_get(m->watch_bus, name)))
2281 UNIT_VTABLE(u)->bus_name_owner_change(u, name, old_owner, new_owner);
2284 void manager_dispatch_bus_query_pid_done(
2295 if (!(u = hashmap_get(m->watch_bus, name)))
2298 UNIT_VTABLE(u)->bus_query_pid_done(u, name, pid);
2301 int manager_open_serialization(Manager *m, FILE **_f) {
2309 if (m->running_as == MANAGER_SYSTEM) {
2310 mkdir_p("/dev/.systemd", 0755);
2312 if (asprintf(&path, "/dev/.systemd/dump-%lu-XXXXXX", (unsigned long) getpid()) < 0)
2315 if (asprintf(&path, "/tmp/systemd-dump-%lu-XXXXXX", (unsigned long) getpid()) < 0)
2319 saved_umask = umask(0077);
2320 fd = mkostemp(path, O_RDWR|O_CLOEXEC);
2330 log_debug("Serializing state to %s", path);
2333 if (!(f = fdopen(fd, "w+")) < 0)
2341 int manager_serialize(Manager *m, FILE *f, FDSet *fds) {
2351 HASHMAP_FOREACH_KEY(u, t, m->units, i) {
2352 if (u->meta.id != t)
2355 if (!unit_can_serialize(u))
2359 fputs(u->meta.id, f);
2362 if ((r = unit_serialize(u, f, fds)) < 0)
2372 int manager_deserialize(Manager *m, FILE *f, FDSet *fds) {
2378 log_debug("Deserializing state...");
2380 m->n_deserializing ++;
2384 char name[UNIT_NAME_MAX+2];
2387 if (!fgets(name, sizeof(name), f)) {
2397 if ((r = manager_load_unit(m, strstrip(name), NULL, NULL, &u)) < 0)
2400 if ((r = unit_deserialize(u, f, fds)) < 0)
2412 assert(m->n_deserializing > 0);
2413 m->n_deserializing --;
2418 int manager_reload(Manager *m) {
2425 if ((r = manager_open_serialization(m, &f)) < 0)
2428 if (!(fds = fdset_new())) {
2433 if ((r = manager_serialize(m, f, fds)) < 0)
2436 if (fseeko(f, 0, SEEK_SET) < 0) {
2441 /* From here on there is no way back. */
2442 manager_clear_jobs_and_units(m);
2444 /* Find new unit paths */
2445 lookup_paths_free(&m->lookup_paths);
2446 if ((q = lookup_paths_init(&m->lookup_paths, m->running_as)) < 0)
2449 m->n_deserializing ++;
2451 /* First, enumerate what we can from all config files */
2452 if ((q = manager_enumerate(m)) < 0)
2455 /* Second, deserialize our stored data */
2456 if ((q = manager_deserialize(m, f, fds)) < 0)
2462 /* Third, fire things up! */
2463 if ((q = manager_coldplug(m)) < 0)
2466 assert(m->n_deserializing > 0);
2467 m->n_deserializing ++;
2479 bool manager_is_booting_or_shutting_down(Manager *m) {
2484 /* Is the initial job still around? */
2485 if (manager_get_job(m, 1))
2488 /* Is there a job for the shutdown target? */
2489 if (((u = manager_get_unit(m, SPECIAL_SHUTDOWN_TARGET))))
2490 return !!u->meta.job;
2495 void manager_reset_maintenance(Manager *m) {
2501 HASHMAP_FOREACH(u, m->units, i)
2502 unit_reset_maintenance(u);
2505 static const char* const manager_running_as_table[_MANAGER_RUNNING_AS_MAX] = {
2506 [MANAGER_SYSTEM] = "system",
2507 [MANAGER_SESSION] = "session"
2510 DEFINE_STRING_TABLE_LOOKUP(manager_running_as, ManagerRunningAs);