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