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