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