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"
55 #include "path-lookup.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;
78 m->notify_watch.type = WATCH_NOTIFY;
79 if ((m->notify_watch.fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0)) < 0) {
80 log_error("Failed to allocate notification socket: %m");
85 sa.sa.sa_family = AF_UNIX;
87 if (m->running_as == MANAGER_SESSION)
88 snprintf(sa.un.sun_path+1, sizeof(sa.un.sun_path)-1, NOTIFY_SOCKET "/%llu", random_ull());
90 strncpy(sa.un.sun_path+1, NOTIFY_SOCKET, sizeof(sa.un.sun_path)-1);
92 if (bind(m->notify_watch.fd, &sa.sa, sizeof(sa)) < 0) {
93 log_error("bind() failed: %m");
97 if (setsockopt(m->notify_watch.fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one)) < 0) {
98 log_error("SO_PASSCRED failed: %m");
104 ev.data.ptr = &m->notify_watch;
106 if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->notify_watch.fd, &ev) < 0)
109 if (asprintf(&ne[0], "NOTIFY_SOCKET=@%s", sa.un.sun_path+1) < 0)
113 t = strv_env_merge(2, m->environment, ne);
119 strv_free(m->environment);
125 static int enable_special_signals(Manager *m) {
130 /* Enable that we get SIGINT on control-alt-del */
131 if (reboot(RB_DISABLE_CAD) < 0)
132 log_warning("Failed to enable ctrl-alt-del handling: %m");
134 if ((fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY)) < 0)
135 log_warning("Failed to open /dev/tty0: %m");
137 /* Enable that we get SIGWINCH on kbrequest */
138 if (ioctl(fd, KDSIGACCEPT, SIGWINCH) < 0)
139 log_warning("Failed to enable kbrequest handling: %s", strerror(errno));
141 close_nointr_nofail(fd);
147 static int manager_setup_signals(Manager *m) {
149 struct epoll_event ev;
154 /* We are not interested in SIGSTOP and friends. */
156 sa.sa_handler = SIG_DFL;
157 sa.sa_flags = SA_NOCLDSTOP|SA_RESTART;
158 assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);
160 assert_se(sigemptyset(&mask) == 0);
162 sigset_add_many(&mask,
163 SIGCHLD, /* Child died */
164 SIGTERM, /* Reexecute daemon */
165 SIGHUP, /* Reload configuration */
166 SIGUSR1, /* systemd/upstart: reconnect to D-Bus */
167 SIGUSR2, /* systemd: dump status */
168 SIGINT, /* Kernel sends us this on control-alt-del */
169 SIGWINCH, /* Kernel sends us this on kbrequest (alt-arrowup) */
170 SIGPWR, /* Some kernel drivers and upsd send us this on power failure */
171 SIGRTMIN+0, /* systemd: start default.target */
172 SIGRTMIN+1, /* systemd: start rescue.target */
173 SIGRTMIN+2, /* systemd: isolate emergency.target */
174 SIGRTMIN+3, /* systemd: start halt.target */
175 SIGRTMIN+4, /* systemd: start poweroff.target */
176 SIGRTMIN+5, /* systemd: start reboot.target */
178 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
180 m->signal_watch.type = WATCH_SIGNAL;
181 if ((m->signal_watch.fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0)
186 ev.data.ptr = &m->signal_watch;
188 if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->signal_watch.fd, &ev) < 0)
191 if (m->running_as == MANAGER_INIT)
192 return enable_special_signals(m);
197 int manager_new(ManagerRunningAs running_as, bool confirm_spawn, Manager **_m) {
203 assert(running_as >= 0);
204 assert(running_as < _MANAGER_RUNNING_AS_MAX);
206 if (!(m = new0(Manager, 1)))
209 timestamp_get(&m->startup_timestamp);
211 m->running_as = running_as;
212 m->confirm_spawn = confirm_spawn;
213 m->name_data_slot = -1;
214 m->exit_code = _MANAGER_EXIT_CODE_INVALID;
215 m->pin_cgroupfs_fd = -1;
217 m->signal_watch.fd = m->mount_watch.fd = m->udev_watch.fd = m->epoll_fd = m->dev_autofs_fd = -1;
218 m->current_job_id = 1; /* start as id #1, so that we can leave #0 around as "null-like" value */
220 if (!(m->environment = strv_copy(environ)))
223 if (!(m->units = hashmap_new(string_hash_func, string_compare_func)))
226 if (!(m->jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
229 if (!(m->transaction_jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
232 if (!(m->watch_pids = hashmap_new(trivial_hash_func, trivial_compare_func)))
235 if (!(m->cgroup_bondings = hashmap_new(string_hash_func, string_compare_func)))
238 if (!(m->watch_bus = hashmap_new(string_hash_func, string_compare_func)))
241 if ((m->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0)
244 if ((r = lookup_paths_init(&m->lookup_paths, m->running_as)) < 0)
247 if ((r = manager_setup_signals(m)) < 0)
250 if ((r = manager_setup_cgroup(m)) < 0)
253 if ((r = manager_setup_notify(m)) < 0)
256 /* Try to connect to the busses, if possible. */
257 if ((r = bus_init_system(m)) < 0 ||
258 (r = bus_init_api(m)) < 0)
261 if (asprintf(&p, "%s/%s", m->cgroup_mount_point, m->cgroup_hierarchy) < 0) {
266 m->pin_cgroupfs_fd = open(p, O_RDONLY|O_CLOEXEC|O_DIRECTORY|O_NOCTTY|O_NONBLOCK);
277 static unsigned manager_dispatch_cleanup_queue(Manager *m) {
283 while ((meta = m->cleanup_queue)) {
284 assert(meta->in_cleanup_queue);
286 unit_free(UNIT(meta));
294 GC_OFFSET_IN_PATH, /* This one is on the path we were travelling */
295 GC_OFFSET_UNSURE, /* No clue */
296 GC_OFFSET_GOOD, /* We still need this unit */
297 GC_OFFSET_BAD, /* We don't need this unit anymore */
301 static void unit_gc_sweep(Unit *u, unsigned gc_marker) {
308 if (u->meta.gc_marker == gc_marker + GC_OFFSET_GOOD ||
309 u->meta.gc_marker == gc_marker + GC_OFFSET_BAD ||
310 u->meta.gc_marker == gc_marker + GC_OFFSET_IN_PATH)
313 if (u->meta.in_cleanup_queue)
316 if (unit_check_gc(u))
319 u->meta.gc_marker = gc_marker + GC_OFFSET_IN_PATH;
323 SET_FOREACH(other, u->meta.dependencies[UNIT_REFERENCED_BY], i) {
324 unit_gc_sweep(other, gc_marker);
326 if (other->meta.gc_marker == gc_marker + GC_OFFSET_GOOD)
329 if (other->meta.gc_marker != gc_marker + GC_OFFSET_BAD)
336 /* We were unable to find anything out about this entry, so
337 * let's investigate it later */
338 u->meta.gc_marker = gc_marker + GC_OFFSET_UNSURE;
339 unit_add_to_gc_queue(u);
343 /* We definitely know that this one is not useful anymore, so
344 * let's mark it for deletion */
345 u->meta.gc_marker = gc_marker + GC_OFFSET_BAD;
346 unit_add_to_cleanup_queue(u);
350 u->meta.gc_marker = gc_marker + GC_OFFSET_GOOD;
353 static unsigned manager_dispatch_gc_queue(Manager *m) {
360 if ((m->n_in_gc_queue < GC_QUEUE_ENTRIES_MAX) &&
361 (m->gc_queue_timestamp <= 0 ||
362 (m->gc_queue_timestamp + GC_QUEUE_USEC_MAX) > now(CLOCK_MONOTONIC)))
365 log_debug("Running GC...");
367 m->gc_marker += _GC_OFFSET_MAX;
368 if (m->gc_marker + _GC_OFFSET_MAX <= _GC_OFFSET_MAX)
371 gc_marker = m->gc_marker;
373 while ((meta = m->gc_queue)) {
374 assert(meta->in_gc_queue);
376 unit_gc_sweep(UNIT(meta), gc_marker);
378 LIST_REMOVE(Meta, gc_queue, m->gc_queue, meta);
379 meta->in_gc_queue = false;
383 if (meta->gc_marker == gc_marker + GC_OFFSET_BAD ||
384 meta->gc_marker == gc_marker + GC_OFFSET_UNSURE) {
385 log_debug("Collecting %s", meta->id);
386 meta->gc_marker = gc_marker + GC_OFFSET_BAD;
387 unit_add_to_cleanup_queue(UNIT(meta));
391 m->n_in_gc_queue = 0;
392 m->gc_queue_timestamp = 0;
397 static void manager_clear_jobs_and_units(Manager *m) {
403 while ((j = hashmap_first(m->transaction_jobs)))
406 while ((u = hashmap_first(m->units)))
409 manager_dispatch_cleanup_queue(m);
411 assert(!m->load_queue);
412 assert(!m->run_queue);
413 assert(!m->dbus_unit_queue);
414 assert(!m->dbus_job_queue);
415 assert(!m->cleanup_queue);
416 assert(!m->gc_queue);
418 assert(hashmap_isempty(m->transaction_jobs));
419 assert(hashmap_isempty(m->jobs));
420 assert(hashmap_isempty(m->units));
423 void manager_free(Manager *m) {
428 manager_clear_jobs_and_units(m);
430 for (c = 0; c < _UNIT_TYPE_MAX; c++)
431 if (unit_vtable[c]->shutdown)
432 unit_vtable[c]->shutdown(m);
434 /* If we reexecute ourselves, we keep the root cgroup
436 manager_shutdown_cgroup(m, m->exit_code != MANAGER_REEXECUTE);
441 hashmap_free(m->units);
442 hashmap_free(m->jobs);
443 hashmap_free(m->transaction_jobs);
444 hashmap_free(m->watch_pids);
445 hashmap_free(m->watch_bus);
447 if (m->epoll_fd >= 0)
448 close_nointr_nofail(m->epoll_fd);
449 if (m->signal_watch.fd >= 0)
450 close_nointr_nofail(m->signal_watch.fd);
451 if (m->notify_watch.fd >= 0)
452 close_nointr_nofail(m->notify_watch.fd);
454 lookup_paths_free(&m->lookup_paths);
455 strv_free(m->environment);
457 free(m->cgroup_controller);
458 free(m->cgroup_hierarchy);
459 free(m->cgroup_mount_point);
461 hashmap_free(m->cgroup_bondings);
463 if (m->pin_cgroupfs_fd >= 0)
464 close_nointr_nofail(m->pin_cgroupfs_fd);
469 int manager_enumerate(Manager *m) {
475 /* Let's ask every type to load all units from disk/kernel
476 * that it might know */
477 for (c = 0; c < _UNIT_TYPE_MAX; c++)
478 if (unit_vtable[c]->enumerate)
479 if ((q = unit_vtable[c]->enumerate(m)) < 0)
482 manager_dispatch_load_queue(m);
486 int manager_coldplug(Manager *m) {
494 /* Then, let's set up their initial state. */
495 HASHMAP_FOREACH_KEY(u, k, m->units, i) {
501 if ((q = unit_coldplug(u)) < 0)
508 int manager_startup(Manager *m, FILE *serialization, FDSet *fds) {
513 /* First, enumerate what we can from all config files */
514 r = manager_enumerate(m);
516 /* Second, deserialize if there is something to deserialize */
518 if ((q = manager_deserialize(m, serialization, fds)) < 0)
521 /* Third, fire things up! */
522 if ((q = manager_coldplug(m)) < 0)
525 /* Now that the initial devices are available, let's see if we
526 * can write the utmp file */
527 manager_write_utmp_reboot(m);
532 static void transaction_delete_job(Manager *m, Job *j, bool delete_dependencies) {
536 /* Deletes one job from the transaction */
538 manager_transaction_unlink_job(m, j, delete_dependencies);
544 static void transaction_delete_unit(Manager *m, Unit *u) {
547 /* Deletes all jobs associated with a certain unit from the
550 while ((j = hashmap_get(m->transaction_jobs, u)))
551 transaction_delete_job(m, j, true);
554 static void transaction_clean_dependencies(Manager *m) {
560 /* Drops all dependencies of all installed jobs */
562 HASHMAP_FOREACH(j, m->jobs, i) {
563 while (j->subject_list)
564 job_dependency_free(j->subject_list);
565 while (j->object_list)
566 job_dependency_free(j->object_list);
569 assert(!m->transaction_anchor);
572 static void transaction_abort(Manager *m) {
577 while ((j = hashmap_first(m->transaction_jobs)))
579 transaction_delete_job(m, j, true);
583 assert(hashmap_isempty(m->transaction_jobs));
585 transaction_clean_dependencies(m);
588 static void transaction_find_jobs_that_matter_to_anchor(Manager *m, Job *j, unsigned generation) {
593 /* A recursive sweep through the graph that marks all units
594 * that matter to the anchor job, i.e. are directly or
595 * indirectly a dependency of the anchor job via paths that
596 * are fully marked as mattering. */
601 l = m->transaction_anchor;
603 LIST_FOREACH(subject, l, l) {
605 /* This link does not matter */
609 /* This unit has already been marked */
610 if (l->object->generation == generation)
613 l->object->matters_to_anchor = true;
614 l->object->generation = generation;
616 transaction_find_jobs_that_matter_to_anchor(m, l->object, generation);
620 static void transaction_merge_and_delete_job(Manager *m, Job *j, Job *other, JobType t) {
621 JobDependency *l, *last;
625 assert(j->unit == other->unit);
626 assert(!j->installed);
628 /* Merges 'other' into 'j' and then deletes j. */
631 j->state = JOB_WAITING;
632 j->override = j->override || other->override;
634 j->matters_to_anchor = j->matters_to_anchor || other->matters_to_anchor;
636 /* Patch us in as new owner of the JobDependency objects */
638 LIST_FOREACH(subject, l, other->subject_list) {
639 assert(l->subject == other);
644 /* Merge both lists */
646 last->subject_next = j->subject_list;
648 j->subject_list->subject_prev = last;
649 j->subject_list = other->subject_list;
652 /* Patch us in as new owner of the JobDependency objects */
654 LIST_FOREACH(object, l, other->object_list) {
655 assert(l->object == other);
660 /* Merge both lists */
662 last->object_next = j->object_list;
664 j->object_list->object_prev = last;
665 j->object_list = other->object_list;
668 /* Kill the other job */
669 other->subject_list = NULL;
670 other->object_list = NULL;
671 transaction_delete_job(m, other, true);
674 static int delete_one_unmergeable_job(Manager *m, Job *j) {
679 /* Tries to delete one item in the linked list
680 * j->transaction_next->transaction_next->... that conflicts
681 * whith another one, in an attempt to make an inconsistent
682 * transaction work. */
684 /* We rely here on the fact that if a merged with b does not
685 * merge with c, either a or b merge with c neither */
686 LIST_FOREACH(transaction, j, j)
687 LIST_FOREACH(transaction, k, j->transaction_next) {
690 /* Is this one mergeable? Then skip it */
691 if (job_type_is_mergeable(j->type, k->type))
694 /* Ok, we found two that conflict, let's see if we can
695 * drop one of them */
696 if (!j->matters_to_anchor)
698 else if (!k->matters_to_anchor)
703 /* Ok, we can drop one, so let's do so. */
704 log_debug("Trying to fix job merging by deleting job %s/%s", d->unit->meta.id, job_type_to_string(d->type));
705 transaction_delete_job(m, d, true);
712 static int transaction_merge_jobs(Manager *m) {
719 /* First step, check whether any of the jobs for one specific
720 * task conflict. If so, try to drop one of them. */
721 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
726 LIST_FOREACH(transaction, k, j->transaction_next) {
727 if ((r = job_type_merge(&t, k->type)) >= 0)
730 /* OK, we could not merge all jobs for this
731 * action. Let's see if we can get rid of one
734 if ((r = delete_one_unmergeable_job(m, j)) >= 0)
735 /* Ok, we managed to drop one, now
736 * let's ask our callers to call us
737 * again after garbage collecting */
740 /* We couldn't merge anything. Failure */
745 /* Second step, merge the jobs. */
746 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
750 /* Merge all transactions */
751 LIST_FOREACH(transaction, k, j->transaction_next)
752 assert_se(job_type_merge(&t, k->type) == 0);
754 /* If an active job is mergeable, merge it too */
755 if (j->unit->meta.job)
756 job_type_merge(&t, j->unit->meta.job->type); /* Might fail. Which is OK */
758 while ((k = j->transaction_next)) {
760 transaction_merge_and_delete_job(m, k, j, t);
763 transaction_merge_and_delete_job(m, j, k, t);
766 assert(!j->transaction_next);
767 assert(!j->transaction_prev);
773 static void transaction_drop_redundant(Manager *m) {
778 /* Goes through the transaction and removes all jobs that are
787 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
788 bool changes_something = false;
791 LIST_FOREACH(transaction, k, j) {
793 if (!job_is_anchor(k) &&
794 job_type_is_redundant(k->type, unit_active_state(k->unit)))
797 changes_something = true;
801 if (changes_something)
804 log_debug("Found redundant job %s/%s, dropping.", j->unit->meta.id, job_type_to_string(j->type));
805 transaction_delete_job(m, j, false);
813 static bool unit_matters_to_anchor(Unit *u, Job *j) {
815 assert(!j->transaction_prev);
817 /* Checks whether at least one of the jobs for this unit
818 * matters to the anchor. */
820 LIST_FOREACH(transaction, j, j)
821 if (j->matters_to_anchor)
827 static int transaction_verify_order_one(Manager *m, Job *j, Job *from, unsigned generation) {
834 assert(!j->transaction_prev);
836 /* Does a recursive sweep through the ordering graph, looking
837 * for a cycle. If we find cycle we try to break it. */
839 /* Have we seen this before? */
840 if (j->generation == generation) {
843 /* If the marker is NULL we have been here already and
844 * decided the job was loop-free from here. Hence
845 * shortcut things and return right-away. */
849 /* So, the marker is not NULL and we already have been
850 * here. We have a cycle. Let's try to break it. We go
851 * backwards in our path and try to find a suitable
852 * job to remove. We use the marker to find our way
853 * back, since smart how we are we stored our way back
855 log_debug("Found ordering cycle on %s/%s", j->unit->meta.id, job_type_to_string(j->type));
857 for (k = from; k; k = ((k->generation == generation && k->marker != k) ? k->marker : NULL)) {
859 log_debug("Walked on cycle path to %s/%s", k->unit->meta.id, job_type_to_string(k->type));
862 !unit_matters_to_anchor(k->unit, k)) {
863 /* Ok, we can drop this one, so let's
865 log_debug("Breaking order cycle by deleting job %s/%s", k->unit->meta.id, job_type_to_string(k->type));
866 transaction_delete_unit(m, k->unit);
870 /* Check if this in fact was the beginning of
876 log_debug("Unable to break cycle");
881 /* Make the marker point to where we come from, so that we can
882 * find our way backwards if we want to break a cycle. We use
883 * a special marker for the beginning: we point to
885 j->marker = from ? from : j;
886 j->generation = generation;
888 /* We assume that the the dependencies are bidirectional, and
889 * hence can ignore UNIT_AFTER */
890 SET_FOREACH(u, j->unit->meta.dependencies[UNIT_BEFORE], i) {
893 /* Is there a job for this unit? */
894 if (!(o = hashmap_get(m->transaction_jobs, u)))
896 /* Ok, there is no job for this in the
897 * transaction, but maybe there is already one
899 if (!(o = u->meta.job))
902 if ((r = transaction_verify_order_one(m, o, j, generation)) < 0)
906 /* Ok, let's backtrack, and remember that this entry is not on
907 * our path anymore. */
913 static int transaction_verify_order(Manager *m, unsigned *generation) {
922 /* Check if the ordering graph is cyclic. If it is, try to fix
923 * that up by dropping one of the jobs. */
927 HASHMAP_FOREACH(j, m->transaction_jobs, i)
928 if ((r = transaction_verify_order_one(m, j, NULL, g)) < 0)
934 static void transaction_collect_garbage(Manager *m) {
939 /* Drop jobs that are not required by any other job */
947 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
951 log_debug("Garbage collecting job %s/%s", j->unit->meta.id, job_type_to_string(j->type));
952 transaction_delete_job(m, j, true);
960 static int transaction_is_destructive(Manager *m) {
966 /* Checks whether applying this transaction means that
967 * existing jobs would be replaced */
969 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
972 assert(!j->transaction_prev);
973 assert(!j->transaction_next);
975 if (j->unit->meta.job &&
976 j->unit->meta.job != j &&
977 !job_type_is_superset(j->type, j->unit->meta.job->type))
984 static void transaction_minimize_impact(Manager *m) {
988 /* Drops all unnecessary jobs that reverse already active jobs
989 * or that stop a running service. */
997 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
998 LIST_FOREACH(transaction, j, j) {
999 bool stops_running_service, changes_existing_job;
1001 /* If it matters, we shouldn't drop it */
1002 if (j->matters_to_anchor)
1005 /* Would this stop a running service?
1006 * Would this change an existing job?
1007 * If so, let's drop this entry */
1009 stops_running_service =
1010 j->type == JOB_STOP && UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(j->unit));
1012 changes_existing_job =
1013 j->unit->meta.job && job_type_is_conflicting(j->type, j->unit->meta.job->state);
1015 if (!stops_running_service && !changes_existing_job)
1018 if (stops_running_service)
1019 log_debug("%s/%s would stop a running service.", j->unit->meta.id, job_type_to_string(j->type));
1021 if (changes_existing_job)
1022 log_debug("%s/%s would change existing job.", j->unit->meta.id, job_type_to_string(j->type));
1024 /* Ok, let's get rid of this */
1025 log_debug("Deleting %s/%s to minimize impact.", j->unit->meta.id, job_type_to_string(j->type));
1027 transaction_delete_job(m, j, true);
1039 static int transaction_apply(Manager *m) {
1044 /* Moves the transaction jobs to the set of active jobs */
1046 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1048 assert(!j->transaction_prev);
1049 assert(!j->transaction_next);
1054 if ((r = hashmap_put(m->jobs, UINT32_TO_PTR(j->id), j)) < 0)
1058 while ((j = hashmap_steal_first(m->transaction_jobs))) {
1062 if (j->unit->meta.job)
1063 job_free(j->unit->meta.job);
1065 j->unit->meta.job = j;
1066 j->installed = true;
1068 /* We're fully installed. Now let's free data we don't
1071 assert(!j->transaction_next);
1072 assert(!j->transaction_prev);
1074 job_add_to_run_queue(j);
1075 job_add_to_dbus_queue(j);
1078 /* As last step, kill all remaining job dependencies. */
1079 transaction_clean_dependencies(m);
1085 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1089 hashmap_remove(m->jobs, UINT32_TO_PTR(j->id));
1095 static int transaction_activate(Manager *m, JobMode mode) {
1097 unsigned generation = 1;
1101 /* This applies the changes recorded in transaction_jobs to
1102 * the actual list of jobs, if possible. */
1104 /* First step: figure out which jobs matter */
1105 transaction_find_jobs_that_matter_to_anchor(m, NULL, generation++);
1107 /* Second step: Try not to stop any running services if
1108 * we don't have to. Don't try to reverse running
1109 * jobs if we don't have to. */
1110 transaction_minimize_impact(m);
1112 /* Third step: Drop redundant jobs */
1113 transaction_drop_redundant(m);
1116 /* Fourth step: Let's remove unneeded jobs that might
1118 transaction_collect_garbage(m);
1120 /* Fifth step: verify order makes sense and correct
1121 * cycles if necessary and possible */
1122 if ((r = transaction_verify_order(m, &generation)) >= 0)
1126 log_debug("Requested transaction contains an unfixable cyclic ordering dependency: %s", strerror(-r));
1130 /* Let's see if the resulting transaction ordering
1131 * graph is still cyclic... */
1135 /* Sixth step: let's drop unmergeable entries if
1136 * necessary and possible, merge entries we can
1138 if ((r = transaction_merge_jobs(m)) >= 0)
1142 log_debug("Requested transaction contains unmergable jobs: %s", strerror(-r));
1146 /* Seventh step: an entry got dropped, let's garbage
1147 * collect its dependencies. */
1148 transaction_collect_garbage(m);
1150 /* Let's see if the resulting transaction still has
1151 * unmergeable entries ... */
1154 /* Eights step: Drop redundant jobs again, if the merging now allows us to drop more. */
1155 transaction_drop_redundant(m);
1157 /* Ninth step: check whether we can actually apply this */
1158 if (mode == JOB_FAIL)
1159 if ((r = transaction_is_destructive(m)) < 0) {
1160 log_debug("Requested transaction contradicts existing jobs: %s", strerror(-r));
1164 /* Tenth step: apply changes */
1165 if ((r = transaction_apply(m)) < 0) {
1166 log_debug("Failed to apply transaction: %s", strerror(-r));
1170 assert(hashmap_isempty(m->transaction_jobs));
1171 assert(!m->transaction_anchor);
1176 transaction_abort(m);
1180 static Job* transaction_add_one_job(Manager *m, JobType type, Unit *unit, bool override, bool *is_new) {
1187 /* Looks for an axisting prospective job and returns that. If
1188 * it doesn't exist it is created and added to the prospective
1191 f = hashmap_get(m->transaction_jobs, unit);
1193 LIST_FOREACH(transaction, j, f) {
1194 assert(j->unit == unit);
1196 if (j->type == type) {
1203 if (unit->meta.job && unit->meta.job->type == type)
1205 else if (!(j = job_new(m, type, unit)))
1210 j->matters_to_anchor = false;
1211 j->override = override;
1213 LIST_PREPEND(Job, transaction, f, j);
1215 if ((r = hashmap_replace(m->transaction_jobs, unit, f)) < 0) {
1223 log_debug("Added job %s/%s to transaction.", unit->meta.id, job_type_to_string(type));
1228 void manager_transaction_unlink_job(Manager *m, Job *j, bool delete_dependencies) {
1232 if (j->transaction_prev)
1233 j->transaction_prev->transaction_next = j->transaction_next;
1234 else if (j->transaction_next)
1235 hashmap_replace(m->transaction_jobs, j->unit, j->transaction_next);
1237 hashmap_remove_value(m->transaction_jobs, j->unit, j);
1239 if (j->transaction_next)
1240 j->transaction_next->transaction_prev = j->transaction_prev;
1242 j->transaction_prev = j->transaction_next = NULL;
1244 while (j->subject_list)
1245 job_dependency_free(j->subject_list);
1247 while (j->object_list) {
1248 Job *other = j->object_list->matters ? j->object_list->subject : NULL;
1250 job_dependency_free(j->object_list);
1252 if (other && delete_dependencies) {
1253 log_debug("Deleting job %s/%s as dependency of job %s/%s",
1254 other->unit->meta.id, job_type_to_string(other->type),
1255 j->unit->meta.id, job_type_to_string(j->type));
1256 transaction_delete_job(m, other, delete_dependencies);
1261 static int transaction_add_job_and_dependencies(
1276 assert(type < _JOB_TYPE_MAX);
1279 if (unit->meta.load_state != UNIT_LOADED)
1282 if (!unit_job_is_applicable(unit, type))
1285 /* First add the job. */
1286 if (!(ret = transaction_add_one_job(m, type, unit, override, &is_new)))
1289 /* Then, add a link to the job. */
1290 if (!job_dependency_new(by, ret, matters))
1294 /* Finally, recursively add in all dependencies. */
1295 if (type == JOB_START || type == JOB_RELOAD_OR_START) {
1296 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES], i)
1297 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, true, override, NULL)) < 0 && r != -EBADR)
1300 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES_OVERRIDABLE], i)
1301 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, !override, override, NULL)) < 0 && r != -EBADR)
1302 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, strerror(-r));
1304 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_WANTS], i)
1305 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, false, false, NULL)) < 0)
1306 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, strerror(-r));
1308 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE], i)
1309 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, true, override, NULL)) < 0 && r != -EBADR)
1312 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE_OVERRIDABLE], i)
1313 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, !override, override, NULL)) < 0 && r != -EBADR)
1314 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, strerror(-r));
1316 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_CONFLICTS], i)
1317 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, dep, ret, true, override, NULL)) < 0 && r != -EBADR)
1320 } else if (type == JOB_STOP || type == JOB_RESTART || type == JOB_TRY_RESTART) {
1322 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRED_BY], i)
1323 if ((r = transaction_add_job_and_dependencies(m, type, dep, ret, true, override, NULL)) < 0 && r != -EBADR)
1327 /* JOB_VERIFY_STARTED, JOB_RELOAD require no dependency handling */
1339 static int transaction_add_isolate_jobs(Manager *m) {
1347 HASHMAP_FOREACH_KEY(u, k, m->units, i) {
1349 /* ignore aliases */
1350 if (u->meta.id != k)
1353 if (UNIT_VTABLE(u)->no_isolate)
1356 /* No need to stop inactive jobs */
1357 if (unit_active_state(u) == UNIT_INACTIVE)
1360 /* Is there already something listed for this? */
1361 if (hashmap_get(m->transaction_jobs, u))
1364 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, u, NULL, true, false, NULL)) < 0)
1365 log_warning("Cannot add isolate job for unit %s, ignoring: %s", u->meta.id, strerror(-r));
1371 int manager_add_job(Manager *m, JobType type, Unit *unit, JobMode mode, bool override, Job **_ret) {
1376 assert(type < _JOB_TYPE_MAX);
1378 assert(mode < _JOB_MODE_MAX);
1380 if (mode == JOB_ISOLATE && type != JOB_START)
1383 log_debug("Trying to enqueue job %s/%s", unit->meta.id, job_type_to_string(type));
1385 if ((r = transaction_add_job_and_dependencies(m, type, unit, NULL, true, override, &ret)) < 0) {
1386 transaction_abort(m);
1390 if (mode == JOB_ISOLATE)
1391 if ((r = transaction_add_isolate_jobs(m)) < 0) {
1392 transaction_abort(m);
1396 if ((r = transaction_activate(m, mode)) < 0)
1399 log_debug("Enqueued job %s/%s as %u", unit->meta.id, job_type_to_string(type), (unsigned) ret->id);
1407 int manager_add_job_by_name(Manager *m, JobType type, const char *name, JobMode mode, bool override, Job **_ret) {
1412 assert(type < _JOB_TYPE_MAX);
1414 assert(mode < _JOB_MODE_MAX);
1416 if ((r = manager_load_unit(m, name, NULL, &unit)) < 0)
1419 return manager_add_job(m, type, unit, mode, override, _ret);
1422 Job *manager_get_job(Manager *m, uint32_t id) {
1425 return hashmap_get(m->jobs, UINT32_TO_PTR(id));
1428 Unit *manager_get_unit(Manager *m, const char *name) {
1432 return hashmap_get(m->units, name);
1435 unsigned manager_dispatch_load_queue(Manager *m) {
1441 /* Make sure we are not run recursively */
1442 if (m->dispatching_load_queue)
1445 m->dispatching_load_queue = true;
1447 /* Dispatches the load queue. Takes a unit from the queue and
1448 * tries to load its data until the queue is empty */
1450 while ((meta = m->load_queue)) {
1451 assert(meta->in_load_queue);
1453 unit_load(UNIT(meta));
1457 m->dispatching_load_queue = false;
1461 int manager_load_unit_prepare(Manager *m, const char *name, const char *path, Unit **_ret) {
1466 assert(name || path);
1468 /* This will prepare the unit for loading, but not actually
1469 * load anything from disk. */
1471 if (path && !is_path(path))
1475 name = file_name_from_path(path);
1477 if (!unit_name_is_valid(name))
1480 if ((ret = manager_get_unit(m, name))) {
1485 if (!(ret = unit_new(m)))
1489 if (!(ret->meta.fragment_path = strdup(path))) {
1494 if ((r = unit_add_name(ret, name)) < 0) {
1499 unit_add_to_load_queue(ret);
1500 unit_add_to_dbus_queue(ret);
1501 unit_add_to_gc_queue(ret);
1509 int manager_load_unit(Manager *m, const char *name, const char *path, Unit **_ret) {
1514 /* This will load the service information files, but not actually
1515 * start any services or anything. */
1517 if ((r = manager_load_unit_prepare(m, name, path, _ret)) != 0)
1520 manager_dispatch_load_queue(m);
1523 *_ret = unit_follow_merge(*_ret);
1528 void manager_dump_jobs(Manager *s, FILE *f, const char *prefix) {
1535 HASHMAP_FOREACH(j, s->jobs, i)
1536 job_dump(j, f, prefix);
1539 void manager_dump_units(Manager *s, FILE *f, const char *prefix) {
1547 HASHMAP_FOREACH_KEY(u, t, s->units, i)
1548 if (u->meta.id == t)
1549 unit_dump(u, f, prefix);
1552 void manager_clear_jobs(Manager *m) {
1557 transaction_abort(m);
1559 while ((j = hashmap_first(m->jobs)))
1563 unsigned manager_dispatch_run_queue(Manager *m) {
1567 if (m->dispatching_run_queue)
1570 m->dispatching_run_queue = true;
1572 while ((j = m->run_queue)) {
1573 assert(j->installed);
1574 assert(j->in_run_queue);
1576 job_run_and_invalidate(j);
1580 m->dispatching_run_queue = false;
1584 unsigned manager_dispatch_dbus_queue(Manager *m) {
1591 if (m->dispatching_dbus_queue)
1594 m->dispatching_dbus_queue = true;
1596 while ((meta = m->dbus_unit_queue)) {
1597 assert(meta->in_dbus_queue);
1599 bus_unit_send_change_signal(UNIT(meta));
1603 while ((j = m->dbus_job_queue)) {
1604 assert(j->in_dbus_queue);
1606 bus_job_send_change_signal(j);
1610 m->dispatching_dbus_queue = false;
1614 static int manager_process_notify_fd(Manager *m) {
1621 struct msghdr msghdr;
1623 struct ucred *ucred;
1625 struct cmsghdr cmsghdr;
1626 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
1632 iovec.iov_base = buf;
1633 iovec.iov_len = sizeof(buf)-1;
1637 msghdr.msg_iov = &iovec;
1638 msghdr.msg_iovlen = 1;
1639 msghdr.msg_control = &control;
1640 msghdr.msg_controllen = sizeof(control);
1642 if ((n = recvmsg(m->notify_watch.fd, &msghdr, MSG_DONTWAIT)) <= 0) {
1646 if (errno == EAGAIN)
1652 if (msghdr.msg_controllen < CMSG_LEN(sizeof(struct ucred)) ||
1653 control.cmsghdr.cmsg_level != SOL_SOCKET ||
1654 control.cmsghdr.cmsg_type != SCM_CREDENTIALS ||
1655 control.cmsghdr.cmsg_len != CMSG_LEN(sizeof(struct ucred))) {
1656 log_warning("Received notify message without credentials. Ignoring.");
1660 ucred = (struct ucred*) CMSG_DATA(&control.cmsghdr);
1662 if (!(u = hashmap_get(m->watch_pids, UINT32_TO_PTR(ucred->pid))))
1663 if (!(u = cgroup_unit_by_pid(m, ucred->pid))) {
1664 log_warning("Cannot find unit for notify message of PID %lu.", (unsigned long) ucred->pid);
1669 if (!(tags = strv_split(buf, "\n\r")))
1672 log_debug("Got notification message for unit %s", u->meta.id);
1674 if (UNIT_VTABLE(u)->notify_message)
1675 UNIT_VTABLE(u)->notify_message(u, tags);
1683 static int manager_dispatch_sigchld(Manager *m) {
1693 /* First we call waitd() for a PID and do not reap the
1694 * zombie. That way we can still access /proc/$PID for
1695 * it while it is a zombie. */
1696 if (waitid(P_ALL, 0, &si, WEXITED|WNOHANG|WNOWAIT) < 0) {
1698 if (errno == ECHILD)
1710 if (si.si_code == CLD_EXITED || si.si_code == CLD_KILLED || si.si_code == CLD_DUMPED) {
1713 get_process_name(si.si_pid, &name);
1714 log_debug("Got SIGCHLD for process %llu (%s)", (unsigned long long) si.si_pid, strna(name));
1718 /* Let's flush any message the dying child might still
1719 * have queued for us. This ensures that the process
1720 * still exists in /proc so that we can figure out
1721 * which cgroup and hence unit it belongs to. */
1722 if ((r = manager_process_notify_fd(m)) < 0)
1725 /* And now figure out the unit this belongs to */
1726 if (!(u = hashmap_get(m->watch_pids, UINT32_TO_PTR(si.si_pid))))
1727 u = cgroup_unit_by_pid(m, si.si_pid);
1729 /* And now, we actually reap the zombie. */
1730 if (waitid(P_PID, si.si_pid, &si, WEXITED) < 0) {
1737 if (si.si_code != CLD_EXITED && si.si_code != CLD_KILLED && si.si_code != CLD_DUMPED)
1740 log_debug("Child %llu died (code=%s, status=%i/%s)",
1741 (long long unsigned) si.si_pid,
1742 sigchld_code_to_string(si.si_code),
1744 strna(si.si_code == CLD_EXITED ? exit_status_to_string(si.si_status) : strsignal(si.si_status)));
1749 log_debug("Child %llu belongs to %s", (long long unsigned) si.si_pid, u->meta.id);
1751 hashmap_remove(m->watch_pids, UINT32_TO_PTR(si.si_pid));
1752 UNIT_VTABLE(u)->sigchld_event(u, si.si_pid, si.si_code, si.si_status);
1758 static int manager_start_target(Manager *m, const char *name, JobMode mode) {
1761 if ((r = manager_add_job_by_name(m, JOB_START, name, mode, true, NULL)) < 0)
1762 log_error("Failed to enqueue %s job: %s", name, strerror(-r));
1767 static int manager_process_signal_fd(Manager *m) {
1769 struct signalfd_siginfo sfsi;
1770 bool sigchld = false;
1775 if ((n = read(m->signal_watch.fd, &sfsi, sizeof(sfsi))) != sizeof(sfsi)) {
1780 if (errno == EAGAIN)
1786 switch (sfsi.ssi_signo) {
1793 if (m->running_as == MANAGER_INIT) {
1794 /* This is for compatibility with the
1795 * original sysvinit */
1796 m->exit_code = MANAGER_REEXECUTE;
1803 if (m->running_as == MANAGER_INIT) {
1804 manager_start_target(m, SPECIAL_CTRL_ALT_DEL_TARGET, JOB_REPLACE);
1808 /* Run the exit target if there is one, if not, just exit. */
1809 if (manager_start_target(m, SPECIAL_EXIT_SERVICE, JOB_REPLACE) < 0) {
1810 m->exit_code = MANAGER_EXIT;
1817 if (m->running_as == MANAGER_INIT)
1818 manager_start_target(m, SPECIAL_KBREQUEST_TARGET, JOB_REPLACE);
1820 /* This is a nop on non-init */
1824 if (m->running_as == MANAGER_INIT)
1825 manager_start_target(m, SPECIAL_SIGPWR_TARGET, JOB_REPLACE);
1827 /* This is a nop on non-init */
1833 u = manager_get_unit(m, SPECIAL_DBUS_SERVICE);
1835 if (!u || UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u))) {
1836 log_info("Trying to reconnect to bus...");
1841 if (!u || !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u))) {
1842 log_info("Loading D-Bus service...");
1843 manager_start_target(m, SPECIAL_DBUS_SERVICE, JOB_REPLACE);
1854 if (!(f = open_memstream(&dump, &size))) {
1855 log_warning("Failed to allocate memory stream.");
1859 manager_dump_units(m, f, "\t");
1860 manager_dump_jobs(m, f, "\t");
1865 log_warning("Failed to write status stream");
1870 log_dump(LOG_INFO, dump);
1877 m->exit_code = MANAGER_RELOAD;
1881 static const char * const table[] = {
1882 [0] = SPECIAL_DEFAULT_TARGET,
1883 [1] = SPECIAL_RESCUE_TARGET,
1884 [2] = SPECIAL_EMERGENCY_SERVICE,
1885 [3] = SPECIAL_HALT_TARGET,
1886 [4] = SPECIAL_POWEROFF_TARGET,
1887 [5] = SPECIAL_REBOOT_TARGET
1890 if ((int) sfsi.ssi_signo >= SIGRTMIN+0 &&
1891 (int) sfsi.ssi_signo < SIGRTMIN+(int) ELEMENTSOF(table)) {
1892 manager_start_target(m, table[sfsi.ssi_signo - SIGRTMIN],
1893 sfsi.ssi_signo == 2 ? JOB_ISOLATE : JOB_REPLACE);
1897 log_info("Got unhandled signal <%s>.", strsignal(sfsi.ssi_signo));
1903 return manager_dispatch_sigchld(m);
1908 static int process_event(Manager *m, struct epoll_event *ev) {
1915 assert(w = ev->data.ptr);
1921 /* An incoming signal? */
1922 if (ev->events != EPOLLIN)
1925 if ((r = manager_process_signal_fd(m)) < 0)
1932 /* An incoming daemon notification event? */
1933 if (ev->events != EPOLLIN)
1936 if ((r = manager_process_notify_fd(m)) < 0)
1943 /* Some fd event, to be dispatched to the units */
1944 UNIT_VTABLE(w->data.unit)->fd_event(w->data.unit, w->fd, ev->events, w);
1951 /* Some timer event, to be dispatched to the units */
1952 if ((k = read(w->fd, &v, sizeof(v))) != sizeof(v)) {
1954 if (k < 0 && (errno == EINTR || errno == EAGAIN))
1957 return k < 0 ? -errno : -EIO;
1960 UNIT_VTABLE(w->data.unit)->timer_event(w->data.unit, v, w);
1965 /* Some mount table change, intended for the mount subsystem */
1966 mount_fd_event(m, ev->events);
1970 /* Some notification from udev, intended for the device subsystem */
1971 device_fd_event(m, ev->events);
1974 case WATCH_DBUS_WATCH:
1975 bus_watch_event(m, w, ev->events);
1978 case WATCH_DBUS_TIMEOUT:
1979 bus_timeout_event(m, w, ev->events);
1983 assert_not_reached("Unknown epoll event type.");
1989 int manager_loop(Manager *m) {
1992 RATELIMIT_DEFINE(rl, 1*USEC_PER_SEC, 1000);
1995 m->exit_code = MANAGER_RUNNING;
1997 /* There might still be some zombies hanging around from
1998 * before we were exec()'ed. Leat's reap them */
1999 if ((r = manager_dispatch_sigchld(m)) < 0)
2002 while (m->exit_code == MANAGER_RUNNING) {
2003 struct epoll_event event;
2006 if (!ratelimit_test(&rl)) {
2007 /* Yay, something is going seriously wrong, pause a little */
2008 log_warning("Looping too fast. Throttling execution a little.");
2012 if (manager_dispatch_load_queue(m) > 0)
2015 if (manager_dispatch_run_queue(m) > 0)
2018 if (bus_dispatch(m) > 0)
2021 if (manager_dispatch_cleanup_queue(m) > 0)
2024 if (manager_dispatch_gc_queue(m) > 0)
2027 if (manager_dispatch_dbus_queue(m) > 0)
2030 if ((n = epoll_wait(m->epoll_fd, &event, 1, -1)) < 0) {
2040 if ((r = process_event(m, &event)) < 0)
2044 return m->exit_code;
2047 int manager_get_unit_from_dbus_path(Manager *m, const char *s, Unit **_u) {
2055 if (!startswith(s, "/org/freedesktop/systemd1/unit/"))
2058 if (!(n = bus_path_unescape(s+31)))
2061 u = manager_get_unit(m, n);
2072 int manager_get_job_from_dbus_path(Manager *m, const char *s, Job **_j) {
2081 if (!startswith(s, "/org/freedesktop/systemd1/job/"))
2084 if ((r = safe_atou(s + 30, &id)) < 0)
2087 if (!(j = manager_get_job(m, id)))
2095 static bool manager_utmp_good(Manager *m) {
2100 if ((r = mount_path_is_mounted(m, _PATH_UTMPX)) <= 0) {
2103 log_warning("Failed to determine whether " _PATH_UTMPX " is mounted: %s", strerror(-r));
2111 void manager_write_utmp_reboot(Manager *m) {
2116 if (m->utmp_reboot_written)
2119 if (m->running_as != MANAGER_INIT)
2122 if (!manager_utmp_good(m))
2125 if ((r = utmp_put_reboot(m->startup_timestamp.realtime)) < 0) {
2127 if (r != -ENOENT && r != -EROFS)
2128 log_warning("Failed to write utmp/wtmp: %s", strerror(-r));
2133 m->utmp_reboot_written = true;
2136 void manager_write_utmp_runlevel(Manager *m, Unit *u) {
2142 if (u->meta.type != UNIT_TARGET)
2145 if (m->running_as != MANAGER_INIT)
2148 if (!manager_utmp_good(m))
2151 if ((runlevel = target_get_runlevel(TARGET(u))) <= 0)
2154 if ((r = utmp_put_runlevel(0, runlevel, 0)) < 0) {
2156 if (r != -ENOENT && r != -EROFS)
2157 log_warning("Failed to write utmp/wtmp: %s", strerror(-r));
2161 void manager_dispatch_bus_name_owner_changed(
2164 const char* old_owner,
2165 const char *new_owner) {
2172 if (!(u = hashmap_get(m->watch_bus, name)))
2175 UNIT_VTABLE(u)->bus_name_owner_change(u, name, old_owner, new_owner);
2178 void manager_dispatch_bus_query_pid_done(
2189 if (!(u = hashmap_get(m->watch_bus, name)))
2192 UNIT_VTABLE(u)->bus_query_pid_done(u, name, pid);
2195 int manager_open_serialization(FILE **_f) {
2203 if (asprintf(&path, "/dev/shm/systemd-%u.dump-XXXXXX", (unsigned) getpid()) < 0)
2206 saved_umask = umask(0077);
2207 fd = mkostemp(path, O_RDWR|O_CLOEXEC);
2217 log_debug("Serializing state to %s", path);
2220 if (!(f = fdopen(fd, "w+")) < 0)
2228 int manager_serialize(Manager *m, FILE *f, FDSet *fds) {
2238 HASHMAP_FOREACH_KEY(u, t, m->units, i) {
2239 if (u->meta.id != t)
2242 if (!unit_can_serialize(u))
2246 fputs(u->meta.id, f);
2249 if ((r = unit_serialize(u, f, fds)) < 0)
2259 int manager_deserialize(Manager *m, FILE *f, FDSet *fds) {
2265 log_debug("Deserializing state...");
2269 char name[UNIT_NAME_MAX+2];
2272 if (!fgets(name, sizeof(name), f)) {
2281 if ((r = manager_load_unit(m, strstrip(name), NULL, &u)) < 0)
2284 if ((r = unit_deserialize(u, f, fds)) < 0)
2294 int manager_reload(Manager *m) {
2301 if ((r = manager_open_serialization(&f)) < 0)
2304 if (!(fds = fdset_new())) {
2309 if ((r = manager_serialize(m, f, fds)) < 0)
2312 if (fseeko(f, 0, SEEK_SET) < 0) {
2317 /* From here on there is no way back. */
2318 manager_clear_jobs_and_units(m);
2320 /* Find new unit paths */
2321 lookup_paths_free(&m->lookup_paths);
2322 if ((q = lookup_paths_init(&m->lookup_paths, m->running_as)) < 0)
2325 /* First, enumerate what we can from all config files */
2326 if ((q = manager_enumerate(m)) < 0)
2329 /* Second, deserialize our stored data */
2330 if ((q = manager_deserialize(m, f, fds)) < 0)
2336 /* Third, fire things up! */
2337 if ((q = manager_coldplug(m)) < 0)
2350 static const char* const manager_running_as_table[_MANAGER_RUNNING_AS_MAX] = {
2351 [MANAGER_INIT] = "init",
2352 [MANAGER_SYSTEM] = "system",
2353 [MANAGER_SESSION] = "session"
2356 DEFINE_STRING_TABLE_LOOKUP(manager_running_as, ManagerRunningAs);