chiark / gitweb /
a32755cedc492c3996bda1869111f095c30f3572
[elogind.git] / manager.c
1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
2
3 #include <assert.h>
4 #include <errno.h>
5 #include <string.h>
6 #include <sys/epoll.h>
7 #include <signal.h>
8 #include <sys/signalfd.h>
9 #include <sys/wait.h>
10 #include <unistd.h>
11 #include <sys/poll.h>
12
13 #include "manager.h"
14 #include "hashmap.h"
15 #include "macro.h"
16 #include "strv.h"
17 #include "log.h"
18 #include "util.h"
19
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 };
25
26 static int manager_setup_signals(Manager *m) {
27         sigset_t mask;
28         struct epoll_event ev;
29
30         assert(m);
31
32         assert_se(reset_all_signal_handlers() == 0);
33
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);
44
45         m->signal_watch.type = WATCH_SIGNAL_FD;
46         if ((m->signal_watch.fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0)
47                 return -errno;
48
49         zero(ev);
50         ev.events = EPOLLIN;
51         ev.data.ptr = &m->signal_watch;
52
53         if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->signal_watch.fd, &ev) < 0)
54                 return -errno;
55
56         return 0;
57 }
58
59 static int manager_load_special_units(Manager *m) {
60         SpecialUnit c;
61         int r;
62
63         assert(m);
64
65         /* Loads all 'special' units, so that we have easy access to them later */
66
67         for (c = 0; c < _SPECIAL_UNIT_MAX; c++)
68                 if ((r = manager_load_unit(m, special_table[c], m->special_units+c)) < 0)
69                         return r;
70
71         return 0;
72 };
73
74 Manager* manager_new(void) {
75         Manager *m;
76
77         if (!(m = new0(Manager, 1)))
78                 return NULL;
79
80         m->signal_watch.fd = m->epoll_fd = -1;
81
82         if (!(m->units = hashmap_new(string_hash_func, string_compare_func)))
83                 goto fail;
84
85         if (!(m->jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
86                 goto fail;
87
88         if (!(m->transaction_jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
89                 goto fail;
90
91         if (!(m->watch_pids = hashmap_new(trivial_hash_func, trivial_compare_func)))
92                 goto fail;
93
94         if ((m->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0)
95                 goto fail;
96
97         if (manager_setup_signals(m) < 0)
98                 goto fail;
99
100         if (manager_load_special_units(m) < 0)
101                 goto fail;
102
103         return m;
104
105 fail:
106         manager_free(m);
107         return NULL;
108 }
109
110 void manager_free(Manager *m) {
111         Unit *u;
112         Job *j;
113
114         assert(m);
115
116         while ((j = hashmap_first(m->transaction_jobs)))
117                 job_free(j);
118
119         while ((u = hashmap_first(m->units)))
120                 unit_free(u);
121
122         hashmap_free(m->units);
123         hashmap_free(m->jobs);
124         hashmap_free(m->transaction_jobs);
125         hashmap_free(m->watch_pids);
126
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);
131
132         free(m);
133 }
134
135 static void transaction_delete_job(Manager *m, Job *j) {
136         assert(m);
137         assert(j);
138
139         /* Deletes one job from the transaction */
140
141         manager_transaction_unlink_job(m, j);
142
143         if (!j->installed)
144                 job_free(j);
145 }
146
147 static void transaction_delete_unit(Manager *m, Unit *u) {
148         Job *j;
149
150         /* Deletes all jobs associated with a certain unit from the
151          * transaction */
152
153         while ((j = hashmap_get(m->transaction_jobs, u)))
154                 transaction_delete_job(m, j);
155 }
156
157 static void transaction_clean_dependencies(Manager *m) {
158         Iterator i;
159         Job *j;
160
161         assert(m);
162
163         /* Drops all dependencies of all installed jobs */
164
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);
170         }
171
172         assert(!m->transaction_anchor);
173 }
174
175 static void transaction_abort(Manager *m) {
176         Job *j;
177
178         assert(m);
179
180         while ((j = hashmap_first(m->transaction_jobs)))
181                 if (j->installed)
182                         transaction_delete_job(m, j);
183                 else
184                         job_free(j);
185
186         assert(hashmap_isempty(m->transaction_jobs));
187
188         transaction_clean_dependencies(m);
189 }
190
191 static void transaction_find_jobs_that_matter_to_anchor(Manager *m, Job *j, unsigned generation) {
192         JobDependency *l;
193
194         assert(m);
195
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. */
200
201         if (j)
202                 l = j->subject_list;
203         else
204                 l = m->transaction_anchor;
205
206         LIST_FOREACH(subject, l, l) {
207
208                 /* This link does not matter */
209                 if (!l->matters)
210                         continue;
211
212                 /* This unit has already been marked */
213                 if (l->object->generation == generation)
214                         continue;
215
216                 l->object->matters_to_anchor = true;
217                 l->object->generation = generation;
218
219                 transaction_find_jobs_that_matter_to_anchor(m, l->object, generation);
220         }
221 }
222
223 static void transaction_merge_and_delete_job(Manager *m, Job *j, Job *other, JobType t) {
224         JobDependency *l, *last;
225
226         assert(j);
227         assert(other);
228         assert(j->unit == other->unit);
229         assert(!j->installed);
230
231         /* Merges 'other' into 'j' and then deletes j. */
232
233         j->type = t;
234         j->state = JOB_WAITING;
235         j->forced = j->forced || other->forced;
236
237         j->matters_to_anchor = j->matters_to_anchor || other->matters_to_anchor;
238
239         /* Patch us in as new owner of the JobDependency objects */
240         last = NULL;
241         LIST_FOREACH(subject, l, other->subject_list) {
242                 assert(l->subject == other);
243                 l->subject = j;
244                 last = l;
245         }
246
247         /* Merge both lists */
248         if (last) {
249                 last->subject_next = j->subject_list;
250                 if (j->subject_list)
251                         j->subject_list->subject_prev = last;
252                 j->subject_list = other->subject_list;
253         }
254
255         /* Patch us in as new owner of the JobDependency objects */
256         last = NULL;
257         LIST_FOREACH(object, l, other->object_list) {
258                 assert(l->object == other);
259                 l->object = j;
260                 last = l;
261         }
262
263         /* Merge both lists */
264         if (last) {
265                 last->object_next = j->object_list;
266                 if (j->object_list)
267                         j->object_list->object_prev = last;
268                 j->object_list = other->object_list;
269         }
270
271         /* Kill the other job */
272         other->subject_list = NULL;
273         other->object_list = NULL;
274         transaction_delete_job(m, other);
275 }
276
277 static int delete_one_unmergeable_job(Manager *m, Job *j) {
278         Job *k;
279
280         assert(j);
281
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. */
286
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) {
291                         Job *d;
292
293                         /* Is this one mergeable? Then skip it */
294                         if (job_type_is_mergeable(j->type, k->type))
295                                 continue;
296
297                         /* Ok, we found two that conflict, let's see if we can
298                          * drop one of them */
299                         if (!j->matters_to_anchor)
300                                 d = j;
301                         else if (!k->matters_to_anchor)
302                                 d = k;
303                         else
304                                 return -ENOEXEC;
305
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);
309                         return 0;
310                 }
311
312         return -EINVAL;
313 }
314
315 static int transaction_merge_jobs(Manager *m) {
316         Job *j;
317         Iterator i;
318         int r;
319
320         assert(m);
321
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) {
325                 JobType t;
326                 Job *k;
327
328                 t = j->type;
329                 LIST_FOREACH(transaction, k, j->transaction_next) {
330                         if ((r = job_type_merge(&t, k->type)) >= 0)
331                                 continue;
332
333                         /* OK, we could not merge all jobs for this
334                          * action. Let's see if we can get rid of one
335                          * of them */
336
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 */
341                                 return -EAGAIN;
342
343                         /* We couldn't merge anything. Failure */
344                         return r;
345                 }
346         }
347
348         /* Second step, merge the jobs. */
349         HASHMAP_FOREACH(j, m->transaction_jobs, i) {
350                 JobType t = j->type;
351                 Job *k;
352
353                 /* Merge all transactions */
354                 LIST_FOREACH(transaction, k, j->transaction_next)
355                         assert_se(job_type_merge(&t, k->type) == 0);
356
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 */
360
361                 while ((k = j->transaction_next)) {
362                         if (j->installed) {
363                                 transaction_merge_and_delete_job(m, k, j, t);
364                                 j = k;
365                         } else
366                                 transaction_merge_and_delete_job(m, j, k, t);
367                 }
368
369                 assert(!j->transaction_next);
370                 assert(!j->transaction_prev);
371         }
372
373         return 0;
374 }
375
376 static bool unit_matters_to_anchor(Unit *u, Job *j) {
377         assert(u);
378         assert(!j->transaction_prev);
379
380         /* Checks whether at least one of the jobs for this unit
381          * matters to the anchor. */
382
383         LIST_FOREACH(transaction, j, j)
384                 if (j->matters_to_anchor)
385                         return true;
386
387         return false;
388 }
389
390 static int transaction_verify_order_one(Manager *m, Job *j, Job *from, unsigned generation) {
391         Iterator i;
392         Unit *u;
393         int r;
394
395         assert(m);
396         assert(j);
397         assert(!j->transaction_prev);
398
399         /* Does a recursive sweep through the ordering graph, looking
400          * for a cycle. If we find cycle we try to break it. */
401
402         /* Did we find a cycle? */
403         if (j->marker && j->generation == generation) {
404                 Job *k;
405
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
411                  * there. */
412
413                 for (k = from; k; k = (k->generation == generation ? k->marker : NULL)) {
414
415                         if (!k->installed &&
416                             !unit_matters_to_anchor(k->unit, k)) {
417                                 /* Ok, we can drop this one, so let's
418                                  * do so. */
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);
421                                 return -EAGAIN;
422                         }
423
424                         /* Check if this in fact was the beginning of
425                          * the cycle */
426                         if (k == j)
427                                 break;
428                 }
429
430                 return -ENOEXEC;
431         }
432
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 */
435         j->marker = from;
436         j->generation = generation;
437
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) {
441                 Job *o;
442
443                 /* Is there a job for this unit? */
444                 if (!(o = hashmap_get(m->transaction_jobs, u)))
445
446                         /* Ok, there is no job for this in the
447                          * transaction, but maybe there is already one
448                          * running? */
449                         if (!(o = u->meta.job))
450                                 continue;
451
452                 if ((r = transaction_verify_order_one(m, o, j, generation)) < 0)
453                         return r;
454         }
455
456         return 0;
457 }
458
459 static int transaction_verify_order(Manager *m, unsigned *generation) {
460         Job *j;
461         int r;
462         Iterator i;
463
464         assert(m);
465         assert(generation);
466
467         /* Check if the ordering graph is cyclic. If it is, try to fix
468          * that up by dropping one of the jobs. */
469
470         HASHMAP_FOREACH(j, m->transaction_jobs, i)
471                 if ((r = transaction_verify_order_one(m, j, NULL, (*generation)++)) < 0)
472                         return r;
473
474         return 0;
475 }
476
477 static void transaction_collect_garbage(Manager *m) {
478         bool again;
479
480         assert(m);
481
482         /* Drop jobs that are not required by any other job */
483
484         do {
485                 Iterator i;
486                 Job *j;
487
488                 again = false;
489
490                 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
491                         if (j->object_list)
492                                 continue;
493
494                         log_debug("Garbage collecting job %s/%s", unit_id(j->unit), job_type_to_string(j->type));
495                         transaction_delete_job(m, j);
496                         again = true;
497                         break;
498                 }
499
500         } while (again);
501 }
502
503 static int transaction_is_destructive(Manager *m, JobMode mode) {
504         Iterator i;
505         Job *j;
506
507         assert(m);
508
509         /* Checks whether applying this transaction means that
510          * existing jobs would be replaced */
511
512         HASHMAP_FOREACH(j, m->transaction_jobs, i) {
513
514                 /* Assume merged */
515                 assert(!j->transaction_prev);
516                 assert(!j->transaction_next);
517
518                 if (j->unit->meta.job &&
519                     j->unit->meta.job != j &&
520                     !job_type_is_superset(j->type, j->unit->meta.job->type))
521                         return -EEXIST;
522         }
523
524         return 0;
525 }
526
527 static void transaction_minimize_impact(Manager *m) {
528         bool again;
529         assert(m);
530
531         /* Drops all unnecessary jobs that reverse already active jobs
532          * or that stop a running service. */
533
534         do {
535                 Job *j;
536                 Iterator i;
537
538                 again = false;
539
540                 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
541                         LIST_FOREACH(transaction, j, j) {
542
543                                 /* If it matters, we shouldn't drop it */
544                                 if (j->matters_to_anchor)
545                                         continue;
546
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)))
552                                         continue;
553
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);
557                                 again = true;
558                                 break;
559                         }
560
561                         if (again)
562                                 break;
563                 }
564
565         } while (again);
566 }
567
568 static int transaction_apply(Manager *m, JobMode mode) {
569         Iterator i;
570         Job *j;
571         int r;
572
573         /* Moves the transaction jobs to the set of active jobs */
574
575         HASHMAP_FOREACH(j, m->transaction_jobs, i) {
576                 /* Assume merged */
577                 assert(!j->transaction_prev);
578                 assert(!j->transaction_next);
579
580                 if (j->installed)
581                         continue;
582
583                 if ((r = hashmap_put(m->jobs, UINT32_TO_PTR(j->id), j)) < 0)
584                         goto rollback;
585         }
586
587         while ((j = hashmap_steal_first(m->transaction_jobs))) {
588                 if (j->installed)
589                         continue;
590
591                 if (j->unit->meta.job)
592                         job_free(j->unit->meta.job);
593
594                 j->unit->meta.job = j;
595                 j->installed = true;
596
597                 /* We're fully installed. Now let's free data we don't
598                  * need anymore. */
599
600                 assert(!j->transaction_next);
601                 assert(!j->transaction_prev);
602
603                 job_schedule_run(j);
604         }
605
606         /* As last step, kill all remaining job dependencies. */
607         transaction_clean_dependencies(m);
608
609         return 0;
610
611 rollback:
612
613         HASHMAP_FOREACH(j, m->transaction_jobs, i) {
614                 if (j->installed)
615                         continue;
616
617                 hashmap_remove(m->jobs, UINT32_TO_PTR(j->id));
618         }
619
620         return r;
621 }
622
623 static int transaction_activate(Manager *m, JobMode mode) {
624         int r;
625         unsigned generation = 1;
626
627         assert(m);
628
629         /* This applies the changes recorded in transaction_jobs to
630          * the actual list of jobs, if possible. */
631
632         /* First step: figure out which jobs matter */
633         transaction_find_jobs_that_matter_to_anchor(m, NULL, generation++);
634
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);
639
640         for (;;) {
641                 /* Third step: Let's remove unneeded jobs that might
642                  * be lurking. */
643                 transaction_collect_garbage(m);
644
645                 /* Fourth step: verify order makes sense and correct
646                  * cycles if necessary and possible */
647                 if ((r = transaction_verify_order(m, &generation)) >= 0)
648                         break;
649
650                 if (r != -EAGAIN)
651                         goto rollback;
652
653                 /* Let's see if the resulting transaction ordering
654                  * graph is still cyclic... */
655         }
656
657         for (;;) {
658                 /* Fifth step: let's drop unmergeable entries if
659                  * necessary and possible, merge entries we can
660                  * merge */
661                 if ((r = transaction_merge_jobs(m)) >= 0)
662                         break;
663
664                 if (r != -EAGAIN)
665                         goto rollback;
666
667                 /* Sixth step: an entry got dropped, let's garbage
668                  * collect its dependencies. */
669                 transaction_collect_garbage(m);
670
671                 /* Let's see if the resulting transaction still has
672                  * unmergeable entries ... */
673         }
674
675         /* Seventh step: check whether we can actually apply this */
676         if (mode == JOB_FAIL)
677                 if ((r = transaction_is_destructive(m, mode)) < 0)
678                         goto rollback;
679
680         /* Eights step: apply changes */
681         if ((r = transaction_apply(m, mode)) < 0)
682                 goto rollback;
683
684         assert(hashmap_isempty(m->transaction_jobs));
685         assert(!m->transaction_anchor);
686
687         return 0;
688
689 rollback:
690         transaction_abort(m);
691         return r;
692 }
693
694 static Job* transaction_add_one_job(Manager *m, JobType type, Unit *unit, bool force, bool *is_new) {
695         Job *j, *f;
696         int r;
697
698         assert(m);
699         assert(unit);
700
701         /* Looks for an axisting prospective job and returns that. If
702          * it doesn't exist it is created and added to the prospective
703          * jobs list. */
704
705         f = hashmap_get(m->transaction_jobs, unit);
706
707         LIST_FOREACH(transaction, j, f) {
708                 assert(j->unit == unit);
709
710                 if (j->type == type) {
711                         if (is_new)
712                                 *is_new = false;
713                         return j;
714                 }
715         }
716
717         if (unit->meta.job && unit->meta.job->type == type)
718                 j = unit->meta.job;
719         else if (!(j = job_new(m, type, unit)))
720                 return NULL;
721
722         j->generation = 0;
723         j->marker = NULL;
724         j->matters_to_anchor = false;
725         j->forced = force;
726
727         LIST_PREPEND(Job, transaction, f, j);
728
729         if ((r = hashmap_replace(m->transaction_jobs, unit, f)) < 0) {
730                 job_free(j);
731                 return NULL;
732         }
733
734         if (is_new)
735                 *is_new = true;
736
737         return j;
738 }
739
740 void manager_transaction_unlink_job(Manager *m, Job *j) {
741         assert(m);
742         assert(j);
743
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);
748         else
749                 hashmap_remove_value(m->transaction_jobs, j->unit, j);
750
751         if (j->transaction_next)
752                 j->transaction_next->transaction_prev = j->transaction_prev;
753
754         j->transaction_prev = j->transaction_next = NULL;
755
756         while (j->subject_list)
757                 job_dependency_free(j->subject_list);
758
759         while (j->object_list) {
760                 Job *other = j->object_list->matters ? j->object_list->subject : NULL;
761
762                 job_dependency_free(j->object_list);
763
764                 if (other) {
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);
769                 }
770         }
771 }
772
773 static int transaction_add_job_and_dependencies(Manager *m, JobType type, Unit *unit, Job *by, bool matters, bool force, Job **_ret) {
774         Job *ret;
775         Iterator i;
776         Unit *dep;
777         int r;
778         bool is_new;
779
780         assert(m);
781         assert(type < _JOB_TYPE_MAX);
782         assert(unit);
783
784         if (unit->meta.load_state != UNIT_LOADED)
785                 return -EINVAL;
786
787         if (!unit_job_is_applicable(unit, type))
788                 return -EBADR;
789
790         /* First add the job. */
791         if (!(ret = transaction_add_one_job(m, type, unit, force, &is_new)))
792                 return -ENOMEM;
793
794         /* Then, add a link to the job. */
795         if (!job_dependency_new(by, ret, matters))
796                 return -ENOMEM;
797
798         if (is_new) {
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)
803                                         goto fail;
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)
806                                         goto fail;
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)
809                                         goto fail;
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)
812                                         goto fail;
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)
815                                         goto fail;
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)
818                                         goto fail;
819
820                 } else if (type == JOB_STOP || type == JOB_RESTART || type == JOB_TRY_RESTART) {
821
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)
824                                         goto fail;
825                 }
826
827                 /* JOB_VERIFY_STARTED, JOB_RELOAD require no dependency handling */
828         }
829
830         return 0;
831
832 fail:
833         return r;
834 }
835
836 int manager_add_job(Manager *m, JobType type, Unit *unit, JobMode mode, bool force, Job **_ret) {
837         int r;
838         Job *ret;
839
840         assert(m);
841         assert(type < _JOB_TYPE_MAX);
842         assert(unit);
843         assert(mode < _JOB_MODE_MAX);
844
845         if ((r = transaction_add_job_and_dependencies(m, type, unit, NULL, true, force, &ret))) {
846                 transaction_abort(m);
847                 return r;
848         }
849
850         if ((r = transaction_activate(m, mode)) < 0)
851                 return r;
852
853         if (_ret)
854                 *_ret = ret;
855
856         return 0;
857 }
858
859 Job *manager_get_job(Manager *m, uint32_t id) {
860         assert(m);
861
862         return hashmap_get(m->jobs, UINT32_TO_PTR(id));
863 }
864
865 Unit *manager_get_unit(Manager *m, const char *name) {
866         assert(m);
867         assert(name);
868
869         return hashmap_get(m->units, name);
870 }
871
872 static void dispatch_load_queue(Manager *m) {
873         Meta *meta;
874
875         assert(m);
876
877         /* Make sure we are not run recursively */
878         if (m->dispatching_load_queue)
879                 return;
880
881         m->dispatching_load_queue = true;
882
883         /* Dispatches the load queue. Takes a unit from the queue and
884          * tries to load its data until the queue is empty */
885
886         while ((meta = m->load_queue)) {
887                 assert(meta->in_load_queue);
888
889                 unit_load(UNIT(meta));
890         }
891
892         m->dispatching_load_queue = false;
893 }
894
895 int manager_load_unit(Manager *m, const char *path, Unit **_ret) {
896         Unit *ret;
897         int r;
898         const char *name;
899
900         assert(m);
901         assert(path);
902         assert(_ret);
903
904         /* This will load the service information files, but not actually
905          * start any services or anything. */
906
907         name = file_name_from_path(path);
908
909         if ((ret = manager_get_unit(m, name))) {
910                 *_ret = ret;
911                 return 0;
912         }
913
914         if (!(ret = unit_new(m)))
915                 return -ENOMEM;
916
917         if (is_path(path)) {
918                 if (!(ret->meta.load_path = strdup(path))) {
919                         unit_free(ret);
920                         return -ENOMEM;
921                 }
922         }
923
924         if ((r = unit_add_name(ret, name)) < 0) {
925                 unit_free(ret);
926                 return r;
927         }
928
929         unit_add_to_load_queue(ret);
930         dispatch_load_queue(m);
931
932         *_ret = ret;
933         return 0;
934 }
935
936 void manager_dump_jobs(Manager *s, FILE *f, const char *prefix) {
937         Iterator i;
938         Job *j;
939
940         assert(s);
941         assert(f);
942
943         HASHMAP_FOREACH(j, s->jobs, i)
944                 job_dump(j, f, prefix);
945 }
946
947 void manager_dump_units(Manager *s, FILE *f, const char *prefix) {
948         Iterator i;
949         Unit *u;
950         const char *t;
951
952         assert(s);
953         assert(f);
954
955         HASHMAP_FOREACH_KEY(u, t, s->units, i)
956                 if (unit_id(u) == t)
957                         unit_dump(u, f, prefix);
958 }
959
960 void manager_clear_jobs(Manager *m) {
961         Job *j;
962
963         assert(m);
964
965         transaction_abort(m);
966
967         while ((j = hashmap_first(m->jobs)))
968                 job_free(j);
969 }
970
971 void manager_dispatch_run_queue(Manager *m) {
972         Job *j;
973
974         if (m->dispatching_run_queue)
975                 return;
976
977         m->dispatching_run_queue = true;
978
979         while ((j = m->run_queue)) {
980                 assert(j->installed);
981                 assert(j->in_run_queue);
982
983                 job_run_and_invalidate(j);
984         }
985
986         m->dispatching_run_queue = false;
987 }
988
989 static int manager_dispatch_sigchld(Manager *m) {
990         assert(m);
991
992         log_debug("dispatching SIGCHLD");
993
994         for (;;) {
995                 siginfo_t si;
996                 Unit *u;
997
998                 zero(si);
999                 if (waitid(P_ALL, 0, &si, WEXITED|WNOHANG) < 0) {
1000
1001                         if (errno == ECHILD)
1002                                 break;
1003
1004                         return -errno;
1005                 }
1006
1007                 if (si.si_pid == 0)
1008                         break;
1009
1010                 if (si.si_code != CLD_EXITED && si.si_code != CLD_KILLED && si.si_code != CLD_DUMPED)
1011                         continue;
1012
1013                 log_debug("child %llu died (code=%s, status=%i)", (long long unsigned) si.si_pid, sigchld_code(si.si_code), si.si_status);
1014
1015                 if (!(u = hashmap_remove(m->watch_pids, UINT32_TO_PTR(si.si_pid))))
1016                         continue;
1017
1018                 UNIT_VTABLE(u)->sigchld_event(u, si.si_pid, si.si_code, si.si_status);
1019         }
1020
1021         return 0;
1022 }
1023
1024 static int manager_process_signal_fd(Manager *m, bool *quit) {
1025         ssize_t n;
1026         struct signalfd_siginfo sfsi;
1027         bool sigchld = false;
1028
1029         assert(m);
1030
1031         for (;;) {
1032                 if ((n = read(m->signal_watch.fd, &sfsi, sizeof(sfsi))) != sizeof(sfsi)) {
1033
1034                         if (n >= 0)
1035                                 return -EIO;
1036
1037                         if (errno == EAGAIN)
1038                                 break;
1039
1040                         return -errno;
1041                 }
1042
1043                 switch (sfsi.ssi_signo) {
1044
1045                 case SIGCHLD:
1046                         sigchld = true;
1047                         break;
1048
1049                 case SIGINT:
1050                 case SIGTERM:
1051                         *quit = true;
1052                         return 0;
1053
1054                 default:
1055                         log_info("Got unhandled signal <%s>.", strsignal(sfsi.ssi_signo));
1056                 }
1057         }
1058
1059         if (sigchld)
1060                 return manager_dispatch_sigchld(m);
1061
1062         return 0;
1063 }
1064
1065 static int process_event(Manager *m, struct epoll_event *ev, bool *quit) {
1066         int r;
1067         Watch *w;
1068
1069         assert(m);
1070         assert(ev);
1071
1072         assert(w = ev->data.ptr);
1073
1074         switch (w->type) {
1075
1076         case WATCH_SIGNAL_FD:
1077
1078                 /* An incoming signal? */
1079                 if (ev->events != POLLIN)
1080                         return -EINVAL;
1081
1082                 if ((r = manager_process_signal_fd(m, quit)) < 0)
1083                         return r;
1084
1085                 break;
1086
1087         case WATCH_FD:
1088
1089                 /* Some fd event, to be dispatched to the units */
1090                 UNIT_VTABLE(w->unit)->fd_event(w->unit, w->fd, ev->events, w);
1091                 break;
1092
1093         case WATCH_TIMER: {
1094                 uint64_t v;
1095                 ssize_t k;
1096
1097                 /* Some timer event, to be dispatched to the units */
1098                 if ((k = read(ev->data.fd, &v, sizeof(v))) != sizeof(v)) {
1099
1100                         if (k < 0 && (errno == EINTR || errno == EAGAIN))
1101                                 break;
1102
1103                         return k < 0 ? -errno : -EIO;
1104                 }
1105
1106                 UNIT_VTABLE(w->unit)->timer_event(w->unit, v, w);
1107                 break;
1108         }
1109
1110         default:
1111                 assert_not_reached("Unknown epoll event type.");
1112         }
1113
1114         return 0;
1115 }
1116
1117 int manager_loop(Manager *m) {
1118         int r;
1119         bool quit = false;
1120
1121         assert(m);
1122
1123         for (;;) {
1124                 struct epoll_event event;
1125                 int n;
1126
1127                 manager_dispatch_run_queue(m);
1128
1129                 if ((n = epoll_wait(m->epoll_fd, &event, 1, -1)) < 0) {
1130
1131                         if (errno == -EINTR)
1132                                 continue;
1133
1134                         return -errno;
1135                 }
1136
1137                 assert(n == 1);
1138
1139                 if ((r = process_event(m, &event, &quit)) < 0)
1140                         return r;
1141
1142                 if (quit)
1143                         return 0;
1144         }
1145 }