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