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_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(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
48 if ((m->signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0)
53 ev.data.fd = m->signal_fd;
55 if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->signal_fd, &ev) < 0)
65 void manager_free(Manager *m) {
71 while ((j = hashmap_first(m->transaction_jobs)))
74 while ((u = hashmap_first(m->units)))
77 hashmap_free(m->units);
78 hashmap_free(m->jobs);
79 hashmap_free(m->transaction_jobs);
80 hashmap_free(m->watch_pids);
83 close_nointr(m->epoll_fd);
84 if (m->signal_fd >= 0)
85 close_nointr(m->signal_fd);
90 static void transaction_delete_job(Manager *m, Job *j) {
94 /* Deletes one job from the transaction */
96 manager_transaction_unlink_job(m, j);
102 static void transaction_delete_unit(Manager *m, Unit *u) {
105 /* Deletes all jobs associated with a certain unit from the
108 while ((j = hashmap_get(m->transaction_jobs, u)))
109 transaction_delete_job(m, j);
112 static void transaction_clean_dependencies(Manager *m) {
118 /* Drops all dependencies of all installed jobs */
120 HASHMAP_FOREACH(j, m->jobs, i) {
121 while (j->subject_list)
122 job_dependency_free(j->subject_list);
123 while (j->object_list)
124 job_dependency_free(j->object_list);
127 assert(!m->transaction_anchor);
130 static void transaction_abort(Manager *m) {
135 while ((j = hashmap_first(m->transaction_jobs)))
137 transaction_delete_job(m, j);
141 assert(hashmap_isempty(m->transaction_jobs));
143 transaction_clean_dependencies(m);
146 static void transaction_find_jobs_that_matter_to_anchor(Manager *m, Job *j, unsigned generation) {
151 /* A recursive sweep through the graph that marks all units
152 * that matter to the anchor job, i.e. are directly or
153 * indirectly a dependency of the anchor job via paths that
154 * are fully marked as mattering. */
159 l = m->transaction_anchor;
161 LIST_FOREACH(subject, l, l) {
163 /* This link does not matter */
167 /* This unit has already been marked */
168 if (l->object->generation == generation)
171 l->object->matters_to_anchor = true;
172 l->object->generation = generation;
174 transaction_find_jobs_that_matter_to_anchor(m, l->object, generation);
178 static void transaction_merge_and_delete_job(Manager *m, Job *j, Job *other, JobType t) {
179 JobDependency *l, *last;
183 assert(j->unit == other->unit);
184 assert(!j->installed);
186 /* Merges 'other' into 'j' and then deletes j. */
189 j->state = JOB_WAITING;
190 j->forced = j->forced || other->forced;
192 j->matters_to_anchor = j->matters_to_anchor || other->matters_to_anchor;
194 /* Patch us in as new owner of the JobDependency objects */
196 LIST_FOREACH(subject, l, other->subject_list) {
197 assert(l->subject == other);
202 /* Merge both lists */
204 last->subject_next = j->subject_list;
206 j->subject_list->subject_prev = last;
207 j->subject_list = other->subject_list;
210 /* Patch us in as new owner of the JobDependency objects */
212 LIST_FOREACH(object, l, other->object_list) {
213 assert(l->object == other);
218 /* Merge both lists */
220 last->object_next = j->object_list;
222 j->object_list->object_prev = last;
223 j->object_list = other->object_list;
226 /* Kill the other job */
227 other->subject_list = NULL;
228 other->object_list = NULL;
229 transaction_delete_job(m, other);
232 static int delete_one_unmergeable_job(Manager *m, Job *j) {
237 /* Tries to delete one item in the linked list
238 * j->transaction_next->transaction_next->... that conflicts
239 * whith another one, in an attempt to make an inconsistent
240 * transaction work. */
242 /* We rely here on the fact that if a merged with b does not
243 * merge with c, either a or b merge with c neither */
244 LIST_FOREACH(transaction, j, j)
245 LIST_FOREACH(transaction, k, j->transaction_next) {
248 /* Is this one mergeable? Then skip it */
249 if (job_type_is_mergeable(j->type, k->type))
252 /* Ok, we found two that conflict, let's see if we can
253 * drop one of them */
254 if (!j->matters_to_anchor)
256 else if (!k->matters_to_anchor)
261 /* Ok, we can drop one, so let's do so. */
262 log_debug("Try to fix job merging by deleting job %s/%s", unit_id(d->unit), job_type_to_string(d->type));
263 transaction_delete_job(m, d);
270 static int transaction_merge_jobs(Manager *m) {
277 /* First step, check whether any of the jobs for one specific
278 * task conflict. If so, try to drop one of them. */
279 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
284 LIST_FOREACH(transaction, k, j->transaction_next) {
285 if ((r = job_type_merge(&t, k->type)) >= 0)
288 /* OK, we could not merge all jobs for this
289 * action. Let's see if we can get rid of one
292 if ((r = delete_one_unmergeable_job(m, j)) >= 0)
293 /* Ok, we managed to drop one, now
294 * let's ask our callers to call us
295 * again after garbage collecting */
298 /* We couldn't merge anything. Failure */
303 /* Second step, merge the jobs. */
304 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
308 /* Merge all transactions */
309 LIST_FOREACH(transaction, k, j->transaction_next)
310 assert_se(job_type_merge(&t, k->type) == 0);
312 /* If an active job is mergeable, merge it too */
313 if (j->unit->meta.job)
314 job_type_merge(&t, j->unit->meta.job->type); /* Might fail. Which is OK */
316 while ((k = j->transaction_next)) {
318 transaction_merge_and_delete_job(m, k, j, t);
321 transaction_merge_and_delete_job(m, j, k, t);
324 assert(!j->transaction_next);
325 assert(!j->transaction_prev);
331 static bool unit_matters_to_anchor(Unit *u, Job *j) {
333 assert(!j->transaction_prev);
335 /* Checks whether at least one of the jobs for this unit
336 * matters to the anchor. */
338 LIST_FOREACH(transaction, j, j)
339 if (j->matters_to_anchor)
345 static int transaction_verify_order_one(Manager *m, Job *j, Job *from, unsigned generation) {
352 assert(!j->transaction_prev);
354 /* Does a recursive sweep through the ordering graph, looking
355 * for a cycle. If we find cycle we try to break it. */
357 /* Did we find a cycle? */
358 if (j->marker && j->generation == generation) {
361 /* So, we already have been here. We have a
362 * cycle. Let's try to break it. We go backwards in
363 * our path and try to find a suitable job to
364 * remove. We use the marker to find our way back,
365 * since smart how we are we stored our way back in
368 for (k = from; k; k = (k->generation == generation ? k->marker : NULL)) {
371 !unit_matters_to_anchor(k->unit, k)) {
372 /* Ok, we can drop this one, so let's
374 log_debug("Breaking order cycle by deleting job %s/%s", unit_id(k->unit), job_type_to_string(k->type));
375 transaction_delete_unit(m, k->unit);
379 /* Check if this in fact was the beginning of
388 /* Make the marker point to where we come from, so that we can
389 * find our way backwards if we want to break a cycle */
391 j->generation = generation;
393 /* We assume that the the dependencies are bidirectional, and
394 * hence can ignore UNIT_AFTER */
395 SET_FOREACH(u, j->unit->meta.dependencies[UNIT_BEFORE], i) {
398 /* Is there a job for this unit? */
399 if (!(o = hashmap_get(m->transaction_jobs, u)))
401 /* Ok, there is no job for this in the
402 * transaction, but maybe there is already one
404 if (!(o = u->meta.job))
407 if ((r = transaction_verify_order_one(m, o, j, generation)) < 0)
414 static int transaction_verify_order(Manager *m, unsigned *generation) {
422 /* Check if the ordering graph is cyclic. If it is, try to fix
423 * that up by dropping one of the jobs. */
425 HASHMAP_FOREACH(j, m->transaction_jobs, i)
426 if ((r = transaction_verify_order_one(m, j, NULL, (*generation)++)) < 0)
432 static void transaction_collect_garbage(Manager *m) {
437 /* Drop jobs that are not required by any other job */
445 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
449 log_debug("Garbage collecting job %s/%s", unit_id(j->unit), job_type_to_string(j->type));
450 transaction_delete_job(m, j);
458 static int transaction_is_destructive(Manager *m, JobMode mode) {
464 /* Checks whether applying this transaction means that
465 * existing jobs would be replaced */
467 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
470 assert(!j->transaction_prev);
471 assert(!j->transaction_next);
473 if (j->unit->meta.job &&
474 j->unit->meta.job != j &&
475 !job_type_is_superset(j->type, j->unit->meta.job->type))
482 static void transaction_minimize_impact(Manager *m) {
486 /* Drops all unnecessary jobs that reverse already active jobs
487 * or that stop a running service. */
495 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
496 LIST_FOREACH(transaction, j, j) {
498 /* If it matters, we shouldn't drop it */
499 if (j->matters_to_anchor)
502 /* Would this stop a running service?
503 * Would this change an existing job?
504 * If so, let's drop this entry */
505 if ((j->type != JOB_STOP || UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(j->unit))) &&
506 (!j->unit->meta.job || job_type_is_conflicting(j->type, j->unit->meta.job->state)))
509 /* Ok, let's get rid of this */
510 log_debug("Deleting %s/%s to minimize impact", unit_id(j->unit), job_type_to_string(j->type));
511 transaction_delete_job(m, j);
523 static int transaction_apply(Manager *m, JobMode mode) {
528 /* Moves the transaction jobs to the set of active jobs */
530 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
532 assert(!j->transaction_prev);
533 assert(!j->transaction_next);
538 if ((r = hashmap_put(m->jobs, UINT32_TO_PTR(j->id), j)) < 0)
542 while ((j = hashmap_steal_first(m->transaction_jobs))) {
546 if (j->unit->meta.job)
547 job_free(j->unit->meta.job);
549 j->unit->meta.job = j;
552 /* We're fully installed. Now let's free data we don't
555 assert(!j->transaction_next);
556 assert(!j->transaction_prev);
560 /* As last step, kill all remaining job dependencies. */
561 transaction_clean_dependencies(m);
567 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
571 hashmap_remove(m->jobs, UINT32_TO_PTR(j->id));
577 static int transaction_activate(Manager *m, JobMode mode) {
579 unsigned generation = 1;
583 /* This applies the changes recorded in transaction_jobs to
584 * the actual list of jobs, if possible. */
586 /* First step: figure out which jobs matter */
587 transaction_find_jobs_that_matter_to_anchor(m, NULL, generation++);
589 /* Second step: Try not to stop any running services if
590 * we don't have to. Don't try to reverse running
591 * jobs if we don't have to. */
592 transaction_minimize_impact(m);
595 /* Third step: Let's remove unneeded jobs that might
597 transaction_collect_garbage(m);
599 /* Fourth step: verify order makes sense and correct
600 * cycles if necessary and possible */
601 if ((r = transaction_verify_order(m, &generation)) >= 0)
607 /* Let's see if the resulting transaction ordering
608 * graph is still cyclic... */
612 /* Fifth step: let's drop unmergeable entries if
613 * necessary and possible, merge entries we can
615 if ((r = transaction_merge_jobs(m)) >= 0)
621 /* Sixth step: an entry got dropped, let's garbage
622 * collect its dependencies. */
623 transaction_collect_garbage(m);
625 /* Let's see if the resulting transaction still has
626 * unmergeable entries ... */
629 /* Seventh step: check whether we can actually apply this */
630 if (mode == JOB_FAIL)
631 if ((r = transaction_is_destructive(m, mode)) < 0)
634 /* Eights step: apply changes */
635 if ((r = transaction_apply(m, mode)) < 0)
638 assert(hashmap_isempty(m->transaction_jobs));
639 assert(!m->transaction_anchor);
644 transaction_abort(m);
648 static Job* transaction_add_one_job(Manager *m, JobType type, Unit *unit, bool force, bool *is_new) {
655 /* Looks for an axisting prospective job and returns that. If
656 * it doesn't exist it is created and added to the prospective
659 f = hashmap_get(m->transaction_jobs, unit);
661 LIST_FOREACH(transaction, j, f) {
662 assert(j->unit == unit);
664 if (j->type == type) {
671 if (unit->meta.job && unit->meta.job->type == type)
673 else if (!(j = job_new(m, type, unit)))
678 j->matters_to_anchor = false;
681 LIST_PREPEND(Job, transaction, f, j);
683 if ((r = hashmap_replace(m->transaction_jobs, unit, f)) < 0) {
694 void manager_transaction_unlink_job(Manager *m, Job *j) {
698 if (j->transaction_prev)
699 j->transaction_prev->transaction_next = j->transaction_next;
700 else if (j->transaction_next)
701 hashmap_replace(m->transaction_jobs, j->unit, j->transaction_next);
703 hashmap_remove_value(m->transaction_jobs, j->unit, j);
705 if (j->transaction_next)
706 j->transaction_next->transaction_prev = j->transaction_prev;
708 j->transaction_prev = j->transaction_next = NULL;
710 while (j->subject_list)
711 job_dependency_free(j->subject_list);
713 while (j->object_list) {
714 Job *other = j->object_list->matters ? j->object_list->subject : NULL;
716 job_dependency_free(j->object_list);
719 log_debug("Deleting job %s/%s as dependency of job %s/%s",
720 unit_id(other->unit), job_type_to_string(other->type),
721 unit_id(j->unit), job_type_to_string(j->type));
722 transaction_delete_job(m, other);
727 static int transaction_add_job_and_dependencies(Manager *m, JobType type, Unit *unit, Job *by, bool matters, bool force, Job **_ret) {
735 assert(type < _JOB_TYPE_MAX);
738 if (unit->meta.load_state != UNIT_LOADED)
741 if (!unit_job_is_applicable(unit, type))
744 /* First add the job. */
745 if (!(ret = transaction_add_one_job(m, type, unit, force, &is_new)))
748 /* Then, add a link to the job. */
749 if (!job_dependency_new(by, ret, matters))
753 /* Finally, recursively add in all dependencies. */
754 if (type == JOB_START || type == JOB_RELOAD_OR_START) {
755 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES], i)
756 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, true, force, NULL)) < 0 && r != -EBADR)
758 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_SOFT_REQUIRES], i)
759 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, !force, force, NULL)) < 0 && r != -EBADR)
761 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_WANTS], i)
762 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, false, force, NULL)) < 0 && r != -EBADR)
764 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE], i)
765 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, true, force, NULL)) < 0 && r != -EBADR)
767 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_SOFT_REQUISITE], i)
768 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, !force, force, NULL)) < 0 && r != -EBADR)
770 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_CONFLICTS], i)
771 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, dep, ret, true, force, NULL)) < 0 && r != -EBADR)
774 } else if (type == JOB_STOP || type == JOB_RESTART || type == JOB_TRY_RESTART) {
776 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRED_BY], i)
777 if ((r = transaction_add_job_and_dependencies(m, type, dep, ret, true, force, NULL)) < 0 && r != -EBADR)
781 /* JOB_VERIFY_STARTED, JOB_RELOAD require no dependency handling */
790 int manager_add_job(Manager *m, JobType type, Unit *unit, JobMode mode, bool force, Job **_ret) {
795 assert(type < _JOB_TYPE_MAX);
797 assert(mode < _JOB_MODE_MAX);
799 if ((r = transaction_add_job_and_dependencies(m, type, unit, NULL, true, force, &ret))) {
800 transaction_abort(m);
804 if ((r = transaction_activate(m, mode)) < 0)
813 Job *manager_get_job(Manager *m, uint32_t id) {
816 return hashmap_get(m->jobs, UINT32_TO_PTR(id));
819 Unit *manager_get_unit(Manager *m, const char *name) {
823 return hashmap_get(m->units, name);
826 static void dispatch_load_queue(Manager *m) {
831 /* Make sure we are not run recursively */
832 if (m->dispatching_load_queue)
835 m->dispatching_load_queue = true;
837 /* Dispatches the load queue. Takes a unit from the queue and
838 * tries to load its data until the queue is empty */
840 while ((meta = m->load_queue)) {
841 assert(meta->in_load_queue);
843 unit_load(UNIT(meta));
846 m->dispatching_load_queue = false;
849 int manager_load_unit(Manager *m, const char *path, Unit **_ret) {
858 /* This will load the service information files, but not actually
859 * start any services or anything. */
861 name = file_name_from_path(path);
863 if ((ret = manager_get_unit(m, name))) {
868 if (!(ret = unit_new(m)))
872 if (!(ret->meta.load_path = strdup(path))) {
878 if ((r = unit_add_name(ret, name)) < 0) {
883 unit_add_to_load_queue(ret);
884 dispatch_load_queue(m);
890 void manager_dump_jobs(Manager *s, FILE *f, const char *prefix) {
897 HASHMAP_FOREACH(j, s->jobs, i)
898 job_dump(j, f, prefix);
901 void manager_dump_units(Manager *s, FILE *f, const char *prefix) {
909 HASHMAP_FOREACH_KEY(u, t, s->units, i)
911 unit_dump(u, f, prefix);
914 void manager_clear_jobs(Manager *m) {
919 transaction_abort(m);
921 while ((j = hashmap_first(m->jobs)))
925 void manager_dispatch_run_queue(Manager *m) {
928 if (m->dispatching_run_queue)
931 m->dispatching_run_queue = true;
933 while ((j = m->run_queue)) {
934 assert(j->installed);
935 assert(j->in_run_queue);
937 job_run_and_invalidate(j);
940 m->dispatching_run_queue = false;
943 static int manager_dispatch_sigchld(Manager *m) {
951 if (waitid(P_ALL, 0, &si, WNOHANG) < 0)
957 if (si.si_code != CLD_EXITED && si.si_code != CLD_KILLED && si.si_code != CLD_DUMPED)
960 if (!(u = hashmap_remove(m->watch_pids, UINT32_TO_PTR(si.si_pid))))
963 UNIT_VTABLE(u)->sigchld_event(u, si.si_pid, si.si_code, si.si_status);
969 static int manager_process_signal_fd(Manager *m) {
971 struct signalfd_siginfo sfsi;
972 bool sigchld = false;
977 if ((n = read(m->signal_fd, &sfsi, sizeof(sfsi))) != sizeof(sfsi)) {
988 if (sfsi.ssi_signo == SIGCHLD)
993 return manager_dispatch_sigchld(m);
998 static int process_event(Manager *m, struct epoll_event *ev) {
1004 switch (ev->data.u32) {
1006 case MANAGER_SIGNAL:
1007 assert(ev->data.fd == m->signal_fd);
1009 /* An incoming signal? */
1010 if (ev->events != POLLIN)
1013 if ((r = manager_process_signal_fd(m)) < 0)
1021 /* Some fd event, to be dispatched to the units */
1022 assert_se(u = ev->data.ptr);
1023 UNIT_VTABLE(u)->fd_event(u, ev->data.fd, ev->events);
1027 case MANAGER_TIMER: {
1032 /* Some timer event, to be dispatched to the units */
1033 if ((k = read(ev->data.fd, &v, sizeof(v))) != sizeof(v)) {
1035 if (k < 0 && (errno == EINTR || errno == EAGAIN))
1038 return k < 0 ? -errno : -EIO;
1041 assert_se(u = ev->data.ptr);
1042 UNIT_VTABLE(u)->timer_event(u, ev->data.fd, v);
1047 assert_not_reached("Unknown epoll event type.");
1053 int manager_loop(Manager *m) {
1059 struct epoll_event events[32];
1062 manager_dispatch_run_queue(m);
1064 if ((n = epoll_wait(m->epoll_fd, events, ELEMENTSOF(events), -1)) < 0) {
1066 if (errno == -EINTR)
1072 for (i = 0; i < n; i++)
1073 if ((r = process_event(m, events + i)) < 0)