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>
46 #include "ratelimit.h"
48 #include "mount-setup.h"
49 #include "utmp-wtmp.h"
50 #include "unit-name.h"
51 #include "dbus-unit.h"
54 #include "path-lookup.h"
56 #include "bus-errors.h"
58 /* As soon as 16 units are in our GC queue, make sure to run a gc sweep */
59 #define GC_QUEUE_ENTRIES_MAX 16
61 /* As soon as 5s passed since a unit was added to our GC queue, make sure to run a gc sweep */
62 #define GC_QUEUE_USEC_MAX (10*USEC_PER_SEC)
64 /* Where clients shall send notification messages to */
65 #define NOTIFY_SOCKET "/org/freedesktop/systemd1/notify"
67 static int manager_setup_notify(Manager *m) {
70 struct sockaddr_un un;
72 struct epoll_event ev;
77 m->notify_watch.type = WATCH_NOTIFY;
78 if ((m->notify_watch.fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0)) < 0) {
79 log_error("Failed to allocate notification socket: %m");
84 sa.sa.sa_family = AF_UNIX;
87 snprintf(sa.un.sun_path+1, sizeof(sa.un.sun_path)-1, NOTIFY_SOCKET "/%llu", random_ull());
89 strncpy(sa.un.sun_path+1, NOTIFY_SOCKET, sizeof(sa.un.sun_path)-1);
91 if (bind(m->notify_watch.fd, &sa.sa, sizeof(sa)) < 0) {
92 log_error("bind() failed: %m");
96 if (setsockopt(m->notify_watch.fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one)) < 0) {
97 log_error("SO_PASSCRED failed: %m");
103 ev.data.ptr = &m->notify_watch;
105 if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->notify_watch.fd, &ev) < 0)
108 if (!(m->notify_socket = strdup(sa.un.sun_path+1)))
114 static int enable_special_signals(Manager *m) {
119 /* Enable that we get SIGINT on control-alt-del */
120 if (reboot(RB_DISABLE_CAD) < 0)
121 log_warning("Failed to enable ctrl-alt-del handling: %m");
123 if ((fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY)) < 0)
124 log_warning("Failed to open /dev/tty0: %m");
126 /* Enable that we get SIGWINCH on kbrequest */
127 if (ioctl(fd, KDSIGACCEPT, SIGWINCH) < 0)
128 log_warning("Failed to enable kbrequest handling: %s", strerror(errno));
130 close_nointr_nofail(fd);
136 static int manager_setup_signals(Manager *m) {
138 struct epoll_event ev;
143 /* We are not interested in SIGSTOP and friends. */
145 sa.sa_handler = SIG_DFL;
146 sa.sa_flags = SA_NOCLDSTOP|SA_RESTART;
147 assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);
149 assert_se(sigemptyset(&mask) == 0);
151 sigset_add_many(&mask,
152 SIGCHLD, /* Child died */
153 SIGTERM, /* Reexecute daemon */
154 SIGHUP, /* Reload configuration */
155 SIGUSR1, /* systemd/upstart: reconnect to D-Bus */
156 SIGUSR2, /* systemd: dump status */
157 SIGINT, /* Kernel sends us this on control-alt-del */
158 SIGWINCH, /* Kernel sends us this on kbrequest (alt-arrowup) */
159 SIGPWR, /* Some kernel drivers and upsd send us this on power failure */
160 SIGRTMIN+0, /* systemd: start default.target */
161 SIGRTMIN+1, /* systemd: start rescue.target */
162 SIGRTMIN+2, /* systemd: isolate emergency.target */
163 SIGRTMIN+3, /* systemd: start halt.target */
164 SIGRTMIN+4, /* systemd: start poweroff.target */
165 SIGRTMIN+5, /* systemd: start reboot.target */
167 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
169 m->signal_watch.type = WATCH_SIGNAL;
170 if ((m->signal_watch.fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0)
175 ev.data.ptr = &m->signal_watch;
177 if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->signal_watch.fd, &ev) < 0)
180 if (m->running_as == MANAGER_SYSTEM)
181 return enable_special_signals(m);
186 int manager_new(ManagerRunningAs running_as, Manager **_m) {
192 assert(running_as >= 0);
193 assert(running_as < _MANAGER_RUNNING_AS_MAX);
195 if (!(m = new0(Manager, 1)))
198 dual_timestamp_get(&m->startup_timestamp);
200 m->running_as = running_as;
201 m->name_data_slot = m->subscribed_data_slot = -1;
202 m->exit_code = _MANAGER_EXIT_CODE_INVALID;
203 m->pin_cgroupfs_fd = -1;
205 m->signal_watch.fd = m->mount_watch.fd = m->udev_watch.fd = m->epoll_fd = m->dev_autofs_fd = -1;
206 m->current_job_id = 1; /* start as id #1, so that we can leave #0 around as "null-like" value */
208 if (!(m->environment = strv_copy(environ)))
211 if (!(m->units = hashmap_new(string_hash_func, string_compare_func)))
214 if (!(m->jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
217 if (!(m->transaction_jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
220 if (!(m->watch_pids = hashmap_new(trivial_hash_func, trivial_compare_func)))
223 if (!(m->cgroup_bondings = hashmap_new(string_hash_func, string_compare_func)))
226 if (!(m->watch_bus = hashmap_new(string_hash_func, string_compare_func)))
229 if ((m->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0)
232 if ((r = lookup_paths_init(&m->lookup_paths, m->running_as)) < 0)
235 if ((r = manager_setup_signals(m)) < 0)
238 if ((r = manager_setup_cgroup(m)) < 0)
241 if ((r = manager_setup_notify(m)) < 0)
244 /* Try to connect to the busses, if possible. */
245 if ((r = bus_init(m)) < 0)
248 if (asprintf(&p, "%s/%s", m->cgroup_mount_point, m->cgroup_hierarchy) < 0) {
253 m->pin_cgroupfs_fd = open(p, O_RDONLY|O_CLOEXEC|O_DIRECTORY|O_NOCTTY|O_NONBLOCK);
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 if (m->exit_code != MANAGER_REEXECUTE)
424 manager_shutdown_cgroup(m);
428 hashmap_free(m->units);
429 hashmap_free(m->jobs);
430 hashmap_free(m->transaction_jobs);
431 hashmap_free(m->watch_pids);
432 hashmap_free(m->watch_bus);
434 if (m->epoll_fd >= 0)
435 close_nointr_nofail(m->epoll_fd);
436 if (m->signal_watch.fd >= 0)
437 close_nointr_nofail(m->signal_watch.fd);
438 if (m->notify_watch.fd >= 0)
439 close_nointr_nofail(m->notify_watch.fd);
441 free(m->notify_socket);
443 lookup_paths_free(&m->lookup_paths);
444 strv_free(m->environment);
446 free(m->cgroup_hierarchy);
447 free(m->cgroup_mount_point);
449 hashmap_free(m->cgroup_bondings);
451 if (m->pin_cgroupfs_fd >= 0)
452 close_nointr_nofail(m->pin_cgroupfs_fd);
457 int manager_enumerate(Manager *m) {
463 /* Let's ask every type to load all units from disk/kernel
464 * that it might know */
465 for (c = 0; c < _UNIT_TYPE_MAX; c++)
466 if (unit_vtable[c]->enumerate)
467 if ((q = unit_vtable[c]->enumerate(m)) < 0)
470 manager_dispatch_load_queue(m);
474 int manager_coldplug(Manager *m) {
482 /* Then, let's set up their initial state. */
483 HASHMAP_FOREACH_KEY(u, k, m->units, i) {
489 if ((q = unit_coldplug(u)) < 0)
496 int manager_startup(Manager *m, FILE *serialization, FDSet *fds) {
501 /* First, enumerate what we can from all config files */
502 r = manager_enumerate(m);
504 /* Second, deserialize if there is something to deserialize */
506 if ((q = manager_deserialize(m, serialization, fds)) < 0)
509 /* Third, fire things up! */
510 if ((q = manager_coldplug(m)) < 0)
513 /* Now that the initial devices are available, let's see if we
514 * can write the utmp file */
515 manager_write_utmp_reboot(m);
520 static void transaction_delete_job(Manager *m, Job *j, bool delete_dependencies) {
524 /* Deletes one job from the transaction */
526 manager_transaction_unlink_job(m, j, delete_dependencies);
532 static void transaction_delete_unit(Manager *m, Unit *u) {
535 /* Deletes all jobs associated with a certain unit from the
538 while ((j = hashmap_get(m->transaction_jobs, u)))
539 transaction_delete_job(m, j, true);
542 static void transaction_clean_dependencies(Manager *m) {
548 /* Drops all dependencies of all installed jobs */
550 HASHMAP_FOREACH(j, m->jobs, i) {
551 while (j->subject_list)
552 job_dependency_free(j->subject_list);
553 while (j->object_list)
554 job_dependency_free(j->object_list);
557 assert(!m->transaction_anchor);
560 static void transaction_abort(Manager *m) {
565 while ((j = hashmap_first(m->transaction_jobs)))
567 transaction_delete_job(m, j, true);
571 assert(hashmap_isempty(m->transaction_jobs));
573 transaction_clean_dependencies(m);
576 static void transaction_find_jobs_that_matter_to_anchor(Manager *m, Job *j, unsigned generation) {
581 /* A recursive sweep through the graph that marks all units
582 * that matter to the anchor job, i.e. are directly or
583 * indirectly a dependency of the anchor job via paths that
584 * are fully marked as mattering. */
589 l = m->transaction_anchor;
591 LIST_FOREACH(subject, l, l) {
593 /* This link does not matter */
597 /* This unit has already been marked */
598 if (l->object->generation == generation)
601 l->object->matters_to_anchor = true;
602 l->object->generation = generation;
604 transaction_find_jobs_that_matter_to_anchor(m, l->object, generation);
608 static void transaction_merge_and_delete_job(Manager *m, Job *j, Job *other, JobType t) {
609 JobDependency *l, *last;
613 assert(j->unit == other->unit);
614 assert(!j->installed);
616 /* Merges 'other' into 'j' and then deletes j. */
619 j->state = JOB_WAITING;
620 j->override = j->override || other->override;
622 j->matters_to_anchor = j->matters_to_anchor || other->matters_to_anchor;
624 /* Patch us in as new owner of the JobDependency objects */
626 LIST_FOREACH(subject, l, other->subject_list) {
627 assert(l->subject == other);
632 /* Merge both lists */
634 last->subject_next = j->subject_list;
636 j->subject_list->subject_prev = last;
637 j->subject_list = other->subject_list;
640 /* Patch us in as new owner of the JobDependency objects */
642 LIST_FOREACH(object, l, other->object_list) {
643 assert(l->object == other);
648 /* Merge both lists */
650 last->object_next = j->object_list;
652 j->object_list->object_prev = last;
653 j->object_list = other->object_list;
656 /* Kill the other job */
657 other->subject_list = NULL;
658 other->object_list = NULL;
659 transaction_delete_job(m, other, true);
662 static int delete_one_unmergeable_job(Manager *m, Job *j) {
667 /* Tries to delete one item in the linked list
668 * j->transaction_next->transaction_next->... that conflicts
669 * whith another one, in an attempt to make an inconsistent
670 * transaction work. */
672 /* We rely here on the fact that if a merged with b does not
673 * merge with c, either a or b merge with c neither */
674 LIST_FOREACH(transaction, j, j)
675 LIST_FOREACH(transaction, k, j->transaction_next) {
678 /* Is this one mergeable? Then skip it */
679 if (job_type_is_mergeable(j->type, k->type))
682 /* Ok, we found two that conflict, let's see if we can
683 * drop one of them */
684 if (!j->matters_to_anchor)
686 else if (!k->matters_to_anchor)
691 /* Ok, we can drop one, so let's do so. */
692 log_notice("Trying to fix job merging by deleting job %s/%s", d->unit->meta.id, job_type_to_string(d->type));
693 transaction_delete_job(m, d, true);
700 static int transaction_merge_jobs(Manager *m, DBusError *e) {
707 /* First step, check whether any of the jobs for one specific
708 * task conflict. If so, try to drop one of them. */
709 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
714 LIST_FOREACH(transaction, k, j->transaction_next) {
715 if ((r = job_type_merge(&t, k->type)) >= 0)
718 /* OK, we could not merge all jobs for this
719 * action. Let's see if we can get rid of one
722 if ((r = delete_one_unmergeable_job(m, j)) >= 0)
723 /* Ok, we managed to drop one, now
724 * let's ask our callers to call us
725 * again after garbage collecting */
728 /* We couldn't merge anything. Failure */
729 dbus_set_error(e, BUS_ERROR_TRANSACTION_JOBS_CONFLICTING, "Transaction contains conflicting jobs '%s' and '%s' for %s. Probably contradicting requirement dependencies configured.",
730 job_type_to_string(t), job_type_to_string(k->type), k->unit->meta.id);
735 /* Second step, merge the jobs. */
736 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
740 /* Merge all transactions */
741 LIST_FOREACH(transaction, k, j->transaction_next)
742 assert_se(job_type_merge(&t, k->type) == 0);
744 /* If an active job is mergeable, merge it too */
745 if (j->unit->meta.job)
746 job_type_merge(&t, j->unit->meta.job->type); /* Might fail. Which is OK */
748 while ((k = j->transaction_next)) {
750 transaction_merge_and_delete_job(m, k, j, t);
753 transaction_merge_and_delete_job(m, j, k, t);
756 assert(!j->transaction_next);
757 assert(!j->transaction_prev);
763 static void transaction_drop_redundant(Manager *m) {
768 /* Goes through the transaction and removes all jobs that are
777 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
778 bool changes_something = false;
781 LIST_FOREACH(transaction, k, j) {
783 if (!job_is_anchor(k) &&
784 job_type_is_redundant(k->type, unit_active_state(k->unit)))
787 changes_something = true;
791 if (changes_something)
794 log_debug("Found redundant job %s/%s, dropping.", j->unit->meta.id, job_type_to_string(j->type));
795 transaction_delete_job(m, j, false);
803 static bool unit_matters_to_anchor(Unit *u, Job *j) {
805 assert(!j->transaction_prev);
807 /* Checks whether at least one of the jobs for this unit
808 * matters to the anchor. */
810 LIST_FOREACH(transaction, j, j)
811 if (j->matters_to_anchor)
817 static int transaction_verify_order_one(Manager *m, Job *j, Job *from, unsigned generation, DBusError *e) {
824 assert(!j->transaction_prev);
826 /* Does a recursive sweep through the ordering graph, looking
827 * for a cycle. If we find cycle we try to break it. */
829 /* Have we seen this before? */
830 if (j->generation == generation) {
833 /* If the marker is NULL we have been here already and
834 * decided the job was loop-free from here. Hence
835 * shortcut things and return right-away. */
839 /* So, the marker is not NULL and we already have been
840 * here. We have a cycle. Let's try to break it. We go
841 * backwards in our path and try to find a suitable
842 * job to remove. We use the marker to find our way
843 * back, since smart how we are we stored our way back
845 log_warning("Found ordering cycle on %s/%s", j->unit->meta.id, job_type_to_string(j->type));
847 for (k = from; k; k = ((k->generation == generation && k->marker != k) ? k->marker : NULL)) {
849 log_info("Walked on cycle path to %s/%s", k->unit->meta.id, job_type_to_string(k->type));
852 !unit_matters_to_anchor(k->unit, k)) {
853 /* Ok, we can drop this one, so let's
855 log_warning("Breaking order cycle by deleting job %s/%s", k->unit->meta.id, job_type_to_string(k->type));
856 transaction_delete_unit(m, k->unit);
860 /* Check if this in fact was the beginning of
866 log_error("Unable to break cycle");
868 dbus_set_error(e, BUS_ERROR_TRANSACTION_ORDER_IS_CYCLIC, "Transaction order is cyclic. See logs for details.");
872 /* Make the marker point to where we come from, so that we can
873 * find our way backwards if we want to break a cycle. We use
874 * a special marker for the beginning: we point to
876 j->marker = from ? from : j;
877 j->generation = generation;
879 /* We assume that the the dependencies are bidirectional, and
880 * hence can ignore UNIT_AFTER */
881 SET_FOREACH(u, j->unit->meta.dependencies[UNIT_BEFORE], i) {
884 /* Is there a job for this unit? */
885 if (!(o = hashmap_get(m->transaction_jobs, u)))
887 /* Ok, there is no job for this in the
888 * transaction, but maybe there is already one
890 if (!(o = u->meta.job))
893 if ((r = transaction_verify_order_one(m, o, j, generation, e)) < 0)
897 /* Ok, let's backtrack, and remember that this entry is not on
898 * our path anymore. */
904 static int transaction_verify_order(Manager *m, unsigned *generation, DBusError *e) {
913 /* Check if the ordering graph is cyclic. If it is, try to fix
914 * that up by dropping one of the jobs. */
918 HASHMAP_FOREACH(j, m->transaction_jobs, i)
919 if ((r = transaction_verify_order_one(m, j, NULL, g, e)) < 0)
925 static void transaction_collect_garbage(Manager *m) {
930 /* Drop jobs that are not required by any other job */
938 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
942 log_debug("Garbage collecting job %s/%s", j->unit->meta.id, job_type_to_string(j->type));
943 transaction_delete_job(m, j, true);
951 static int transaction_is_destructive(Manager *m, DBusError *e) {
957 /* Checks whether applying this transaction means that
958 * existing jobs would be replaced */
960 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
963 assert(!j->transaction_prev);
964 assert(!j->transaction_next);
966 if (j->unit->meta.job &&
967 j->unit->meta.job != j &&
968 !job_type_is_superset(j->type, j->unit->meta.job->type)) {
970 dbus_set_error(e, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE, "Transaction is destructive.");
978 static void transaction_minimize_impact(Manager *m) {
982 /* Drops all unnecessary jobs that reverse already active jobs
983 * or that stop a running service. */
991 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
992 LIST_FOREACH(transaction, j, j) {
993 bool stops_running_service, changes_existing_job;
995 /* If it matters, we shouldn't drop it */
996 if (j->matters_to_anchor)
999 /* Would this stop a running service?
1000 * Would this change an existing job?
1001 * If so, let's drop this entry */
1003 stops_running_service =
1004 j->type == JOB_STOP && UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(j->unit));
1006 changes_existing_job =
1007 j->unit->meta.job && job_type_is_conflicting(j->type, j->unit->meta.job->state);
1009 if (!stops_running_service && !changes_existing_job)
1012 if (stops_running_service)
1013 log_info("%s/%s would stop a running service.", j->unit->meta.id, job_type_to_string(j->type));
1015 if (changes_existing_job)
1016 log_info("%s/%s would change existing job.", j->unit->meta.id, job_type_to_string(j->type));
1018 /* Ok, let's get rid of this */
1019 log_info("Deleting %s/%s to minimize impact.", j->unit->meta.id, job_type_to_string(j->type));
1021 transaction_delete_job(m, j, true);
1033 static int transaction_apply(Manager *m) {
1038 /* Moves the transaction jobs to the set of active jobs */
1040 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1042 assert(!j->transaction_prev);
1043 assert(!j->transaction_next);
1048 if ((r = hashmap_put(m->jobs, UINT32_TO_PTR(j->id), j)) < 0)
1052 while ((j = hashmap_steal_first(m->transaction_jobs))) {
1056 if (j->unit->meta.job)
1057 job_free(j->unit->meta.job);
1059 j->unit->meta.job = j;
1060 j->installed = true;
1062 /* We're fully installed. Now let's free data we don't
1065 assert(!j->transaction_next);
1066 assert(!j->transaction_prev);
1068 job_add_to_run_queue(j);
1069 job_add_to_dbus_queue(j);
1072 /* As last step, kill all remaining job dependencies. */
1073 transaction_clean_dependencies(m);
1079 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1083 hashmap_remove(m->jobs, UINT32_TO_PTR(j->id));
1089 static int transaction_activate(Manager *m, JobMode mode, DBusError *e) {
1091 unsigned generation = 1;
1095 /* This applies the changes recorded in transaction_jobs to
1096 * the actual list of jobs, if possible. */
1098 /* First step: figure out which jobs matter */
1099 transaction_find_jobs_that_matter_to_anchor(m, NULL, generation++);
1101 /* Second step: Try not to stop any running services if
1102 * we don't have to. Don't try to reverse running
1103 * jobs if we don't have to. */
1104 transaction_minimize_impact(m);
1106 /* Third step: Drop redundant jobs */
1107 transaction_drop_redundant(m);
1110 /* Fourth step: Let's remove unneeded jobs that might
1112 transaction_collect_garbage(m);
1114 /* Fifth step: verify order makes sense and correct
1115 * cycles if necessary and possible */
1116 if ((r = transaction_verify_order(m, &generation, e)) >= 0)
1120 log_warning("Requested transaction contains an unfixable cyclic ordering dependency: %s", bus_error(e, r));
1124 /* Let's see if the resulting transaction ordering
1125 * graph is still cyclic... */
1129 /* Sixth step: let's drop unmergeable entries if
1130 * necessary and possible, merge entries we can
1132 if ((r = transaction_merge_jobs(m, e)) >= 0)
1136 log_warning("Requested transaction contains unmergable jobs: %s", bus_error(e, r));
1140 /* Seventh step: an entry got dropped, let's garbage
1141 * collect its dependencies. */
1142 transaction_collect_garbage(m);
1144 /* Let's see if the resulting transaction still has
1145 * unmergeable entries ... */
1148 /* Eights step: Drop redundant jobs again, if the merging now allows us to drop more. */
1149 transaction_drop_redundant(m);
1151 /* Ninth step: check whether we can actually apply this */
1152 if (mode == JOB_FAIL)
1153 if ((r = transaction_is_destructive(m, e)) < 0) {
1154 log_notice("Requested transaction contradicts existing jobs: %s", bus_error(e, r));
1158 /* Tenth step: apply changes */
1159 if ((r = transaction_apply(m)) < 0) {
1160 log_warning("Failed to apply transaction: %s", strerror(-r));
1164 assert(hashmap_isempty(m->transaction_jobs));
1165 assert(!m->transaction_anchor);
1170 transaction_abort(m);
1174 static Job* transaction_add_one_job(Manager *m, JobType type, Unit *unit, bool override, bool *is_new) {
1181 /* Looks for an axisting prospective job and returns that. If
1182 * it doesn't exist it is created and added to the prospective
1185 f = hashmap_get(m->transaction_jobs, unit);
1187 LIST_FOREACH(transaction, j, f) {
1188 assert(j->unit == unit);
1190 if (j->type == type) {
1197 if (unit->meta.job && unit->meta.job->type == type)
1199 else if (!(j = job_new(m, type, unit)))
1204 j->matters_to_anchor = false;
1205 j->override = override;
1207 LIST_PREPEND(Job, transaction, f, j);
1209 if ((r = hashmap_replace(m->transaction_jobs, unit, f)) < 0) {
1217 log_debug("Added job %s/%s to transaction.", unit->meta.id, job_type_to_string(type));
1222 void manager_transaction_unlink_job(Manager *m, Job *j, bool delete_dependencies) {
1226 if (j->transaction_prev)
1227 j->transaction_prev->transaction_next = j->transaction_next;
1228 else if (j->transaction_next)
1229 hashmap_replace(m->transaction_jobs, j->unit, j->transaction_next);
1231 hashmap_remove_value(m->transaction_jobs, j->unit, j);
1233 if (j->transaction_next)
1234 j->transaction_next->transaction_prev = j->transaction_prev;
1236 j->transaction_prev = j->transaction_next = NULL;
1238 while (j->subject_list)
1239 job_dependency_free(j->subject_list);
1241 while (j->object_list) {
1242 Job *other = j->object_list->matters ? j->object_list->subject : NULL;
1244 job_dependency_free(j->object_list);
1246 if (other && delete_dependencies) {
1247 log_info("Deleting job %s/%s as dependency of job %s/%s",
1248 other->unit->meta.id, job_type_to_string(other->type),
1249 j->unit->meta.id, job_type_to_string(j->type));
1250 transaction_delete_job(m, other, delete_dependencies);
1255 static int transaction_add_job_and_dependencies(
1271 assert(type < _JOB_TYPE_MAX);
1274 if (unit->meta.load_state != UNIT_LOADED) {
1275 dbus_set_error(e, BUS_ERROR_LOAD_FAILED, "Unit %s failed to load. See logs for details.", unit->meta.id);
1279 if (!unit_job_is_applicable(unit, type)) {
1280 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);
1284 /* First add the job. */
1285 if (!(ret = transaction_add_one_job(m, type, unit, override, &is_new)))
1288 /* Then, add a link to the job. */
1289 if (!job_dependency_new(by, ret, matters))
1293 /* Finally, recursively add in all dependencies. */
1294 if (type == JOB_START || type == JOB_RELOAD_OR_START) {
1295 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES], i)
1296 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, true, override, e, NULL)) < 0 && r != -EBADR)
1299 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES_OVERRIDABLE], i)
1300 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, !override, override, e, NULL)) < 0 && r != -EBADR)
1301 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, strerror(-r));
1303 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_WANTS], i)
1304 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, false, false, e, NULL)) < 0)
1305 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, strerror(-r));
1307 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE], i)
1308 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, true, override, e, NULL)) < 0 && r != -EBADR)
1311 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE_OVERRIDABLE], i)
1312 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, !override, override, e, NULL)) < 0 && r != -EBADR)
1313 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, strerror(-r));
1315 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_CONFLICTS], i)
1316 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, dep, ret, true, override, e, NULL)) < 0 && r != -EBADR)
1319 } else if (type == JOB_STOP || type == JOB_RESTART || type == JOB_TRY_RESTART) {
1321 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRED_BY], i)
1322 if ((r = transaction_add_job_and_dependencies(m, type, dep, ret, true, override, e, NULL)) < 0 && r != -EBADR)
1326 /* JOB_VERIFY_STARTED, JOB_RELOAD require no dependency handling */
1338 static int transaction_add_isolate_jobs(Manager *m) {
1346 HASHMAP_FOREACH_KEY(u, k, m->units, i) {
1348 /* ignore aliases */
1349 if (u->meta.id != k)
1352 if (UNIT_VTABLE(u)->no_isolate)
1355 /* No need to stop inactive jobs */
1356 if (UNIT_IS_INACTIVE_OR_MAINTENANCE(unit_active_state(u)))
1359 /* Is there already something listed for this? */
1360 if (hashmap_get(m->transaction_jobs, u))
1363 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, u, NULL, true, false, NULL, NULL)) < 0)
1364 log_warning("Cannot add isolate job for unit %s, ignoring: %s", u->meta.id, strerror(-r));
1370 int manager_add_job(Manager *m, JobType type, Unit *unit, JobMode mode, bool override, DBusError *e, Job **_ret) {
1375 assert(type < _JOB_TYPE_MAX);
1377 assert(mode < _JOB_MODE_MAX);
1379 if (mode == JOB_ISOLATE && type != JOB_START) {
1380 dbus_set_error(e, BUS_ERROR_INVALID_JOB_MODE, "Isolate is only valid for start.");
1384 log_debug("Trying to enqueue job %s/%s", unit->meta.id, job_type_to_string(type));
1386 if ((r = transaction_add_job_and_dependencies(m, type, unit, NULL, true, override, e, &ret)) < 0) {
1387 transaction_abort(m);
1391 if (mode == JOB_ISOLATE)
1392 if ((r = transaction_add_isolate_jobs(m)) < 0) {
1393 transaction_abort(m);
1397 if ((r = transaction_activate(m, mode, e)) < 0)
1400 log_debug("Enqueued job %s/%s as %u", unit->meta.id, job_type_to_string(type), (unsigned) ret->id);
1408 int manager_add_job_by_name(Manager *m, JobType type, const char *name, JobMode mode, bool override, DBusError *e, Job **_ret) {
1413 assert(type < _JOB_TYPE_MAX);
1415 assert(mode < _JOB_MODE_MAX);
1417 if ((r = manager_load_unit(m, name, NULL, NULL, &unit)) < 0)
1420 return manager_add_job(m, type, unit, mode, override, e, _ret);
1423 Job *manager_get_job(Manager *m, uint32_t id) {
1426 return hashmap_get(m->jobs, UINT32_TO_PTR(id));
1429 Unit *manager_get_unit(Manager *m, const char *name) {
1433 return hashmap_get(m->units, name);
1436 unsigned manager_dispatch_load_queue(Manager *m) {
1442 /* Make sure we are not run recursively */
1443 if (m->dispatching_load_queue)
1446 m->dispatching_load_queue = true;
1448 /* Dispatches the load queue. Takes a unit from the queue and
1449 * tries to load its data until the queue is empty */
1451 while ((meta = m->load_queue)) {
1452 assert(meta->in_load_queue);
1454 unit_load((Unit*) meta);
1458 m->dispatching_load_queue = false;
1462 int manager_load_unit_prepare(Manager *m, const char *name, const char *path, DBusError *e, Unit **_ret) {
1467 assert(name || path);
1469 /* This will prepare the unit for loading, but not actually
1470 * load anything from disk. */
1472 if (path && !is_path(path)) {
1473 dbus_set_error(e, BUS_ERROR_INVALID_PATH, "Path %s is not absolute.", path);
1478 name = file_name_from_path(path);
1480 if (!unit_name_is_valid(name)) {
1481 dbus_set_error(e, BUS_ERROR_INVALID_NAME, "Unit name %s is not valid.", name);
1485 if ((ret = manager_get_unit(m, name))) {
1490 if (!(ret = unit_new(m)))
1494 if (!(ret->meta.fragment_path = strdup(path))) {
1499 if ((r = unit_add_name(ret, name)) < 0) {
1504 unit_add_to_load_queue(ret);
1505 unit_add_to_dbus_queue(ret);
1506 unit_add_to_gc_queue(ret);
1514 int manager_load_unit(Manager *m, const char *name, const char *path, DBusError *e, Unit **_ret) {
1519 /* This will load the service information files, but not actually
1520 * start any services or anything. */
1522 if ((r = manager_load_unit_prepare(m, name, path, e, _ret)) != 0)
1525 manager_dispatch_load_queue(m);
1528 *_ret = unit_follow_merge(*_ret);
1533 void manager_dump_jobs(Manager *s, FILE *f, const char *prefix) {
1540 HASHMAP_FOREACH(j, s->jobs, i)
1541 job_dump(j, f, prefix);
1544 void manager_dump_units(Manager *s, FILE *f, const char *prefix) {
1552 HASHMAP_FOREACH_KEY(u, t, s->units, i)
1553 if (u->meta.id == t)
1554 unit_dump(u, f, prefix);
1557 void manager_clear_jobs(Manager *m) {
1562 transaction_abort(m);
1564 while ((j = hashmap_first(m->jobs)))
1568 unsigned manager_dispatch_run_queue(Manager *m) {
1572 if (m->dispatching_run_queue)
1575 m->dispatching_run_queue = true;
1577 while ((j = m->run_queue)) {
1578 assert(j->installed);
1579 assert(j->in_run_queue);
1581 job_run_and_invalidate(j);
1585 m->dispatching_run_queue = false;
1589 unsigned manager_dispatch_dbus_queue(Manager *m) {
1596 if (m->dispatching_dbus_queue)
1599 m->dispatching_dbus_queue = true;
1601 while ((meta = m->dbus_unit_queue)) {
1602 assert(meta->in_dbus_queue);
1604 bus_unit_send_change_signal((Unit*) meta);
1608 while ((j = m->dbus_job_queue)) {
1609 assert(j->in_dbus_queue);
1611 bus_job_send_change_signal(j);
1615 m->dispatching_dbus_queue = false;
1619 static int manager_process_notify_fd(Manager *m) {
1626 struct msghdr msghdr;
1628 struct ucred *ucred;
1630 struct cmsghdr cmsghdr;
1631 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
1637 iovec.iov_base = buf;
1638 iovec.iov_len = sizeof(buf)-1;
1642 msghdr.msg_iov = &iovec;
1643 msghdr.msg_iovlen = 1;
1644 msghdr.msg_control = &control;
1645 msghdr.msg_controllen = sizeof(control);
1647 if ((n = recvmsg(m->notify_watch.fd, &msghdr, MSG_DONTWAIT)) <= 0) {
1651 if (errno == EAGAIN)
1657 if (msghdr.msg_controllen < CMSG_LEN(sizeof(struct ucred)) ||
1658 control.cmsghdr.cmsg_level != SOL_SOCKET ||
1659 control.cmsghdr.cmsg_type != SCM_CREDENTIALS ||
1660 control.cmsghdr.cmsg_len != CMSG_LEN(sizeof(struct ucred))) {
1661 log_warning("Received notify message without credentials. Ignoring.");
1665 ucred = (struct ucred*) CMSG_DATA(&control.cmsghdr);
1667 if (!(u = hashmap_get(m->watch_pids, UINT32_TO_PTR(ucred->pid))))
1668 if (!(u = cgroup_unit_by_pid(m, ucred->pid))) {
1669 log_warning("Cannot find unit for notify message of PID %lu.", (unsigned long) ucred->pid);
1673 assert((size_t) n < sizeof(buf));
1675 if (!(tags = strv_split(buf, "\n\r")))
1678 log_debug("Got notification message for unit %s", u->meta.id);
1680 if (UNIT_VTABLE(u)->notify_message)
1681 UNIT_VTABLE(u)->notify_message(u, ucred->pid, tags);
1689 static int manager_dispatch_sigchld(Manager *m) {
1699 /* First we call waitd() for a PID and do not reap the
1700 * zombie. That way we can still access /proc/$PID for
1701 * it while it is a zombie. */
1702 if (waitid(P_ALL, 0, &si, WEXITED|WNOHANG|WNOWAIT) < 0) {
1704 if (errno == ECHILD)
1716 if (si.si_code == CLD_EXITED || si.si_code == CLD_KILLED || si.si_code == CLD_DUMPED) {
1719 get_process_name(si.si_pid, &name);
1720 log_debug("Got SIGCHLD for process %lu (%s)", (unsigned long) si.si_pid, strna(name));
1724 /* Let's flush any message the dying child might still
1725 * have queued for us. This ensures that the process
1726 * still exists in /proc so that we can figure out
1727 * which cgroup and hence unit it belongs to. */
1728 if ((r = manager_process_notify_fd(m)) < 0)
1731 /* And now figure out the unit this belongs to */
1732 if (!(u = hashmap_get(m->watch_pids, UINT32_TO_PTR(si.si_pid))))
1733 u = cgroup_unit_by_pid(m, si.si_pid);
1735 /* And now, we actually reap the zombie. */
1736 if (waitid(P_PID, si.si_pid, &si, WEXITED) < 0) {
1743 if (si.si_code != CLD_EXITED && si.si_code != CLD_KILLED && si.si_code != CLD_DUMPED)
1746 log_debug("Child %lu died (code=%s, status=%i/%s)",
1747 (long unsigned) si.si_pid,
1748 sigchld_code_to_string(si.si_code),
1750 strna(si.si_code == CLD_EXITED ? exit_status_to_string(si.si_status) : signal_to_string(si.si_status)));
1755 log_debug("Child %llu belongs to %s", (long long unsigned) si.si_pid, u->meta.id);
1757 hashmap_remove(m->watch_pids, UINT32_TO_PTR(si.si_pid));
1758 UNIT_VTABLE(u)->sigchld_event(u, si.si_pid, si.si_code, si.si_status);
1764 static int manager_start_target(Manager *m, const char *name, JobMode mode) {
1768 dbus_error_init(&error);
1770 log_info("Activating special unit %s", name);
1772 if ((r = manager_add_job_by_name(m, JOB_START, name, mode, true, &error, NULL)) < 0)
1773 log_error("Failed to enqueue %s job: %s", name, bus_error(&error, r));
1775 dbus_error_free(&error);
1780 static int manager_process_signal_fd(Manager *m) {
1782 struct signalfd_siginfo sfsi;
1783 bool sigchld = false;
1788 if ((n = read(m->signal_watch.fd, &sfsi, sizeof(sfsi))) != sizeof(sfsi)) {
1793 if (errno == EAGAIN)
1799 log_debug("Received SIG%s", strna(signal_to_string(sfsi.ssi_signo)));
1801 switch (sfsi.ssi_signo) {
1808 if (m->running_as == MANAGER_SYSTEM) {
1809 /* This is for compatibility with the
1810 * original sysvinit */
1811 m->exit_code = MANAGER_REEXECUTE;
1818 if (m->running_as == MANAGER_SYSTEM) {
1819 manager_start_target(m, SPECIAL_CTRL_ALT_DEL_TARGET, JOB_REPLACE);
1823 /* Run the exit target if there is one, if not, just exit. */
1824 if (manager_start_target(m, SPECIAL_EXIT_SERVICE, JOB_REPLACE) < 0) {
1825 m->exit_code = MANAGER_EXIT;
1832 if (m->running_as == MANAGER_SYSTEM)
1833 manager_start_target(m, SPECIAL_KBREQUEST_TARGET, JOB_REPLACE);
1835 /* This is a nop on non-init */
1839 if (m->running_as == MANAGER_SYSTEM)
1840 manager_start_target(m, SPECIAL_SIGPWR_TARGET, JOB_REPLACE);
1842 /* This is a nop on non-init */
1848 u = manager_get_unit(m, SPECIAL_DBUS_SERVICE);
1850 if (!u || UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u))) {
1851 log_info("Trying to reconnect to bus...");
1855 if (!u || !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u))) {
1856 log_info("Loading D-Bus service...");
1857 manager_start_target(m, SPECIAL_DBUS_SERVICE, JOB_REPLACE);
1868 if (!(f = open_memstream(&dump, &size))) {
1869 log_warning("Failed to allocate memory stream.");
1873 manager_dump_units(m, f, "\t");
1874 manager_dump_jobs(m, f, "\t");
1879 log_warning("Failed to write status stream");
1884 log_dump(LOG_INFO, dump);
1891 m->exit_code = MANAGER_RELOAD;
1895 static const char * const table[] = {
1896 [0] = SPECIAL_DEFAULT_TARGET,
1897 [1] = SPECIAL_RESCUE_TARGET,
1898 [2] = SPECIAL_EMERGENCY_SERVICE,
1899 [3] = SPECIAL_HALT_TARGET,
1900 [4] = SPECIAL_POWEROFF_TARGET,
1901 [5] = SPECIAL_REBOOT_TARGET
1904 if ((int) sfsi.ssi_signo >= SIGRTMIN+0 &&
1905 (int) sfsi.ssi_signo < SIGRTMIN+(int) ELEMENTSOF(table)) {
1906 manager_start_target(m, table[sfsi.ssi_signo - SIGRTMIN],
1907 (sfsi.ssi_signo == 1 || sfsi.ssi_signo == 2) ? JOB_ISOLATE : JOB_REPLACE);
1911 log_warning("Got unhandled signal <%s>.", strna(signal_to_string(sfsi.ssi_signo)));
1917 return manager_dispatch_sigchld(m);
1922 static int process_event(Manager *m, struct epoll_event *ev) {
1929 assert(w = ev->data.ptr);
1935 /* An incoming signal? */
1936 if (ev->events != EPOLLIN)
1939 if ((r = manager_process_signal_fd(m)) < 0)
1946 /* An incoming daemon notification event? */
1947 if (ev->events != EPOLLIN)
1950 if ((r = manager_process_notify_fd(m)) < 0)
1957 /* Some fd event, to be dispatched to the units */
1958 UNIT_VTABLE(w->data.unit)->fd_event(w->data.unit, w->fd, ev->events, w);
1965 /* Some timer event, to be dispatched to the units */
1966 if ((k = read(w->fd, &v, sizeof(v))) != sizeof(v)) {
1968 if (k < 0 && (errno == EINTR || errno == EAGAIN))
1971 return k < 0 ? -errno : -EIO;
1974 UNIT_VTABLE(w->data.unit)->timer_event(w->data.unit, v, w);
1979 /* Some mount table change, intended for the mount subsystem */
1980 mount_fd_event(m, ev->events);
1984 /* Some notification from udev, intended for the device subsystem */
1985 device_fd_event(m, ev->events);
1988 case WATCH_DBUS_WATCH:
1989 bus_watch_event(m, w, ev->events);
1992 case WATCH_DBUS_TIMEOUT:
1993 bus_timeout_event(m, w, ev->events);
1997 assert_not_reached("Unknown epoll event type.");
2003 int manager_loop(Manager *m) {
2006 RATELIMIT_DEFINE(rl, 1*USEC_PER_SEC, 1000);
2009 m->exit_code = MANAGER_RUNNING;
2011 /* There might still be some zombies hanging around from
2012 * before we were exec()'ed. Leat's reap them */
2013 if ((r = manager_dispatch_sigchld(m)) < 0)
2016 while (m->exit_code == MANAGER_RUNNING) {
2017 struct epoll_event event;
2020 if (!ratelimit_test(&rl)) {
2021 /* Yay, something is going seriously wrong, pause a little */
2022 log_warning("Looping too fast. Throttling execution a little.");
2026 if (manager_dispatch_load_queue(m) > 0)
2029 if (manager_dispatch_run_queue(m) > 0)
2032 if (bus_dispatch(m) > 0)
2035 if (manager_dispatch_cleanup_queue(m) > 0)
2038 if (manager_dispatch_gc_queue(m) > 0)
2041 if (manager_dispatch_dbus_queue(m) > 0)
2044 if ((n = epoll_wait(m->epoll_fd, &event, 1, -1)) < 0) {
2054 if ((r = process_event(m, &event)) < 0)
2058 return m->exit_code;
2061 int manager_get_unit_from_dbus_path(Manager *m, const char *s, Unit **_u) {
2069 if (!startswith(s, "/org/freedesktop/systemd1/unit/"))
2072 if (!(n = bus_path_unescape(s+31)))
2075 u = manager_get_unit(m, n);
2086 int manager_get_job_from_dbus_path(Manager *m, const char *s, Job **_j) {
2095 if (!startswith(s, "/org/freedesktop/systemd1/job/"))
2098 if ((r = safe_atou(s + 30, &id)) < 0)
2101 if (!(j = manager_get_job(m, id)))
2109 static bool manager_utmp_good(Manager *m) {
2114 if ((r = mount_path_is_mounted(m, _PATH_UTMPX)) <= 0) {
2117 log_warning("Failed to determine whether " _PATH_UTMPX " is mounted: %s", strerror(-r));
2125 void manager_write_utmp_reboot(Manager *m) {
2130 if (m->utmp_reboot_written)
2133 if (m->running_as != MANAGER_SYSTEM)
2136 if (!manager_utmp_good(m))
2139 if ((r = utmp_put_reboot(m->startup_timestamp.realtime)) < 0) {
2141 if (r != -ENOENT && r != -EROFS)
2142 log_warning("Failed to write utmp/wtmp: %s", strerror(-r));
2147 m->utmp_reboot_written = true;
2150 void manager_write_utmp_runlevel(Manager *m, Unit *u) {
2156 if (u->meta.type != UNIT_TARGET)
2159 if (m->running_as != MANAGER_SYSTEM)
2162 if (!manager_utmp_good(m))
2165 if ((runlevel = target_get_runlevel(TARGET(u))) <= 0)
2168 if ((r = utmp_put_runlevel(0, runlevel, 0)) < 0) {
2170 if (r != -ENOENT && r != -EROFS)
2171 log_warning("Failed to write utmp/wtmp: %s", strerror(-r));
2175 void manager_dispatch_bus_name_owner_changed(
2178 const char* old_owner,
2179 const char *new_owner) {
2186 if (!(u = hashmap_get(m->watch_bus, name)))
2189 UNIT_VTABLE(u)->bus_name_owner_change(u, name, old_owner, new_owner);
2192 void manager_dispatch_bus_query_pid_done(
2203 if (!(u = hashmap_get(m->watch_bus, name)))
2206 UNIT_VTABLE(u)->bus_query_pid_done(u, name, pid);
2209 int manager_open_serialization(FILE **_f) {
2217 if (asprintf(&path, "/dev/shm/systemd-%u.dump-XXXXXX", (unsigned) getpid()) < 0)
2220 saved_umask = umask(0077);
2221 fd = mkostemp(path, O_RDWR|O_CLOEXEC);
2231 log_debug("Serializing state to %s", path);
2234 if (!(f = fdopen(fd, "w+")) < 0)
2242 int manager_serialize(Manager *m, FILE *f, FDSet *fds) {
2252 HASHMAP_FOREACH_KEY(u, t, m->units, i) {
2253 if (u->meta.id != t)
2256 if (!unit_can_serialize(u))
2260 fputs(u->meta.id, f);
2263 if ((r = unit_serialize(u, f, fds)) < 0)
2273 int manager_deserialize(Manager *m, FILE *f, FDSet *fds) {
2279 log_debug("Deserializing state...");
2281 m->deserializing = true;
2285 char name[UNIT_NAME_MAX+2];
2288 if (!fgets(name, sizeof(name), f)) {
2298 if ((r = manager_load_unit(m, strstrip(name), NULL, NULL, &u)) < 0)
2301 if ((r = unit_deserialize(u, f, fds)) < 0)
2313 m->deserializing = false;
2318 int manager_reload(Manager *m) {
2325 if ((r = manager_open_serialization(&f)) < 0)
2328 if (!(fds = fdset_new())) {
2333 if ((r = manager_serialize(m, f, fds)) < 0)
2336 if (fseeko(f, 0, SEEK_SET) < 0) {
2341 /* From here on there is no way back. */
2342 manager_clear_jobs_and_units(m);
2344 /* Find new unit paths */
2345 lookup_paths_free(&m->lookup_paths);
2346 if ((q = lookup_paths_init(&m->lookup_paths, m->running_as)) < 0)
2349 /* First, enumerate what we can from all config files */
2350 if ((q = manager_enumerate(m)) < 0)
2353 /* Second, deserialize our stored data */
2354 if ((q = manager_deserialize(m, f, fds)) < 0)
2360 /* Third, fire things up! */
2361 if ((q = manager_coldplug(m)) < 0)
2374 bool manager_is_booting_or_shutting_down(Manager *m) {
2379 /* Is the initial job still around? */
2380 if (manager_get_job(m, 1))
2383 /* Is there a job for the shutdown target? */
2384 if (((u = manager_get_unit(m, SPECIAL_SHUTDOWN_TARGET))))
2385 return !!u->meta.job;
2390 static const char* const manager_running_as_table[_MANAGER_RUNNING_AS_MAX] = {
2391 [MANAGER_SYSTEM] = "system",
2392 [MANAGER_SESSION] = "session"
2395 DEFINE_STRING_TABLE_LOOKUP(manager_running_as, ManagerRunningAs);