1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
8 #include <sys/signalfd.h>
20 static const char * const special_table[_SPECIAL_UNIT_MAX] = {
21 [SPECIAL_SYSLOG_SERVICE] = "syslog.service",
22 [SPECIAL_DBUS_SERVICE] = "messagebus.service",
23 [SPECIAL_LOGGER_SOCKET] = "systemd-logger.socket"
26 static int manager_setup_signals(Manager *m) {
28 struct epoll_event ev;
32 assert_se(reset_all_signal_handlers() == 0);
34 assert_se(sigemptyset(&mask) == 0);
35 assert_se(sigaddset(&mask, SIGCHLD) == 0);
36 assert_se(sigaddset(&mask, SIGINT) == 0); /* Kernel sends us this on control-alt-del */
37 assert_se(sigaddset(&mask, SIGWINCH) == 0); /* Kernel sends us this on kbrequest (alt-arrowup) */
38 assert_se(sigaddset(&mask, SIGTERM) == 0);
39 assert_se(sigaddset(&mask, SIGHUP) == 0);
40 assert_se(sigaddset(&mask, SIGUSR1) == 0);
41 assert_se(sigaddset(&mask, SIGUSR2) == 0);
42 assert_se(sigaddset(&mask, SIGPIPE) == 0);
43 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
45 m->signal_watch.type = WATCH_SIGNAL_FD;
46 if ((m->signal_watch.fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0)
51 ev.data.ptr = &m->signal_watch;
53 if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->signal_watch.fd, &ev) < 0)
59 static int manager_load_special_units(Manager *m) {
65 /* Loads all 'special' units, so that we have easy access to them later */
67 for (c = 0; c < _SPECIAL_UNIT_MAX; c++)
68 if ((r = manager_load_unit(m, special_table[c], m->special_units+c)) < 0)
74 Manager* manager_new(void) {
77 if (!(m = new0(Manager, 1)))
80 m->signal_watch.fd = m->epoll_fd = -1;
82 if (!(m->units = hashmap_new(string_hash_func, string_compare_func)))
85 if (!(m->jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
88 if (!(m->transaction_jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
91 if (!(m->watch_pids = hashmap_new(trivial_hash_func, trivial_compare_func)))
94 if ((m->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0)
97 if (manager_setup_signals(m) < 0)
100 if (manager_load_special_units(m) < 0)
110 void manager_free(Manager *m) {
116 while ((j = hashmap_first(m->transaction_jobs)))
119 while ((u = hashmap_first(m->units)))
122 hashmap_free(m->units);
123 hashmap_free(m->jobs);
124 hashmap_free(m->transaction_jobs);
125 hashmap_free(m->watch_pids);
127 if (m->epoll_fd >= 0)
128 close_nointr(m->epoll_fd);
129 if (m->signal_watch.fd >= 0)
130 close_nointr(m->signal_watch.fd);
135 static void transaction_delete_job(Manager *m, Job *j) {
139 /* Deletes one job from the transaction */
141 manager_transaction_unlink_job(m, j);
147 static void transaction_delete_unit(Manager *m, Unit *u) {
150 /* Deletes all jobs associated with a certain unit from the
153 while ((j = hashmap_get(m->transaction_jobs, u)))
154 transaction_delete_job(m, j);
157 static void transaction_clean_dependencies(Manager *m) {
163 /* Drops all dependencies of all installed jobs */
165 HASHMAP_FOREACH(j, m->jobs, i) {
166 while (j->subject_list)
167 job_dependency_free(j->subject_list);
168 while (j->object_list)
169 job_dependency_free(j->object_list);
172 assert(!m->transaction_anchor);
175 static void transaction_abort(Manager *m) {
180 while ((j = hashmap_first(m->transaction_jobs)))
182 transaction_delete_job(m, j);
186 assert(hashmap_isempty(m->transaction_jobs));
188 transaction_clean_dependencies(m);
191 static void transaction_find_jobs_that_matter_to_anchor(Manager *m, Job *j, unsigned generation) {
196 /* A recursive sweep through the graph that marks all units
197 * that matter to the anchor job, i.e. are directly or
198 * indirectly a dependency of the anchor job via paths that
199 * are fully marked as mattering. */
204 l = m->transaction_anchor;
206 LIST_FOREACH(subject, l, l) {
208 /* This link does not matter */
212 /* This unit has already been marked */
213 if (l->object->generation == generation)
216 l->object->matters_to_anchor = true;
217 l->object->generation = generation;
219 transaction_find_jobs_that_matter_to_anchor(m, l->object, generation);
223 static void transaction_merge_and_delete_job(Manager *m, Job *j, Job *other, JobType t) {
224 JobDependency *l, *last;
228 assert(j->unit == other->unit);
229 assert(!j->installed);
231 /* Merges 'other' into 'j' and then deletes j. */
234 j->state = JOB_WAITING;
235 j->forced = j->forced || other->forced;
237 j->matters_to_anchor = j->matters_to_anchor || other->matters_to_anchor;
239 /* Patch us in as new owner of the JobDependency objects */
241 LIST_FOREACH(subject, l, other->subject_list) {
242 assert(l->subject == other);
247 /* Merge both lists */
249 last->subject_next = j->subject_list;
251 j->subject_list->subject_prev = last;
252 j->subject_list = other->subject_list;
255 /* Patch us in as new owner of the JobDependency objects */
257 LIST_FOREACH(object, l, other->object_list) {
258 assert(l->object == other);
263 /* Merge both lists */
265 last->object_next = j->object_list;
267 j->object_list->object_prev = last;
268 j->object_list = other->object_list;
271 /* Kill the other job */
272 other->subject_list = NULL;
273 other->object_list = NULL;
274 transaction_delete_job(m, other);
277 static int delete_one_unmergeable_job(Manager *m, Job *j) {
282 /* Tries to delete one item in the linked list
283 * j->transaction_next->transaction_next->... that conflicts
284 * whith another one, in an attempt to make an inconsistent
285 * transaction work. */
287 /* We rely here on the fact that if a merged with b does not
288 * merge with c, either a or b merge with c neither */
289 LIST_FOREACH(transaction, j, j)
290 LIST_FOREACH(transaction, k, j->transaction_next) {
293 /* Is this one mergeable? Then skip it */
294 if (job_type_is_mergeable(j->type, k->type))
297 /* Ok, we found two that conflict, let's see if we can
298 * drop one of them */
299 if (!j->matters_to_anchor)
301 else if (!k->matters_to_anchor)
306 /* Ok, we can drop one, so let's do so. */
307 log_debug("Try to fix job merging by deleting job %s/%s", unit_id(d->unit), job_type_to_string(d->type));
308 transaction_delete_job(m, d);
315 static int transaction_merge_jobs(Manager *m) {
322 /* First step, check whether any of the jobs for one specific
323 * task conflict. If so, try to drop one of them. */
324 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
329 LIST_FOREACH(transaction, k, j->transaction_next) {
330 if ((r = job_type_merge(&t, k->type)) >= 0)
333 /* OK, we could not merge all jobs for this
334 * action. Let's see if we can get rid of one
337 if ((r = delete_one_unmergeable_job(m, j)) >= 0)
338 /* Ok, we managed to drop one, now
339 * let's ask our callers to call us
340 * again after garbage collecting */
343 /* We couldn't merge anything. Failure */
348 /* Second step, merge the jobs. */
349 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
353 /* Merge all transactions */
354 LIST_FOREACH(transaction, k, j->transaction_next)
355 assert_se(job_type_merge(&t, k->type) == 0);
357 /* If an active job is mergeable, merge it too */
358 if (j->unit->meta.job)
359 job_type_merge(&t, j->unit->meta.job->type); /* Might fail. Which is OK */
361 while ((k = j->transaction_next)) {
363 transaction_merge_and_delete_job(m, k, j, t);
366 transaction_merge_and_delete_job(m, j, k, t);
369 assert(!j->transaction_next);
370 assert(!j->transaction_prev);
376 static bool unit_matters_to_anchor(Unit *u, Job *j) {
378 assert(!j->transaction_prev);
380 /* Checks whether at least one of the jobs for this unit
381 * matters to the anchor. */
383 LIST_FOREACH(transaction, j, j)
384 if (j->matters_to_anchor)
390 static int transaction_verify_order_one(Manager *m, Job *j, Job *from, unsigned generation) {
397 assert(!j->transaction_prev);
399 /* Does a recursive sweep through the ordering graph, looking
400 * for a cycle. If we find cycle we try to break it. */
402 /* Did we find a cycle? */
403 if (j->marker && j->generation == generation) {
406 /* So, we already have been here. We have a
407 * cycle. Let's try to break it. We go backwards in
408 * our path and try to find a suitable job to
409 * remove. We use the marker to find our way back,
410 * since smart how we are we stored our way back in
413 for (k = from; k; k = (k->generation == generation ? k->marker : NULL)) {
416 !unit_matters_to_anchor(k->unit, k)) {
417 /* Ok, we can drop this one, so let's
419 log_debug("Breaking order cycle by deleting job %s/%s", unit_id(k->unit), job_type_to_string(k->type));
420 transaction_delete_unit(m, k->unit);
424 /* Check if this in fact was the beginning of
433 /* Make the marker point to where we come from, so that we can
434 * find our way backwards if we want to break a cycle */
436 j->generation = generation;
438 /* We assume that the the dependencies are bidirectional, and
439 * hence can ignore UNIT_AFTER */
440 SET_FOREACH(u, j->unit->meta.dependencies[UNIT_BEFORE], i) {
443 /* Is there a job for this unit? */
444 if (!(o = hashmap_get(m->transaction_jobs, u)))
446 /* Ok, there is no job for this in the
447 * transaction, but maybe there is already one
449 if (!(o = u->meta.job))
452 if ((r = transaction_verify_order_one(m, o, j, generation)) < 0)
459 static int transaction_verify_order(Manager *m, unsigned *generation) {
467 /* Check if the ordering graph is cyclic. If it is, try to fix
468 * that up by dropping one of the jobs. */
470 HASHMAP_FOREACH(j, m->transaction_jobs, i)
471 if ((r = transaction_verify_order_one(m, j, NULL, (*generation)++)) < 0)
477 static void transaction_collect_garbage(Manager *m) {
482 /* Drop jobs that are not required by any other job */
490 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
494 log_debug("Garbage collecting job %s/%s", unit_id(j->unit), job_type_to_string(j->type));
495 transaction_delete_job(m, j);
503 static int transaction_is_destructive(Manager *m, JobMode mode) {
509 /* Checks whether applying this transaction means that
510 * existing jobs would be replaced */
512 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
515 assert(!j->transaction_prev);
516 assert(!j->transaction_next);
518 if (j->unit->meta.job &&
519 j->unit->meta.job != j &&
520 !job_type_is_superset(j->type, j->unit->meta.job->type))
527 static void transaction_minimize_impact(Manager *m) {
531 /* Drops all unnecessary jobs that reverse already active jobs
532 * or that stop a running service. */
540 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
541 LIST_FOREACH(transaction, j, j) {
543 /* If it matters, we shouldn't drop it */
544 if (j->matters_to_anchor)
547 /* Would this stop a running service?
548 * Would this change an existing job?
549 * If so, let's drop this entry */
550 if ((j->type != JOB_STOP || UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(j->unit))) &&
551 (!j->unit->meta.job || job_type_is_conflicting(j->type, j->unit->meta.job->state)))
554 /* Ok, let's get rid of this */
555 log_debug("Deleting %s/%s to minimize impact", unit_id(j->unit), job_type_to_string(j->type));
556 transaction_delete_job(m, j);
568 static int transaction_apply(Manager *m, JobMode mode) {
573 /* Moves the transaction jobs to the set of active jobs */
575 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
577 assert(!j->transaction_prev);
578 assert(!j->transaction_next);
583 if ((r = hashmap_put(m->jobs, UINT32_TO_PTR(j->id), j)) < 0)
587 while ((j = hashmap_steal_first(m->transaction_jobs))) {
591 if (j->unit->meta.job)
592 job_free(j->unit->meta.job);
594 j->unit->meta.job = j;
597 /* We're fully installed. Now let's free data we don't
600 assert(!j->transaction_next);
601 assert(!j->transaction_prev);
606 /* As last step, kill all remaining job dependencies. */
607 transaction_clean_dependencies(m);
613 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
617 hashmap_remove(m->jobs, UINT32_TO_PTR(j->id));
623 static int transaction_activate(Manager *m, JobMode mode) {
625 unsigned generation = 1;
629 /* This applies the changes recorded in transaction_jobs to
630 * the actual list of jobs, if possible. */
632 /* First step: figure out which jobs matter */
633 transaction_find_jobs_that_matter_to_anchor(m, NULL, generation++);
635 /* Second step: Try not to stop any running services if
636 * we don't have to. Don't try to reverse running
637 * jobs if we don't have to. */
638 transaction_minimize_impact(m);
641 /* Third step: Let's remove unneeded jobs that might
643 transaction_collect_garbage(m);
645 /* Fourth step: verify order makes sense and correct
646 * cycles if necessary and possible */
647 if ((r = transaction_verify_order(m, &generation)) >= 0)
653 /* Let's see if the resulting transaction ordering
654 * graph is still cyclic... */
658 /* Fifth step: let's drop unmergeable entries if
659 * necessary and possible, merge entries we can
661 if ((r = transaction_merge_jobs(m)) >= 0)
667 /* Sixth step: an entry got dropped, let's garbage
668 * collect its dependencies. */
669 transaction_collect_garbage(m);
671 /* Let's see if the resulting transaction still has
672 * unmergeable entries ... */
675 /* Seventh step: check whether we can actually apply this */
676 if (mode == JOB_FAIL)
677 if ((r = transaction_is_destructive(m, mode)) < 0)
680 /* Eights step: apply changes */
681 if ((r = transaction_apply(m, mode)) < 0)
684 assert(hashmap_isempty(m->transaction_jobs));
685 assert(!m->transaction_anchor);
690 transaction_abort(m);
694 static Job* transaction_add_one_job(Manager *m, JobType type, Unit *unit, bool force, bool *is_new) {
701 /* Looks for an axisting prospective job and returns that. If
702 * it doesn't exist it is created and added to the prospective
705 f = hashmap_get(m->transaction_jobs, unit);
707 LIST_FOREACH(transaction, j, f) {
708 assert(j->unit == unit);
710 if (j->type == type) {
717 if (unit->meta.job && unit->meta.job->type == type)
719 else if (!(j = job_new(m, type, unit)))
724 j->matters_to_anchor = false;
727 LIST_PREPEND(Job, transaction, f, j);
729 if ((r = hashmap_replace(m->transaction_jobs, unit, f)) < 0) {
740 void manager_transaction_unlink_job(Manager *m, Job *j) {
744 if (j->transaction_prev)
745 j->transaction_prev->transaction_next = j->transaction_next;
746 else if (j->transaction_next)
747 hashmap_replace(m->transaction_jobs, j->unit, j->transaction_next);
749 hashmap_remove_value(m->transaction_jobs, j->unit, j);
751 if (j->transaction_next)
752 j->transaction_next->transaction_prev = j->transaction_prev;
754 j->transaction_prev = j->transaction_next = NULL;
756 while (j->subject_list)
757 job_dependency_free(j->subject_list);
759 while (j->object_list) {
760 Job *other = j->object_list->matters ? j->object_list->subject : NULL;
762 job_dependency_free(j->object_list);
765 log_debug("Deleting job %s/%s as dependency of job %s/%s",
766 unit_id(other->unit), job_type_to_string(other->type),
767 unit_id(j->unit), job_type_to_string(j->type));
768 transaction_delete_job(m, other);
773 static int transaction_add_job_and_dependencies(Manager *m, JobType type, Unit *unit, Job *by, bool matters, bool force, Job **_ret) {
781 assert(type < _JOB_TYPE_MAX);
784 if (unit->meta.load_state != UNIT_LOADED)
787 if (!unit_job_is_applicable(unit, type))
790 /* First add the job. */
791 if (!(ret = transaction_add_one_job(m, type, unit, force, &is_new)))
794 /* Then, add a link to the job. */
795 if (!job_dependency_new(by, ret, matters))
799 /* Finally, recursively add in all dependencies. */
800 if (type == JOB_START || type == JOB_RELOAD_OR_START) {
801 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES], i)
802 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, true, force, NULL)) < 0 && r != -EBADR)
804 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_SOFT_REQUIRES], i)
805 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, !force, force, NULL)) < 0 && r != -EBADR)
807 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_WANTS], i)
808 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, false, force, NULL)) < 0 && r != -EBADR)
810 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE], i)
811 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, true, force, NULL)) < 0 && r != -EBADR)
813 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_SOFT_REQUISITE], i)
814 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, !force, force, NULL)) < 0 && r != -EBADR)
816 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_CONFLICTS], i)
817 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, dep, ret, true, force, NULL)) < 0 && r != -EBADR)
820 } else if (type == JOB_STOP || type == JOB_RESTART || type == JOB_TRY_RESTART) {
822 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRED_BY], i)
823 if ((r = transaction_add_job_and_dependencies(m, type, dep, ret, true, force, NULL)) < 0 && r != -EBADR)
827 /* JOB_VERIFY_STARTED, JOB_RELOAD require no dependency handling */
836 int manager_add_job(Manager *m, JobType type, Unit *unit, JobMode mode, bool force, Job **_ret) {
841 assert(type < _JOB_TYPE_MAX);
843 assert(mode < _JOB_MODE_MAX);
845 if ((r = transaction_add_job_and_dependencies(m, type, unit, NULL, true, force, &ret))) {
846 transaction_abort(m);
850 if ((r = transaction_activate(m, mode)) < 0)
859 Job *manager_get_job(Manager *m, uint32_t id) {
862 return hashmap_get(m->jobs, UINT32_TO_PTR(id));
865 Unit *manager_get_unit(Manager *m, const char *name) {
869 return hashmap_get(m->units, name);
872 static void dispatch_load_queue(Manager *m) {
877 /* Make sure we are not run recursively */
878 if (m->dispatching_load_queue)
881 m->dispatching_load_queue = true;
883 /* Dispatches the load queue. Takes a unit from the queue and
884 * tries to load its data until the queue is empty */
886 while ((meta = m->load_queue)) {
887 assert(meta->in_load_queue);
889 unit_load(UNIT(meta));
892 m->dispatching_load_queue = false;
895 int manager_load_unit(Manager *m, const char *path, Unit **_ret) {
904 /* This will load the service information files, but not actually
905 * start any services or anything. */
907 name = file_name_from_path(path);
909 if ((ret = manager_get_unit(m, name))) {
914 if (!(ret = unit_new(m)))
918 if (!(ret->meta.load_path = strdup(path))) {
924 if ((r = unit_add_name(ret, name)) < 0) {
929 unit_add_to_load_queue(ret);
930 dispatch_load_queue(m);
936 void manager_dump_jobs(Manager *s, FILE *f, const char *prefix) {
943 HASHMAP_FOREACH(j, s->jobs, i)
944 job_dump(j, f, prefix);
947 void manager_dump_units(Manager *s, FILE *f, const char *prefix) {
955 HASHMAP_FOREACH_KEY(u, t, s->units, i)
957 unit_dump(u, f, prefix);
960 void manager_clear_jobs(Manager *m) {
965 transaction_abort(m);
967 while ((j = hashmap_first(m->jobs)))
971 void manager_dispatch_run_queue(Manager *m) {
974 if (m->dispatching_run_queue)
977 m->dispatching_run_queue = true;
979 while ((j = m->run_queue)) {
980 assert(j->installed);
981 assert(j->in_run_queue);
983 job_run_and_invalidate(j);
986 m->dispatching_run_queue = false;
989 static int manager_dispatch_sigchld(Manager *m) {
992 log_debug("dispatching SIGCHLD");
999 if (waitid(P_ALL, 0, &si, WEXITED|WNOHANG) < 0) {
1001 if (errno == ECHILD)
1010 if (si.si_code != CLD_EXITED && si.si_code != CLD_KILLED && si.si_code != CLD_DUMPED)
1013 log_debug("child %llu died (code=%s, status=%i)", (long long unsigned) si.si_pid, sigchld_code(si.si_code), si.si_status);
1015 if (!(u = hashmap_remove(m->watch_pids, UINT32_TO_PTR(si.si_pid))))
1018 UNIT_VTABLE(u)->sigchld_event(u, si.si_pid, si.si_code, si.si_status);
1024 static int manager_process_signal_fd(Manager *m, bool *quit) {
1026 struct signalfd_siginfo sfsi;
1027 bool sigchld = false;
1032 if ((n = read(m->signal_watch.fd, &sfsi, sizeof(sfsi))) != sizeof(sfsi)) {
1037 if (errno == EAGAIN)
1043 switch (sfsi.ssi_signo) {
1055 log_info("Got unhandled signal <%s>.", strsignal(sfsi.ssi_signo));
1060 return manager_dispatch_sigchld(m);
1065 static int process_event(Manager *m, struct epoll_event *ev, bool *quit) {
1072 assert(w = ev->data.ptr);
1076 case WATCH_SIGNAL_FD:
1078 /* An incoming signal? */
1079 if (ev->events != POLLIN)
1082 if ((r = manager_process_signal_fd(m, quit)) < 0)
1089 /* Some fd event, to be dispatched to the units */
1090 UNIT_VTABLE(w->unit)->fd_event(w->unit, w->fd, ev->events, w);
1097 /* Some timer event, to be dispatched to the units */
1098 if ((k = read(ev->data.fd, &v, sizeof(v))) != sizeof(v)) {
1100 if (k < 0 && (errno == EINTR || errno == EAGAIN))
1103 return k < 0 ? -errno : -EIO;
1106 UNIT_VTABLE(w->unit)->timer_event(w->unit, v, w);
1111 assert_not_reached("Unknown epoll event type.");
1117 int manager_loop(Manager *m) {
1124 struct epoll_event event;
1127 manager_dispatch_run_queue(m);
1129 if ((n = epoll_wait(m->epoll_fd, &event, 1, -1)) < 0) {
1131 if (errno == -EINTR)
1139 if ((r = process_event(m, &event, &quit)) < 0)