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