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