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