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