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