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",
24 [SPECIAL_KBREQUEST_TARGET] = "kbrequest.target",
25 [SPECIAL_CTRL_ALT_DEL_TARGET] = "ctrl-alt-del.target"
28 static int manager_setup_signals(Manager *m) {
30 struct epoll_event ev;
34 assert_se(reset_all_signal_handlers() == 0);
36 assert_se(sigemptyset(&mask) == 0);
37 assert_se(sigaddset(&mask, SIGCHLD) == 0);
38 assert_se(sigaddset(&mask, SIGINT) == 0); /* Kernel sends us this on control-alt-del */
39 assert_se(sigaddset(&mask, SIGWINCH) == 0); /* Kernel sends us this on kbrequest (alt-arrowup) */
40 assert_se(sigaddset(&mask, SIGTERM) == 0);
41 assert_se(sigaddset(&mask, SIGHUP) == 0);
42 assert_se(sigaddset(&mask, SIGUSR1) == 0);
43 assert_se(sigaddset(&mask, SIGUSR2) == 0);
44 assert_se(sigaddset(&mask, SIGPIPE) == 0);
45 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
47 m->signal_watch.type = WATCH_SIGNAL_FD;
48 if ((m->signal_watch.fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0)
53 ev.data.ptr = &m->signal_watch;
55 if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->signal_watch.fd, &ev) < 0)
61 static int manager_load_special_units(Manager *m) {
67 /* Loads all 'special' units, so that we have easy access to them later */
69 for (c = 0; c < _SPECIAL_UNIT_MAX; c++)
70 if ((r = manager_load_unit(m, special_table[c], m->special_units+c)) < 0)
76 static int manager_enumerate(Manager *m) {
82 for (c = 0; c < _UNIT_TYPE_MAX; c++)
83 if (unit_vtable[c]->enumerate)
84 if ((r = unit_vtable[c]->enumerate(m)) < 0)
90 Manager* manager_new(void) {
93 if (!(m = new0(Manager, 1)))
96 m->signal_watch.fd = m->epoll_fd = -1;
98 if (!(m->units = hashmap_new(string_hash_func, string_compare_func)))
101 if (!(m->jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
104 if (!(m->transaction_jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
107 if (!(m->watch_pids = hashmap_new(trivial_hash_func, trivial_compare_func)))
110 if ((m->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0)
113 if (manager_setup_signals(m) < 0)
116 if (manager_load_special_units(m) < 0)
119 if (manager_enumerate(m) < 0)
129 void manager_free(Manager *m) {
136 while ((j = hashmap_first(m->transaction_jobs)))
139 while ((u = hashmap_first(m->units)))
142 for (c = 0; c < _UNIT_TYPE_MAX; c++)
143 if (unit_vtable[c]->shutdown)
144 unit_vtable[c]->shutdown(m);
146 hashmap_free(m->units);
147 hashmap_free(m->jobs);
148 hashmap_free(m->transaction_jobs);
149 hashmap_free(m->watch_pids);
151 if (m->epoll_fd >= 0)
152 close_nointr(m->epoll_fd);
153 if (m->signal_watch.fd >= 0)
154 close_nointr(m->signal_watch.fd);
159 static void transaction_delete_job(Manager *m, Job *j) {
163 /* Deletes one job from the transaction */
165 manager_transaction_unlink_job(m, j);
171 static void transaction_delete_unit(Manager *m, Unit *u) {
174 /* Deletes all jobs associated with a certain unit from the
177 while ((j = hashmap_get(m->transaction_jobs, u)))
178 transaction_delete_job(m, j);
181 static void transaction_clean_dependencies(Manager *m) {
187 /* Drops all dependencies of all installed jobs */
189 HASHMAP_FOREACH(j, m->jobs, i) {
190 while (j->subject_list)
191 job_dependency_free(j->subject_list);
192 while (j->object_list)
193 job_dependency_free(j->object_list);
196 assert(!m->transaction_anchor);
199 static void transaction_abort(Manager *m) {
204 while ((j = hashmap_first(m->transaction_jobs)))
206 transaction_delete_job(m, j);
210 assert(hashmap_isempty(m->transaction_jobs));
212 transaction_clean_dependencies(m);
215 static void transaction_find_jobs_that_matter_to_anchor(Manager *m, Job *j, unsigned generation) {
220 /* A recursive sweep through the graph that marks all units
221 * that matter to the anchor job, i.e. are directly or
222 * indirectly a dependency of the anchor job via paths that
223 * are fully marked as mattering. */
228 l = m->transaction_anchor;
230 LIST_FOREACH(subject, l, l) {
232 /* This link does not matter */
236 /* This unit has already been marked */
237 if (l->object->generation == generation)
240 l->object->matters_to_anchor = true;
241 l->object->generation = generation;
243 transaction_find_jobs_that_matter_to_anchor(m, l->object, generation);
247 static void transaction_merge_and_delete_job(Manager *m, Job *j, Job *other, JobType t) {
248 JobDependency *l, *last;
252 assert(j->unit == other->unit);
253 assert(!j->installed);
255 /* Merges 'other' into 'j' and then deletes j. */
258 j->state = JOB_WAITING;
259 j->forced = j->forced || other->forced;
261 j->matters_to_anchor = j->matters_to_anchor || other->matters_to_anchor;
263 /* Patch us in as new owner of the JobDependency objects */
265 LIST_FOREACH(subject, l, other->subject_list) {
266 assert(l->subject == other);
271 /* Merge both lists */
273 last->subject_next = j->subject_list;
275 j->subject_list->subject_prev = last;
276 j->subject_list = other->subject_list;
279 /* Patch us in as new owner of the JobDependency objects */
281 LIST_FOREACH(object, l, other->object_list) {
282 assert(l->object == other);
287 /* Merge both lists */
289 last->object_next = j->object_list;
291 j->object_list->object_prev = last;
292 j->object_list = other->object_list;
295 /* Kill the other job */
296 other->subject_list = NULL;
297 other->object_list = NULL;
298 transaction_delete_job(m, other);
301 static int delete_one_unmergeable_job(Manager *m, Job *j) {
306 /* Tries to delete one item in the linked list
307 * j->transaction_next->transaction_next->... that conflicts
308 * whith another one, in an attempt to make an inconsistent
309 * transaction work. */
311 /* We rely here on the fact that if a merged with b does not
312 * merge with c, either a or b merge with c neither */
313 LIST_FOREACH(transaction, j, j)
314 LIST_FOREACH(transaction, k, j->transaction_next) {
317 /* Is this one mergeable? Then skip it */
318 if (job_type_is_mergeable(j->type, k->type))
321 /* Ok, we found two that conflict, let's see if we can
322 * drop one of them */
323 if (!j->matters_to_anchor)
325 else if (!k->matters_to_anchor)
330 /* Ok, we can drop one, so let's do so. */
331 log_debug("Try to fix job merging by deleting job %s/%s", unit_id(d->unit), job_type_to_string(d->type));
332 transaction_delete_job(m, d);
339 static int transaction_merge_jobs(Manager *m) {
346 /* First step, check whether any of the jobs for one specific
347 * task conflict. If so, try to drop one of them. */
348 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
353 LIST_FOREACH(transaction, k, j->transaction_next) {
354 if ((r = job_type_merge(&t, k->type)) >= 0)
357 /* OK, we could not merge all jobs for this
358 * action. Let's see if we can get rid of one
361 if ((r = delete_one_unmergeable_job(m, j)) >= 0)
362 /* Ok, we managed to drop one, now
363 * let's ask our callers to call us
364 * again after garbage collecting */
367 /* We couldn't merge anything. Failure */
372 /* Second step, merge the jobs. */
373 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
377 /* Merge all transactions */
378 LIST_FOREACH(transaction, k, j->transaction_next)
379 assert_se(job_type_merge(&t, k->type) == 0);
381 /* If an active job is mergeable, merge it too */
382 if (j->unit->meta.job)
383 job_type_merge(&t, j->unit->meta.job->type); /* Might fail. Which is OK */
385 while ((k = j->transaction_next)) {
387 transaction_merge_and_delete_job(m, k, j, t);
390 transaction_merge_and_delete_job(m, j, k, t);
393 assert(!j->transaction_next);
394 assert(!j->transaction_prev);
400 static bool unit_matters_to_anchor(Unit *u, Job *j) {
402 assert(!j->transaction_prev);
404 /* Checks whether at least one of the jobs for this unit
405 * matters to the anchor. */
407 LIST_FOREACH(transaction, j, j)
408 if (j->matters_to_anchor)
414 static int transaction_verify_order_one(Manager *m, Job *j, Job *from, unsigned generation) {
421 assert(!j->transaction_prev);
423 /* Does a recursive sweep through the ordering graph, looking
424 * for a cycle. If we find cycle we try to break it. */
426 /* Did we find a cycle? */
427 if (j->marker && j->generation == generation) {
430 /* So, we already have been here. We have a
431 * cycle. Let's try to break it. We go backwards in
432 * our path and try to find a suitable job to
433 * remove. We use the marker to find our way back,
434 * since smart how we are we stored our way back in
437 for (k = from; k; k = (k->generation == generation ? k->marker : NULL)) {
440 !unit_matters_to_anchor(k->unit, k)) {
441 /* Ok, we can drop this one, so let's
443 log_debug("Breaking order cycle by deleting job %s/%s", unit_id(k->unit), job_type_to_string(k->type));
444 transaction_delete_unit(m, k->unit);
448 /* Check if this in fact was the beginning of
457 /* Make the marker point to where we come from, so that we can
458 * find our way backwards if we want to break a cycle */
460 j->generation = generation;
462 /* We assume that the the dependencies are bidirectional, and
463 * hence can ignore UNIT_AFTER */
464 SET_FOREACH(u, j->unit->meta.dependencies[UNIT_BEFORE], i) {
467 /* Is there a job for this unit? */
468 if (!(o = hashmap_get(m->transaction_jobs, u)))
470 /* Ok, there is no job for this in the
471 * transaction, but maybe there is already one
473 if (!(o = u->meta.job))
476 if ((r = transaction_verify_order_one(m, o, j, generation)) < 0)
483 static int transaction_verify_order(Manager *m, unsigned *generation) {
491 /* Check if the ordering graph is cyclic. If it is, try to fix
492 * that up by dropping one of the jobs. */
494 HASHMAP_FOREACH(j, m->transaction_jobs, i)
495 if ((r = transaction_verify_order_one(m, j, NULL, (*generation)++)) < 0)
501 static void transaction_collect_garbage(Manager *m) {
506 /* Drop jobs that are not required by any other job */
514 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
518 log_debug("Garbage collecting job %s/%s", unit_id(j->unit), job_type_to_string(j->type));
519 transaction_delete_job(m, j);
527 static int transaction_is_destructive(Manager *m, JobMode mode) {
533 /* Checks whether applying this transaction means that
534 * existing jobs would be replaced */
536 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
539 assert(!j->transaction_prev);
540 assert(!j->transaction_next);
542 if (j->unit->meta.job &&
543 j->unit->meta.job != j &&
544 !job_type_is_superset(j->type, j->unit->meta.job->type))
551 static void transaction_minimize_impact(Manager *m) {
555 /* Drops all unnecessary jobs that reverse already active jobs
556 * or that stop a running service. */
564 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
565 LIST_FOREACH(transaction, j, j) {
567 /* If it matters, we shouldn't drop it */
568 if (j->matters_to_anchor)
571 /* Would this stop a running service?
572 * Would this change an existing job?
573 * If so, let's drop this entry */
574 if ((j->type != JOB_STOP || UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(j->unit))) &&
575 (!j->unit->meta.job || job_type_is_conflicting(j->type, j->unit->meta.job->state)))
578 /* Ok, let's get rid of this */
579 log_debug("Deleting %s/%s to minimize impact", unit_id(j->unit), job_type_to_string(j->type));
580 transaction_delete_job(m, j);
592 static int transaction_apply(Manager *m, JobMode mode) {
597 /* Moves the transaction jobs to the set of active jobs */
599 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
601 assert(!j->transaction_prev);
602 assert(!j->transaction_next);
607 if ((r = hashmap_put(m->jobs, UINT32_TO_PTR(j->id), j)) < 0)
611 while ((j = hashmap_steal_first(m->transaction_jobs))) {
615 if (j->unit->meta.job)
616 job_free(j->unit->meta.job);
618 j->unit->meta.job = j;
621 /* We're fully installed. Now let's free data we don't
624 assert(!j->transaction_next);
625 assert(!j->transaction_prev);
630 /* As last step, kill all remaining job dependencies. */
631 transaction_clean_dependencies(m);
637 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
641 hashmap_remove(m->jobs, UINT32_TO_PTR(j->id));
647 static int transaction_activate(Manager *m, JobMode mode) {
649 unsigned generation = 1;
653 /* This applies the changes recorded in transaction_jobs to
654 * the actual list of jobs, if possible. */
656 /* First step: figure out which jobs matter */
657 transaction_find_jobs_that_matter_to_anchor(m, NULL, generation++);
659 /* Second step: Try not to stop any running services if
660 * we don't have to. Don't try to reverse running
661 * jobs if we don't have to. */
662 transaction_minimize_impact(m);
665 /* Third step: Let's remove unneeded jobs that might
667 transaction_collect_garbage(m);
669 /* Fourth step: verify order makes sense and correct
670 * cycles if necessary and possible */
671 if ((r = transaction_verify_order(m, &generation)) >= 0)
677 /* Let's see if the resulting transaction ordering
678 * graph is still cyclic... */
682 /* Fifth step: let's drop unmergeable entries if
683 * necessary and possible, merge entries we can
685 if ((r = transaction_merge_jobs(m)) >= 0)
691 /* Sixth step: an entry got dropped, let's garbage
692 * collect its dependencies. */
693 transaction_collect_garbage(m);
695 /* Let's see if the resulting transaction still has
696 * unmergeable entries ... */
699 /* Seventh step: check whether we can actually apply this */
700 if (mode == JOB_FAIL)
701 if ((r = transaction_is_destructive(m, mode)) < 0)
704 /* Eights step: apply changes */
705 if ((r = transaction_apply(m, mode)) < 0)
708 assert(hashmap_isempty(m->transaction_jobs));
709 assert(!m->transaction_anchor);
714 transaction_abort(m);
718 static Job* transaction_add_one_job(Manager *m, JobType type, Unit *unit, bool force, bool *is_new) {
725 /* Looks for an axisting prospective job and returns that. If
726 * it doesn't exist it is created and added to the prospective
729 f = hashmap_get(m->transaction_jobs, unit);
731 LIST_FOREACH(transaction, j, f) {
732 assert(j->unit == unit);
734 if (j->type == type) {
741 if (unit->meta.job && unit->meta.job->type == type)
743 else if (!(j = job_new(m, type, unit)))
748 j->matters_to_anchor = false;
751 LIST_PREPEND(Job, transaction, f, j);
753 if ((r = hashmap_replace(m->transaction_jobs, unit, f)) < 0) {
764 void manager_transaction_unlink_job(Manager *m, Job *j) {
768 if (j->transaction_prev)
769 j->transaction_prev->transaction_next = j->transaction_next;
770 else if (j->transaction_next)
771 hashmap_replace(m->transaction_jobs, j->unit, j->transaction_next);
773 hashmap_remove_value(m->transaction_jobs, j->unit, j);
775 if (j->transaction_next)
776 j->transaction_next->transaction_prev = j->transaction_prev;
778 j->transaction_prev = j->transaction_next = NULL;
780 while (j->subject_list)
781 job_dependency_free(j->subject_list);
783 while (j->object_list) {
784 Job *other = j->object_list->matters ? j->object_list->subject : NULL;
786 job_dependency_free(j->object_list);
789 log_debug("Deleting job %s/%s as dependency of job %s/%s",
790 unit_id(other->unit), job_type_to_string(other->type),
791 unit_id(j->unit), job_type_to_string(j->type));
792 transaction_delete_job(m, other);
797 static int transaction_add_job_and_dependencies(Manager *m, JobType type, Unit *unit, Job *by, bool matters, bool force, Job **_ret) {
805 assert(type < _JOB_TYPE_MAX);
808 if (unit->meta.load_state != UNIT_LOADED)
811 if (!unit_job_is_applicable(unit, type))
814 /* First add the job. */
815 if (!(ret = transaction_add_one_job(m, type, unit, force, &is_new)))
818 /* Then, add a link to the job. */
819 if (!job_dependency_new(by, ret, matters))
823 /* Finally, recursively add in all dependencies. */
824 if (type == JOB_START || type == JOB_RELOAD_OR_START) {
825 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES], i)
826 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, true, force, NULL)) < 0 && r != -EBADR)
828 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_SOFT_REQUIRES], i)
829 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, !force, force, NULL)) < 0 && r != -EBADR)
831 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_WANTS], i)
832 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, false, force, NULL)) < 0 && r != -EBADR)
834 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE], i)
835 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, true, force, NULL)) < 0 && r != -EBADR)
837 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_SOFT_REQUISITE], i)
838 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, !force, force, NULL)) < 0 && r != -EBADR)
840 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_CONFLICTS], i)
841 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, dep, ret, true, force, NULL)) < 0 && r != -EBADR)
844 } else if (type == JOB_STOP || type == JOB_RESTART || type == JOB_TRY_RESTART) {
846 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRED_BY], i)
847 if ((r = transaction_add_job_and_dependencies(m, type, dep, ret, true, force, NULL)) < 0 && r != -EBADR)
851 /* JOB_VERIFY_STARTED, JOB_RELOAD require no dependency handling */
860 int manager_add_job(Manager *m, JobType type, Unit *unit, JobMode mode, bool force, Job **_ret) {
865 assert(type < _JOB_TYPE_MAX);
867 assert(mode < _JOB_MODE_MAX);
869 if ((r = transaction_add_job_and_dependencies(m, type, unit, NULL, true, force, &ret))) {
870 transaction_abort(m);
874 if ((r = transaction_activate(m, mode)) < 0)
883 Job *manager_get_job(Manager *m, uint32_t id) {
886 return hashmap_get(m->jobs, UINT32_TO_PTR(id));
889 Unit *manager_get_unit(Manager *m, const char *name) {
893 return hashmap_get(m->units, name);
896 static void dispatch_load_queue(Manager *m) {
901 /* Make sure we are not run recursively */
902 if (m->dispatching_load_queue)
905 m->dispatching_load_queue = true;
907 /* Dispatches the load queue. Takes a unit from the queue and
908 * tries to load its data until the queue is empty */
910 while ((meta = m->load_queue)) {
911 assert(meta->in_load_queue);
913 unit_load(UNIT(meta));
916 m->dispatching_load_queue = false;
919 int manager_load_unit(Manager *m, const char *path, Unit **_ret) {
928 /* This will load the service information files, but not actually
929 * start any services or anything. */
931 name = file_name_from_path(path);
933 if ((ret = manager_get_unit(m, name))) {
938 if (!(ret = unit_new(m)))
942 if (!(ret->meta.load_path = strdup(path))) {
948 if ((r = unit_add_name(ret, name)) < 0) {
953 unit_add_to_load_queue(ret);
954 dispatch_load_queue(m);
960 void manager_dump_jobs(Manager *s, FILE *f, const char *prefix) {
967 HASHMAP_FOREACH(j, s->jobs, i)
968 job_dump(j, f, prefix);
971 void manager_dump_units(Manager *s, FILE *f, const char *prefix) {
979 HASHMAP_FOREACH_KEY(u, t, s->units, i)
981 unit_dump(u, f, prefix);
984 void manager_clear_jobs(Manager *m) {
989 transaction_abort(m);
991 while ((j = hashmap_first(m->jobs)))
995 void manager_dispatch_run_queue(Manager *m) {
998 if (m->dispatching_run_queue)
1001 m->dispatching_run_queue = true;
1003 while ((j = m->run_queue)) {
1004 assert(j->installed);
1005 assert(j->in_run_queue);
1007 job_run_and_invalidate(j);
1010 m->dispatching_run_queue = false;
1013 static int manager_dispatch_sigchld(Manager *m) {
1016 log_debug("dispatching SIGCHLD");
1023 if (waitid(P_ALL, 0, &si, WEXITED|WNOHANG) < 0) {
1025 if (errno == ECHILD)
1034 if (si.si_code != CLD_EXITED && si.si_code != CLD_KILLED && si.si_code != CLD_DUMPED)
1037 log_debug("child %llu died (code=%s, status=%i)", (long long unsigned) si.si_pid, sigchld_code(si.si_code), si.si_status);
1039 if (!(u = hashmap_remove(m->watch_pids, UINT32_TO_PTR(si.si_pid))))
1042 UNIT_VTABLE(u)->sigchld_event(u, si.si_pid, si.si_code, si.si_status);
1048 static int manager_process_signal_fd(Manager *m, bool *quit) {
1050 struct signalfd_siginfo sfsi;
1051 bool sigchld = false;
1056 if ((n = read(m->signal_watch.fd, &sfsi, sizeof(sfsi))) != sizeof(sfsi)) {
1061 if (errno == EAGAIN)
1067 switch (sfsi.ssi_signo) {
1079 log_info("Got unhandled signal <%s>.", strsignal(sfsi.ssi_signo));
1084 return manager_dispatch_sigchld(m);
1089 static int process_event(Manager *m, struct epoll_event *ev, bool *quit) {
1096 assert(w = ev->data.ptr);
1100 case WATCH_SIGNAL_FD:
1102 /* An incoming signal? */
1103 if (ev->events != POLLIN)
1106 if ((r = manager_process_signal_fd(m, quit)) < 0)
1113 /* Some fd event, to be dispatched to the units */
1114 UNIT_VTABLE(w->unit)->fd_event(w->unit, w->fd, ev->events, w);
1121 /* Some timer event, to be dispatched to the units */
1122 if ((k = read(ev->data.fd, &v, sizeof(v))) != sizeof(v)) {
1124 if (k < 0 && (errno == EINTR || errno == EAGAIN))
1127 return k < 0 ? -errno : -EIO;
1130 UNIT_VTABLE(w->unit)->timer_event(w->unit, v, w);
1135 assert_not_reached("Unknown epoll event type.");
1141 int manager_loop(Manager *m) {
1148 struct epoll_event event;
1151 manager_dispatch_run_queue(m);
1153 if ((n = epoll_wait(m->epoll_fd, &event, 1, -1)) < 0) {
1155 if (errno == -EINTR)
1163 if ((r = process_event(m, &event, &quit)) < 0)