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 static int enable_special_signals(Manager
*m
) {
60 /* Enable that we get SIGINT on control-alt-del */
61 if (reboot(RB_DISABLE_CAD
) < 0)
62 log_warning("Failed to enable ctrl-alt-del handling: %m");
64 if ((fd
= open_terminal("/dev/tty0", O_RDWR
)) < 0)
65 log_warning("Failed to open /dev/tty0: %m");
67 /* Enable that we get SIGWINCH on kbrequest */
68 if (ioctl(fd
, KDSIGACCEPT
, SIGWINCH
) < 0)
69 log_warning("Failed to enable kbrequest handling: %s", strerror(errno
));
71 close_nointr_nofail(fd
);
77 static int manager_setup_signals(Manager
*m
) {
79 struct epoll_event ev
;
84 /* We are not interested in SIGSTOP and friends. */
86 sa
.sa_handler
= SIG_DFL
;
87 sa
.sa_flags
= SA_NOCLDSTOP
|SA_RESTART
;
88 assert_se(sigaction(SIGCHLD
, &sa
, NULL
) == 0);
90 assert_se(sigemptyset(&mask
) == 0);
91 assert_se(sigaddset(&mask
, SIGCHLD
) == 0);
92 assert_se(sigaddset(&mask
, SIGTERM
) == 0);
93 assert_se(sigaddset(&mask
, SIGHUP
) == 0);
94 assert_se(sigaddset(&mask
, SIGUSR1
) == 0);
95 assert_se(sigaddset(&mask
, SIGUSR2
) == 0);
96 assert_se(sigaddset(&mask
, SIGINT
) == 0); /* Kernel sends us this on control-alt-del */
97 assert_se(sigaddset(&mask
, SIGWINCH
) == 0); /* Kernel sends us this on kbrequest (alt-arrowup) */
98 assert_se(sigaddset(&mask
, SIGPWR
) == 0); /* Some kernel drivers and upsd send us this on power failure */
99 assert_se(sigprocmask(SIG_SETMASK
, &mask
, NULL
) == 0);
101 m
->signal_watch
.type
= WATCH_SIGNAL
;
102 if ((m
->signal_watch
.fd
= signalfd(-1, &mask
, SFD_NONBLOCK
|SFD_CLOEXEC
)) < 0)
107 ev
.data
.ptr
= &m
->signal_watch
;
109 if (epoll_ctl(m
->epoll_fd
, EPOLL_CTL_ADD
, m
->signal_watch
.fd
, &ev
) < 0)
112 if (m
->running_as
== MANAGER_INIT
)
113 return enable_special_signals(m
);
118 static char** session_dirs(void) {
119 const char *home
, *e
;
120 char *config_home
= NULL
, *data_home
= NULL
;
121 char **config_dirs
= NULL
, **data_dirs
= NULL
;
122 char **r
= NULL
, **t
;
124 /* Implement the mechanisms defined in
126 * http://standards.freedesktop.org/basedir-spec/basedir-spec-0.6.html
128 * We look in both the config and the data dirs because we
129 * want to encourage that distributors ship their unit files
130 * as data, and allow overriding as configuration.
133 home
= getenv("HOME");
135 if ((e
= getenv("XDG_CONFIG_HOME"))) {
136 if (asprintf(&config_home
, "%s/systemd/session", e
) < 0)
140 if (asprintf(&config_home
, "%s/.config/systemd/session", home
) < 0)
144 if ((e
= getenv("XDG_CONFIG_DIRS")))
145 config_dirs
= strv_split(e
, ":");
147 config_dirs
= strv_new("/etc/xdg", NULL
);
152 if ((e
= getenv("XDG_DATA_HOME"))) {
153 if (asprintf(&data_home
, "%s/systemd/session", e
) < 0)
157 if (asprintf(&data_home
, "%s/.local/share/systemd/session", home
) < 0)
161 if ((e
= getenv("XDG_DATA_DIRS")))
162 data_dirs
= strv_split(e
, ":");
164 data_dirs
= strv_new("/usr/local/share", "/usr/share", NULL
);
169 /* Now merge everything we found. */
171 if (!(t
= strv_append(r
, config_home
)))
177 if (!(t
= strv_merge_concat(r
, config_dirs
, "/systemd/session")))
182 if (!(t
= strv_append(r
, SESSION_CONFIG_UNIT_PATH
)))
188 if (!(t
= strv_append(r
, data_home
)))
194 if (!(t
= strv_merge_concat(r
, data_dirs
, "/systemd/session")))
199 if (!(t
= strv_append(r
, SESSION_DATA_UNIT_PATH
)))
204 if (!strv_path_make_absolute_cwd(r
))
209 strv_free(config_dirs
);
211 strv_free(data_dirs
);
221 static int manager_find_paths(Manager
*m
) {
227 /* First priority is whatever has been passed to us via env
229 if ((e
= getenv("SYSTEMD_UNIT_PATH")))
230 if (!(m
->unit_path
= split_path_and_make_absolute(e
)))
233 if (strv_isempty(m
->unit_path
)) {
235 /* Nothing is set, so let's figure something out. */
236 strv_free(m
->unit_path
);
238 if (m
->running_as
== MANAGER_SESSION
) {
239 if (!(m
->unit_path
= session_dirs()))
242 if (!(m
->unit_path
= strv_new(
243 SYSTEM_CONFIG_UNIT_PATH
, /* /etc/systemd/system/ */
244 SYSTEM_DATA_UNIT_PATH
, /* /lib/systemd/system/ */
249 if (m
->running_as
== MANAGER_INIT
) {
250 /* /etc/init.d/ compativility does not matter to users */
252 if ((e
= getenv("SYSTEMD_SYSVINIT_PATH")))
253 if (!(m
->sysvinit_path
= split_path_and_make_absolute(e
)))
256 if (strv_isempty(m
->sysvinit_path
)) {
257 strv_free(m
->sysvinit_path
);
259 if (!(m
->sysvinit_path
= strv_new(
260 SYSTEM_SYSVINIT_PATH
, /* /etc/init.d/ */
265 if ((e
= getenv("SYSTEMD_SYSVRCND_PATH")))
266 if (!(m
->sysvrcnd_path
= split_path_and_make_absolute(e
)))
269 if (strv_isempty(m
->sysvrcnd_path
)) {
270 strv_free(m
->sysvrcnd_path
);
272 if (!(m
->sysvrcnd_path
= strv_new(
273 SYSTEM_SYSVRCND_PATH
, /* /etc/rcN.d/ */
279 strv_uniq(m
->unit_path
);
280 strv_uniq(m
->sysvinit_path
);
281 strv_uniq(m
->sysvrcnd_path
);
283 assert(!strv_isempty(m
->unit_path
));
284 if (!(t
= strv_join(m
->unit_path
, "\n\t")))
286 log_debug("Looking for unit files in:\n\t%s", t
);
289 if (!strv_isempty(m
->sysvinit_path
)) {
291 if (!(t
= strv_join(m
->sysvinit_path
, "\n\t")))
294 log_debug("Looking for SysV init scripts in:\n\t%s", t
);
297 log_debug("Ignoring SysV init scripts.");
299 if (!strv_isempty(m
->sysvrcnd_path
)) {
301 if (!(t
= strv_join(m
->sysvrcnd_path
, "\n\t")))
304 log_debug("Looking for SysV rcN.d links in:\n\t%s", t
);
307 log_debug("Ignoring SysV rcN.d links.");
312 int manager_new(ManagerRunningAs running_as
, bool confirm_spawn
, Manager
**_m
) {
317 assert(running_as
>= 0);
318 assert(running_as
< _MANAGER_RUNNING_AS_MAX
);
320 if (!(m
= new0(Manager
, 1)))
323 m
->boot_timestamp
= now(CLOCK_REALTIME
);
325 m
->running_as
= running_as
;
326 m
->confirm_spawn
= confirm_spawn
;
327 m
->name_data_slot
= -1;
328 m
->exit_code
= _MANAGER_EXIT_CODE_INVALID
;
330 m
->signal_watch
.fd
= m
->mount_watch
.fd
= m
->udev_watch
.fd
= m
->epoll_fd
= m
->dev_autofs_fd
= -1;
331 m
->current_job_id
= 1; /* start as id #1, so that we can leave #0 around as "null-like" value */
333 if (!(m
->units
= hashmap_new(string_hash_func
, string_compare_func
)))
336 if (!(m
->jobs
= hashmap_new(trivial_hash_func
, trivial_compare_func
)))
339 if (!(m
->transaction_jobs
= hashmap_new(trivial_hash_func
, trivial_compare_func
)))
342 if (!(m
->watch_pids
= hashmap_new(trivial_hash_func
, trivial_compare_func
)))
345 if (!(m
->cgroup_bondings
= hashmap_new(string_hash_func
, string_compare_func
)))
348 if (!(m
->watch_bus
= hashmap_new(string_hash_func
, string_compare_func
)))
351 if ((m
->epoll_fd
= epoll_create1(EPOLL_CLOEXEC
)) < 0)
354 if ((r
= manager_find_paths(m
)) < 0)
357 if ((r
= manager_setup_signals(m
)) < 0)
360 if ((r
= manager_setup_cgroup(m
)) < 0)
363 /* Try to connect to the busses, if possible. */
364 if ((r
= bus_init_system(m
)) < 0 ||
365 (r
= bus_init_api(m
)) < 0)
376 static unsigned manager_dispatch_cleanup_queue(Manager
*m
) {
382 while ((meta
= m
->cleanup_queue
)) {
383 assert(meta
->in_cleanup_queue
);
385 unit_free(UNIT(meta
));
392 static void manager_clear_jobs_and_units(Manager
*m
) {
398 while ((j
= hashmap_first(m
->transaction_jobs
)))
401 while ((u
= hashmap_first(m
->units
)))
405 void manager_free(Manager
*m
) {
410 manager_clear_jobs_and_units(m
);
412 for (c
= 0; c
< _UNIT_TYPE_MAX
; c
++)
413 if (unit_vtable
[c
]->shutdown
)
414 unit_vtable
[c
]->shutdown(m
);
416 /* If we reexecute ourselves, we keep the root cgroup
418 manager_shutdown_cgroup(m
, m
->exit_code
!= MANAGER_REEXECUTE
);
423 hashmap_free(m
->units
);
424 hashmap_free(m
->jobs
);
425 hashmap_free(m
->transaction_jobs
);
426 hashmap_free(m
->watch_pids
);
427 hashmap_free(m
->watch_bus
);
429 if (m
->epoll_fd
>= 0)
430 close_nointr_nofail(m
->epoll_fd
);
431 if (m
->signal_watch
.fd
>= 0)
432 close_nointr_nofail(m
->signal_watch
.fd
);
434 strv_free(m
->unit_path
);
435 strv_free(m
->sysvinit_path
);
436 strv_free(m
->sysvrcnd_path
);
438 free(m
->cgroup_controller
);
439 free(m
->cgroup_hierarchy
);
441 hashmap_free(m
->cgroup_bondings
);
446 int manager_enumerate(Manager
*m
) {
452 /* Let's ask every type to load all units from disk/kernel
453 * that it might know */
454 for (c
= 0; c
< _UNIT_TYPE_MAX
; c
++)
455 if (unit_vtable
[c
]->enumerate
)
456 if ((q
= unit_vtable
[c
]->enumerate(m
)) < 0)
459 manager_dispatch_load_queue(m
);
463 int manager_coldplug(Manager
*m
) {
471 /* Then, let's set up their initial state. */
472 HASHMAP_FOREACH_KEY(u
, k
, m
->units
, i
) {
478 if (UNIT_VTABLE(u
)->coldplug
)
479 if ((q
= UNIT_VTABLE(u
)->coldplug(u
)) < 0)
486 int manager_startup(Manager
*m
, FILE *serialization
, FDSet
*fds
) {
491 /* First, enumerate what we can from all config files */
492 r
= manager_enumerate(m
);
494 /* Second, deserialize if there is something to deserialize */
496 if ((q
= manager_deserialize(m
, serialization
, fds
)) < 0)
499 /* Third, fire things up! */
500 if ((q
= manager_coldplug(m
)) < 0)
503 /* Now that the initial devices are available, let's see if we
504 * can write the utmp file */
505 manager_write_utmp_reboot(m
);
510 static void transaction_delete_job(Manager
*m
, Job
*j
, bool delete_dependencies
) {
514 /* Deletes one job from the transaction */
516 manager_transaction_unlink_job(m
, j
, delete_dependencies
);
522 static void transaction_delete_unit(Manager
*m
, Unit
*u
) {
525 /* Deletes all jobs associated with a certain unit from the
528 while ((j
= hashmap_get(m
->transaction_jobs
, u
)))
529 transaction_delete_job(m
, j
, true);
532 static void transaction_clean_dependencies(Manager
*m
) {
538 /* Drops all dependencies of all installed jobs */
540 HASHMAP_FOREACH(j
, m
->jobs
, i
) {
541 while (j
->subject_list
)
542 job_dependency_free(j
->subject_list
);
543 while (j
->object_list
)
544 job_dependency_free(j
->object_list
);
547 assert(!m
->transaction_anchor
);
550 static void transaction_abort(Manager
*m
) {
555 while ((j
= hashmap_first(m
->transaction_jobs
)))
557 transaction_delete_job(m
, j
, true);
561 assert(hashmap_isempty(m
->transaction_jobs
));
563 transaction_clean_dependencies(m
);
566 static void transaction_find_jobs_that_matter_to_anchor(Manager
*m
, Job
*j
, unsigned generation
) {
571 /* A recursive sweep through the graph that marks all units
572 * that matter to the anchor job, i.e. are directly or
573 * indirectly a dependency of the anchor job via paths that
574 * are fully marked as mattering. */
579 l
= m
->transaction_anchor
;
581 LIST_FOREACH(subject
, l
, l
) {
583 /* This link does not matter */
587 /* This unit has already been marked */
588 if (l
->object
->generation
== generation
)
591 l
->object
->matters_to_anchor
= true;
592 l
->object
->generation
= generation
;
594 transaction_find_jobs_that_matter_to_anchor(m
, l
->object
, generation
);
598 static void transaction_merge_and_delete_job(Manager
*m
, Job
*j
, Job
*other
, JobType t
) {
599 JobDependency
*l
, *last
;
603 assert(j
->unit
== other
->unit
);
604 assert(!j
->installed
);
606 /* Merges 'other' into 'j' and then deletes j. */
609 j
->state
= JOB_WAITING
;
610 j
->override
= j
->override
|| other
->override
;
612 j
->matters_to_anchor
= j
->matters_to_anchor
|| other
->matters_to_anchor
;
614 /* Patch us in as new owner of the JobDependency objects */
616 LIST_FOREACH(subject
, l
, other
->subject_list
) {
617 assert(l
->subject
== other
);
622 /* Merge both lists */
624 last
->subject_next
= j
->subject_list
;
626 j
->subject_list
->subject_prev
= last
;
627 j
->subject_list
= other
->subject_list
;
630 /* Patch us in as new owner of the JobDependency objects */
632 LIST_FOREACH(object
, l
, other
->object_list
) {
633 assert(l
->object
== other
);
638 /* Merge both lists */
640 last
->object_next
= j
->object_list
;
642 j
->object_list
->object_prev
= last
;
643 j
->object_list
= other
->object_list
;
646 /* Kill the other job */
647 other
->subject_list
= NULL
;
648 other
->object_list
= NULL
;
649 transaction_delete_job(m
, other
, true);
652 static int delete_one_unmergeable_job(Manager
*m
, Job
*j
) {
657 /* Tries to delete one item in the linked list
658 * j->transaction_next->transaction_next->... that conflicts
659 * whith another one, in an attempt to make an inconsistent
660 * transaction work. */
662 /* We rely here on the fact that if a merged with b does not
663 * merge with c, either a or b merge with c neither */
664 LIST_FOREACH(transaction
, j
, j
)
665 LIST_FOREACH(transaction
, k
, j
->transaction_next
) {
668 /* Is this one mergeable? Then skip it */
669 if (job_type_is_mergeable(j
->type
, k
->type
))
672 /* Ok, we found two that conflict, let's see if we can
673 * drop one of them */
674 if (!j
->matters_to_anchor
)
676 else if (!k
->matters_to_anchor
)
681 /* Ok, we can drop one, so let's do so. */
682 log_debug("Trying to fix job merging by deleting job %s/%s", d
->unit
->meta
.id
, job_type_to_string(d
->type
));
683 transaction_delete_job(m
, d
, true);
690 static int transaction_merge_jobs(Manager
*m
) {
697 /* First step, check whether any of the jobs for one specific
698 * task conflict. If so, try to drop one of them. */
699 HASHMAP_FOREACH(j
, m
->transaction_jobs
, i
) {
704 LIST_FOREACH(transaction
, k
, j
->transaction_next
) {
705 if ((r
= job_type_merge(&t
, k
->type
)) >= 0)
708 /* OK, we could not merge all jobs for this
709 * action. Let's see if we can get rid of one
712 if ((r
= delete_one_unmergeable_job(m
, j
)) >= 0)
713 /* Ok, we managed to drop one, now
714 * let's ask our callers to call us
715 * again after garbage collecting */
718 /* We couldn't merge anything. Failure */
723 /* Second step, merge the jobs. */
724 HASHMAP_FOREACH(j
, m
->transaction_jobs
, i
) {
728 /* Merge all transactions */
729 LIST_FOREACH(transaction
, k
, j
->transaction_next
)
730 assert_se(job_type_merge(&t
, k
->type
) == 0);
732 /* If an active job is mergeable, merge it too */
733 if (j
->unit
->meta
.job
)
734 job_type_merge(&t
, j
->unit
->meta
.job
->type
); /* Might fail. Which is OK */
736 while ((k
= j
->transaction_next
)) {
738 transaction_merge_and_delete_job(m
, k
, j
, t
);
741 transaction_merge_and_delete_job(m
, j
, k
, t
);
744 assert(!j
->transaction_next
);
745 assert(!j
->transaction_prev
);
751 static void transaction_drop_redundant(Manager
*m
) {
756 /* Goes through the transaction and removes all jobs that are
765 HASHMAP_FOREACH(j
, m
->transaction_jobs
, i
) {
766 bool changes_something
= false;
769 LIST_FOREACH(transaction
, k
, j
) {
771 if (!job_is_anchor(k
) &&
772 job_type_is_redundant(k
->type
, unit_active_state(k
->unit
)))
775 changes_something
= true;
779 if (changes_something
)
782 log_debug("Found redundant job %s/%s, dropping.", j
->unit
->meta
.id
, job_type_to_string(j
->type
));
783 transaction_delete_job(m
, j
, false);
791 static bool unit_matters_to_anchor(Unit
*u
, Job
*j
) {
793 assert(!j
->transaction_prev
);
795 /* Checks whether at least one of the jobs for this unit
796 * matters to the anchor. */
798 LIST_FOREACH(transaction
, j
, j
)
799 if (j
->matters_to_anchor
)
805 static int transaction_verify_order_one(Manager
*m
, Job
*j
, Job
*from
, unsigned generation
) {
812 assert(!j
->transaction_prev
);
814 /* Does a recursive sweep through the ordering graph, looking
815 * for a cycle. If we find cycle we try to break it. */
817 /* Did we find a cycle? */
818 if (j
->marker
&& j
->generation
== generation
) {
821 /* So, we already have been here. We have a
822 * cycle. Let's try to break it. We go backwards in
823 * our path and try to find a suitable job to
824 * remove. We use the marker to find our way back,
825 * since smart how we are we stored our way back in
828 log_debug("Found ordering cycle on %s/%s", j
->unit
->meta
.id
, job_type_to_string(j
->type
));
830 for (k
= from
; k
; k
= (k
->generation
== generation
? k
->marker
: NULL
)) {
832 log_debug("Walked on cycle path to %s/%s", k
->unit
->meta
.id
, job_type_to_string(k
->type
));
835 !unit_matters_to_anchor(k
->unit
, k
)) {
836 /* Ok, we can drop this one, so let's
838 log_debug("Breaking order cycle by deleting job %s/%s", k
->unit
->meta
.id
, job_type_to_string(k
->type
));
839 transaction_delete_unit(m
, k
->unit
);
843 /* Check if this in fact was the beginning of
849 log_debug("Unable to break cycle");
854 /* Make the marker point to where we come from, so that we can
855 * find our way backwards if we want to break a cycle */
857 j
->generation
= generation
;
859 /* We assume that the the dependencies are bidirectional, and
860 * hence can ignore UNIT_AFTER */
861 SET_FOREACH(u
, j
->unit
->meta
.dependencies
[UNIT_BEFORE
], i
) {
864 /* Is there a job for this unit? */
865 if (!(o
= hashmap_get(m
->transaction_jobs
, u
)))
867 /* Ok, there is no job for this in the
868 * transaction, but maybe there is already one
870 if (!(o
= u
->meta
.job
))
873 if ((r
= transaction_verify_order_one(m
, o
, j
, generation
)) < 0)
877 /* Ok, let's backtrack, and remember that this entry is not on
878 * our path anymore. */
884 static int transaction_verify_order(Manager
*m
, unsigned *generation
) {
892 /* Check if the ordering graph is cyclic. If it is, try to fix
893 * that up by dropping one of the jobs. */
895 HASHMAP_FOREACH(j
, m
->transaction_jobs
, i
)
896 if ((r
= transaction_verify_order_one(m
, j
, NULL
, (*generation
)++)) < 0)
902 static void transaction_collect_garbage(Manager
*m
) {
907 /* Drop jobs that are not required by any other job */
915 HASHMAP_FOREACH(j
, m
->transaction_jobs
, i
) {
919 log_debug("Garbage collecting job %s/%s", j
->unit
->meta
.id
, job_type_to_string(j
->type
));
920 transaction_delete_job(m
, j
, true);
928 static int transaction_is_destructive(Manager
*m
, JobMode mode
) {
934 /* Checks whether applying this transaction means that
935 * existing jobs would be replaced */
937 HASHMAP_FOREACH(j
, m
->transaction_jobs
, i
) {
940 assert(!j
->transaction_prev
);
941 assert(!j
->transaction_next
);
943 if (j
->unit
->meta
.job
&&
944 j
->unit
->meta
.job
!= j
&&
945 !job_type_is_superset(j
->type
, j
->unit
->meta
.job
->type
))
952 static void transaction_minimize_impact(Manager
*m
) {
956 /* Drops all unnecessary jobs that reverse already active jobs
957 * or that stop a running service. */
965 HASHMAP_FOREACH(j
, m
->transaction_jobs
, i
) {
966 LIST_FOREACH(transaction
, j
, j
) {
967 bool stops_running_service
, changes_existing_job
;
969 /* If it matters, we shouldn't drop it */
970 if (j
->matters_to_anchor
)
973 /* Would this stop a running service?
974 * Would this change an existing job?
975 * If so, let's drop this entry */
977 stops_running_service
=
978 j
->type
== JOB_STOP
&& UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(j
->unit
));
980 changes_existing_job
=
981 j
->unit
->meta
.job
&& job_type_is_conflicting(j
->type
, j
->unit
->meta
.job
->state
);
983 if (!stops_running_service
&& !changes_existing_job
)
986 if (stops_running_service
)
987 log_debug("%s/%s would stop a running service.", j
->unit
->meta
.id
, job_type_to_string(j
->type
));
989 if (changes_existing_job
)
990 log_debug("%s/%s would change existing job.", j
->unit
->meta
.id
, job_type_to_string(j
->type
));
992 /* Ok, let's get rid of this */
993 log_debug("Deleting %s/%s to minimize impact.", j
->unit
->meta
.id
, job_type_to_string(j
->type
));
995 transaction_delete_job(m
, j
, true);
1007 static int transaction_apply(Manager
*m
, JobMode mode
) {
1012 /* Moves the transaction jobs to the set of active jobs */
1014 HASHMAP_FOREACH(j
, m
->transaction_jobs
, i
) {
1016 assert(!j
->transaction_prev
);
1017 assert(!j
->transaction_next
);
1022 if ((r
= hashmap_put(m
->jobs
, UINT32_TO_PTR(j
->id
), j
)) < 0)
1026 while ((j
= hashmap_steal_first(m
->transaction_jobs
))) {
1030 if (j
->unit
->meta
.job
)
1031 job_free(j
->unit
->meta
.job
);
1033 j
->unit
->meta
.job
= j
;
1034 j
->installed
= true;
1036 /* We're fully installed. Now let's free data we don't
1039 assert(!j
->transaction_next
);
1040 assert(!j
->transaction_prev
);
1042 job_add_to_run_queue(j
);
1043 job_add_to_dbus_queue(j
);
1046 /* As last step, kill all remaining job dependencies. */
1047 transaction_clean_dependencies(m
);
1053 HASHMAP_FOREACH(j
, m
->transaction_jobs
, i
) {
1057 hashmap_remove(m
->jobs
, UINT32_TO_PTR(j
->id
));
1063 static int transaction_activate(Manager
*m
, JobMode mode
) {
1065 unsigned generation
= 1;
1069 /* This applies the changes recorded in transaction_jobs to
1070 * the actual list of jobs, if possible. */
1072 /* First step: figure out which jobs matter */
1073 transaction_find_jobs_that_matter_to_anchor(m
, NULL
, generation
++);
1075 /* Second step: Try not to stop any running services if
1076 * we don't have to. Don't try to reverse running
1077 * jobs if we don't have to. */
1078 transaction_minimize_impact(m
);
1080 /* Third step: Drop redundant jobs */
1081 transaction_drop_redundant(m
);
1084 /* Fourth step: Let's remove unneeded jobs that might
1086 transaction_collect_garbage(m
);
1088 /* Fifth step: verify order makes sense and correct
1089 * cycles if necessary and possible */
1090 if ((r
= transaction_verify_order(m
, &generation
)) >= 0)
1094 log_debug("Requested transaction contains an unfixable cyclic ordering dependency: %s", strerror(-r
));
1098 /* Let's see if the resulting transaction ordering
1099 * graph is still cyclic... */
1103 /* Sixth step: let's drop unmergeable entries if
1104 * necessary and possible, merge entries we can
1106 if ((r
= transaction_merge_jobs(m
)) >= 0)
1110 log_debug("Requested transaction contains unmergable jobs: %s", strerror(-r
));
1114 /* Seventh step: an entry got dropped, let's garbage
1115 * collect its dependencies. */
1116 transaction_collect_garbage(m
);
1118 /* Let's see if the resulting transaction still has
1119 * unmergeable entries ... */
1122 /* Eights step: Drop redundant jobs again, if the merging now allows us to drop more. */
1123 transaction_drop_redundant(m
);
1125 /* Ninth step: check whether we can actually apply this */
1126 if (mode
== JOB_FAIL
)
1127 if ((r
= transaction_is_destructive(m
, mode
)) < 0) {
1128 log_debug("Requested transaction contradicts existing jobs: %s", strerror(-r
));
1132 /* Tenth step: apply changes */
1133 if ((r
= transaction_apply(m
, mode
)) < 0) {
1134 log_debug("Failed to apply transaction: %s", strerror(-r
));
1138 assert(hashmap_isempty(m
->transaction_jobs
));
1139 assert(!m
->transaction_anchor
);
1144 transaction_abort(m
);
1148 static Job
* transaction_add_one_job(Manager
*m
, JobType type
, Unit
*unit
, bool override
, bool *is_new
) {
1155 /* Looks for an axisting prospective job and returns that. If
1156 * it doesn't exist it is created and added to the prospective
1159 f
= hashmap_get(m
->transaction_jobs
, unit
);
1161 LIST_FOREACH(transaction
, j
, f
) {
1162 assert(j
->unit
== unit
);
1164 if (j
->type
== type
) {
1171 if (unit
->meta
.job
&& unit
->meta
.job
->type
== type
)
1173 else if (!(j
= job_new(m
, type
, unit
)))
1178 j
->matters_to_anchor
= false;
1179 j
->override
= override
;
1181 LIST_PREPEND(Job
, transaction
, f
, j
);
1183 if ((r
= hashmap_replace(m
->transaction_jobs
, unit
, f
)) < 0) {
1191 log_debug("Added job %s/%s to transaction.", unit
->meta
.id
, job_type_to_string(type
));
1196 void manager_transaction_unlink_job(Manager
*m
, Job
*j
, bool delete_dependencies
) {
1200 if (j
->transaction_prev
)
1201 j
->transaction_prev
->transaction_next
= j
->transaction_next
;
1202 else if (j
->transaction_next
)
1203 hashmap_replace(m
->transaction_jobs
, j
->unit
, j
->transaction_next
);
1205 hashmap_remove_value(m
->transaction_jobs
, j
->unit
, j
);
1207 if (j
->transaction_next
)
1208 j
->transaction_next
->transaction_prev
= j
->transaction_prev
;
1210 j
->transaction_prev
= j
->transaction_next
= NULL
;
1212 while (j
->subject_list
)
1213 job_dependency_free(j
->subject_list
);
1215 while (j
->object_list
) {
1216 Job
*other
= j
->object_list
->matters
? j
->object_list
->subject
: NULL
;
1218 job_dependency_free(j
->object_list
);
1220 if (other
&& delete_dependencies
) {
1221 log_debug("Deleting job %s/%s as dependency of job %s/%s",
1222 other
->unit
->meta
.id
, job_type_to_string(other
->type
),
1223 j
->unit
->meta
.id
, job_type_to_string(j
->type
));
1224 transaction_delete_job(m
, other
, delete_dependencies
);
1229 static int transaction_add_job_and_dependencies(
1244 assert(type
< _JOB_TYPE_MAX
);
1247 if (unit
->meta
.load_state
!= UNIT_LOADED
)
1250 if (!unit_job_is_applicable(unit
, type
))
1253 /* First add the job. */
1254 if (!(ret
= transaction_add_one_job(m
, type
, unit
, override
, &is_new
)))
1257 /* Then, add a link to the job. */
1258 if (!job_dependency_new(by
, ret
, matters
))
1262 /* Finally, recursively add in all dependencies. */
1263 if (type
== JOB_START
|| type
== JOB_RELOAD_OR_START
) {
1264 SET_FOREACH(dep
, ret
->unit
->meta
.dependencies
[UNIT_REQUIRES
], i
)
1265 if ((r
= transaction_add_job_and_dependencies(m
, JOB_START
, dep
, ret
, true, override
, NULL
)) < 0 && r
!= -EBADR
)
1268 SET_FOREACH(dep
, ret
->unit
->meta
.dependencies
[UNIT_REQUIRES_OVERRIDABLE
], i
)
1269 if ((r
= transaction_add_job_and_dependencies(m
, JOB_START
, dep
, ret
, !override
, override
, NULL
)) < 0 && r
!= -EBADR
)
1270 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep
->meta
.id
, strerror(-r
));
1272 SET_FOREACH(dep
, ret
->unit
->meta
.dependencies
[UNIT_WANTS
], i
)
1273 if ((r
= transaction_add_job_and_dependencies(m
, JOB_START
, dep
, ret
, false, false, NULL
)) < 0)
1274 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep
->meta
.id
, strerror(-r
));
1276 SET_FOREACH(dep
, ret
->unit
->meta
.dependencies
[UNIT_REQUISITE
], i
)
1277 if ((r
= transaction_add_job_and_dependencies(m
, JOB_VERIFY_ACTIVE
, dep
, ret
, true, override
, NULL
)) < 0 && r
!= -EBADR
)
1280 SET_FOREACH(dep
, ret
->unit
->meta
.dependencies
[UNIT_REQUISITE_OVERRIDABLE
], i
)
1281 if ((r
= transaction_add_job_and_dependencies(m
, JOB_VERIFY_ACTIVE
, dep
, ret
, !override
, override
, NULL
)) < 0 && r
!= -EBADR
)
1282 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep
->meta
.id
, strerror(-r
));
1284 SET_FOREACH(dep
, ret
->unit
->meta
.dependencies
[UNIT_CONFLICTS
], i
)
1285 if ((r
= transaction_add_job_and_dependencies(m
, JOB_STOP
, dep
, ret
, true, override
, NULL
)) < 0 && r
!= -EBADR
)
1288 } else if (type
== JOB_STOP
|| type
== JOB_RESTART
|| type
== JOB_TRY_RESTART
) {
1290 SET_FOREACH(dep
, ret
->unit
->meta
.dependencies
[UNIT_REQUIRED_BY
], i
)
1291 if ((r
= transaction_add_job_and_dependencies(m
, type
, dep
, ret
, true, override
, NULL
)) < 0 && r
!= -EBADR
)
1295 /* JOB_VERIFY_STARTED, JOB_RELOAD require no dependency handling */
1307 int manager_add_job(Manager
*m
, JobType type
, Unit
*unit
, JobMode mode
, bool override
, Job
**_ret
) {
1312 assert(type
< _JOB_TYPE_MAX
);
1314 assert(mode
< _JOB_MODE_MAX
);
1316 log_debug("Trying to enqueue job %s/%s", unit
->meta
.id
, job_type_to_string(type
));
1318 if ((r
= transaction_add_job_and_dependencies(m
, type
, unit
, NULL
, true, override
, &ret
)) < 0) {
1319 transaction_abort(m
);
1323 if ((r
= transaction_activate(m
, mode
)) < 0)
1326 log_debug("Enqueued job %s/%s as %u", unit
->meta
.id
, job_type_to_string(type
), (unsigned) ret
->id
);
1334 int manager_add_job_by_name(Manager
*m
, JobType type
, const char *name
, JobMode mode
, bool override
, Job
**_ret
) {
1339 assert(type
< _JOB_TYPE_MAX
);
1341 assert(mode
< _JOB_MODE_MAX
);
1343 if ((r
= manager_load_unit(m
, name
, NULL
, &unit
)) < 0)
1346 return manager_add_job(m
, type
, unit
, mode
, override
, _ret
);
1349 Job
*manager_get_job(Manager
*m
, uint32_t id
) {
1352 return hashmap_get(m
->jobs
, UINT32_TO_PTR(id
));
1355 Unit
*manager_get_unit(Manager
*m
, const char *name
) {
1359 return hashmap_get(m
->units
, name
);
1362 unsigned manager_dispatch_load_queue(Manager
*m
) {
1368 /* Make sure we are not run recursively */
1369 if (m
->dispatching_load_queue
)
1372 m
->dispatching_load_queue
= true;
1374 /* Dispatches the load queue. Takes a unit from the queue and
1375 * tries to load its data until the queue is empty */
1377 while ((meta
= m
->load_queue
)) {
1378 assert(meta
->in_load_queue
);
1380 unit_load(UNIT(meta
));
1384 m
->dispatching_load_queue
= false;
1388 int manager_load_unit(Manager
*m
, const char *name
, const char *path
, Unit
**_ret
) {
1393 assert(name
|| path
);
1395 /* This will load the service information files, but not actually
1396 * start any services or anything. */
1398 if (path
&& !is_path(path
))
1402 name
= file_name_from_path(path
);
1404 if (!unit_name_is_valid(name
))
1407 if ((ret
= manager_get_unit(m
, name
))) {
1412 if (!(ret
= unit_new(m
)))
1416 if (!(ret
->meta
.fragment_path
= strdup(path
))) {
1421 if ((r
= unit_add_name(ret
, name
)) < 0) {
1426 unit_add_to_load_queue(ret
);
1427 unit_add_to_dbus_queue(ret
);
1429 manager_dispatch_load_queue(m
);
1432 *_ret
= unit_follow_merge(ret
);
1437 void manager_dump_jobs(Manager
*s
, FILE *f
, const char *prefix
) {
1444 HASHMAP_FOREACH(j
, s
->jobs
, i
)
1445 job_dump(j
, f
, prefix
);
1448 void manager_dump_units(Manager
*s
, FILE *f
, const char *prefix
) {
1456 HASHMAP_FOREACH_KEY(u
, t
, s
->units
, i
)
1457 if (u
->meta
.id
== t
)
1458 unit_dump(u
, f
, prefix
);
1461 void manager_clear_jobs(Manager
*m
) {
1466 transaction_abort(m
);
1468 while ((j
= hashmap_first(m
->jobs
)))
1472 unsigned manager_dispatch_run_queue(Manager
*m
) {
1476 if (m
->dispatching_run_queue
)
1479 m
->dispatching_run_queue
= true;
1481 while ((j
= m
->run_queue
)) {
1482 assert(j
->installed
);
1483 assert(j
->in_run_queue
);
1485 job_run_and_invalidate(j
);
1489 m
->dispatching_run_queue
= false;
1493 unsigned manager_dispatch_dbus_queue(Manager
*m
) {
1500 if (m
->dispatching_dbus_queue
)
1503 m
->dispatching_dbus_queue
= true;
1505 while ((meta
= m
->dbus_unit_queue
)) {
1506 assert(meta
->in_dbus_queue
);
1508 bus_unit_send_change_signal(UNIT(meta
));
1512 while ((j
= m
->dbus_job_queue
)) {
1513 assert(j
->in_dbus_queue
);
1515 bus_job_send_change_signal(j
);
1519 m
->dispatching_dbus_queue
= false;
1523 static int manager_dispatch_sigchld(Manager
*m
) {
1532 /* First we call waitd() for a PID and do not reap the
1533 * zombie. That way we can still access /proc/$PID for
1534 * it while it is a zombie. */
1535 if (waitid(P_ALL
, 0, &si
, WEXITED
|WNOHANG
|WNOWAIT
) < 0) {
1537 if (errno
== ECHILD
)
1549 if (si
.si_code
== CLD_EXITED
|| si
.si_code
== CLD_KILLED
|| si
.si_code
== CLD_DUMPED
) {
1552 get_process_name(si
.si_pid
, &name
);
1553 log_debug("Got SIGCHLD for process %llu (%s)", (unsigned long long) si
.si_pid
, strna(name
));
1557 /* And now, we actually reap the zombie. */
1558 if (waitid(P_PID
, si
.si_pid
, &si
, WEXITED
) < 0) {
1565 if (si
.si_code
!= CLD_EXITED
&& si
.si_code
!= CLD_KILLED
&& si
.si_code
!= CLD_DUMPED
)
1568 log_debug("Child %llu died (code=%s, status=%i/%s)",
1569 (long long unsigned) si
.si_pid
,
1570 sigchld_code_to_string(si
.si_code
),
1572 strna(si
.si_code
== CLD_EXITED
? exit_status_to_string(si
.si_status
) : strsignal(si
.si_status
)));
1574 if (!(u
= hashmap_remove(m
->watch_pids
, UINT32_TO_PTR(si
.si_pid
))))
1577 log_debug("Child %llu belongs to %s", (long long unsigned) si
.si_pid
, u
->meta
.id
);
1579 UNIT_VTABLE(u
)->sigchld_event(u
, si
.si_pid
, si
.si_code
, si
.si_status
);
1585 static void manager_start_target(Manager
*m
, const char *name
) {
1588 if ((r
= manager_add_job_by_name(m
, JOB_START
, name
, JOB_REPLACE
, true, NULL
)) < 0)
1589 log_error("Failed to enqueue %s job: %s", name
, strerror(-r
));
1592 static int manager_process_signal_fd(Manager
*m
) {
1594 struct signalfd_siginfo sfsi
;
1595 bool sigchld
= false;
1600 if ((n
= read(m
->signal_watch
.fd
, &sfsi
, sizeof(sfsi
))) != sizeof(sfsi
)) {
1605 if (errno
== EAGAIN
)
1611 switch (sfsi
.ssi_signo
) {
1620 if (m
->running_as
== MANAGER_INIT
) {
1621 manager_start_target(m
, SPECIAL_CTRL_ALT_DEL_TARGET
);
1625 m
->exit_code
= MANAGER_EXIT
;
1630 if (m
->running_as
== MANAGER_INIT
)
1631 manager_start_target(m
, SPECIAL_KBREQUEST_TARGET
);
1633 /* This is a nop on non-init */
1637 if (m
->running_as
== MANAGER_INIT
)
1638 manager_start_target(m
, SPECIAL_SIGPWR_TARGET
);
1640 /* This is a nop on non-init */
1644 manager_dump_units(m
, stdout
, "\t");
1645 manager_dump_jobs(m
, stdout
, "\t");
1651 u
= manager_get_unit(m
, SPECIAL_DBUS_SERVICE
);
1653 if (!u
|| UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u
))) {
1654 log_info("Trying to reconnect to bus...");
1659 if (!u
|| !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u
))) {
1660 log_info("Loading D-Bus service...");
1661 manager_start_target(m
, SPECIAL_DBUS_SERVICE
);
1668 m
->exit_code
= MANAGER_RELOAD
;
1672 log_info("Got unhandled signal <%s>.", strsignal(sfsi
.ssi_signo
));
1677 return manager_dispatch_sigchld(m
);
1682 static int process_event(Manager
*m
, struct epoll_event
*ev
) {
1689 assert(w
= ev
->data
.ptr
);
1695 /* An incoming signal? */
1696 if (ev
->events
!= EPOLLIN
)
1699 if ((r
= manager_process_signal_fd(m
)) < 0)
1706 /* Some fd event, to be dispatched to the units */
1707 UNIT_VTABLE(w
->data
.unit
)->fd_event(w
->data
.unit
, w
->fd
, ev
->events
, w
);
1714 /* Some timer event, to be dispatched to the units */
1715 if ((k
= read(w
->fd
, &v
, sizeof(v
))) != sizeof(v
)) {
1717 if (k
< 0 && (errno
== EINTR
|| errno
== EAGAIN
))
1720 return k
< 0 ? -errno
: -EIO
;
1723 UNIT_VTABLE(w
->data
.unit
)->timer_event(w
->data
.unit
, v
, w
);
1728 /* Some mount table change, intended for the mount subsystem */
1729 mount_fd_event(m
, ev
->events
);
1733 /* Some notification from udev, intended for the device subsystem */
1734 device_fd_event(m
, ev
->events
);
1737 case WATCH_DBUS_WATCH
:
1738 bus_watch_event(m
, w
, ev
->events
);
1741 case WATCH_DBUS_TIMEOUT
:
1742 bus_timeout_event(m
, w
, ev
->events
);
1746 assert_not_reached("Unknown epoll event type.");
1752 int manager_loop(Manager
*m
) {
1755 RATELIMIT_DEFINE(rl
, 1*USEC_PER_SEC
, 1000);
1758 m
->exit_code
= MANAGER_RUNNING
;
1760 while (m
->exit_code
== MANAGER_RUNNING
) {
1761 struct epoll_event event
;
1764 if (!ratelimit_test(&rl
)) {
1765 /* Yay, something is going seriously wrong, pause a little */
1766 log_warning("Looping too fast. Throttling execution a little.");
1770 if (manager_dispatch_cleanup_queue(m
) > 0)
1773 if (manager_dispatch_load_queue(m
) > 0)
1776 if (manager_dispatch_run_queue(m
) > 0)
1779 if (bus_dispatch(m
) > 0)
1782 if (manager_dispatch_dbus_queue(m
) > 0)
1785 if ((n
= epoll_wait(m
->epoll_fd
, &event
, 1, -1)) < 0) {
1787 if (errno
== -EINTR
)
1795 if ((r
= process_event(m
, &event
)) < 0)
1799 return m
->exit_code
;
1802 int manager_get_unit_from_dbus_path(Manager
*m
, const char *s
, Unit
**_u
) {
1810 if (!startswith(s
, "/org/freedesktop/systemd1/unit/"))
1813 if (!(n
= bus_path_unescape(s
+31)))
1816 u
= manager_get_unit(m
, n
);
1827 int manager_get_job_from_dbus_path(Manager
*m
, const char *s
, Job
**_j
) {
1836 if (!startswith(s
, "/org/freedesktop/systemd1/job/"))
1839 if ((r
= safe_atou(s
+ 30, &id
)) < 0)
1842 if (!(j
= manager_get_job(m
, id
)))
1850 static bool manager_utmp_good(Manager
*m
) {
1855 if ((r
= mount_path_is_mounted(m
, _PATH_UTMPX
)) <= 0) {
1858 log_warning("Failed to determine whether " _PATH_UTMPX
" is mounted: %s", strerror(-r
));
1866 void manager_write_utmp_reboot(Manager
*m
) {
1871 if (m
->utmp_reboot_written
)
1874 if (m
->running_as
!= MANAGER_INIT
)
1877 if (!manager_utmp_good(m
))
1880 if ((r
= utmp_put_reboot(m
->boot_timestamp
)) < 0) {
1882 if (r
!= -ENOENT
&& r
!= -EROFS
)
1883 log_warning("Failed to write utmp/wtmp: %s", strerror(-r
));
1888 m
->utmp_reboot_written
= true;
1891 void manager_write_utmp_runlevel(Manager
*m
, Unit
*u
) {
1897 if (u
->meta
.type
!= UNIT_TARGET
)
1900 if (m
->running_as
!= MANAGER_INIT
)
1903 if (!manager_utmp_good(m
))
1906 if ((runlevel
= target_get_runlevel(TARGET(u
))) <= 0)
1909 if ((r
= utmp_put_runlevel(0, runlevel
, 0)) < 0) {
1911 if (r
!= -ENOENT
&& r
!= -EROFS
)
1912 log_warning("Failed to write utmp/wtmp: %s", strerror(-r
));
1916 void manager_dispatch_bus_name_owner_changed(
1919 const char* old_owner
,
1920 const char *new_owner
) {
1927 if (!(u
= hashmap_get(m
->watch_bus
, name
)))
1930 UNIT_VTABLE(u
)->bus_name_owner_change(u
, name
, old_owner
, new_owner
);
1933 void manager_dispatch_bus_query_pid_done(
1944 if (!(u
= hashmap_get(m
->watch_bus
, name
)))
1947 UNIT_VTABLE(u
)->bus_query_pid_done(u
, name
, pid
);
1950 int manager_open_serialization(FILE **_f
) {
1958 if (asprintf(&path
, "/dev/shm/systemd-%u.dump-XXXXXX", (unsigned) getpid()) < 0)
1961 saved_umask
= umask(0077);
1962 fd
= mkostemp(path
, O_RDWR
|O_CLOEXEC
);
1972 log_debug("Serializing state to %s", path
);
1975 if (!(f
= fdopen(fd
, "w+")) < 0)
1983 int manager_serialize(Manager
*m
, FILE *f
, FDSet
*fds
) {
1993 HASHMAP_FOREACH_KEY(u
, t
, m
->units
, i
) {
1994 if (u
->meta
.id
!= t
)
1997 if (!unit_can_serialize(u
))
2001 fputs(u
->meta
.id
, f
);
2004 if ((r
= unit_serialize(u
, f
, fds
)) < 0)
2014 int manager_deserialize(Manager
*m
, FILE *f
, FDSet
*fds
) {
2020 log_debug("Deserializing state...");
2024 char name
[UNIT_NAME_MAX
+2];
2027 if (!fgets(name
, sizeof(name
), f
)) {
2036 if ((r
= manager_load_unit(m
, strstrip(name
), NULL
, &u
)) < 0)
2039 if ((r
= unit_deserialize(u
, f
, fds
)) < 0)
2049 int manager_reload(Manager
*m
) {
2056 if ((r
= manager_open_serialization(&f
)) < 0)
2059 if (!(fds
= fdset_new())) {
2064 if ((r
= manager_serialize(m
, f
, fds
)) < 0)
2067 if (fseeko(f
, 0, SEEK_SET
) < 0) {
2072 /* From here on there is no way back. */
2073 manager_clear_jobs_and_units(m
);
2075 /* First, enumerate what we can from all config files */
2076 if ((q
= manager_enumerate(m
)) < 0)
2079 /* Second, deserialize our stored data */
2080 if ((q
= manager_deserialize(m
, f
, fds
)) < 0)
2086 /* Third, fire things up! */
2087 if ((q
= manager_coldplug(m
)) < 0)
2100 static const char* const manager_running_as_table
[_MANAGER_RUNNING_AS_MAX
] = {
2101 [MANAGER_INIT
] = "init",
2102 [MANAGER_SYSTEM
] = "system",
2103 [MANAGER_SESSION
] = "session"
2106 DEFINE_STRING_TABLE_LOOKUP(manager_running_as
, ManagerRunningAs
);