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