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