1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
8 #include <sys/signalfd.h>
19 Manager* manager_new(void) {
22 struct epoll_event ev;
24 if (!(m = new0(Manager, 1)))
27 m->signal_watch.fd = m->epoll_fd = -1;
29 if (!(m->units = hashmap_new(string_hash_func, string_compare_func)))
32 if (!(m->jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
35 if (!(m->transaction_jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
38 if (!(m->watch_pids = hashmap_new(trivial_hash_func, trivial_compare_func)))
41 if ((m->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0)
44 assert_se(sigemptyset(&mask) == 0);
45 assert_se(sigaddset(&mask, SIGCHLD) == 0);
46 assert_se(sigaddset(&mask, SIGINT) == 0);
47 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
49 m->signal_watch.type = WATCH_SIGNAL_FD;
50 if ((m->signal_watch.fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0)
55 ev.data.ptr = &m->signal_watch;
57 if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->signal_watch.fd, &ev) < 0)
67 void manager_free(Manager *m) {
73 while ((j = hashmap_first(m->transaction_jobs)))
76 while ((u = hashmap_first(m->units)))
79 hashmap_free(m->units);
80 hashmap_free(m->jobs);
81 hashmap_free(m->transaction_jobs);
82 hashmap_free(m->watch_pids);
85 close_nointr(m->epoll_fd);
86 if (m->signal_watch.fd >= 0)
87 close_nointr(m->signal_watch.fd);
92 static void transaction_delete_job(Manager *m, Job *j) {
96 /* Deletes one job from the transaction */
98 manager_transaction_unlink_job(m, j);
104 static void transaction_delete_unit(Manager *m, Unit *u) {
107 /* Deletes all jobs associated with a certain unit from the
110 while ((j = hashmap_get(m->transaction_jobs, u)))
111 transaction_delete_job(m, j);
114 static void transaction_clean_dependencies(Manager *m) {
120 /* Drops all dependencies of all installed jobs */
122 HASHMAP_FOREACH(j, m->jobs, i) {
123 while (j->subject_list)
124 job_dependency_free(j->subject_list);
125 while (j->object_list)
126 job_dependency_free(j->object_list);
129 assert(!m->transaction_anchor);
132 static void transaction_abort(Manager *m) {
137 while ((j = hashmap_first(m->transaction_jobs)))
139 transaction_delete_job(m, j);
143 assert(hashmap_isempty(m->transaction_jobs));
145 transaction_clean_dependencies(m);
148 static void transaction_find_jobs_that_matter_to_anchor(Manager *m, Job *j, unsigned generation) {
153 /* A recursive sweep through the graph that marks all units
154 * that matter to the anchor job, i.e. are directly or
155 * indirectly a dependency of the anchor job via paths that
156 * are fully marked as mattering. */
161 l = m->transaction_anchor;
163 LIST_FOREACH(subject, l, l) {
165 /* This link does not matter */
169 /* This unit has already been marked */
170 if (l->object->generation == generation)
173 l->object->matters_to_anchor = true;
174 l->object->generation = generation;
176 transaction_find_jobs_that_matter_to_anchor(m, l->object, generation);
180 static void transaction_merge_and_delete_job(Manager *m, Job *j, Job *other, JobType t) {
181 JobDependency *l, *last;
185 assert(j->unit == other->unit);
186 assert(!j->installed);
188 /* Merges 'other' into 'j' and then deletes j. */
191 j->state = JOB_WAITING;
192 j->forced = j->forced || other->forced;
194 j->matters_to_anchor = j->matters_to_anchor || other->matters_to_anchor;
196 /* Patch us in as new owner of the JobDependency objects */
198 LIST_FOREACH(subject, l, other->subject_list) {
199 assert(l->subject == other);
204 /* Merge both lists */
206 last->subject_next = j->subject_list;
208 j->subject_list->subject_prev = last;
209 j->subject_list = other->subject_list;
212 /* Patch us in as new owner of the JobDependency objects */
214 LIST_FOREACH(object, l, other->object_list) {
215 assert(l->object == other);
220 /* Merge both lists */
222 last->object_next = j->object_list;
224 j->object_list->object_prev = last;
225 j->object_list = other->object_list;
228 /* Kill the other job */
229 other->subject_list = NULL;
230 other->object_list = NULL;
231 transaction_delete_job(m, other);
234 static int delete_one_unmergeable_job(Manager *m, Job *j) {
239 /* Tries to delete one item in the linked list
240 * j->transaction_next->transaction_next->... that conflicts
241 * whith another one, in an attempt to make an inconsistent
242 * transaction work. */
244 /* We rely here on the fact that if a merged with b does not
245 * merge with c, either a or b merge with c neither */
246 LIST_FOREACH(transaction, j, j)
247 LIST_FOREACH(transaction, k, j->transaction_next) {
250 /* Is this one mergeable? Then skip it */
251 if (job_type_is_mergeable(j->type, k->type))
254 /* Ok, we found two that conflict, let's see if we can
255 * drop one of them */
256 if (!j->matters_to_anchor)
258 else if (!k->matters_to_anchor)
263 /* Ok, we can drop one, so let's do so. */
264 log_debug("Try to fix job merging by deleting job %s/%s", unit_id(d->unit), job_type_to_string(d->type));
265 transaction_delete_job(m, d);
272 static int transaction_merge_jobs(Manager *m) {
279 /* First step, check whether any of the jobs for one specific
280 * task conflict. If so, try to drop one of them. */
281 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
286 LIST_FOREACH(transaction, k, j->transaction_next) {
287 if ((r = job_type_merge(&t, k->type)) >= 0)
290 /* OK, we could not merge all jobs for this
291 * action. Let's see if we can get rid of one
294 if ((r = delete_one_unmergeable_job(m, j)) >= 0)
295 /* Ok, we managed to drop one, now
296 * let's ask our callers to call us
297 * again after garbage collecting */
300 /* We couldn't merge anything. Failure */
305 /* Second step, merge the jobs. */
306 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
310 /* Merge all transactions */
311 LIST_FOREACH(transaction, k, j->transaction_next)
312 assert_se(job_type_merge(&t, k->type) == 0);
314 /* If an active job is mergeable, merge it too */
315 if (j->unit->meta.job)
316 job_type_merge(&t, j->unit->meta.job->type); /* Might fail. Which is OK */
318 while ((k = j->transaction_next)) {
320 transaction_merge_and_delete_job(m, k, j, t);
323 transaction_merge_and_delete_job(m, j, k, t);
326 assert(!j->transaction_next);
327 assert(!j->transaction_prev);
333 static bool unit_matters_to_anchor(Unit *u, Job *j) {
335 assert(!j->transaction_prev);
337 /* Checks whether at least one of the jobs for this unit
338 * matters to the anchor. */
340 LIST_FOREACH(transaction, j, j)
341 if (j->matters_to_anchor)
347 static int transaction_verify_order_one(Manager *m, Job *j, Job *from, unsigned generation) {
354 assert(!j->transaction_prev);
356 /* Does a recursive sweep through the ordering graph, looking
357 * for a cycle. If we find cycle we try to break it. */
359 /* Did we find a cycle? */
360 if (j->marker && j->generation == generation) {
363 /* So, we already have been here. We have a
364 * cycle. Let's try to break it. We go backwards in
365 * our path and try to find a suitable job to
366 * remove. We use the marker to find our way back,
367 * since smart how we are we stored our way back in
370 for (k = from; k; k = (k->generation == generation ? k->marker : NULL)) {
373 !unit_matters_to_anchor(k->unit, k)) {
374 /* Ok, we can drop this one, so let's
376 log_debug("Breaking order cycle by deleting job %s/%s", unit_id(k->unit), job_type_to_string(k->type));
377 transaction_delete_unit(m, k->unit);
381 /* Check if this in fact was the beginning of
390 /* Make the marker point to where we come from, so that we can
391 * find our way backwards if we want to break a cycle */
393 j->generation = generation;
395 /* We assume that the the dependencies are bidirectional, and
396 * hence can ignore UNIT_AFTER */
397 SET_FOREACH(u, j->unit->meta.dependencies[UNIT_BEFORE], i) {
400 /* Is there a job for this unit? */
401 if (!(o = hashmap_get(m->transaction_jobs, u)))
403 /* Ok, there is no job for this in the
404 * transaction, but maybe there is already one
406 if (!(o = u->meta.job))
409 if ((r = transaction_verify_order_one(m, o, j, generation)) < 0)
416 static int transaction_verify_order(Manager *m, unsigned *generation) {
424 /* Check if the ordering graph is cyclic. If it is, try to fix
425 * that up by dropping one of the jobs. */
427 HASHMAP_FOREACH(j, m->transaction_jobs, i)
428 if ((r = transaction_verify_order_one(m, j, NULL, (*generation)++)) < 0)
434 static void transaction_collect_garbage(Manager *m) {
439 /* Drop jobs that are not required by any other job */
447 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
451 log_debug("Garbage collecting job %s/%s", unit_id(j->unit), job_type_to_string(j->type));
452 transaction_delete_job(m, j);
460 static int transaction_is_destructive(Manager *m, JobMode mode) {
466 /* Checks whether applying this transaction means that
467 * existing jobs would be replaced */
469 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
472 assert(!j->transaction_prev);
473 assert(!j->transaction_next);
475 if (j->unit->meta.job &&
476 j->unit->meta.job != j &&
477 !job_type_is_superset(j->type, j->unit->meta.job->type))
484 static void transaction_minimize_impact(Manager *m) {
488 /* Drops all unnecessary jobs that reverse already active jobs
489 * or that stop a running service. */
497 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
498 LIST_FOREACH(transaction, j, j) {
500 /* If it matters, we shouldn't drop it */
501 if (j->matters_to_anchor)
504 /* Would this stop a running service?
505 * Would this change an existing job?
506 * If so, let's drop this entry */
507 if ((j->type != JOB_STOP || UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(j->unit))) &&
508 (!j->unit->meta.job || job_type_is_conflicting(j->type, j->unit->meta.job->state)))
511 /* Ok, let's get rid of this */
512 log_debug("Deleting %s/%s to minimize impact", unit_id(j->unit), job_type_to_string(j->type));
513 transaction_delete_job(m, j);
525 static int transaction_apply(Manager *m, JobMode mode) {
530 /* Moves the transaction jobs to the set of active jobs */
532 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
534 assert(!j->transaction_prev);
535 assert(!j->transaction_next);
540 if ((r = hashmap_put(m->jobs, UINT32_TO_PTR(j->id), j)) < 0)
544 while ((j = hashmap_steal_first(m->transaction_jobs))) {
548 if (j->unit->meta.job)
549 job_free(j->unit->meta.job);
551 j->unit->meta.job = j;
554 /* We're fully installed. Now let's free data we don't
557 assert(!j->transaction_next);
558 assert(!j->transaction_prev);
563 /* As last step, kill all remaining job dependencies. */
564 transaction_clean_dependencies(m);
570 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
574 hashmap_remove(m->jobs, UINT32_TO_PTR(j->id));
580 static int transaction_activate(Manager *m, JobMode mode) {
582 unsigned generation = 1;
586 /* This applies the changes recorded in transaction_jobs to
587 * the actual list of jobs, if possible. */
589 /* First step: figure out which jobs matter */
590 transaction_find_jobs_that_matter_to_anchor(m, NULL, generation++);
592 /* Second step: Try not to stop any running services if
593 * we don't have to. Don't try to reverse running
594 * jobs if we don't have to. */
595 transaction_minimize_impact(m);
598 /* Third step: Let's remove unneeded jobs that might
600 transaction_collect_garbage(m);
602 /* Fourth step: verify order makes sense and correct
603 * cycles if necessary and possible */
604 if ((r = transaction_verify_order(m, &generation)) >= 0)
610 /* Let's see if the resulting transaction ordering
611 * graph is still cyclic... */
615 /* Fifth step: let's drop unmergeable entries if
616 * necessary and possible, merge entries we can
618 if ((r = transaction_merge_jobs(m)) >= 0)
624 /* Sixth step: an entry got dropped, let's garbage
625 * collect its dependencies. */
626 transaction_collect_garbage(m);
628 /* Let's see if the resulting transaction still has
629 * unmergeable entries ... */
632 /* Seventh step: check whether we can actually apply this */
633 if (mode == JOB_FAIL)
634 if ((r = transaction_is_destructive(m, mode)) < 0)
637 /* Eights step: apply changes */
638 if ((r = transaction_apply(m, mode)) < 0)
641 assert(hashmap_isempty(m->transaction_jobs));
642 assert(!m->transaction_anchor);
647 transaction_abort(m);
651 static Job* transaction_add_one_job(Manager *m, JobType type, Unit *unit, bool force, bool *is_new) {
658 /* Looks for an axisting prospective job and returns that. If
659 * it doesn't exist it is created and added to the prospective
662 f = hashmap_get(m->transaction_jobs, unit);
664 LIST_FOREACH(transaction, j, f) {
665 assert(j->unit == unit);
667 if (j->type == type) {
674 if (unit->meta.job && unit->meta.job->type == type)
676 else if (!(j = job_new(m, type, unit)))
681 j->matters_to_anchor = false;
684 LIST_PREPEND(Job, transaction, f, j);
686 if ((r = hashmap_replace(m->transaction_jobs, unit, f)) < 0) {
697 void manager_transaction_unlink_job(Manager *m, Job *j) {
701 if (j->transaction_prev)
702 j->transaction_prev->transaction_next = j->transaction_next;
703 else if (j->transaction_next)
704 hashmap_replace(m->transaction_jobs, j->unit, j->transaction_next);
706 hashmap_remove_value(m->transaction_jobs, j->unit, j);
708 if (j->transaction_next)
709 j->transaction_next->transaction_prev = j->transaction_prev;
711 j->transaction_prev = j->transaction_next = NULL;
713 while (j->subject_list)
714 job_dependency_free(j->subject_list);
716 while (j->object_list) {
717 Job *other = j->object_list->matters ? j->object_list->subject : NULL;
719 job_dependency_free(j->object_list);
722 log_debug("Deleting job %s/%s as dependency of job %s/%s",
723 unit_id(other->unit), job_type_to_string(other->type),
724 unit_id(j->unit), job_type_to_string(j->type));
725 transaction_delete_job(m, other);
730 static int transaction_add_job_and_dependencies(Manager *m, JobType type, Unit *unit, Job *by, bool matters, bool force, Job **_ret) {
738 assert(type < _JOB_TYPE_MAX);
741 if (unit->meta.load_state != UNIT_LOADED)
744 if (!unit_job_is_applicable(unit, type))
747 /* First add the job. */
748 if (!(ret = transaction_add_one_job(m, type, unit, force, &is_new)))
751 /* Then, add a link to the job. */
752 if (!job_dependency_new(by, ret, matters))
756 /* Finally, recursively add in all dependencies. */
757 if (type == JOB_START || type == JOB_RELOAD_OR_START) {
758 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES], i)
759 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, true, force, NULL)) < 0 && r != -EBADR)
761 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_SOFT_REQUIRES], i)
762 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, !force, force, NULL)) < 0 && r != -EBADR)
764 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_WANTS], i)
765 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, false, force, NULL)) < 0 && r != -EBADR)
767 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE], i)
768 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, true, force, NULL)) < 0 && r != -EBADR)
770 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_SOFT_REQUISITE], i)
771 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, !force, force, NULL)) < 0 && r != -EBADR)
773 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_CONFLICTS], i)
774 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, dep, ret, true, force, NULL)) < 0 && r != -EBADR)
777 } else if (type == JOB_STOP || type == JOB_RESTART || type == JOB_TRY_RESTART) {
779 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRED_BY], i)
780 if ((r = transaction_add_job_and_dependencies(m, type, dep, ret, true, force, NULL)) < 0 && r != -EBADR)
784 /* JOB_VERIFY_STARTED, JOB_RELOAD require no dependency handling */
793 int manager_add_job(Manager *m, JobType type, Unit *unit, JobMode mode, bool force, Job **_ret) {
798 assert(type < _JOB_TYPE_MAX);
800 assert(mode < _JOB_MODE_MAX);
802 if ((r = transaction_add_job_and_dependencies(m, type, unit, NULL, true, force, &ret))) {
803 transaction_abort(m);
807 if ((r = transaction_activate(m, mode)) < 0)
816 Job *manager_get_job(Manager *m, uint32_t id) {
819 return hashmap_get(m->jobs, UINT32_TO_PTR(id));
822 Unit *manager_get_unit(Manager *m, const char *name) {
826 return hashmap_get(m->units, name);
829 static void dispatch_load_queue(Manager *m) {
834 /* Make sure we are not run recursively */
835 if (m->dispatching_load_queue)
838 m->dispatching_load_queue = true;
840 /* Dispatches the load queue. Takes a unit from the queue and
841 * tries to load its data until the queue is empty */
843 while ((meta = m->load_queue)) {
844 assert(meta->in_load_queue);
846 unit_load(UNIT(meta));
849 m->dispatching_load_queue = false;
852 int manager_load_unit(Manager *m, const char *path, Unit **_ret) {
861 /* This will load the service information files, but not actually
862 * start any services or anything. */
864 name = file_name_from_path(path);
866 if ((ret = manager_get_unit(m, name))) {
871 if (!(ret = unit_new(m)))
875 if (!(ret->meta.load_path = strdup(path))) {
881 if ((r = unit_add_name(ret, name)) < 0) {
886 unit_add_to_load_queue(ret);
887 dispatch_load_queue(m);
893 void manager_dump_jobs(Manager *s, FILE *f, const char *prefix) {
900 HASHMAP_FOREACH(j, s->jobs, i)
901 job_dump(j, f, prefix);
904 void manager_dump_units(Manager *s, FILE *f, const char *prefix) {
912 HASHMAP_FOREACH_KEY(u, t, s->units, i)
914 unit_dump(u, f, prefix);
917 void manager_clear_jobs(Manager *m) {
922 transaction_abort(m);
924 while ((j = hashmap_first(m->jobs)))
928 void manager_dispatch_run_queue(Manager *m) {
931 if (m->dispatching_run_queue)
934 m->dispatching_run_queue = true;
936 while ((j = m->run_queue)) {
937 assert(j->installed);
938 assert(j->in_run_queue);
940 job_run_and_invalidate(j);
943 m->dispatching_run_queue = false;
946 static int manager_dispatch_sigchld(Manager *m) {
949 log_debug("dispatching SIGCHLD");
956 if (waitid(P_ALL, 0, &si, WEXITED|WNOHANG) < 0) {
967 if (si.si_code != CLD_EXITED && si.si_code != CLD_KILLED && si.si_code != CLD_DUMPED)
970 log_debug("child %llu died (code=%s, status=%i)", (long long unsigned) si.si_pid, sigchld_code(si.si_code), si.si_status);
972 if (!(u = hashmap_remove(m->watch_pids, UINT32_TO_PTR(si.si_pid))))
975 UNIT_VTABLE(u)->sigchld_event(u, si.si_pid, si.si_code, si.si_status);
981 static int manager_process_signal_fd(Manager *m, bool *quit) {
983 struct signalfd_siginfo sfsi;
984 bool sigchld = false;
989 if ((n = read(m->signal_watch.fd, &sfsi, sizeof(sfsi))) != sizeof(sfsi)) {
1000 switch (sfsi.ssi_signo) {
1013 return manager_dispatch_sigchld(m);
1018 static int process_event(Manager *m, struct epoll_event *ev, bool *quit) {
1025 assert(w = ev->data.ptr);
1029 case WATCH_SIGNAL_FD:
1031 /* An incoming signal? */
1032 if (ev->events != POLLIN)
1035 if ((r = manager_process_signal_fd(m, quit)) < 0)
1042 /* Some fd event, to be dispatched to the units */
1043 UNIT_VTABLE(w->unit)->fd_event(w->unit, w->fd, ev->events, w);
1050 /* Some timer event, to be dispatched to the units */
1051 if ((k = read(ev->data.fd, &v, sizeof(v))) != sizeof(v)) {
1053 if (k < 0 && (errno == EINTR || errno == EAGAIN))
1056 return k < 0 ? -errno : -EIO;
1059 UNIT_VTABLE(w->unit)->timer_event(w->unit, v, w);
1064 assert_not_reached("Unknown epoll event type.");
1070 int manager_loop(Manager *m) {
1077 struct epoll_event events[32];
1080 manager_dispatch_run_queue(m);
1082 if ((n = epoll_wait(m->epoll_fd, events, ELEMENTSOF(events), -1)) < 0) {
1084 if (errno == -EINTR)
1090 for (i = 0; i < n; i++) {
1091 if ((r = process_event(m, events + i, &quit)) < 0)