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>
43 #include "ratelimit.h"
45 #include "mount-setup.h"
46 #include "utmp-wtmp.h"
48 static int manager_setup_signals(Manager *m) {
50 struct epoll_event ev;
54 assert_se(sigemptyset(&mask) == 0);
55 assert_se(sigaddset(&mask, SIGCHLD) == 0);
56 assert_se(sigaddset(&mask, SIGINT) == 0); /* Kernel sends us this on control-alt-del */
57 assert_se(sigaddset(&mask, SIGWINCH) == 0); /* Kernel sends us this on kbrequest (alt-arrowup) */
58 assert_se(sigaddset(&mask, SIGTERM) == 0);
59 assert_se(sigaddset(&mask, SIGHUP) == 0);
60 assert_se(sigaddset(&mask, SIGUSR1) == 0);
61 assert_se(sigaddset(&mask, SIGUSR2) == 0);
62 assert_se(sigaddset(&mask, SIGPIPE) == 0);
63 assert_se(sigaddset(&mask, SIGPWR) == 0);
64 assert_se(sigaddset(&mask, SIGTTIN) == 0);
65 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
67 m->signal_watch.type = WATCH_SIGNAL;
68 if ((m->signal_watch.fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0)
73 ev.data.ptr = &m->signal_watch;
75 if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->signal_watch.fd, &ev) < 0)
78 if (m->running_as == MANAGER_INIT) {
79 /* Enable that we get SIGINT on control-alt-del */
80 if (reboot(RB_DISABLE_CAD) < 0)
81 log_warning("Failed to enable ctrl-alt-del handling: %s", strerror(errno));
83 /* Enable that we get SIGWINCH on kbrequest */
84 if (ioctl(0, KDSIGACCEPT, SIGWINCH) < 0)
85 log_warning("Failed to enable kbrequest handling: %s", strerror(errno));
91 static char** session_dirs(void) {
93 char *config_home = NULL, *data_home = NULL;
94 char **config_dirs = NULL, **data_dirs = NULL;
97 /* Implement the mechanisms defined in
99 * http://standards.freedesktop.org/basedir-spec/basedir-spec-0.6.html
101 * We look in both the config and the data dirs because we
102 * want to encourage that distributors ship their unit files
103 * as data, and allow overriding as configuration.
106 home = getenv("HOME");
108 if ((e = getenv("XDG_CONFIG_HOME"))) {
109 if (asprintf(&config_home, "%s/systemd/session", e) < 0)
113 if (asprintf(&config_home, "%s/.config/systemd/session", home) < 0)
117 if ((e = getenv("XDG_CONFIG_DIRS")))
118 config_dirs = strv_split(e, ":");
120 config_dirs = strv_new("/etc/xdg", NULL);
125 if ((e = getenv("XDG_DATA_HOME"))) {
126 if (asprintf(&data_home, "%s/systemd/session", e) < 0)
130 if (asprintf(&data_home, "%s/.local/share/systemd/session", home) < 0)
134 if ((e = getenv("XDG_DATA_DIRS")))
135 data_dirs = strv_split(e, ":");
137 data_dirs = strv_new("/usr/local/share", "/usr/share", NULL);
142 /* Now merge everything we found. */
144 if (!(t = strv_append(r, config_home)))
150 if (!(t = strv_merge_concat(r, config_dirs, "/systemd/session")))
155 if (!(t = strv_append(r, SESSION_CONFIG_UNIT_PATH)))
161 if (!(t = strv_append(r, data_home)))
167 if (!(t = strv_merge_concat(r, data_dirs, "/systemd/session")))
172 if (!(t = strv_append(r, SESSION_DATA_UNIT_PATH)))
177 if (!strv_path_make_absolute_cwd(r))
182 strv_free(config_dirs);
184 strv_free(data_dirs);
194 static int manager_find_paths(Manager *m) {
200 /* First priority is whatever has been passed to us via env
202 if ((e = getenv("SYSTEMD_UNIT_PATH")))
203 if (!(m->unit_path = split_path_and_make_absolute(e)))
206 if (strv_isempty(m->unit_path)) {
208 /* Nothing is set, so let's figure something out. */
209 strv_free(m->unit_path);
211 if (m->running_as == MANAGER_SESSION) {
212 if (!(m->unit_path = session_dirs()))
215 if (!(m->unit_path = strv_new(
216 SYSTEM_CONFIG_UNIT_PATH, /* /etc/systemd/system/ */
217 SYSTEM_DATA_UNIT_PATH, /* /lib/systemd/system/ */
222 if (m->running_as == MANAGER_INIT) {
223 /* /etc/init.d/ compativility does not matter to users */
225 if ((e = getenv("SYSTEMD_SYSVINIT_PATH")))
226 if (!(m->sysvinit_path = split_path_and_make_absolute(e)))
229 if (strv_isempty(m->sysvinit_path)) {
230 strv_free(m->sysvinit_path);
232 if (!(m->sysvinit_path = strv_new(
233 SYSTEM_SYSVINIT_PATH, /* /etc/init.d/ */
238 if ((e = getenv("SYSTEMD_SYSVRCND_PATH")))
239 if (!(m->sysvrcnd_path = split_path_and_make_absolute(e)))
242 if (strv_isempty(m->sysvrcnd_path)) {
243 strv_free(m->sysvrcnd_path);
245 if (!(m->sysvrcnd_path = strv_new(
246 SYSTEM_SYSVRCND_PATH, /* /etc/rcN.d/ */
252 strv_uniq(m->unit_path);
253 strv_uniq(m->sysvinit_path);
254 strv_uniq(m->sysvrcnd_path);
256 assert(!strv_isempty(m->unit_path));
257 if (!(t = strv_join(m->unit_path, "\n\t")))
259 log_debug("Looking for unit files in:\n\t%s", t);
262 if (!strv_isempty(m->sysvinit_path)) {
264 if (!(t = strv_join(m->sysvinit_path, "\n\t")))
267 log_debug("Looking for SysV init scripts in:\n\t%s", t);
270 log_debug("Ignoring SysV init scripts.");
272 if (!strv_isempty(m->sysvrcnd_path)) {
274 if (!(t = strv_join(m->sysvrcnd_path, "\n\t")))
277 log_debug("Looking for SysV rcN.d links in:\n\t%s", t);
280 log_debug("Ignoring SysV rcN.d links.");
285 int manager_new(ManagerRunningAs running_as, Manager **_m) {
290 assert(running_as >= 0);
291 assert(running_as < _MANAGER_RUNNING_AS_MAX);
293 if (!(m = new0(Manager, 1)))
296 m->boot_timestamp = now(CLOCK_REALTIME);
298 m->running_as = running_as;
299 m->signal_watch.fd = m->mount_watch.fd = m->udev_watch.fd = m->epoll_fd = -1;
300 m->current_job_id = 1; /* start as id #1, so that we can leave #0 around as "null-like" value */
302 if (!(m->units = hashmap_new(string_hash_func, string_compare_func)))
305 if (!(m->jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
308 if (!(m->transaction_jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
311 if (!(m->watch_pids = hashmap_new(trivial_hash_func, trivial_compare_func)))
314 if (!(m->cgroup_bondings = hashmap_new(string_hash_func, string_compare_func)))
317 if ((m->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0)
320 if ((r = manager_find_paths(m)) < 0)
323 if ((r = manager_setup_signals(m)) < 0)
326 if ((r = manager_setup_cgroup(m)) < 0)
329 /* Try to connect to the busses, if possible. */
330 if ((r = bus_init_system(m)) < 0 ||
331 (r = bus_init_api(m)) < 0)
342 static unsigned manager_dispatch_cleanup_queue(Manager *m) {
348 while ((meta = m->cleanup_queue)) {
349 assert(meta->in_cleanup_queue);
351 unit_free(UNIT(meta));
358 void manager_free(Manager *m) {
365 while ((j = hashmap_first(m->transaction_jobs)))
368 while ((u = hashmap_first(m->units)))
371 manager_dispatch_cleanup_queue(m);
373 for (c = 0; c < _UNIT_TYPE_MAX; c++)
374 if (unit_vtable[c]->shutdown)
375 unit_vtable[c]->shutdown(m);
377 manager_shutdown_cgroup(m);
382 hashmap_free(m->units);
383 hashmap_free(m->jobs);
384 hashmap_free(m->transaction_jobs);
385 hashmap_free(m->watch_pids);
387 if (m->epoll_fd >= 0)
388 close_nointr(m->epoll_fd);
389 if (m->signal_watch.fd >= 0)
390 close_nointr(m->signal_watch.fd);
392 strv_free(m->unit_path);
393 strv_free(m->sysvinit_path);
394 strv_free(m->sysvrcnd_path);
396 free(m->cgroup_controller);
397 free(m->cgroup_hierarchy);
399 assert(hashmap_isempty(m->cgroup_bondings));
400 hashmap_free(m->cgroup_bondings);
405 int manager_coldplug(Manager *m) {
414 /* First, let's ask every type to load all units from
415 * disk/kernel that it might know */
416 for (c = 0; c < _UNIT_TYPE_MAX; c++)
417 if (unit_vtable[c]->enumerate)
418 if ((r = unit_vtable[c]->enumerate(m)) < 0)
421 manager_dispatch_load_queue(m);
423 /* Then, let's set up their initial state. */
424 HASHMAP_FOREACH_KEY(u, k, m->units, i) {
430 if (UNIT_VTABLE(u)->coldplug)
431 if ((r = UNIT_VTABLE(u)->coldplug(u)) < 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->forced = j->forced || other->forced;
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", unit_id(d->unit), 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.", unit_id(j->unit), 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 /* Did we find a cycle? */
750 if (j->marker && j->generation == generation) {
753 /* So, we already have been here. We have a
754 * cycle. Let's try to break it. We go backwards in
755 * our path and try to find a suitable job to
756 * remove. We use the marker to find our way back,
757 * since smart how we are we stored our way back in
760 log_debug("Found ordering cycle on %s/%s", unit_id(j->unit), job_type_to_string(j->type));
762 for (k = from; k; k = (k->generation == generation ? k->marker : NULL)) {
764 log_debug("Walked on cycle path to %s/%s", unit_id(k->unit), job_type_to_string(k->type));
767 !unit_matters_to_anchor(k->unit, k)) {
768 /* Ok, we can drop this one, so let's
770 log_debug("Breaking order cycle by deleting job %s/%s", unit_id(k->unit), job_type_to_string(k->type));
771 transaction_delete_unit(m, k->unit);
775 /* Check if this in fact was the beginning of
781 log_debug("Unable to break cycle");
786 /* Make the marker point to where we come from, so that we can
787 * find our way backwards if we want to break a cycle */
789 j->generation = generation;
791 /* We assume that the the dependencies are bidirectional, and
792 * hence can ignore UNIT_AFTER */
793 SET_FOREACH(u, j->unit->meta.dependencies[UNIT_BEFORE], i) {
796 /* Is there a job for this unit? */
797 if (!(o = hashmap_get(m->transaction_jobs, u)))
799 /* Ok, there is no job for this in the
800 * transaction, but maybe there is already one
802 if (!(o = u->meta.job))
805 if ((r = transaction_verify_order_one(m, o, j, generation)) < 0)
809 /* Ok, let's backtrack, and remember that this entry is not on
810 * our path anymore. */
816 static int transaction_verify_order(Manager *m, unsigned *generation) {
824 /* Check if the ordering graph is cyclic. If it is, try to fix
825 * that up by dropping one of the jobs. */
827 HASHMAP_FOREACH(j, m->transaction_jobs, i)
828 if ((r = transaction_verify_order_one(m, j, NULL, (*generation)++)) < 0)
834 static void transaction_collect_garbage(Manager *m) {
839 /* Drop jobs that are not required by any other job */
847 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
851 log_debug("Garbage collecting job %s/%s", unit_id(j->unit), job_type_to_string(j->type));
852 transaction_delete_job(m, j, true);
860 static int transaction_is_destructive(Manager *m, JobMode mode) {
866 /* Checks whether applying this transaction means that
867 * existing jobs would be replaced */
869 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
872 assert(!j->transaction_prev);
873 assert(!j->transaction_next);
875 if (j->unit->meta.job &&
876 j->unit->meta.job != j &&
877 !job_type_is_superset(j->type, j->unit->meta.job->type))
884 static void transaction_minimize_impact(Manager *m) {
888 /* Drops all unnecessary jobs that reverse already active jobs
889 * or that stop a running service. */
897 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
898 LIST_FOREACH(transaction, j, j) {
899 bool stops_running_service, changes_existing_job;
901 /* If it matters, we shouldn't drop it */
902 if (j->matters_to_anchor)
905 /* Would this stop a running service?
906 * Would this change an existing job?
907 * If so, let's drop this entry */
909 stops_running_service =
910 j->type == JOB_STOP && UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(j->unit));
912 changes_existing_job =
913 j->unit->meta.job && job_type_is_conflicting(j->type, j->unit->meta.job->state);
915 if (!stops_running_service && !changes_existing_job)
918 if (stops_running_service)
919 log_debug("%s/%s would stop a running service.", unit_id(j->unit), job_type_to_string(j->type));
921 if (changes_existing_job)
922 log_debug("%s/%s would change existing job.", unit_id(j->unit), job_type_to_string(j->type));
924 /* Ok, let's get rid of this */
925 log_debug("Deleting %s/%s to minimize impact.", unit_id(j->unit), job_type_to_string(j->type));
927 transaction_delete_job(m, j, true);
939 static int transaction_apply(Manager *m, JobMode mode) {
944 /* Moves the transaction jobs to the set of active jobs */
946 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
948 assert(!j->transaction_prev);
949 assert(!j->transaction_next);
954 if ((r = hashmap_put(m->jobs, UINT32_TO_PTR(j->id), j)) < 0)
958 while ((j = hashmap_steal_first(m->transaction_jobs))) {
962 if (j->unit->meta.job)
963 job_free(j->unit->meta.job);
965 j->unit->meta.job = j;
968 /* We're fully installed. Now let's free data we don't
971 assert(!j->transaction_next);
972 assert(!j->transaction_prev);
974 job_add_to_run_queue(j);
975 job_add_to_dbus_queue(j);
978 /* As last step, kill all remaining job dependencies. */
979 transaction_clean_dependencies(m);
985 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
989 hashmap_remove(m->jobs, UINT32_TO_PTR(j->id));
995 static int transaction_activate(Manager *m, JobMode mode) {
997 unsigned generation = 1;
1001 /* This applies the changes recorded in transaction_jobs to
1002 * the actual list of jobs, if possible. */
1004 /* First step: figure out which jobs matter */
1005 transaction_find_jobs_that_matter_to_anchor(m, NULL, generation++);
1007 /* Second step: Try not to stop any running services if
1008 * we don't have to. Don't try to reverse running
1009 * jobs if we don't have to. */
1010 transaction_minimize_impact(m);
1012 /* Third step: Drop redundant jobs */
1013 transaction_drop_redundant(m);
1016 /* Fourth step: Let's remove unneeded jobs that might
1018 transaction_collect_garbage(m);
1020 /* Fifth step: verify order makes sense and correct
1021 * cycles if necessary and possible */
1022 if ((r = transaction_verify_order(m, &generation)) >= 0)
1026 log_debug("Requested transaction contains an unfixable cyclic ordering dependency: %s", strerror(-r));
1030 /* Let's see if the resulting transaction ordering
1031 * graph is still cyclic... */
1035 /* Sixth step: let's drop unmergeable entries if
1036 * necessary and possible, merge entries we can
1038 if ((r = transaction_merge_jobs(m)) >= 0)
1042 log_debug("Requested transaction contains unmergable jobs: %s", strerror(-r));
1046 /* Seventh step: an entry got dropped, let's garbage
1047 * collect its dependencies. */
1048 transaction_collect_garbage(m);
1050 /* Let's see if the resulting transaction still has
1051 * unmergeable entries ... */
1054 /* Eights step: Drop redundant jobs again, if the merging now allows us to drop more. */
1055 transaction_drop_redundant(m);
1057 /* Ninth step: check whether we can actually apply this */
1058 if (mode == JOB_FAIL)
1059 if ((r = transaction_is_destructive(m, mode)) < 0) {
1060 log_debug("Requested transaction contradicts existing jobs: %s", strerror(-r));
1064 /* Tenth step: apply changes */
1065 if ((r = transaction_apply(m, mode)) < 0) {
1066 log_debug("Failed to apply transaction: %s", strerror(-r));
1070 assert(hashmap_isempty(m->transaction_jobs));
1071 assert(!m->transaction_anchor);
1076 transaction_abort(m);
1080 static Job* transaction_add_one_job(Manager *m, JobType type, Unit *unit, bool force, bool *is_new) {
1087 /* Looks for an axisting prospective job and returns that. If
1088 * it doesn't exist it is created and added to the prospective
1091 f = hashmap_get(m->transaction_jobs, unit);
1093 LIST_FOREACH(transaction, j, f) {
1094 assert(j->unit == unit);
1096 if (j->type == type) {
1103 if (unit->meta.job && unit->meta.job->type == type)
1105 else if (!(j = job_new(m, type, unit)))
1110 j->matters_to_anchor = false;
1113 LIST_PREPEND(Job, transaction, f, j);
1115 if ((r = hashmap_replace(m->transaction_jobs, unit, f)) < 0) {
1123 log_debug("Added job %s/%s to transaction.", unit_id(unit), job_type_to_string(type));
1128 void manager_transaction_unlink_job(Manager *m, Job *j, bool delete_dependencies) {
1132 if (j->transaction_prev)
1133 j->transaction_prev->transaction_next = j->transaction_next;
1134 else if (j->transaction_next)
1135 hashmap_replace(m->transaction_jobs, j->unit, j->transaction_next);
1137 hashmap_remove_value(m->transaction_jobs, j->unit, j);
1139 if (j->transaction_next)
1140 j->transaction_next->transaction_prev = j->transaction_prev;
1142 j->transaction_prev = j->transaction_next = NULL;
1144 while (j->subject_list)
1145 job_dependency_free(j->subject_list);
1147 while (j->object_list) {
1148 Job *other = j->object_list->matters ? j->object_list->subject : NULL;
1150 job_dependency_free(j->object_list);
1152 if (other && delete_dependencies) {
1153 log_debug("Deleting job %s/%s as dependency of job %s/%s",
1154 unit_id(other->unit), job_type_to_string(other->type),
1155 unit_id(j->unit), job_type_to_string(j->type));
1156 transaction_delete_job(m, other, delete_dependencies);
1161 static int transaction_add_job_and_dependencies(Manager *m, JobType type, Unit *unit, Job *by, bool matters, bool force, Job **_ret) {
1169 assert(type < _JOB_TYPE_MAX);
1172 if (unit->meta.load_state != UNIT_LOADED)
1175 if (!unit_job_is_applicable(unit, type))
1178 /* First add the job. */
1179 if (!(ret = transaction_add_one_job(m, type, unit, force, &is_new)))
1182 /* Then, add a link to the job. */
1183 if (!job_dependency_new(by, ret, matters))
1187 /* Finally, recursively add in all dependencies. */
1188 if (type == JOB_START || type == JOB_RELOAD_OR_START) {
1189 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES], i)
1190 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, true, force, NULL)) < 0 && r != -EBADR)
1192 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_SOFT_REQUIRES], i)
1193 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, !force, force, NULL)) < 0 && r != -EBADR)
1195 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_WANTS], i)
1196 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, false, force, NULL)) < 0)
1197 log_warning("Cannot add dependency job for unit %s, ignoring: %s", unit_id(dep), strerror(-r));
1198 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE], i)
1199 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, true, force, NULL)) < 0 && r != -EBADR)
1201 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_SOFT_REQUISITE], i)
1202 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, !force, force, NULL)) < 0 && r != -EBADR)
1204 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_CONFLICTS], i)
1205 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, dep, ret, true, force, NULL)) < 0 && r != -EBADR)
1208 } else if (type == JOB_STOP || type == JOB_RESTART || type == JOB_TRY_RESTART) {
1210 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRED_BY], i)
1211 if ((r = transaction_add_job_and_dependencies(m, type, dep, ret, true, force, NULL)) < 0 && r != -EBADR)
1215 /* JOB_VERIFY_STARTED, JOB_RELOAD require no dependency handling */
1227 int manager_add_job(Manager *m, JobType type, Unit *unit, JobMode mode, bool force, Job **_ret) {
1232 assert(type < _JOB_TYPE_MAX);
1234 assert(mode < _JOB_MODE_MAX);
1236 log_debug("Trying to enqueue job %s/%s", unit_id(unit), job_type_to_string(type));
1238 if ((r = transaction_add_job_and_dependencies(m, type, unit, NULL, true, force, &ret)) < 0) {
1239 transaction_abort(m);
1243 if ((r = transaction_activate(m, mode)) < 0)
1246 log_debug("Enqueued job %s/%s as %u", unit_id(unit), job_type_to_string(type), (unsigned) ret->id);
1254 Job *manager_get_job(Manager *m, uint32_t id) {
1257 return hashmap_get(m->jobs, UINT32_TO_PTR(id));
1260 Unit *manager_get_unit(Manager *m, const char *name) {
1264 return hashmap_get(m->units, name);
1267 unsigned manager_dispatch_load_queue(Manager *m) {
1273 /* Make sure we are not run recursively */
1274 if (m->dispatching_load_queue)
1277 m->dispatching_load_queue = true;
1279 /* Dispatches the load queue. Takes a unit from the queue and
1280 * tries to load its data until the queue is empty */
1282 while ((meta = m->load_queue)) {
1283 assert(meta->in_load_queue);
1285 unit_load(UNIT(meta));
1289 m->dispatching_load_queue = false;
1293 int manager_load_unit(Manager *m, const char *path, Unit **_ret) {
1302 /* This will load the service information files, but not actually
1303 * start any services or anything. */
1305 name = file_name_from_path(path);
1307 if ((ret = manager_get_unit(m, name))) {
1312 if (!(ret = unit_new(m)))
1315 if (is_path(path)) {
1316 if (!(ret->meta.fragment_path = strdup(path))) {
1322 if ((r = unit_add_name(ret, name)) < 0) {
1327 unit_add_to_load_queue(ret);
1328 unit_add_to_dbus_queue(ret);
1330 manager_dispatch_load_queue(m);
1332 *_ret = unit_follow_merge(ret);
1336 void manager_dump_jobs(Manager *s, FILE *f, const char *prefix) {
1343 HASHMAP_FOREACH(j, s->jobs, i)
1344 job_dump(j, f, prefix);
1347 void manager_dump_units(Manager *s, FILE *f, const char *prefix) {
1355 HASHMAP_FOREACH_KEY(u, t, s->units, i)
1356 if (unit_id(u) == t)
1357 unit_dump(u, f, prefix);
1360 void manager_clear_jobs(Manager *m) {
1365 transaction_abort(m);
1367 while ((j = hashmap_first(m->jobs)))
1371 unsigned manager_dispatch_run_queue(Manager *m) {
1375 if (m->dispatching_run_queue)
1378 m->dispatching_run_queue = true;
1380 while ((j = m->run_queue)) {
1381 assert(j->installed);
1382 assert(j->in_run_queue);
1384 job_run_and_invalidate(j);
1388 m->dispatching_run_queue = false;
1392 unsigned manager_dispatch_dbus_queue(Manager *m) {
1399 if (m->dispatching_dbus_queue)
1402 m->dispatching_dbus_queue = true;
1404 while ((meta = m->dbus_unit_queue)) {
1405 assert(meta->in_dbus_queue);
1407 bus_unit_send_change_signal(UNIT(meta));
1411 while ((j = m->dbus_job_queue)) {
1412 assert(j->in_dbus_queue);
1414 bus_job_send_change_signal(j);
1418 m->dispatching_dbus_queue = false;
1422 static int manager_dispatch_sigchld(Manager *m) {
1430 if (waitid(P_ALL, 0, &si, WEXITED|WNOHANG) < 0) {
1432 if (errno == ECHILD)
1441 if (si.si_code != CLD_EXITED && si.si_code != CLD_KILLED && si.si_code != CLD_DUMPED)
1444 log_debug("child %llu died (code=%s, status=%i)", (long long unsigned) si.si_pid, sigchld_code_to_string(si.si_code), si.si_status);
1446 if (!(u = hashmap_remove(m->watch_pids, UINT32_TO_PTR(si.si_pid))))
1449 log_debug("child %llu belongs to %s", (long long unsigned) si.si_pid, unit_id(u));
1451 UNIT_VTABLE(u)->sigchld_event(u, si.si_pid, si.si_code, si.si_status);
1457 static int manager_process_signal_fd(Manager *m, bool *quit) {
1459 struct signalfd_siginfo sfsi;
1460 bool sigchld = false;
1465 if ((n = read(m->signal_watch.fd, &sfsi, sizeof(sfsi))) != sizeof(sfsi)) {
1470 if (errno == EAGAIN)
1476 switch (sfsi.ssi_signo) {
1481 get_process_name(sfsi.ssi_pid, &name);
1482 log_debug("Got SIGCHLD for process %llu (%s)", (unsigned long long) sfsi.ssi_pid, strna(name));
1492 if (m->running_as != MANAGER_INIT) {
1500 if ((r = manager_load_unit(m, SPECIAL_CTRL_ALT_DEL_TARGET, &target)) < 0)
1501 log_error("Failed to load ctrl-alt-del target: %s", strerror(-r));
1502 else if ((r = manager_add_job(m, JOB_START, target, JOB_REPLACE, true, NULL)) < 0)
1503 log_error("Failed to enqueue ctrl-alt-del job: %s", strerror(-r));
1510 if (m->running_as == MANAGER_INIT) {
1514 if ((r = manager_load_unit(m, SPECIAL_KBREQUEST_TARGET, &target)) < 0)
1515 log_error("Failed to load kbrequest target: %s", strerror(-r));
1516 else if ((r = manager_add_job(m, JOB_START, target, JOB_REPLACE, true, NULL)) < 0)
1517 log_error("Failed to enqueue kbrequest job: %s", strerror(-r));
1522 /* This is a nop on non-init systemd's */
1528 printf("→ By units:\n");
1529 manager_dump_units(m, stdout, "\t");
1531 printf("→ By jobs:\n");
1532 manager_dump_jobs(m, stdout, "\t");
1537 log_info("Got unhandled signal <%s>.", strsignal(sfsi.ssi_signo));
1542 return manager_dispatch_sigchld(m);
1547 static int process_event(Manager *m, struct epoll_event *ev, bool *quit) {
1554 assert(w = ev->data.ptr);
1560 /* An incoming signal? */
1561 if (ev->events != EPOLLIN)
1564 if ((r = manager_process_signal_fd(m, quit)) < 0)
1571 /* Some fd event, to be dispatched to the units */
1572 UNIT_VTABLE(w->data.unit)->fd_event(w->data.unit, w->fd, ev->events, w);
1579 /* Some timer event, to be dispatched to the units */
1580 if ((k = read(w->fd, &v, sizeof(v))) != sizeof(v)) {
1582 if (k < 0 && (errno == EINTR || errno == EAGAIN))
1585 return k < 0 ? -errno : -EIO;
1588 UNIT_VTABLE(w->data.unit)->timer_event(w->data.unit, v, w);
1593 /* Some mount table change, intended for the mount subsystem */
1594 mount_fd_event(m, ev->events);
1598 /* Some notification from udev, intended for the device subsystem */
1599 device_fd_event(m, ev->events);
1602 case WATCH_DBUS_WATCH:
1603 bus_watch_event(m, w, ev->events);
1606 case WATCH_DBUS_TIMEOUT:
1607 bus_timeout_event(m, w, ev->events);
1611 assert_not_reached("Unknown epoll event type.");
1617 int manager_loop(Manager *m) {
1621 RATELIMIT_DEFINE(rl, 1*USEC_PER_SEC, 1000);
1626 struct epoll_event event;
1629 if (!ratelimit_test(&rl)) {
1630 /* Yay, something is going seriously wrong, pause a little */
1631 log_warning("Looping too fast. Throttling execution a little.");
1635 if (manager_dispatch_cleanup_queue(m) > 0)
1638 if (manager_dispatch_load_queue(m) > 0)
1641 if (manager_dispatch_run_queue(m) > 0)
1644 if (bus_dispatch(m) > 0)
1647 if (manager_dispatch_dbus_queue(m) > 0)
1650 if ((n = epoll_wait(m->epoll_fd, &event, 1, -1)) < 0) {
1652 if (errno == -EINTR)
1660 if ((r = process_event(m, &event, &quit)) < 0)
1667 int manager_get_unit_from_dbus_path(Manager *m, const char *s, Unit **_u) {
1675 if (!startswith(s, "/org/freedesktop/systemd1/unit/"))
1678 if (!(n = bus_path_unescape(s+31)))
1681 u = manager_get_unit(m, n);
1692 int manager_get_job_from_dbus_path(Manager *m, const char *s, Job **_j) {
1701 if (!startswith(s, "/org/freedesktop/systemd1/job/"))
1704 if ((r = safe_atou(s + 30, &id)) < 0)
1707 if (!(j = manager_get_job(m, id)))
1715 static bool manager_utmp_good(Manager *m) {
1720 if ((r = mount_path_is_mounted(m, _PATH_UTMPX)) <= 0) {
1723 log_warning("Failed to determine whether " _PATH_UTMPX " is mounted: %s", strerror(-r));
1731 void manager_write_utmp_reboot(Manager *m) {
1736 if (m->utmp_reboot_written)
1739 if (m->running_as != MANAGER_INIT)
1742 if (!manager_utmp_good(m))
1745 if ((r = utmp_put_reboot(m->boot_timestamp)) < 0) {
1747 if (r != -ENOENT && r != -EROFS)
1748 log_warning("Failed to write utmp/wtmp: %s", strerror(-r));
1753 m->utmp_reboot_written = true;
1756 void manager_write_utmp_runlevel(Manager *m, Unit *u) {
1762 if (u->meta.type != UNIT_TARGET)
1765 if (m->running_as != MANAGER_INIT)
1768 if (!manager_utmp_good(m))
1771 if ((runlevel = target_get_runlevel(TARGET(u))) <= 0)
1774 if ((r = utmp_put_runlevel(0, runlevel, 0)) < 0) {
1776 if (r != -ENOENT && r != -EROFS)
1777 log_warning("Failed to write utmp/wtmp: %s", strerror(-r));
1781 static const char* const manager_running_as_table[_MANAGER_RUNNING_AS_MAX] = {
1782 [MANAGER_INIT] = "init",
1783 [MANAGER_SYSTEM] = "system",
1784 [MANAGER_SESSION] = "session"
1787 DEFINE_STRING_TABLE_LOOKUP(manager_running_as, ManagerRunningAs);