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