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>
45 #include "ratelimit.h"
47 #include "mount-setup.h"
48 #include "utmp-wtmp.h"
49 #include "unit-name.h"
50 #include "dbus-unit.h"
53 static int enable_special_signals(Manager
*m
) {
58 /* Enable that we get SIGINT on control-alt-del */
59 if (reboot(RB_DISABLE_CAD
) < 0)
60 log_warning("Failed to enable ctrl-alt-del handling: %m");
62 if ((fd
= open_terminal("/dev/tty0", O_RDWR
)) < 0)
63 log_warning("Failed to open /dev/tty0: %m");
65 /* Enable that we get SIGWINCH on kbrequest */
66 if (ioctl(fd
, KDSIGACCEPT
, SIGWINCH
) < 0)
67 log_warning("Failed to enable kbrequest handling: %s", strerror(errno
));
69 close_nointr_nofail(fd
);
75 static int manager_setup_signals(Manager
*m
) {
77 struct epoll_event ev
;
82 /* We are not interested in SIGSTOP and friends. */
84 sa
.sa_handler
= SIG_DFL
;
85 sa
.sa_flags
= SA_NOCLDSTOP
|SA_RESTART
;
86 assert_se(sigaction(SIGCHLD
, &sa
, NULL
) == 0);
88 assert_se(sigemptyset(&mask
) == 0);
89 assert_se(sigaddset(&mask
, SIGCHLD
) == 0);
90 assert_se(sigaddset(&mask
, SIGTERM
) == 0);
91 assert_se(sigaddset(&mask
, SIGHUP
) == 0);
92 assert_se(sigaddset(&mask
, SIGUSR1
) == 0);
93 assert_se(sigaddset(&mask
, SIGUSR2
) == 0);
94 assert_se(sigaddset(&mask
, SIGINT
) == 0); /* Kernel sends us this on control-alt-del */
95 assert_se(sigaddset(&mask
, SIGWINCH
) == 0); /* Kernel sends us this on kbrequest (alt-arrowup) */
96 assert_se(sigaddset(&mask
, SIGPWR
) == 0); /* Some kernel drivers and upsd send us this on power failure */
97 assert_se(sigprocmask(SIG_SETMASK
, &mask
, NULL
) == 0);
99 m
->signal_watch
.type
= WATCH_SIGNAL
;
100 if ((m
->signal_watch
.fd
= signalfd(-1, &mask
, SFD_NONBLOCK
|SFD_CLOEXEC
)) < 0)
105 ev
.data
.ptr
= &m
->signal_watch
;
107 if (epoll_ctl(m
->epoll_fd
, EPOLL_CTL_ADD
, m
->signal_watch
.fd
, &ev
) < 0)
110 if (m
->running_as
== MANAGER_INIT
)
111 return enable_special_signals(m
);
116 static char** session_dirs(void) {
117 const char *home
, *e
;
118 char *config_home
= NULL
, *data_home
= NULL
;
119 char **config_dirs
= NULL
, **data_dirs
= NULL
;
120 char **r
= NULL
, **t
;
122 /* Implement the mechanisms defined in
124 * http://standards.freedesktop.org/basedir-spec/basedir-spec-0.6.html
126 * We look in both the config and the data dirs because we
127 * want to encourage that distributors ship their unit files
128 * as data, and allow overriding as configuration.
131 home
= getenv("HOME");
133 if ((e
= getenv("XDG_CONFIG_HOME"))) {
134 if (asprintf(&config_home
, "%s/systemd/session", e
) < 0)
138 if (asprintf(&config_home
, "%s/.config/systemd/session", home
) < 0)
142 if ((e
= getenv("XDG_CONFIG_DIRS")))
143 config_dirs
= strv_split(e
, ":");
145 config_dirs
= strv_new("/etc/xdg", NULL
);
150 if ((e
= getenv("XDG_DATA_HOME"))) {
151 if (asprintf(&data_home
, "%s/systemd/session", e
) < 0)
155 if (asprintf(&data_home
, "%s/.local/share/systemd/session", home
) < 0)
159 if ((e
= getenv("XDG_DATA_DIRS")))
160 data_dirs
= strv_split(e
, ":");
162 data_dirs
= strv_new("/usr/local/share", "/usr/share", NULL
);
167 /* Now merge everything we found. */
169 if (!(t
= strv_append(r
, config_home
)))
175 if (!(t
= strv_merge_concat(r
, config_dirs
, "/systemd/session")))
180 if (!(t
= strv_append(r
, SESSION_CONFIG_UNIT_PATH
)))
186 if (!(t
= strv_append(r
, data_home
)))
192 if (!(t
= strv_merge_concat(r
, data_dirs
, "/systemd/session")))
197 if (!(t
= strv_append(r
, SESSION_DATA_UNIT_PATH
)))
202 if (!strv_path_make_absolute_cwd(r
))
207 strv_free(config_dirs
);
209 strv_free(data_dirs
);
219 static int manager_find_paths(Manager
*m
) {
225 /* First priority is whatever has been passed to us via env
227 if ((e
= getenv("SYSTEMD_UNIT_PATH")))
228 if (!(m
->unit_path
= split_path_and_make_absolute(e
)))
231 if (strv_isempty(m
->unit_path
)) {
233 /* Nothing is set, so let's figure something out. */
234 strv_free(m
->unit_path
);
236 if (m
->running_as
== MANAGER_SESSION
) {
237 if (!(m
->unit_path
= session_dirs()))
240 if (!(m
->unit_path
= strv_new(
241 SYSTEM_CONFIG_UNIT_PATH
, /* /etc/systemd/system/ */
242 SYSTEM_DATA_UNIT_PATH
, /* /lib/systemd/system/ */
247 if (m
->running_as
== MANAGER_INIT
) {
248 /* /etc/init.d/ compativility does not matter to users */
250 if ((e
= getenv("SYSTEMD_SYSVINIT_PATH")))
251 if (!(m
->sysvinit_path
= split_path_and_make_absolute(e
)))
254 if (strv_isempty(m
->sysvinit_path
)) {
255 strv_free(m
->sysvinit_path
);
257 if (!(m
->sysvinit_path
= strv_new(
258 SYSTEM_SYSVINIT_PATH
, /* /etc/init.d/ */
263 if ((e
= getenv("SYSTEMD_SYSVRCND_PATH")))
264 if (!(m
->sysvrcnd_path
= split_path_and_make_absolute(e
)))
267 if (strv_isempty(m
->sysvrcnd_path
)) {
268 strv_free(m
->sysvrcnd_path
);
270 if (!(m
->sysvrcnd_path
= strv_new(
271 SYSTEM_SYSVRCND_PATH
, /* /etc/rcN.d/ */
277 strv_uniq(m
->unit_path
);
278 strv_uniq(m
->sysvinit_path
);
279 strv_uniq(m
->sysvrcnd_path
);
281 assert(!strv_isempty(m
->unit_path
));
282 if (!(t
= strv_join(m
->unit_path
, "\n\t")))
284 log_debug("Looking for unit files in:\n\t%s", t
);
287 if (!strv_isempty(m
->sysvinit_path
)) {
289 if (!(t
= strv_join(m
->sysvinit_path
, "\n\t")))
292 log_debug("Looking for SysV init scripts in:\n\t%s", t
);
295 log_debug("Ignoring SysV init scripts.");
297 if (!strv_isempty(m
->sysvrcnd_path
)) {
299 if (!(t
= strv_join(m
->sysvrcnd_path
, "\n\t")))
302 log_debug("Looking for SysV rcN.d links in:\n\t%s", t
);
305 log_debug("Ignoring SysV rcN.d links.");
310 int manager_new(ManagerRunningAs running_as
, bool confirm_spawn
, Manager
**_m
) {
315 assert(running_as
>= 0);
316 assert(running_as
< _MANAGER_RUNNING_AS_MAX
);
318 if (!(m
= new0(Manager
, 1)))
321 m
->boot_timestamp
= now(CLOCK_REALTIME
);
323 m
->running_as
= running_as
;
324 m
->confirm_spawn
= confirm_spawn
;
325 m
->name_data_slot
= -1;
327 m
->signal_watch
.fd
= m
->mount_watch
.fd
= m
->udev_watch
.fd
= m
->epoll_fd
= m
->dev_autofs_fd
= -1;
328 m
->current_job_id
= 1; /* start as id #1, so that we can leave #0 around as "null-like" value */
330 if (!(m
->units
= hashmap_new(string_hash_func
, string_compare_func
)))
333 if (!(m
->jobs
= hashmap_new(trivial_hash_func
, trivial_compare_func
)))
336 if (!(m
->transaction_jobs
= hashmap_new(trivial_hash_func
, trivial_compare_func
)))
339 if (!(m
->watch_pids
= hashmap_new(trivial_hash_func
, trivial_compare_func
)))
342 if (!(m
->cgroup_bondings
= hashmap_new(string_hash_func
, string_compare_func
)))
345 if (!(m
->watch_bus
= hashmap_new(string_hash_func
, string_compare_func
)))
348 if ((m
->epoll_fd
= epoll_create1(EPOLL_CLOEXEC
)) < 0)
351 if ((r
= manager_find_paths(m
)) < 0)
354 if ((r
= manager_setup_signals(m
)) < 0)
357 if ((r
= manager_setup_cgroup(m
)) < 0)
360 /* Try to connect to the busses, if possible. */
361 if ((r
= bus_init_system(m
)) < 0 ||
362 (r
= bus_init_api(m
)) < 0)
373 static unsigned manager_dispatch_cleanup_queue(Manager
*m
) {
379 while ((meta
= m
->cleanup_queue
)) {
380 assert(meta
->in_cleanup_queue
);
382 unit_free(UNIT(meta
));
389 void manager_free(Manager
*m
) {
396 while ((j
= hashmap_first(m
->transaction_jobs
)))
399 while ((u
= hashmap_first(m
->units
)))
402 manager_dispatch_cleanup_queue(m
);
404 for (c
= 0; c
< _UNIT_TYPE_MAX
; c
++)
405 if (unit_vtable
[c
]->shutdown
)
406 unit_vtable
[c
]->shutdown(m
);
408 manager_shutdown_cgroup(m
);
413 hashmap_free(m
->units
);
414 hashmap_free(m
->jobs
);
415 hashmap_free(m
->transaction_jobs
);
416 hashmap_free(m
->watch_pids
);
417 hashmap_free(m
->watch_bus
);
419 if (m
->epoll_fd
>= 0)
420 close_nointr(m
->epoll_fd
);
421 if (m
->signal_watch
.fd
>= 0)
422 close_nointr(m
->signal_watch
.fd
);
424 strv_free(m
->unit_path
);
425 strv_free(m
->sysvinit_path
);
426 strv_free(m
->sysvrcnd_path
);
428 free(m
->cgroup_controller
);
429 free(m
->cgroup_hierarchy
);
431 assert(hashmap_isempty(m
->cgroup_bondings
));
432 hashmap_free(m
->cgroup_bondings
);
437 int manager_coldplug(Manager
*m
) {
446 /* First, let's ask every type to load all units from
447 * disk/kernel that it might know */
448 for (c
= 0; c
< _UNIT_TYPE_MAX
; c
++)
449 if (unit_vtable
[c
]->enumerate
)
450 if ((r
= unit_vtable
[c
]->enumerate(m
)) < 0)
453 manager_dispatch_load_queue(m
);
455 /* Then, let's set up their initial state. */
456 HASHMAP_FOREACH_KEY(u
, k
, m
->units
, i
) {
462 if (UNIT_VTABLE(u
)->coldplug
)
463 if ((r
= UNIT_VTABLE(u
)->coldplug(u
)) < 0)
467 /* Now that the initial devices are available, let's see if we
468 * can write the utmp file */
469 manager_write_utmp_reboot(m
);
474 static void transaction_delete_job(Manager
*m
, Job
*j
, bool delete_dependencies
) {
478 /* Deletes one job from the transaction */
480 manager_transaction_unlink_job(m
, j
, delete_dependencies
);
486 static void transaction_delete_unit(Manager
*m
, Unit
*u
) {
489 /* Deletes all jobs associated with a certain unit from the
492 while ((j
= hashmap_get(m
->transaction_jobs
, u
)))
493 transaction_delete_job(m
, j
, true);
496 static void transaction_clean_dependencies(Manager
*m
) {
502 /* Drops all dependencies of all installed jobs */
504 HASHMAP_FOREACH(j
, m
->jobs
, i
) {
505 while (j
->subject_list
)
506 job_dependency_free(j
->subject_list
);
507 while (j
->object_list
)
508 job_dependency_free(j
->object_list
);
511 assert(!m
->transaction_anchor
);
514 static void transaction_abort(Manager
*m
) {
519 while ((j
= hashmap_first(m
->transaction_jobs
)))
521 transaction_delete_job(m
, j
, true);
525 assert(hashmap_isempty(m
->transaction_jobs
));
527 transaction_clean_dependencies(m
);
530 static void transaction_find_jobs_that_matter_to_anchor(Manager
*m
, Job
*j
, unsigned generation
) {
535 /* A recursive sweep through the graph that marks all units
536 * that matter to the anchor job, i.e. are directly or
537 * indirectly a dependency of the anchor job via paths that
538 * are fully marked as mattering. */
543 l
= m
->transaction_anchor
;
545 LIST_FOREACH(subject
, l
, l
) {
547 /* This link does not matter */
551 /* This unit has already been marked */
552 if (l
->object
->generation
== generation
)
555 l
->object
->matters_to_anchor
= true;
556 l
->object
->generation
= generation
;
558 transaction_find_jobs_that_matter_to_anchor(m
, l
->object
, generation
);
562 static void transaction_merge_and_delete_job(Manager
*m
, Job
*j
, Job
*other
, JobType t
) {
563 JobDependency
*l
, *last
;
567 assert(j
->unit
== other
->unit
);
568 assert(!j
->installed
);
570 /* Merges 'other' into 'j' and then deletes j. */
573 j
->state
= JOB_WAITING
;
574 j
->override
= j
->override
|| other
->override
;
576 j
->matters_to_anchor
= j
->matters_to_anchor
|| other
->matters_to_anchor
;
578 /* Patch us in as new owner of the JobDependency objects */
580 LIST_FOREACH(subject
, l
, other
->subject_list
) {
581 assert(l
->subject
== other
);
586 /* Merge both lists */
588 last
->subject_next
= j
->subject_list
;
590 j
->subject_list
->subject_prev
= last
;
591 j
->subject_list
= other
->subject_list
;
594 /* Patch us in as new owner of the JobDependency objects */
596 LIST_FOREACH(object
, l
, other
->object_list
) {
597 assert(l
->object
== other
);
602 /* Merge both lists */
604 last
->object_next
= j
->object_list
;
606 j
->object_list
->object_prev
= last
;
607 j
->object_list
= other
->object_list
;
610 /* Kill the other job */
611 other
->subject_list
= NULL
;
612 other
->object_list
= NULL
;
613 transaction_delete_job(m
, other
, true);
616 static int delete_one_unmergeable_job(Manager
*m
, Job
*j
) {
621 /* Tries to delete one item in the linked list
622 * j->transaction_next->transaction_next->... that conflicts
623 * whith another one, in an attempt to make an inconsistent
624 * transaction work. */
626 /* We rely here on the fact that if a merged with b does not
627 * merge with c, either a or b merge with c neither */
628 LIST_FOREACH(transaction
, j
, j
)
629 LIST_FOREACH(transaction
, k
, j
->transaction_next
) {
632 /* Is this one mergeable? Then skip it */
633 if (job_type_is_mergeable(j
->type
, k
->type
))
636 /* Ok, we found two that conflict, let's see if we can
637 * drop one of them */
638 if (!j
->matters_to_anchor
)
640 else if (!k
->matters_to_anchor
)
645 /* Ok, we can drop one, so let's do so. */
646 log_debug("Trying to fix job merging by deleting job %s/%s", d
->unit
->meta
.id
, job_type_to_string(d
->type
));
647 transaction_delete_job(m
, d
, true);
654 static int transaction_merge_jobs(Manager
*m
) {
661 /* First step, check whether any of the jobs for one specific
662 * task conflict. If so, try to drop one of them. */
663 HASHMAP_FOREACH(j
, m
->transaction_jobs
, i
) {
668 LIST_FOREACH(transaction
, k
, j
->transaction_next
) {
669 if ((r
= job_type_merge(&t
, k
->type
)) >= 0)
672 /* OK, we could not merge all jobs for this
673 * action. Let's see if we can get rid of one
676 if ((r
= delete_one_unmergeable_job(m
, j
)) >= 0)
677 /* Ok, we managed to drop one, now
678 * let's ask our callers to call us
679 * again after garbage collecting */
682 /* We couldn't merge anything. Failure */
687 /* Second step, merge the jobs. */
688 HASHMAP_FOREACH(j
, m
->transaction_jobs
, i
) {
692 /* Merge all transactions */
693 LIST_FOREACH(transaction
, k
, j
->transaction_next
)
694 assert_se(job_type_merge(&t
, k
->type
) == 0);
696 /* If an active job is mergeable, merge it too */
697 if (j
->unit
->meta
.job
)
698 job_type_merge(&t
, j
->unit
->meta
.job
->type
); /* Might fail. Which is OK */
700 while ((k
= j
->transaction_next
)) {
702 transaction_merge_and_delete_job(m
, k
, j
, t
);
705 transaction_merge_and_delete_job(m
, j
, k
, t
);
708 assert(!j
->transaction_next
);
709 assert(!j
->transaction_prev
);
715 static void transaction_drop_redundant(Manager
*m
) {
720 /* Goes through the transaction and removes all jobs that are
729 HASHMAP_FOREACH(j
, m
->transaction_jobs
, i
) {
730 bool changes_something
= false;
733 LIST_FOREACH(transaction
, k
, j
) {
735 if (!job_is_anchor(k
) &&
736 job_type_is_redundant(k
->type
, unit_active_state(k
->unit
)))
739 changes_something
= true;
743 if (changes_something
)
746 log_debug("Found redundant job %s/%s, dropping.", j
->unit
->meta
.id
, job_type_to_string(j
->type
));
747 transaction_delete_job(m
, j
, false);
755 static bool unit_matters_to_anchor(Unit
*u
, Job
*j
) {
757 assert(!j
->transaction_prev
);
759 /* Checks whether at least one of the jobs for this unit
760 * matters to the anchor. */
762 LIST_FOREACH(transaction
, j
, j
)
763 if (j
->matters_to_anchor
)
769 static int transaction_verify_order_one(Manager
*m
, Job
*j
, Job
*from
, unsigned generation
) {
776 assert(!j
->transaction_prev
);
778 /* Does a recursive sweep through the ordering graph, looking
779 * for a cycle. If we find cycle we try to break it. */
781 /* Did we find a cycle? */
782 if (j
->marker
&& j
->generation
== generation
) {
785 /* So, we already have been here. We have a
786 * cycle. Let's try to break it. We go backwards in
787 * our path and try to find a suitable job to
788 * remove. We use the marker to find our way back,
789 * since smart how we are we stored our way back in
792 log_debug("Found ordering cycle on %s/%s", j
->unit
->meta
.id
, job_type_to_string(j
->type
));
794 for (k
= from
; k
; k
= (k
->generation
== generation
? k
->marker
: NULL
)) {
796 log_debug("Walked on cycle path to %s/%s", k
->unit
->meta
.id
, job_type_to_string(k
->type
));
799 !unit_matters_to_anchor(k
->unit
, k
)) {
800 /* Ok, we can drop this one, so let's
802 log_debug("Breaking order cycle by deleting job %s/%s", k
->unit
->meta
.id
, job_type_to_string(k
->type
));
803 transaction_delete_unit(m
, k
->unit
);
807 /* Check if this in fact was the beginning of
813 log_debug("Unable to break cycle");
818 /* Make the marker point to where we come from, so that we can
819 * find our way backwards if we want to break a cycle */
821 j
->generation
= generation
;
823 /* We assume that the the dependencies are bidirectional, and
824 * hence can ignore UNIT_AFTER */
825 SET_FOREACH(u
, j
->unit
->meta
.dependencies
[UNIT_BEFORE
], i
) {
828 /* Is there a job for this unit? */
829 if (!(o
= hashmap_get(m
->transaction_jobs
, u
)))
831 /* Ok, there is no job for this in the
832 * transaction, but maybe there is already one
834 if (!(o
= u
->meta
.job
))
837 if ((r
= transaction_verify_order_one(m
, o
, j
, generation
)) < 0)
841 /* Ok, let's backtrack, and remember that this entry is not on
842 * our path anymore. */
848 static int transaction_verify_order(Manager
*m
, unsigned *generation
) {
856 /* Check if the ordering graph is cyclic. If it is, try to fix
857 * that up by dropping one of the jobs. */
859 HASHMAP_FOREACH(j
, m
->transaction_jobs
, i
)
860 if ((r
= transaction_verify_order_one(m
, j
, NULL
, (*generation
)++)) < 0)
866 static void transaction_collect_garbage(Manager
*m
) {
871 /* Drop jobs that are not required by any other job */
879 HASHMAP_FOREACH(j
, m
->transaction_jobs
, i
) {
883 log_debug("Garbage collecting job %s/%s", j
->unit
->meta
.id
, job_type_to_string(j
->type
));
884 transaction_delete_job(m
, j
, true);
892 static int transaction_is_destructive(Manager
*m
, JobMode mode
) {
898 /* Checks whether applying this transaction means that
899 * existing jobs would be replaced */
901 HASHMAP_FOREACH(j
, m
->transaction_jobs
, i
) {
904 assert(!j
->transaction_prev
);
905 assert(!j
->transaction_next
);
907 if (j
->unit
->meta
.job
&&
908 j
->unit
->meta
.job
!= j
&&
909 !job_type_is_superset(j
->type
, j
->unit
->meta
.job
->type
))
916 static void transaction_minimize_impact(Manager
*m
) {
920 /* Drops all unnecessary jobs that reverse already active jobs
921 * or that stop a running service. */
929 HASHMAP_FOREACH(j
, m
->transaction_jobs
, i
) {
930 LIST_FOREACH(transaction
, j
, j
) {
931 bool stops_running_service
, changes_existing_job
;
933 /* If it matters, we shouldn't drop it */
934 if (j
->matters_to_anchor
)
937 /* Would this stop a running service?
938 * Would this change an existing job?
939 * If so, let's drop this entry */
941 stops_running_service
=
942 j
->type
== JOB_STOP
&& UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(j
->unit
));
944 changes_existing_job
=
945 j
->unit
->meta
.job
&& job_type_is_conflicting(j
->type
, j
->unit
->meta
.job
->state
);
947 if (!stops_running_service
&& !changes_existing_job
)
950 if (stops_running_service
)
951 log_debug("%s/%s would stop a running service.", j
->unit
->meta
.id
, job_type_to_string(j
->type
));
953 if (changes_existing_job
)
954 log_debug("%s/%s would change existing job.", j
->unit
->meta
.id
, job_type_to_string(j
->type
));
956 /* Ok, let's get rid of this */
957 log_debug("Deleting %s/%s to minimize impact.", j
->unit
->meta
.id
, job_type_to_string(j
->type
));
959 transaction_delete_job(m
, j
, true);
971 static int transaction_apply(Manager
*m
, JobMode mode
) {
976 /* Moves the transaction jobs to the set of active jobs */
978 HASHMAP_FOREACH(j
, m
->transaction_jobs
, i
) {
980 assert(!j
->transaction_prev
);
981 assert(!j
->transaction_next
);
986 if ((r
= hashmap_put(m
->jobs
, UINT32_TO_PTR(j
->id
), j
)) < 0)
990 while ((j
= hashmap_steal_first(m
->transaction_jobs
))) {
994 if (j
->unit
->meta
.job
)
995 job_free(j
->unit
->meta
.job
);
997 j
->unit
->meta
.job
= j
;
1000 /* We're fully installed. Now let's free data we don't
1003 assert(!j
->transaction_next
);
1004 assert(!j
->transaction_prev
);
1006 job_add_to_run_queue(j
);
1007 job_add_to_dbus_queue(j
);
1010 /* As last step, kill all remaining job dependencies. */
1011 transaction_clean_dependencies(m
);
1017 HASHMAP_FOREACH(j
, m
->transaction_jobs
, i
) {
1021 hashmap_remove(m
->jobs
, UINT32_TO_PTR(j
->id
));
1027 static int transaction_activate(Manager
*m
, JobMode mode
) {
1029 unsigned generation
= 1;
1033 /* This applies the changes recorded in transaction_jobs to
1034 * the actual list of jobs, if possible. */
1036 /* First step: figure out which jobs matter */
1037 transaction_find_jobs_that_matter_to_anchor(m
, NULL
, generation
++);
1039 /* Second step: Try not to stop any running services if
1040 * we don't have to. Don't try to reverse running
1041 * jobs if we don't have to. */
1042 transaction_minimize_impact(m
);
1044 /* Third step: Drop redundant jobs */
1045 transaction_drop_redundant(m
);
1048 /* Fourth step: Let's remove unneeded jobs that might
1050 transaction_collect_garbage(m
);
1052 /* Fifth step: verify order makes sense and correct
1053 * cycles if necessary and possible */
1054 if ((r
= transaction_verify_order(m
, &generation
)) >= 0)
1058 log_debug("Requested transaction contains an unfixable cyclic ordering dependency: %s", strerror(-r
));
1062 /* Let's see if the resulting transaction ordering
1063 * graph is still cyclic... */
1067 /* Sixth step: let's drop unmergeable entries if
1068 * necessary and possible, merge entries we can
1070 if ((r
= transaction_merge_jobs(m
)) >= 0)
1074 log_debug("Requested transaction contains unmergable jobs: %s", strerror(-r
));
1078 /* Seventh step: an entry got dropped, let's garbage
1079 * collect its dependencies. */
1080 transaction_collect_garbage(m
);
1082 /* Let's see if the resulting transaction still has
1083 * unmergeable entries ... */
1086 /* Eights step: Drop redundant jobs again, if the merging now allows us to drop more. */
1087 transaction_drop_redundant(m
);
1089 /* Ninth step: check whether we can actually apply this */
1090 if (mode
== JOB_FAIL
)
1091 if ((r
= transaction_is_destructive(m
, mode
)) < 0) {
1092 log_debug("Requested transaction contradicts existing jobs: %s", strerror(-r
));
1096 /* Tenth step: apply changes */
1097 if ((r
= transaction_apply(m
, mode
)) < 0) {
1098 log_debug("Failed to apply transaction: %s", strerror(-r
));
1102 assert(hashmap_isempty(m
->transaction_jobs
));
1103 assert(!m
->transaction_anchor
);
1108 transaction_abort(m
);
1112 static Job
* transaction_add_one_job(Manager
*m
, JobType type
, Unit
*unit
, bool override
, bool *is_new
) {
1119 /* Looks for an axisting prospective job and returns that. If
1120 * it doesn't exist it is created and added to the prospective
1123 f
= hashmap_get(m
->transaction_jobs
, unit
);
1125 LIST_FOREACH(transaction
, j
, f
) {
1126 assert(j
->unit
== unit
);
1128 if (j
->type
== type
) {
1135 if (unit
->meta
.job
&& unit
->meta
.job
->type
== type
)
1137 else if (!(j
= job_new(m
, type
, unit
)))
1142 j
->matters_to_anchor
= false;
1143 j
->override
= override
;
1145 LIST_PREPEND(Job
, transaction
, f
, j
);
1147 if ((r
= hashmap_replace(m
->transaction_jobs
, unit
, f
)) < 0) {
1155 log_debug("Added job %s/%s to transaction.", unit
->meta
.id
, job_type_to_string(type
));
1160 void manager_transaction_unlink_job(Manager
*m
, Job
*j
, bool delete_dependencies
) {
1164 if (j
->transaction_prev
)
1165 j
->transaction_prev
->transaction_next
= j
->transaction_next
;
1166 else if (j
->transaction_next
)
1167 hashmap_replace(m
->transaction_jobs
, j
->unit
, j
->transaction_next
);
1169 hashmap_remove_value(m
->transaction_jobs
, j
->unit
, j
);
1171 if (j
->transaction_next
)
1172 j
->transaction_next
->transaction_prev
= j
->transaction_prev
;
1174 j
->transaction_prev
= j
->transaction_next
= NULL
;
1176 while (j
->subject_list
)
1177 job_dependency_free(j
->subject_list
);
1179 while (j
->object_list
) {
1180 Job
*other
= j
->object_list
->matters
? j
->object_list
->subject
: NULL
;
1182 job_dependency_free(j
->object_list
);
1184 if (other
&& delete_dependencies
) {
1185 log_debug("Deleting job %s/%s as dependency of job %s/%s",
1186 other
->unit
->meta
.id
, job_type_to_string(other
->type
),
1187 j
->unit
->meta
.id
, job_type_to_string(j
->type
));
1188 transaction_delete_job(m
, other
, delete_dependencies
);
1193 static int transaction_add_job_and_dependencies(
1208 assert(type
< _JOB_TYPE_MAX
);
1211 if (unit
->meta
.load_state
!= UNIT_LOADED
)
1214 if (!unit_job_is_applicable(unit
, type
))
1217 /* First add the job. */
1218 if (!(ret
= transaction_add_one_job(m
, type
, unit
, override
, &is_new
)))
1221 /* Then, add a link to the job. */
1222 if (!job_dependency_new(by
, ret
, matters
))
1226 /* Finally, recursively add in all dependencies. */
1227 if (type
== JOB_START
|| type
== JOB_RELOAD_OR_START
) {
1228 SET_FOREACH(dep
, ret
->unit
->meta
.dependencies
[UNIT_REQUIRES
], i
)
1229 if ((r
= transaction_add_job_and_dependencies(m
, JOB_START
, dep
, ret
, true, override
, NULL
)) < 0 && r
!= -EBADR
)
1232 SET_FOREACH(dep
, ret
->unit
->meta
.dependencies
[UNIT_REQUIRES_OVERRIDABLE
], i
)
1233 if ((r
= transaction_add_job_and_dependencies(m
, JOB_START
, dep
, ret
, !override
, override
, NULL
)) < 0 && r
!= -EBADR
)
1234 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep
->meta
.id
, strerror(-r
));
1236 SET_FOREACH(dep
, ret
->unit
->meta
.dependencies
[UNIT_WANTS
], i
)
1237 if ((r
= transaction_add_job_and_dependencies(m
, JOB_START
, dep
, ret
, false, false, NULL
)) < 0)
1238 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep
->meta
.id
, strerror(-r
));
1240 SET_FOREACH(dep
, ret
->unit
->meta
.dependencies
[UNIT_REQUISITE
], i
)
1241 if ((r
= transaction_add_job_and_dependencies(m
, JOB_VERIFY_ACTIVE
, dep
, ret
, true, override
, NULL
)) < 0 && r
!= -EBADR
)
1244 SET_FOREACH(dep
, ret
->unit
->meta
.dependencies
[UNIT_REQUISITE_OVERRIDABLE
], i
)
1245 if ((r
= transaction_add_job_and_dependencies(m
, JOB_VERIFY_ACTIVE
, dep
, ret
, !override
, override
, NULL
)) < 0 && r
!= -EBADR
)
1246 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep
->meta
.id
, strerror(-r
));
1248 SET_FOREACH(dep
, ret
->unit
->meta
.dependencies
[UNIT_CONFLICTS
], i
)
1249 if ((r
= transaction_add_job_and_dependencies(m
, JOB_STOP
, dep
, ret
, true, override
, NULL
)) < 0 && r
!= -EBADR
)
1252 } else if (type
== JOB_STOP
|| type
== JOB_RESTART
|| type
== JOB_TRY_RESTART
) {
1254 SET_FOREACH(dep
, ret
->unit
->meta
.dependencies
[UNIT_REQUIRED_BY
], i
)
1255 if ((r
= transaction_add_job_and_dependencies(m
, type
, dep
, ret
, true, override
, NULL
)) < 0 && r
!= -EBADR
)
1259 /* JOB_VERIFY_STARTED, JOB_RELOAD require no dependency handling */
1271 int manager_add_job(Manager
*m
, JobType type
, Unit
*unit
, JobMode mode
, bool override
, Job
**_ret
) {
1276 assert(type
< _JOB_TYPE_MAX
);
1278 assert(mode
< _JOB_MODE_MAX
);
1280 log_debug("Trying to enqueue job %s/%s", unit
->meta
.id
, job_type_to_string(type
));
1282 if ((r
= transaction_add_job_and_dependencies(m
, type
, unit
, NULL
, true, override
, &ret
)) < 0) {
1283 transaction_abort(m
);
1287 if ((r
= transaction_activate(m
, mode
)) < 0)
1290 log_debug("Enqueued job %s/%s as %u", unit
->meta
.id
, job_type_to_string(type
), (unsigned) ret
->id
);
1298 int manager_add_job_by_name(Manager
*m
, JobType type
, const char *name
, JobMode mode
, bool override
, Job
**_ret
) {
1303 assert(type
< _JOB_TYPE_MAX
);
1305 assert(mode
< _JOB_MODE_MAX
);
1307 if ((r
= manager_load_unit(m
, name
, NULL
, &unit
)) < 0)
1310 return manager_add_job(m
, type
, unit
, mode
, override
, _ret
);
1313 Job
*manager_get_job(Manager
*m
, uint32_t id
) {
1316 return hashmap_get(m
->jobs
, UINT32_TO_PTR(id
));
1319 Unit
*manager_get_unit(Manager
*m
, const char *name
) {
1323 return hashmap_get(m
->units
, name
);
1326 unsigned manager_dispatch_load_queue(Manager
*m
) {
1332 /* Make sure we are not run recursively */
1333 if (m
->dispatching_load_queue
)
1336 m
->dispatching_load_queue
= true;
1338 /* Dispatches the load queue. Takes a unit from the queue and
1339 * tries to load its data until the queue is empty */
1341 while ((meta
= m
->load_queue
)) {
1342 assert(meta
->in_load_queue
);
1344 unit_load(UNIT(meta
));
1348 m
->dispatching_load_queue
= false;
1352 int manager_load_unit(Manager
*m
, const char *name
, const char *path
, Unit
**_ret
) {
1357 assert(name
|| path
);
1359 /* This will load the service information files, but not actually
1360 * start any services or anything. */
1362 if (path
&& !is_path(path
))
1366 name
= file_name_from_path(path
);
1368 if (!unit_name_is_valid(name
))
1371 if ((ret
= manager_get_unit(m
, name
))) {
1376 if (!(ret
= unit_new(m
)))
1380 if (!(ret
->meta
.fragment_path
= strdup(path
))) {
1385 if ((r
= unit_add_name(ret
, name
)) < 0) {
1390 unit_add_to_load_queue(ret
);
1391 unit_add_to_dbus_queue(ret
);
1393 manager_dispatch_load_queue(m
);
1396 *_ret
= unit_follow_merge(ret
);
1401 void manager_dump_jobs(Manager
*s
, FILE *f
, const char *prefix
) {
1408 HASHMAP_FOREACH(j
, s
->jobs
, i
)
1409 job_dump(j
, f
, prefix
);
1412 void manager_dump_units(Manager
*s
, FILE *f
, const char *prefix
) {
1420 HASHMAP_FOREACH_KEY(u
, t
, s
->units
, i
)
1421 if (u
->meta
.id
== t
)
1422 unit_dump(u
, f
, prefix
);
1425 void manager_clear_jobs(Manager
*m
) {
1430 transaction_abort(m
);
1432 while ((j
= hashmap_first(m
->jobs
)))
1436 unsigned manager_dispatch_run_queue(Manager
*m
) {
1440 if (m
->dispatching_run_queue
)
1443 m
->dispatching_run_queue
= true;
1445 while ((j
= m
->run_queue
)) {
1446 assert(j
->installed
);
1447 assert(j
->in_run_queue
);
1449 job_run_and_invalidate(j
);
1453 m
->dispatching_run_queue
= false;
1457 unsigned manager_dispatch_dbus_queue(Manager
*m
) {
1464 if (m
->dispatching_dbus_queue
)
1467 m
->dispatching_dbus_queue
= true;
1469 while ((meta
= m
->dbus_unit_queue
)) {
1470 assert(meta
->in_dbus_queue
);
1472 bus_unit_send_change_signal(UNIT(meta
));
1476 while ((j
= m
->dbus_job_queue
)) {
1477 assert(j
->in_dbus_queue
);
1479 bus_job_send_change_signal(j
);
1483 m
->dispatching_dbus_queue
= false;
1487 static int manager_dispatch_sigchld(Manager
*m
) {
1496 /* First we call waitd() for a PID and do not reap the
1497 * zombie. That way we can still access /proc/$PID for
1498 * it while it is a zombie. */
1499 if (waitid(P_ALL
, 0, &si
, WEXITED
|WNOHANG
|WNOWAIT
) < 0) {
1501 if (errno
== ECHILD
)
1513 if (si
.si_code
== CLD_EXITED
|| si
.si_code
== CLD_KILLED
|| si
.si_code
== CLD_DUMPED
) {
1516 get_process_name(si
.si_pid
, &name
);
1517 log_debug("Got SIGCHLD for process %llu (%s)", (unsigned long long) si
.si_pid
, strna(name
));
1521 /* And now, we actually reap the zombie. */
1522 if (waitid(P_PID
, si
.si_pid
, &si
, WEXITED
) < 0) {
1529 if (si
.si_code
!= CLD_EXITED
&& si
.si_code
!= CLD_KILLED
&& si
.si_code
!= CLD_DUMPED
)
1532 log_debug("Child %llu died (code=%s, status=%i/%s)",
1533 (long long unsigned) si
.si_pid
,
1534 sigchld_code_to_string(si
.si_code
),
1536 strna(si
.si_code
== CLD_EXITED
? exit_status_to_string(si
.si_status
) : strsignal(si
.si_status
)));
1538 if (!(u
= hashmap_remove(m
->watch_pids
, UINT32_TO_PTR(si
.si_pid
))))
1541 log_debug("Child %llu belongs to %s", (long long unsigned) si
.si_pid
, u
->meta
.id
);
1543 UNIT_VTABLE(u
)->sigchld_event(u
, si
.si_pid
, si
.si_code
, si
.si_status
);
1549 static void manager_start_target(Manager
*m
, const char *name
) {
1552 if ((r
= manager_add_job_by_name(m
, JOB_START
, name
, JOB_REPLACE
, true, NULL
)) < 0)
1553 log_error("Failed to enqueue %s job: %s", name
, strerror(-r
));
1556 static int manager_process_signal_fd(Manager
*m
, bool *quit
) {
1558 struct signalfd_siginfo sfsi
;
1559 bool sigchld
= false;
1564 if ((n
= read(m
->signal_watch
.fd
, &sfsi
, sizeof(sfsi
))) != sizeof(sfsi
)) {
1569 if (errno
== EAGAIN
)
1575 switch (sfsi
.ssi_signo
) {
1584 if (m
->running_as
== MANAGER_INIT
) {
1585 manager_start_target(m
, SPECIAL_CTRL_ALT_DEL_TARGET
);
1594 if (m
->running_as
== MANAGER_INIT
)
1595 manager_start_target(m
, SPECIAL_KBREQUEST_TARGET
);
1597 /* This is a nop on non-init */
1601 if (m
->running_as
== MANAGER_INIT
)
1602 manager_start_target(m
, SPECIAL_SIGPWR_TARGET
);
1604 /* This is a nop on non-init */
1608 manager_dump_units(m
, stdout
, "\t");
1609 manager_dump_jobs(m
, stdout
, "\t");
1615 u
= manager_get_unit(m
, SPECIAL_DBUS_SERVICE
);
1617 if (!u
|| UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u
))) {
1618 log_info("Trying to reconnect to bus...");
1623 if (!u
|| !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u
))) {
1624 log_info("Loading D-Bus service...");
1625 manager_start_target(m
, SPECIAL_DBUS_SERVICE
);
1632 log_info("Got unhandled signal <%s>.", strsignal(sfsi
.ssi_signo
));
1637 return manager_dispatch_sigchld(m
);
1642 static int process_event(Manager
*m
, struct epoll_event
*ev
, bool *quit
) {
1649 assert(w
= ev
->data
.ptr
);
1655 /* An incoming signal? */
1656 if (ev
->events
!= EPOLLIN
)
1659 if ((r
= manager_process_signal_fd(m
, quit
)) < 0)
1666 /* Some fd event, to be dispatched to the units */
1667 UNIT_VTABLE(w
->data
.unit
)->fd_event(w
->data
.unit
, w
->fd
, ev
->events
, w
);
1674 /* Some timer event, to be dispatched to the units */
1675 if ((k
= read(w
->fd
, &v
, sizeof(v
))) != sizeof(v
)) {
1677 if (k
< 0 && (errno
== EINTR
|| errno
== EAGAIN
))
1680 return k
< 0 ? -errno
: -EIO
;
1683 UNIT_VTABLE(w
->data
.unit
)->timer_event(w
->data
.unit
, v
, w
);
1688 /* Some mount table change, intended for the mount subsystem */
1689 mount_fd_event(m
, ev
->events
);
1693 /* Some notification from udev, intended for the device subsystem */
1694 device_fd_event(m
, ev
->events
);
1697 case WATCH_DBUS_WATCH
:
1698 bus_watch_event(m
, w
, ev
->events
);
1701 case WATCH_DBUS_TIMEOUT
:
1702 bus_timeout_event(m
, w
, ev
->events
);
1706 assert_not_reached("Unknown epoll event type.");
1712 int manager_loop(Manager
*m
) {
1716 RATELIMIT_DEFINE(rl
, 1*USEC_PER_SEC
, 1000);
1721 struct epoll_event event
;
1724 if (!ratelimit_test(&rl
)) {
1725 /* Yay, something is going seriously wrong, pause a little */
1726 log_warning("Looping too fast. Throttling execution a little.");
1730 if (manager_dispatch_cleanup_queue(m
) > 0)
1733 if (manager_dispatch_load_queue(m
) > 0)
1736 if (manager_dispatch_run_queue(m
) > 0)
1739 if (bus_dispatch(m
) > 0)
1742 if (manager_dispatch_dbus_queue(m
) > 0)
1745 if ((n
= epoll_wait(m
->epoll_fd
, &event
, 1, -1)) < 0) {
1747 if (errno
== -EINTR
)
1755 if ((r
= process_event(m
, &event
, &quit
)) < 0)
1762 int manager_get_unit_from_dbus_path(Manager
*m
, const char *s
, Unit
**_u
) {
1770 if (!startswith(s
, "/org/freedesktop/systemd1/unit/"))
1773 if (!(n
= bus_path_unescape(s
+31)))
1776 u
= manager_get_unit(m
, n
);
1787 int manager_get_job_from_dbus_path(Manager
*m
, const char *s
, Job
**_j
) {
1796 if (!startswith(s
, "/org/freedesktop/systemd1/job/"))
1799 if ((r
= safe_atou(s
+ 30, &id
)) < 0)
1802 if (!(j
= manager_get_job(m
, id
)))
1810 static bool manager_utmp_good(Manager
*m
) {
1815 if ((r
= mount_path_is_mounted(m
, _PATH_UTMPX
)) <= 0) {
1818 log_warning("Failed to determine whether " _PATH_UTMPX
" is mounted: %s", strerror(-r
));
1826 void manager_write_utmp_reboot(Manager
*m
) {
1831 if (m
->utmp_reboot_written
)
1834 if (m
->running_as
!= MANAGER_INIT
)
1837 if (!manager_utmp_good(m
))
1840 if ((r
= utmp_put_reboot(m
->boot_timestamp
)) < 0) {
1842 if (r
!= -ENOENT
&& r
!= -EROFS
)
1843 log_warning("Failed to write utmp/wtmp: %s", strerror(-r
));
1848 m
->utmp_reboot_written
= true;
1851 void manager_write_utmp_runlevel(Manager
*m
, Unit
*u
) {
1857 if (u
->meta
.type
!= UNIT_TARGET
)
1860 if (m
->running_as
!= MANAGER_INIT
)
1863 if (!manager_utmp_good(m
))
1866 if ((runlevel
= target_get_runlevel(TARGET(u
))) <= 0)
1869 if ((r
= utmp_put_runlevel(0, runlevel
, 0)) < 0) {
1871 if (r
!= -ENOENT
&& r
!= -EROFS
)
1872 log_warning("Failed to write utmp/wtmp: %s", strerror(-r
));
1876 void manager_dispatch_bus_name_owner_changed(
1879 const char* old_owner
,
1880 const char *new_owner
) {
1887 if (!(u
= hashmap_get(m
->watch_bus
, name
)))
1890 UNIT_VTABLE(u
)->bus_name_owner_change(u
, name
, old_owner
, new_owner
);
1893 void manager_dispatch_bus_query_pid_done(
1904 if (!(u
= hashmap_get(m
->watch_bus
, name
)))
1907 UNIT_VTABLE(u
)->bus_query_pid_done(u
, name
, pid
);
1910 static const char* const manager_running_as_table
[_MANAGER_RUNNING_AS_MAX
] = {
1911 [MANAGER_INIT
] = "init",
1912 [MANAGER_SYSTEM
] = "system",
1913 [MANAGER_SESSION
] = "session"
1916 DEFINE_STRING_TABLE_LOOKUP(manager_running_as
, ManagerRunningAs
);