1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
25 #include <sys/epoll.h>
27 #include <sys/signalfd.h>
32 #include <sys/reboot.h>
33 #include <sys/ioctl.h>
35 #include <libcgroup.h>
38 #include <sys/types.h>
47 #include "ratelimit.h"
49 #include "mount-setup.h"
50 #include "utmp-wtmp.h"
51 #include "unit-name.h"
52 #include "dbus-unit.h"
55 #include "path-lookup.h"
58 /* As soon as 16 units are in our GC queue, make sure to run a gc sweep */
59 #define GC_QUEUE_ENTRIES_MAX 16
61 /* As soon as 5s passed since a unit was added to our GC queue, make sure to run a gc sweep */
62 #define GC_QUEUE_USEC_MAX (10*USEC_PER_SEC)
64 /* Where clients shall send notification messages to */
65 #define NOTIFY_SOCKET "/org/freedesktop/systemd1/notify"
67 static int manager_setup_notify(Manager
*m
) {
70 struct sockaddr_un un
;
72 struct epoll_event ev
;
77 m
->notify_watch
.type
= WATCH_NOTIFY
;
78 if ((m
->notify_watch
.fd
= socket(AF_UNIX
, SOCK_DGRAM
|SOCK_CLOEXEC
|SOCK_NONBLOCK
, 0)) < 0) {
79 log_error("Failed to allocate notification socket: %m");
84 sa
.sa
.sa_family
= AF_UNIX
;
86 if (m
->running_as
== MANAGER_SESSION
)
87 snprintf(sa
.un
.sun_path
+1, sizeof(sa
.un
.sun_path
)-1, NOTIFY_SOCKET
"/%llu", random_ull());
89 strncpy(sa
.un
.sun_path
+1, NOTIFY_SOCKET
, sizeof(sa
.un
.sun_path
)-1);
91 if (bind(m
->notify_watch
.fd
, &sa
.sa
, sizeof(sa
)) < 0) {
92 log_error("bind() failed: %m");
96 if (setsockopt(m
->notify_watch
.fd
, SOL_SOCKET
, SO_PASSCRED
, &one
, sizeof(one
)) < 0) {
97 log_error("SO_PASSCRED failed: %m");
103 ev
.data
.ptr
= &m
->notify_watch
;
105 if (epoll_ctl(m
->epoll_fd
, EPOLL_CTL_ADD
, m
->notify_watch
.fd
, &ev
) < 0)
108 if (!(m
->notify_socket
= strdup(sa
.un
.sun_path
+1)))
114 static int enable_special_signals(Manager
*m
) {
119 /* Enable that we get SIGINT on control-alt-del */
120 if (reboot(RB_DISABLE_CAD
) < 0)
121 log_warning("Failed to enable ctrl-alt-del handling: %m");
123 if ((fd
= open_terminal("/dev/tty0", O_RDWR
|O_NOCTTY
)) < 0)
124 log_warning("Failed to open /dev/tty0: %m");
126 /* Enable that we get SIGWINCH on kbrequest */
127 if (ioctl(fd
, KDSIGACCEPT
, SIGWINCH
) < 0)
128 log_warning("Failed to enable kbrequest handling: %s", strerror(errno
));
130 close_nointr_nofail(fd
);
136 static int manager_setup_signals(Manager
*m
) {
138 struct epoll_event ev
;
143 /* We are not interested in SIGSTOP and friends. */
145 sa
.sa_handler
= SIG_DFL
;
146 sa
.sa_flags
= SA_NOCLDSTOP
|SA_RESTART
;
147 assert_se(sigaction(SIGCHLD
, &sa
, NULL
) == 0);
149 assert_se(sigemptyset(&mask
) == 0);
151 sigset_add_many(&mask
,
152 SIGCHLD
, /* Child died */
153 SIGTERM
, /* Reexecute daemon */
154 SIGHUP
, /* Reload configuration */
155 SIGUSR1
, /* systemd/upstart: reconnect to D-Bus */
156 SIGUSR2
, /* systemd: dump status */
157 SIGINT
, /* Kernel sends us this on control-alt-del */
158 SIGWINCH
, /* Kernel sends us this on kbrequest (alt-arrowup) */
159 SIGPWR
, /* Some kernel drivers and upsd send us this on power failure */
160 SIGRTMIN
+0, /* systemd: start default.target */
161 SIGRTMIN
+1, /* systemd: start rescue.target */
162 SIGRTMIN
+2, /* systemd: isolate emergency.target */
163 SIGRTMIN
+3, /* systemd: start halt.target */
164 SIGRTMIN
+4, /* systemd: start poweroff.target */
165 SIGRTMIN
+5, /* systemd: start reboot.target */
167 assert_se(sigprocmask(SIG_SETMASK
, &mask
, NULL
) == 0);
169 m
->signal_watch
.type
= WATCH_SIGNAL
;
170 if ((m
->signal_watch
.fd
= signalfd(-1, &mask
, SFD_NONBLOCK
|SFD_CLOEXEC
)) < 0)
175 ev
.data
.ptr
= &m
->signal_watch
;
177 if (epoll_ctl(m
->epoll_fd
, EPOLL_CTL_ADD
, m
->signal_watch
.fd
, &ev
) < 0)
180 if (m
->running_as
== MANAGER_INIT
)
181 return enable_special_signals(m
);
186 int manager_new(ManagerRunningAs running_as
, bool confirm_spawn
, Manager
**_m
) {
192 assert(running_as
>= 0);
193 assert(running_as
< _MANAGER_RUNNING_AS_MAX
);
195 if (!(m
= new0(Manager
, 1)))
198 timestamp_get(&m
->startup_timestamp
);
200 m
->running_as
= running_as
;
201 m
->confirm_spawn
= confirm_spawn
;
202 m
->name_data_slot
= -1;
203 m
->exit_code
= _MANAGER_EXIT_CODE_INVALID
;
204 m
->pin_cgroupfs_fd
= -1;
206 m
->signal_watch
.fd
= m
->mount_watch
.fd
= m
->udev_watch
.fd
= m
->epoll_fd
= m
->dev_autofs_fd
= -1;
207 m
->current_job_id
= 1; /* start as id #1, so that we can leave #0 around as "null-like" value */
209 if (!(m
->environment
= strv_copy(environ
)))
212 if (!(m
->units
= hashmap_new(string_hash_func
, string_compare_func
)))
215 if (!(m
->jobs
= hashmap_new(trivial_hash_func
, trivial_compare_func
)))
218 if (!(m
->transaction_jobs
= hashmap_new(trivial_hash_func
, trivial_compare_func
)))
221 if (!(m
->watch_pids
= hashmap_new(trivial_hash_func
, trivial_compare_func
)))
224 if (!(m
->cgroup_bondings
= hashmap_new(string_hash_func
, string_compare_func
)))
227 if (!(m
->watch_bus
= hashmap_new(string_hash_func
, string_compare_func
)))
230 if ((m
->epoll_fd
= epoll_create1(EPOLL_CLOEXEC
)) < 0)
233 if ((r
= lookup_paths_init(&m
->lookup_paths
, m
->running_as
)) < 0)
236 if ((r
= manager_setup_signals(m
)) < 0)
239 if ((r
= manager_setup_cgroup(m
)) < 0)
242 if ((r
= manager_setup_notify(m
)) < 0)
245 /* Try to connect to the busses, if possible. */
246 if ((r
= bus_init(m
)) < 0)
249 if (asprintf(&p
, "%s/%s", m
->cgroup_mount_point
, m
->cgroup_hierarchy
) < 0) {
254 m
->pin_cgroupfs_fd
= open(p
, O_RDONLY
|O_CLOEXEC
|O_DIRECTORY
|O_NOCTTY
|O_NONBLOCK
);
265 static unsigned manager_dispatch_cleanup_queue(Manager
*m
) {
271 while ((meta
= m
->cleanup_queue
)) {
272 assert(meta
->in_cleanup_queue
);
274 unit_free(UNIT(meta
));
282 GC_OFFSET_IN_PATH
, /* This one is on the path we were travelling */
283 GC_OFFSET_UNSURE
, /* No clue */
284 GC_OFFSET_GOOD
, /* We still need this unit */
285 GC_OFFSET_BAD
, /* We don't need this unit anymore */
289 static void unit_gc_sweep(Unit
*u
, unsigned gc_marker
) {
296 if (u
->meta
.gc_marker
== gc_marker
+ GC_OFFSET_GOOD
||
297 u
->meta
.gc_marker
== gc_marker
+ GC_OFFSET_BAD
||
298 u
->meta
.gc_marker
== gc_marker
+ GC_OFFSET_IN_PATH
)
301 if (u
->meta
.in_cleanup_queue
)
304 if (unit_check_gc(u
))
307 u
->meta
.gc_marker
= gc_marker
+ GC_OFFSET_IN_PATH
;
311 SET_FOREACH(other
, u
->meta
.dependencies
[UNIT_REFERENCED_BY
], i
) {
312 unit_gc_sweep(other
, gc_marker
);
314 if (other
->meta
.gc_marker
== gc_marker
+ GC_OFFSET_GOOD
)
317 if (other
->meta
.gc_marker
!= gc_marker
+ GC_OFFSET_BAD
)
324 /* We were unable to find anything out about this entry, so
325 * let's investigate it later */
326 u
->meta
.gc_marker
= gc_marker
+ GC_OFFSET_UNSURE
;
327 unit_add_to_gc_queue(u
);
331 /* We definitely know that this one is not useful anymore, so
332 * let's mark it for deletion */
333 u
->meta
.gc_marker
= gc_marker
+ GC_OFFSET_BAD
;
334 unit_add_to_cleanup_queue(u
);
338 u
->meta
.gc_marker
= gc_marker
+ GC_OFFSET_GOOD
;
341 static unsigned manager_dispatch_gc_queue(Manager
*m
) {
348 if ((m
->n_in_gc_queue
< GC_QUEUE_ENTRIES_MAX
) &&
349 (m
->gc_queue_timestamp
<= 0 ||
350 (m
->gc_queue_timestamp
+ GC_QUEUE_USEC_MAX
) > now(CLOCK_MONOTONIC
)))
353 log_debug("Running GC...");
355 m
->gc_marker
+= _GC_OFFSET_MAX
;
356 if (m
->gc_marker
+ _GC_OFFSET_MAX
<= _GC_OFFSET_MAX
)
359 gc_marker
= m
->gc_marker
;
361 while ((meta
= m
->gc_queue
)) {
362 assert(meta
->in_gc_queue
);
364 unit_gc_sweep(UNIT(meta
), gc_marker
);
366 LIST_REMOVE(Meta
, gc_queue
, m
->gc_queue
, meta
);
367 meta
->in_gc_queue
= false;
371 if (meta
->gc_marker
== gc_marker
+ GC_OFFSET_BAD
||
372 meta
->gc_marker
== gc_marker
+ GC_OFFSET_UNSURE
) {
373 log_debug("Collecting %s", meta
->id
);
374 meta
->gc_marker
= gc_marker
+ GC_OFFSET_BAD
;
375 unit_add_to_cleanup_queue(UNIT(meta
));
379 m
->n_in_gc_queue
= 0;
380 m
->gc_queue_timestamp
= 0;
385 static void manager_clear_jobs_and_units(Manager
*m
) {
391 while ((j
= hashmap_first(m
->transaction_jobs
)))
394 while ((u
= hashmap_first(m
->units
)))
397 manager_dispatch_cleanup_queue(m
);
399 assert(!m
->load_queue
);
400 assert(!m
->run_queue
);
401 assert(!m
->dbus_unit_queue
);
402 assert(!m
->dbus_job_queue
);
403 assert(!m
->cleanup_queue
);
404 assert(!m
->gc_queue
);
406 assert(hashmap_isempty(m
->transaction_jobs
));
407 assert(hashmap_isempty(m
->jobs
));
408 assert(hashmap_isempty(m
->units
));
411 void manager_free(Manager
*m
) {
416 manager_clear_jobs_and_units(m
);
418 for (c
= 0; c
< _UNIT_TYPE_MAX
; c
++)
419 if (unit_vtable
[c
]->shutdown
)
420 unit_vtable
[c
]->shutdown(m
);
422 /* If we reexecute ourselves, we keep the root cgroup
424 manager_shutdown_cgroup(m
, m
->exit_code
!= MANAGER_REEXECUTE
);
428 hashmap_free(m
->units
);
429 hashmap_free(m
->jobs
);
430 hashmap_free(m
->transaction_jobs
);
431 hashmap_free(m
->watch_pids
);
432 hashmap_free(m
->watch_bus
);
434 if (m
->epoll_fd
>= 0)
435 close_nointr_nofail(m
->epoll_fd
);
436 if (m
->signal_watch
.fd
>= 0)
437 close_nointr_nofail(m
->signal_watch
.fd
);
438 if (m
->notify_watch
.fd
>= 0)
439 close_nointr_nofail(m
->notify_watch
.fd
);
441 free(m
->notify_socket
);
443 lookup_paths_free(&m
->lookup_paths
);
444 strv_free(m
->environment
);
446 free(m
->cgroup_controller
);
447 free(m
->cgroup_hierarchy
);
448 free(m
->cgroup_mount_point
);
450 hashmap_free(m
->cgroup_bondings
);
452 if (m
->pin_cgroupfs_fd
>= 0)
453 close_nointr_nofail(m
->pin_cgroupfs_fd
);
458 int manager_enumerate(Manager
*m
) {
464 /* Let's ask every type to load all units from disk/kernel
465 * that it might know */
466 for (c
= 0; c
< _UNIT_TYPE_MAX
; c
++)
467 if (unit_vtable
[c
]->enumerate
)
468 if ((q
= unit_vtable
[c
]->enumerate(m
)) < 0)
471 manager_dispatch_load_queue(m
);
475 int manager_coldplug(Manager
*m
) {
483 /* Then, let's set up their initial state. */
484 HASHMAP_FOREACH_KEY(u
, k
, m
->units
, i
) {
490 if ((q
= unit_coldplug(u
)) < 0)
497 int manager_startup(Manager
*m
, FILE *serialization
, FDSet
*fds
) {
502 /* First, enumerate what we can from all config files */
503 r
= manager_enumerate(m
);
505 /* Second, deserialize if there is something to deserialize */
507 if ((q
= manager_deserialize(m
, serialization
, fds
)) < 0)
510 /* Third, fire things up! */
511 if ((q
= manager_coldplug(m
)) < 0)
514 /* Now that the initial devices are available, let's see if we
515 * can write the utmp file */
516 manager_write_utmp_reboot(m
);
521 static void transaction_delete_job(Manager
*m
, Job
*j
, bool delete_dependencies
) {
525 /* Deletes one job from the transaction */
527 manager_transaction_unlink_job(m
, j
, delete_dependencies
);
533 static void transaction_delete_unit(Manager
*m
, Unit
*u
) {
536 /* Deletes all jobs associated with a certain unit from the
539 while ((j
= hashmap_get(m
->transaction_jobs
, u
)))
540 transaction_delete_job(m
, j
, true);
543 static void transaction_clean_dependencies(Manager
*m
) {
549 /* Drops all dependencies of all installed jobs */
551 HASHMAP_FOREACH(j
, m
->jobs
, i
) {
552 while (j
->subject_list
)
553 job_dependency_free(j
->subject_list
);
554 while (j
->object_list
)
555 job_dependency_free(j
->object_list
);
558 assert(!m
->transaction_anchor
);
561 static void transaction_abort(Manager
*m
) {
566 while ((j
= hashmap_first(m
->transaction_jobs
)))
568 transaction_delete_job(m
, j
, true);
572 assert(hashmap_isempty(m
->transaction_jobs
));
574 transaction_clean_dependencies(m
);
577 static void transaction_find_jobs_that_matter_to_anchor(Manager
*m
, Job
*j
, unsigned generation
) {
582 /* A recursive sweep through the graph that marks all units
583 * that matter to the anchor job, i.e. are directly or
584 * indirectly a dependency of the anchor job via paths that
585 * are fully marked as mattering. */
590 l
= m
->transaction_anchor
;
592 LIST_FOREACH(subject
, l
, l
) {
594 /* This link does not matter */
598 /* This unit has already been marked */
599 if (l
->object
->generation
== generation
)
602 l
->object
->matters_to_anchor
= true;
603 l
->object
->generation
= generation
;
605 transaction_find_jobs_that_matter_to_anchor(m
, l
->object
, generation
);
609 static void transaction_merge_and_delete_job(Manager
*m
, Job
*j
, Job
*other
, JobType t
) {
610 JobDependency
*l
, *last
;
614 assert(j
->unit
== other
->unit
);
615 assert(!j
->installed
);
617 /* Merges 'other' into 'j' and then deletes j. */
620 j
->state
= JOB_WAITING
;
621 j
->override
= j
->override
|| other
->override
;
623 j
->matters_to_anchor
= j
->matters_to_anchor
|| other
->matters_to_anchor
;
625 /* Patch us in as new owner of the JobDependency objects */
627 LIST_FOREACH(subject
, l
, other
->subject_list
) {
628 assert(l
->subject
== other
);
633 /* Merge both lists */
635 last
->subject_next
= j
->subject_list
;
637 j
->subject_list
->subject_prev
= last
;
638 j
->subject_list
= other
->subject_list
;
641 /* Patch us in as new owner of the JobDependency objects */
643 LIST_FOREACH(object
, l
, other
->object_list
) {
644 assert(l
->object
== other
);
649 /* Merge both lists */
651 last
->object_next
= j
->object_list
;
653 j
->object_list
->object_prev
= last
;
654 j
->object_list
= other
->object_list
;
657 /* Kill the other job */
658 other
->subject_list
= NULL
;
659 other
->object_list
= NULL
;
660 transaction_delete_job(m
, other
, true);
663 static int delete_one_unmergeable_job(Manager
*m
, Job
*j
) {
668 /* Tries to delete one item in the linked list
669 * j->transaction_next->transaction_next->... that conflicts
670 * whith another one, in an attempt to make an inconsistent
671 * transaction work. */
673 /* We rely here on the fact that if a merged with b does not
674 * merge with c, either a or b merge with c neither */
675 LIST_FOREACH(transaction
, j
, j
)
676 LIST_FOREACH(transaction
, k
, j
->transaction_next
) {
679 /* Is this one mergeable? Then skip it */
680 if (job_type_is_mergeable(j
->type
, k
->type
))
683 /* Ok, we found two that conflict, let's see if we can
684 * drop one of them */
685 if (!j
->matters_to_anchor
)
687 else if (!k
->matters_to_anchor
)
692 /* Ok, we can drop one, so let's do so. */
693 log_debug("Trying to fix job merging by deleting job %s/%s", d
->unit
->meta
.id
, job_type_to_string(d
->type
));
694 transaction_delete_job(m
, d
, true);
701 static int transaction_merge_jobs(Manager
*m
) {
708 /* First step, check whether any of the jobs for one specific
709 * task conflict. If so, try to drop one of them. */
710 HASHMAP_FOREACH(j
, m
->transaction_jobs
, i
) {
715 LIST_FOREACH(transaction
, k
, j
->transaction_next
) {
716 if ((r
= job_type_merge(&t
, k
->type
)) >= 0)
719 /* OK, we could not merge all jobs for this
720 * action. Let's see if we can get rid of one
723 if ((r
= delete_one_unmergeable_job(m
, j
)) >= 0)
724 /* Ok, we managed to drop one, now
725 * let's ask our callers to call us
726 * again after garbage collecting */
729 /* We couldn't merge anything. Failure */
734 /* Second step, merge the jobs. */
735 HASHMAP_FOREACH(j
, m
->transaction_jobs
, i
) {
739 /* Merge all transactions */
740 LIST_FOREACH(transaction
, k
, j
->transaction_next
)
741 assert_se(job_type_merge(&t
, k
->type
) == 0);
743 /* If an active job is mergeable, merge it too */
744 if (j
->unit
->meta
.job
)
745 job_type_merge(&t
, j
->unit
->meta
.job
->type
); /* Might fail. Which is OK */
747 while ((k
= j
->transaction_next
)) {
749 transaction_merge_and_delete_job(m
, k
, j
, t
);
752 transaction_merge_and_delete_job(m
, j
, k
, t
);
755 assert(!j
->transaction_next
);
756 assert(!j
->transaction_prev
);
762 static void transaction_drop_redundant(Manager
*m
) {
767 /* Goes through the transaction and removes all jobs that are
776 HASHMAP_FOREACH(j
, m
->transaction_jobs
, i
) {
777 bool changes_something
= false;
780 LIST_FOREACH(transaction
, k
, j
) {
782 if (!job_is_anchor(k
) &&
783 job_type_is_redundant(k
->type
, unit_active_state(k
->unit
)))
786 changes_something
= true;
790 if (changes_something
)
793 log_debug("Found redundant job %s/%s, dropping.", j
->unit
->meta
.id
, job_type_to_string(j
->type
));
794 transaction_delete_job(m
, j
, false);
802 static bool unit_matters_to_anchor(Unit
*u
, Job
*j
) {
804 assert(!j
->transaction_prev
);
806 /* Checks whether at least one of the jobs for this unit
807 * matters to the anchor. */
809 LIST_FOREACH(transaction
, j
, j
)
810 if (j
->matters_to_anchor
)
816 static int transaction_verify_order_one(Manager
*m
, Job
*j
, Job
*from
, unsigned generation
) {
823 assert(!j
->transaction_prev
);
825 /* Does a recursive sweep through the ordering graph, looking
826 * for a cycle. If we find cycle we try to break it. */
828 /* Have we seen this before? */
829 if (j
->generation
== generation
) {
832 /* If the marker is NULL we have been here already and
833 * decided the job was loop-free from here. Hence
834 * shortcut things and return right-away. */
838 /* So, the marker is not NULL and we already have been
839 * here. We have a cycle. Let's try to break it. We go
840 * backwards in our path and try to find a suitable
841 * job to remove. We use the marker to find our way
842 * back, since smart how we are we stored our way back
844 log_debug("Found ordering cycle on %s/%s", j
->unit
->meta
.id
, job_type_to_string(j
->type
));
846 for (k
= from
; k
; k
= ((k
->generation
== generation
&& k
->marker
!= k
) ? k
->marker
: NULL
)) {
848 log_debug("Walked on cycle path to %s/%s", k
->unit
->meta
.id
, job_type_to_string(k
->type
));
851 !unit_matters_to_anchor(k
->unit
, k
)) {
852 /* Ok, we can drop this one, so let's
854 log_debug("Breaking order cycle by deleting job %s/%s", k
->unit
->meta
.id
, job_type_to_string(k
->type
));
855 transaction_delete_unit(m
, k
->unit
);
859 /* Check if this in fact was the beginning of
865 log_debug("Unable to break cycle");
870 /* Make the marker point to where we come from, so that we can
871 * find our way backwards if we want to break a cycle. We use
872 * a special marker for the beginning: we point to
874 j
->marker
= from
? from
: j
;
875 j
->generation
= generation
;
877 /* We assume that the the dependencies are bidirectional, and
878 * hence can ignore UNIT_AFTER */
879 SET_FOREACH(u
, j
->unit
->meta
.dependencies
[UNIT_BEFORE
], i
) {
882 /* Is there a job for this unit? */
883 if (!(o
= hashmap_get(m
->transaction_jobs
, u
)))
885 /* Ok, there is no job for this in the
886 * transaction, but maybe there is already one
888 if (!(o
= u
->meta
.job
))
891 if ((r
= transaction_verify_order_one(m
, o
, j
, generation
)) < 0)
895 /* Ok, let's backtrack, and remember that this entry is not on
896 * our path anymore. */
902 static int transaction_verify_order(Manager
*m
, unsigned *generation
) {
911 /* Check if the ordering graph is cyclic. If it is, try to fix
912 * that up by dropping one of the jobs. */
916 HASHMAP_FOREACH(j
, m
->transaction_jobs
, i
)
917 if ((r
= transaction_verify_order_one(m
, j
, NULL
, g
)) < 0)
923 static void transaction_collect_garbage(Manager
*m
) {
928 /* Drop jobs that are not required by any other job */
936 HASHMAP_FOREACH(j
, m
->transaction_jobs
, i
) {
940 log_debug("Garbage collecting job %s/%s", j
->unit
->meta
.id
, job_type_to_string(j
->type
));
941 transaction_delete_job(m
, j
, true);
949 static int transaction_is_destructive(Manager
*m
) {
955 /* Checks whether applying this transaction means that
956 * existing jobs would be replaced */
958 HASHMAP_FOREACH(j
, m
->transaction_jobs
, i
) {
961 assert(!j
->transaction_prev
);
962 assert(!j
->transaction_next
);
964 if (j
->unit
->meta
.job
&&
965 j
->unit
->meta
.job
!= j
&&
966 !job_type_is_superset(j
->type
, j
->unit
->meta
.job
->type
))
973 static void transaction_minimize_impact(Manager
*m
) {
977 /* Drops all unnecessary jobs that reverse already active jobs
978 * or that stop a running service. */
986 HASHMAP_FOREACH(j
, m
->transaction_jobs
, i
) {
987 LIST_FOREACH(transaction
, j
, j
) {
988 bool stops_running_service
, changes_existing_job
;
990 /* If it matters, we shouldn't drop it */
991 if (j
->matters_to_anchor
)
994 /* Would this stop a running service?
995 * Would this change an existing job?
996 * If so, let's drop this entry */
998 stops_running_service
=
999 j
->type
== JOB_STOP
&& UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(j
->unit
));
1001 changes_existing_job
=
1002 j
->unit
->meta
.job
&& job_type_is_conflicting(j
->type
, j
->unit
->meta
.job
->state
);
1004 if (!stops_running_service
&& !changes_existing_job
)
1007 if (stops_running_service
)
1008 log_debug("%s/%s would stop a running service.", j
->unit
->meta
.id
, job_type_to_string(j
->type
));
1010 if (changes_existing_job
)
1011 log_debug("%s/%s would change existing job.", j
->unit
->meta
.id
, job_type_to_string(j
->type
));
1013 /* Ok, let's get rid of this */
1014 log_debug("Deleting %s/%s to minimize impact.", j
->unit
->meta
.id
, job_type_to_string(j
->type
));
1016 transaction_delete_job(m
, j
, true);
1028 static int transaction_apply(Manager
*m
) {
1033 /* Moves the transaction jobs to the set of active jobs */
1035 HASHMAP_FOREACH(j
, m
->transaction_jobs
, i
) {
1037 assert(!j
->transaction_prev
);
1038 assert(!j
->transaction_next
);
1043 if ((r
= hashmap_put(m
->jobs
, UINT32_TO_PTR(j
->id
), j
)) < 0)
1047 while ((j
= hashmap_steal_first(m
->transaction_jobs
))) {
1051 if (j
->unit
->meta
.job
)
1052 job_free(j
->unit
->meta
.job
);
1054 j
->unit
->meta
.job
= j
;
1055 j
->installed
= true;
1057 /* We're fully installed. Now let's free data we don't
1060 assert(!j
->transaction_next
);
1061 assert(!j
->transaction_prev
);
1063 job_add_to_run_queue(j
);
1064 job_add_to_dbus_queue(j
);
1067 /* As last step, kill all remaining job dependencies. */
1068 transaction_clean_dependencies(m
);
1074 HASHMAP_FOREACH(j
, m
->transaction_jobs
, i
) {
1078 hashmap_remove(m
->jobs
, UINT32_TO_PTR(j
->id
));
1084 static int transaction_activate(Manager
*m
, JobMode mode
) {
1086 unsigned generation
= 1;
1090 /* This applies the changes recorded in transaction_jobs to
1091 * the actual list of jobs, if possible. */
1093 /* First step: figure out which jobs matter */
1094 transaction_find_jobs_that_matter_to_anchor(m
, NULL
, generation
++);
1096 /* Second step: Try not to stop any running services if
1097 * we don't have to. Don't try to reverse running
1098 * jobs if we don't have to. */
1099 transaction_minimize_impact(m
);
1101 /* Third step: Drop redundant jobs */
1102 transaction_drop_redundant(m
);
1105 /* Fourth step: Let's remove unneeded jobs that might
1107 transaction_collect_garbage(m
);
1109 /* Fifth step: verify order makes sense and correct
1110 * cycles if necessary and possible */
1111 if ((r
= transaction_verify_order(m
, &generation
)) >= 0)
1115 log_debug("Requested transaction contains an unfixable cyclic ordering dependency: %s", strerror(-r
));
1119 /* Let's see if the resulting transaction ordering
1120 * graph is still cyclic... */
1124 /* Sixth step: let's drop unmergeable entries if
1125 * necessary and possible, merge entries we can
1127 if ((r
= transaction_merge_jobs(m
)) >= 0)
1131 log_debug("Requested transaction contains unmergable jobs: %s", strerror(-r
));
1135 /* Seventh step: an entry got dropped, let's garbage
1136 * collect its dependencies. */
1137 transaction_collect_garbage(m
);
1139 /* Let's see if the resulting transaction still has
1140 * unmergeable entries ... */
1143 /* Eights step: Drop redundant jobs again, if the merging now allows us to drop more. */
1144 transaction_drop_redundant(m
);
1146 /* Ninth step: check whether we can actually apply this */
1147 if (mode
== JOB_FAIL
)
1148 if ((r
= transaction_is_destructive(m
)) < 0) {
1149 log_debug("Requested transaction contradicts existing jobs: %s", strerror(-r
));
1153 /* Tenth step: apply changes */
1154 if ((r
= transaction_apply(m
)) < 0) {
1155 log_debug("Failed to apply transaction: %s", strerror(-r
));
1159 assert(hashmap_isempty(m
->transaction_jobs
));
1160 assert(!m
->transaction_anchor
);
1165 transaction_abort(m
);
1169 static Job
* transaction_add_one_job(Manager
*m
, JobType type
, Unit
*unit
, bool override
, bool *is_new
) {
1176 /* Looks for an axisting prospective job and returns that. If
1177 * it doesn't exist it is created and added to the prospective
1180 f
= hashmap_get(m
->transaction_jobs
, unit
);
1182 LIST_FOREACH(transaction
, j
, f
) {
1183 assert(j
->unit
== unit
);
1185 if (j
->type
== type
) {
1192 if (unit
->meta
.job
&& unit
->meta
.job
->type
== type
)
1194 else if (!(j
= job_new(m
, type
, unit
)))
1199 j
->matters_to_anchor
= false;
1200 j
->override
= override
;
1202 LIST_PREPEND(Job
, transaction
, f
, j
);
1204 if ((r
= hashmap_replace(m
->transaction_jobs
, unit
, f
)) < 0) {
1212 log_debug("Added job %s/%s to transaction.", unit
->meta
.id
, job_type_to_string(type
));
1217 void manager_transaction_unlink_job(Manager
*m
, Job
*j
, bool delete_dependencies
) {
1221 if (j
->transaction_prev
)
1222 j
->transaction_prev
->transaction_next
= j
->transaction_next
;
1223 else if (j
->transaction_next
)
1224 hashmap_replace(m
->transaction_jobs
, j
->unit
, j
->transaction_next
);
1226 hashmap_remove_value(m
->transaction_jobs
, j
->unit
, j
);
1228 if (j
->transaction_next
)
1229 j
->transaction_next
->transaction_prev
= j
->transaction_prev
;
1231 j
->transaction_prev
= j
->transaction_next
= NULL
;
1233 while (j
->subject_list
)
1234 job_dependency_free(j
->subject_list
);
1236 while (j
->object_list
) {
1237 Job
*other
= j
->object_list
->matters
? j
->object_list
->subject
: NULL
;
1239 job_dependency_free(j
->object_list
);
1241 if (other
&& delete_dependencies
) {
1242 log_debug("Deleting job %s/%s as dependency of job %s/%s",
1243 other
->unit
->meta
.id
, job_type_to_string(other
->type
),
1244 j
->unit
->meta
.id
, job_type_to_string(j
->type
));
1245 transaction_delete_job(m
, other
, delete_dependencies
);
1250 static int transaction_add_job_and_dependencies(
1265 assert(type
< _JOB_TYPE_MAX
);
1268 if (unit
->meta
.load_state
!= UNIT_LOADED
)
1271 if (!unit_job_is_applicable(unit
, type
))
1274 /* First add the job. */
1275 if (!(ret
= transaction_add_one_job(m
, type
, unit
, override
, &is_new
)))
1278 /* Then, add a link to the job. */
1279 if (!job_dependency_new(by
, ret
, matters
))
1283 /* Finally, recursively add in all dependencies. */
1284 if (type
== JOB_START
|| type
== JOB_RELOAD_OR_START
) {
1285 SET_FOREACH(dep
, ret
->unit
->meta
.dependencies
[UNIT_REQUIRES
], i
)
1286 if ((r
= transaction_add_job_and_dependencies(m
, JOB_START
, dep
, ret
, true, override
, NULL
)) < 0 && r
!= -EBADR
)
1289 SET_FOREACH(dep
, ret
->unit
->meta
.dependencies
[UNIT_REQUIRES_OVERRIDABLE
], i
)
1290 if ((r
= transaction_add_job_and_dependencies(m
, JOB_START
, dep
, ret
, !override
, override
, NULL
)) < 0 && r
!= -EBADR
)
1291 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep
->meta
.id
, strerror(-r
));
1293 SET_FOREACH(dep
, ret
->unit
->meta
.dependencies
[UNIT_WANTS
], i
)
1294 if ((r
= transaction_add_job_and_dependencies(m
, JOB_START
, dep
, ret
, false, false, NULL
)) < 0)
1295 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep
->meta
.id
, strerror(-r
));
1297 SET_FOREACH(dep
, ret
->unit
->meta
.dependencies
[UNIT_REQUISITE
], i
)
1298 if ((r
= transaction_add_job_and_dependencies(m
, JOB_VERIFY_ACTIVE
, dep
, ret
, true, override
, NULL
)) < 0 && r
!= -EBADR
)
1301 SET_FOREACH(dep
, ret
->unit
->meta
.dependencies
[UNIT_REQUISITE_OVERRIDABLE
], i
)
1302 if ((r
= transaction_add_job_and_dependencies(m
, JOB_VERIFY_ACTIVE
, dep
, ret
, !override
, override
, NULL
)) < 0 && r
!= -EBADR
)
1303 log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep
->meta
.id
, strerror(-r
));
1305 SET_FOREACH(dep
, ret
->unit
->meta
.dependencies
[UNIT_CONFLICTS
], i
)
1306 if ((r
= transaction_add_job_and_dependencies(m
, JOB_STOP
, dep
, ret
, true, override
, NULL
)) < 0 && r
!= -EBADR
)
1309 } else if (type
== JOB_STOP
|| type
== JOB_RESTART
|| type
== JOB_TRY_RESTART
) {
1311 SET_FOREACH(dep
, ret
->unit
->meta
.dependencies
[UNIT_REQUIRED_BY
], i
)
1312 if ((r
= transaction_add_job_and_dependencies(m
, type
, dep
, ret
, true, override
, NULL
)) < 0 && r
!= -EBADR
)
1316 /* JOB_VERIFY_STARTED, JOB_RELOAD require no dependency handling */
1328 static int transaction_add_isolate_jobs(Manager
*m
) {
1336 HASHMAP_FOREACH_KEY(u
, k
, m
->units
, i
) {
1338 /* ignore aliases */
1339 if (u
->meta
.id
!= k
)
1342 if (UNIT_VTABLE(u
)->no_isolate
)
1345 /* No need to stop inactive jobs */
1346 if (unit_active_state(u
) == UNIT_INACTIVE
)
1349 /* Is there already something listed for this? */
1350 if (hashmap_get(m
->transaction_jobs
, u
))
1353 if ((r
= transaction_add_job_and_dependencies(m
, JOB_STOP
, u
, NULL
, true, false, NULL
)) < 0)
1354 log_warning("Cannot add isolate job for unit %s, ignoring: %s", u
->meta
.id
, strerror(-r
));
1360 int manager_add_job(Manager
*m
, JobType type
, Unit
*unit
, JobMode mode
, bool override
, Job
**_ret
) {
1365 assert(type
< _JOB_TYPE_MAX
);
1367 assert(mode
< _JOB_MODE_MAX
);
1369 if (mode
== JOB_ISOLATE
&& type
!= JOB_START
)
1372 log_debug("Trying to enqueue job %s/%s", unit
->meta
.id
, job_type_to_string(type
));
1374 if ((r
= transaction_add_job_and_dependencies(m
, type
, unit
, NULL
, true, override
, &ret
)) < 0) {
1375 transaction_abort(m
);
1379 if (mode
== JOB_ISOLATE
)
1380 if ((r
= transaction_add_isolate_jobs(m
)) < 0) {
1381 transaction_abort(m
);
1385 if ((r
= transaction_activate(m
, mode
)) < 0)
1388 log_debug("Enqueued job %s/%s as %u", unit
->meta
.id
, job_type_to_string(type
), (unsigned) ret
->id
);
1396 int manager_add_job_by_name(Manager
*m
, JobType type
, const char *name
, JobMode mode
, bool override
, Job
**_ret
) {
1401 assert(type
< _JOB_TYPE_MAX
);
1403 assert(mode
< _JOB_MODE_MAX
);
1405 if ((r
= manager_load_unit(m
, name
, NULL
, &unit
)) < 0)
1408 return manager_add_job(m
, type
, unit
, mode
, override
, _ret
);
1411 Job
*manager_get_job(Manager
*m
, uint32_t id
) {
1414 return hashmap_get(m
->jobs
, UINT32_TO_PTR(id
));
1417 Unit
*manager_get_unit(Manager
*m
, const char *name
) {
1421 return hashmap_get(m
->units
, name
);
1424 unsigned manager_dispatch_load_queue(Manager
*m
) {
1430 /* Make sure we are not run recursively */
1431 if (m
->dispatching_load_queue
)
1434 m
->dispatching_load_queue
= true;
1436 /* Dispatches the load queue. Takes a unit from the queue and
1437 * tries to load its data until the queue is empty */
1439 while ((meta
= m
->load_queue
)) {
1440 assert(meta
->in_load_queue
);
1442 unit_load(UNIT(meta
));
1446 m
->dispatching_load_queue
= false;
1450 int manager_load_unit_prepare(Manager
*m
, const char *name
, const char *path
, Unit
**_ret
) {
1455 assert(name
|| path
);
1457 /* This will prepare the unit for loading, but not actually
1458 * load anything from disk. */
1460 if (path
&& !is_path(path
))
1464 name
= file_name_from_path(path
);
1466 if (!unit_name_is_valid(name
))
1469 if ((ret
= manager_get_unit(m
, name
))) {
1474 if (!(ret
= unit_new(m
)))
1478 if (!(ret
->meta
.fragment_path
= strdup(path
))) {
1483 if ((r
= unit_add_name(ret
, name
)) < 0) {
1488 unit_add_to_load_queue(ret
);
1489 unit_add_to_dbus_queue(ret
);
1490 unit_add_to_gc_queue(ret
);
1498 int manager_load_unit(Manager
*m
, const char *name
, const char *path
, Unit
**_ret
) {
1503 /* This will load the service information files, but not actually
1504 * start any services or anything. */
1506 if ((r
= manager_load_unit_prepare(m
, name
, path
, _ret
)) != 0)
1509 manager_dispatch_load_queue(m
);
1512 *_ret
= unit_follow_merge(*_ret
);
1517 void manager_dump_jobs(Manager
*s
, FILE *f
, const char *prefix
) {
1524 HASHMAP_FOREACH(j
, s
->jobs
, i
)
1525 job_dump(j
, f
, prefix
);
1528 void manager_dump_units(Manager
*s
, FILE *f
, const char *prefix
) {
1536 HASHMAP_FOREACH_KEY(u
, t
, s
->units
, i
)
1537 if (u
->meta
.id
== t
)
1538 unit_dump(u
, f
, prefix
);
1541 void manager_clear_jobs(Manager
*m
) {
1546 transaction_abort(m
);
1548 while ((j
= hashmap_first(m
->jobs
)))
1552 unsigned manager_dispatch_run_queue(Manager
*m
) {
1556 if (m
->dispatching_run_queue
)
1559 m
->dispatching_run_queue
= true;
1561 while ((j
= m
->run_queue
)) {
1562 assert(j
->installed
);
1563 assert(j
->in_run_queue
);
1565 job_run_and_invalidate(j
);
1569 m
->dispatching_run_queue
= false;
1573 unsigned manager_dispatch_dbus_queue(Manager
*m
) {
1580 if (m
->dispatching_dbus_queue
)
1583 m
->dispatching_dbus_queue
= true;
1585 while ((meta
= m
->dbus_unit_queue
)) {
1586 assert(meta
->in_dbus_queue
);
1588 bus_unit_send_change_signal(UNIT(meta
));
1592 while ((j
= m
->dbus_job_queue
)) {
1593 assert(j
->in_dbus_queue
);
1595 bus_job_send_change_signal(j
);
1599 m
->dispatching_dbus_queue
= false;
1603 static int manager_process_notify_fd(Manager
*m
) {
1610 struct msghdr msghdr
;
1612 struct ucred
*ucred
;
1614 struct cmsghdr cmsghdr
;
1615 uint8_t buf
[CMSG_SPACE(sizeof(struct ucred
))];
1621 iovec
.iov_base
= buf
;
1622 iovec
.iov_len
= sizeof(buf
)-1;
1626 msghdr
.msg_iov
= &iovec
;
1627 msghdr
.msg_iovlen
= 1;
1628 msghdr
.msg_control
= &control
;
1629 msghdr
.msg_controllen
= sizeof(control
);
1631 if ((n
= recvmsg(m
->notify_watch
.fd
, &msghdr
, MSG_DONTWAIT
)) <= 0) {
1635 if (errno
== EAGAIN
)
1641 if (msghdr
.msg_controllen
< CMSG_LEN(sizeof(struct ucred
)) ||
1642 control
.cmsghdr
.cmsg_level
!= SOL_SOCKET
||
1643 control
.cmsghdr
.cmsg_type
!= SCM_CREDENTIALS
||
1644 control
.cmsghdr
.cmsg_len
!= CMSG_LEN(sizeof(struct ucred
))) {
1645 log_warning("Received notify message without credentials. Ignoring.");
1649 ucred
= (struct ucred
*) CMSG_DATA(&control
.cmsghdr
);
1651 if (!(u
= hashmap_get(m
->watch_pids
, UINT32_TO_PTR(ucred
->pid
))))
1652 if (!(u
= cgroup_unit_by_pid(m
, ucred
->pid
))) {
1653 log_warning("Cannot find unit for notify message of PID %lu.", (unsigned long) ucred
->pid
);
1657 assert((size_t) n
< sizeof(buf
));
1659 if (!(tags
= strv_split(buf
, "\n\r")))
1662 log_debug("Got notification message for unit %s", u
->meta
.id
);
1664 if (UNIT_VTABLE(u
)->notify_message
)
1665 UNIT_VTABLE(u
)->notify_message(u
, ucred
->pid
, tags
);
1673 static int manager_dispatch_sigchld(Manager
*m
) {
1683 /* First we call waitd() for a PID and do not reap the
1684 * zombie. That way we can still access /proc/$PID for
1685 * it while it is a zombie. */
1686 if (waitid(P_ALL
, 0, &si
, WEXITED
|WNOHANG
|WNOWAIT
) < 0) {
1688 if (errno
== ECHILD
)
1700 if (si
.si_code
== CLD_EXITED
|| si
.si_code
== CLD_KILLED
|| si
.si_code
== CLD_DUMPED
) {
1703 get_process_name(si
.si_pid
, &name
);
1704 log_debug("Got SIGCHLD for process %llu (%s)", (unsigned long long) si
.si_pid
, strna(name
));
1708 /* Let's flush any message the dying child might still
1709 * have queued for us. This ensures that the process
1710 * still exists in /proc so that we can figure out
1711 * which cgroup and hence unit it belongs to. */
1712 if ((r
= manager_process_notify_fd(m
)) < 0)
1715 /* And now figure out the unit this belongs to */
1716 if (!(u
= hashmap_get(m
->watch_pids
, UINT32_TO_PTR(si
.si_pid
))))
1717 u
= cgroup_unit_by_pid(m
, si
.si_pid
);
1719 /* And now, we actually reap the zombie. */
1720 if (waitid(P_PID
, si
.si_pid
, &si
, WEXITED
) < 0) {
1727 if (si
.si_code
!= CLD_EXITED
&& si
.si_code
!= CLD_KILLED
&& si
.si_code
!= CLD_DUMPED
)
1730 log_debug("Child %llu died (code=%s, status=%i/%s)",
1731 (long long unsigned) si
.si_pid
,
1732 sigchld_code_to_string(si
.si_code
),
1734 strna(si
.si_code
== CLD_EXITED
? exit_status_to_string(si
.si_status
) : strsignal(si
.si_status
)));
1739 log_debug("Child %llu belongs to %s", (long long unsigned) si
.si_pid
, u
->meta
.id
);
1741 hashmap_remove(m
->watch_pids
, UINT32_TO_PTR(si
.si_pid
));
1742 UNIT_VTABLE(u
)->sigchld_event(u
, si
.si_pid
, si
.si_code
, si
.si_status
);
1748 static int manager_start_target(Manager
*m
, const char *name
, JobMode mode
) {
1751 if ((r
= manager_add_job_by_name(m
, JOB_START
, name
, mode
, true, NULL
)) < 0)
1752 log_error("Failed to enqueue %s job: %s", name
, strerror(-r
));
1757 static int manager_process_signal_fd(Manager
*m
) {
1759 struct signalfd_siginfo sfsi
;
1760 bool sigchld
= false;
1765 if ((n
= read(m
->signal_watch
.fd
, &sfsi
, sizeof(sfsi
))) != sizeof(sfsi
)) {
1770 if (errno
== EAGAIN
)
1776 switch (sfsi
.ssi_signo
) {
1783 if (m
->running_as
== MANAGER_INIT
) {
1784 /* This is for compatibility with the
1785 * original sysvinit */
1786 m
->exit_code
= MANAGER_REEXECUTE
;
1793 if (m
->running_as
== MANAGER_INIT
) {
1794 manager_start_target(m
, SPECIAL_CTRL_ALT_DEL_TARGET
, JOB_REPLACE
);
1798 /* Run the exit target if there is one, if not, just exit. */
1799 if (manager_start_target(m
, SPECIAL_EXIT_SERVICE
, JOB_REPLACE
) < 0) {
1800 m
->exit_code
= MANAGER_EXIT
;
1807 if (m
->running_as
== MANAGER_INIT
)
1808 manager_start_target(m
, SPECIAL_KBREQUEST_TARGET
, JOB_REPLACE
);
1810 /* This is a nop on non-init */
1814 if (m
->running_as
== MANAGER_INIT
)
1815 manager_start_target(m
, SPECIAL_SIGPWR_TARGET
, JOB_REPLACE
);
1817 /* This is a nop on non-init */
1823 u
= manager_get_unit(m
, SPECIAL_DBUS_SERVICE
);
1825 if (!u
|| UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u
))) {
1826 log_info("Trying to reconnect to bus...");
1830 if (!u
|| !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u
))) {
1831 log_info("Loading D-Bus service...");
1832 manager_start_target(m
, SPECIAL_DBUS_SERVICE
, JOB_REPLACE
);
1843 if (!(f
= open_memstream(&dump
, &size
))) {
1844 log_warning("Failed to allocate memory stream.");
1848 manager_dump_units(m
, f
, "\t");
1849 manager_dump_jobs(m
, f
, "\t");
1854 log_warning("Failed to write status stream");
1859 log_dump(LOG_INFO
, dump
);
1866 m
->exit_code
= MANAGER_RELOAD
;
1870 static const char * const table
[] = {
1871 [0] = SPECIAL_DEFAULT_TARGET
,
1872 [1] = SPECIAL_RESCUE_TARGET
,
1873 [2] = SPECIAL_EMERGENCY_SERVICE
,
1874 [3] = SPECIAL_HALT_TARGET
,
1875 [4] = SPECIAL_POWEROFF_TARGET
,
1876 [5] = SPECIAL_REBOOT_TARGET
1879 if ((int) sfsi
.ssi_signo
>= SIGRTMIN
+0 &&
1880 (int) sfsi
.ssi_signo
< SIGRTMIN
+(int) ELEMENTSOF(table
)) {
1881 manager_start_target(m
, table
[sfsi
.ssi_signo
- SIGRTMIN
],
1882 sfsi
.ssi_signo
== 2 ? JOB_ISOLATE
: JOB_REPLACE
);
1886 log_info("Got unhandled signal <%s>.", strsignal(sfsi
.ssi_signo
));
1892 return manager_dispatch_sigchld(m
);
1897 static int process_event(Manager
*m
, struct epoll_event
*ev
) {
1904 assert(w
= ev
->data
.ptr
);
1910 /* An incoming signal? */
1911 if (ev
->events
!= EPOLLIN
)
1914 if ((r
= manager_process_signal_fd(m
)) < 0)
1921 /* An incoming daemon notification event? */
1922 if (ev
->events
!= EPOLLIN
)
1925 if ((r
= manager_process_notify_fd(m
)) < 0)
1932 /* Some fd event, to be dispatched to the units */
1933 UNIT_VTABLE(w
->data
.unit
)->fd_event(w
->data
.unit
, w
->fd
, ev
->events
, w
);
1940 /* Some timer event, to be dispatched to the units */
1941 if ((k
= read(w
->fd
, &v
, sizeof(v
))) != sizeof(v
)) {
1943 if (k
< 0 && (errno
== EINTR
|| errno
== EAGAIN
))
1946 return k
< 0 ? -errno
: -EIO
;
1949 UNIT_VTABLE(w
->data
.unit
)->timer_event(w
->data
.unit
, v
, w
);
1954 /* Some mount table change, intended for the mount subsystem */
1955 mount_fd_event(m
, ev
->events
);
1959 /* Some notification from udev, intended for the device subsystem */
1960 device_fd_event(m
, ev
->events
);
1963 case WATCH_DBUS_WATCH
:
1964 bus_watch_event(m
, w
, ev
->events
);
1967 case WATCH_DBUS_TIMEOUT
:
1968 bus_timeout_event(m
, w
, ev
->events
);
1972 assert_not_reached("Unknown epoll event type.");
1978 int manager_loop(Manager
*m
) {
1981 RATELIMIT_DEFINE(rl
, 1*USEC_PER_SEC
, 1000);
1984 m
->exit_code
= MANAGER_RUNNING
;
1986 /* There might still be some zombies hanging around from
1987 * before we were exec()'ed. Leat's reap them */
1988 if ((r
= manager_dispatch_sigchld(m
)) < 0)
1991 while (m
->exit_code
== MANAGER_RUNNING
) {
1992 struct epoll_event event
;
1995 if (!ratelimit_test(&rl
)) {
1996 /* Yay, something is going seriously wrong, pause a little */
1997 log_warning("Looping too fast. Throttling execution a little.");
2001 if (manager_dispatch_load_queue(m
) > 0)
2004 if (manager_dispatch_run_queue(m
) > 0)
2007 if (bus_dispatch(m
) > 0)
2010 if (manager_dispatch_cleanup_queue(m
) > 0)
2013 if (manager_dispatch_gc_queue(m
) > 0)
2016 if (manager_dispatch_dbus_queue(m
) > 0)
2019 if ((n
= epoll_wait(m
->epoll_fd
, &event
, 1, -1)) < 0) {
2029 if ((r
= process_event(m
, &event
)) < 0)
2033 return m
->exit_code
;
2036 int manager_get_unit_from_dbus_path(Manager
*m
, const char *s
, Unit
**_u
) {
2044 if (!startswith(s
, "/org/freedesktop/systemd1/unit/"))
2047 if (!(n
= bus_path_unescape(s
+31)))
2050 u
= manager_get_unit(m
, n
);
2061 int manager_get_job_from_dbus_path(Manager
*m
, const char *s
, Job
**_j
) {
2070 if (!startswith(s
, "/org/freedesktop/systemd1/job/"))
2073 if ((r
= safe_atou(s
+ 30, &id
)) < 0)
2076 if (!(j
= manager_get_job(m
, id
)))
2084 static bool manager_utmp_good(Manager
*m
) {
2089 if ((r
= mount_path_is_mounted(m
, _PATH_UTMPX
)) <= 0) {
2092 log_warning("Failed to determine whether " _PATH_UTMPX
" is mounted: %s", strerror(-r
));
2100 void manager_write_utmp_reboot(Manager
*m
) {
2105 if (m
->utmp_reboot_written
)
2108 if (m
->running_as
!= MANAGER_INIT
)
2111 if (!manager_utmp_good(m
))
2114 if ((r
= utmp_put_reboot(m
->startup_timestamp
.realtime
)) < 0) {
2116 if (r
!= -ENOENT
&& r
!= -EROFS
)
2117 log_warning("Failed to write utmp/wtmp: %s", strerror(-r
));
2122 m
->utmp_reboot_written
= true;
2125 void manager_write_utmp_runlevel(Manager
*m
, Unit
*u
) {
2131 if (u
->meta
.type
!= UNIT_TARGET
)
2134 if (m
->running_as
!= MANAGER_INIT
)
2137 if (!manager_utmp_good(m
))
2140 if ((runlevel
= target_get_runlevel(TARGET(u
))) <= 0)
2143 if ((r
= utmp_put_runlevel(0, runlevel
, 0)) < 0) {
2145 if (r
!= -ENOENT
&& r
!= -EROFS
)
2146 log_warning("Failed to write utmp/wtmp: %s", strerror(-r
));
2150 void manager_dispatch_bus_name_owner_changed(
2153 const char* old_owner
,
2154 const char *new_owner
) {
2161 if (!(u
= hashmap_get(m
->watch_bus
, name
)))
2164 UNIT_VTABLE(u
)->bus_name_owner_change(u
, name
, old_owner
, new_owner
);
2167 void manager_dispatch_bus_query_pid_done(
2178 if (!(u
= hashmap_get(m
->watch_bus
, name
)))
2181 UNIT_VTABLE(u
)->bus_query_pid_done(u
, name
, pid
);
2184 int manager_open_serialization(FILE **_f
) {
2192 if (asprintf(&path
, "/dev/shm/systemd-%u.dump-XXXXXX", (unsigned) getpid()) < 0)
2195 saved_umask
= umask(0077);
2196 fd
= mkostemp(path
, O_RDWR
|O_CLOEXEC
);
2206 log_debug("Serializing state to %s", path
);
2209 if (!(f
= fdopen(fd
, "w+")) < 0)
2217 int manager_serialize(Manager
*m
, FILE *f
, FDSet
*fds
) {
2227 HASHMAP_FOREACH_KEY(u
, t
, m
->units
, i
) {
2228 if (u
->meta
.id
!= t
)
2231 if (!unit_can_serialize(u
))
2235 fputs(u
->meta
.id
, f
);
2238 if ((r
= unit_serialize(u
, f
, fds
)) < 0)
2248 int manager_deserialize(Manager
*m
, FILE *f
, FDSet
*fds
) {
2254 log_debug("Deserializing state...");
2258 char name
[UNIT_NAME_MAX
+2];
2261 if (!fgets(name
, sizeof(name
), f
)) {
2270 if ((r
= manager_load_unit(m
, strstrip(name
), NULL
, &u
)) < 0)
2273 if ((r
= unit_deserialize(u
, f
, fds
)) < 0)
2283 int manager_reload(Manager
*m
) {
2290 if ((r
= manager_open_serialization(&f
)) < 0)
2293 if (!(fds
= fdset_new())) {
2298 if ((r
= manager_serialize(m
, f
, fds
)) < 0)
2301 if (fseeko(f
, 0, SEEK_SET
) < 0) {
2306 /* From here on there is no way back. */
2307 manager_clear_jobs_and_units(m
);
2309 /* Find new unit paths */
2310 lookup_paths_free(&m
->lookup_paths
);
2311 if ((q
= lookup_paths_init(&m
->lookup_paths
, m
->running_as
)) < 0)
2314 /* First, enumerate what we can from all config files */
2315 if ((q
= manager_enumerate(m
)) < 0)
2318 /* Second, deserialize our stored data */
2319 if ((q
= manager_deserialize(m
, f
, fds
)) < 0)
2325 /* Third, fire things up! */
2326 if ((q
= manager_coldplug(m
)) < 0)
2339 static const char* const manager_running_as_table
[_MANAGER_RUNNING_AS_MAX
] = {
2340 [MANAGER_INIT
] = "init",
2341 [MANAGER_SYSTEM
] = "system",
2342 [MANAGER_SESSION
] = "session"
2345 DEFINE_STRING_TABLE_LOOKUP(manager_running_as
, ManagerRunningAs
);