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