chiark / gitweb /
dbus: be a bit more explicit about which bus connection failed
[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 #include <sys/reboot.h>
32 #include <sys/ioctl.h>
33 #include <linux/kd.h>
34 #include <libcgroup.h>
35
36 #include "manager.h"
37 #include "hashmap.h"
38 #include "macro.h"
39 #include "strv.h"
40 #include "log.h"
41 #include "util.h"
42 #include "ratelimit.h"
43 #include "cgroup.h"
44 #include "mount-setup.h"
45
46 static int manager_setup_signals(Manager *m) {
47         sigset_t mask;
48         struct epoll_event ev;
49
50         assert(m);
51
52         assert_se(sigemptyset(&mask) == 0);
53         assert_se(sigaddset(&mask, SIGCHLD) == 0);
54         assert_se(sigaddset(&mask, SIGINT) == 0);   /* Kernel sends us this on control-alt-del */
55         assert_se(sigaddset(&mask, SIGWINCH) == 0); /* Kernel sends us this on kbrequest (alt-arrowup) */
56         assert_se(sigaddset(&mask, SIGTERM) == 0);
57         assert_se(sigaddset(&mask, SIGHUP) == 0);
58         assert_se(sigaddset(&mask, SIGUSR1) == 0);
59         assert_se(sigaddset(&mask, SIGUSR2) == 0);
60         assert_se(sigaddset(&mask, SIGPIPE) == 0);
61         assert_se(sigaddset(&mask, SIGPWR) == 0);
62         assert_se(sigaddset(&mask, SIGTTIN) == 0);
63         assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
64
65         m->signal_watch.type = WATCH_SIGNAL;
66         if ((m->signal_watch.fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0)
67                 return -errno;
68
69         zero(ev);
70         ev.events = EPOLLIN;
71         ev.data.ptr = &m->signal_watch;
72
73         if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->signal_watch.fd, &ev) < 0)
74                 return -errno;
75
76         if (m->running_as == MANAGER_INIT) {
77                 /* Enable that we get SIGINT on control-alt-del */
78                 if (reboot(RB_DISABLE_CAD) < 0)
79                         log_warning("Failed to enable ctrl-alt-del handling: %s", strerror(errno));
80
81                 /* Enable that we get SIGWINCH on kbrequest */
82                 if (ioctl(0, KDSIGACCEPT, SIGWINCH) < 0)
83                         log_warning("Failed to enable kbrequest handling: %s", strerror(errno));
84         }
85
86         return 0;
87 }
88
89 static char** session_dirs(void) {
90         const char *home, *e;
91         char *config_home = NULL, *data_home = NULL;
92         char **config_dirs = NULL, **data_dirs = NULL;
93         char **r = NULL, **t;
94
95         /* Implement the mechanisms defined in
96          *
97          * http://standards.freedesktop.org/basedir-spec/basedir-spec-0.6.html
98          *
99          * We look in both the config and the data dirs because we
100          * want to encourage that distributors ship their unit files
101          * as data, and allow overriding as configuration.
102          */
103
104         home = getenv("HOME");
105
106         if ((e = getenv("XDG_CONFIG_HOME"))) {
107                 if (asprintf(&config_home, "%s/systemd/session", e) < 0)
108                         goto fail;
109
110         } else if (home) {
111                 if (asprintf(&config_home, "%s/.config/systemd/session", home) < 0)
112                         goto fail;
113         }
114
115         if ((e = getenv("XDG_CONFIG_DIRS")))
116                 config_dirs = strv_split(e, ":");
117         else
118                 config_dirs = strv_new("/etc/xdg", NULL);
119
120         if (!config_dirs)
121                 goto fail;
122
123         if ((e = getenv("XDG_DATA_HOME"))) {
124                 if (asprintf(&data_home, "%s/systemd/session", e) < 0)
125                         goto fail;
126
127         } else if (home) {
128                 if (asprintf(&data_home, "%s/.local/share/systemd/session", home) < 0)
129                         goto fail;
130         }
131
132         if ((e = getenv("XDG_DATA_DIRS")))
133                 data_dirs = strv_split(e, ":");
134         else
135                 data_dirs = strv_new("/usr/local/share", "/usr/share", NULL);
136
137         if (!data_dirs)
138                 goto fail;
139
140         /* Now merge everything we found. */
141         if (config_home) {
142                 if (!(t = strv_append(r, config_home)))
143                         goto fail;
144                 strv_free(r);
145                 r = t;
146         }
147
148         if (!(t = strv_merge_concat(r, config_dirs, "/systemd/session")))
149                 goto finish;
150         strv_free(r);
151         r = t;
152
153         if (!(t = strv_append(r, SESSION_CONFIG_UNIT_PATH)))
154                 goto fail;
155         strv_free(r);
156         r = t;
157
158         if (data_home) {
159                 if (!(t = strv_append(r, data_home)))
160                         goto fail;
161                 strv_free(r);
162                 r = t;
163         }
164
165         if (!(t = strv_merge_concat(r, data_dirs, "/systemd/session")))
166                 goto fail;
167         strv_free(r);
168         r = t;
169
170         if (!(t = strv_append(r, SESSION_DATA_UNIT_PATH)))
171                 goto fail;
172         strv_free(r);
173         r = t;
174
175         if (!strv_path_make_absolute_cwd(r))
176             goto fail;
177
178 finish:
179         free(config_home);
180         strv_free(config_dirs);
181         free(data_home);
182         strv_free(data_dirs);
183
184         return r;
185
186 fail:
187         strv_free(r);
188         r = NULL;
189         goto finish;
190 }
191
192 static int manager_find_paths(Manager *m) {
193         const char *e;
194         char *t;
195
196         assert(m);
197
198         /* First priority is whatever has been passed to us via env
199          * vars */
200         if ((e = getenv("SYSTEMD_UNIT_PATH")))
201                 if (!(m->unit_path = split_path_and_make_absolute(e)))
202                         return -ENOMEM;
203
204         if (strv_isempty(m->unit_path)) {
205
206                 /* Nothing is set, so let's figure something out. */
207                 strv_free(m->unit_path);
208
209                 if (m->running_as == MANAGER_SESSION) {
210                         if (!(m->unit_path = session_dirs()))
211                                 return -ENOMEM;
212                 } else
213                         if (!(m->unit_path = strv_new(
214                                               SYSTEM_CONFIG_UNIT_PATH,  /* /etc/systemd/system/ */
215                                               SYSTEM_DATA_UNIT_PATH,    /* /lib/systemd/system/ */
216                                               NULL)))
217                                 return -ENOMEM;
218         }
219
220         if (m->running_as == MANAGER_INIT) {
221                 /* /etc/init.d/ compativility does not matter to users */
222
223                 if ((e = getenv("SYSTEMD_SYSVINIT_PATH")))
224                         if (!(m->sysvinit_path = split_path_and_make_absolute(e)))
225                                 return -ENOMEM;
226
227                 if (strv_isempty(m->sysvinit_path)) {
228                         strv_free(m->sysvinit_path);
229
230                         if (!(m->sysvinit_path = strv_new(
231                                               SYSTEM_SYSVINIT_PATH,     /* /etc/init.d/ */
232                                               NULL)))
233                                 return -ENOMEM;
234                 }
235         }
236
237         strv_uniq(m->unit_path);
238         strv_uniq(m->sysvinit_path);
239
240         assert(!strv_isempty(m->unit_path));
241         if (!(t = strv_join(m->unit_path, "\n\t")))
242                 return -ENOMEM;
243         log_debug("Looking for unit files in:\n\t%s", t);
244         free(t);
245
246         if (!strv_isempty(m->sysvinit_path)) {
247
248                 if (!(t = strv_join(m->sysvinit_path, "\n\t")))
249                         return -ENOMEM;
250
251                 log_debug("Looking for SysV init scripts in:\n\t%s", t);
252                 free(t);
253         } else
254                 log_debug("Ignoring SysV init scripts.");
255
256         return 0;
257 }
258
259 int manager_new(ManagerRunningAs running_as, Manager **_m) {
260         Manager *m;
261         int r = -ENOMEM;
262
263         assert(_m);
264         assert(running_as >= 0);
265         assert(running_as < _MANAGER_RUNNING_AS_MAX);
266
267         if (!(m = new0(Manager, 1)))
268                 return -ENOMEM;
269
270         m->running_as = running_as;
271         m->signal_watch.fd = m->mount_watch.fd = m->udev_watch.fd = m->epoll_fd = -1;
272         m->current_job_id = 1; /* start as id #1, so that we can leave #0 around as "null-like" value */
273
274         if (!(m->units = hashmap_new(string_hash_func, string_compare_func)))
275                 goto fail;
276
277         if (!(m->jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
278                 goto fail;
279
280         if (!(m->transaction_jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
281                 goto fail;
282
283         if (!(m->watch_pids = hashmap_new(trivial_hash_func, trivial_compare_func)))
284                 goto fail;
285
286         if (!(m->cgroup_bondings = hashmap_new(string_hash_func, string_compare_func)))
287                 goto fail;
288
289         if ((m->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0)
290                 goto fail;
291
292         if ((r = manager_find_paths(m)) < 0)
293                 goto fail;
294
295         if ((r = manager_setup_signals(m)) < 0)
296                 goto fail;
297
298         if ((r = manager_setup_cgroup(m)) < 0)
299                 goto fail;
300
301         /* Try to connect to the busses, if possible. */
302         if ((r = bus_init_system(m)) < 0 ||
303             (r = bus_init_api(m)) < 0)
304                 goto fail;
305
306         *_m = m;
307         return 0;
308
309 fail:
310         manager_free(m);
311         return r;
312 }
313
314 static unsigned manager_dispatch_cleanup_queue(Manager *m) {
315         Meta *meta;
316         unsigned n = 0;
317
318         assert(m);
319
320         while ((meta = m->cleanup_queue)) {
321                 assert(meta->in_cleanup_queue);
322
323                 unit_free(UNIT(meta));
324                 n++;
325         }
326
327         return n;
328 }
329
330 void manager_free(Manager *m) {
331         UnitType c;
332         Unit *u;
333         Job *j;
334
335         assert(m);
336
337         while ((j = hashmap_first(m->transaction_jobs)))
338                 job_free(j);
339
340         while ((u = hashmap_first(m->units)))
341                 unit_free(u);
342
343         manager_dispatch_cleanup_queue(m);
344
345         for (c = 0; c < _UNIT_TYPE_MAX; c++)
346                 if (unit_vtable[c]->shutdown)
347                         unit_vtable[c]->shutdown(m);
348
349         manager_shutdown_cgroup(m);
350
351         bus_done_api(m);
352         bus_done_system(m);
353
354         hashmap_free(m->units);
355         hashmap_free(m->jobs);
356         hashmap_free(m->transaction_jobs);
357         hashmap_free(m->watch_pids);
358
359         if (m->epoll_fd >= 0)
360                 close_nointr(m->epoll_fd);
361         if (m->signal_watch.fd >= 0)
362                 close_nointr(m->signal_watch.fd);
363
364         strv_free(m->unit_path);
365         strv_free(m->sysvinit_path);
366
367         free(m->cgroup_controller);
368         free(m->cgroup_hierarchy);
369
370         assert(hashmap_isempty(m->cgroup_bondings));
371         hashmap_free(m->cgroup_bondings);
372
373         free(m);
374 }
375
376 int manager_coldplug(Manager *m) {
377         int r;
378         UnitType c;
379         Iterator i;
380         Unit *u;
381         char *k;
382
383         assert(m);
384
385         /* First, let's ask every type to load all units from
386          * disk/kernel that it might know */
387         for (c = 0; c < _UNIT_TYPE_MAX; c++)
388                 if (unit_vtable[c]->enumerate)
389                         if ((r = unit_vtable[c]->enumerate(m)) < 0)
390                                 return r;
391
392         manager_dispatch_load_queue(m);
393
394         /* Then, let's set up their initial state. */
395         HASHMAP_FOREACH_KEY(u, k, m->units, i) {
396
397                 /* ignore aliases */
398                 if (unit_id(u) != k)
399                         continue;
400
401                 if (UNIT_VTABLE(u)->coldplug)
402                         if ((r = UNIT_VTABLE(u)->coldplug(u)) < 0)
403                                 return r;
404         }
405
406         return 0;
407 }
408
409 static void transaction_delete_job(Manager *m, Job *j, bool delete_dependencies) {
410         assert(m);
411         assert(j);
412
413         /* Deletes one job from the transaction */
414
415         manager_transaction_unlink_job(m, j, delete_dependencies);
416
417         if (!j->installed)
418                 job_free(j);
419 }
420
421 static void transaction_delete_unit(Manager *m, Unit *u) {
422         Job *j;
423
424         /* Deletes all jobs associated with a certain unit from the
425          * transaction */
426
427         while ((j = hashmap_get(m->transaction_jobs, u)))
428                 transaction_delete_job(m, j, true);
429 }
430
431 static void transaction_clean_dependencies(Manager *m) {
432         Iterator i;
433         Job *j;
434
435         assert(m);
436
437         /* Drops all dependencies of all installed jobs */
438
439         HASHMAP_FOREACH(j, m->jobs, i) {
440                 while (j->subject_list)
441                         job_dependency_free(j->subject_list);
442                 while (j->object_list)
443                         job_dependency_free(j->object_list);
444         }
445
446         assert(!m->transaction_anchor);
447 }
448
449 static void transaction_abort(Manager *m) {
450         Job *j;
451
452         assert(m);
453
454         while ((j = hashmap_first(m->transaction_jobs)))
455                 if (j->installed)
456                         transaction_delete_job(m, j, true);
457                 else
458                         job_free(j);
459
460         assert(hashmap_isempty(m->transaction_jobs));
461
462         transaction_clean_dependencies(m);
463 }
464
465 static void transaction_find_jobs_that_matter_to_anchor(Manager *m, Job *j, unsigned generation) {
466         JobDependency *l;
467
468         assert(m);
469
470         /* A recursive sweep through the graph that marks all units
471          * that matter to the anchor job, i.e. are directly or
472          * indirectly a dependency of the anchor job via paths that
473          * are fully marked as mattering. */
474
475         if (j)
476                 l = j->subject_list;
477         else
478                 l = m->transaction_anchor;
479
480         LIST_FOREACH(subject, l, l) {
481
482                 /* This link does not matter */
483                 if (!l->matters)
484                         continue;
485
486                 /* This unit has already been marked */
487                 if (l->object->generation == generation)
488                         continue;
489
490                 l->object->matters_to_anchor = true;
491                 l->object->generation = generation;
492
493                 transaction_find_jobs_that_matter_to_anchor(m, l->object, generation);
494         }
495 }
496
497 static void transaction_merge_and_delete_job(Manager *m, Job *j, Job *other, JobType t) {
498         JobDependency *l, *last;
499
500         assert(j);
501         assert(other);
502         assert(j->unit == other->unit);
503         assert(!j->installed);
504
505         /* Merges 'other' into 'j' and then deletes j. */
506
507         j->type = t;
508         j->state = JOB_WAITING;
509         j->forced = j->forced || other->forced;
510
511         j->matters_to_anchor = j->matters_to_anchor || other->matters_to_anchor;
512
513         /* Patch us in as new owner of the JobDependency objects */
514         last = NULL;
515         LIST_FOREACH(subject, l, other->subject_list) {
516                 assert(l->subject == other);
517                 l->subject = j;
518                 last = l;
519         }
520
521         /* Merge both lists */
522         if (last) {
523                 last->subject_next = j->subject_list;
524                 if (j->subject_list)
525                         j->subject_list->subject_prev = last;
526                 j->subject_list = other->subject_list;
527         }
528
529         /* Patch us in as new owner of the JobDependency objects */
530         last = NULL;
531         LIST_FOREACH(object, l, other->object_list) {
532                 assert(l->object == other);
533                 l->object = j;
534                 last = l;
535         }
536
537         /* Merge both lists */
538         if (last) {
539                 last->object_next = j->object_list;
540                 if (j->object_list)
541                         j->object_list->object_prev = last;
542                 j->object_list = other->object_list;
543         }
544
545         /* Kill the other job */
546         other->subject_list = NULL;
547         other->object_list = NULL;
548         transaction_delete_job(m, other, true);
549 }
550
551 static int delete_one_unmergeable_job(Manager *m, Job *j) {
552         Job *k;
553
554         assert(j);
555
556         /* Tries to delete one item in the linked list
557          * j->transaction_next->transaction_next->... that conflicts
558          * whith another one, in an attempt to make an inconsistent
559          * transaction work. */
560
561         /* We rely here on the fact that if a merged with b does not
562          * merge with c, either a or b merge with c neither */
563         LIST_FOREACH(transaction, j, j)
564                 LIST_FOREACH(transaction, k, j->transaction_next) {
565                         Job *d;
566
567                         /* Is this one mergeable? Then skip it */
568                         if (job_type_is_mergeable(j->type, k->type))
569                                 continue;
570
571                         /* Ok, we found two that conflict, let's see if we can
572                          * drop one of them */
573                         if (!j->matters_to_anchor)
574                                 d = j;
575                         else if (!k->matters_to_anchor)
576                                 d = k;
577                         else
578                                 return -ENOEXEC;
579
580                         /* Ok, we can drop one, so let's do so. */
581                         log_debug("Trying to fix job merging by deleting job %s/%s", unit_id(d->unit), job_type_to_string(d->type));
582                         transaction_delete_job(m, d, true);
583                         return 0;
584                 }
585
586         return -EINVAL;
587 }
588
589 static int transaction_merge_jobs(Manager *m) {
590         Job *j;
591         Iterator i;
592         int r;
593
594         assert(m);
595
596         /* First step, check whether any of the jobs for one specific
597          * task conflict. If so, try to drop one of them. */
598         HASHMAP_FOREACH(j, m->transaction_jobs, i) {
599                 JobType t;
600                 Job *k;
601
602                 t = j->type;
603                 LIST_FOREACH(transaction, k, j->transaction_next) {
604                         if ((r = job_type_merge(&t, k->type)) >= 0)
605                                 continue;
606
607                         /* OK, we could not merge all jobs for this
608                          * action. Let's see if we can get rid of one
609                          * of them */
610
611                         if ((r = delete_one_unmergeable_job(m, j)) >= 0)
612                                 /* Ok, we managed to drop one, now
613                                  * let's ask our callers to call us
614                                  * again after garbage collecting */
615                                 return -EAGAIN;
616
617                         /* We couldn't merge anything. Failure */
618                         return r;
619                 }
620         }
621
622         /* Second step, merge the jobs. */
623         HASHMAP_FOREACH(j, m->transaction_jobs, i) {
624                 JobType t = j->type;
625                 Job *k;
626
627                 /* Merge all transactions */
628                 LIST_FOREACH(transaction, k, j->transaction_next)
629                         assert_se(job_type_merge(&t, k->type) == 0);
630
631                 /* If an active job is mergeable, merge it too */
632                 if (j->unit->meta.job)
633                         job_type_merge(&t, j->unit->meta.job->type); /* Might fail. Which is OK */
634
635                 while ((k = j->transaction_next)) {
636                         if (j->installed) {
637                                 transaction_merge_and_delete_job(m, k, j, t);
638                                 j = k;
639                         } else
640                                 transaction_merge_and_delete_job(m, j, k, t);
641                 }
642
643                 assert(!j->transaction_next);
644                 assert(!j->transaction_prev);
645         }
646
647         return 0;
648 }
649
650 static void transaction_drop_redundant(Manager *m) {
651         bool again;
652
653         assert(m);
654
655         /* Goes through the transaction and removes all jobs that are
656          * a noop */
657
658         do {
659                 Job *j;
660                 Iterator i;
661
662                 again = false;
663
664                 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
665                         bool changes_something = false;
666                         Job *k;
667
668                         LIST_FOREACH(transaction, k, j) {
669
670                                 if (!job_is_anchor(k) &&
671                                     job_type_is_redundant(k->type, unit_active_state(k->unit)))
672                                         continue;
673
674                                 changes_something = true;
675                                 break;
676                         }
677
678                         if (changes_something)
679                                 continue;
680
681                         log_debug("Found redundant job %s/%s, dropping.", unit_id(j->unit), job_type_to_string(j->type));
682                         transaction_delete_job(m, j, false);
683                         again = true;
684                         break;
685                 }
686
687         } while (again);
688 }
689
690 static bool unit_matters_to_anchor(Unit *u, Job *j) {
691         assert(u);
692         assert(!j->transaction_prev);
693
694         /* Checks whether at least one of the jobs for this unit
695          * matters to the anchor. */
696
697         LIST_FOREACH(transaction, j, j)
698                 if (j->matters_to_anchor)
699                         return true;
700
701         return false;
702 }
703
704 static int transaction_verify_order_one(Manager *m, Job *j, Job *from, unsigned generation) {
705         Iterator i;
706         Unit *u;
707         int r;
708
709         assert(m);
710         assert(j);
711         assert(!j->transaction_prev);
712
713         /* Does a recursive sweep through the ordering graph, looking
714          * for a cycle. If we find cycle we try to break it. */
715
716         /* Did we find a cycle? */
717         if (j->marker && j->generation == generation) {
718                 Job *k;
719
720                 /* So, we already have been here. We have a
721                  * cycle. Let's try to break it. We go backwards in
722                  * our path and try to find a suitable job to
723                  * remove. We use the marker to find our way back,
724                  * since smart how we are we stored our way back in
725                  * there. */
726
727                 log_debug("Found ordering cycle on %s/%s", unit_id(j->unit), job_type_to_string(j->type));
728
729                 for (k = from; k; k = (k->generation == generation ? k->marker : NULL)) {
730
731                         log_debug("Walked on cycle path to %s/%s", unit_id(k->unit), job_type_to_string(k->type));
732
733                         if (!k->installed &&
734                             !unit_matters_to_anchor(k->unit, k)) {
735                                 /* Ok, we can drop this one, so let's
736                                  * do so. */
737                                 log_debug("Breaking order cycle by deleting job %s/%s", unit_id(k->unit), job_type_to_string(k->type));
738                                 transaction_delete_unit(m, k->unit);
739                                 return -EAGAIN;
740                         }
741
742                         /* Check if this in fact was the beginning of
743                          * the cycle */
744                         if (k == j)
745                                 break;
746                 }
747
748                 log_debug("Unable to break cycle");
749
750                 return -ENOEXEC;
751         }
752
753         /* Make the marker point to where we come from, so that we can
754          * find our way backwards if we want to break a cycle */
755         j->marker = from;
756         j->generation = generation;
757
758         /* We assume that the the dependencies are bidirectional, and
759          * hence can ignore UNIT_AFTER */
760         SET_FOREACH(u, j->unit->meta.dependencies[UNIT_BEFORE], i) {
761                 Job *o;
762
763                 /* Is there a job for this unit? */
764                 if (!(o = hashmap_get(m->transaction_jobs, u)))
765
766                         /* Ok, there is no job for this in the
767                          * transaction, but maybe there is already one
768                          * running? */
769                         if (!(o = u->meta.job))
770                                 continue;
771
772                 if ((r = transaction_verify_order_one(m, o, j, generation)) < 0)
773                         return r;
774         }
775
776         /* Ok, let's backtrack, and remember that this entry is not on
777          * our path anymore. */
778         j->marker = NULL;
779
780         return 0;
781 }
782
783 static int transaction_verify_order(Manager *m, unsigned *generation) {
784         Job *j;
785         int r;
786         Iterator i;
787
788         assert(m);
789         assert(generation);
790
791         /* Check if the ordering graph is cyclic. If it is, try to fix
792          * that up by dropping one of the jobs. */
793
794         HASHMAP_FOREACH(j, m->transaction_jobs, i)
795                 if ((r = transaction_verify_order_one(m, j, NULL, (*generation)++)) < 0)
796                         return r;
797
798         return 0;
799 }
800
801 static void transaction_collect_garbage(Manager *m) {
802         bool again;
803
804         assert(m);
805
806         /* Drop jobs that are not required by any other job */
807
808         do {
809                 Iterator i;
810                 Job *j;
811
812                 again = false;
813
814                 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
815                         if (j->object_list)
816                                 continue;
817
818                         log_debug("Garbage collecting job %s/%s", unit_id(j->unit), job_type_to_string(j->type));
819                         transaction_delete_job(m, j, true);
820                         again = true;
821                         break;
822                 }
823
824         } while (again);
825 }
826
827 static int transaction_is_destructive(Manager *m, JobMode mode) {
828         Iterator i;
829         Job *j;
830
831         assert(m);
832
833         /* Checks whether applying this transaction means that
834          * existing jobs would be replaced */
835
836         HASHMAP_FOREACH(j, m->transaction_jobs, i) {
837
838                 /* Assume merged */
839                 assert(!j->transaction_prev);
840                 assert(!j->transaction_next);
841
842                 if (j->unit->meta.job &&
843                     j->unit->meta.job != j &&
844                     !job_type_is_superset(j->type, j->unit->meta.job->type))
845                         return -EEXIST;
846         }
847
848         return 0;
849 }
850
851 static void transaction_minimize_impact(Manager *m) {
852         bool again;
853         assert(m);
854
855         /* Drops all unnecessary jobs that reverse already active jobs
856          * or that stop a running service. */
857
858         do {
859                 Job *j;
860                 Iterator i;
861
862                 again = false;
863
864                 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
865                         LIST_FOREACH(transaction, j, j) {
866                                 bool stops_running_service, changes_existing_job;
867
868                                 /* If it matters, we shouldn't drop it */
869                                 if (j->matters_to_anchor)
870                                         continue;
871
872                                 /* Would this stop a running service?
873                                  * Would this change an existing job?
874                                  * If so, let's drop this entry */
875
876                                 stops_running_service =
877                                         j->type == JOB_STOP && UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(j->unit));
878
879                                 changes_existing_job =
880                                         j->unit->meta.job && job_type_is_conflicting(j->type, j->unit->meta.job->state);
881
882                                 if (!stops_running_service && !changes_existing_job)
883                                         continue;
884
885                                 if (stops_running_service)
886                                         log_debug("%s/%s would stop a running service.", unit_id(j->unit), job_type_to_string(j->type));
887
888                                 if (changes_existing_job)
889                                         log_debug("%s/%s would change existing job.", unit_id(j->unit), job_type_to_string(j->type));
890
891                                 /* Ok, let's get rid of this */
892                                 log_debug("Deleting %s/%s to minimize impact.", unit_id(j->unit), job_type_to_string(j->type));
893
894                                 transaction_delete_job(m, j, true);
895                                 again = true;
896                                 break;
897                         }
898
899                         if (again)
900                                 break;
901                 }
902
903         } while (again);
904 }
905
906 static int transaction_apply(Manager *m, JobMode mode) {
907         Iterator i;
908         Job *j;
909         int r;
910
911         /* Moves the transaction jobs to the set of active jobs */
912
913         HASHMAP_FOREACH(j, m->transaction_jobs, i) {
914                 /* Assume merged */
915                 assert(!j->transaction_prev);
916                 assert(!j->transaction_next);
917
918                 if (j->installed)
919                         continue;
920
921                 if ((r = hashmap_put(m->jobs, UINT32_TO_PTR(j->id), j)) < 0)
922                         goto rollback;
923         }
924
925         while ((j = hashmap_steal_first(m->transaction_jobs))) {
926                 if (j->installed)
927                         continue;
928
929                 if (j->unit->meta.job)
930                         job_free(j->unit->meta.job);
931
932                 j->unit->meta.job = j;
933                 j->installed = true;
934
935                 /* We're fully installed. Now let's free data we don't
936                  * need anymore. */
937
938                 assert(!j->transaction_next);
939                 assert(!j->transaction_prev);
940
941                 job_add_to_run_queue(j);
942                 job_add_to_dbus_queue(j);
943         }
944
945         /* As last step, kill all remaining job dependencies. */
946         transaction_clean_dependencies(m);
947
948         return 0;
949
950 rollback:
951
952         HASHMAP_FOREACH(j, m->transaction_jobs, i) {
953                 if (j->installed)
954                         continue;
955
956                 hashmap_remove(m->jobs, UINT32_TO_PTR(j->id));
957         }
958
959         return r;
960 }
961
962 static int transaction_activate(Manager *m, JobMode mode) {
963         int r;
964         unsigned generation = 1;
965
966         assert(m);
967
968         /* This applies the changes recorded in transaction_jobs to
969          * the actual list of jobs, if possible. */
970
971         /* First step: figure out which jobs matter */
972         transaction_find_jobs_that_matter_to_anchor(m, NULL, generation++);
973
974         /* Second step: Try not to stop any running services if
975          * we don't have to. Don't try to reverse running
976          * jobs if we don't have to. */
977         transaction_minimize_impact(m);
978
979         /* Third step: Drop redundant jobs */
980         transaction_drop_redundant(m);
981
982         for (;;) {
983                 /* Fourth step: Let's remove unneeded jobs that might
984                  * be lurking. */
985                 transaction_collect_garbage(m);
986
987                 /* Fifth step: verify order makes sense and correct
988                  * cycles if necessary and possible */
989                 if ((r = transaction_verify_order(m, &generation)) >= 0)
990                         break;
991
992                 if (r != -EAGAIN) {
993                         log_debug("Requested transaction contains an unfixable cyclic ordering dependency: %s", strerror(-r));
994                         goto rollback;
995                 }
996
997                 /* Let's see if the resulting transaction ordering
998                  * graph is still cyclic... */
999         }
1000
1001         for (;;) {
1002                 /* Sixth step: let's drop unmergeable entries if
1003                  * necessary and possible, merge entries we can
1004                  * merge */
1005                 if ((r = transaction_merge_jobs(m)) >= 0)
1006                         break;
1007
1008                 if (r != -EAGAIN) {
1009                         log_debug("Requested transaction contains unmergable jobs: %s", strerror(-r));
1010                         goto rollback;
1011                 }
1012
1013                 /* Seventh step: an entry got dropped, let's garbage
1014                  * collect its dependencies. */
1015                 transaction_collect_garbage(m);
1016
1017                 /* Let's see if the resulting transaction still has
1018                  * unmergeable entries ... */
1019         }
1020
1021         /* Eights step: Drop redundant jobs again, if the merging now allows us to drop more. */
1022         transaction_drop_redundant(m);
1023
1024         /* Ninth step: check whether we can actually apply this */
1025         if (mode == JOB_FAIL)
1026                 if ((r = transaction_is_destructive(m, mode)) < 0) {
1027                         log_debug("Requested transaction contradicts existing jobs: %s", strerror(-r));
1028                         goto rollback;
1029                 }
1030
1031         /* Tenth step: apply changes */
1032         if ((r = transaction_apply(m, mode)) < 0) {
1033                 log_debug("Failed to apply transaction: %s", strerror(-r));
1034                 goto rollback;
1035         }
1036
1037         assert(hashmap_isempty(m->transaction_jobs));
1038         assert(!m->transaction_anchor);
1039
1040         return 0;
1041
1042 rollback:
1043         transaction_abort(m);
1044         return r;
1045 }
1046
1047 static Job* transaction_add_one_job(Manager *m, JobType type, Unit *unit, bool force, bool *is_new) {
1048         Job *j, *f;
1049         int r;
1050
1051         assert(m);
1052         assert(unit);
1053
1054         /* Looks for an axisting prospective job and returns that. If
1055          * it doesn't exist it is created and added to the prospective
1056          * jobs list. */
1057
1058         f = hashmap_get(m->transaction_jobs, unit);
1059
1060         LIST_FOREACH(transaction, j, f) {
1061                 assert(j->unit == unit);
1062
1063                 if (j->type == type) {
1064                         if (is_new)
1065                                 *is_new = false;
1066                         return j;
1067                 }
1068         }
1069
1070         if (unit->meta.job && unit->meta.job->type == type)
1071                 j = unit->meta.job;
1072         else if (!(j = job_new(m, type, unit)))
1073                 return NULL;
1074
1075         j->generation = 0;
1076         j->marker = NULL;
1077         j->matters_to_anchor = false;
1078         j->forced = force;
1079
1080         LIST_PREPEND(Job, transaction, f, j);
1081
1082         if ((r = hashmap_replace(m->transaction_jobs, unit, f)) < 0) {
1083                 job_free(j);
1084                 return NULL;
1085         }
1086
1087         if (is_new)
1088                 *is_new = true;
1089
1090         log_debug("Added job %s/%s to transaction.", unit_id(unit), job_type_to_string(type));
1091
1092         return j;
1093 }
1094
1095 void manager_transaction_unlink_job(Manager *m, Job *j, bool delete_dependencies) {
1096         assert(m);
1097         assert(j);
1098
1099         if (j->transaction_prev)
1100                 j->transaction_prev->transaction_next = j->transaction_next;
1101         else if (j->transaction_next)
1102                 hashmap_replace(m->transaction_jobs, j->unit, j->transaction_next);
1103         else
1104                 hashmap_remove_value(m->transaction_jobs, j->unit, j);
1105
1106         if (j->transaction_next)
1107                 j->transaction_next->transaction_prev = j->transaction_prev;
1108
1109         j->transaction_prev = j->transaction_next = NULL;
1110
1111         while (j->subject_list)
1112                 job_dependency_free(j->subject_list);
1113
1114         while (j->object_list) {
1115                 Job *other = j->object_list->matters ? j->object_list->subject : NULL;
1116
1117                 job_dependency_free(j->object_list);
1118
1119                 if (other && delete_dependencies) {
1120                         log_debug("Deleting job %s/%s as dependency of job %s/%s",
1121                                   unit_id(other->unit), job_type_to_string(other->type),
1122                                   unit_id(j->unit), job_type_to_string(j->type));
1123                         transaction_delete_job(m, other, delete_dependencies);
1124                 }
1125         }
1126 }
1127
1128 static int transaction_add_job_and_dependencies(Manager *m, JobType type, Unit *unit, Job *by, bool matters, bool force, Job **_ret) {
1129         Job *ret;
1130         Iterator i;
1131         Unit *dep;
1132         int r;
1133         bool is_new;
1134
1135         assert(m);
1136         assert(type < _JOB_TYPE_MAX);
1137         assert(unit);
1138
1139         if (unit->meta.load_state != UNIT_LOADED)
1140                 return -EINVAL;
1141
1142         if (!unit_job_is_applicable(unit, type))
1143                 return -EBADR;
1144
1145         /* First add the job. */
1146         if (!(ret = transaction_add_one_job(m, type, unit, force, &is_new)))
1147                 return -ENOMEM;
1148
1149         /* Then, add a link to the job. */
1150         if (!job_dependency_new(by, ret, matters))
1151                 return -ENOMEM;
1152
1153         if (is_new) {
1154                 /* Finally, recursively add in all dependencies. */
1155                 if (type == JOB_START || type == JOB_RELOAD_OR_START) {
1156                         SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES], i)
1157                                 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, true, force, NULL)) < 0 && r != -EBADR)
1158                                         goto fail;
1159                         SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_SOFT_REQUIRES], i)
1160                                 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, !force, force, NULL)) < 0 && r != -EBADR)
1161                                         goto fail;
1162                         SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_WANTS], i)
1163                                 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, false, force, NULL)) < 0)
1164                                         log_warning("Cannot add dependency job for unit %s, ignoring: %s", unit_id(dep), strerror(-r));
1165                         SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE], i)
1166                                 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, true, force, NULL)) < 0 && r != -EBADR)
1167                                         goto fail;
1168                         SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_SOFT_REQUISITE], i)
1169                                 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, !force, force, NULL)) < 0 && r != -EBADR)
1170                                         goto fail;
1171                         SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_CONFLICTS], i)
1172                                 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, dep, ret, true, force, NULL)) < 0 && r != -EBADR)
1173                                         goto fail;
1174
1175                 } else if (type == JOB_STOP || type == JOB_RESTART || type == JOB_TRY_RESTART) {
1176
1177                         SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRED_BY], i)
1178                                 if ((r = transaction_add_job_and_dependencies(m, type, dep, ret, true, force, NULL)) < 0 && r != -EBADR)
1179                                         goto fail;
1180                 }
1181
1182                 /* JOB_VERIFY_STARTED, JOB_RELOAD require no dependency handling */
1183         }
1184
1185         if (_ret)
1186                 *_ret = ret;
1187
1188         return 0;
1189
1190 fail:
1191         return r;
1192 }
1193
1194 int manager_add_job(Manager *m, JobType type, Unit *unit, JobMode mode, bool force, Job **_ret) {
1195         int r;
1196         Job *ret;
1197
1198         assert(m);
1199         assert(type < _JOB_TYPE_MAX);
1200         assert(unit);
1201         assert(mode < _JOB_MODE_MAX);
1202
1203         log_debug("Trying to enqueue job %s/%s", unit_id(unit), job_type_to_string(type));
1204
1205         if ((r = transaction_add_job_and_dependencies(m, type, unit, NULL, true, force, &ret)) < 0) {
1206                 transaction_abort(m);
1207                 return r;
1208         }
1209
1210         if ((r = transaction_activate(m, mode)) < 0)
1211                 return r;
1212
1213         log_debug("Enqueued job %s/%s as %u", unit_id(unit), job_type_to_string(type), (unsigned) ret->id);
1214
1215         if (_ret)
1216                 *_ret = ret;
1217
1218         return 0;
1219 }
1220
1221 Job *manager_get_job(Manager *m, uint32_t id) {
1222         assert(m);
1223
1224         return hashmap_get(m->jobs, UINT32_TO_PTR(id));
1225 }
1226
1227 Unit *manager_get_unit(Manager *m, const char *name) {
1228         assert(m);
1229         assert(name);
1230
1231         return hashmap_get(m->units, name);
1232 }
1233
1234 unsigned manager_dispatch_load_queue(Manager *m) {
1235         Meta *meta;
1236         unsigned n = 0;
1237
1238         assert(m);
1239
1240         /* Make sure we are not run recursively */
1241         if (m->dispatching_load_queue)
1242                 return 0;
1243
1244         m->dispatching_load_queue = true;
1245
1246         /* Dispatches the load queue. Takes a unit from the queue and
1247          * tries to load its data until the queue is empty */
1248
1249         while ((meta = m->load_queue)) {
1250                 assert(meta->in_load_queue);
1251
1252                 unit_load(UNIT(meta));
1253                 n++;
1254         }
1255
1256         m->dispatching_load_queue = false;
1257         return n;
1258 }
1259
1260 int manager_load_unit(Manager *m, const char *path, Unit **_ret) {
1261         Unit *ret;
1262         int r;
1263         const char *name;
1264
1265         assert(m);
1266         assert(path);
1267         assert(_ret);
1268
1269         /* This will load the service information files, but not actually
1270          * start any services or anything. */
1271
1272         name = file_name_from_path(path);
1273
1274         if ((ret = manager_get_unit(m, name))) {
1275                 *_ret = ret;
1276                 return 0;
1277         }
1278
1279         if (!(ret = unit_new(m)))
1280                 return -ENOMEM;
1281
1282         if (is_path(path)) {
1283                 if (!(ret->meta.fragment_path = strdup(path))) {
1284                         unit_free(ret);
1285                         return -ENOMEM;
1286                 }
1287         }
1288
1289         if ((r = unit_add_name(ret, name)) < 0) {
1290                 unit_free(ret);
1291                 return r;
1292         }
1293
1294         unit_add_to_load_queue(ret);
1295         unit_add_to_dbus_queue(ret);
1296
1297         manager_dispatch_load_queue(m);
1298
1299         *_ret = unit_follow_merge(ret);
1300         return 0;
1301 }
1302
1303 void manager_dump_jobs(Manager *s, FILE *f, const char *prefix) {
1304         Iterator i;
1305         Job *j;
1306
1307         assert(s);
1308         assert(f);
1309
1310         HASHMAP_FOREACH(j, s->jobs, i)
1311                 job_dump(j, f, prefix);
1312 }
1313
1314 void manager_dump_units(Manager *s, FILE *f, const char *prefix) {
1315         Iterator i;
1316         Unit *u;
1317         const char *t;
1318
1319         assert(s);
1320         assert(f);
1321
1322         HASHMAP_FOREACH_KEY(u, t, s->units, i)
1323                 if (unit_id(u) == t)
1324                         unit_dump(u, f, prefix);
1325 }
1326
1327 void manager_clear_jobs(Manager *m) {
1328         Job *j;
1329
1330         assert(m);
1331
1332         transaction_abort(m);
1333
1334         while ((j = hashmap_first(m->jobs)))
1335                 job_free(j);
1336 }
1337
1338 unsigned manager_dispatch_run_queue(Manager *m) {
1339         Job *j;
1340         unsigned n = 0;
1341
1342         if (m->dispatching_run_queue)
1343                 return 0;
1344
1345         m->dispatching_run_queue = true;
1346
1347         while ((j = m->run_queue)) {
1348                 assert(j->installed);
1349                 assert(j->in_run_queue);
1350
1351                 job_run_and_invalidate(j);
1352                 n++;
1353         }
1354
1355         m->dispatching_run_queue = false;
1356         return n;
1357 }
1358
1359 unsigned manager_dispatch_dbus_queue(Manager *m) {
1360         Job *j;
1361         Meta *meta;
1362         unsigned n = 0;
1363
1364         assert(m);
1365
1366         if (m->dispatching_dbus_queue)
1367                 return 0;
1368
1369         m->dispatching_dbus_queue = true;
1370
1371         while ((meta = m->dbus_unit_queue)) {
1372                 assert(meta->in_dbus_queue);
1373
1374                 bus_unit_send_change_signal(UNIT(meta));
1375                 n++;
1376         }
1377
1378         while ((j = m->dbus_job_queue)) {
1379                 assert(j->in_dbus_queue);
1380
1381                 bus_job_send_change_signal(j);
1382                 n++;
1383         }
1384
1385         m->dispatching_dbus_queue = false;
1386         return n;
1387 }
1388
1389 static int manager_dispatch_sigchld(Manager *m) {
1390         assert(m);
1391
1392         log_debug("dispatching SIGCHLD");
1393
1394         for (;;) {
1395                 siginfo_t si;
1396                 Unit *u;
1397
1398                 zero(si);
1399                 if (waitid(P_ALL, 0, &si, WEXITED|WNOHANG) < 0) {
1400
1401                         if (errno == ECHILD)
1402                                 break;
1403
1404                         return -errno;
1405                 }
1406
1407                 if (si.si_pid == 0)
1408                         break;
1409
1410                 if (si.si_code != CLD_EXITED && si.si_code != CLD_KILLED && si.si_code != CLD_DUMPED)
1411                         continue;
1412
1413                 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);
1414
1415                 if (!(u = hashmap_remove(m->watch_pids, UINT32_TO_PTR(si.si_pid))))
1416                         continue;
1417
1418                 UNIT_VTABLE(u)->sigchld_event(u, si.si_pid, si.si_code, si.si_status);
1419         }
1420
1421         return 0;
1422 }
1423
1424 static int manager_process_signal_fd(Manager *m, bool *quit) {
1425         ssize_t n;
1426         struct signalfd_siginfo sfsi;
1427         bool sigchld = false;
1428
1429         assert(m);
1430
1431         for (;;) {
1432                 if ((n = read(m->signal_watch.fd, &sfsi, sizeof(sfsi))) != sizeof(sfsi)) {
1433
1434                         if (n >= 0)
1435                                 return -EIO;
1436
1437                         if (errno == EAGAIN)
1438                                 break;
1439
1440                         return -errno;
1441                 }
1442
1443                 switch (sfsi.ssi_signo) {
1444
1445                 case SIGCHLD:
1446                         sigchld = true;
1447                         break;
1448
1449                 case SIGINT:
1450                 case SIGTERM:
1451
1452                         if (m->running_as != MANAGER_INIT) {
1453                                 *quit = true;
1454                                 return 0;
1455
1456                         } else {
1457                                 Unit *target;
1458                                 int r;
1459
1460                                 if ((r = manager_load_unit(m, SPECIAL_CTRL_ALT_DEL_TARGET, &target)) < 0)
1461                                         log_error("Failed to load ctrl-alt-del target: %s", strerror(-r));
1462                                 else if ((r = manager_add_job(m, JOB_START, target, JOB_REPLACE, true, NULL)) < 0)
1463                                         log_error("Failed to enqueue ctrl-alt-del job: %s", strerror(-r));
1464
1465                                 break;
1466                         }
1467
1468                 case SIGWINCH:
1469
1470                         if (m->running_as == MANAGER_INIT) {
1471                                 Unit *target;
1472                                 int r;
1473
1474                                 if ((r = manager_load_unit(m, SPECIAL_KBREQUEST_TARGET, &target)) < 0)
1475                                         log_error("Failed to load kbrequest target: %s", strerror(-r));
1476                                 else if ((r = manager_add_job(m, JOB_START, target, JOB_REPLACE, true, NULL)) < 0)
1477                                         log_error("Failed to enqueue kbrequest job: %s", strerror(-r));
1478
1479                                 break;
1480                         }
1481
1482                         /* This is a nop on non-init systemd's */
1483
1484                         break;
1485
1486                 case SIGUSR1:
1487
1488                         printf("→ By units:\n");
1489                         manager_dump_units(m, stdout, "\t");
1490
1491                         printf("→ By jobs:\n");
1492                         manager_dump_jobs(m, stdout, "\t");
1493
1494                         break;
1495
1496                 default:
1497                         log_info("Got unhandled signal <%s>.", strsignal(sfsi.ssi_signo));
1498                 }
1499         }
1500
1501         if (sigchld)
1502                 return manager_dispatch_sigchld(m);
1503
1504         return 0;
1505 }
1506
1507 static int process_event(Manager *m, struct epoll_event *ev, bool *quit) {
1508         int r;
1509         Watch *w;
1510
1511         assert(m);
1512         assert(ev);
1513
1514         assert(w = ev->data.ptr);
1515
1516         switch (w->type) {
1517
1518         case WATCH_SIGNAL:
1519
1520                 /* An incoming signal? */
1521                 if (ev->events != EPOLLIN)
1522                         return -EINVAL;
1523
1524                 if ((r = manager_process_signal_fd(m, quit)) < 0)
1525                         return r;
1526
1527                 break;
1528
1529         case WATCH_FD:
1530
1531                 /* Some fd event, to be dispatched to the units */
1532                 UNIT_VTABLE(w->data.unit)->fd_event(w->data.unit, w->fd, ev->events, w);
1533                 break;
1534
1535         case WATCH_TIMER: {
1536                 uint64_t v;
1537                 ssize_t k;
1538
1539                 /* Some timer event, to be dispatched to the units */
1540                 if ((k = read(w->fd, &v, sizeof(v))) != sizeof(v)) {
1541
1542                         if (k < 0 && (errno == EINTR || errno == EAGAIN))
1543                                 break;
1544
1545                         return k < 0 ? -errno : -EIO;
1546                 }
1547
1548                 UNIT_VTABLE(w->data.unit)->timer_event(w->data.unit, v, w);
1549                 break;
1550         }
1551
1552         case WATCH_MOUNT:
1553                 /* Some mount table change, intended for the mount subsystem */
1554                 mount_fd_event(m, ev->events);
1555                 break;
1556
1557         case WATCH_UDEV:
1558                 /* Some notification from udev, intended for the device subsystem */
1559                 device_fd_event(m, ev->events);
1560                 break;
1561
1562         case WATCH_DBUS_WATCH:
1563                 bus_watch_event(m, w, ev->events);
1564                 break;
1565
1566         case WATCH_DBUS_TIMEOUT:
1567                 bus_timeout_event(m, w, ev->events);
1568                 break;
1569
1570         default:
1571                 assert_not_reached("Unknown epoll event type.");
1572         }
1573
1574         return 0;
1575 }
1576
1577 int manager_loop(Manager *m) {
1578         int r;
1579         bool quit = false;
1580
1581         RATELIMIT_DEFINE(rl, 1*USEC_PER_SEC, 1000);
1582
1583         assert(m);
1584
1585         do {
1586                 struct epoll_event event;
1587                 int n;
1588
1589                 if (!ratelimit_test(&rl)) {
1590                         /* Yay, something is going seriously wrong, pause a little */
1591                         log_warning("Looping too fast. Throttling execution a little.");
1592                         sleep(1);
1593                 }
1594
1595                 if (manager_dispatch_cleanup_queue(m) > 0)
1596                         continue;
1597
1598                 if (manager_dispatch_load_queue(m) > 0)
1599                         continue;
1600
1601                 if (manager_dispatch_run_queue(m) > 0)
1602                         continue;
1603
1604                 if (bus_dispatch(m) > 0)
1605                         continue;
1606
1607                 if (manager_dispatch_dbus_queue(m) > 0)
1608                         continue;
1609
1610                 if ((n = epoll_wait(m->epoll_fd, &event, 1, -1)) < 0) {
1611
1612                         if (errno == -EINTR)
1613                                 continue;
1614
1615                         return -errno;
1616                 }
1617
1618                 assert(n == 1);
1619
1620                 if ((r = process_event(m, &event, &quit)) < 0)
1621                         return r;
1622         } while (!quit);
1623
1624         return 0;
1625 }
1626
1627 int manager_get_unit_from_dbus_path(Manager *m, const char *s, Unit **_u) {
1628         char *n;
1629         Unit *u;
1630
1631         assert(m);
1632         assert(s);
1633         assert(_u);
1634
1635         if (!startswith(s, "/org/freedesktop/systemd1/unit/"))
1636                 return -EINVAL;
1637
1638         if (!(n = bus_path_unescape(s+31)))
1639                 return -ENOMEM;
1640
1641         u = manager_get_unit(m, n);
1642         free(n);
1643
1644         if (!u)
1645                 return -ENOENT;
1646
1647         *_u = u;
1648
1649         return 0;
1650 }
1651
1652 int manager_get_job_from_dbus_path(Manager *m, const char *s, Job **_j) {
1653         Job *j;
1654         unsigned id;
1655         int r;
1656
1657         assert(m);
1658         assert(s);
1659         assert(_j);
1660
1661         if (!startswith(s, "/org/freedesktop/systemd1/job/"))
1662                 return -EINVAL;
1663
1664         if ((r = safe_atou(s + 30, &id)) < 0)
1665                 return r;
1666
1667         if (!(j = manager_get_job(m, id)))
1668                 return -ENOENT;
1669
1670         *_j = j;
1671
1672         return 0;
1673 }
1674
1675 static const char* const manager_running_as_table[_MANAGER_RUNNING_AS_MAX] = {
1676         [MANAGER_INIT] = "init",
1677         [MANAGER_SYSTEM] = "system",
1678         [MANAGER_SESSION] = "session"
1679 };
1680
1681 DEFINE_STRING_TABLE_LOOKUP(manager_running_as, ManagerRunningAs);