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"
57 /* As soon as 16 units are in our GC queue, make sure to run a gc sweep */
58 #define GC_QUEUE_ENTRIES_MAX 16
60 /* As soon as 5s passed since a unit was added to our GC queue, make sure to run a gc sweep */
61 #define GC_QUEUE_USEC_MAX (10*USEC_PER_SEC)
63 static int enable_special_signals(Manager *m) {
68 /* Enable that we get SIGINT on control-alt-del */
69 if (reboot(RB_DISABLE_CAD) < 0)
70 log_warning("Failed to enable ctrl-alt-del handling: %m");
72 if ((fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY)) < 0)
73 log_warning("Failed to open /dev/tty0: %m");
75 /* Enable that we get SIGWINCH on kbrequest */
76 if (ioctl(fd, KDSIGACCEPT, SIGWINCH) < 0)
77 log_warning("Failed to enable kbrequest handling: %s", strerror(errno));
79 close_nointr_nofail(fd);
85 static int manager_setup_signals(Manager *m) {
87 struct epoll_event ev;
92 /* We are not interested in SIGSTOP and friends. */
94 sa.sa_handler = SIG_DFL;
95 sa.sa_flags = SA_NOCLDSTOP|SA_RESTART;
96 assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);
98 assert_se(sigemptyset(&mask) == 0);
99 assert_se(sigaddset(&mask, SIGCHLD) == 0);
100 assert_se(sigaddset(&mask, SIGTERM) == 0);
101 assert_se(sigaddset(&mask, SIGHUP) == 0);
102 assert_se(sigaddset(&mask, SIGUSR1) == 0);
103 assert_se(sigaddset(&mask, SIGUSR2) == 0);
104 assert_se(sigaddset(&mask, SIGINT) == 0); /* Kernel sends us this on control-alt-del */
105 assert_se(sigaddset(&mask, SIGWINCH) == 0); /* Kernel sends us this on kbrequest (alt-arrowup) */
106 assert_se(sigaddset(&mask, SIGPWR) == 0); /* Some kernel drivers and upsd send us this on power failure */
107 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
109 m->signal_watch.type = WATCH_SIGNAL;
110 if ((m->signal_watch.fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0)
115 ev.data.ptr = &m->signal_watch;
117 if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->signal_watch.fd, &ev) < 0)
120 if (m->running_as == MANAGER_INIT)
121 return enable_special_signals(m);
126 int manager_new(ManagerRunningAs running_as, bool confirm_spawn, Manager **_m) {
131 assert(running_as >= 0);
132 assert(running_as < _MANAGER_RUNNING_AS_MAX);
134 if (!(m = new0(Manager, 1)))
137 timestamp_get(&m->startup_timestamp);
139 m->running_as = running_as;
140 m->confirm_spawn = confirm_spawn;
141 m->name_data_slot = -1;
142 m->exit_code = _MANAGER_EXIT_CODE_INVALID;
144 m->signal_watch.fd = m->mount_watch.fd = m->udev_watch.fd = m->epoll_fd = m->dev_autofs_fd = -1;
145 m->current_job_id = 1; /* start as id #1, so that we can leave #0 around as "null-like" value */
147 if (!(m->environment = strv_copy(environ)))
150 if (!(m->units = hashmap_new(string_hash_func, string_compare_func)))
153 if (!(m->jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
156 if (!(m->transaction_jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
159 if (!(m->watch_pids = hashmap_new(trivial_hash_func, trivial_compare_func)))
162 if (!(m->cgroup_bondings = hashmap_new(string_hash_func, string_compare_func)))
165 if (!(m->watch_bus = hashmap_new(string_hash_func, string_compare_func)))
168 if ((m->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0)
171 if ((r = lookup_paths_init(&m->lookup_paths, m->running_as)) < 0)
174 if ((r = manager_setup_signals(m)) < 0)
177 if ((r = manager_setup_cgroup(m)) < 0)
180 /* Try to connect to the busses, if possible. */
181 if ((r = bus_init_system(m)) < 0 ||
182 (r = bus_init_api(m)) < 0)
193 static unsigned manager_dispatch_cleanup_queue(Manager *m) {
199 while ((meta = m->cleanup_queue)) {
200 assert(meta->in_cleanup_queue);
202 unit_free(UNIT(meta));
210 GC_OFFSET_IN_PATH, /* This one is on the path we were travelling */
211 GC_OFFSET_UNSURE, /* No clue */
212 GC_OFFSET_GOOD, /* We still need this unit */
213 GC_OFFSET_BAD, /* We don't need this unit anymore */
217 static void unit_gc_sweep(Unit *u, unsigned gc_marker) {
224 if (u->meta.gc_marker == gc_marker + GC_OFFSET_GOOD ||
225 u->meta.gc_marker == gc_marker + GC_OFFSET_BAD ||
226 u->meta.gc_marker == gc_marker + GC_OFFSET_IN_PATH)
229 if (u->meta.in_cleanup_queue)
232 if (unit_check_gc(u))
235 u->meta.gc_marker = gc_marker + GC_OFFSET_IN_PATH;
239 SET_FOREACH(other, u->meta.dependencies[UNIT_REFERENCED_BY], i) {
240 unit_gc_sweep(other, gc_marker);
242 if (other->meta.gc_marker == gc_marker + GC_OFFSET_GOOD)
245 if (other->meta.gc_marker != gc_marker + GC_OFFSET_BAD)
252 /* We were unable to find anything out about this entry, so
253 * let's investigate it later */
254 u->meta.gc_marker = gc_marker + GC_OFFSET_UNSURE;
255 unit_add_to_gc_queue(u);
259 /* We definitely know that this one is not useful anymore, so
260 * let's mark it for deletion */
261 u->meta.gc_marker = gc_marker + GC_OFFSET_BAD;
262 unit_add_to_cleanup_queue(u);
266 u->meta.gc_marker = gc_marker + GC_OFFSET_GOOD;
269 static unsigned manager_dispatch_gc_queue(Manager *m) {
276 if ((m->n_in_gc_queue < GC_QUEUE_ENTRIES_MAX) &&
277 (m->gc_queue_timestamp <= 0 ||
278 (m->gc_queue_timestamp + GC_QUEUE_USEC_MAX) > now(CLOCK_MONOTONIC)))
281 log_debug("Running GC...");
283 m->gc_marker += _GC_OFFSET_MAX;
284 if (m->gc_marker + _GC_OFFSET_MAX <= _GC_OFFSET_MAX)
287 gc_marker = m->gc_marker;
289 while ((meta = m->gc_queue)) {
290 assert(meta->in_gc_queue);
292 unit_gc_sweep(UNIT(meta), gc_marker);
294 LIST_REMOVE(Meta, gc_queue, m->gc_queue, meta);
295 meta->in_gc_queue = false;
299 if (meta->gc_marker == gc_marker + GC_OFFSET_BAD ||
300 meta->gc_marker == gc_marker + GC_OFFSET_UNSURE) {
301 log_debug("Collecting %s", meta->id);
302 meta->gc_marker = gc_marker + GC_OFFSET_BAD;
303 unit_add_to_cleanup_queue(UNIT(meta));
307 m->n_in_gc_queue = 0;
308 m->gc_queue_timestamp = 0;
313 static void manager_clear_jobs_and_units(Manager *m) {
319 while ((j = hashmap_first(m->transaction_jobs)))
322 while ((u = hashmap_first(m->units)))
325 manager_dispatch_cleanup_queue(m);
327 assert(!m->load_queue);
328 assert(!m->run_queue);
329 assert(!m->dbus_unit_queue);
330 assert(!m->dbus_job_queue);
331 assert(!m->cleanup_queue);
332 assert(!m->gc_queue);
334 assert(hashmap_isempty(m->transaction_jobs));
335 assert(hashmap_isempty(m->jobs));
336 assert(hashmap_isempty(m->units));
339 void manager_free(Manager *m) {
344 manager_clear_jobs_and_units(m);
346 for (c = 0; c < _UNIT_TYPE_MAX; c++)
347 if (unit_vtable[c]->shutdown)
348 unit_vtable[c]->shutdown(m);
350 /* If we reexecute ourselves, we keep the root cgroup
352 manager_shutdown_cgroup(m, m->exit_code != MANAGER_REEXECUTE);
357 hashmap_free(m->units);
358 hashmap_free(m->jobs);
359 hashmap_free(m->transaction_jobs);
360 hashmap_free(m->watch_pids);
361 hashmap_free(m->watch_bus);
363 if (m->epoll_fd >= 0)
364 close_nointr_nofail(m->epoll_fd);
365 if (m->signal_watch.fd >= 0)
366 close_nointr_nofail(m->signal_watch.fd);
368 lookup_paths_free(&m->lookup_paths);
369 strv_free(m->environment);
371 free(m->cgroup_controller);
372 free(m->cgroup_hierarchy);
374 hashmap_free(m->cgroup_bondings);
379 int manager_enumerate(Manager *m) {
385 /* Let's ask every type to load all units from disk/kernel
386 * that it might know */
387 for (c = 0; c < _UNIT_TYPE_MAX; c++)
388 if (unit_vtable[c]->enumerate)
389 if ((q = unit_vtable[c]->enumerate(m)) < 0)
392 manager_dispatch_load_queue(m);
396 int manager_coldplug(Manager *m) {
404 /* Then, let's set up their initial state. */
405 HASHMAP_FOREACH_KEY(u, k, m->units, i) {
411 if ((q = unit_coldplug(u)) < 0)
418 int manager_startup(Manager *m, FILE *serialization, FDSet *fds) {
423 /* First, enumerate what we can from all config files */
424 r = manager_enumerate(m);
426 /* Second, deserialize if there is something to deserialize */
428 if ((q = manager_deserialize(m, serialization, fds)) < 0)
431 /* Third, fire things up! */
432 if ((q = manager_coldplug(m)) < 0)
435 /* Now that the initial devices are available, let's see if we
436 * can write the utmp file */
437 manager_write_utmp_reboot(m);
442 static void transaction_delete_job(Manager *m, Job *j, bool delete_dependencies) {
446 /* Deletes one job from the transaction */
448 manager_transaction_unlink_job(m, j, delete_dependencies);
454 static void transaction_delete_unit(Manager *m, Unit *u) {
457 /* Deletes all jobs associated with a certain unit from the
460 while ((j = hashmap_get(m->transaction_jobs, u)))
461 transaction_delete_job(m, j, true);
464 static void transaction_clean_dependencies(Manager *m) {
470 /* Drops all dependencies of all installed jobs */
472 HASHMAP_FOREACH(j, m->jobs, i) {
473 while (j->subject_list)
474 job_dependency_free(j->subject_list);
475 while (j->object_list)
476 job_dependency_free(j->object_list);
479 assert(!m->transaction_anchor);
482 static void transaction_abort(Manager *m) {
487 while ((j = hashmap_first(m->transaction_jobs)))
489 transaction_delete_job(m, j, true);
493 assert(hashmap_isempty(m->transaction_jobs));
495 transaction_clean_dependencies(m);
498 static void transaction_find_jobs_that_matter_to_anchor(Manager *m, Job *j, unsigned generation) {
503 /* A recursive sweep through the graph that marks all units
504 * that matter to the anchor job, i.e. are directly or
505 * indirectly a dependency of the anchor job via paths that
506 * are fully marked as mattering. */
511 l = m->transaction_anchor;
513 LIST_FOREACH(subject, l, l) {
515 /* This link does not matter */
519 /* This unit has already been marked */
520 if (l->object->generation == generation)
523 l->object->matters_to_anchor = true;
524 l->object->generation = generation;
526 transaction_find_jobs_that_matter_to_anchor(m, l->object, generation);
530 static void transaction_merge_and_delete_job(Manager *m, Job *j, Job *other, JobType t) {
531 JobDependency *l, *last;
535 assert(j->unit == other->unit);
536 assert(!j->installed);
538 /* Merges 'other' into 'j' and then deletes j. */
541 j->state = JOB_WAITING;
542 j->override = j->override || other->override;
544 j->matters_to_anchor = j->matters_to_anchor || other->matters_to_anchor;
546 /* Patch us in as new owner of the JobDependency objects */
548 LIST_FOREACH(subject, l, other->subject_list) {
549 assert(l->subject == other);
554 /* Merge both lists */
556 last->subject_next = j->subject_list;
558 j->subject_list->subject_prev = last;
559 j->subject_list = other->subject_list;
562 /* Patch us in as new owner of the JobDependency objects */
564 LIST_FOREACH(object, l, other->object_list) {
565 assert(l->object == other);
570 /* Merge both lists */
572 last->object_next = j->object_list;
574 j->object_list->object_prev = last;
575 j->object_list = other->object_list;
578 /* Kill the other job */
579 other->subject_list = NULL;
580 other->object_list = NULL;
581 transaction_delete_job(m, other, true);
584 static int delete_one_unmergeable_job(Manager *m, Job *j) {
589 /* Tries to delete one item in the linked list
590 * j->transaction_next->transaction_next->... that conflicts
591 * whith another one, in an attempt to make an inconsistent
592 * transaction work. */
594 /* We rely here on the fact that if a merged with b does not
595 * merge with c, either a or b merge with c neither */
596 LIST_FOREACH(transaction, j, j)
597 LIST_FOREACH(transaction, k, j->transaction_next) {
600 /* Is this one mergeable? Then skip it */
601 if (job_type_is_mergeable(j->type, k->type))
604 /* Ok, we found two that conflict, let's see if we can
605 * drop one of them */
606 if (!j->matters_to_anchor)
608 else if (!k->matters_to_anchor)
613 /* Ok, we can drop one, so let's do so. */
614 log_debug("Trying to fix job merging by deleting job %s/%s", d->unit->meta.id, job_type_to_string(d->type));
615 transaction_delete_job(m, d, true);
622 static int transaction_merge_jobs(Manager *m) {
629 /* First step, check whether any of the jobs for one specific
630 * task conflict. If so, try to drop one of them. */
631 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
636 LIST_FOREACH(transaction, k, j->transaction_next) {
637 if ((r = job_type_merge(&t, k->type)) >= 0)
640 /* OK, we could not merge all jobs for this
641 * action. Let's see if we can get rid of one
644 if ((r = delete_one_unmergeable_job(m, j)) >= 0)
645 /* Ok, we managed to drop one, now
646 * let's ask our callers to call us
647 * again after garbage collecting */
650 /* We couldn't merge anything. Failure */
655 /* Second step, merge the jobs. */
656 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
660 /* Merge all transactions */
661 LIST_FOREACH(transaction, k, j->transaction_next)
662 assert_se(job_type_merge(&t, k->type) == 0);
664 /* If an active job is mergeable, merge it too */
665 if (j->unit->meta.job)
666 job_type_merge(&t, j->unit->meta.job->type); /* Might fail. Which is OK */
668 while ((k = j->transaction_next)) {
670 transaction_merge_and_delete_job(m, k, j, t);
673 transaction_merge_and_delete_job(m, j, k, t);
676 assert(!j->transaction_next);
677 assert(!j->transaction_prev);
683 static void transaction_drop_redundant(Manager *m) {
688 /* Goes through the transaction and removes all jobs that are
697 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
698 bool changes_something = false;
701 LIST_FOREACH(transaction, k, j) {
703 if (!job_is_anchor(k) &&
704 job_type_is_redundant(k->type, unit_active_state(k->unit)))
707 changes_something = true;
711 if (changes_something)
714 log_debug("Found redundant job %s/%s, dropping.", j->unit->meta.id, job_type_to_string(j->type));
715 transaction_delete_job(m, j, false);
723 static bool unit_matters_to_anchor(Unit *u, Job *j) {
725 assert(!j->transaction_prev);
727 /* Checks whether at least one of the jobs for this unit
728 * matters to the anchor. */
730 LIST_FOREACH(transaction, j, j)
731 if (j->matters_to_anchor)
737 static int transaction_verify_order_one(Manager *m, Job *j, Job *from, unsigned generation) {
744 assert(!j->transaction_prev);
746 /* Does a recursive sweep through the ordering graph, looking
747 * for a cycle. If we find cycle we try to break it. */
749 /* Have we seen this before? */
750 if (j->generation == generation) {
753 /* If the marker is NULL we have been here already and
754 * decided the job was loop-free from here. Hence
755 * shortcut things and return right-away. */
759 /* So, the marker is not NULL and we already have been
760 * here. We have a cycle. Let's try to break it. We go
761 * backwards in our path and try to find a suitable
762 * job to remove. We use the marker to find our way
763 * back, since smart how we are we stored our way back
765 log_debug("Found ordering cycle on %s/%s", j->unit->meta.id, job_type_to_string(j->type));
767 for (k = from; k; k = ((k->generation == generation && k->marker != k) ? k->marker : NULL)) {
769 log_debug("Walked on cycle path to %s/%s", k->unit->meta.id, job_type_to_string(k->type));
772 !unit_matters_to_anchor(k->unit, k)) {
773 /* Ok, we can drop this one, so let's
775 log_debug("Breaking order cycle by deleting job %s/%s", k->unit->meta.id, job_type_to_string(k->type));
776 transaction_delete_unit(m, k->unit);
780 /* Check if this in fact was the beginning of
786 log_debug("Unable to break cycle");
791 /* Make the marker point to where we come from, so that we can
792 * find our way backwards if we want to break a cycle. We use
793 * a special marker for the beginning: we point to
795 j->marker = from ? from : j;
796 j->generation = generation;
798 /* We assume that the the dependencies are bidirectional, and
799 * hence can ignore UNIT_AFTER */
800 SET_FOREACH(u, j->unit->meta.dependencies[UNIT_BEFORE], i) {
803 /* Is there a job for this unit? */
804 if (!(o = hashmap_get(m->transaction_jobs, u)))
806 /* Ok, there is no job for this in the
807 * transaction, but maybe there is already one
809 if (!(o = u->meta.job))
812 if ((r = transaction_verify_order_one(m, o, j, generation)) < 0)
816 /* Ok, let's backtrack, and remember that this entry is not on
817 * our path anymore. */
823 static int transaction_verify_order(Manager *m, unsigned *generation) {
832 /* Check if the ordering graph is cyclic. If it is, try to fix
833 * that up by dropping one of the jobs. */
837 HASHMAP_FOREACH(j, m->transaction_jobs, i)
838 if ((r = transaction_verify_order_one(m, j, NULL, g)) < 0)
844 static void transaction_collect_garbage(Manager *m) {
849 /* Drop jobs that are not required by any other job */
857 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
861 log_debug("Garbage collecting job %s/%s", j->unit->meta.id, job_type_to_string(j->type));
862 transaction_delete_job(m, j, true);
870 static int transaction_is_destructive(Manager *m) {
876 /* Checks whether applying this transaction means that
877 * existing jobs would be replaced */
879 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
882 assert(!j->transaction_prev);
883 assert(!j->transaction_next);
885 if (j->unit->meta.job &&
886 j->unit->meta.job != j &&
887 !job_type_is_superset(j->type, j->unit->meta.job->type))
894 static void transaction_minimize_impact(Manager *m) {
898 /* Drops all unnecessary jobs that reverse already active jobs
899 * or that stop a running service. */
907 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
908 LIST_FOREACH(transaction, j, j) {
909 bool stops_running_service, changes_existing_job;
911 /* If it matters, we shouldn't drop it */
912 if (j->matters_to_anchor)
915 /* Would this stop a running service?
916 * Would this change an existing job?
917 * If so, let's drop this entry */
919 stops_running_service =
920 j->type == JOB_STOP && UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(j->unit));
922 changes_existing_job =
923 j->unit->meta.job && job_type_is_conflicting(j->type, j->unit->meta.job->state);
925 if (!stops_running_service && !changes_existing_job)
928 if (stops_running_service)
929 log_debug("%s/%s would stop a running service.", j->unit->meta.id, job_type_to_string(j->type));
931 if (changes_existing_job)
932 log_debug("%s/%s would change existing job.", j->unit->meta.id, job_type_to_string(j->type));
934 /* Ok, let's get rid of this */
935 log_debug("Deleting %s/%s to minimize impact.", j->unit->meta.id, job_type_to_string(j->type));
937 transaction_delete_job(m, j, true);
949 static int transaction_apply(Manager *m) {
954 /* Moves the transaction jobs to the set of active jobs */
956 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
958 assert(!j->transaction_prev);
959 assert(!j->transaction_next);
964 if ((r = hashmap_put(m->jobs, UINT32_TO_PTR(j->id), j)) < 0)
968 while ((j = hashmap_steal_first(m->transaction_jobs))) {
972 if (j->unit->meta.job)
973 job_free(j->unit->meta.job);
975 j->unit->meta.job = j;
978 /* We're fully installed. Now let's free data we don't
981 assert(!j->transaction_next);
982 assert(!j->transaction_prev);
984 job_add_to_run_queue(j);
985 job_add_to_dbus_queue(j);
988 /* As last step, kill all remaining job dependencies. */
989 transaction_clean_dependencies(m);
995 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
999 hashmap_remove(m->jobs, UINT32_TO_PTR(j->id));
1005 static int transaction_activate(Manager *m, JobMode mode) {
1007 unsigned generation = 1;
1011 /* This applies the changes recorded in transaction_jobs to
1012 * the actual list of jobs, if possible. */
1014 /* First step: figure out which jobs matter */
1015 transaction_find_jobs_that_matter_to_anchor(m, NULL, generation++);
1017 /* Second step: Try not to stop any running services if
1018 * we don't have to. Don't try to reverse running
1019 * jobs if we don't have to. */
1020 transaction_minimize_impact(m);
1022 /* Third step: Drop redundant jobs */
1023 transaction_drop_redundant(m);
1026 /* Fourth step: Let's remove unneeded jobs that might
1028 transaction_collect_garbage(m);
1030 /* Fifth step: verify order makes sense and correct
1031 * cycles if necessary and possible */
1032 if ((r = transaction_verify_order(m, &generation)) >= 0)
1036 log_debug("Requested transaction contains an unfixable cyclic ordering dependency: %s", strerror(-r));
1040 /* Let's see if the resulting transaction ordering
1041 * graph is still cyclic... */
1045 /* Sixth step: let's drop unmergeable entries if
1046 * necessary and possible, merge entries we can
1048 if ((r = transaction_merge_jobs(m)) >= 0)
1052 log_debug("Requested transaction contains unmergable jobs: %s", strerror(-r));
1056 /* Seventh step: an entry got dropped, let's garbage
1057 * collect its dependencies. */
1058 transaction_collect_garbage(m);
1060 /* Let's see if the resulting transaction still has
1061 * unmergeable entries ... */
1064 /* Eights step: Drop redundant jobs again, if the merging now allows us to drop more. */
1065 transaction_drop_redundant(m);
1067 /* Ninth step: check whether we can actually apply this */
1068 if (mode == JOB_FAIL)
1069 if ((r = transaction_is_destructive(m)) < 0) {
1070 log_debug("Requested transaction contradicts existing jobs: %s", strerror(-r));
1074 /* Tenth step: apply changes */
1075 if ((r = transaction_apply(m)) < 0) {
1076 log_debug("Failed to apply transaction: %s", strerror(-r));
1080 assert(hashmap_isempty(m->transaction_jobs));
1081 assert(!m->transaction_anchor);
1086 transaction_abort(m);
1090 static Job* transaction_add_one_job(Manager *m, JobType type, Unit *unit, bool override, bool *is_new) {
1097 /* Looks for an axisting prospective job and returns that. If
1098 * it doesn't exist it is created and added to the prospective
1101 f = hashmap_get(m->transaction_jobs, unit);
1103 LIST_FOREACH(transaction, j, f) {
1104 assert(j->unit == unit);
1106 if (j->type == type) {
1113 if (unit->meta.job && unit->meta.job->type == type)
1115 else if (!(j = job_new(m, type, unit)))
1120 j->matters_to_anchor = false;
1121 j->override = override;
1123 LIST_PREPEND(Job, transaction, f, j);
1125 if ((r = hashmap_replace(m->transaction_jobs, unit, f)) < 0) {
1133 log_debug("Added job %s/%s to transaction.", unit->meta.id, job_type_to_string(type));
1138 void manager_transaction_unlink_job(Manager *m, Job *j, bool delete_dependencies) {
1142 if (j->transaction_prev)
1143 j->transaction_prev->transaction_next = j->transaction_next;
1144 else if (j->transaction_next)
1145 hashmap_replace(m->transaction_jobs, j->unit, j->transaction_next);
1147 hashmap_remove_value(m->transaction_jobs, j->unit, j);
1149 if (j->transaction_next)
1150 j->transaction_next->transaction_prev = j->transaction_prev;
1152 j->transaction_prev = j->transaction_next = NULL;
1154 while (j->subject_list)
1155 job_dependency_free(j->subject_list);
1157 while (j->object_list) {
1158 Job *other = j->object_list->matters ? j->object_list->subject : NULL;
1160 job_dependency_free(j->object_list);
1162 if (other && delete_dependencies) {
1163 log_debug("Deleting job %s/%s as dependency of job %s/%s",
1164 other->unit->meta.id, job_type_to_string(other->type),
1165 j->unit->meta.id, job_type_to_string(j->type));
1166 transaction_delete_job(m, other, delete_dependencies);
1171 static int transaction_add_job_and_dependencies(
1186 assert(type < _JOB_TYPE_MAX);
1189 if (unit->meta.load_state != UNIT_LOADED)
1192 if (!unit_job_is_applicable(unit, type))
1195 /* First add the job. */
1196 if (!(ret = transaction_add_one_job(m, type, unit, override, &is_new)))
1199 /* Then, add a link to the job. */
1200 if (!job_dependency_new(by, ret, matters))
1204 /* Finally, recursively add in all dependencies. */
1205 if (type == JOB_START || type == JOB_RELOAD_OR_START) {
1206 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES], i)
1207 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, true, override, NULL)) < 0 && r != -EBADR)
1210 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES_OVERRIDABLE], i)
1211 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, !override, override, NULL)) < 0 && r != -EBADR)
1212 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, strerror(-r));
1214 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_WANTS], i)
1215 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, false, false, NULL)) < 0)
1216 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, strerror(-r));
1218 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE], i)
1219 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, true, override, NULL)) < 0 && r != -EBADR)
1222 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE_OVERRIDABLE], i)
1223 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, !override, override, NULL)) < 0 && r != -EBADR)
1224 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, strerror(-r));
1226 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_CONFLICTS], i)
1227 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, dep, ret, true, override, NULL)) < 0 && r != -EBADR)
1230 } else if (type == JOB_STOP || type == JOB_RESTART || type == JOB_TRY_RESTART) {
1232 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRED_BY], i)
1233 if ((r = transaction_add_job_and_dependencies(m, type, dep, ret, true, override, NULL)) < 0 && r != -EBADR)
1237 /* JOB_VERIFY_STARTED, JOB_RELOAD require no dependency handling */
1249 static int transaction_add_isolate_jobs(Manager *m) {
1257 HASHMAP_FOREACH_KEY(u, k, m->units, i) {
1259 /* ignore aliases */
1260 if (u->meta.id != k)
1263 if (UNIT_VTABLE(u)->no_isolate)
1266 /* No need to stop inactive jobs */
1267 if (unit_active_state(u) == UNIT_INACTIVE)
1270 /* Is there already something listed for this? */
1271 if (hashmap_get(m->transaction_jobs, u))
1274 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, u, NULL, true, false, NULL)) < 0)
1275 log_warning("Cannot add isolate job for unit %s, ignoring: %s", u->meta.id, strerror(-r));
1281 int manager_add_job(Manager *m, JobType type, Unit *unit, JobMode mode, bool override, Job **_ret) {
1286 assert(type < _JOB_TYPE_MAX);
1288 assert(mode < _JOB_MODE_MAX);
1290 if (mode == JOB_ISOLATE && type != JOB_START)
1293 log_debug("Trying to enqueue job %s/%s", unit->meta.id, job_type_to_string(type));
1295 if ((r = transaction_add_job_and_dependencies(m, type, unit, NULL, true, override, &ret)) < 0) {
1296 transaction_abort(m);
1300 if (mode == JOB_ISOLATE)
1301 if ((r = transaction_add_isolate_jobs(m)) < 0) {
1302 transaction_abort(m);
1306 if ((r = transaction_activate(m, mode)) < 0)
1309 log_debug("Enqueued job %s/%s as %u", unit->meta.id, job_type_to_string(type), (unsigned) ret->id);
1317 int manager_add_job_by_name(Manager *m, JobType type, const char *name, JobMode mode, bool override, Job **_ret) {
1322 assert(type < _JOB_TYPE_MAX);
1324 assert(mode < _JOB_MODE_MAX);
1326 if ((r = manager_load_unit(m, name, NULL, &unit)) < 0)
1329 return manager_add_job(m, type, unit, mode, override, _ret);
1332 Job *manager_get_job(Manager *m, uint32_t id) {
1335 return hashmap_get(m->jobs, UINT32_TO_PTR(id));
1338 Unit *manager_get_unit(Manager *m, const char *name) {
1342 return hashmap_get(m->units, name);
1345 unsigned manager_dispatch_load_queue(Manager *m) {
1351 /* Make sure we are not run recursively */
1352 if (m->dispatching_load_queue)
1355 m->dispatching_load_queue = true;
1357 /* Dispatches the load queue. Takes a unit from the queue and
1358 * tries to load its data until the queue is empty */
1360 while ((meta = m->load_queue)) {
1361 assert(meta->in_load_queue);
1363 unit_load(UNIT(meta));
1367 m->dispatching_load_queue = false;
1371 int manager_load_unit_prepare(Manager *m, const char *name, const char *path, Unit **_ret) {
1376 assert(name || path);
1378 /* This will prepare the unit for loading, but not actually
1379 * load anything from disk. */
1381 if (path && !is_path(path))
1385 name = file_name_from_path(path);
1387 if (!unit_name_is_valid(name))
1390 if ((ret = manager_get_unit(m, name))) {
1395 if (!(ret = unit_new(m)))
1399 if (!(ret->meta.fragment_path = strdup(path))) {
1404 if ((r = unit_add_name(ret, name)) < 0) {
1409 unit_add_to_load_queue(ret);
1410 unit_add_to_dbus_queue(ret);
1411 unit_add_to_gc_queue(ret);
1419 int manager_load_unit(Manager *m, const char *name, const char *path, Unit **_ret) {
1424 /* This will load the service information files, but not actually
1425 * start any services or anything. */
1427 if ((r = manager_load_unit_prepare(m, name, path, _ret)) != 0)
1430 manager_dispatch_load_queue(m);
1433 *_ret = unit_follow_merge(*_ret);
1438 void manager_dump_jobs(Manager *s, FILE *f, const char *prefix) {
1445 HASHMAP_FOREACH(j, s->jobs, i)
1446 job_dump(j, f, prefix);
1449 void manager_dump_units(Manager *s, FILE *f, const char *prefix) {
1457 HASHMAP_FOREACH_KEY(u, t, s->units, i)
1458 if (u->meta.id == t)
1459 unit_dump(u, f, prefix);
1462 void manager_clear_jobs(Manager *m) {
1467 transaction_abort(m);
1469 while ((j = hashmap_first(m->jobs)))
1473 unsigned manager_dispatch_run_queue(Manager *m) {
1477 if (m->dispatching_run_queue)
1480 m->dispatching_run_queue = true;
1482 while ((j = m->run_queue)) {
1483 assert(j->installed);
1484 assert(j->in_run_queue);
1486 job_run_and_invalidate(j);
1490 m->dispatching_run_queue = false;
1494 unsigned manager_dispatch_dbus_queue(Manager *m) {
1501 if (m->dispatching_dbus_queue)
1504 m->dispatching_dbus_queue = true;
1506 while ((meta = m->dbus_unit_queue)) {
1507 assert(meta->in_dbus_queue);
1509 bus_unit_send_change_signal(UNIT(meta));
1513 while ((j = m->dbus_job_queue)) {
1514 assert(j->in_dbus_queue);
1516 bus_job_send_change_signal(j);
1520 m->dispatching_dbus_queue = false;
1524 static int manager_dispatch_sigchld(Manager *m) {
1533 /* First we call waitd() for a PID and do not reap the
1534 * zombie. That way we can still access /proc/$PID for
1535 * it while it is a zombie. */
1536 if (waitid(P_ALL, 0, &si, WEXITED|WNOHANG|WNOWAIT) < 0) {
1538 if (errno == ECHILD)
1550 if (si.si_code == CLD_EXITED || si.si_code == CLD_KILLED || si.si_code == CLD_DUMPED) {
1553 get_process_name(si.si_pid, &name);
1554 log_debug("Got SIGCHLD for process %llu (%s)", (unsigned long long) si.si_pid, strna(name));
1558 /* And now, we actually reap the zombie. */
1559 if (waitid(P_PID, si.si_pid, &si, WEXITED) < 0) {
1566 if (si.si_code != CLD_EXITED && si.si_code != CLD_KILLED && si.si_code != CLD_DUMPED)
1569 log_debug("Child %llu died (code=%s, status=%i/%s)",
1570 (long long unsigned) si.si_pid,
1571 sigchld_code_to_string(si.si_code),
1573 strna(si.si_code == CLD_EXITED ? exit_status_to_string(si.si_status) : strsignal(si.si_status)));
1575 if (!(u = hashmap_remove(m->watch_pids, UINT32_TO_PTR(si.si_pid))))
1578 log_debug("Child %llu belongs to %s", (long long unsigned) si.si_pid, u->meta.id);
1580 UNIT_VTABLE(u)->sigchld_event(u, si.si_pid, si.si_code, si.si_status);
1586 static int manager_start_target(Manager *m, const char *name) {
1589 if ((r = manager_add_job_by_name(m, JOB_START, name, JOB_REPLACE, true, NULL)) < 0)
1590 log_error("Failed to enqueue %s job: %s", name, strerror(-r));
1595 static int manager_process_signal_fd(Manager *m) {
1597 struct signalfd_siginfo sfsi;
1598 bool sigchld = false;
1603 if ((n = read(m->signal_watch.fd, &sfsi, sizeof(sfsi))) != sizeof(sfsi)) {
1608 if (errno == EAGAIN)
1614 switch (sfsi.ssi_signo) {
1621 if (m->running_as == MANAGER_INIT) {
1622 /* This is for compatibility with the
1623 * original sysvinit */
1624 m->exit_code = MANAGER_REEXECUTE;
1631 if (m->running_as == MANAGER_INIT) {
1632 manager_start_target(m, SPECIAL_CTRL_ALT_DEL_TARGET);
1636 /* Run the exit target if there is one, if not, just exit. */
1637 if (manager_start_target(m, SPECIAL_EXIT_SERVICE) < 0) {
1638 m->exit_code = MANAGER_EXIT;
1645 if (m->running_as == MANAGER_INIT)
1646 manager_start_target(m, SPECIAL_KBREQUEST_TARGET);
1648 /* This is a nop on non-init */
1652 if (m->running_as == MANAGER_INIT)
1653 manager_start_target(m, SPECIAL_SIGPWR_TARGET);
1655 /* This is a nop on non-init */
1661 u = manager_get_unit(m, SPECIAL_DBUS_SERVICE);
1663 if (!u || UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u))) {
1664 log_info("Trying to reconnect to bus...");
1669 if (!u || !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u))) {
1670 log_info("Loading D-Bus service...");
1671 manager_start_target(m, SPECIAL_DBUS_SERVICE);
1682 if (!(f = open_memstream(&dump, &size))) {
1683 log_warning("Failed to allocate memory stream.");
1687 manager_dump_units(m, f, "\t");
1688 manager_dump_jobs(m, f, "\t");
1693 log_warning("Failed to write status stream");
1698 log_dump(LOG_INFO, dump);
1705 m->exit_code = MANAGER_RELOAD;
1709 log_info("Got unhandled signal <%s>.", strsignal(sfsi.ssi_signo));
1714 return manager_dispatch_sigchld(m);
1719 static int process_event(Manager *m, struct epoll_event *ev) {
1726 assert(w = ev->data.ptr);
1732 /* An incoming signal? */
1733 if (ev->events != EPOLLIN)
1736 if ((r = manager_process_signal_fd(m)) < 0)
1743 /* Some fd event, to be dispatched to the units */
1744 UNIT_VTABLE(w->data.unit)->fd_event(w->data.unit, w->fd, ev->events, w);
1751 /* Some timer event, to be dispatched to the units */
1752 if ((k = read(w->fd, &v, sizeof(v))) != sizeof(v)) {
1754 if (k < 0 && (errno == EINTR || errno == EAGAIN))
1757 return k < 0 ? -errno : -EIO;
1760 UNIT_VTABLE(w->data.unit)->timer_event(w->data.unit, v, w);
1765 /* Some mount table change, intended for the mount subsystem */
1766 mount_fd_event(m, ev->events);
1770 /* Some notification from udev, intended for the device subsystem */
1771 device_fd_event(m, ev->events);
1774 case WATCH_DBUS_WATCH:
1775 bus_watch_event(m, w, ev->events);
1778 case WATCH_DBUS_TIMEOUT:
1779 bus_timeout_event(m, w, ev->events);
1783 assert_not_reached("Unknown epoll event type.");
1789 int manager_loop(Manager *m) {
1792 RATELIMIT_DEFINE(rl, 1*USEC_PER_SEC, 1000);
1795 m->exit_code = MANAGER_RUNNING;
1797 /* There might still be some zombies hanging around from
1798 * before we were exec()'ed. Leat's reap them */
1799 if ((r = manager_dispatch_sigchld(m)) < 0)
1802 while (m->exit_code == MANAGER_RUNNING) {
1803 struct epoll_event event;
1806 if (!ratelimit_test(&rl)) {
1807 /* Yay, something is going seriously wrong, pause a little */
1808 log_warning("Looping too fast. Throttling execution a little.");
1812 if (manager_dispatch_load_queue(m) > 0)
1815 if (manager_dispatch_run_queue(m) > 0)
1818 if (bus_dispatch(m) > 0)
1821 if (manager_dispatch_cleanup_queue(m) > 0)
1824 if (manager_dispatch_gc_queue(m) > 0)
1827 if (manager_dispatch_dbus_queue(m) > 0)
1830 if ((n = epoll_wait(m->epoll_fd, &event, 1, -1)) < 0) {
1840 if ((r = process_event(m, &event)) < 0)
1844 return m->exit_code;
1847 int manager_get_unit_from_dbus_path(Manager *m, const char *s, Unit **_u) {
1855 if (!startswith(s, "/org/freedesktop/systemd1/unit/"))
1858 if (!(n = bus_path_unescape(s+31)))
1861 u = manager_get_unit(m, n);
1872 int manager_get_job_from_dbus_path(Manager *m, const char *s, Job **_j) {
1881 if (!startswith(s, "/org/freedesktop/systemd1/job/"))
1884 if ((r = safe_atou(s + 30, &id)) < 0)
1887 if (!(j = manager_get_job(m, id)))
1895 static bool manager_utmp_good(Manager *m) {
1900 if ((r = mount_path_is_mounted(m, _PATH_UTMPX)) <= 0) {
1903 log_warning("Failed to determine whether " _PATH_UTMPX " is mounted: %s", strerror(-r));
1911 void manager_write_utmp_reboot(Manager *m) {
1916 if (m->utmp_reboot_written)
1919 if (m->running_as != MANAGER_INIT)
1922 if (!manager_utmp_good(m))
1925 if ((r = utmp_put_reboot(m->startup_timestamp.realtime)) < 0) {
1927 if (r != -ENOENT && r != -EROFS)
1928 log_warning("Failed to write utmp/wtmp: %s", strerror(-r));
1933 m->utmp_reboot_written = true;
1936 void manager_write_utmp_runlevel(Manager *m, Unit *u) {
1942 if (u->meta.type != UNIT_TARGET)
1945 if (m->running_as != MANAGER_INIT)
1948 if (!manager_utmp_good(m))
1951 if ((runlevel = target_get_runlevel(TARGET(u))) <= 0)
1954 if ((r = utmp_put_runlevel(0, runlevel, 0)) < 0) {
1956 if (r != -ENOENT && r != -EROFS)
1957 log_warning("Failed to write utmp/wtmp: %s", strerror(-r));
1961 void manager_dispatch_bus_name_owner_changed(
1964 const char* old_owner,
1965 const char *new_owner) {
1972 if (!(u = hashmap_get(m->watch_bus, name)))
1975 UNIT_VTABLE(u)->bus_name_owner_change(u, name, old_owner, new_owner);
1978 void manager_dispatch_bus_query_pid_done(
1989 if (!(u = hashmap_get(m->watch_bus, name)))
1992 UNIT_VTABLE(u)->bus_query_pid_done(u, name, pid);
1995 int manager_open_serialization(FILE **_f) {
2003 if (asprintf(&path, "/dev/shm/systemd-%u.dump-XXXXXX", (unsigned) getpid()) < 0)
2006 saved_umask = umask(0077);
2007 fd = mkostemp(path, O_RDWR|O_CLOEXEC);
2017 log_debug("Serializing state to %s", path);
2020 if (!(f = fdopen(fd, "w+")) < 0)
2028 int manager_serialize(Manager *m, FILE *f, FDSet *fds) {
2038 HASHMAP_FOREACH_KEY(u, t, m->units, i) {
2039 if (u->meta.id != t)
2042 if (!unit_can_serialize(u))
2046 fputs(u->meta.id, f);
2049 if ((r = unit_serialize(u, f, fds)) < 0)
2059 int manager_deserialize(Manager *m, FILE *f, FDSet *fds) {
2065 log_debug("Deserializing state...");
2069 char name[UNIT_NAME_MAX+2];
2072 if (!fgets(name, sizeof(name), f)) {
2081 if ((r = manager_load_unit(m, strstrip(name), NULL, &u)) < 0)
2084 if ((r = unit_deserialize(u, f, fds)) < 0)
2094 int manager_reload(Manager *m) {
2101 if ((r = manager_open_serialization(&f)) < 0)
2104 if (!(fds = fdset_new())) {
2109 if ((r = manager_serialize(m, f, fds)) < 0)
2112 if (fseeko(f, 0, SEEK_SET) < 0) {
2117 /* From here on there is no way back. */
2118 manager_clear_jobs_and_units(m);
2120 /* Find new unit paths */
2121 lookup_paths_free(&m->lookup_paths);
2122 if ((q = lookup_paths_init(&m->lookup_paths, m->running_as)) < 0)
2125 /* First, enumerate what we can from all config files */
2126 if ((q = manager_enumerate(m)) < 0)
2129 /* Second, deserialize our stored data */
2130 if ((q = manager_deserialize(m, f, fds)) < 0)
2136 /* Third, fire things up! */
2137 if ((q = manager_coldplug(m)) < 0)
2150 static const char* const manager_running_as_table[_MANAGER_RUNNING_AS_MAX] = {
2151 [MANAGER_INIT] = "init",
2152 [MANAGER_SYSTEM] = "system",
2153 [MANAGER_SESSION] = "session"
2156 DEFINE_STRING_TABLE_LOOKUP(manager_running_as, ManagerRunningAs);