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