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