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