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