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