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