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>
35 #include <libcgroup.h>
38 #include <sys/types.h>
47 #include "ratelimit.h"
49 #include "mount-setup.h"
50 #include "utmp-wtmp.h"
51 #include "unit-name.h"
52 #include "dbus-unit.h"
56 /* As soon as 16 units are in our GC queue, make sure to run a gc sweep */
57 #define GC_QUEUE_ENTRIES_MAX 16
59 /* As soon as 5s passed since a unit was added to our GC queue, make sure to run a gc sweep */
60 #define GC_QUEUE_USEC_MAX (10*USEC_PER_SEC)
62 static int enable_special_signals(Manager *m) {
67 /* Enable that we get SIGINT on control-alt-del */
68 if (reboot(RB_DISABLE_CAD) < 0)
69 log_warning("Failed to enable ctrl-alt-del handling: %m");
71 if ((fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY)) < 0)
72 log_warning("Failed to open /dev/tty0: %m");
74 /* Enable that we get SIGWINCH on kbrequest */
75 if (ioctl(fd, KDSIGACCEPT, SIGWINCH) < 0)
76 log_warning("Failed to enable kbrequest handling: %s", strerror(errno));
78 close_nointr_nofail(fd);
84 static int manager_setup_signals(Manager *m) {
86 struct epoll_event ev;
91 /* We are not interested in SIGSTOP and friends. */
93 sa.sa_handler = SIG_DFL;
94 sa.sa_flags = SA_NOCLDSTOP|SA_RESTART;
95 assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);
97 assert_se(sigemptyset(&mask) == 0);
98 assert_se(sigaddset(&mask, SIGCHLD) == 0);
99 assert_se(sigaddset(&mask, SIGTERM) == 0);
100 assert_se(sigaddset(&mask, SIGHUP) == 0);
101 assert_se(sigaddset(&mask, SIGUSR1) == 0);
102 assert_se(sigaddset(&mask, SIGUSR2) == 0);
103 assert_se(sigaddset(&mask, SIGINT) == 0); /* Kernel sends us this on control-alt-del */
104 assert_se(sigaddset(&mask, SIGWINCH) == 0); /* Kernel sends us this on kbrequest (alt-arrowup) */
105 assert_se(sigaddset(&mask, SIGPWR) == 0); /* Some kernel drivers and upsd send us this on power failure */
106 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
108 m->signal_watch.type = WATCH_SIGNAL;
109 if ((m->signal_watch.fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0)
114 ev.data.ptr = &m->signal_watch;
116 if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->signal_watch.fd, &ev) < 0)
119 if (m->running_as == MANAGER_INIT)
120 return enable_special_signals(m);
125 static char** session_dirs(void) {
126 const char *home, *e;
127 char *config_home = NULL, *data_home = NULL;
128 char **config_dirs = NULL, **data_dirs = NULL;
129 char **r = NULL, **t;
131 /* Implement the mechanisms defined in
133 * http://standards.freedesktop.org/basedir-spec/basedir-spec-0.6.html
135 * We look in both the config and the data dirs because we
136 * want to encourage that distributors ship their unit files
137 * as data, and allow overriding as configuration.
140 home = getenv("HOME");
142 if ((e = getenv("XDG_CONFIG_HOME"))) {
143 if (asprintf(&config_home, "%s/systemd/session", e) < 0)
147 if (asprintf(&config_home, "%s/.config/systemd/session", home) < 0)
151 if ((e = getenv("XDG_CONFIG_DIRS")))
152 if (!(config_dirs = strv_split(e, ":")))
155 /* We don't treat /etc/xdg/systemd here as the spec
156 * suggests because we assume that that is a link to
157 * /etc/systemd/ anyway. */
159 if ((e = getenv("XDG_DATA_HOME"))) {
160 if (asprintf(&data_home, "%s/systemd/session", e) < 0)
164 if (asprintf(&data_home, "%s/.local/share/systemd/session", home) < 0)
167 /* There is really no need for two unit dirs in $HOME,
168 * except to be fully compliant with the XDG spec. We
169 * now try to link the two dirs, so that we can
170 * minimize disk seeks a little. Further down we'll
171 * then filter out this link, if it is actually is
174 mkdir_parents(data_home, 0777);
175 symlink("../../../.config/systemd/session", data_home);
178 if ((e = getenv("XDG_DATA_DIRS")))
179 data_dirs = strv_split(e, ":");
181 data_dirs = strv_new("/usr/local/share", "/usr/share", NULL);
186 /* Now merge everything we found. */
188 if (!(t = strv_append(r, config_home)))
194 if (!(t = strv_merge_concat(r, config_dirs, "/systemd/session")))
199 if (!(t = strv_append(r, SESSION_CONFIG_UNIT_PATH)))
205 if (!(t = strv_append(r, data_home)))
211 if (!(t = strv_merge_concat(r, data_dirs, "/systemd/session")))
216 if (!(t = strv_append(r, SESSION_DATA_UNIT_PATH)))
221 if (!strv_path_make_absolute_cwd(r))
226 strv_free(config_dirs);
228 strv_free(data_dirs);
238 static int manager_find_paths(Manager *m) {
244 /* Unset previous data, in case we are called on reload */
245 strv_free(m->unit_path);
246 strv_free(m->sysvinit_path);
247 strv_free(m->sysvrcnd_path);
248 m->unit_path = m->sysvinit_path = m->sysvrcnd_path = NULL;
250 /* First priority is whatever has been passed to us via env
252 if ((e = getenv("SYSTEMD_UNIT_PATH")))
253 if (!(m->unit_path = split_path_and_make_absolute(e)))
256 if (strv_isempty(m->unit_path)) {
258 /* Nothing is set, so let's figure something out. */
259 strv_free(m->unit_path);
261 if (m->running_as == MANAGER_SESSION) {
262 if (!(m->unit_path = session_dirs()))
265 if (!(m->unit_path = strv_new(
266 SYSTEM_CONFIG_UNIT_PATH, /* /etc/systemd/system/ */
267 SYSTEM_DATA_UNIT_PATH, /* /lib/systemd/system/ */
272 if (m->running_as == MANAGER_INIT) {
273 /* /etc/init.d/ compatibility does not matter to users */
275 if ((e = getenv("SYSTEMD_SYSVINIT_PATH")))
276 if (!(m->sysvinit_path = split_path_and_make_absolute(e)))
279 if (strv_isempty(m->sysvinit_path)) {
280 strv_free(m->sysvinit_path);
282 if (!(m->sysvinit_path = strv_new(
283 SYSTEM_SYSVINIT_PATH, /* /etc/init.d/ */
288 if ((e = getenv("SYSTEMD_SYSVRCND_PATH")))
289 if (!(m->sysvrcnd_path = split_path_and_make_absolute(e)))
292 if (strv_isempty(m->sysvrcnd_path)) {
293 strv_free(m->sysvrcnd_path);
295 if (!(m->sysvrcnd_path = strv_new(
296 SYSTEM_SYSVRCND_PATH, /* /etc/rcN.d/ */
303 if (!strv_path_canonicalize(m->unit_path))
306 if (m->sysvinit_path)
307 if (!strv_path_canonicalize(m->sysvinit_path))
310 if (m->sysvrcnd_path)
311 if (!strv_path_canonicalize(m->sysvrcnd_path))
314 strv_uniq(m->unit_path);
315 strv_uniq(m->sysvinit_path);
316 strv_uniq(m->sysvrcnd_path);
318 if (!strv_isempty(m->unit_path)) {
320 if (!(t = strv_join(m->unit_path, "\n\t")))
322 log_debug("Looking for unit files in:\n\t%s", t);
325 log_debug("Ignoring unit files.");
326 strv_free(m->unit_path);
330 if (!strv_isempty(m->sysvinit_path)) {
332 if (!(t = strv_join(m->sysvinit_path, "\n\t")))
335 log_debug("Looking for SysV init scripts in:\n\t%s", t);
338 log_debug("Ignoring SysV init scripts.");
339 strv_free(m->sysvinit_path);
340 m->sysvinit_path = NULL;
343 if (!strv_isempty(m->sysvrcnd_path)) {
345 if (!(t = strv_join(m->sysvrcnd_path, "\n\t")))
348 log_debug("Looking for SysV rcN.d links in:\n\t%s", t);
351 log_debug("Ignoring SysV rcN.d links.");
352 strv_free(m->sysvrcnd_path);
353 m->sysvrcnd_path = NULL;
359 int manager_new(ManagerRunningAs running_as, bool confirm_spawn, Manager **_m) {
364 assert(running_as >= 0);
365 assert(running_as < _MANAGER_RUNNING_AS_MAX);
367 if (!(m = new0(Manager, 1)))
370 timestamp_get(&m->startup_timestamp);
372 m->running_as = running_as;
373 m->confirm_spawn = confirm_spawn;
374 m->name_data_slot = -1;
375 m->exit_code = _MANAGER_EXIT_CODE_INVALID;
377 m->signal_watch.fd = m->mount_watch.fd = m->udev_watch.fd = m->epoll_fd = m->dev_autofs_fd = -1;
378 m->current_job_id = 1; /* start as id #1, so that we can leave #0 around as "null-like" value */
380 if (!(m->environment = strv_copy(environ)))
383 if (!(m->units = hashmap_new(string_hash_func, string_compare_func)))
386 if (!(m->jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
389 if (!(m->transaction_jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
392 if (!(m->watch_pids = hashmap_new(trivial_hash_func, trivial_compare_func)))
395 if (!(m->cgroup_bondings = hashmap_new(string_hash_func, string_compare_func)))
398 if (!(m->watch_bus = hashmap_new(string_hash_func, string_compare_func)))
401 if ((m->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0)
404 if ((r = manager_find_paths(m)) < 0)
407 if ((r = manager_setup_signals(m)) < 0)
410 if ((r = manager_setup_cgroup(m)) < 0)
413 /* Try to connect to the busses, if possible. */
414 if ((r = bus_init_system(m)) < 0 ||
415 (r = bus_init_api(m)) < 0)
426 static unsigned manager_dispatch_cleanup_queue(Manager *m) {
432 while ((meta = m->cleanup_queue)) {
433 assert(meta->in_cleanup_queue);
435 unit_free(UNIT(meta));
443 GC_OFFSET_IN_PATH, /* This one is on the path we were travelling */
444 GC_OFFSET_UNSURE, /* No clue */
445 GC_OFFSET_GOOD, /* We still need this unit */
446 GC_OFFSET_BAD, /* We don't need this unit anymore */
450 static void unit_gc_sweep(Unit *u, unsigned gc_marker) {
457 if (u->meta.gc_marker == gc_marker + GC_OFFSET_GOOD ||
458 u->meta.gc_marker == gc_marker + GC_OFFSET_BAD ||
459 u->meta.gc_marker == gc_marker + GC_OFFSET_IN_PATH)
462 if (u->meta.in_cleanup_queue)
465 if (unit_check_gc(u))
468 u->meta.gc_marker = gc_marker + GC_OFFSET_IN_PATH;
472 SET_FOREACH(other, u->meta.dependencies[UNIT_REFERENCED_BY], i) {
473 unit_gc_sweep(other, gc_marker);
475 if (other->meta.gc_marker == gc_marker + GC_OFFSET_GOOD)
478 if (other->meta.gc_marker != gc_marker + GC_OFFSET_BAD)
485 /* We were unable to find anything out about this entry, so
486 * let's investigate it later */
487 u->meta.gc_marker = gc_marker + GC_OFFSET_UNSURE;
488 unit_add_to_gc_queue(u);
492 /* We definitely know that this one is not useful anymore, so
493 * let's mark it for deletion */
494 u->meta.gc_marker = gc_marker + GC_OFFSET_BAD;
495 unit_add_to_cleanup_queue(u);
499 u->meta.gc_marker = gc_marker + GC_OFFSET_GOOD;
502 static unsigned manager_dispatch_gc_queue(Manager *m) {
509 if ((m->n_in_gc_queue < GC_QUEUE_ENTRIES_MAX) &&
510 (m->gc_queue_timestamp <= 0 ||
511 (m->gc_queue_timestamp + GC_QUEUE_USEC_MAX) > now(CLOCK_MONOTONIC)))
514 log_debug("Running GC...");
516 m->gc_marker += _GC_OFFSET_MAX;
517 if (m->gc_marker + _GC_OFFSET_MAX <= _GC_OFFSET_MAX)
520 gc_marker = m->gc_marker;
522 while ((meta = m->gc_queue)) {
523 assert(meta->in_gc_queue);
525 unit_gc_sweep(UNIT(meta), gc_marker);
527 LIST_REMOVE(Meta, gc_queue, m->gc_queue, meta);
528 meta->in_gc_queue = false;
532 if (meta->gc_marker == gc_marker + GC_OFFSET_BAD ||
533 meta->gc_marker == gc_marker + GC_OFFSET_UNSURE) {
534 log_debug("Collecting %s", meta->id);
535 meta->gc_marker = gc_marker + GC_OFFSET_BAD;
536 unit_add_to_cleanup_queue(UNIT(meta));
540 m->n_in_gc_queue = 0;
541 m->gc_queue_timestamp = 0;
546 static void manager_clear_jobs_and_units(Manager *m) {
552 while ((j = hashmap_first(m->transaction_jobs)))
555 while ((u = hashmap_first(m->units)))
558 manager_dispatch_cleanup_queue(m);
560 assert(!m->load_queue);
561 assert(!m->run_queue);
562 assert(!m->dbus_unit_queue);
563 assert(!m->dbus_job_queue);
564 assert(!m->cleanup_queue);
565 assert(!m->gc_queue);
567 assert(hashmap_isempty(m->transaction_jobs));
568 assert(hashmap_isempty(m->jobs));
569 assert(hashmap_isempty(m->units));
572 void manager_free(Manager *m) {
577 manager_clear_jobs_and_units(m);
579 for (c = 0; c < _UNIT_TYPE_MAX; c++)
580 if (unit_vtable[c]->shutdown)
581 unit_vtable[c]->shutdown(m);
583 /* If we reexecute ourselves, we keep the root cgroup
585 manager_shutdown_cgroup(m, m->exit_code != MANAGER_REEXECUTE);
590 hashmap_free(m->units);
591 hashmap_free(m->jobs);
592 hashmap_free(m->transaction_jobs);
593 hashmap_free(m->watch_pids);
594 hashmap_free(m->watch_bus);
596 if (m->epoll_fd >= 0)
597 close_nointr_nofail(m->epoll_fd);
598 if (m->signal_watch.fd >= 0)
599 close_nointr_nofail(m->signal_watch.fd);
601 strv_free(m->unit_path);
602 strv_free(m->sysvinit_path);
603 strv_free(m->sysvrcnd_path);
604 strv_free(m->environment);
606 free(m->cgroup_controller);
607 free(m->cgroup_hierarchy);
609 hashmap_free(m->cgroup_bondings);
614 int manager_enumerate(Manager *m) {
620 /* Let's ask every type to load all units from disk/kernel
621 * that it might know */
622 for (c = 0; c < _UNIT_TYPE_MAX; c++)
623 if (unit_vtable[c]->enumerate)
624 if ((q = unit_vtable[c]->enumerate(m)) < 0)
627 manager_dispatch_load_queue(m);
631 int manager_coldplug(Manager *m) {
639 /* Then, let's set up their initial state. */
640 HASHMAP_FOREACH_KEY(u, k, m->units, i) {
646 if ((q = unit_coldplug(u)) < 0)
653 int manager_startup(Manager *m, FILE *serialization, FDSet *fds) {
658 /* First, enumerate what we can from all config files */
659 r = manager_enumerate(m);
661 /* Second, deserialize if there is something to deserialize */
663 if ((q = manager_deserialize(m, serialization, fds)) < 0)
666 /* Third, fire things up! */
667 if ((q = manager_coldplug(m)) < 0)
670 /* Now that the initial devices are available, let's see if we
671 * can write the utmp file */
672 manager_write_utmp_reboot(m);
677 static void transaction_delete_job(Manager *m, Job *j, bool delete_dependencies) {
681 /* Deletes one job from the transaction */
683 manager_transaction_unlink_job(m, j, delete_dependencies);
689 static void transaction_delete_unit(Manager *m, Unit *u) {
692 /* Deletes all jobs associated with a certain unit from the
695 while ((j = hashmap_get(m->transaction_jobs, u)))
696 transaction_delete_job(m, j, true);
699 static void transaction_clean_dependencies(Manager *m) {
705 /* Drops all dependencies of all installed jobs */
707 HASHMAP_FOREACH(j, m->jobs, i) {
708 while (j->subject_list)
709 job_dependency_free(j->subject_list);
710 while (j->object_list)
711 job_dependency_free(j->object_list);
714 assert(!m->transaction_anchor);
717 static void transaction_abort(Manager *m) {
722 while ((j = hashmap_first(m->transaction_jobs)))
724 transaction_delete_job(m, j, true);
728 assert(hashmap_isempty(m->transaction_jobs));
730 transaction_clean_dependencies(m);
733 static void transaction_find_jobs_that_matter_to_anchor(Manager *m, Job *j, unsigned generation) {
738 /* A recursive sweep through the graph that marks all units
739 * that matter to the anchor job, i.e. are directly or
740 * indirectly a dependency of the anchor job via paths that
741 * are fully marked as mattering. */
746 l = m->transaction_anchor;
748 LIST_FOREACH(subject, l, l) {
750 /* This link does not matter */
754 /* This unit has already been marked */
755 if (l->object->generation == generation)
758 l->object->matters_to_anchor = true;
759 l->object->generation = generation;
761 transaction_find_jobs_that_matter_to_anchor(m, l->object, generation);
765 static void transaction_merge_and_delete_job(Manager *m, Job *j, Job *other, JobType t) {
766 JobDependency *l, *last;
770 assert(j->unit == other->unit);
771 assert(!j->installed);
773 /* Merges 'other' into 'j' and then deletes j. */
776 j->state = JOB_WAITING;
777 j->override = j->override || other->override;
779 j->matters_to_anchor = j->matters_to_anchor || other->matters_to_anchor;
781 /* Patch us in as new owner of the JobDependency objects */
783 LIST_FOREACH(subject, l, other->subject_list) {
784 assert(l->subject == other);
789 /* Merge both lists */
791 last->subject_next = j->subject_list;
793 j->subject_list->subject_prev = last;
794 j->subject_list = other->subject_list;
797 /* Patch us in as new owner of the JobDependency objects */
799 LIST_FOREACH(object, l, other->object_list) {
800 assert(l->object == other);
805 /* Merge both lists */
807 last->object_next = j->object_list;
809 j->object_list->object_prev = last;
810 j->object_list = other->object_list;
813 /* Kill the other job */
814 other->subject_list = NULL;
815 other->object_list = NULL;
816 transaction_delete_job(m, other, true);
819 static int delete_one_unmergeable_job(Manager *m, Job *j) {
824 /* Tries to delete one item in the linked list
825 * j->transaction_next->transaction_next->... that conflicts
826 * whith another one, in an attempt to make an inconsistent
827 * transaction work. */
829 /* We rely here on the fact that if a merged with b does not
830 * merge with c, either a or b merge with c neither */
831 LIST_FOREACH(transaction, j, j)
832 LIST_FOREACH(transaction, k, j->transaction_next) {
835 /* Is this one mergeable? Then skip it */
836 if (job_type_is_mergeable(j->type, k->type))
839 /* Ok, we found two that conflict, let's see if we can
840 * drop one of them */
841 if (!j->matters_to_anchor)
843 else if (!k->matters_to_anchor)
848 /* Ok, we can drop one, so let's do so. */
849 log_debug("Trying to fix job merging by deleting job %s/%s", d->unit->meta.id, job_type_to_string(d->type));
850 transaction_delete_job(m, d, true);
857 static int transaction_merge_jobs(Manager *m) {
864 /* First step, check whether any of the jobs for one specific
865 * task conflict. If so, try to drop one of them. */
866 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
871 LIST_FOREACH(transaction, k, j->transaction_next) {
872 if ((r = job_type_merge(&t, k->type)) >= 0)
875 /* OK, we could not merge all jobs for this
876 * action. Let's see if we can get rid of one
879 if ((r = delete_one_unmergeable_job(m, j)) >= 0)
880 /* Ok, we managed to drop one, now
881 * let's ask our callers to call us
882 * again after garbage collecting */
885 /* We couldn't merge anything. Failure */
890 /* Second step, merge the jobs. */
891 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
895 /* Merge all transactions */
896 LIST_FOREACH(transaction, k, j->transaction_next)
897 assert_se(job_type_merge(&t, k->type) == 0);
899 /* If an active job is mergeable, merge it too */
900 if (j->unit->meta.job)
901 job_type_merge(&t, j->unit->meta.job->type); /* Might fail. Which is OK */
903 while ((k = j->transaction_next)) {
905 transaction_merge_and_delete_job(m, k, j, t);
908 transaction_merge_and_delete_job(m, j, k, t);
911 assert(!j->transaction_next);
912 assert(!j->transaction_prev);
918 static void transaction_drop_redundant(Manager *m) {
923 /* Goes through the transaction and removes all jobs that are
932 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
933 bool changes_something = false;
936 LIST_FOREACH(transaction, k, j) {
938 if (!job_is_anchor(k) &&
939 job_type_is_redundant(k->type, unit_active_state(k->unit)))
942 changes_something = true;
946 if (changes_something)
949 log_debug("Found redundant job %s/%s, dropping.", j->unit->meta.id, job_type_to_string(j->type));
950 transaction_delete_job(m, j, false);
958 static bool unit_matters_to_anchor(Unit *u, Job *j) {
960 assert(!j->transaction_prev);
962 /* Checks whether at least one of the jobs for this unit
963 * matters to the anchor. */
965 LIST_FOREACH(transaction, j, j)
966 if (j->matters_to_anchor)
972 static int transaction_verify_order_one(Manager *m, Job *j, Job *from, unsigned generation) {
979 assert(!j->transaction_prev);
981 /* Does a recursive sweep through the ordering graph, looking
982 * for a cycle. If we find cycle we try to break it. */
984 /* Have we seen this before? */
985 if (j->generation == generation) {
988 /* If the marker is NULL we have been here already and
989 * decided the job was loop-free from here. Hence
990 * shortcut things and return right-away. */
994 /* So, the marker is not NULL and we already have been
995 * here. We have a cycle. Let's try to break it. We go
996 * backwards in our path and try to find a suitable
997 * job to remove. We use the marker to find our way
998 * back, since smart how we are we stored our way back
1000 log_debug("Found ordering cycle on %s/%s", j->unit->meta.id, job_type_to_string(j->type));
1002 for (k = from; k; k = ((k->generation == generation && k->marker != k) ? k->marker : NULL)) {
1004 log_debug("Walked on cycle path to %s/%s", k->unit->meta.id, job_type_to_string(k->type));
1006 if (!k->installed &&
1007 !unit_matters_to_anchor(k->unit, k)) {
1008 /* Ok, we can drop this one, so let's
1010 log_debug("Breaking order cycle by deleting job %s/%s", k->unit->meta.id, job_type_to_string(k->type));
1011 transaction_delete_unit(m, k->unit);
1015 /* Check if this in fact was the beginning of
1021 log_debug("Unable to break cycle");
1026 /* Make the marker point to where we come from, so that we can
1027 * find our way backwards if we want to break a cycle. We use
1028 * a special marker for the beginning: we point to
1030 j->marker = from ? from : j;
1031 j->generation = generation;
1033 /* We assume that the the dependencies are bidirectional, and
1034 * hence can ignore UNIT_AFTER */
1035 SET_FOREACH(u, j->unit->meta.dependencies[UNIT_BEFORE], i) {
1038 /* Is there a job for this unit? */
1039 if (!(o = hashmap_get(m->transaction_jobs, u)))
1041 /* Ok, there is no job for this in the
1042 * transaction, but maybe there is already one
1044 if (!(o = u->meta.job))
1047 if ((r = transaction_verify_order_one(m, o, j, generation)) < 0)
1051 /* Ok, let's backtrack, and remember that this entry is not on
1052 * our path anymore. */
1058 static int transaction_verify_order(Manager *m, unsigned *generation) {
1067 /* Check if the ordering graph is cyclic. If it is, try to fix
1068 * that up by dropping one of the jobs. */
1070 g = (*generation)++;
1072 HASHMAP_FOREACH(j, m->transaction_jobs, i)
1073 if ((r = transaction_verify_order_one(m, j, NULL, g)) < 0)
1079 static void transaction_collect_garbage(Manager *m) {
1084 /* Drop jobs that are not required by any other job */
1092 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1096 log_debug("Garbage collecting job %s/%s", j->unit->meta.id, job_type_to_string(j->type));
1097 transaction_delete_job(m, j, true);
1105 static int transaction_is_destructive(Manager *m) {
1111 /* Checks whether applying this transaction means that
1112 * existing jobs would be replaced */
1114 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1117 assert(!j->transaction_prev);
1118 assert(!j->transaction_next);
1120 if (j->unit->meta.job &&
1121 j->unit->meta.job != j &&
1122 !job_type_is_superset(j->type, j->unit->meta.job->type))
1129 static void transaction_minimize_impact(Manager *m) {
1133 /* Drops all unnecessary jobs that reverse already active jobs
1134 * or that stop a running service. */
1142 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1143 LIST_FOREACH(transaction, j, j) {
1144 bool stops_running_service, changes_existing_job;
1146 /* If it matters, we shouldn't drop it */
1147 if (j->matters_to_anchor)
1150 /* Would this stop a running service?
1151 * Would this change an existing job?
1152 * If so, let's drop this entry */
1154 stops_running_service =
1155 j->type == JOB_STOP && UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(j->unit));
1157 changes_existing_job =
1158 j->unit->meta.job && job_type_is_conflicting(j->type, j->unit->meta.job->state);
1160 if (!stops_running_service && !changes_existing_job)
1163 if (stops_running_service)
1164 log_debug("%s/%s would stop a running service.", j->unit->meta.id, job_type_to_string(j->type));
1166 if (changes_existing_job)
1167 log_debug("%s/%s would change existing job.", j->unit->meta.id, job_type_to_string(j->type));
1169 /* Ok, let's get rid of this */
1170 log_debug("Deleting %s/%s to minimize impact.", j->unit->meta.id, job_type_to_string(j->type));
1172 transaction_delete_job(m, j, true);
1184 static int transaction_apply(Manager *m) {
1189 /* Moves the transaction jobs to the set of active jobs */
1191 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1193 assert(!j->transaction_prev);
1194 assert(!j->transaction_next);
1199 if ((r = hashmap_put(m->jobs, UINT32_TO_PTR(j->id), j)) < 0)
1203 while ((j = hashmap_steal_first(m->transaction_jobs))) {
1207 if (j->unit->meta.job)
1208 job_free(j->unit->meta.job);
1210 j->unit->meta.job = j;
1211 j->installed = true;
1213 /* We're fully installed. Now let's free data we don't
1216 assert(!j->transaction_next);
1217 assert(!j->transaction_prev);
1219 job_add_to_run_queue(j);
1220 job_add_to_dbus_queue(j);
1223 /* As last step, kill all remaining job dependencies. */
1224 transaction_clean_dependencies(m);
1230 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1234 hashmap_remove(m->jobs, UINT32_TO_PTR(j->id));
1240 static int transaction_activate(Manager *m, JobMode mode) {
1242 unsigned generation = 1;
1246 /* This applies the changes recorded in transaction_jobs to
1247 * the actual list of jobs, if possible. */
1249 /* First step: figure out which jobs matter */
1250 transaction_find_jobs_that_matter_to_anchor(m, NULL, generation++);
1252 /* Second step: Try not to stop any running services if
1253 * we don't have to. Don't try to reverse running
1254 * jobs if we don't have to. */
1255 transaction_minimize_impact(m);
1257 /* Third step: Drop redundant jobs */
1258 transaction_drop_redundant(m);
1261 /* Fourth step: Let's remove unneeded jobs that might
1263 transaction_collect_garbage(m);
1265 /* Fifth step: verify order makes sense and correct
1266 * cycles if necessary and possible */
1267 if ((r = transaction_verify_order(m, &generation)) >= 0)
1271 log_debug("Requested transaction contains an unfixable cyclic ordering dependency: %s", strerror(-r));
1275 /* Let's see if the resulting transaction ordering
1276 * graph is still cyclic... */
1280 /* Sixth step: let's drop unmergeable entries if
1281 * necessary and possible, merge entries we can
1283 if ((r = transaction_merge_jobs(m)) >= 0)
1287 log_debug("Requested transaction contains unmergable jobs: %s", strerror(-r));
1291 /* Seventh step: an entry got dropped, let's garbage
1292 * collect its dependencies. */
1293 transaction_collect_garbage(m);
1295 /* Let's see if the resulting transaction still has
1296 * unmergeable entries ... */
1299 /* Eights step: Drop redundant jobs again, if the merging now allows us to drop more. */
1300 transaction_drop_redundant(m);
1302 /* Ninth step: check whether we can actually apply this */
1303 if (mode == JOB_FAIL)
1304 if ((r = transaction_is_destructive(m)) < 0) {
1305 log_debug("Requested transaction contradicts existing jobs: %s", strerror(-r));
1309 /* Tenth step: apply changes */
1310 if ((r = transaction_apply(m)) < 0) {
1311 log_debug("Failed to apply transaction: %s", strerror(-r));
1315 assert(hashmap_isempty(m->transaction_jobs));
1316 assert(!m->transaction_anchor);
1321 transaction_abort(m);
1325 static Job* transaction_add_one_job(Manager *m, JobType type, Unit *unit, bool override, bool *is_new) {
1332 /* Looks for an axisting prospective job and returns that. If
1333 * it doesn't exist it is created and added to the prospective
1336 f = hashmap_get(m->transaction_jobs, unit);
1338 LIST_FOREACH(transaction, j, f) {
1339 assert(j->unit == unit);
1341 if (j->type == type) {
1348 if (unit->meta.job && unit->meta.job->type == type)
1350 else if (!(j = job_new(m, type, unit)))
1355 j->matters_to_anchor = false;
1356 j->override = override;
1358 LIST_PREPEND(Job, transaction, f, j);
1360 if ((r = hashmap_replace(m->transaction_jobs, unit, f)) < 0) {
1368 log_debug("Added job %s/%s to transaction.", unit->meta.id, job_type_to_string(type));
1373 void manager_transaction_unlink_job(Manager *m, Job *j, bool delete_dependencies) {
1377 if (j->transaction_prev)
1378 j->transaction_prev->transaction_next = j->transaction_next;
1379 else if (j->transaction_next)
1380 hashmap_replace(m->transaction_jobs, j->unit, j->transaction_next);
1382 hashmap_remove_value(m->transaction_jobs, j->unit, j);
1384 if (j->transaction_next)
1385 j->transaction_next->transaction_prev = j->transaction_prev;
1387 j->transaction_prev = j->transaction_next = NULL;
1389 while (j->subject_list)
1390 job_dependency_free(j->subject_list);
1392 while (j->object_list) {
1393 Job *other = j->object_list->matters ? j->object_list->subject : NULL;
1395 job_dependency_free(j->object_list);
1397 if (other && delete_dependencies) {
1398 log_debug("Deleting job %s/%s as dependency of job %s/%s",
1399 other->unit->meta.id, job_type_to_string(other->type),
1400 j->unit->meta.id, job_type_to_string(j->type));
1401 transaction_delete_job(m, other, delete_dependencies);
1406 static int transaction_add_job_and_dependencies(
1421 assert(type < _JOB_TYPE_MAX);
1424 if (unit->meta.load_state != UNIT_LOADED)
1427 if (!unit_job_is_applicable(unit, type))
1430 /* First add the job. */
1431 if (!(ret = transaction_add_one_job(m, type, unit, override, &is_new)))
1434 /* Then, add a link to the job. */
1435 if (!job_dependency_new(by, ret, matters))
1439 /* Finally, recursively add in all dependencies. */
1440 if (type == JOB_START || type == JOB_RELOAD_OR_START) {
1441 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES], i)
1442 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, true, override, NULL)) < 0 && r != -EBADR)
1445 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES_OVERRIDABLE], i)
1446 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, !override, override, NULL)) < 0 && r != -EBADR)
1447 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, strerror(-r));
1449 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_WANTS], i)
1450 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, false, false, NULL)) < 0)
1451 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, strerror(-r));
1453 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE], i)
1454 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, true, override, NULL)) < 0 && r != -EBADR)
1457 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE_OVERRIDABLE], i)
1458 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, !override, override, NULL)) < 0 && r != -EBADR)
1459 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, strerror(-r));
1461 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_CONFLICTS], i)
1462 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, dep, ret, true, override, NULL)) < 0 && r != -EBADR)
1465 } else if (type == JOB_STOP || type == JOB_RESTART || type == JOB_TRY_RESTART) {
1467 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRED_BY], i)
1468 if ((r = transaction_add_job_and_dependencies(m, type, dep, ret, true, override, NULL)) < 0 && r != -EBADR)
1472 /* JOB_VERIFY_STARTED, JOB_RELOAD require no dependency handling */
1484 static int transaction_add_isolate_jobs(Manager *m) {
1492 HASHMAP_FOREACH_KEY(u, k, m->units, i) {
1494 /* ignore aliases */
1495 if (u->meta.id != k)
1498 if (UNIT_VTABLE(u)->no_isolate)
1501 /* No need to stop inactive jobs */
1502 if (unit_active_state(u) == UNIT_INACTIVE)
1505 /* Is there already something listed for this? */
1506 if (hashmap_get(m->transaction_jobs, u))
1509 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, u, NULL, true, false, NULL)) < 0)
1510 log_warning("Cannot add isolate job for unit %s, ignoring: %s", u->meta.id, strerror(-r));
1516 int manager_add_job(Manager *m, JobType type, Unit *unit, JobMode mode, bool override, Job **_ret) {
1521 assert(type < _JOB_TYPE_MAX);
1523 assert(mode < _JOB_MODE_MAX);
1525 if (mode == JOB_ISOLATE && type != JOB_START)
1528 log_debug("Trying to enqueue job %s/%s", unit->meta.id, job_type_to_string(type));
1530 if ((r = transaction_add_job_and_dependencies(m, type, unit, NULL, true, override, &ret)) < 0) {
1531 transaction_abort(m);
1535 if (mode == JOB_ISOLATE)
1536 if ((r = transaction_add_isolate_jobs(m)) < 0) {
1537 transaction_abort(m);
1541 if ((r = transaction_activate(m, mode)) < 0)
1544 log_debug("Enqueued job %s/%s as %u", unit->meta.id, job_type_to_string(type), (unsigned) ret->id);
1552 int manager_add_job_by_name(Manager *m, JobType type, const char *name, JobMode mode, bool override, Job **_ret) {
1557 assert(type < _JOB_TYPE_MAX);
1559 assert(mode < _JOB_MODE_MAX);
1561 if ((r = manager_load_unit(m, name, NULL, &unit)) < 0)
1564 return manager_add_job(m, type, unit, mode, override, _ret);
1567 Job *manager_get_job(Manager *m, uint32_t id) {
1570 return hashmap_get(m->jobs, UINT32_TO_PTR(id));
1573 Unit *manager_get_unit(Manager *m, const char *name) {
1577 return hashmap_get(m->units, name);
1580 unsigned manager_dispatch_load_queue(Manager *m) {
1586 /* Make sure we are not run recursively */
1587 if (m->dispatching_load_queue)
1590 m->dispatching_load_queue = true;
1592 /* Dispatches the load queue. Takes a unit from the queue and
1593 * tries to load its data until the queue is empty */
1595 while ((meta = m->load_queue)) {
1596 assert(meta->in_load_queue);
1598 unit_load(UNIT(meta));
1602 m->dispatching_load_queue = false;
1606 int manager_load_unit_prepare(Manager *m, const char *name, const char *path, Unit **_ret) {
1611 assert(name || path);
1613 /* This will prepare the unit for loading, but not actually
1614 * load anything from disk. */
1616 if (path && !is_path(path))
1620 name = file_name_from_path(path);
1622 if (!unit_name_is_valid(name))
1625 if ((ret = manager_get_unit(m, name))) {
1630 if (!(ret = unit_new(m)))
1634 if (!(ret->meta.fragment_path = strdup(path))) {
1639 if ((r = unit_add_name(ret, name)) < 0) {
1644 unit_add_to_load_queue(ret);
1645 unit_add_to_dbus_queue(ret);
1646 unit_add_to_gc_queue(ret);
1654 int manager_load_unit(Manager *m, const char *name, const char *path, Unit **_ret) {
1659 /* This will load the service information files, but not actually
1660 * start any services or anything. */
1662 if ((r = manager_load_unit_prepare(m, name, path, _ret)) != 0)
1665 manager_dispatch_load_queue(m);
1668 *_ret = unit_follow_merge(*_ret);
1673 void manager_dump_jobs(Manager *s, FILE *f, const char *prefix) {
1680 HASHMAP_FOREACH(j, s->jobs, i)
1681 job_dump(j, f, prefix);
1684 void manager_dump_units(Manager *s, FILE *f, const char *prefix) {
1692 HASHMAP_FOREACH_KEY(u, t, s->units, i)
1693 if (u->meta.id == t)
1694 unit_dump(u, f, prefix);
1697 void manager_clear_jobs(Manager *m) {
1702 transaction_abort(m);
1704 while ((j = hashmap_first(m->jobs)))
1708 unsigned manager_dispatch_run_queue(Manager *m) {
1712 if (m->dispatching_run_queue)
1715 m->dispatching_run_queue = true;
1717 while ((j = m->run_queue)) {
1718 assert(j->installed);
1719 assert(j->in_run_queue);
1721 job_run_and_invalidate(j);
1725 m->dispatching_run_queue = false;
1729 unsigned manager_dispatch_dbus_queue(Manager *m) {
1736 if (m->dispatching_dbus_queue)
1739 m->dispatching_dbus_queue = true;
1741 while ((meta = m->dbus_unit_queue)) {
1742 assert(meta->in_dbus_queue);
1744 bus_unit_send_change_signal(UNIT(meta));
1748 while ((j = m->dbus_job_queue)) {
1749 assert(j->in_dbus_queue);
1751 bus_job_send_change_signal(j);
1755 m->dispatching_dbus_queue = false;
1759 static int manager_dispatch_sigchld(Manager *m) {
1768 /* First we call waitd() for a PID and do not reap the
1769 * zombie. That way we can still access /proc/$PID for
1770 * it while it is a zombie. */
1771 if (waitid(P_ALL, 0, &si, WEXITED|WNOHANG|WNOWAIT) < 0) {
1773 if (errno == ECHILD)
1785 if (si.si_code == CLD_EXITED || si.si_code == CLD_KILLED || si.si_code == CLD_DUMPED) {
1788 get_process_name(si.si_pid, &name);
1789 log_debug("Got SIGCHLD for process %llu (%s)", (unsigned long long) si.si_pid, strna(name));
1793 /* And now, we actually reap the zombie. */
1794 if (waitid(P_PID, si.si_pid, &si, WEXITED) < 0) {
1801 if (si.si_code != CLD_EXITED && si.si_code != CLD_KILLED && si.si_code != CLD_DUMPED)
1804 log_debug("Child %llu died (code=%s, status=%i/%s)",
1805 (long long unsigned) si.si_pid,
1806 sigchld_code_to_string(si.si_code),
1808 strna(si.si_code == CLD_EXITED ? exit_status_to_string(si.si_status) : strsignal(si.si_status)));
1810 if (!(u = hashmap_remove(m->watch_pids, UINT32_TO_PTR(si.si_pid))))
1813 log_debug("Child %llu belongs to %s", (long long unsigned) si.si_pid, u->meta.id);
1815 UNIT_VTABLE(u)->sigchld_event(u, si.si_pid, si.si_code, si.si_status);
1821 static int manager_start_target(Manager *m, const char *name) {
1824 if ((r = manager_add_job_by_name(m, JOB_START, name, JOB_REPLACE, true, NULL)) < 0)
1825 log_error("Failed to enqueue %s job: %s", name, strerror(-r));
1830 static int manager_process_signal_fd(Manager *m) {
1832 struct signalfd_siginfo sfsi;
1833 bool sigchld = false;
1838 if ((n = read(m->signal_watch.fd, &sfsi, sizeof(sfsi))) != sizeof(sfsi)) {
1843 if (errno == EAGAIN)
1849 switch (sfsi.ssi_signo) {
1856 if (m->running_as == MANAGER_INIT) {
1857 /* This is for compatibility with the
1858 * original sysvinit */
1859 m->exit_code = MANAGER_REEXECUTE;
1866 if (m->running_as == MANAGER_INIT) {
1867 manager_start_target(m, SPECIAL_CTRL_ALT_DEL_TARGET);
1871 /* Run the exit target if there is one, if not, just exit. */
1872 if (manager_start_target(m, SPECIAL_EXIT_SERVICE) < 0) {
1873 m->exit_code = MANAGER_EXIT;
1880 if (m->running_as == MANAGER_INIT)
1881 manager_start_target(m, SPECIAL_KBREQUEST_TARGET);
1883 /* This is a nop on non-init */
1887 if (m->running_as == MANAGER_INIT)
1888 manager_start_target(m, SPECIAL_SIGPWR_TARGET);
1890 /* This is a nop on non-init */
1896 u = manager_get_unit(m, SPECIAL_DBUS_SERVICE);
1898 if (!u || UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u))) {
1899 log_info("Trying to reconnect to bus...");
1904 if (!u || !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u))) {
1905 log_info("Loading D-Bus service...");
1906 manager_start_target(m, SPECIAL_DBUS_SERVICE);
1917 if (!(f = open_memstream(&dump, &size))) {
1918 log_warning("Failed to allocate memory stream.");
1922 manager_dump_units(m, f, "\t");
1923 manager_dump_jobs(m, f, "\t");
1928 log_warning("Failed to write status stream");
1933 log_dump(LOG_INFO, dump);
1940 m->exit_code = MANAGER_RELOAD;
1944 log_info("Got unhandled signal <%s>.", strsignal(sfsi.ssi_signo));
1949 return manager_dispatch_sigchld(m);
1954 static int process_event(Manager *m, struct epoll_event *ev) {
1961 assert(w = ev->data.ptr);
1967 /* An incoming signal? */
1968 if (ev->events != EPOLLIN)
1971 if ((r = manager_process_signal_fd(m)) < 0)
1978 /* Some fd event, to be dispatched to the units */
1979 UNIT_VTABLE(w->data.unit)->fd_event(w->data.unit, w->fd, ev->events, w);
1986 /* Some timer event, to be dispatched to the units */
1987 if ((k = read(w->fd, &v, sizeof(v))) != sizeof(v)) {
1989 if (k < 0 && (errno == EINTR || errno == EAGAIN))
1992 return k < 0 ? -errno : -EIO;
1995 UNIT_VTABLE(w->data.unit)->timer_event(w->data.unit, v, w);
2000 /* Some mount table change, intended for the mount subsystem */
2001 mount_fd_event(m, ev->events);
2005 /* Some notification from udev, intended for the device subsystem */
2006 device_fd_event(m, ev->events);
2009 case WATCH_DBUS_WATCH:
2010 bus_watch_event(m, w, ev->events);
2013 case WATCH_DBUS_TIMEOUT:
2014 bus_timeout_event(m, w, ev->events);
2018 assert_not_reached("Unknown epoll event type.");
2024 int manager_loop(Manager *m) {
2027 RATELIMIT_DEFINE(rl, 1*USEC_PER_SEC, 1000);
2030 m->exit_code = MANAGER_RUNNING;
2032 /* There might still be some zombies hanging around from
2033 * before we were exec()'ed. Leat's reap them */
2034 if ((r = manager_dispatch_sigchld(m)) < 0)
2037 while (m->exit_code == MANAGER_RUNNING) {
2038 struct epoll_event event;
2041 if (!ratelimit_test(&rl)) {
2042 /* Yay, something is going seriously wrong, pause a little */
2043 log_warning("Looping too fast. Throttling execution a little.");
2047 if (manager_dispatch_load_queue(m) > 0)
2050 if (manager_dispatch_run_queue(m) > 0)
2053 if (bus_dispatch(m) > 0)
2056 if (manager_dispatch_cleanup_queue(m) > 0)
2059 if (manager_dispatch_gc_queue(m) > 0)
2062 if (manager_dispatch_dbus_queue(m) > 0)
2065 if ((n = epoll_wait(m->epoll_fd, &event, 1, -1)) < 0) {
2075 if ((r = process_event(m, &event)) < 0)
2079 return m->exit_code;
2082 int manager_get_unit_from_dbus_path(Manager *m, const char *s, Unit **_u) {
2090 if (!startswith(s, "/org/freedesktop/systemd1/unit/"))
2093 if (!(n = bus_path_unescape(s+31)))
2096 u = manager_get_unit(m, n);
2107 int manager_get_job_from_dbus_path(Manager *m, const char *s, Job **_j) {
2116 if (!startswith(s, "/org/freedesktop/systemd1/job/"))
2119 if ((r = safe_atou(s + 30, &id)) < 0)
2122 if (!(j = manager_get_job(m, id)))
2130 static bool manager_utmp_good(Manager *m) {
2135 if ((r = mount_path_is_mounted(m, _PATH_UTMPX)) <= 0) {
2138 log_warning("Failed to determine whether " _PATH_UTMPX " is mounted: %s", strerror(-r));
2146 void manager_write_utmp_reboot(Manager *m) {
2151 if (m->utmp_reboot_written)
2154 if (m->running_as != MANAGER_INIT)
2157 if (!manager_utmp_good(m))
2160 if ((r = utmp_put_reboot(m->startup_timestamp.realtime)) < 0) {
2162 if (r != -ENOENT && r != -EROFS)
2163 log_warning("Failed to write utmp/wtmp: %s", strerror(-r));
2168 m->utmp_reboot_written = true;
2171 void manager_write_utmp_runlevel(Manager *m, Unit *u) {
2177 if (u->meta.type != UNIT_TARGET)
2180 if (m->running_as != MANAGER_INIT)
2183 if (!manager_utmp_good(m))
2186 if ((runlevel = target_get_runlevel(TARGET(u))) <= 0)
2189 if ((r = utmp_put_runlevel(0, runlevel, 0)) < 0) {
2191 if (r != -ENOENT && r != -EROFS)
2192 log_warning("Failed to write utmp/wtmp: %s", strerror(-r));
2196 void manager_dispatch_bus_name_owner_changed(
2199 const char* old_owner,
2200 const char *new_owner) {
2207 if (!(u = hashmap_get(m->watch_bus, name)))
2210 UNIT_VTABLE(u)->bus_name_owner_change(u, name, old_owner, new_owner);
2213 void manager_dispatch_bus_query_pid_done(
2224 if (!(u = hashmap_get(m->watch_bus, name)))
2227 UNIT_VTABLE(u)->bus_query_pid_done(u, name, pid);
2230 int manager_open_serialization(FILE **_f) {
2238 if (asprintf(&path, "/dev/shm/systemd-%u.dump-XXXXXX", (unsigned) getpid()) < 0)
2241 saved_umask = umask(0077);
2242 fd = mkostemp(path, O_RDWR|O_CLOEXEC);
2252 log_debug("Serializing state to %s", path);
2255 if (!(f = fdopen(fd, "w+")) < 0)
2263 int manager_serialize(Manager *m, FILE *f, FDSet *fds) {
2273 HASHMAP_FOREACH_KEY(u, t, m->units, i) {
2274 if (u->meta.id != t)
2277 if (!unit_can_serialize(u))
2281 fputs(u->meta.id, f);
2284 if ((r = unit_serialize(u, f, fds)) < 0)
2294 int manager_deserialize(Manager *m, FILE *f, FDSet *fds) {
2300 log_debug("Deserializing state...");
2304 char name[UNIT_NAME_MAX+2];
2307 if (!fgets(name, sizeof(name), f)) {
2316 if ((r = manager_load_unit(m, strstrip(name), NULL, &u)) < 0)
2319 if ((r = unit_deserialize(u, f, fds)) < 0)
2329 int manager_reload(Manager *m) {
2336 if ((r = manager_open_serialization(&f)) < 0)
2339 if (!(fds = fdset_new())) {
2344 if ((r = manager_serialize(m, f, fds)) < 0)
2347 if (fseeko(f, 0, SEEK_SET) < 0) {
2352 /* From here on there is no way back. */
2353 manager_clear_jobs_and_units(m);
2355 /* Find new unit paths */
2356 if ((q = manager_find_paths(m)) < 0)
2359 /* First, enumerate what we can from all config files */
2360 if ((q = manager_enumerate(m)) < 0)
2363 /* Second, deserialize our stored data */
2364 if ((q = manager_deserialize(m, f, fds)) < 0)
2370 /* Third, fire things up! */
2371 if ((q = manager_coldplug(m)) < 0)
2384 static const char* const manager_running_as_table[_MANAGER_RUNNING_AS_MAX] = {
2385 [MANAGER_INIT] = "init",
2386 [MANAGER_SYSTEM] = "system",
2387 [MANAGER_SESSION] = "session"
2390 DEFINE_STRING_TABLE_LOOKUP(manager_running_as, ManagerRunningAs);