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"
50 static int enable_special_signals(Manager
*m
) {
55 /* Enable that we get SIGINT on control-alt-del */
56 if (reboot(RB_DISABLE_CAD
) < 0)
57 log_warning("Failed to enable ctrl-alt-del handling: %m");
59 if ((fd
= open_terminal("/dev/tty0", O_RDWR
)) < 0)
60 log_warning("Failed to open /dev/tty0: %m");
62 /* Enable that we get SIGWINCH on kbrequest */
63 if (ioctl(fd
, KDSIGACCEPT
, SIGWINCH
) < 0)
64 log_warning("Failed to enable kbrequest handling: %s", strerror(errno
));
66 close_nointr_nofail(fd
);
72 static int manager_setup_signals(Manager
*m
) {
74 struct epoll_event ev
;
79 /* We are not interested in SIGSTOP and friends. */
81 sa
.sa_handler
= SIG_DFL
;
82 sa
.sa_flags
= SA_NOCLDSTOP
|SA_RESTART
;
83 assert_se(sigaction(SIGCHLD
, &sa
, NULL
) == 0);
85 assert_se(sigemptyset(&mask
) == 0);
86 assert_se(sigaddset(&mask
, SIGCHLD
) == 0);
87 assert_se(sigaddset(&mask
, SIGINT
) == 0); /* Kernel sends us this on control-alt-del */
88 assert_se(sigaddset(&mask
, SIGWINCH
) == 0); /* Kernel sends us this on kbrequest (alt-arrowup) */
89 assert_se(sigaddset(&mask
, SIGTERM
) == 0);
90 assert_se(sigaddset(&mask
, SIGHUP
) == 0);
91 assert_se(sigaddset(&mask
, SIGUSR1
) == 0);
92 assert_se(sigaddset(&mask
, SIGUSR2
) == 0);
93 assert_se(sigaddset(&mask
, SIGPWR
) == 0);
94 assert_se(sigprocmask(SIG_SETMASK
, &mask
, NULL
) == 0);
96 m
->signal_watch
.type
= WATCH_SIGNAL
;
97 if ((m
->signal_watch
.fd
= signalfd(-1, &mask
, SFD_NONBLOCK
|SFD_CLOEXEC
)) < 0)
102 ev
.data
.ptr
= &m
->signal_watch
;
104 if (epoll_ctl(m
->epoll_fd
, EPOLL_CTL_ADD
, m
->signal_watch
.fd
, &ev
) < 0)
107 if (m
->running_as
== MANAGER_INIT
)
108 return enable_special_signals(m
);
113 static char** session_dirs(void) {
114 const char *home
, *e
;
115 char *config_home
= NULL
, *data_home
= NULL
;
116 char **config_dirs
= NULL
, **data_dirs
= NULL
;
117 char **r
= NULL
, **t
;
119 /* Implement the mechanisms defined in
121 * http://standards.freedesktop.org/basedir-spec/basedir-spec-0.6.html
123 * We look in both the config and the data dirs because we
124 * want to encourage that distributors ship their unit files
125 * as data, and allow overriding as configuration.
128 home
= getenv("HOME");
130 if ((e
= getenv("XDG_CONFIG_HOME"))) {
131 if (asprintf(&config_home
, "%s/systemd/session", e
) < 0)
135 if (asprintf(&config_home
, "%s/.config/systemd/session", home
) < 0)
139 if ((e
= getenv("XDG_CONFIG_DIRS")))
140 config_dirs
= strv_split(e
, ":");
142 config_dirs
= strv_new("/etc/xdg", NULL
);
147 if ((e
= getenv("XDG_DATA_HOME"))) {
148 if (asprintf(&data_home
, "%s/systemd/session", e
) < 0)
152 if (asprintf(&data_home
, "%s/.local/share/systemd/session", home
) < 0)
156 if ((e
= getenv("XDG_DATA_DIRS")))
157 data_dirs
= strv_split(e
, ":");
159 data_dirs
= strv_new("/usr/local/share", "/usr/share", NULL
);
164 /* Now merge everything we found. */
166 if (!(t
= strv_append(r
, config_home
)))
172 if (!(t
= strv_merge_concat(r
, config_dirs
, "/systemd/session")))
177 if (!(t
= strv_append(r
, SESSION_CONFIG_UNIT_PATH
)))
183 if (!(t
= strv_append(r
, data_home
)))
189 if (!(t
= strv_merge_concat(r
, data_dirs
, "/systemd/session")))
194 if (!(t
= strv_append(r
, SESSION_DATA_UNIT_PATH
)))
199 if (!strv_path_make_absolute_cwd(r
))
204 strv_free(config_dirs
);
206 strv_free(data_dirs
);
216 static int manager_find_paths(Manager
*m
) {
222 /* First priority is whatever has been passed to us via env
224 if ((e
= getenv("SYSTEMD_UNIT_PATH")))
225 if (!(m
->unit_path
= split_path_and_make_absolute(e
)))
228 if (strv_isempty(m
->unit_path
)) {
230 /* Nothing is set, so let's figure something out. */
231 strv_free(m
->unit_path
);
233 if (m
->running_as
== MANAGER_SESSION
) {
234 if (!(m
->unit_path
= session_dirs()))
237 if (!(m
->unit_path
= strv_new(
238 SYSTEM_CONFIG_UNIT_PATH
, /* /etc/systemd/system/ */
239 SYSTEM_DATA_UNIT_PATH
, /* /lib/systemd/system/ */
244 if (m
->running_as
== MANAGER_INIT
) {
245 /* /etc/init.d/ compativility does not matter to users */
247 if ((e
= getenv("SYSTEMD_SYSVINIT_PATH")))
248 if (!(m
->sysvinit_path
= split_path_and_make_absolute(e
)))
251 if (strv_isempty(m
->sysvinit_path
)) {
252 strv_free(m
->sysvinit_path
);
254 if (!(m
->sysvinit_path
= strv_new(
255 SYSTEM_SYSVINIT_PATH
, /* /etc/init.d/ */
260 if ((e
= getenv("SYSTEMD_SYSVRCND_PATH")))
261 if (!(m
->sysvrcnd_path
= split_path_and_make_absolute(e
)))
264 if (strv_isempty(m
->sysvrcnd_path
)) {
265 strv_free(m
->sysvrcnd_path
);
267 if (!(m
->sysvrcnd_path
= strv_new(
268 SYSTEM_SYSVRCND_PATH
, /* /etc/rcN.d/ */
274 strv_uniq(m
->unit_path
);
275 strv_uniq(m
->sysvinit_path
);
276 strv_uniq(m
->sysvrcnd_path
);
278 assert(!strv_isempty(m
->unit_path
));
279 if (!(t
= strv_join(m
->unit_path
, "\n\t")))
281 log_debug("Looking for unit files in:\n\t%s", t
);
284 if (!strv_isempty(m
->sysvinit_path
)) {
286 if (!(t
= strv_join(m
->sysvinit_path
, "\n\t")))
289 log_debug("Looking for SysV init scripts in:\n\t%s", t
);
292 log_debug("Ignoring SysV init scripts.");
294 if (!strv_isempty(m
->sysvrcnd_path
)) {
296 if (!(t
= strv_join(m
->sysvrcnd_path
, "\n\t")))
299 log_debug("Looking for SysV rcN.d links in:\n\t%s", t
);
302 log_debug("Ignoring SysV rcN.d links.");
307 int manager_new(ManagerRunningAs running_as
, bool confirm_spawn
, Manager
**_m
) {
312 assert(running_as
>= 0);
313 assert(running_as
< _MANAGER_RUNNING_AS_MAX
);
315 if (!(m
= new0(Manager
, 1)))
318 m
->boot_timestamp
= now(CLOCK_REALTIME
);
320 m
->running_as
= running_as
;
321 m
->confirm_spawn
= confirm_spawn
;
323 m
->signal_watch
.fd
= m
->mount_watch
.fd
= m
->udev_watch
.fd
= m
->epoll_fd
= -1;
324 m
->current_job_id
= 1; /* start as id #1, so that we can leave #0 around as "null-like" value */
326 if (!(m
->units
= hashmap_new(string_hash_func
, string_compare_func
)))
329 if (!(m
->jobs
= hashmap_new(trivial_hash_func
, trivial_compare_func
)))
332 if (!(m
->transaction_jobs
= hashmap_new(trivial_hash_func
, trivial_compare_func
)))
335 if (!(m
->watch_pids
= hashmap_new(trivial_hash_func
, trivial_compare_func
)))
338 if (!(m
->cgroup_bondings
= hashmap_new(string_hash_func
, string_compare_func
)))
341 if ((m
->epoll_fd
= epoll_create1(EPOLL_CLOEXEC
)) < 0)
344 if ((r
= manager_find_paths(m
)) < 0)
347 if ((r
= manager_setup_signals(m
)) < 0)
350 if ((r
= manager_setup_cgroup(m
)) < 0)
353 /* Try to connect to the busses, if possible. */
354 if ((r
= bus_init_system(m
)) < 0 ||
355 (r
= bus_init_api(m
)) < 0)
366 static unsigned manager_dispatch_cleanup_queue(Manager
*m
) {
372 while ((meta
= m
->cleanup_queue
)) {
373 assert(meta
->in_cleanup_queue
);
375 unit_free(UNIT(meta
));
382 void manager_free(Manager
*m
) {
389 while ((j
= hashmap_first(m
->transaction_jobs
)))
392 while ((u
= hashmap_first(m
->units
)))
395 manager_dispatch_cleanup_queue(m
);
397 for (c
= 0; c
< _UNIT_TYPE_MAX
; c
++)
398 if (unit_vtable
[c
]->shutdown
)
399 unit_vtable
[c
]->shutdown(m
);
401 manager_shutdown_cgroup(m
);
406 hashmap_free(m
->units
);
407 hashmap_free(m
->jobs
);
408 hashmap_free(m
->transaction_jobs
);
409 hashmap_free(m
->watch_pids
);
411 if (m
->epoll_fd
>= 0)
412 close_nointr(m
->epoll_fd
);
413 if (m
->signal_watch
.fd
>= 0)
414 close_nointr(m
->signal_watch
.fd
);
416 strv_free(m
->unit_path
);
417 strv_free(m
->sysvinit_path
);
418 strv_free(m
->sysvrcnd_path
);
420 free(m
->cgroup_controller
);
421 free(m
->cgroup_hierarchy
);
423 assert(hashmap_isempty(m
->cgroup_bondings
));
424 hashmap_free(m
->cgroup_bondings
);
429 int manager_coldplug(Manager
*m
) {
438 /* First, let's ask every type to load all units from
439 * disk/kernel that it might know */
440 for (c
= 0; c
< _UNIT_TYPE_MAX
; c
++)
441 if (unit_vtable
[c
]->enumerate
)
442 if ((r
= unit_vtable
[c
]->enumerate(m
)) < 0)
445 manager_dispatch_load_queue(m
);
447 /* Then, let's set up their initial state. */
448 HASHMAP_FOREACH_KEY(u
, k
, m
->units
, i
) {
454 if (UNIT_VTABLE(u
)->coldplug
)
455 if ((r
= UNIT_VTABLE(u
)->coldplug(u
)) < 0)
459 /* Now that the initial devices are available, let's see if we
460 * can write the utmp file */
461 manager_write_utmp_reboot(m
);
466 static void transaction_delete_job(Manager
*m
, Job
*j
, bool delete_dependencies
) {
470 /* Deletes one job from the transaction */
472 manager_transaction_unlink_job(m
, j
, delete_dependencies
);
478 static void transaction_delete_unit(Manager
*m
, Unit
*u
) {
481 /* Deletes all jobs associated with a certain unit from the
484 while ((j
= hashmap_get(m
->transaction_jobs
, u
)))
485 transaction_delete_job(m
, j
, true);
488 static void transaction_clean_dependencies(Manager
*m
) {
494 /* Drops all dependencies of all installed jobs */
496 HASHMAP_FOREACH(j
, m
->jobs
, i
) {
497 while (j
->subject_list
)
498 job_dependency_free(j
->subject_list
);
499 while (j
->object_list
)
500 job_dependency_free(j
->object_list
);
503 assert(!m
->transaction_anchor
);
506 static void transaction_abort(Manager
*m
) {
511 while ((j
= hashmap_first(m
->transaction_jobs
)))
513 transaction_delete_job(m
, j
, true);
517 assert(hashmap_isempty(m
->transaction_jobs
));
519 transaction_clean_dependencies(m
);
522 static void transaction_find_jobs_that_matter_to_anchor(Manager
*m
, Job
*j
, unsigned generation
) {
527 /* A recursive sweep through the graph that marks all units
528 * that matter to the anchor job, i.e. are directly or
529 * indirectly a dependency of the anchor job via paths that
530 * are fully marked as mattering. */
535 l
= m
->transaction_anchor
;
537 LIST_FOREACH(subject
, l
, l
) {
539 /* This link does not matter */
543 /* This unit has already been marked */
544 if (l
->object
->generation
== generation
)
547 l
->object
->matters_to_anchor
= true;
548 l
->object
->generation
= generation
;
550 transaction_find_jobs_that_matter_to_anchor(m
, l
->object
, generation
);
554 static void transaction_merge_and_delete_job(Manager
*m
, Job
*j
, Job
*other
, JobType t
) {
555 JobDependency
*l
, *last
;
559 assert(j
->unit
== other
->unit
);
560 assert(!j
->installed
);
562 /* Merges 'other' into 'j' and then deletes j. */
565 j
->state
= JOB_WAITING
;
566 j
->forced
= j
->forced
|| other
->forced
;
568 j
->matters_to_anchor
= j
->matters_to_anchor
|| other
->matters_to_anchor
;
570 /* Patch us in as new owner of the JobDependency objects */
572 LIST_FOREACH(subject
, l
, other
->subject_list
) {
573 assert(l
->subject
== other
);
578 /* Merge both lists */
580 last
->subject_next
= j
->subject_list
;
582 j
->subject_list
->subject_prev
= last
;
583 j
->subject_list
= other
->subject_list
;
586 /* Patch us in as new owner of the JobDependency objects */
588 LIST_FOREACH(object
, l
, other
->object_list
) {
589 assert(l
->object
== other
);
594 /* Merge both lists */
596 last
->object_next
= j
->object_list
;
598 j
->object_list
->object_prev
= last
;
599 j
->object_list
= other
->object_list
;
602 /* Kill the other job */
603 other
->subject_list
= NULL
;
604 other
->object_list
= NULL
;
605 transaction_delete_job(m
, other
, true);
608 static int delete_one_unmergeable_job(Manager
*m
, Job
*j
) {
613 /* Tries to delete one item in the linked list
614 * j->transaction_next->transaction_next->... that conflicts
615 * whith another one, in an attempt to make an inconsistent
616 * transaction work. */
618 /* We rely here on the fact that if a merged with b does not
619 * merge with c, either a or b merge with c neither */
620 LIST_FOREACH(transaction
, j
, j
)
621 LIST_FOREACH(transaction
, k
, j
->transaction_next
) {
624 /* Is this one mergeable? Then skip it */
625 if (job_type_is_mergeable(j
->type
, k
->type
))
628 /* Ok, we found two that conflict, let's see if we can
629 * drop one of them */
630 if (!j
->matters_to_anchor
)
632 else if (!k
->matters_to_anchor
)
637 /* Ok, we can drop one, so let's do so. */
638 log_debug("Trying to fix job merging by deleting job %s/%s", unit_id(d
->unit
), job_type_to_string(d
->type
));
639 transaction_delete_job(m
, d
, true);
646 static int transaction_merge_jobs(Manager
*m
) {
653 /* First step, check whether any of the jobs for one specific
654 * task conflict. If so, try to drop one of them. */
655 HASHMAP_FOREACH(j
, m
->transaction_jobs
, i
) {
660 LIST_FOREACH(transaction
, k
, j
->transaction_next
) {
661 if ((r
= job_type_merge(&t
, k
->type
)) >= 0)
664 /* OK, we could not merge all jobs for this
665 * action. Let's see if we can get rid of one
668 if ((r
= delete_one_unmergeable_job(m
, j
)) >= 0)
669 /* Ok, we managed to drop one, now
670 * let's ask our callers to call us
671 * again after garbage collecting */
674 /* We couldn't merge anything. Failure */
679 /* Second step, merge the jobs. */
680 HASHMAP_FOREACH(j
, m
->transaction_jobs
, i
) {
684 /* Merge all transactions */
685 LIST_FOREACH(transaction
, k
, j
->transaction_next
)
686 assert_se(job_type_merge(&t
, k
->type
) == 0);
688 /* If an active job is mergeable, merge it too */
689 if (j
->unit
->meta
.job
)
690 job_type_merge(&t
, j
->unit
->meta
.job
->type
); /* Might fail. Which is OK */
692 while ((k
= j
->transaction_next
)) {
694 transaction_merge_and_delete_job(m
, k
, j
, t
);
697 transaction_merge_and_delete_job(m
, j
, k
, t
);
700 assert(!j
->transaction_next
);
701 assert(!j
->transaction_prev
);
707 static void transaction_drop_redundant(Manager
*m
) {
712 /* Goes through the transaction and removes all jobs that are
721 HASHMAP_FOREACH(j
, m
->transaction_jobs
, i
) {
722 bool changes_something
= false;
725 LIST_FOREACH(transaction
, k
, j
) {
727 if (!job_is_anchor(k
) &&
728 job_type_is_redundant(k
->type
, unit_active_state(k
->unit
)))
731 changes_something
= true;
735 if (changes_something
)
738 log_debug("Found redundant job %s/%s, dropping.", unit_id(j
->unit
), job_type_to_string(j
->type
));
739 transaction_delete_job(m
, j
, false);
747 static bool unit_matters_to_anchor(Unit
*u
, Job
*j
) {
749 assert(!j
->transaction_prev
);
751 /* Checks whether at least one of the jobs for this unit
752 * matters to the anchor. */
754 LIST_FOREACH(transaction
, j
, j
)
755 if (j
->matters_to_anchor
)
761 static int transaction_verify_order_one(Manager
*m
, Job
*j
, Job
*from
, unsigned generation
) {
768 assert(!j
->transaction_prev
);
770 /* Does a recursive sweep through the ordering graph, looking
771 * for a cycle. If we find cycle we try to break it. */
773 /* Did we find a cycle? */
774 if (j
->marker
&& j
->generation
== generation
) {
777 /* So, we already have been here. We have a
778 * cycle. Let's try to break it. We go backwards in
779 * our path and try to find a suitable job to
780 * remove. We use the marker to find our way back,
781 * since smart how we are we stored our way back in
784 log_debug("Found ordering cycle on %s/%s", unit_id(j
->unit
), job_type_to_string(j
->type
));
786 for (k
= from
; k
; k
= (k
->generation
== generation
? k
->marker
: NULL
)) {
788 log_debug("Walked on cycle path to %s/%s", unit_id(k
->unit
), job_type_to_string(k
->type
));
791 !unit_matters_to_anchor(k
->unit
, k
)) {
792 /* Ok, we can drop this one, so let's
794 log_debug("Breaking order cycle by deleting job %s/%s", unit_id(k
->unit
), job_type_to_string(k
->type
));
795 transaction_delete_unit(m
, k
->unit
);
799 /* Check if this in fact was the beginning of
805 log_debug("Unable to break cycle");
810 /* Make the marker point to where we come from, so that we can
811 * find our way backwards if we want to break a cycle */
813 j
->generation
= generation
;
815 /* We assume that the the dependencies are bidirectional, and
816 * hence can ignore UNIT_AFTER */
817 SET_FOREACH(u
, j
->unit
->meta
.dependencies
[UNIT_BEFORE
], i
) {
820 /* Is there a job for this unit? */
821 if (!(o
= hashmap_get(m
->transaction_jobs
, u
)))
823 /* Ok, there is no job for this in the
824 * transaction, but maybe there is already one
826 if (!(o
= u
->meta
.job
))
829 if ((r
= transaction_verify_order_one(m
, o
, j
, generation
)) < 0)
833 /* Ok, let's backtrack, and remember that this entry is not on
834 * our path anymore. */
840 static int transaction_verify_order(Manager
*m
, unsigned *generation
) {
848 /* Check if the ordering graph is cyclic. If it is, try to fix
849 * that up by dropping one of the jobs. */
851 HASHMAP_FOREACH(j
, m
->transaction_jobs
, i
)
852 if ((r
= transaction_verify_order_one(m
, j
, NULL
, (*generation
)++)) < 0)
858 static void transaction_collect_garbage(Manager
*m
) {
863 /* Drop jobs that are not required by any other job */
871 HASHMAP_FOREACH(j
, m
->transaction_jobs
, i
) {
875 log_debug("Garbage collecting job %s/%s", unit_id(j
->unit
), job_type_to_string(j
->type
));
876 transaction_delete_job(m
, j
, true);
884 static int transaction_is_destructive(Manager
*m
, JobMode mode
) {
890 /* Checks whether applying this transaction means that
891 * existing jobs would be replaced */
893 HASHMAP_FOREACH(j
, m
->transaction_jobs
, i
) {
896 assert(!j
->transaction_prev
);
897 assert(!j
->transaction_next
);
899 if (j
->unit
->meta
.job
&&
900 j
->unit
->meta
.job
!= j
&&
901 !job_type_is_superset(j
->type
, j
->unit
->meta
.job
->type
))
908 static void transaction_minimize_impact(Manager
*m
) {
912 /* Drops all unnecessary jobs that reverse already active jobs
913 * or that stop a running service. */
921 HASHMAP_FOREACH(j
, m
->transaction_jobs
, i
) {
922 LIST_FOREACH(transaction
, j
, j
) {
923 bool stops_running_service
, changes_existing_job
;
925 /* If it matters, we shouldn't drop it */
926 if (j
->matters_to_anchor
)
929 /* Would this stop a running service?
930 * Would this change an existing job?
931 * If so, let's drop this entry */
933 stops_running_service
=
934 j
->type
== JOB_STOP
&& UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(j
->unit
));
936 changes_existing_job
=
937 j
->unit
->meta
.job
&& job_type_is_conflicting(j
->type
, j
->unit
->meta
.job
->state
);
939 if (!stops_running_service
&& !changes_existing_job
)
942 if (stops_running_service
)
943 log_debug("%s/%s would stop a running service.", unit_id(j
->unit
), job_type_to_string(j
->type
));
945 if (changes_existing_job
)
946 log_debug("%s/%s would change existing job.", unit_id(j
->unit
), job_type_to_string(j
->type
));
948 /* Ok, let's get rid of this */
949 log_debug("Deleting %s/%s to minimize impact.", unit_id(j
->unit
), job_type_to_string(j
->type
));
951 transaction_delete_job(m
, j
, true);
963 static int transaction_apply(Manager
*m
, JobMode mode
) {
968 /* Moves the transaction jobs to the set of active jobs */
970 HASHMAP_FOREACH(j
, m
->transaction_jobs
, i
) {
972 assert(!j
->transaction_prev
);
973 assert(!j
->transaction_next
);
978 if ((r
= hashmap_put(m
->jobs
, UINT32_TO_PTR(j
->id
), j
)) < 0)
982 while ((j
= hashmap_steal_first(m
->transaction_jobs
))) {
986 if (j
->unit
->meta
.job
)
987 job_free(j
->unit
->meta
.job
);
989 j
->unit
->meta
.job
= j
;
992 /* We're fully installed. Now let's free data we don't
995 assert(!j
->transaction_next
);
996 assert(!j
->transaction_prev
);
998 job_add_to_run_queue(j
);
999 job_add_to_dbus_queue(j
);
1002 /* As last step, kill all remaining job dependencies. */
1003 transaction_clean_dependencies(m
);
1009 HASHMAP_FOREACH(j
, m
->transaction_jobs
, i
) {
1013 hashmap_remove(m
->jobs
, UINT32_TO_PTR(j
->id
));
1019 static int transaction_activate(Manager
*m
, JobMode mode
) {
1021 unsigned generation
= 1;
1025 /* This applies the changes recorded in transaction_jobs to
1026 * the actual list of jobs, if possible. */
1028 /* First step: figure out which jobs matter */
1029 transaction_find_jobs_that_matter_to_anchor(m
, NULL
, generation
++);
1031 /* Second step: Try not to stop any running services if
1032 * we don't have to. Don't try to reverse running
1033 * jobs if we don't have to. */
1034 transaction_minimize_impact(m
);
1036 /* Third step: Drop redundant jobs */
1037 transaction_drop_redundant(m
);
1040 /* Fourth step: Let's remove unneeded jobs that might
1042 transaction_collect_garbage(m
);
1044 /* Fifth step: verify order makes sense and correct
1045 * cycles if necessary and possible */
1046 if ((r
= transaction_verify_order(m
, &generation
)) >= 0)
1050 log_debug("Requested transaction contains an unfixable cyclic ordering dependency: %s", strerror(-r
));
1054 /* Let's see if the resulting transaction ordering
1055 * graph is still cyclic... */
1059 /* Sixth step: let's drop unmergeable entries if
1060 * necessary and possible, merge entries we can
1062 if ((r
= transaction_merge_jobs(m
)) >= 0)
1066 log_debug("Requested transaction contains unmergable jobs: %s", strerror(-r
));
1070 /* Seventh step: an entry got dropped, let's garbage
1071 * collect its dependencies. */
1072 transaction_collect_garbage(m
);
1074 /* Let's see if the resulting transaction still has
1075 * unmergeable entries ... */
1078 /* Eights step: Drop redundant jobs again, if the merging now allows us to drop more. */
1079 transaction_drop_redundant(m
);
1081 /* Ninth step: check whether we can actually apply this */
1082 if (mode
== JOB_FAIL
)
1083 if ((r
= transaction_is_destructive(m
, mode
)) < 0) {
1084 log_debug("Requested transaction contradicts existing jobs: %s", strerror(-r
));
1088 /* Tenth step: apply changes */
1089 if ((r
= transaction_apply(m
, mode
)) < 0) {
1090 log_debug("Failed to apply transaction: %s", strerror(-r
));
1094 assert(hashmap_isempty(m
->transaction_jobs
));
1095 assert(!m
->transaction_anchor
);
1100 transaction_abort(m
);
1104 static Job
* transaction_add_one_job(Manager
*m
, JobType type
, Unit
*unit
, bool force
, bool *is_new
) {
1111 /* Looks for an axisting prospective job and returns that. If
1112 * it doesn't exist it is created and added to the prospective
1115 f
= hashmap_get(m
->transaction_jobs
, unit
);
1117 LIST_FOREACH(transaction
, j
, f
) {
1118 assert(j
->unit
== unit
);
1120 if (j
->type
== type
) {
1127 if (unit
->meta
.job
&& unit
->meta
.job
->type
== type
)
1129 else if (!(j
= job_new(m
, type
, unit
)))
1134 j
->matters_to_anchor
= false;
1137 LIST_PREPEND(Job
, transaction
, f
, j
);
1139 if ((r
= hashmap_replace(m
->transaction_jobs
, unit
, f
)) < 0) {
1147 log_debug("Added job %s/%s to transaction.", unit_id(unit
), job_type_to_string(type
));
1152 void manager_transaction_unlink_job(Manager
*m
, Job
*j
, bool delete_dependencies
) {
1156 if (j
->transaction_prev
)
1157 j
->transaction_prev
->transaction_next
= j
->transaction_next
;
1158 else if (j
->transaction_next
)
1159 hashmap_replace(m
->transaction_jobs
, j
->unit
, j
->transaction_next
);
1161 hashmap_remove_value(m
->transaction_jobs
, j
->unit
, j
);
1163 if (j
->transaction_next
)
1164 j
->transaction_next
->transaction_prev
= j
->transaction_prev
;
1166 j
->transaction_prev
= j
->transaction_next
= NULL
;
1168 while (j
->subject_list
)
1169 job_dependency_free(j
->subject_list
);
1171 while (j
->object_list
) {
1172 Job
*other
= j
->object_list
->matters
? j
->object_list
->subject
: NULL
;
1174 job_dependency_free(j
->object_list
);
1176 if (other
&& delete_dependencies
) {
1177 log_debug("Deleting job %s/%s as dependency of job %s/%s",
1178 unit_id(other
->unit
), job_type_to_string(other
->type
),
1179 unit_id(j
->unit
), job_type_to_string(j
->type
));
1180 transaction_delete_job(m
, other
, delete_dependencies
);
1185 static int transaction_add_job_and_dependencies(Manager
*m
, JobType type
, Unit
*unit
, Job
*by
, bool matters
, bool force
, Job
**_ret
) {
1193 assert(type
< _JOB_TYPE_MAX
);
1196 if (unit
->meta
.load_state
!= UNIT_LOADED
)
1199 if (!unit_job_is_applicable(unit
, type
))
1202 /* First add the job. */
1203 if (!(ret
= transaction_add_one_job(m
, type
, unit
, force
, &is_new
)))
1206 /* Then, add a link to the job. */
1207 if (!job_dependency_new(by
, ret
, matters
))
1211 /* Finally, recursively add in all dependencies. */
1212 if (type
== JOB_START
|| type
== JOB_RELOAD_OR_START
) {
1213 SET_FOREACH(dep
, ret
->unit
->meta
.dependencies
[UNIT_REQUIRES
], i
)
1214 if ((r
= transaction_add_job_and_dependencies(m
, JOB_START
, dep
, ret
, true, force
, NULL
)) < 0 && r
!= -EBADR
)
1216 SET_FOREACH(dep
, ret
->unit
->meta
.dependencies
[UNIT_SOFT_REQUIRES
], i
)
1217 if ((r
= transaction_add_job_and_dependencies(m
, JOB_START
, dep
, ret
, !force
, force
, NULL
)) < 0 && r
!= -EBADR
)
1219 SET_FOREACH(dep
, ret
->unit
->meta
.dependencies
[UNIT_WANTS
], i
)
1220 if ((r
= transaction_add_job_and_dependencies(m
, JOB_START
, dep
, ret
, false, force
, NULL
)) < 0)
1221 log_warning("Cannot add dependency job for unit %s, ignoring: %s", unit_id(dep
), strerror(-r
));
1222 SET_FOREACH(dep
, ret
->unit
->meta
.dependencies
[UNIT_REQUISITE
], i
)
1223 if ((r
= transaction_add_job_and_dependencies(m
, JOB_VERIFY_ACTIVE
, dep
, ret
, true, force
, NULL
)) < 0 && r
!= -EBADR
)
1225 SET_FOREACH(dep
, ret
->unit
->meta
.dependencies
[UNIT_SOFT_REQUISITE
], i
)
1226 if ((r
= transaction_add_job_and_dependencies(m
, JOB_VERIFY_ACTIVE
, dep
, ret
, !force
, force
, NULL
)) < 0 && r
!= -EBADR
)
1228 SET_FOREACH(dep
, ret
->unit
->meta
.dependencies
[UNIT_CONFLICTS
], i
)
1229 if ((r
= transaction_add_job_and_dependencies(m
, JOB_STOP
, dep
, ret
, true, force
, NULL
)) < 0 && r
!= -EBADR
)
1232 } else if (type
== JOB_STOP
|| type
== JOB_RESTART
|| type
== JOB_TRY_RESTART
) {
1234 SET_FOREACH(dep
, ret
->unit
->meta
.dependencies
[UNIT_REQUIRED_BY
], i
)
1235 if ((r
= transaction_add_job_and_dependencies(m
, type
, dep
, ret
, true, force
, NULL
)) < 0 && r
!= -EBADR
)
1239 /* JOB_VERIFY_STARTED, JOB_RELOAD require no dependency handling */
1251 int manager_add_job(Manager
*m
, JobType type
, Unit
*unit
, JobMode mode
, bool force
, Job
**_ret
) {
1256 assert(type
< _JOB_TYPE_MAX
);
1258 assert(mode
< _JOB_MODE_MAX
);
1260 log_debug("Trying to enqueue job %s/%s", unit_id(unit
), job_type_to_string(type
));
1262 if ((r
= transaction_add_job_and_dependencies(m
, type
, unit
, NULL
, true, force
, &ret
)) < 0) {
1263 transaction_abort(m
);
1267 if ((r
= transaction_activate(m
, mode
)) < 0)
1270 log_debug("Enqueued job %s/%s as %u", unit_id(unit
), job_type_to_string(type
), (unsigned) ret
->id
);
1278 int manager_add_job_by_name(Manager
*m
, JobType type
, const char *name
, JobMode mode
, bool force
, Job
**_ret
) {
1283 assert(type
< _JOB_TYPE_MAX
);
1285 assert(mode
< _JOB_MODE_MAX
);
1287 if ((r
= manager_load_unit(m
, name
, &unit
)) < 0)
1290 return manager_add_job(m
, type
, unit
, mode
, force
, _ret
);
1293 Job
*manager_get_job(Manager
*m
, uint32_t id
) {
1296 return hashmap_get(m
->jobs
, UINT32_TO_PTR(id
));
1299 Unit
*manager_get_unit(Manager
*m
, const char *name
) {
1303 return hashmap_get(m
->units
, name
);
1306 unsigned manager_dispatch_load_queue(Manager
*m
) {
1312 /* Make sure we are not run recursively */
1313 if (m
->dispatching_load_queue
)
1316 m
->dispatching_load_queue
= true;
1318 /* Dispatches the load queue. Takes a unit from the queue and
1319 * tries to load its data until the queue is empty */
1321 while ((meta
= m
->load_queue
)) {
1322 assert(meta
->in_load_queue
);
1324 unit_load(UNIT(meta
));
1328 m
->dispatching_load_queue
= false;
1332 int manager_load_unit(Manager
*m
, const char *path
, Unit
**_ret
) {
1341 /* This will load the service information files, but not actually
1342 * start any services or anything. */
1344 name
= file_name_from_path(path
);
1346 if ((ret
= manager_get_unit(m
, name
))) {
1351 if (!(ret
= unit_new(m
)))
1354 if (is_path(path
)) {
1355 if (!(ret
->meta
.fragment_path
= strdup(path
))) {
1361 if ((r
= unit_add_name(ret
, name
)) < 0) {
1366 unit_add_to_load_queue(ret
);
1367 unit_add_to_dbus_queue(ret
);
1369 manager_dispatch_load_queue(m
);
1371 *_ret
= unit_follow_merge(ret
);
1375 void manager_dump_jobs(Manager
*s
, FILE *f
, const char *prefix
) {
1382 HASHMAP_FOREACH(j
, s
->jobs
, i
)
1383 job_dump(j
, f
, prefix
);
1386 void manager_dump_units(Manager
*s
, FILE *f
, const char *prefix
) {
1394 HASHMAP_FOREACH_KEY(u
, t
, s
->units
, i
)
1395 if (unit_id(u
) == t
)
1396 unit_dump(u
, f
, prefix
);
1399 void manager_clear_jobs(Manager
*m
) {
1404 transaction_abort(m
);
1406 while ((j
= hashmap_first(m
->jobs
)))
1410 unsigned manager_dispatch_run_queue(Manager
*m
) {
1414 if (m
->dispatching_run_queue
)
1417 m
->dispatching_run_queue
= true;
1419 while ((j
= m
->run_queue
)) {
1420 assert(j
->installed
);
1421 assert(j
->in_run_queue
);
1423 job_run_and_invalidate(j
);
1427 m
->dispatching_run_queue
= false;
1431 unsigned manager_dispatch_dbus_queue(Manager
*m
) {
1438 if (m
->dispatching_dbus_queue
)
1441 m
->dispatching_dbus_queue
= true;
1443 while ((meta
= m
->dbus_unit_queue
)) {
1444 assert(meta
->in_dbus_queue
);
1446 bus_unit_send_change_signal(UNIT(meta
));
1450 while ((j
= m
->dbus_job_queue
)) {
1451 assert(j
->in_dbus_queue
);
1453 bus_job_send_change_signal(j
);
1457 m
->dispatching_dbus_queue
= false;
1461 static int manager_dispatch_sigchld(Manager
*m
) {
1470 /* First we call waitd() for a PID and do not reap the
1471 * zombie. That way we can still access /proc/$PID for
1472 * it while it is a zombie. */
1473 if (waitid(P_ALL
, 0, &si
, WEXITED
|WNOHANG
|WNOWAIT
) < 0) {
1475 if (errno
== ECHILD
)
1487 if (si
.si_code
== CLD_EXITED
|| si
.si_code
== CLD_KILLED
|| si
.si_code
== CLD_DUMPED
) {
1490 get_process_name(si
.si_pid
, &name
);
1491 log_debug("Got SIGCHLD for process %llu (%s)", (unsigned long long) si
.si_pid
, strna(name
));
1495 /* And now, we actually reap the zombie. */
1496 if (waitid(P_PID
, si
.si_pid
, &si
, WEXITED
) < 0) {
1503 if (si
.si_code
!= CLD_EXITED
&& si
.si_code
!= CLD_KILLED
&& si
.si_code
!= CLD_DUMPED
)
1506 log_debug("Child %llu died (code=%s, status=%i/%s)",
1507 (long long unsigned) si
.si_pid
,
1508 sigchld_code_to_string(si
.si_code
),
1510 strna(si
.si_code
== CLD_EXITED
? exit_status_to_string(si
.si_status
) : strsignal(si
.si_status
)));
1512 if (!(u
= hashmap_remove(m
->watch_pids
, UINT32_TO_PTR(si
.si_pid
))))
1515 log_debug("Child %llu belongs to %s", (long long unsigned) si
.si_pid
, unit_id(u
));
1517 UNIT_VTABLE(u
)->sigchld_event(u
, si
.si_pid
, si
.si_code
, si
.si_status
);
1523 static void manager_start_target(Manager
*m
, const char *name
) {
1526 if ((r
= manager_add_job_by_name(m
, JOB_START
, name
, JOB_REPLACE
, true, NULL
)) < 0)
1527 log_error("Failed to enqueue %s job: %s", name
, strerror(-r
));
1530 static int manager_process_signal_fd(Manager
*m
, bool *quit
) {
1532 struct signalfd_siginfo sfsi
;
1533 bool sigchld
= false;
1538 if ((n
= read(m
->signal_watch
.fd
, &sfsi
, sizeof(sfsi
))) != sizeof(sfsi
)) {
1543 if (errno
== EAGAIN
)
1549 switch (sfsi
.ssi_signo
) {
1558 if (m
->running_as
== MANAGER_INIT
) {
1559 manager_start_target(m
, SPECIAL_CTRL_ALT_DEL_TARGET
);
1568 if (m
->running_as
== MANAGER_INIT
)
1569 manager_start_target(m
, SPECIAL_KBREQUEST_TARGET
);
1571 /* This is a nop on non-init */
1575 if (m
->running_as
== MANAGER_INIT
)
1576 manager_start_target(m
, SPECIAL_SIGPWR_TARGET
);
1578 /* This is a nop on non-init */
1582 manager_dump_units(m
, stdout
, "\t");
1583 manager_dump_jobs(m
, stdout
, "\t");
1587 log_info("Got unhandled signal <%s>.", strsignal(sfsi
.ssi_signo
));
1592 return manager_dispatch_sigchld(m
);
1597 static int process_event(Manager
*m
, struct epoll_event
*ev
, bool *quit
) {
1604 assert(w
= ev
->data
.ptr
);
1610 /* An incoming signal? */
1611 if (ev
->events
!= EPOLLIN
)
1614 if ((r
= manager_process_signal_fd(m
, quit
)) < 0)
1621 /* Some fd event, to be dispatched to the units */
1622 UNIT_VTABLE(w
->data
.unit
)->fd_event(w
->data
.unit
, w
->fd
, ev
->events
, w
);
1629 /* Some timer event, to be dispatched to the units */
1630 if ((k
= read(w
->fd
, &v
, sizeof(v
))) != sizeof(v
)) {
1632 if (k
< 0 && (errno
== EINTR
|| errno
== EAGAIN
))
1635 return k
< 0 ? -errno
: -EIO
;
1638 UNIT_VTABLE(w
->data
.unit
)->timer_event(w
->data
.unit
, v
, w
);
1643 /* Some mount table change, intended for the mount subsystem */
1644 mount_fd_event(m
, ev
->events
);
1648 /* Some notification from udev, intended for the device subsystem */
1649 device_fd_event(m
, ev
->events
);
1652 case WATCH_DBUS_WATCH
:
1653 bus_watch_event(m
, w
, ev
->events
);
1656 case WATCH_DBUS_TIMEOUT
:
1657 bus_timeout_event(m
, w
, ev
->events
);
1661 assert_not_reached("Unknown epoll event type.");
1667 int manager_loop(Manager
*m
) {
1671 RATELIMIT_DEFINE(rl
, 1*USEC_PER_SEC
, 1000);
1676 struct epoll_event event
;
1679 if (!ratelimit_test(&rl
)) {
1680 /* Yay, something is going seriously wrong, pause a little */
1681 log_warning("Looping too fast. Throttling execution a little.");
1685 if (manager_dispatch_cleanup_queue(m
) > 0)
1688 if (manager_dispatch_load_queue(m
) > 0)
1691 if (manager_dispatch_run_queue(m
) > 0)
1694 if (bus_dispatch(m
) > 0)
1697 if (manager_dispatch_dbus_queue(m
) > 0)
1700 if ((n
= epoll_wait(m
->epoll_fd
, &event
, 1, -1)) < 0) {
1702 if (errno
== -EINTR
)
1710 if ((r
= process_event(m
, &event
, &quit
)) < 0)
1717 int manager_get_unit_from_dbus_path(Manager
*m
, const char *s
, Unit
**_u
) {
1725 if (!startswith(s
, "/org/freedesktop/systemd1/unit/"))
1728 if (!(n
= bus_path_unescape(s
+31)))
1731 u
= manager_get_unit(m
, n
);
1742 int manager_get_job_from_dbus_path(Manager
*m
, const char *s
, Job
**_j
) {
1751 if (!startswith(s
, "/org/freedesktop/systemd1/job/"))
1754 if ((r
= safe_atou(s
+ 30, &id
)) < 0)
1757 if (!(j
= manager_get_job(m
, id
)))
1765 static bool manager_utmp_good(Manager
*m
) {
1770 if ((r
= mount_path_is_mounted(m
, _PATH_UTMPX
)) <= 0) {
1773 log_warning("Failed to determine whether " _PATH_UTMPX
" is mounted: %s", strerror(-r
));
1781 void manager_write_utmp_reboot(Manager
*m
) {
1786 if (m
->utmp_reboot_written
)
1789 if (m
->running_as
!= MANAGER_INIT
)
1792 if (!manager_utmp_good(m
))
1795 if ((r
= utmp_put_reboot(m
->boot_timestamp
)) < 0) {
1797 if (r
!= -ENOENT
&& r
!= -EROFS
)
1798 log_warning("Failed to write utmp/wtmp: %s", strerror(-r
));
1803 m
->utmp_reboot_written
= true;
1806 void manager_write_utmp_runlevel(Manager
*m
, Unit
*u
) {
1812 if (u
->meta
.type
!= UNIT_TARGET
)
1815 if (m
->running_as
!= MANAGER_INIT
)
1818 if (!manager_utmp_good(m
))
1821 if ((runlevel
= target_get_runlevel(TARGET(u
))) <= 0)
1824 if ((r
= utmp_put_runlevel(0, runlevel
, 0)) < 0) {
1826 if (r
!= -ENOENT
&& r
!= -EROFS
)
1827 log_warning("Failed to write utmp/wtmp: %s", strerror(-r
));
1831 static const char* const manager_running_as_table
[_MANAGER_RUNNING_AS_MAX
] = {
1832 [MANAGER_INIT
] = "init",
1833 [MANAGER_SYSTEM
] = "system",
1834 [MANAGER_SESSION
] = "session"
1837 DEFINE_STRING_TABLE_LOOKUP(manager_running_as
, ManagerRunningAs
);