chiark / gitweb /
service: increase default timeout for sysv scripts to 3min
[elogind.git] / src / manager.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
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 <termios.h>
35 #include <fcntl.h>
36 #include <sys/types.h>
37 #include <sys/stat.h>
38 #include <dirent.h>
39
40 #ifdef HAVE_AUDIT
41 #include <libaudit.h>
42 #endif
43
44 #include "manager.h"
45 #include "hashmap.h"
46 #include "macro.h"
47 #include "strv.h"
48 #include "log.h"
49 #include "util.h"
50 #include "ratelimit.h"
51 #include "cgroup.h"
52 #include "mount-setup.h"
53 #include "unit-name.h"
54 #include "dbus-unit.h"
55 #include "dbus-job.h"
56 #include "missing.h"
57 #include "path-lookup.h"
58 #include "special.h"
59 #include "bus-errors.h"
60 #include "exit-status.h"
61
62 /* As soon as 16 units are in our GC queue, make sure to run a gc sweep */
63 #define GC_QUEUE_ENTRIES_MAX 16
64
65 /* As soon as 5s passed since a unit was added to our GC queue, make sure to run a gc sweep */
66 #define GC_QUEUE_USEC_MAX (10*USEC_PER_SEC)
67
68 /* Where clients shall send notification messages to */
69 #define NOTIFY_SOCKET "/org/freedesktop/systemd1/notify"
70
71 static int manager_setup_notify(Manager *m) {
72         union {
73                 struct sockaddr sa;
74                 struct sockaddr_un un;
75         } sa;
76         struct epoll_event ev;
77         int one = 1;
78
79         assert(m);
80
81         m->notify_watch.type = WATCH_NOTIFY;
82         if ((m->notify_watch.fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0)) < 0) {
83                 log_error("Failed to allocate notification socket: %m");
84                 return -errno;
85         }
86
87         zero(sa);
88         sa.sa.sa_family = AF_UNIX;
89
90         if (getpid() != 1)
91                 snprintf(sa.un.sun_path+1, sizeof(sa.un.sun_path)-1, NOTIFY_SOCKET "/%llu", random_ull());
92         else
93                 strncpy(sa.un.sun_path+1, NOTIFY_SOCKET, sizeof(sa.un.sun_path)-1);
94
95         if (bind(m->notify_watch.fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + 1 + strlen(sa.un.sun_path+1)) < 0) {
96                 log_error("bind() failed: %m");
97                 return -errno;
98         }
99
100         if (setsockopt(m->notify_watch.fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one)) < 0) {
101                 log_error("SO_PASSCRED failed: %m");
102                 return -errno;
103         }
104
105         zero(ev);
106         ev.events = EPOLLIN;
107         ev.data.ptr = &m->notify_watch;
108
109         if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->notify_watch.fd, &ev) < 0)
110                 return -errno;
111
112         if (!(m->notify_socket = strdup(sa.un.sun_path+1)))
113                 return -ENOMEM;
114
115         log_debug("Using notification socket %s", m->notify_socket);
116
117         return 0;
118 }
119
120 static int enable_special_signals(Manager *m) {
121         char fd;
122
123         assert(m);
124
125         /* Enable that we get SIGINT on control-alt-del */
126         if (reboot(RB_DISABLE_CAD) < 0)
127                 log_warning("Failed to enable ctrl-alt-del handling: %m");
128
129         if ((fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY)) < 0)
130                 log_warning("Failed to open /dev/tty0: %m");
131         else {
132                 /* Enable that we get SIGWINCH on kbrequest */
133                 if (ioctl(fd, KDSIGACCEPT, SIGWINCH) < 0)
134                         log_warning("Failed to enable kbrequest handling: %s", strerror(errno));
135
136                 close_nointr_nofail(fd);
137         }
138
139         return 0;
140 }
141
142 static int manager_setup_signals(Manager *m) {
143         sigset_t mask;
144         struct epoll_event ev;
145         struct sigaction sa;
146
147         assert(m);
148
149         /* We are not interested in SIGSTOP and friends. */
150         zero(sa);
151         sa.sa_handler = SIG_DFL;
152         sa.sa_flags = SA_NOCLDSTOP|SA_RESTART;
153         assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);
154
155         assert_se(sigemptyset(&mask) == 0);
156
157         sigset_add_many(&mask,
158                         SIGCHLD,     /* Child died */
159                         SIGTERM,     /* Reexecute daemon */
160                         SIGHUP,      /* Reload configuration */
161                         SIGUSR1,     /* systemd/upstart: reconnect to D-Bus */
162                         SIGUSR2,     /* systemd: dump status */
163                         SIGINT,      /* Kernel sends us this on control-alt-del */
164                         SIGWINCH,    /* Kernel sends us this on kbrequest (alt-arrowup) */
165                         SIGPWR,      /* Some kernel drivers and upsd send us this on power failure */
166                         SIGRTMIN+0,  /* systemd: start default.target */
167                         SIGRTMIN+1,  /* systemd: start rescue.target */
168                         SIGRTMIN+2,  /* systemd: isolate emergency.target */
169                         SIGRTMIN+3,  /* systemd: start halt.target */
170                         SIGRTMIN+4,  /* systemd: start poweroff.target */
171                         SIGRTMIN+5,  /* systemd: start reboot.target */
172                         -1);
173         assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
174
175         m->signal_watch.type = WATCH_SIGNAL;
176         if ((m->signal_watch.fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0)
177                 return -errno;
178
179         zero(ev);
180         ev.events = EPOLLIN;
181         ev.data.ptr = &m->signal_watch;
182
183         if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->signal_watch.fd, &ev) < 0)
184                 return -errno;
185
186         if (m->running_as == MANAGER_SYSTEM)
187                 return enable_special_signals(m);
188
189         return 0;
190 }
191
192 int manager_new(ManagerRunningAs running_as, Manager **_m) {
193         Manager *m;
194         int r = -ENOMEM;
195
196         assert(_m);
197         assert(running_as >= 0);
198         assert(running_as < _MANAGER_RUNNING_AS_MAX);
199
200         if (!(m = new0(Manager, 1)))
201                 return -ENOMEM;
202
203         dual_timestamp_get(&m->startup_timestamp);
204
205         m->running_as = running_as;
206         m->name_data_slot = m->subscribed_data_slot = -1;
207         m->exit_code = _MANAGER_EXIT_CODE_INVALID;
208         m->pin_cgroupfs_fd = -1;
209
210 #ifdef HAVE_AUDIT
211         m->audit_fd = -1;
212 #endif
213
214         m->signal_watch.fd = m->mount_watch.fd = m->udev_watch.fd = m->epoll_fd = m->dev_autofs_fd = -1;
215         m->current_job_id = 1; /* start as id #1, so that we can leave #0 around as "null-like" value */
216
217         if (!(m->environment = strv_copy(environ)))
218                 goto fail;
219
220         if (!(m->units = hashmap_new(string_hash_func, string_compare_func)))
221                 goto fail;
222
223         if (!(m->jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
224                 goto fail;
225
226         if (!(m->transaction_jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
227                 goto fail;
228
229         if (!(m->watch_pids = hashmap_new(trivial_hash_func, trivial_compare_func)))
230                 goto fail;
231
232         if (!(m->cgroup_bondings = hashmap_new(string_hash_func, string_compare_func)))
233                 goto fail;
234
235         if (!(m->watch_bus = hashmap_new(string_hash_func, string_compare_func)))
236                 goto fail;
237
238         if ((m->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0)
239                 goto fail;
240
241         if ((r = lookup_paths_init(&m->lookup_paths, m->running_as)) < 0)
242                 goto fail;
243
244         if ((r = manager_setup_signals(m)) < 0)
245                 goto fail;
246
247         if ((r = manager_setup_cgroup(m)) < 0)
248                 goto fail;
249
250         if ((r = manager_setup_notify(m)) < 0)
251                 goto fail;
252
253         /* Try to connect to the busses, if possible. */
254         if ((r = bus_init(m)) < 0)
255                 goto fail;
256
257 #ifdef HAVE_AUDIT
258         if ((m->audit_fd = audit_open()) < 0)
259                 log_error("Failed to connect to audit log: %m");
260 #endif
261
262         *_m = m;
263         return 0;
264
265 fail:
266         manager_free(m);
267         return r;
268 }
269
270 static unsigned manager_dispatch_cleanup_queue(Manager *m) {
271         Meta *meta;
272         unsigned n = 0;
273
274         assert(m);
275
276         while ((meta = m->cleanup_queue)) {
277                 assert(meta->in_cleanup_queue);
278
279                 unit_free((Unit*) meta);
280                 n++;
281         }
282
283         return n;
284 }
285
286 enum {
287         GC_OFFSET_IN_PATH,  /* This one is on the path we were travelling */
288         GC_OFFSET_UNSURE,   /* No clue */
289         GC_OFFSET_GOOD,     /* We still need this unit */
290         GC_OFFSET_BAD,      /* We don't need this unit anymore */
291         _GC_OFFSET_MAX
292 };
293
294 static void unit_gc_sweep(Unit *u, unsigned gc_marker) {
295         Iterator i;
296         Unit *other;
297         bool is_bad;
298
299         assert(u);
300
301         if (u->meta.gc_marker == gc_marker + GC_OFFSET_GOOD ||
302             u->meta.gc_marker == gc_marker + GC_OFFSET_BAD ||
303             u->meta.gc_marker == gc_marker + GC_OFFSET_IN_PATH)
304                 return;
305
306         if (u->meta.in_cleanup_queue)
307                 goto bad;
308
309         if (unit_check_gc(u))
310                 goto good;
311
312         u->meta.gc_marker = gc_marker + GC_OFFSET_IN_PATH;
313
314         is_bad = true;
315
316         SET_FOREACH(other, u->meta.dependencies[UNIT_REFERENCED_BY], i) {
317                 unit_gc_sweep(other, gc_marker);
318
319                 if (other->meta.gc_marker == gc_marker + GC_OFFSET_GOOD)
320                         goto good;
321
322                 if (other->meta.gc_marker != gc_marker + GC_OFFSET_BAD)
323                         is_bad = false;
324         }
325
326         if (is_bad)
327                 goto bad;
328
329         /* We were unable to find anything out about this entry, so
330          * let's investigate it later */
331         u->meta.gc_marker = gc_marker + GC_OFFSET_UNSURE;
332         unit_add_to_gc_queue(u);
333         return;
334
335 bad:
336         /* We definitely know that this one is not useful anymore, so
337          * let's mark it for deletion */
338         u->meta.gc_marker = gc_marker + GC_OFFSET_BAD;
339         unit_add_to_cleanup_queue(u);
340         return;
341
342 good:
343         u->meta.gc_marker = gc_marker + GC_OFFSET_GOOD;
344 }
345
346 static unsigned manager_dispatch_gc_queue(Manager *m) {
347         Meta *meta;
348         unsigned n = 0;
349         unsigned gc_marker;
350
351         assert(m);
352
353         if ((m->n_in_gc_queue < GC_QUEUE_ENTRIES_MAX) &&
354             (m->gc_queue_timestamp <= 0 ||
355              (m->gc_queue_timestamp + GC_QUEUE_USEC_MAX) > now(CLOCK_MONOTONIC)))
356                 return 0;
357
358         log_debug("Running GC...");
359
360         m->gc_marker += _GC_OFFSET_MAX;
361         if (m->gc_marker + _GC_OFFSET_MAX <= _GC_OFFSET_MAX)
362                 m->gc_marker = 1;
363
364         gc_marker = m->gc_marker;
365
366         while ((meta = m->gc_queue)) {
367                 assert(meta->in_gc_queue);
368
369                 unit_gc_sweep((Unit*) meta, gc_marker);
370
371                 LIST_REMOVE(Meta, gc_queue, m->gc_queue, meta);
372                 meta->in_gc_queue = false;
373
374                 n++;
375
376                 if (meta->gc_marker == gc_marker + GC_OFFSET_BAD ||
377                     meta->gc_marker == gc_marker + GC_OFFSET_UNSURE) {
378                         log_debug("Collecting %s", meta->id);
379                         meta->gc_marker = gc_marker + GC_OFFSET_BAD;
380                         unit_add_to_cleanup_queue((Unit*) meta);
381                 }
382         }
383
384         m->n_in_gc_queue = 0;
385         m->gc_queue_timestamp = 0;
386
387         return n;
388 }
389
390 static void manager_clear_jobs_and_units(Manager *m) {
391         Job *j;
392         Unit *u;
393
394         assert(m);
395
396         while ((j = hashmap_first(m->transaction_jobs)))
397                 job_free(j);
398
399         while ((u = hashmap_first(m->units)))
400                 unit_free(u);
401
402         manager_dispatch_cleanup_queue(m);
403
404         assert(!m->load_queue);
405         assert(!m->run_queue);
406         assert(!m->dbus_unit_queue);
407         assert(!m->dbus_job_queue);
408         assert(!m->cleanup_queue);
409         assert(!m->gc_queue);
410
411         assert(hashmap_isempty(m->transaction_jobs));
412         assert(hashmap_isempty(m->jobs));
413         assert(hashmap_isempty(m->units));
414 }
415
416 void manager_free(Manager *m) {
417         UnitType c;
418
419         assert(m);
420
421         manager_clear_jobs_and_units(m);
422
423         for (c = 0; c < _UNIT_TYPE_MAX; c++)
424                 if (unit_vtable[c]->shutdown)
425                         unit_vtable[c]->shutdown(m);
426
427         /* If we reexecute ourselves, we keep the root cgroup
428          * around */
429         manager_shutdown_cgroup(m, m->exit_code != MANAGER_REEXECUTE);
430
431         bus_done(m);
432
433         hashmap_free(m->units);
434         hashmap_free(m->jobs);
435         hashmap_free(m->transaction_jobs);
436         hashmap_free(m->watch_pids);
437         hashmap_free(m->watch_bus);
438
439         if (m->epoll_fd >= 0)
440                 close_nointr_nofail(m->epoll_fd);
441         if (m->signal_watch.fd >= 0)
442                 close_nointr_nofail(m->signal_watch.fd);
443         if (m->notify_watch.fd >= 0)
444                 close_nointr_nofail(m->notify_watch.fd);
445
446 #ifdef HAVE_AUDIT
447         if (m->audit_fd >= 0)
448                 audit_close(m->audit_fd);
449 #endif
450
451         free(m->notify_socket);
452         free(m->console);
453
454         lookup_paths_free(&m->lookup_paths);
455         strv_free(m->environment);
456
457         hashmap_free(m->cgroup_bondings);
458         set_free_free(m->unit_path_cache);
459
460         free(m);
461 }
462
463 int manager_enumerate(Manager *m) {
464         int r = 0, q;
465         UnitType c;
466
467         assert(m);
468
469         /* Let's ask every type to load all units from disk/kernel
470          * that it might know */
471         for (c = 0; c < _UNIT_TYPE_MAX; c++)
472                 if (unit_vtable[c]->enumerate)
473                         if ((q = unit_vtable[c]->enumerate(m)) < 0)
474                                 r = q;
475
476         manager_dispatch_load_queue(m);
477         return r;
478 }
479
480 int manager_coldplug(Manager *m) {
481         int r = 0, q;
482         Iterator i;
483         Unit *u;
484         char *k;
485
486         assert(m);
487
488         /* Then, let's set up their initial state. */
489         HASHMAP_FOREACH_KEY(u, k, m->units, i) {
490
491                 /* ignore aliases */
492                 if (u->meta.id != k)
493                         continue;
494
495                 if ((q = unit_coldplug(u)) < 0)
496                         r = q;
497         }
498
499         return r;
500 }
501
502 static void manager_build_unit_path_cache(Manager *m) {
503         char **i;
504         DIR *d = NULL;
505         int r;
506
507         assert(m);
508
509         set_free_free(m->unit_path_cache);
510
511         if (!(m->unit_path_cache = set_new(string_hash_func, string_compare_func))) {
512                 log_error("Failed to allocate unit path cache.");
513                 return;
514         }
515
516         /* This simply builds a list of files we know exist, so that
517          * we don't always have to go to disk */
518
519         STRV_FOREACH(i, m->lookup_paths.unit_path) {
520                 struct dirent *de;
521
522                 if (!(d = opendir(*i))) {
523                         log_error("Failed to open directory: %m");
524                         continue;
525                 }
526
527                 while ((de = readdir(d))) {
528                         char *p;
529
530                         if (ignore_file(de->d_name))
531                                 continue;
532
533                         if (asprintf(&p, "%s/%s", streq(*i, "/") ? "" : *i, de->d_name) < 0) {
534                                 r = -ENOMEM;
535                                 goto fail;
536                         }
537
538                         if ((r = set_put(m->unit_path_cache, p)) < 0) {
539                                 free(p);
540                                 goto fail;
541                         }
542                 }
543
544                 closedir(d);
545                 d = NULL;
546         }
547
548         return;
549
550 fail:
551         log_error("Failed to build unit path cache: %s", strerror(-r));
552
553         set_free_free(m->unit_path_cache);
554         m->unit_path_cache = NULL;
555
556         if (d)
557                 closedir(d);
558 }
559
560 int manager_startup(Manager *m, FILE *serialization, FDSet *fds) {
561         int r, q;
562
563         assert(m);
564
565         manager_build_unit_path_cache(m);
566
567         /* If we will deserialize make sure that during enumeration
568          * this is already known, so we increase the counter here
569          * already */
570         if (serialization)
571                 m->n_deserializing ++;
572
573         /* First, enumerate what we can from all config files */
574         r = manager_enumerate(m);
575
576         /* Second, deserialize if there is something to deserialize */
577         if (serialization)
578                 if ((q = manager_deserialize(m, serialization, fds)) < 0)
579                         r = q;
580
581         /* Third, fire things up! */
582         if ((q = manager_coldplug(m)) < 0)
583                 r = q;
584
585         if (serialization) {
586                 assert(m->n_deserializing > 0);
587                 m->n_deserializing --;
588         }
589
590         return r;
591 }
592
593 static void transaction_delete_job(Manager *m, Job *j, bool delete_dependencies) {
594         assert(m);
595         assert(j);
596
597         /* Deletes one job from the transaction */
598
599         manager_transaction_unlink_job(m, j, delete_dependencies);
600
601         if (!j->installed)
602                 job_free(j);
603 }
604
605 static void transaction_delete_unit(Manager *m, Unit *u) {
606         Job *j;
607
608         /* Deletes all jobs associated with a certain unit from the
609          * transaction */
610
611         while ((j = hashmap_get(m->transaction_jobs, u)))
612                 transaction_delete_job(m, j, true);
613 }
614
615 static void transaction_clean_dependencies(Manager *m) {
616         Iterator i;
617         Job *j;
618
619         assert(m);
620
621         /* Drops all dependencies of all installed jobs */
622
623         HASHMAP_FOREACH(j, m->jobs, i) {
624                 while (j->subject_list)
625                         job_dependency_free(j->subject_list);
626                 while (j->object_list)
627                         job_dependency_free(j->object_list);
628         }
629
630         assert(!m->transaction_anchor);
631 }
632
633 static void transaction_abort(Manager *m) {
634         Job *j;
635
636         assert(m);
637
638         while ((j = hashmap_first(m->transaction_jobs)))
639                 if (j->installed)
640                         transaction_delete_job(m, j, true);
641                 else
642                         job_free(j);
643
644         assert(hashmap_isempty(m->transaction_jobs));
645
646         transaction_clean_dependencies(m);
647 }
648
649 static void transaction_find_jobs_that_matter_to_anchor(Manager *m, Job *j, unsigned generation) {
650         JobDependency *l;
651
652         assert(m);
653
654         /* A recursive sweep through the graph that marks all units
655          * that matter to the anchor job, i.e. are directly or
656          * indirectly a dependency of the anchor job via paths that
657          * are fully marked as mattering. */
658
659         if (j)
660                 l = j->subject_list;
661         else
662                 l = m->transaction_anchor;
663
664         LIST_FOREACH(subject, l, l) {
665
666                 /* This link does not matter */
667                 if (!l->matters)
668                         continue;
669
670                 /* This unit has already been marked */
671                 if (l->object->generation == generation)
672                         continue;
673
674                 l->object->matters_to_anchor = true;
675                 l->object->generation = generation;
676
677                 transaction_find_jobs_that_matter_to_anchor(m, l->object, generation);
678         }
679 }
680
681 static void transaction_merge_and_delete_job(Manager *m, Job *j, Job *other, JobType t) {
682         JobDependency *l, *last;
683
684         assert(j);
685         assert(other);
686         assert(j->unit == other->unit);
687         assert(!j->installed);
688
689         /* Merges 'other' into 'j' and then deletes j. */
690
691         j->type = t;
692         j->state = JOB_WAITING;
693         j->override = j->override || other->override;
694
695         j->matters_to_anchor = j->matters_to_anchor || other->matters_to_anchor;
696
697         /* Patch us in as new owner of the JobDependency objects */
698         last = NULL;
699         LIST_FOREACH(subject, l, other->subject_list) {
700                 assert(l->subject == other);
701                 l->subject = j;
702                 last = l;
703         }
704
705         /* Merge both lists */
706         if (last) {
707                 last->subject_next = j->subject_list;
708                 if (j->subject_list)
709                         j->subject_list->subject_prev = last;
710                 j->subject_list = other->subject_list;
711         }
712
713         /* Patch us in as new owner of the JobDependency objects */
714         last = NULL;
715         LIST_FOREACH(object, l, other->object_list) {
716                 assert(l->object == other);
717                 l->object = j;
718                 last = l;
719         }
720
721         /* Merge both lists */
722         if (last) {
723                 last->object_next = j->object_list;
724                 if (j->object_list)
725                         j->object_list->object_prev = last;
726                 j->object_list = other->object_list;
727         }
728
729         /* Kill the other job */
730         other->subject_list = NULL;
731         other->object_list = NULL;
732         transaction_delete_job(m, other, true);
733 }
734 static bool job_is_conflicted_by(Job *j) {
735         JobDependency *l;
736
737         assert(j);
738
739         /* Returns true if this job is pulled in by a least one
740          * ConflictedBy dependency. */
741
742         LIST_FOREACH(object, l, j->object_list)
743                 if (l->conflicts)
744                         return true;
745
746         return false;
747 }
748
749 static int delete_one_unmergeable_job(Manager *m, Job *j) {
750         Job *k;
751
752         assert(j);
753
754         /* Tries to delete one item in the linked list
755          * j->transaction_next->transaction_next->... that conflicts
756          * whith another one, in an attempt to make an inconsistent
757          * transaction work. */
758
759         /* We rely here on the fact that if a merged with b does not
760          * merge with c, either a or b merge with c neither */
761         LIST_FOREACH(transaction, j, j)
762                 LIST_FOREACH(transaction, k, j->transaction_next) {
763                         Job *d;
764
765                         /* Is this one mergeable? Then skip it */
766                         if (job_type_is_mergeable(j->type, k->type))
767                                 continue;
768
769                         /* Ok, we found two that conflict, let's see if we can
770                          * drop one of them */
771                         if (!j->matters_to_anchor && !k->matters_to_anchor) {
772
773                                 /* Both jobs don't matter, so let's
774                                  * find the one that is smarter to
775                                  * remove. Let's think positive and
776                                  * rather remove stops then starts --
777                                  * except if something is being
778                                  * stopped because it is conflicted by
779                                  * another unit in which case we
780                                  * rather remove the start. */
781
782                                 log_debug("Looking at job %s/%s conflicted_by=%s", j->unit->meta.id, job_type_to_string(j->type), yes_no(j->type == JOB_STOP && job_is_conflicted_by(j)));
783                                 log_debug("Looking at job %s/%s conflicted_by=%s", k->unit->meta.id, job_type_to_string(k->type), yes_no(k->type == JOB_STOP && job_is_conflicted_by(k)));
784
785                                 if (j->type == JOB_STOP) {
786
787                                         if (job_is_conflicted_by(j))
788                                                 d = k;
789                                         else
790                                                 d = j;
791
792                                 } else if (k->type == JOB_STOP) {
793
794                                         if (job_is_conflicted_by(k))
795                                                 d = j;
796                                         else
797                                                 d = k;
798                                 } else
799                                         d = j;
800
801                         } else if (!j->matters_to_anchor)
802                                 d = j;
803                         else if (!k->matters_to_anchor)
804                                 d = k;
805                         else
806                                 return -ENOEXEC;
807
808                         /* Ok, we can drop one, so let's do so. */
809                         log_debug("Fixing conflicting jobs by deleting job %s/%s", d->unit->meta.id, job_type_to_string(d->type));
810                         transaction_delete_job(m, d, true);
811                         return 0;
812                 }
813
814         return -EINVAL;
815 }
816
817 static int transaction_merge_jobs(Manager *m, DBusError *e) {
818         Job *j;
819         Iterator i;
820         int r;
821
822         assert(m);
823
824         /* First step, check whether any of the jobs for one specific
825          * task conflict. If so, try to drop one of them. */
826         HASHMAP_FOREACH(j, m->transaction_jobs, i) {
827                 JobType t;
828                 Job *k;
829
830                 t = j->type;
831                 LIST_FOREACH(transaction, k, j->transaction_next) {
832                         if (job_type_merge(&t, k->type) >= 0)
833                                 continue;
834
835                         /* OK, we could not merge all jobs for this
836                          * action. Let's see if we can get rid of one
837                          * of them */
838
839                         if ((r = delete_one_unmergeable_job(m, j)) >= 0)
840                                 /* Ok, we managed to drop one, now
841                                  * let's ask our callers to call us
842                                  * again after garbage collecting */
843                                 return -EAGAIN;
844
845                         /* We couldn't merge anything. Failure */
846                         dbus_set_error(e, BUS_ERROR_TRANSACTION_JOBS_CONFLICTING, "Transaction contains conflicting jobs '%s' and '%s' for %s. Probably contradicting requirement dependencies configured.",
847                                        job_type_to_string(t), job_type_to_string(k->type), k->unit->meta.id);
848                         return r;
849                 }
850         }
851
852         /* Second step, merge the jobs. */
853         HASHMAP_FOREACH(j, m->transaction_jobs, i) {
854                 JobType t = j->type;
855                 Job *k;
856
857                 /* Merge all transactions */
858                 LIST_FOREACH(transaction, k, j->transaction_next)
859                         assert_se(job_type_merge(&t, k->type) == 0);
860
861                 /* If an active job is mergeable, merge it too */
862                 if (j->unit->meta.job)
863                         job_type_merge(&t, j->unit->meta.job->type); /* Might fail. Which is OK */
864
865                 while ((k = j->transaction_next)) {
866                         if (j->installed) {
867                                 transaction_merge_and_delete_job(m, k, j, t);
868                                 j = k;
869                         } else
870                                 transaction_merge_and_delete_job(m, j, k, t);
871                 }
872
873                 assert(!j->transaction_next);
874                 assert(!j->transaction_prev);
875         }
876
877         return 0;
878 }
879
880 static void transaction_drop_redundant(Manager *m) {
881         bool again;
882
883         assert(m);
884
885         /* Goes through the transaction and removes all jobs that are
886          * a noop */
887
888         do {
889                 Job *j;
890                 Iterator i;
891
892                 again = false;
893
894                 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
895                         bool changes_something = false;
896                         Job *k;
897
898                         LIST_FOREACH(transaction, k, j) {
899
900                                 if (!job_is_anchor(k) &&
901                                     job_type_is_redundant(k->type, unit_active_state(k->unit)))
902                                         continue;
903
904                                 changes_something = true;
905                                 break;
906                         }
907
908                         if (changes_something)
909                                 continue;
910
911                         log_debug("Found redundant job %s/%s, dropping.", j->unit->meta.id, job_type_to_string(j->type));
912                         transaction_delete_job(m, j, false);
913                         again = true;
914                         break;
915                 }
916
917         } while (again);
918 }
919
920 static bool unit_matters_to_anchor(Unit *u, Job *j) {
921         assert(u);
922         assert(!j->transaction_prev);
923
924         /* Checks whether at least one of the jobs for this unit
925          * matters to the anchor. */
926
927         LIST_FOREACH(transaction, j, j)
928                 if (j->matters_to_anchor)
929                         return true;
930
931         return false;
932 }
933
934 static int transaction_verify_order_one(Manager *m, Job *j, Job *from, unsigned generation, DBusError *e) {
935         Iterator i;
936         Unit *u;
937         int r;
938
939         assert(m);
940         assert(j);
941         assert(!j->transaction_prev);
942
943         /* Does a recursive sweep through the ordering graph, looking
944          * for a cycle. If we find cycle we try to break it. */
945
946         /* Have we seen this before? */
947         if (j->generation == generation) {
948                 Job *k, *delete;
949
950                 /* If the marker is NULL we have been here already and
951                  * decided the job was loop-free from here. Hence
952                  * shortcut things and return right-away. */
953                 if (!j->marker)
954                         return 0;
955
956                 /* So, the marker is not NULL and we already have been
957                  * here. We have a cycle. Let's try to break it. We go
958                  * backwards in our path and try to find a suitable
959                  * job to remove. We use the marker to find our way
960                  * back, since smart how we are we stored our way back
961                  * in there. */
962                 log_warning("Found ordering cycle on %s/%s", j->unit->meta.id, job_type_to_string(j->type));
963
964                 delete = NULL;
965                 for (k = from; k; k = ((k->generation == generation && k->marker != k) ? k->marker : NULL)) {
966
967                         log_info("Walked on cycle path to %s/%s", k->unit->meta.id, job_type_to_string(k->type));
968
969                         if (!delete &&
970                             !k->installed &&
971                             !unit_matters_to_anchor(k->unit, k)) {
972                                 /* Ok, we can drop this one, so let's
973                                  * do so. */
974                                 delete = k;
975                         }
976
977                         /* Check if this in fact was the beginning of
978                          * the cycle */
979                         if (k == j)
980                                 break;
981                 }
982
983
984                 if (delete) {
985                         log_warning("Breaking ordering cycle by deleting job %s/%s", delete->unit->meta.id, job_type_to_string(delete->type));
986                         transaction_delete_unit(m, delete->unit);
987                         return -EAGAIN;
988                 }
989
990                 log_error("Unable to break cycle");
991
992                 dbus_set_error(e, BUS_ERROR_TRANSACTION_ORDER_IS_CYCLIC, "Transaction order is cyclic. See system logs for details.");
993                 return -ENOEXEC;
994         }
995
996         /* Make the marker point to where we come from, so that we can
997          * find our way backwards if we want to break a cycle. We use
998          * a special marker for the beginning: we point to
999          * ourselves. */
1000         j->marker = from ? from : j;
1001         j->generation = generation;
1002
1003         /* We assume that the the dependencies are bidirectional, and
1004          * hence can ignore UNIT_AFTER */
1005         SET_FOREACH(u, j->unit->meta.dependencies[UNIT_BEFORE], i) {
1006                 Job *o;
1007
1008                 /* Is there a job for this unit? */
1009                 if (!(o = hashmap_get(m->transaction_jobs, u)))
1010
1011                         /* Ok, there is no job for this in the
1012                          * transaction, but maybe there is already one
1013                          * running? */
1014                         if (!(o = u->meta.job))
1015                                 continue;
1016
1017                 if ((r = transaction_verify_order_one(m, o, j, generation, e)) < 0)
1018                         return r;
1019         }
1020
1021         /* Ok, let's backtrack, and remember that this entry is not on
1022          * our path anymore. */
1023         j->marker = NULL;
1024
1025         return 0;
1026 }
1027
1028 static int transaction_verify_order(Manager *m, unsigned *generation, DBusError *e) {
1029         Job *j;
1030         int r;
1031         Iterator i;
1032         unsigned g;
1033
1034         assert(m);
1035         assert(generation);
1036
1037         /* Check if the ordering graph is cyclic. If it is, try to fix
1038          * that up by dropping one of the jobs. */
1039
1040         g = (*generation)++;
1041
1042         HASHMAP_FOREACH(j, m->transaction_jobs, i)
1043                 if ((r = transaction_verify_order_one(m, j, NULL, g, e)) < 0)
1044                         return r;
1045
1046         return 0;
1047 }
1048
1049 static void transaction_collect_garbage(Manager *m) {
1050         bool again;
1051
1052         assert(m);
1053
1054         /* Drop jobs that are not required by any other job */
1055
1056         do {
1057                 Iterator i;
1058                 Job *j;
1059
1060                 again = false;
1061
1062                 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1063                         if (j->object_list)
1064                                 continue;
1065
1066                         log_debug("Garbage collecting job %s/%s", j->unit->meta.id, job_type_to_string(j->type));
1067                         transaction_delete_job(m, j, true);
1068                         again = true;
1069                         break;
1070                 }
1071
1072         } while (again);
1073 }
1074
1075 static int transaction_is_destructive(Manager *m, DBusError *e) {
1076         Iterator i;
1077         Job *j;
1078
1079         assert(m);
1080
1081         /* Checks whether applying this transaction means that
1082          * existing jobs would be replaced */
1083
1084         HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1085
1086                 /* Assume merged */
1087                 assert(!j->transaction_prev);
1088                 assert(!j->transaction_next);
1089
1090                 if (j->unit->meta.job &&
1091                     j->unit->meta.job != j &&
1092                     !job_type_is_superset(j->type, j->unit->meta.job->type)) {
1093
1094                         dbus_set_error(e, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE, "Transaction is destructive.");
1095                         return -EEXIST;
1096                 }
1097         }
1098
1099         return 0;
1100 }
1101
1102 static void transaction_minimize_impact(Manager *m) {
1103         bool again;
1104         assert(m);
1105
1106         /* Drops all unnecessary jobs that reverse already active jobs
1107          * or that stop a running service. */
1108
1109         do {
1110                 Job *j;
1111                 Iterator i;
1112
1113                 again = false;
1114
1115                 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1116                         LIST_FOREACH(transaction, j, j) {
1117                                 bool stops_running_service, changes_existing_job;
1118
1119                                 /* If it matters, we shouldn't drop it */
1120                                 if (j->matters_to_anchor)
1121                                         continue;
1122
1123                                 /* Would this stop a running service?
1124                                  * Would this change an existing job?
1125                                  * If so, let's drop this entry */
1126
1127                                 stops_running_service =
1128                                         j->type == JOB_STOP && UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(j->unit));
1129
1130                                 changes_existing_job =
1131                                         j->unit->meta.job && job_type_is_conflicting(j->type, j->unit->meta.job->type);
1132
1133                                 if (!stops_running_service && !changes_existing_job)
1134                                         continue;
1135
1136                                 if (stops_running_service)
1137                                         log_info("%s/%s would stop a running service.", j->unit->meta.id, job_type_to_string(j->type));
1138
1139                                 if (changes_existing_job)
1140                                         log_info("%s/%s would change existing job.", j->unit->meta.id, job_type_to_string(j->type));
1141
1142                                 /* Ok, let's get rid of this */
1143                                 log_info("Deleting %s/%s to minimize impact.", j->unit->meta.id, job_type_to_string(j->type));
1144
1145                                 transaction_delete_job(m, j, true);
1146                                 again = true;
1147                                 break;
1148                         }
1149
1150                         if (again)
1151                                 break;
1152                 }
1153
1154         } while (again);
1155 }
1156
1157 static int transaction_apply(Manager *m) {
1158         Iterator i;
1159         Job *j;
1160         int r;
1161
1162         /* Moves the transaction jobs to the set of active jobs */
1163
1164         HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1165                 /* Assume merged */
1166                 assert(!j->transaction_prev);
1167                 assert(!j->transaction_next);
1168
1169                 if (j->installed)
1170                         continue;
1171
1172                 if ((r = hashmap_put(m->jobs, UINT32_TO_PTR(j->id), j)) < 0)
1173                         goto rollback;
1174         }
1175
1176         while ((j = hashmap_steal_first(m->transaction_jobs))) {
1177                 if (j->installed)
1178                         continue;
1179
1180                 if (j->unit->meta.job)
1181                         job_free(j->unit->meta.job);
1182
1183                 j->unit->meta.job = j;
1184                 j->installed = true;
1185                 m->n_installed_jobs ++;
1186
1187                 /* We're fully installed. Now let's free data we don't
1188                  * need anymore. */
1189
1190                 assert(!j->transaction_next);
1191                 assert(!j->transaction_prev);
1192
1193                 job_add_to_run_queue(j);
1194                 job_add_to_dbus_queue(j);
1195                 job_start_timer(j);
1196         }
1197
1198         /* As last step, kill all remaining job dependencies. */
1199         transaction_clean_dependencies(m);
1200
1201         return 0;
1202
1203 rollback:
1204
1205         HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1206                 if (j->installed)
1207                         continue;
1208
1209                 hashmap_remove(m->jobs, UINT32_TO_PTR(j->id));
1210         }
1211
1212         return r;
1213 }
1214
1215 static int transaction_activate(Manager *m, JobMode mode, DBusError *e) {
1216         int r;
1217         unsigned generation = 1;
1218
1219         assert(m);
1220
1221         /* This applies the changes recorded in transaction_jobs to
1222          * the actual list of jobs, if possible. */
1223
1224         /* First step: figure out which jobs matter */
1225         transaction_find_jobs_that_matter_to_anchor(m, NULL, generation++);
1226
1227         /* Second step: Try not to stop any running services if
1228          * we don't have to. Don't try to reverse running
1229          * jobs if we don't have to. */
1230         if (mode != JOB_ISOLATE)
1231                 transaction_minimize_impact(m);
1232
1233         /* Third step: Drop redundant jobs */
1234         transaction_drop_redundant(m);
1235
1236         for (;;) {
1237                 /* Fourth step: Let's remove unneeded jobs that might
1238                  * be lurking. */
1239                 transaction_collect_garbage(m);
1240
1241                 /* Fifth step: verify order makes sense and correct
1242                  * cycles if necessary and possible */
1243                 if ((r = transaction_verify_order(m, &generation, e)) >= 0)
1244                         break;
1245
1246                 if (r != -EAGAIN) {
1247                         log_warning("Requested transaction contains an unfixable cyclic ordering dependency: %s", bus_error(e, r));
1248                         goto rollback;
1249                 }
1250
1251                 /* Let's see if the resulting transaction ordering
1252                  * graph is still cyclic... */
1253         }
1254
1255         for (;;) {
1256                 /* Sixth step: let's drop unmergeable entries if
1257                  * necessary and possible, merge entries we can
1258                  * merge */
1259                 if ((r = transaction_merge_jobs(m, e)) >= 0)
1260                         break;
1261
1262                 if (r != -EAGAIN) {
1263                         log_warning("Requested transaction contains unmergable jobs: %s", bus_error(e, r));
1264                         goto rollback;
1265                 }
1266
1267                 /* Seventh step: an entry got dropped, let's garbage
1268                  * collect its dependencies. */
1269                 transaction_collect_garbage(m);
1270
1271                 /* Let's see if the resulting transaction still has
1272                  * unmergeable entries ... */
1273         }
1274
1275         /* Eights step: Drop redundant jobs again, if the merging now allows us to drop more. */
1276         transaction_drop_redundant(m);
1277
1278         /* Ninth step: check whether we can actually apply this */
1279         if (mode == JOB_FAIL)
1280                 if ((r = transaction_is_destructive(m, e)) < 0) {
1281                         log_notice("Requested transaction contradicts existing jobs: %s", bus_error(e, r));
1282                         goto rollback;
1283                 }
1284
1285         /* Tenth step: apply changes */
1286         if ((r = transaction_apply(m)) < 0) {
1287                 log_warning("Failed to apply transaction: %s", strerror(-r));
1288                 goto rollback;
1289         }
1290
1291         assert(hashmap_isempty(m->transaction_jobs));
1292         assert(!m->transaction_anchor);
1293
1294         return 0;
1295
1296 rollback:
1297         transaction_abort(m);
1298         return r;
1299 }
1300
1301 static Job* transaction_add_one_job(Manager *m, JobType type, Unit *unit, bool override, bool *is_new) {
1302         Job *j, *f;
1303
1304         assert(m);
1305         assert(unit);
1306
1307         /* Looks for an axisting prospective job and returns that. If
1308          * it doesn't exist it is created and added to the prospective
1309          * jobs list. */
1310
1311         f = hashmap_get(m->transaction_jobs, unit);
1312
1313         LIST_FOREACH(transaction, j, f) {
1314                 assert(j->unit == unit);
1315
1316                 if (j->type == type) {
1317                         if (is_new)
1318                                 *is_new = false;
1319                         return j;
1320                 }
1321         }
1322
1323         if (unit->meta.job && unit->meta.job->type == type)
1324                 j = unit->meta.job;
1325         else if (!(j = job_new(m, type, unit)))
1326                 return NULL;
1327
1328         j->generation = 0;
1329         j->marker = NULL;
1330         j->matters_to_anchor = false;
1331         j->override = override;
1332
1333         LIST_PREPEND(Job, transaction, f, j);
1334
1335         if (hashmap_replace(m->transaction_jobs, unit, f) < 0) {
1336                 job_free(j);
1337                 return NULL;
1338         }
1339
1340         if (is_new)
1341                 *is_new = true;
1342
1343         log_debug("Added job %s/%s to transaction.", unit->meta.id, job_type_to_string(type));
1344
1345         return j;
1346 }
1347
1348 void manager_transaction_unlink_job(Manager *m, Job *j, bool delete_dependencies) {
1349         assert(m);
1350         assert(j);
1351
1352         if (j->transaction_prev)
1353                 j->transaction_prev->transaction_next = j->transaction_next;
1354         else if (j->transaction_next)
1355                 hashmap_replace(m->transaction_jobs, j->unit, j->transaction_next);
1356         else
1357                 hashmap_remove_value(m->transaction_jobs, j->unit, j);
1358
1359         if (j->transaction_next)
1360                 j->transaction_next->transaction_prev = j->transaction_prev;
1361
1362         j->transaction_prev = j->transaction_next = NULL;
1363
1364         while (j->subject_list)
1365                 job_dependency_free(j->subject_list);
1366
1367         while (j->object_list) {
1368                 Job *other = j->object_list->matters ? j->object_list->subject : NULL;
1369
1370                 job_dependency_free(j->object_list);
1371
1372                 if (other && delete_dependencies) {
1373                         log_debug("Deleting job %s/%s as dependency of job %s/%s",
1374                                   other->unit->meta.id, job_type_to_string(other->type),
1375                                   j->unit->meta.id, job_type_to_string(j->type));
1376                         transaction_delete_job(m, other, delete_dependencies);
1377                 }
1378         }
1379 }
1380
1381 static int transaction_add_job_and_dependencies(
1382                 Manager *m,
1383                 JobType type,
1384                 Unit *unit,
1385                 Job *by,
1386                 bool matters,
1387                 bool override,
1388                 bool conflicts,
1389                 DBusError *e,
1390                 Job **_ret) {
1391         Job *ret;
1392         Iterator i;
1393         Unit *dep;
1394         int r;
1395         bool is_new;
1396
1397         assert(m);
1398         assert(type < _JOB_TYPE_MAX);
1399         assert(unit);
1400
1401         if (unit->meta.load_state != UNIT_LOADED &&
1402             unit->meta.load_state != UNIT_ERROR &&
1403             unit->meta.load_state != UNIT_BANNED) {
1404                 dbus_set_error(e, BUS_ERROR_LOAD_FAILED, "Unit %s is not loaded properly.", unit->meta.id);
1405                 return -EINVAL;
1406         }
1407
1408         if (type != JOB_STOP && unit->meta.load_state == UNIT_ERROR) {
1409                 dbus_set_error(e, BUS_ERROR_LOAD_FAILED,
1410                                "Unit %s failed to load: %s. "
1411                                "You might find more information in the system logs.",
1412                                unit->meta.id,
1413                                strerror(-unit->meta.load_error));
1414                 return -EINVAL;
1415         }
1416
1417         if (type != JOB_STOP && unit->meta.load_state == UNIT_BANNED) {
1418                 dbus_set_error(e, BUS_ERROR_BANNED, "Unit %s is banned.", unit->meta.id);
1419                 return -EINVAL;
1420         }
1421
1422         if (!unit_job_is_applicable(unit, type)) {
1423                 dbus_set_error(e, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE, "Job type %s is not applicable for unit %s.", job_type_to_string(type), unit->meta.id);
1424                 return -EBADR;
1425         }
1426
1427         /* First add the job. */
1428         if (!(ret = transaction_add_one_job(m, type, unit, override, &is_new)))
1429                 return -ENOMEM;
1430
1431         /* Then, add a link to the job. */
1432         if (!job_dependency_new(by, ret, matters, conflicts))
1433                 return -ENOMEM;
1434
1435         if (is_new) {
1436                 /* Finally, recursively add in all dependencies. */
1437                 if (type == JOB_START || type == JOB_RELOAD_OR_START) {
1438                         SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES], i)
1439                                 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, true, override, false, e, NULL)) < 0 && r != -EBADR)
1440                                         goto fail;
1441
1442                         SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES_OVERRIDABLE], i)
1443                                 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, !override, override, false, e, NULL)) < 0 && r != -EBADR) {
1444                                         log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, bus_error(e, r));
1445
1446                                         if (e)
1447                                                 dbus_error_free(e);
1448                                 }
1449
1450                         SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_WANTS], i)
1451                                 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, false, false, false, e, NULL)) < 0) {
1452                                         log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, bus_error(e, r));
1453
1454                                         if (e)
1455                                                 dbus_error_free(e);
1456                                 }
1457
1458                         SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE], i)
1459                                 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, true, override, false, e, NULL)) < 0 && r != -EBADR)
1460                                         goto fail;
1461
1462                         SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE_OVERRIDABLE], i)
1463                                 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, !override, override, false, e, NULL)) < 0 && r != -EBADR) {
1464                                         log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, bus_error(e, r));
1465
1466                                         if (e)
1467                                                 dbus_error_free(e);
1468                                 }
1469
1470                         SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_CONFLICTS], i)
1471                                 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, dep, ret, true, override, true, e, NULL)) < 0 && r != -EBADR)
1472                                         goto fail;
1473
1474                         SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_CONFLICTED_BY], i)
1475                                 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, dep, ret, true, override, false, e, NULL)) < 0 && r != -EBADR)
1476                                         goto fail;
1477
1478                 } else if (type == JOB_STOP || type == JOB_RESTART || type == JOB_TRY_RESTART) {
1479
1480                         SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRED_BY], i)
1481                                 if ((r = transaction_add_job_and_dependencies(m, type, dep, ret, true, override, false, e, NULL)) < 0 && r != -EBADR)
1482                                         goto fail;
1483                 }
1484
1485                 /* JOB_VERIFY_STARTED, JOB_RELOAD require no dependency handling */
1486         }
1487
1488         if (_ret)
1489                 *_ret = ret;
1490
1491         return 0;
1492
1493 fail:
1494         return r;
1495 }
1496
1497 static int transaction_add_isolate_jobs(Manager *m) {
1498         Iterator i;
1499         Unit *u;
1500         char *k;
1501         int r;
1502
1503         assert(m);
1504
1505         HASHMAP_FOREACH_KEY(u, k, m->units, i) {
1506
1507                 /* ignore aliases */
1508                 if (u->meta.id != k)
1509                         continue;
1510
1511                 if (UNIT_VTABLE(u)->no_isolate)
1512                         continue;
1513
1514                 /* No need to stop inactive jobs */
1515                 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(u)))
1516                         continue;
1517
1518                 /* Is there already something listed for this? */
1519                 if (hashmap_get(m->transaction_jobs, u))
1520                         continue;
1521
1522                 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, u, NULL, true, false, false, NULL, NULL)) < 0)
1523                         log_warning("Cannot add isolate job for unit %s, ignoring: %s", u->meta.id, strerror(-r));
1524         }
1525
1526         return 0;
1527 }
1528
1529 int manager_add_job(Manager *m, JobType type, Unit *unit, JobMode mode, bool override, DBusError *e, Job **_ret) {
1530         int r;
1531         Job *ret;
1532
1533         assert(m);
1534         assert(type < _JOB_TYPE_MAX);
1535         assert(unit);
1536         assert(mode < _JOB_MODE_MAX);
1537
1538         if (mode == JOB_ISOLATE && type != JOB_START) {
1539                 dbus_set_error(e, BUS_ERROR_INVALID_JOB_MODE, "Isolate is only valid for start.");
1540                 return -EINVAL;
1541         }
1542
1543         if (mode == JOB_ISOLATE && !unit->meta.allow_isolate) {
1544                 dbus_set_error(e, BUS_ERROR_NO_ISOLATION, "Operation refused, unit may not be isolated.");
1545                 return -EPERM;
1546         }
1547
1548         log_debug("Trying to enqueue job %s/%s/%s", unit->meta.id, job_type_to_string(type), job_mode_to_string(mode));
1549
1550         if ((r = transaction_add_job_and_dependencies(m, type, unit, NULL, true, override, false, e, &ret)) < 0) {
1551                 transaction_abort(m);
1552                 return r;
1553         }
1554
1555         if (mode == JOB_ISOLATE)
1556                 if ((r = transaction_add_isolate_jobs(m)) < 0) {
1557                         transaction_abort(m);
1558                         return r;
1559                 }
1560
1561         if ((r = transaction_activate(m, mode, e)) < 0)
1562                 return r;
1563
1564         log_debug("Enqueued job %s/%s as %u", unit->meta.id, job_type_to_string(type), (unsigned) ret->id);
1565
1566         if (_ret)
1567                 *_ret = ret;
1568
1569         return 0;
1570 }
1571
1572 int manager_add_job_by_name(Manager *m, JobType type, const char *name, JobMode mode, bool override, DBusError *e, Job **_ret) {
1573         Unit *unit;
1574         int r;
1575
1576         assert(m);
1577         assert(type < _JOB_TYPE_MAX);
1578         assert(name);
1579         assert(mode < _JOB_MODE_MAX);
1580
1581         if ((r = manager_load_unit(m, name, NULL, NULL, &unit)) < 0)
1582                 return r;
1583
1584         return manager_add_job(m, type, unit, mode, override, e, _ret);
1585 }
1586
1587 Job *manager_get_job(Manager *m, uint32_t id) {
1588         assert(m);
1589
1590         return hashmap_get(m->jobs, UINT32_TO_PTR(id));
1591 }
1592
1593 Unit *manager_get_unit(Manager *m, const char *name) {
1594         assert(m);
1595         assert(name);
1596
1597         return hashmap_get(m->units, name);
1598 }
1599
1600 unsigned manager_dispatch_load_queue(Manager *m) {
1601         Meta *meta;
1602         unsigned n = 0;
1603
1604         assert(m);
1605
1606         /* Make sure we are not run recursively */
1607         if (m->dispatching_load_queue)
1608                 return 0;
1609
1610         m->dispatching_load_queue = true;
1611
1612         /* Dispatches the load queue. Takes a unit from the queue and
1613          * tries to load its data until the queue is empty */
1614
1615         while ((meta = m->load_queue)) {
1616                 assert(meta->in_load_queue);
1617
1618                 unit_load((Unit*) meta);
1619                 n++;
1620         }
1621
1622         m->dispatching_load_queue = false;
1623         return n;
1624 }
1625
1626 int manager_load_unit_prepare(Manager *m, const char *name, const char *path, DBusError *e, Unit **_ret) {
1627         Unit *ret;
1628         int r;
1629
1630         assert(m);
1631         assert(name || path);
1632
1633         /* This will prepare the unit for loading, but not actually
1634          * load anything from disk. */
1635
1636         if (path && !is_path(path)) {
1637                 dbus_set_error(e, BUS_ERROR_INVALID_PATH, "Path %s is not absolute.", path);
1638                 return -EINVAL;
1639         }
1640
1641         if (!name)
1642                 name = file_name_from_path(path);
1643
1644         if (!unit_name_is_valid(name)) {
1645                 dbus_set_error(e, BUS_ERROR_INVALID_NAME, "Unit name %s is not valid.", name);
1646                 return -EINVAL;
1647         }
1648
1649         if ((ret = manager_get_unit(m, name))) {
1650                 *_ret = ret;
1651                 return 1;
1652         }
1653
1654         if (!(ret = unit_new(m)))
1655                 return -ENOMEM;
1656
1657         if (path)
1658                 if (!(ret->meta.fragment_path = strdup(path))) {
1659                         unit_free(ret);
1660                         return -ENOMEM;
1661                 }
1662
1663         if ((r = unit_add_name(ret, name)) < 0) {
1664                 unit_free(ret);
1665                 return r;
1666         }
1667
1668         unit_add_to_load_queue(ret);
1669         unit_add_to_dbus_queue(ret);
1670         unit_add_to_gc_queue(ret);
1671
1672         if (_ret)
1673                 *_ret = ret;
1674
1675         return 0;
1676 }
1677
1678 int manager_load_unit(Manager *m, const char *name, const char *path, DBusError *e, Unit **_ret) {
1679         int r;
1680
1681         assert(m);
1682
1683         /* This will load the service information files, but not actually
1684          * start any services or anything. */
1685
1686         if ((r = manager_load_unit_prepare(m, name, path, e, _ret)) != 0)
1687                 return r;
1688
1689         manager_dispatch_load_queue(m);
1690
1691         if (_ret)
1692                 *_ret = unit_follow_merge(*_ret);
1693
1694         return 0;
1695 }
1696
1697 void manager_dump_jobs(Manager *s, FILE *f, const char *prefix) {
1698         Iterator i;
1699         Job *j;
1700
1701         assert(s);
1702         assert(f);
1703
1704         HASHMAP_FOREACH(j, s->jobs, i)
1705                 job_dump(j, f, prefix);
1706 }
1707
1708 void manager_dump_units(Manager *s, FILE *f, const char *prefix) {
1709         Iterator i;
1710         Unit *u;
1711         const char *t;
1712
1713         assert(s);
1714         assert(f);
1715
1716         HASHMAP_FOREACH_KEY(u, t, s->units, i)
1717                 if (u->meta.id == t)
1718                         unit_dump(u, f, prefix);
1719 }
1720
1721 void manager_clear_jobs(Manager *m) {
1722         Job *j;
1723
1724         assert(m);
1725
1726         transaction_abort(m);
1727
1728         while ((j = hashmap_first(m->jobs)))
1729                 job_free(j);
1730 }
1731
1732 unsigned manager_dispatch_run_queue(Manager *m) {
1733         Job *j;
1734         unsigned n = 0;
1735
1736         if (m->dispatching_run_queue)
1737                 return 0;
1738
1739         m->dispatching_run_queue = true;
1740
1741         while ((j = m->run_queue)) {
1742                 assert(j->installed);
1743                 assert(j->in_run_queue);
1744
1745                 job_run_and_invalidate(j);
1746                 n++;
1747         }
1748
1749         m->dispatching_run_queue = false;
1750         return n;
1751 }
1752
1753 unsigned manager_dispatch_dbus_queue(Manager *m) {
1754         Job *j;
1755         Meta *meta;
1756         unsigned n = 0;
1757
1758         assert(m);
1759
1760         if (m->dispatching_dbus_queue)
1761                 return 0;
1762
1763         m->dispatching_dbus_queue = true;
1764
1765         while ((meta = m->dbus_unit_queue)) {
1766                 assert(meta->in_dbus_queue);
1767
1768                 bus_unit_send_change_signal((Unit*) meta);
1769                 n++;
1770         }
1771
1772         while ((j = m->dbus_job_queue)) {
1773                 assert(j->in_dbus_queue);
1774
1775                 bus_job_send_change_signal(j);
1776                 n++;
1777         }
1778
1779         m->dispatching_dbus_queue = false;
1780         return n;
1781 }
1782
1783 static int manager_process_notify_fd(Manager *m) {
1784         ssize_t n;
1785
1786         assert(m);
1787
1788         for (;;) {
1789                 char buf[4096];
1790                 struct msghdr msghdr;
1791                 struct iovec iovec;
1792                 struct ucred *ucred;
1793                 union {
1794                         struct cmsghdr cmsghdr;
1795                         uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
1796                 } control;
1797                 Unit *u;
1798                 char **tags;
1799
1800                 zero(iovec);
1801                 iovec.iov_base = buf;
1802                 iovec.iov_len = sizeof(buf)-1;
1803
1804                 zero(control);
1805                 zero(msghdr);
1806                 msghdr.msg_iov = &iovec;
1807                 msghdr.msg_iovlen = 1;
1808                 msghdr.msg_control = &control;
1809                 msghdr.msg_controllen = sizeof(control);
1810
1811                 if ((n = recvmsg(m->notify_watch.fd, &msghdr, MSG_DONTWAIT)) <= 0) {
1812                         if (n >= 0)
1813                                 return -EIO;
1814
1815                         if (errno == EAGAIN || errno == EINTR)
1816                                 break;
1817
1818                         return -errno;
1819                 }
1820
1821                 if (msghdr.msg_controllen < CMSG_LEN(sizeof(struct ucred)) ||
1822                     control.cmsghdr.cmsg_level != SOL_SOCKET ||
1823                     control.cmsghdr.cmsg_type != SCM_CREDENTIALS ||
1824                     control.cmsghdr.cmsg_len != CMSG_LEN(sizeof(struct ucred))) {
1825                         log_warning("Received notify message without credentials. Ignoring.");
1826                         continue;
1827                 }
1828
1829                 ucred = (struct ucred*) CMSG_DATA(&control.cmsghdr);
1830
1831                 if (!(u = hashmap_get(m->watch_pids, LONG_TO_PTR(ucred->pid))))
1832                         if (!(u = cgroup_unit_by_pid(m, ucred->pid))) {
1833                                 log_warning("Cannot find unit for notify message of PID %lu.", (unsigned long) ucred->pid);
1834                                 continue;
1835                         }
1836
1837                 assert((size_t) n < sizeof(buf));
1838                 buf[n] = 0;
1839                 if (!(tags = strv_split(buf, "\n\r")))
1840                         return -ENOMEM;
1841
1842                 log_debug("Got notification message for unit %s", u->meta.id);
1843
1844                 if (UNIT_VTABLE(u)->notify_message)
1845                         UNIT_VTABLE(u)->notify_message(u, ucred->pid, tags);
1846
1847                 strv_free(tags);
1848         }
1849
1850         return 0;
1851 }
1852
1853 static int manager_dispatch_sigchld(Manager *m) {
1854         assert(m);
1855
1856         for (;;) {
1857                 siginfo_t si;
1858                 Unit *u;
1859                 int r;
1860
1861                 zero(si);
1862
1863                 /* First we call waitd() for a PID and do not reap the
1864                  * zombie. That way we can still access /proc/$PID for
1865                  * it while it is a zombie. */
1866                 if (waitid(P_ALL, 0, &si, WEXITED|WNOHANG|WNOWAIT) < 0) {
1867
1868                         if (errno == ECHILD)
1869                                 break;
1870
1871                         if (errno == EINTR)
1872                                 continue;
1873
1874                         return -errno;
1875                 }
1876
1877                 if (si.si_pid <= 0)
1878                         break;
1879
1880                 if (si.si_code == CLD_EXITED || si.si_code == CLD_KILLED || si.si_code == CLD_DUMPED) {
1881                         char *name = NULL;
1882
1883                         get_process_name(si.si_pid, &name);
1884                         log_debug("Got SIGCHLD for process %lu (%s)", (unsigned long) si.si_pid, strna(name));
1885                         free(name);
1886                 }
1887
1888                 /* Let's flush any message the dying child might still
1889                  * have queued for us. This ensures that the process
1890                  * still exists in /proc so that we can figure out
1891                  * which cgroup and hence unit it belongs to. */
1892                 if ((r = manager_process_notify_fd(m)) < 0)
1893                         return r;
1894
1895                 /* And now figure out the unit this belongs to */
1896                 if (!(u = hashmap_get(m->watch_pids, LONG_TO_PTR(si.si_pid))))
1897                         u = cgroup_unit_by_pid(m, si.si_pid);
1898
1899                 /* And now, we actually reap the zombie. */
1900                 if (waitid(P_PID, si.si_pid, &si, WEXITED) < 0) {
1901                         if (errno == EINTR)
1902                                 continue;
1903
1904                         return -errno;
1905                 }
1906
1907                 if (si.si_code != CLD_EXITED && si.si_code != CLD_KILLED && si.si_code != CLD_DUMPED)
1908                         continue;
1909
1910                 log_debug("Child %lu died (code=%s, status=%i/%s)",
1911                           (long unsigned) si.si_pid,
1912                           sigchld_code_to_string(si.si_code),
1913                           si.si_status,
1914                           strna(si.si_code == CLD_EXITED
1915                                 ? exit_status_to_string(si.si_status, EXIT_STATUS_FULL)
1916                                 : signal_to_string(si.si_status)));
1917
1918                 if (!u)
1919                         continue;
1920
1921                 log_debug("Child %lu belongs to %s", (long unsigned) si.si_pid, u->meta.id);
1922
1923                 hashmap_remove(m->watch_pids, LONG_TO_PTR(si.si_pid));
1924                 UNIT_VTABLE(u)->sigchld_event(u, si.si_pid, si.si_code, si.si_status);
1925         }
1926
1927         return 0;
1928 }
1929
1930 static int manager_start_target(Manager *m, const char *name, JobMode mode) {
1931         int r;
1932         DBusError error;
1933
1934         dbus_error_init(&error);
1935
1936         log_info("Activating special unit %s", name);
1937
1938         if ((r = manager_add_job_by_name(m, JOB_START, name, mode, true, &error, NULL)) < 0)
1939                 log_error("Failed to enqueue %s job: %s", name, bus_error(&error, r));
1940
1941         dbus_error_free(&error);
1942
1943         return r;
1944 }
1945
1946 static int manager_process_signal_fd(Manager *m) {
1947         ssize_t n;
1948         struct signalfd_siginfo sfsi;
1949         bool sigchld = false;
1950
1951         assert(m);
1952
1953         for (;;) {
1954                 if ((n = read(m->signal_watch.fd, &sfsi, sizeof(sfsi))) != sizeof(sfsi)) {
1955
1956                         if (n >= 0)
1957                                 return -EIO;
1958
1959                         if (errno == EINTR || errno == EAGAIN)
1960                                 break;
1961
1962                         return -errno;
1963                 }
1964
1965                 log_debug("Received SIG%s", strna(signal_to_string(sfsi.ssi_signo)));
1966
1967                 switch (sfsi.ssi_signo) {
1968
1969                 case SIGCHLD:
1970                         sigchld = true;
1971                         break;
1972
1973                 case SIGTERM:
1974                         if (m->running_as == MANAGER_SYSTEM) {
1975                                 /* This is for compatibility with the
1976                                  * original sysvinit */
1977                                 m->exit_code = MANAGER_REEXECUTE;
1978                                 break;
1979                         }
1980
1981                         /* Fall through */
1982
1983                 case SIGINT:
1984                         if (m->running_as == MANAGER_SYSTEM) {
1985                                 manager_start_target(m, SPECIAL_CTRL_ALT_DEL_TARGET, JOB_REPLACE);
1986                                 break;
1987                         }
1988
1989                         /* Run the exit target if there is one, if not, just exit. */
1990                         if (manager_start_target(m, SPECIAL_EXIT_SERVICE, JOB_REPLACE) < 0) {
1991                                 m->exit_code = MANAGER_EXIT;
1992                                 return 0;
1993                         }
1994
1995                         break;
1996
1997                 case SIGWINCH:
1998                         if (m->running_as == MANAGER_SYSTEM)
1999                                 manager_start_target(m, SPECIAL_KBREQUEST_TARGET, JOB_REPLACE);
2000
2001                         /* This is a nop on non-init */
2002                         break;
2003
2004                 case SIGPWR:
2005                         if (m->running_as == MANAGER_SYSTEM)
2006                                 manager_start_target(m, SPECIAL_SIGPWR_TARGET, JOB_REPLACE);
2007
2008                         /* This is a nop on non-init */
2009                         break;
2010
2011                 case SIGUSR1: {
2012                         Unit *u;
2013
2014                         u = manager_get_unit(m, SPECIAL_DBUS_SERVICE);
2015
2016                         if (!u || UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u))) {
2017                                 log_info("Trying to reconnect to bus...");
2018                                 bus_init(m);
2019                         }
2020
2021                         if (!u || !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u))) {
2022                                 log_info("Loading D-Bus service...");
2023                                 manager_start_target(m, SPECIAL_DBUS_SERVICE, JOB_REPLACE);
2024                         }
2025
2026                         break;
2027                 }
2028
2029                 case SIGUSR2: {
2030                         FILE *f;
2031                         char *dump = NULL;
2032                         size_t size;
2033
2034                         if (!(f = open_memstream(&dump, &size))) {
2035                                 log_warning("Failed to allocate memory stream.");
2036                                 break;
2037                         }
2038
2039                         manager_dump_units(m, f, "\t");
2040                         manager_dump_jobs(m, f, "\t");
2041
2042                         if (ferror(f)) {
2043                                 fclose(f);
2044                                 free(dump);
2045                                 log_warning("Failed to write status stream");
2046                                 break;
2047                         }
2048
2049                         fclose(f);
2050                         log_dump(LOG_INFO, dump);
2051                         free(dump);
2052
2053                         break;
2054                 }
2055
2056                 case SIGHUP:
2057                         m->exit_code = MANAGER_RELOAD;
2058                         break;
2059
2060                 default: {
2061                         static const char * const table[] = {
2062                                 [0] = SPECIAL_DEFAULT_TARGET,
2063                                 [1] = SPECIAL_RESCUE_TARGET,
2064                                 [2] = SPECIAL_EMERGENCY_TARGET,
2065                                 [3] = SPECIAL_HALT_TARGET,
2066                                 [4] = SPECIAL_POWEROFF_TARGET,
2067                                 [5] = SPECIAL_REBOOT_TARGET
2068                         };
2069
2070                         if ((int) sfsi.ssi_signo >= SIGRTMIN+0 &&
2071                             (int) sfsi.ssi_signo < SIGRTMIN+(int) ELEMENTSOF(table)) {
2072                                 manager_start_target(m, table[sfsi.ssi_signo - SIGRTMIN],
2073                                                      (sfsi.ssi_signo == 1 || sfsi.ssi_signo == 2) ? JOB_ISOLATE : JOB_REPLACE);
2074                                 break;
2075                         }
2076
2077                         log_warning("Got unhandled signal <%s>.", strna(signal_to_string(sfsi.ssi_signo)));
2078                 }
2079                 }
2080         }
2081
2082         if (sigchld)
2083                 return manager_dispatch_sigchld(m);
2084
2085         return 0;
2086 }
2087
2088 static int process_event(Manager *m, struct epoll_event *ev) {
2089         int r;
2090         Watch *w;
2091
2092         assert(m);
2093         assert(ev);
2094
2095         assert(w = ev->data.ptr);
2096
2097         switch (w->type) {
2098
2099         case WATCH_SIGNAL:
2100
2101                 /* An incoming signal? */
2102                 if (ev->events != EPOLLIN)
2103                         return -EINVAL;
2104
2105                 if ((r = manager_process_signal_fd(m)) < 0)
2106                         return r;
2107
2108                 break;
2109
2110         case WATCH_NOTIFY:
2111
2112                 /* An incoming daemon notification event? */
2113                 if (ev->events != EPOLLIN)
2114                         return -EINVAL;
2115
2116                 if ((r = manager_process_notify_fd(m)) < 0)
2117                         return r;
2118
2119                 break;
2120
2121         case WATCH_FD:
2122
2123                 /* Some fd event, to be dispatched to the units */
2124                 UNIT_VTABLE(w->data.unit)->fd_event(w->data.unit, w->fd, ev->events, w);
2125                 break;
2126
2127         case WATCH_UNIT_TIMER:
2128         case WATCH_JOB_TIMER: {
2129                 uint64_t v;
2130                 ssize_t k;
2131
2132                 /* Some timer event, to be dispatched to the units */
2133                 if ((k = read(w->fd, &v, sizeof(v))) != sizeof(v)) {
2134
2135                         if (k < 0 && (errno == EINTR || errno == EAGAIN))
2136                                 break;
2137
2138                         return k < 0 ? -errno : -EIO;
2139                 }
2140
2141                 if (w->type == WATCH_UNIT_TIMER)
2142                         UNIT_VTABLE(w->data.unit)->timer_event(w->data.unit, v, w);
2143                 else
2144                         job_timer_event(w->data.job, v, w);
2145                 break;
2146         }
2147
2148         case WATCH_MOUNT:
2149                 /* Some mount table change, intended for the mount subsystem */
2150                 mount_fd_event(m, ev->events);
2151                 break;
2152
2153         case WATCH_UDEV:
2154                 /* Some notification from udev, intended for the device subsystem */
2155                 device_fd_event(m, ev->events);
2156                 break;
2157
2158         case WATCH_DBUS_WATCH:
2159                 bus_watch_event(m, w, ev->events);
2160                 break;
2161
2162         case WATCH_DBUS_TIMEOUT:
2163                 bus_timeout_event(m, w, ev->events);
2164                 break;
2165
2166         default:
2167                 assert_not_reached("Unknown epoll event type.");
2168         }
2169
2170         return 0;
2171 }
2172
2173 int manager_loop(Manager *m) {
2174         int r;
2175
2176         RATELIMIT_DEFINE(rl, 1*USEC_PER_SEC, 1000);
2177
2178         assert(m);
2179         m->exit_code = MANAGER_RUNNING;
2180
2181         /* Release the path cache */
2182         set_free_free(m->unit_path_cache);
2183         m->unit_path_cache = NULL;
2184
2185         manager_check_finished(m);
2186
2187         /* There might still be some zombies hanging around from
2188          * before we were exec()'ed. Leat's reap them */
2189         if ((r = manager_dispatch_sigchld(m)) < 0)
2190                 return r;
2191
2192         while (m->exit_code == MANAGER_RUNNING) {
2193                 struct epoll_event event;
2194                 int n;
2195
2196                 if (!ratelimit_test(&rl)) {
2197                         /* Yay, something is going seriously wrong, pause a little */
2198                         log_warning("Looping too fast. Throttling execution a little.");
2199                         sleep(1);
2200                 }
2201
2202                 if (manager_dispatch_load_queue(m) > 0)
2203                         continue;
2204
2205                 if (manager_dispatch_run_queue(m) > 0)
2206                         continue;
2207
2208                 if (bus_dispatch(m) > 0)
2209                         continue;
2210
2211                 if (manager_dispatch_cleanup_queue(m) > 0)
2212                         continue;
2213
2214                 if (manager_dispatch_gc_queue(m) > 0)
2215                         continue;
2216
2217                 if (manager_dispatch_dbus_queue(m) > 0)
2218                         continue;
2219
2220                 if ((n = epoll_wait(m->epoll_fd, &event, 1, -1)) < 0) {
2221
2222                         if (errno == EINTR)
2223                                 continue;
2224
2225                         return -errno;
2226                 }
2227
2228                 assert(n == 1);
2229
2230                 if ((r = process_event(m, &event)) < 0)
2231                         return r;
2232         }
2233
2234         return m->exit_code;
2235 }
2236
2237 int manager_get_unit_from_dbus_path(Manager *m, const char *s, Unit **_u) {
2238         char *n;
2239         Unit *u;
2240
2241         assert(m);
2242         assert(s);
2243         assert(_u);
2244
2245         if (!startswith(s, "/org/freedesktop/systemd1/unit/"))
2246                 return -EINVAL;
2247
2248         if (!(n = bus_path_unescape(s+31)))
2249                 return -ENOMEM;
2250
2251         u = manager_get_unit(m, n);
2252         free(n);
2253
2254         if (!u)
2255                 return -ENOENT;
2256
2257         *_u = u;
2258
2259         return 0;
2260 }
2261
2262 int manager_get_job_from_dbus_path(Manager *m, const char *s, Job **_j) {
2263         Job *j;
2264         unsigned id;
2265         int r;
2266
2267         assert(m);
2268         assert(s);
2269         assert(_j);
2270
2271         if (!startswith(s, "/org/freedesktop/systemd1/job/"))
2272                 return -EINVAL;
2273
2274         if ((r = safe_atou(s + 30, &id)) < 0)
2275                 return r;
2276
2277         if (!(j = manager_get_job(m, id)))
2278                 return -ENOENT;
2279
2280         *_j = j;
2281
2282         return 0;
2283 }
2284
2285 void manager_send_unit_audit(Manager *m, Unit *u, int type, bool success) {
2286
2287 #ifdef HAVE_AUDIT
2288         char *p;
2289
2290         if (m->audit_fd < 0)
2291                 return;
2292
2293         /* Don't generate audit events if the service was already
2294          * started and we're just deserializing */
2295         if (m->n_deserializing > 0)
2296                 return;
2297
2298         if (!(p = unit_name_to_prefix_and_instance(u->meta.id))) {
2299                 log_error("Failed to allocate unit name for audit message: %s", strerror(ENOMEM));
2300                 return;
2301         }
2302
2303         if (audit_log_user_comm_message(m->audit_fd, type, "", p, NULL, NULL, NULL, success) < 0)
2304                 log_error("Failed to send audit message: %m");
2305
2306         free(p);
2307 #endif
2308
2309 }
2310
2311 void manager_send_unit_plymouth(Manager *m, Unit *u) {
2312         int fd = -1;
2313         union sockaddr_union sa;
2314         int n = 0;
2315         char *message = NULL;
2316         ssize_t r;
2317
2318         /* Don't generate plymouth events if the service was already
2319          * started and we're just deserializing */
2320         if (m->n_deserializing > 0)
2321                 return;
2322
2323         if (m->running_as != MANAGER_SYSTEM)
2324                 return;
2325
2326         if (u->meta.type != UNIT_SERVICE &&
2327             u->meta.type != UNIT_MOUNT &&
2328             u->meta.type != UNIT_SWAP)
2329                 return;
2330
2331         /* We set SOCK_NONBLOCK here so that we rather drop the
2332          * message then wait for plymouth */
2333         if ((fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0)) < 0) {
2334                 log_error("socket() failed: %m");
2335                 return;
2336         }
2337
2338         zero(sa);
2339         sa.sa.sa_family = AF_UNIX;
2340         strncpy(sa.un.sun_path+1, "/ply-boot-protocol", sizeof(sa.un.sun_path)-1);
2341         if (connect(fd, &sa.sa, sizeof(sa.un)) < 0) {
2342
2343                 if (errno != EPIPE &&
2344                     errno != EAGAIN &&
2345                     errno != ENOENT &&
2346                     errno != ECONNREFUSED &&
2347                     errno != ECONNRESET &&
2348                     errno != ECONNABORTED)
2349                         log_error("connect() failed: %m");
2350
2351                 goto finish;
2352         }
2353
2354         if (asprintf(&message, "U\002%c%s%n", (int) (strlen(u->meta.id) + 1), u->meta.id, &n) < 0) {
2355                 log_error("Out of memory");
2356                 goto finish;
2357         }
2358
2359         errno = 0;
2360         if ((r = write(fd, message, n + 1)) != n + 1) {
2361
2362                 if (errno != EPIPE &&
2363                     errno != EAGAIN &&
2364                     errno != ENOENT &&
2365                     errno != ECONNREFUSED &&
2366                     errno != ECONNRESET &&
2367                     errno != ECONNABORTED)
2368                         log_error("Failed to write Plymouth message: %m");
2369
2370                 goto finish;
2371         }
2372
2373 finish:
2374         if (fd >= 0)
2375                 close_nointr_nofail(fd);
2376
2377         free(message);
2378 }
2379
2380 void manager_dispatch_bus_name_owner_changed(
2381                 Manager *m,
2382                 const char *name,
2383                 const char* old_owner,
2384                 const char *new_owner) {
2385
2386         Unit *u;
2387
2388         assert(m);
2389         assert(name);
2390
2391         if (!(u = hashmap_get(m->watch_bus, name)))
2392                 return;
2393
2394         UNIT_VTABLE(u)->bus_name_owner_change(u, name, old_owner, new_owner);
2395 }
2396
2397 void manager_dispatch_bus_query_pid_done(
2398                 Manager *m,
2399                 const char *name,
2400                 pid_t pid) {
2401
2402         Unit *u;
2403
2404         assert(m);
2405         assert(name);
2406         assert(pid >= 1);
2407
2408         if (!(u = hashmap_get(m->watch_bus, name)))
2409                 return;
2410
2411         UNIT_VTABLE(u)->bus_query_pid_done(u, name, pid);
2412 }
2413
2414 int manager_open_serialization(Manager *m, FILE **_f) {
2415         char *path;
2416         mode_t saved_umask;
2417         int fd;
2418         FILE *f;
2419
2420         assert(_f);
2421
2422         if (m->running_as == MANAGER_SYSTEM) {
2423                 mkdir_p("/dev/.systemd", 0755);
2424
2425                 if (asprintf(&path, "/dev/.systemd/dump-%lu-XXXXXX", (unsigned long) getpid()) < 0)
2426                         return -ENOMEM;
2427         } else {
2428                 if (asprintf(&path, "/tmp/systemd-dump-%lu-XXXXXX", (unsigned long) getpid()) < 0)
2429                         return -ENOMEM;
2430         }
2431
2432         saved_umask = umask(0077);
2433         fd = mkostemp(path, O_RDWR|O_CLOEXEC);
2434         umask(saved_umask);
2435
2436         if (fd < 0) {
2437                 free(path);
2438                 return -errno;
2439         }
2440
2441         unlink(path);
2442
2443         log_debug("Serializing state to %s", path);
2444         free(path);
2445
2446         if (!(f = fdopen(fd, "w+")) < 0)
2447                 return -errno;
2448
2449         *_f = f;
2450
2451         return 0;
2452 }
2453
2454 int manager_serialize(Manager *m, FILE *f, FDSet *fds) {
2455         Iterator i;
2456         Unit *u;
2457         const char *t;
2458         int r;
2459
2460         assert(m);
2461         assert(f);
2462         assert(fds);
2463
2464         fprintf(f, "startup-timestamp=%llu %llu\n\n",
2465                 (unsigned long long) m->startup_timestamp.realtime,
2466                 (unsigned long long) m->startup_timestamp.monotonic);
2467
2468         HASHMAP_FOREACH_KEY(u, t, m->units, i) {
2469                 if (u->meta.id != t)
2470                         continue;
2471
2472                 if (!unit_can_serialize(u))
2473                         continue;
2474
2475                 /* Start marker */
2476                 fputs(u->meta.id, f);
2477                 fputc('\n', f);
2478
2479                 if ((r = unit_serialize(u, f, fds)) < 0)
2480                         return r;
2481         }
2482
2483         if (ferror(f))
2484                 return -EIO;
2485
2486         return 0;
2487 }
2488
2489 int manager_deserialize(Manager *m, FILE *f, FDSet *fds) {
2490         int r = 0;
2491
2492         assert(m);
2493         assert(f);
2494
2495         log_debug("Deserializing state...");
2496
2497         m->n_deserializing ++;
2498
2499         for (;;) {
2500                 char line[1024], *l;
2501
2502                 if (!fgets(line, sizeof(line), f)) {
2503                         if (feof(f))
2504                                 r = 0;
2505                         else
2506                                 r = -errno;
2507
2508                         goto finish;
2509                 }
2510
2511                 char_array_0(line);
2512                 l = strstrip(line);
2513
2514                 if (l[0] == 0)
2515                         break;
2516
2517                 if (startswith(l, "startup-timestamp=")) {
2518                         unsigned long long a, b;
2519
2520                         if (sscanf(l+18, "%lli %llu", &a, &b) != 2)
2521                                 log_debug("Failed to parse startup timestamp value %s", l+18);
2522                         else {
2523                                 m->startup_timestamp.realtime = a;
2524                                 m->startup_timestamp.monotonic = b;
2525                         }
2526                 } else
2527                         log_debug("Unknown serialization item '%s'", l);
2528         }
2529
2530         for (;;) {
2531                 Unit *u;
2532                 char name[UNIT_NAME_MAX+2];
2533
2534                 /* Start marker */
2535                 if (!fgets(name, sizeof(name), f)) {
2536                         if (feof(f))
2537                                 r = 0;
2538                         else
2539                                 r = -errno;
2540
2541                         goto finish;
2542                 }
2543
2544                 char_array_0(name);
2545
2546                 if ((r = manager_load_unit(m, strstrip(name), NULL, NULL, &u)) < 0)
2547                         goto finish;
2548
2549                 if ((r = unit_deserialize(u, f, fds)) < 0)
2550                         goto finish;
2551         }
2552
2553 finish:
2554         if (ferror(f)) {
2555                 r = -EIO;
2556                 goto finish;
2557         }
2558
2559         assert(m->n_deserializing > 0);
2560         m->n_deserializing --;
2561
2562         return r;
2563 }
2564
2565 int manager_reload(Manager *m) {
2566         int r, q;
2567         FILE *f;
2568         FDSet *fds;
2569
2570         assert(m);
2571
2572         if ((r = manager_open_serialization(m, &f)) < 0)
2573                 return r;
2574
2575         if (!(fds = fdset_new())) {
2576                 r = -ENOMEM;
2577                 goto finish;
2578         }
2579
2580         if ((r = manager_serialize(m, f, fds)) < 0)
2581                 goto finish;
2582
2583         if (fseeko(f, 0, SEEK_SET) < 0) {
2584                 r = -errno;
2585                 goto finish;
2586         }
2587
2588         /* From here on there is no way back. */
2589         manager_clear_jobs_and_units(m);
2590
2591         /* Find new unit paths */
2592         lookup_paths_free(&m->lookup_paths);
2593         if ((q = lookup_paths_init(&m->lookup_paths, m->running_as)) < 0)
2594                 r = q;
2595
2596         m->n_deserializing ++;
2597
2598         /* First, enumerate what we can from all config files */
2599         if ((q = manager_enumerate(m)) < 0)
2600                 r = q;
2601
2602         /* Second, deserialize our stored data */
2603         if ((q = manager_deserialize(m, f, fds)) < 0)
2604                 r = q;
2605
2606         fclose(f);
2607         f = NULL;
2608
2609         /* Third, fire things up! */
2610         if ((q = manager_coldplug(m)) < 0)
2611                 r = q;
2612
2613         assert(m->n_deserializing > 0);
2614         m->n_deserializing ++;
2615
2616 finish:
2617         if (f)
2618                 fclose(f);
2619
2620         if (fds)
2621                 fdset_free(fds);
2622
2623         return r;
2624 }
2625
2626 bool manager_is_booting_or_shutting_down(Manager *m) {
2627         Unit *u;
2628
2629         assert(m);
2630
2631         /* Is the initial job still around? */
2632         if (manager_get_job(m, 1))
2633                 return true;
2634
2635         /* Is there a job for the shutdown target? */
2636         if (((u = manager_get_unit(m, SPECIAL_SHUTDOWN_TARGET))))
2637                 return !!u->meta.job;
2638
2639         return false;
2640 }
2641
2642 void manager_reset_failed(Manager *m) {
2643         Unit *u;
2644         Iterator i;
2645
2646         assert(m);
2647
2648         HASHMAP_FOREACH(u, m->units, i)
2649                 unit_reset_failed(u);
2650 }
2651
2652 int manager_set_console(Manager *m, const char *console) {
2653         char *c;
2654
2655         assert(m);
2656
2657         if (!(c = strdup(console)))
2658                 return -ENOMEM;
2659
2660         free(m->console);
2661         m->console = c;
2662
2663         log_debug("Using kernel console %s", c);
2664
2665         return 0;
2666 }
2667
2668 bool manager_unit_pending_inactive(Manager *m, const char *name) {
2669         Unit *u;
2670
2671         assert(m);
2672         assert(name);
2673
2674         /* Returns true if the unit is inactive or going down */
2675         if (!(u = manager_get_unit(m, name)))
2676                 return true;
2677
2678         return unit_pending_inactive(u);
2679 }
2680
2681 void manager_check_finished(Manager *m) {
2682         char userspace[FORMAT_TIMESPAN_MAX], kernel[FORMAT_TIMESPAN_MAX], sum[FORMAT_TIMESPAN_MAX];
2683
2684         assert(m);
2685
2686         if (dual_timestamp_is_set(&m->finish_timestamp))
2687                 return;
2688
2689         if (hashmap_size(m->jobs) > 0)
2690                 return;
2691
2692         dual_timestamp_get(&m->finish_timestamp);
2693
2694         if (m->running_as == MANAGER_SYSTEM)
2695                 log_info("Startup finished in %s (kernel) + %s (userspace) = %s.",
2696                          format_timespan(kernel, sizeof(kernel),
2697                                          m->startup_timestamp.monotonic),
2698                          format_timespan(userspace, sizeof(userspace),
2699                                          m->finish_timestamp.monotonic - m->startup_timestamp.monotonic),
2700                          format_timespan(sum, sizeof(sum),
2701                                          m->finish_timestamp.monotonic));
2702         else
2703                 log_debug("Startup finished in %s.",
2704                           format_timespan(userspace, sizeof(userspace),
2705                                           m->finish_timestamp.monotonic - m->startup_timestamp.monotonic));
2706
2707 }
2708
2709 static const char* const manager_running_as_table[_MANAGER_RUNNING_AS_MAX] = {
2710         [MANAGER_SYSTEM] = "system",
2711         [MANAGER_SESSION] = "session"
2712 };
2713
2714 DEFINE_STRING_TABLE_LOOKUP(manager_running_as, ManagerRunningAs);