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