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