chiark / gitweb /
Merge branch 'master' of ssh://git.freedesktop.org/git/systemd
[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
553 void manager_free(Manager *m) {
554         UnitType c;
555
556         assert(m);
557
558         manager_dispatch_cleanup_queue(m);
559         manager_clear_jobs_and_units(m);
560
561         for (c = 0; c < _UNIT_TYPE_MAX; c++)
562                 if (unit_vtable[c]->shutdown)
563                         unit_vtable[c]->shutdown(m);
564
565         /* If we reexecute ourselves, we keep the root cgroup
566          * around */
567         manager_shutdown_cgroup(m, m->exit_code != MANAGER_REEXECUTE);
568
569         bus_done_api(m);
570         bus_done_system(m);
571
572         hashmap_free(m->units);
573         hashmap_free(m->jobs);
574         hashmap_free(m->transaction_jobs);
575         hashmap_free(m->watch_pids);
576         hashmap_free(m->watch_bus);
577
578         if (m->epoll_fd >= 0)
579                 close_nointr_nofail(m->epoll_fd);
580         if (m->signal_watch.fd >= 0)
581                 close_nointr_nofail(m->signal_watch.fd);
582
583         strv_free(m->unit_path);
584         strv_free(m->sysvinit_path);
585         strv_free(m->sysvrcnd_path);
586         strv_free(m->environment);
587
588         free(m->cgroup_controller);
589         free(m->cgroup_hierarchy);
590
591         hashmap_free(m->cgroup_bondings);
592
593         free(m);
594 }
595
596 int manager_enumerate(Manager *m) {
597         int r = 0, q;
598         UnitType c;
599
600         assert(m);
601
602         /* Let's ask every type to load all units from disk/kernel
603          * that it might know */
604         for (c = 0; c < _UNIT_TYPE_MAX; c++)
605                 if (unit_vtable[c]->enumerate)
606                         if ((q = unit_vtable[c]->enumerate(m)) < 0)
607                                 r = q;
608
609         manager_dispatch_load_queue(m);
610         return r;
611 }
612
613 int manager_coldplug(Manager *m) {
614         int r = 0, q;
615         Iterator i;
616         Unit *u;
617         char *k;
618
619         assert(m);
620
621         /* Then, let's set up their initial state. */
622         HASHMAP_FOREACH_KEY(u, k, m->units, i) {
623
624                 /* ignore aliases */
625                 if (u->meta.id != k)
626                         continue;
627
628                 if ((q = unit_coldplug(u)) < 0)
629                         r = q;
630         }
631
632         return r;
633 }
634
635 int manager_startup(Manager *m, FILE *serialization, FDSet *fds) {
636         int r, q;
637
638         assert(m);
639
640         /* First, enumerate what we can from all config files */
641         r = manager_enumerate(m);
642
643         /* Second, deserialize if there is something to deserialize */
644         if (serialization)
645                 if ((q = manager_deserialize(m, serialization, fds)) < 0)
646                         r = q;
647
648         /* Third, fire things up! */
649         if ((q = manager_coldplug(m)) < 0)
650                 r = q;
651
652         /* Now that the initial devices are available, let's see if we
653          * can write the utmp file */
654         manager_write_utmp_reboot(m);
655
656         return r;
657 }
658
659 static void transaction_delete_job(Manager *m, Job *j, bool delete_dependencies) {
660         assert(m);
661         assert(j);
662
663         /* Deletes one job from the transaction */
664
665         manager_transaction_unlink_job(m, j, delete_dependencies);
666
667         if (!j->installed)
668                 job_free(j);
669 }
670
671 static void transaction_delete_unit(Manager *m, Unit *u) {
672         Job *j;
673
674         /* Deletes all jobs associated with a certain unit from the
675          * transaction */
676
677         while ((j = hashmap_get(m->transaction_jobs, u)))
678                 transaction_delete_job(m, j, true);
679 }
680
681 static void transaction_clean_dependencies(Manager *m) {
682         Iterator i;
683         Job *j;
684
685         assert(m);
686
687         /* Drops all dependencies of all installed jobs */
688
689         HASHMAP_FOREACH(j, m->jobs, i) {
690                 while (j->subject_list)
691                         job_dependency_free(j->subject_list);
692                 while (j->object_list)
693                         job_dependency_free(j->object_list);
694         }
695
696         assert(!m->transaction_anchor);
697 }
698
699 static void transaction_abort(Manager *m) {
700         Job *j;
701
702         assert(m);
703
704         while ((j = hashmap_first(m->transaction_jobs)))
705                 if (j->installed)
706                         transaction_delete_job(m, j, true);
707                 else
708                         job_free(j);
709
710         assert(hashmap_isempty(m->transaction_jobs));
711
712         transaction_clean_dependencies(m);
713 }
714
715 static void transaction_find_jobs_that_matter_to_anchor(Manager *m, Job *j, unsigned generation) {
716         JobDependency *l;
717
718         assert(m);
719
720         /* A recursive sweep through the graph that marks all units
721          * that matter to the anchor job, i.e. are directly or
722          * indirectly a dependency of the anchor job via paths that
723          * are fully marked as mattering. */
724
725         if (j)
726                 l = j->subject_list;
727         else
728                 l = m->transaction_anchor;
729
730         LIST_FOREACH(subject, l, l) {
731
732                 /* This link does not matter */
733                 if (!l->matters)
734                         continue;
735
736                 /* This unit has already been marked */
737                 if (l->object->generation == generation)
738                         continue;
739
740                 l->object->matters_to_anchor = true;
741                 l->object->generation = generation;
742
743                 transaction_find_jobs_that_matter_to_anchor(m, l->object, generation);
744         }
745 }
746
747 static void transaction_merge_and_delete_job(Manager *m, Job *j, Job *other, JobType t) {
748         JobDependency *l, *last;
749
750         assert(j);
751         assert(other);
752         assert(j->unit == other->unit);
753         assert(!j->installed);
754
755         /* Merges 'other' into 'j' and then deletes j. */
756
757         j->type = t;
758         j->state = JOB_WAITING;
759         j->override = j->override || other->override;
760
761         j->matters_to_anchor = j->matters_to_anchor || other->matters_to_anchor;
762
763         /* Patch us in as new owner of the JobDependency objects */
764         last = NULL;
765         LIST_FOREACH(subject, l, other->subject_list) {
766                 assert(l->subject == other);
767                 l->subject = j;
768                 last = l;
769         }
770
771         /* Merge both lists */
772         if (last) {
773                 last->subject_next = j->subject_list;
774                 if (j->subject_list)
775                         j->subject_list->subject_prev = last;
776                 j->subject_list = other->subject_list;
777         }
778
779         /* Patch us in as new owner of the JobDependency objects */
780         last = NULL;
781         LIST_FOREACH(object, l, other->object_list) {
782                 assert(l->object == other);
783                 l->object = j;
784                 last = l;
785         }
786
787         /* Merge both lists */
788         if (last) {
789                 last->object_next = j->object_list;
790                 if (j->object_list)
791                         j->object_list->object_prev = last;
792                 j->object_list = other->object_list;
793         }
794
795         /* Kill the other job */
796         other->subject_list = NULL;
797         other->object_list = NULL;
798         transaction_delete_job(m, other, true);
799 }
800
801 static int delete_one_unmergeable_job(Manager *m, Job *j) {
802         Job *k;
803
804         assert(j);
805
806         /* Tries to delete one item in the linked list
807          * j->transaction_next->transaction_next->... that conflicts
808          * whith another one, in an attempt to make an inconsistent
809          * transaction work. */
810
811         /* We rely here on the fact that if a merged with b does not
812          * merge with c, either a or b merge with c neither */
813         LIST_FOREACH(transaction, j, j)
814                 LIST_FOREACH(transaction, k, j->transaction_next) {
815                         Job *d;
816
817                         /* Is this one mergeable? Then skip it */
818                         if (job_type_is_mergeable(j->type, k->type))
819                                 continue;
820
821                         /* Ok, we found two that conflict, let's see if we can
822                          * drop one of them */
823                         if (!j->matters_to_anchor)
824                                 d = j;
825                         else if (!k->matters_to_anchor)
826                                 d = k;
827                         else
828                                 return -ENOEXEC;
829
830                         /* Ok, we can drop one, so let's do so. */
831                         log_debug("Trying to fix job merging by deleting job %s/%s", d->unit->meta.id, job_type_to_string(d->type));
832                         transaction_delete_job(m, d, true);
833                         return 0;
834                 }
835
836         return -EINVAL;
837 }
838
839 static int transaction_merge_jobs(Manager *m) {
840         Job *j;
841         Iterator i;
842         int r;
843
844         assert(m);
845
846         /* First step, check whether any of the jobs for one specific
847          * task conflict. If so, try to drop one of them. */
848         HASHMAP_FOREACH(j, m->transaction_jobs, i) {
849                 JobType t;
850                 Job *k;
851
852                 t = j->type;
853                 LIST_FOREACH(transaction, k, j->transaction_next) {
854                         if ((r = job_type_merge(&t, k->type)) >= 0)
855                                 continue;
856
857                         /* OK, we could not merge all jobs for this
858                          * action. Let's see if we can get rid of one
859                          * of them */
860
861                         if ((r = delete_one_unmergeable_job(m, j)) >= 0)
862                                 /* Ok, we managed to drop one, now
863                                  * let's ask our callers to call us
864                                  * again after garbage collecting */
865                                 return -EAGAIN;
866
867                         /* We couldn't merge anything. Failure */
868                         return r;
869                 }
870         }
871
872         /* Second step, merge the jobs. */
873         HASHMAP_FOREACH(j, m->transaction_jobs, i) {
874                 JobType t = j->type;
875                 Job *k;
876
877                 /* Merge all transactions */
878                 LIST_FOREACH(transaction, k, j->transaction_next)
879                         assert_se(job_type_merge(&t, k->type) == 0);
880
881                 /* If an active job is mergeable, merge it too */
882                 if (j->unit->meta.job)
883                         job_type_merge(&t, j->unit->meta.job->type); /* Might fail. Which is OK */
884
885                 while ((k = j->transaction_next)) {
886                         if (j->installed) {
887                                 transaction_merge_and_delete_job(m, k, j, t);
888                                 j = k;
889                         } else
890                                 transaction_merge_and_delete_job(m, j, k, t);
891                 }
892
893                 assert(!j->transaction_next);
894                 assert(!j->transaction_prev);
895         }
896
897         return 0;
898 }
899
900 static void transaction_drop_redundant(Manager *m) {
901         bool again;
902
903         assert(m);
904
905         /* Goes through the transaction and removes all jobs that are
906          * a noop */
907
908         do {
909                 Job *j;
910                 Iterator i;
911
912                 again = false;
913
914                 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
915                         bool changes_something = false;
916                         Job *k;
917
918                         LIST_FOREACH(transaction, k, j) {
919
920                                 if (!job_is_anchor(k) &&
921                                     job_type_is_redundant(k->type, unit_active_state(k->unit)))
922                                         continue;
923
924                                 changes_something = true;
925                                 break;
926                         }
927
928                         if (changes_something)
929                                 continue;
930
931                         log_debug("Found redundant job %s/%s, dropping.", j->unit->meta.id, job_type_to_string(j->type));
932                         transaction_delete_job(m, j, false);
933                         again = true;
934                         break;
935                 }
936
937         } while (again);
938 }
939
940 static bool unit_matters_to_anchor(Unit *u, Job *j) {
941         assert(u);
942         assert(!j->transaction_prev);
943
944         /* Checks whether at least one of the jobs for this unit
945          * matters to the anchor. */
946
947         LIST_FOREACH(transaction, j, j)
948                 if (j->matters_to_anchor)
949                         return true;
950
951         return false;
952 }
953
954 static int transaction_verify_order_one(Manager *m, Job *j, Job *from, unsigned generation) {
955         Iterator i;
956         Unit *u;
957         int r;
958
959         assert(m);
960         assert(j);
961         assert(!j->transaction_prev);
962
963         /* Does a recursive sweep through the ordering graph, looking
964          * for a cycle. If we find cycle we try to break it. */
965
966         /* Have we seen this before? */
967         if (j->generation == generation) {
968                 Job *k;
969
970                 /* If the marker is NULL we have been here already and
971                  * decided the job was loop-free from here. Hence
972                  * shortcut things and return right-away. */
973                 if (!j->marker)
974                         return 0;
975
976                 /* So, the marker is not NULL and we already have been
977                  * here. We have a cycle. Let's try to break it. We go
978                  * backwards in our path and try to find a suitable
979                  * job to remove. We use the marker to find our way
980                  * back, since smart how we are we stored our way back
981                  * in there. */
982                 log_debug("Found ordering cycle on %s/%s", j->unit->meta.id, job_type_to_string(j->type));
983
984                 for (k = from; k; k = ((k->generation == generation && k->marker != k) ? k->marker : NULL)) {
985
986                         log_debug("Walked on cycle path to %s/%s", k->unit->meta.id, job_type_to_string(k->type));
987
988                         if (!k->installed &&
989                             !unit_matters_to_anchor(k->unit, k)) {
990                                 /* Ok, we can drop this one, so let's
991                                  * do so. */
992                                 log_debug("Breaking order cycle by deleting job %s/%s", k->unit->meta.id, job_type_to_string(k->type));
993                                 transaction_delete_unit(m, k->unit);
994                                 return -EAGAIN;
995                         }
996
997                         /* Check if this in fact was the beginning of
998                          * the cycle */
999                         if (k == j)
1000                                 break;
1001                 }
1002
1003                 log_debug("Unable to break cycle");
1004
1005                 return -ENOEXEC;
1006         }
1007
1008         /* Make the marker point to where we come from, so that we can
1009          * find our way backwards if we want to break a cycle. We use
1010          * a special marker for the beginning: we point to
1011          * ourselves. */
1012         j->marker = from ? from : j;
1013         j->generation = generation;
1014
1015         /* We assume that the the dependencies are bidirectional, and
1016          * hence can ignore UNIT_AFTER */
1017         SET_FOREACH(u, j->unit->meta.dependencies[UNIT_BEFORE], i) {
1018                 Job *o;
1019
1020                 /* Is there a job for this unit? */
1021                 if (!(o = hashmap_get(m->transaction_jobs, u)))
1022
1023                         /* Ok, there is no job for this in the
1024                          * transaction, but maybe there is already one
1025                          * running? */
1026                         if (!(o = u->meta.job))
1027                                 continue;
1028
1029                 if ((r = transaction_verify_order_one(m, o, j, generation)) < 0)
1030                         return r;
1031         }
1032
1033         /* Ok, let's backtrack, and remember that this entry is not on
1034          * our path anymore. */
1035         j->marker = NULL;
1036
1037         return 0;
1038 }
1039
1040 static int transaction_verify_order(Manager *m, unsigned *generation) {
1041         Job *j;
1042         int r;
1043         Iterator i;
1044         unsigned g;
1045
1046         assert(m);
1047         assert(generation);
1048
1049         /* Check if the ordering graph is cyclic. If it is, try to fix
1050          * that up by dropping one of the jobs. */
1051
1052         g = (*generation)++;
1053
1054         HASHMAP_FOREACH(j, m->transaction_jobs, i)
1055                 if ((r = transaction_verify_order_one(m, j, NULL, g)) < 0)
1056                         return r;
1057
1058         return 0;
1059 }
1060
1061 static void transaction_collect_garbage(Manager *m) {
1062         bool again;
1063
1064         assert(m);
1065
1066         /* Drop jobs that are not required by any other job */
1067
1068         do {
1069                 Iterator i;
1070                 Job *j;
1071
1072                 again = false;
1073
1074                 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1075                         if (j->object_list)
1076                                 continue;
1077
1078                         log_debug("Garbage collecting job %s/%s", j->unit->meta.id, job_type_to_string(j->type));
1079                         transaction_delete_job(m, j, true);
1080                         again = true;
1081                         break;
1082                 }
1083
1084         } while (again);
1085 }
1086
1087 static int transaction_is_destructive(Manager *m) {
1088         Iterator i;
1089         Job *j;
1090
1091         assert(m);
1092
1093         /* Checks whether applying this transaction means that
1094          * existing jobs would be replaced */
1095
1096         HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1097
1098                 /* Assume merged */
1099                 assert(!j->transaction_prev);
1100                 assert(!j->transaction_next);
1101
1102                 if (j->unit->meta.job &&
1103                     j->unit->meta.job != j &&
1104                     !job_type_is_superset(j->type, j->unit->meta.job->type))
1105                         return -EEXIST;
1106         }
1107
1108         return 0;
1109 }
1110
1111 static void transaction_minimize_impact(Manager *m) {
1112         bool again;
1113         assert(m);
1114
1115         /* Drops all unnecessary jobs that reverse already active jobs
1116          * or that stop a running service. */
1117
1118         do {
1119                 Job *j;
1120                 Iterator i;
1121
1122                 again = false;
1123
1124                 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1125                         LIST_FOREACH(transaction, j, j) {
1126                                 bool stops_running_service, changes_existing_job;
1127
1128                                 /* If it matters, we shouldn't drop it */
1129                                 if (j->matters_to_anchor)
1130                                         continue;
1131
1132                                 /* Would this stop a running service?
1133                                  * Would this change an existing job?
1134                                  * If so, let's drop this entry */
1135
1136                                 stops_running_service =
1137                                         j->type == JOB_STOP && UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(j->unit));
1138
1139                                 changes_existing_job =
1140                                         j->unit->meta.job && job_type_is_conflicting(j->type, j->unit->meta.job->state);
1141
1142                                 if (!stops_running_service && !changes_existing_job)
1143                                         continue;
1144
1145                                 if (stops_running_service)
1146                                         log_debug("%s/%s would stop a running service.", j->unit->meta.id, job_type_to_string(j->type));
1147
1148                                 if (changes_existing_job)
1149                                         log_debug("%s/%s would change existing job.", j->unit->meta.id, job_type_to_string(j->type));
1150
1151                                 /* Ok, let's get rid of this */
1152                                 log_debug("Deleting %s/%s to minimize impact.", j->unit->meta.id, job_type_to_string(j->type));
1153
1154                                 transaction_delete_job(m, j, true);
1155                                 again = true;
1156                                 break;
1157                         }
1158
1159                         if (again)
1160                                 break;
1161                 }
1162
1163         } while (again);
1164 }
1165
1166 static int transaction_apply(Manager *m) {
1167         Iterator i;
1168         Job *j;
1169         int r;
1170
1171         /* Moves the transaction jobs to the set of active jobs */
1172
1173         HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1174                 /* Assume merged */
1175                 assert(!j->transaction_prev);
1176                 assert(!j->transaction_next);
1177
1178                 if (j->installed)
1179                         continue;
1180
1181                 if ((r = hashmap_put(m->jobs, UINT32_TO_PTR(j->id), j)) < 0)
1182                         goto rollback;
1183         }
1184
1185         while ((j = hashmap_steal_first(m->transaction_jobs))) {
1186                 if (j->installed)
1187                         continue;
1188
1189                 if (j->unit->meta.job)
1190                         job_free(j->unit->meta.job);
1191
1192                 j->unit->meta.job = j;
1193                 j->installed = true;
1194
1195                 /* We're fully installed. Now let's free data we don't
1196                  * need anymore. */
1197
1198                 assert(!j->transaction_next);
1199                 assert(!j->transaction_prev);
1200
1201                 job_add_to_run_queue(j);
1202                 job_add_to_dbus_queue(j);
1203         }
1204
1205         /* As last step, kill all remaining job dependencies. */
1206         transaction_clean_dependencies(m);
1207
1208         return 0;
1209
1210 rollback:
1211
1212         HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1213                 if (j->installed)
1214                         continue;
1215
1216                 hashmap_remove(m->jobs, UINT32_TO_PTR(j->id));
1217         }
1218
1219         return r;
1220 }
1221
1222 static int transaction_activate(Manager *m, JobMode mode) {
1223         int r;
1224         unsigned generation = 1;
1225
1226         assert(m);
1227
1228         /* This applies the changes recorded in transaction_jobs to
1229          * the actual list of jobs, if possible. */
1230
1231         /* First step: figure out which jobs matter */
1232         transaction_find_jobs_that_matter_to_anchor(m, NULL, generation++);
1233
1234         /* Second step: Try not to stop any running services if
1235          * we don't have to. Don't try to reverse running
1236          * jobs if we don't have to. */
1237         transaction_minimize_impact(m);
1238
1239         /* Third step: Drop redundant jobs */
1240         transaction_drop_redundant(m);
1241
1242         for (;;) {
1243                 /* Fourth step: Let's remove unneeded jobs that might
1244                  * be lurking. */
1245                 transaction_collect_garbage(m);
1246
1247                 /* Fifth step: verify order makes sense and correct
1248                  * cycles if necessary and possible */
1249                 if ((r = transaction_verify_order(m, &generation)) >= 0)
1250                         break;
1251
1252                 if (r != -EAGAIN) {
1253                         log_debug("Requested transaction contains an unfixable cyclic ordering dependency: %s", strerror(-r));
1254                         goto rollback;
1255                 }
1256
1257                 /* Let's see if the resulting transaction ordering
1258                  * graph is still cyclic... */
1259         }
1260
1261         for (;;) {
1262                 /* Sixth step: let's drop unmergeable entries if
1263                  * necessary and possible, merge entries we can
1264                  * merge */
1265                 if ((r = transaction_merge_jobs(m)) >= 0)
1266                         break;
1267
1268                 if (r != -EAGAIN) {
1269                         log_debug("Requested transaction contains unmergable jobs: %s", strerror(-r));
1270                         goto rollback;
1271                 }
1272
1273                 /* Seventh step: an entry got dropped, let's garbage
1274                  * collect its dependencies. */
1275                 transaction_collect_garbage(m);
1276
1277                 /* Let's see if the resulting transaction still has
1278                  * unmergeable entries ... */
1279         }
1280
1281         /* Eights step: Drop redundant jobs again, if the merging now allows us to drop more. */
1282         transaction_drop_redundant(m);
1283
1284         /* Ninth step: check whether we can actually apply this */
1285         if (mode == JOB_FAIL)
1286                 if ((r = transaction_is_destructive(m)) < 0) {
1287                         log_debug("Requested transaction contradicts existing jobs: %s", strerror(-r));
1288                         goto rollback;
1289                 }
1290
1291         /* Tenth step: apply changes */
1292         if ((r = transaction_apply(m)) < 0) {
1293                 log_debug("Failed to apply transaction: %s", strerror(-r));
1294                 goto rollback;
1295         }
1296
1297         assert(hashmap_isempty(m->transaction_jobs));
1298         assert(!m->transaction_anchor);
1299
1300         return 0;
1301
1302 rollback:
1303         transaction_abort(m);
1304         return r;
1305 }
1306
1307 static Job* transaction_add_one_job(Manager *m, JobType type, Unit *unit, bool override, bool *is_new) {
1308         Job *j, *f;
1309         int r;
1310
1311         assert(m);
1312         assert(unit);
1313
1314         /* Looks for an axisting prospective job and returns that. If
1315          * it doesn't exist it is created and added to the prospective
1316          * jobs list. */
1317
1318         f = hashmap_get(m->transaction_jobs, unit);
1319
1320         LIST_FOREACH(transaction, j, f) {
1321                 assert(j->unit == unit);
1322
1323                 if (j->type == type) {
1324                         if (is_new)
1325                                 *is_new = false;
1326                         return j;
1327                 }
1328         }
1329
1330         if (unit->meta.job && unit->meta.job->type == type)
1331                 j = unit->meta.job;
1332         else if (!(j = job_new(m, type, unit)))
1333                 return NULL;
1334
1335         j->generation = 0;
1336         j->marker = NULL;
1337         j->matters_to_anchor = false;
1338         j->override = override;
1339
1340         LIST_PREPEND(Job, transaction, f, j);
1341
1342         if ((r = hashmap_replace(m->transaction_jobs, unit, f)) < 0) {
1343                 job_free(j);
1344                 return NULL;
1345         }
1346
1347         if (is_new)
1348                 *is_new = true;
1349
1350         log_debug("Added job %s/%s to transaction.", unit->meta.id, job_type_to_string(type));
1351
1352         return j;
1353 }
1354
1355 void manager_transaction_unlink_job(Manager *m, Job *j, bool delete_dependencies) {
1356         assert(m);
1357         assert(j);
1358
1359         if (j->transaction_prev)
1360                 j->transaction_prev->transaction_next = j->transaction_next;
1361         else if (j->transaction_next)
1362                 hashmap_replace(m->transaction_jobs, j->unit, j->transaction_next);
1363         else
1364                 hashmap_remove_value(m->transaction_jobs, j->unit, j);
1365
1366         if (j->transaction_next)
1367                 j->transaction_next->transaction_prev = j->transaction_prev;
1368
1369         j->transaction_prev = j->transaction_next = NULL;
1370
1371         while (j->subject_list)
1372                 job_dependency_free(j->subject_list);
1373
1374         while (j->object_list) {
1375                 Job *other = j->object_list->matters ? j->object_list->subject : NULL;
1376
1377                 job_dependency_free(j->object_list);
1378
1379                 if (other && delete_dependencies) {
1380                         log_debug("Deleting job %s/%s as dependency of job %s/%s",
1381                                   other->unit->meta.id, job_type_to_string(other->type),
1382                                   j->unit->meta.id, job_type_to_string(j->type));
1383                         transaction_delete_job(m, other, delete_dependencies);
1384                 }
1385         }
1386 }
1387
1388 static int transaction_add_job_and_dependencies(
1389                 Manager *m,
1390                 JobType type,
1391                 Unit *unit,
1392                 Job *by,
1393                 bool matters,
1394                 bool override,
1395                 Job **_ret) {
1396         Job *ret;
1397         Iterator i;
1398         Unit *dep;
1399         int r;
1400         bool is_new;
1401
1402         assert(m);
1403         assert(type < _JOB_TYPE_MAX);
1404         assert(unit);
1405
1406         if (unit->meta.load_state != UNIT_LOADED)
1407                 return -EINVAL;
1408
1409         if (!unit_job_is_applicable(unit, type))
1410                 return -EBADR;
1411
1412         /* First add the job. */
1413         if (!(ret = transaction_add_one_job(m, type, unit, override, &is_new)))
1414                 return -ENOMEM;
1415
1416         /* Then, add a link to the job. */
1417         if (!job_dependency_new(by, ret, matters))
1418                 return -ENOMEM;
1419
1420         if (is_new) {
1421                 /* Finally, recursively add in all dependencies. */
1422                 if (type == JOB_START || type == JOB_RELOAD_OR_START) {
1423                         SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES], i)
1424                                 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, true, override, NULL)) < 0 && r != -EBADR)
1425                                         goto fail;
1426
1427                         SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES_OVERRIDABLE], i)
1428                                 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, !override, override, NULL)) < 0 && r != -EBADR)
1429                                         log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, strerror(-r));
1430
1431                         SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_WANTS], i)
1432                                 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, false, false, NULL)) < 0)
1433                                         log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, strerror(-r));
1434
1435                         SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE], i)
1436                                 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, true, override, NULL)) < 0 && r != -EBADR)
1437                                         goto fail;
1438
1439                         SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE_OVERRIDABLE], i)
1440                                 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, 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_CONFLICTS], i)
1444                                 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, dep, ret, true, override, NULL)) < 0 && r != -EBADR)
1445                                         goto fail;
1446
1447                 } else if (type == JOB_STOP || type == JOB_RESTART || type == JOB_TRY_RESTART) {
1448
1449                         SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRED_BY], i)
1450                                 if ((r = transaction_add_job_and_dependencies(m, type, dep, ret, true, override, NULL)) < 0 && r != -EBADR)
1451                                         goto fail;
1452                 }
1453
1454                 /* JOB_VERIFY_STARTED, JOB_RELOAD require no dependency handling */
1455         }
1456
1457         if (_ret)
1458                 *_ret = ret;
1459
1460         return 0;
1461
1462 fail:
1463         return r;
1464 }
1465
1466 static int transaction_add_isolate_jobs(Manager *m) {
1467         Iterator i;
1468         Unit *u;
1469         char *k;
1470         int r;
1471
1472         assert(m);
1473
1474         HASHMAP_FOREACH_KEY(u, k, m->units, i) {
1475
1476                 /* ignore aliases */
1477                 if (u->meta.id != k)
1478                         continue;
1479
1480                 if (UNIT_VTABLE(u)->no_isolate)
1481                         continue;
1482
1483                 /* No need to stop inactive jobs */
1484                 if (unit_active_state(u) == UNIT_INACTIVE)
1485                         continue;
1486
1487                 /* Is there already something listed for this? */
1488                 if (hashmap_get(m->transaction_jobs, u))
1489                         continue;
1490
1491                 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, u, NULL, true, false, NULL)) < 0)
1492                         log_warning("Cannot add isolate job for unit %s, ignoring: %s", u->meta.id, strerror(-r));
1493         }
1494
1495         return 0;
1496 }
1497
1498 int manager_add_job(Manager *m, JobType type, Unit *unit, JobMode mode, bool override, Job **_ret) {
1499         int r;
1500         Job *ret;
1501
1502         assert(m);
1503         assert(type < _JOB_TYPE_MAX);
1504         assert(unit);
1505         assert(mode < _JOB_MODE_MAX);
1506
1507         if (mode == JOB_ISOLATE && type != JOB_START)
1508                 return -EINVAL;
1509
1510         log_debug("Trying to enqueue job %s/%s", unit->meta.id, job_type_to_string(type));
1511
1512         if ((r = transaction_add_job_and_dependencies(m, type, unit, NULL, true, override, &ret)) < 0) {
1513                 transaction_abort(m);
1514                 return r;
1515         }
1516
1517         if (mode == JOB_ISOLATE)
1518                 if ((r = transaction_add_isolate_jobs(m)) < 0) {
1519                         transaction_abort(m);
1520                         return r;
1521                 }
1522
1523         if ((r = transaction_activate(m, mode)) < 0)
1524                 return r;
1525
1526         log_debug("Enqueued job %s/%s as %u", unit->meta.id, job_type_to_string(type), (unsigned) ret->id);
1527
1528         if (_ret)
1529                 *_ret = ret;
1530
1531         return 0;
1532 }
1533
1534 int manager_add_job_by_name(Manager *m, JobType type, const char *name, JobMode mode, bool override, Job **_ret) {
1535         Unit *unit;
1536         int r;
1537
1538         assert(m);
1539         assert(type < _JOB_TYPE_MAX);
1540         assert(name);
1541         assert(mode < _JOB_MODE_MAX);
1542
1543         if ((r = manager_load_unit(m, name, NULL, &unit)) < 0)
1544                 return r;
1545
1546         return manager_add_job(m, type, unit, mode, override, _ret);
1547 }
1548
1549 Job *manager_get_job(Manager *m, uint32_t id) {
1550         assert(m);
1551
1552         return hashmap_get(m->jobs, UINT32_TO_PTR(id));
1553 }
1554
1555 Unit *manager_get_unit(Manager *m, const char *name) {
1556         assert(m);
1557         assert(name);
1558
1559         return hashmap_get(m->units, name);
1560 }
1561
1562 unsigned manager_dispatch_load_queue(Manager *m) {
1563         Meta *meta;
1564         unsigned n = 0;
1565
1566         assert(m);
1567
1568         /* Make sure we are not run recursively */
1569         if (m->dispatching_load_queue)
1570                 return 0;
1571
1572         m->dispatching_load_queue = true;
1573
1574         /* Dispatches the load queue. Takes a unit from the queue and
1575          * tries to load its data until the queue is empty */
1576
1577         while ((meta = m->load_queue)) {
1578                 assert(meta->in_load_queue);
1579
1580                 unit_load(UNIT(meta));
1581                 n++;
1582         }
1583
1584         m->dispatching_load_queue = false;
1585         return n;
1586 }
1587
1588 int manager_load_unit_prepare(Manager *m, const char *name, const char *path, Unit **_ret) {
1589         Unit *ret;
1590         int r;
1591
1592         assert(m);
1593         assert(name || path);
1594
1595         /* This will prepare the unit for loading, but not actually
1596          * load anything from disk. */
1597
1598         if (path && !is_path(path))
1599                 return -EINVAL;
1600
1601         if (!name)
1602                 name = file_name_from_path(path);
1603
1604         if (!unit_name_is_valid(name))
1605                 return -EINVAL;
1606
1607         if ((ret = manager_get_unit(m, name))) {
1608                 *_ret = ret;
1609                 return 1;
1610         }
1611
1612         if (!(ret = unit_new(m)))
1613                 return -ENOMEM;
1614
1615         if (path)
1616                 if (!(ret->meta.fragment_path = strdup(path))) {
1617                         unit_free(ret);
1618                         return -ENOMEM;
1619                 }
1620
1621         if ((r = unit_add_name(ret, name)) < 0) {
1622                 unit_free(ret);
1623                 return r;
1624         }
1625
1626         unit_add_to_load_queue(ret);
1627         unit_add_to_dbus_queue(ret);
1628         unit_add_to_gc_queue(ret);
1629
1630         if (_ret)
1631                 *_ret = ret;
1632
1633         return 0;
1634 }
1635
1636 int manager_load_unit(Manager *m, const char *name, const char *path, Unit **_ret) {
1637         int r;
1638
1639         assert(m);
1640
1641         /* This will load the service information files, but not actually
1642          * start any services or anything. */
1643
1644         if ((r = manager_load_unit_prepare(m, name, path, _ret)) != 0)
1645                 return r;
1646
1647         manager_dispatch_load_queue(m);
1648
1649         if (_ret)
1650                 *_ret = unit_follow_merge(*_ret);
1651
1652         return 0;
1653 }
1654
1655 void manager_dump_jobs(Manager *s, FILE *f, const char *prefix) {
1656         Iterator i;
1657         Job *j;
1658
1659         assert(s);
1660         assert(f);
1661
1662         HASHMAP_FOREACH(j, s->jobs, i)
1663                 job_dump(j, f, prefix);
1664 }
1665
1666 void manager_dump_units(Manager *s, FILE *f, const char *prefix) {
1667         Iterator i;
1668         Unit *u;
1669         const char *t;
1670
1671         assert(s);
1672         assert(f);
1673
1674         HASHMAP_FOREACH_KEY(u, t, s->units, i)
1675                 if (u->meta.id == t)
1676                         unit_dump(u, f, prefix);
1677 }
1678
1679 void manager_clear_jobs(Manager *m) {
1680         Job *j;
1681
1682         assert(m);
1683
1684         transaction_abort(m);
1685
1686         while ((j = hashmap_first(m->jobs)))
1687                 job_free(j);
1688 }
1689
1690 unsigned manager_dispatch_run_queue(Manager *m) {
1691         Job *j;
1692         unsigned n = 0;
1693
1694         if (m->dispatching_run_queue)
1695                 return 0;
1696
1697         m->dispatching_run_queue = true;
1698
1699         while ((j = m->run_queue)) {
1700                 assert(j->installed);
1701                 assert(j->in_run_queue);
1702
1703                 job_run_and_invalidate(j);
1704                 n++;
1705         }
1706
1707         m->dispatching_run_queue = false;
1708         return n;
1709 }
1710
1711 unsigned manager_dispatch_dbus_queue(Manager *m) {
1712         Job *j;
1713         Meta *meta;
1714         unsigned n = 0;
1715
1716         assert(m);
1717
1718         if (m->dispatching_dbus_queue)
1719                 return 0;
1720
1721         m->dispatching_dbus_queue = true;
1722
1723         while ((meta = m->dbus_unit_queue)) {
1724                 assert(meta->in_dbus_queue);
1725
1726                 bus_unit_send_change_signal(UNIT(meta));
1727                 n++;
1728         }
1729
1730         while ((j = m->dbus_job_queue)) {
1731                 assert(j->in_dbus_queue);
1732
1733                 bus_job_send_change_signal(j);
1734                 n++;
1735         }
1736
1737         m->dispatching_dbus_queue = false;
1738         return n;
1739 }
1740
1741 static int manager_dispatch_sigchld(Manager *m) {
1742         assert(m);
1743
1744         for (;;) {
1745                 siginfo_t si;
1746                 Unit *u;
1747
1748                 zero(si);
1749
1750                 /* First we call waitd() for a PID and do not reap the
1751                  * zombie. That way we can still access /proc/$PID for
1752                  * it while it is a zombie. */
1753                 if (waitid(P_ALL, 0, &si, WEXITED|WNOHANG|WNOWAIT) < 0) {
1754
1755                         if (errno == ECHILD)
1756                                 break;
1757
1758                         if (errno == EINTR)
1759                                 continue;
1760
1761                         return -errno;
1762                 }
1763
1764                 if (si.si_pid <= 0)
1765                         break;
1766
1767                 if (si.si_code == CLD_EXITED || si.si_code == CLD_KILLED || si.si_code == CLD_DUMPED) {
1768                         char *name = NULL;
1769
1770                         get_process_name(si.si_pid, &name);
1771                         log_debug("Got SIGCHLD for process %llu (%s)", (unsigned long long) si.si_pid, strna(name));
1772                         free(name);
1773                 }
1774
1775                 /* And now, we actually reap the zombie. */
1776                 if (waitid(P_PID, si.si_pid, &si, WEXITED) < 0) {
1777                         if (errno == EINTR)
1778                                 continue;
1779
1780                         return -errno;
1781                 }
1782
1783                 if (si.si_code != CLD_EXITED && si.si_code != CLD_KILLED && si.si_code != CLD_DUMPED)
1784                         continue;
1785
1786                 log_debug("Child %llu died (code=%s, status=%i/%s)",
1787                           (long long unsigned) si.si_pid,
1788                           sigchld_code_to_string(si.si_code),
1789                           si.si_status,
1790                           strna(si.si_code == CLD_EXITED ? exit_status_to_string(si.si_status) : strsignal(si.si_status)));
1791
1792                 if (!(u = hashmap_remove(m->watch_pids, UINT32_TO_PTR(si.si_pid))))
1793                         continue;
1794
1795                 log_debug("Child %llu belongs to %s", (long long unsigned) si.si_pid, u->meta.id);
1796
1797                 UNIT_VTABLE(u)->sigchld_event(u, si.si_pid, si.si_code, si.si_status);
1798         }
1799
1800         return 0;
1801 }
1802
1803 static int manager_start_target(Manager *m, const char *name) {
1804         int r;
1805
1806         if ((r = manager_add_job_by_name(m, JOB_START, name, JOB_REPLACE, true, NULL)) < 0)
1807                 log_error("Failed to enqueue %s job: %s", name, strerror(-r));
1808
1809         return r;
1810 }
1811
1812 static int manager_process_signal_fd(Manager *m) {
1813         ssize_t n;
1814         struct signalfd_siginfo sfsi;
1815         bool sigchld = false;
1816
1817         assert(m);
1818
1819         for (;;) {
1820                 if ((n = read(m->signal_watch.fd, &sfsi, sizeof(sfsi))) != sizeof(sfsi)) {
1821
1822                         if (n >= 0)
1823                                 return -EIO;
1824
1825                         if (errno == EAGAIN)
1826                                 break;
1827
1828                         return -errno;
1829                 }
1830
1831                 switch (sfsi.ssi_signo) {
1832
1833                 case SIGCHLD:
1834                         sigchld = true;
1835                         break;
1836
1837                 case SIGTERM:
1838                         if (m->running_as == MANAGER_INIT) {
1839                                 /* This is for compatibility with the
1840                                  * original sysvinit */
1841                                 m->exit_code = MANAGER_REEXECUTE;
1842                                 break;
1843                         }
1844
1845                         /* Fall through */
1846
1847                 case SIGINT:
1848                         if (m->running_as == MANAGER_INIT) {
1849                                 manager_start_target(m, SPECIAL_CTRL_ALT_DEL_TARGET);
1850                                 break;
1851                         }
1852
1853                         /* Run the exit target if there is one, if not, just exit. */
1854                         if (manager_start_target(m, SPECIAL_EXIT_SERVICE) < 0) {
1855                                 m->exit_code = MANAGER_EXIT;
1856                                 return 0;
1857                         }
1858
1859                         break;
1860
1861                 case SIGWINCH:
1862                         if (m->running_as == MANAGER_INIT)
1863                                 manager_start_target(m, SPECIAL_KBREQUEST_TARGET);
1864
1865                         /* This is a nop on non-init */
1866                         break;
1867
1868                 case SIGPWR:
1869                         if (m->running_as == MANAGER_INIT)
1870                                 manager_start_target(m, SPECIAL_SIGPWR_TARGET);
1871
1872                         /* This is a nop on non-init */
1873                         break;
1874
1875                 case SIGUSR1: {
1876                         Unit *u;
1877
1878                         u = manager_get_unit(m, SPECIAL_DBUS_SERVICE);
1879
1880                         if (!u || UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u))) {
1881                                 log_info("Trying to reconnect to bus...");
1882                                 bus_init_system(m);
1883                                 bus_init_api(m);
1884                         }
1885
1886                         if (!u || !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u))) {
1887                                 log_info("Loading D-Bus service...");
1888                                 manager_start_target(m, SPECIAL_DBUS_SERVICE);
1889                         }
1890
1891                         break;
1892                 }
1893
1894                 case SIGUSR2: {
1895                         FILE *f;
1896                         char *dump = NULL;
1897                         size_t size;
1898
1899                         if (!(f = open_memstream(&dump, &size))) {
1900                                 log_warning("Failed to allocate memory stream.");
1901                                 break;
1902                         }
1903
1904                         manager_dump_units(m, f, "\t");
1905                         manager_dump_jobs(m, f, "\t");
1906
1907                         if (ferror(f)) {
1908                                 fclose(f);
1909                                 free(dump);
1910                                 log_warning("Failed to write status stream");
1911                                 break;
1912                         }
1913
1914                         fclose(f);
1915                         log_dump(LOG_INFO, dump);
1916                         free(dump);
1917
1918                         break;
1919                 }
1920
1921                 case SIGHUP:
1922                         m->exit_code = MANAGER_RELOAD;
1923                         break;
1924
1925                 default:
1926                         log_info("Got unhandled signal <%s>.", strsignal(sfsi.ssi_signo));
1927                 }
1928         }
1929
1930         if (sigchld)
1931                 return manager_dispatch_sigchld(m);
1932
1933         return 0;
1934 }
1935
1936 static int process_event(Manager *m, struct epoll_event *ev) {
1937         int r;
1938         Watch *w;
1939
1940         assert(m);
1941         assert(ev);
1942
1943         assert(w = ev->data.ptr);
1944
1945         switch (w->type) {
1946
1947         case WATCH_SIGNAL:
1948
1949                 /* An incoming signal? */
1950                 if (ev->events != EPOLLIN)
1951                         return -EINVAL;
1952
1953                 if ((r = manager_process_signal_fd(m)) < 0)
1954                         return r;
1955
1956                 break;
1957
1958         case WATCH_FD:
1959
1960                 /* Some fd event, to be dispatched to the units */
1961                 UNIT_VTABLE(w->data.unit)->fd_event(w->data.unit, w->fd, ev->events, w);
1962                 break;
1963
1964         case WATCH_TIMER: {
1965                 uint64_t v;
1966                 ssize_t k;
1967
1968                 /* Some timer event, to be dispatched to the units */
1969                 if ((k = read(w->fd, &v, sizeof(v))) != sizeof(v)) {
1970
1971                         if (k < 0 && (errno == EINTR || errno == EAGAIN))
1972                                 break;
1973
1974                         return k < 0 ? -errno : -EIO;
1975                 }
1976
1977                 UNIT_VTABLE(w->data.unit)->timer_event(w->data.unit, v, w);
1978                 break;
1979         }
1980
1981         case WATCH_MOUNT:
1982                 /* Some mount table change, intended for the mount subsystem */
1983                 mount_fd_event(m, ev->events);
1984                 break;
1985
1986         case WATCH_UDEV:
1987                 /* Some notification from udev, intended for the device subsystem */
1988                 device_fd_event(m, ev->events);
1989                 break;
1990
1991         case WATCH_DBUS_WATCH:
1992                 bus_watch_event(m, w, ev->events);
1993                 break;
1994
1995         case WATCH_DBUS_TIMEOUT:
1996                 bus_timeout_event(m, w, ev->events);
1997                 break;
1998
1999         default:
2000                 assert_not_reached("Unknown epoll event type.");
2001         }
2002
2003         return 0;
2004 }
2005
2006 int manager_loop(Manager *m) {
2007         int r;
2008
2009         RATELIMIT_DEFINE(rl, 1*USEC_PER_SEC, 1000);
2010
2011         assert(m);
2012         m->exit_code = MANAGER_RUNNING;
2013
2014         /* There might still be some zombies hanging around from
2015          * before we were exec()'ed. Leat's reap them */
2016         if ((r = manager_dispatch_sigchld(m)) < 0)
2017                 return r;
2018
2019         while (m->exit_code == MANAGER_RUNNING) {
2020                 struct epoll_event event;
2021                 int n;
2022
2023                 if (!ratelimit_test(&rl)) {
2024                         /* Yay, something is going seriously wrong, pause a little */
2025                         log_warning("Looping too fast. Throttling execution a little.");
2026                         sleep(1);
2027                 }
2028
2029                 if (manager_dispatch_load_queue(m) > 0)
2030                         continue;
2031
2032                 if (manager_dispatch_run_queue(m) > 0)
2033                         continue;
2034
2035                 if (bus_dispatch(m) > 0)
2036                         continue;
2037
2038                 if (manager_dispatch_cleanup_queue(m) > 0)
2039                         continue;
2040
2041                 if (manager_dispatch_gc_queue(m) > 0)
2042                         continue;
2043
2044                 if (manager_dispatch_dbus_queue(m) > 0)
2045                         continue;
2046
2047                 if ((n = epoll_wait(m->epoll_fd, &event, 1, -1)) < 0) {
2048
2049                         if (errno == EINTR)
2050                                 continue;
2051
2052                         return -errno;
2053                 }
2054
2055                 assert(n == 1);
2056
2057                 if ((r = process_event(m, &event)) < 0)
2058                         return r;
2059         }
2060
2061         return m->exit_code;
2062 }
2063
2064 int manager_get_unit_from_dbus_path(Manager *m, const char *s, Unit **_u) {
2065         char *n;
2066         Unit *u;
2067
2068         assert(m);
2069         assert(s);
2070         assert(_u);
2071
2072         if (!startswith(s, "/org/freedesktop/systemd1/unit/"))
2073                 return -EINVAL;
2074
2075         if (!(n = bus_path_unescape(s+31)))
2076                 return -ENOMEM;
2077
2078         u = manager_get_unit(m, n);
2079         free(n);
2080
2081         if (!u)
2082                 return -ENOENT;
2083
2084         *_u = u;
2085
2086         return 0;
2087 }
2088
2089 int manager_get_job_from_dbus_path(Manager *m, const char *s, Job **_j) {
2090         Job *j;
2091         unsigned id;
2092         int r;
2093
2094         assert(m);
2095         assert(s);
2096         assert(_j);
2097
2098         if (!startswith(s, "/org/freedesktop/systemd1/job/"))
2099                 return -EINVAL;
2100
2101         if ((r = safe_atou(s + 30, &id)) < 0)
2102                 return r;
2103
2104         if (!(j = manager_get_job(m, id)))
2105                 return -ENOENT;
2106
2107         *_j = j;
2108
2109         return 0;
2110 }
2111
2112 static bool manager_utmp_good(Manager *m) {
2113         int r;
2114
2115         assert(m);
2116
2117         if ((r = mount_path_is_mounted(m, _PATH_UTMPX)) <= 0) {
2118
2119                 if (r < 0)
2120                         log_warning("Failed to determine whether " _PATH_UTMPX " is mounted: %s", strerror(-r));
2121
2122                 return false;
2123         }
2124
2125         return true;
2126 }
2127
2128 void manager_write_utmp_reboot(Manager *m) {
2129         int r;
2130
2131         assert(m);
2132
2133         if (m->utmp_reboot_written)
2134                 return;
2135
2136         if (m->running_as != MANAGER_INIT)
2137                 return;
2138
2139         if (!manager_utmp_good(m))
2140                 return;
2141
2142         if ((r = utmp_put_reboot(m->startup_timestamp.realtime)) < 0) {
2143
2144                 if (r != -ENOENT && r != -EROFS)
2145                         log_warning("Failed to write utmp/wtmp: %s", strerror(-r));
2146
2147                 return;
2148         }
2149
2150         m->utmp_reboot_written = true;
2151 }
2152
2153 void manager_write_utmp_runlevel(Manager *m, Unit *u) {
2154         int runlevel, r;
2155
2156         assert(m);
2157         assert(u);
2158
2159         if (u->meta.type != UNIT_TARGET)
2160                 return;
2161
2162         if (m->running_as != MANAGER_INIT)
2163                 return;
2164
2165         if (!manager_utmp_good(m))
2166                 return;
2167
2168         if ((runlevel = target_get_runlevel(TARGET(u))) <= 0)
2169                 return;
2170
2171         if ((r = utmp_put_runlevel(0, runlevel, 0)) < 0) {
2172
2173                 if (r != -ENOENT && r != -EROFS)
2174                         log_warning("Failed to write utmp/wtmp: %s", strerror(-r));
2175         }
2176 }
2177
2178 void manager_dispatch_bus_name_owner_changed(
2179                 Manager *m,
2180                 const char *name,
2181                 const char* old_owner,
2182                 const char *new_owner) {
2183
2184         Unit *u;
2185
2186         assert(m);
2187         assert(name);
2188
2189         if (!(u = hashmap_get(m->watch_bus, name)))
2190                 return;
2191
2192         UNIT_VTABLE(u)->bus_name_owner_change(u, name, old_owner, new_owner);
2193 }
2194
2195 void manager_dispatch_bus_query_pid_done(
2196                 Manager *m,
2197                 const char *name,
2198                 pid_t pid) {
2199
2200         Unit *u;
2201
2202         assert(m);
2203         assert(name);
2204         assert(pid >= 1);
2205
2206         if (!(u = hashmap_get(m->watch_bus, name)))
2207                 return;
2208
2209         UNIT_VTABLE(u)->bus_query_pid_done(u, name, pid);
2210 }
2211
2212 int manager_open_serialization(FILE **_f) {
2213         char *path;
2214         mode_t saved_umask;
2215         int fd;
2216         FILE *f;
2217
2218         assert(_f);
2219
2220         if (asprintf(&path, "/dev/shm/systemd-%u.dump-XXXXXX", (unsigned) getpid()) < 0)
2221                 return -ENOMEM;
2222
2223         saved_umask = umask(0077);
2224         fd = mkostemp(path, O_RDWR|O_CLOEXEC);
2225         umask(saved_umask);
2226
2227         if (fd < 0) {
2228                 free(path);
2229                 return -errno;
2230         }
2231
2232         unlink(path);
2233
2234         log_debug("Serializing state to %s", path);
2235         free(path);
2236
2237         if (!(f = fdopen(fd, "w+")) < 0)
2238                 return -errno;
2239
2240         *_f = f;
2241
2242         return 0;
2243 }
2244
2245 int manager_serialize(Manager *m, FILE *f, FDSet *fds) {
2246         Iterator i;
2247         Unit *u;
2248         const char *t;
2249         int r;
2250
2251         assert(m);
2252         assert(f);
2253         assert(fds);
2254
2255         HASHMAP_FOREACH_KEY(u, t, m->units, i) {
2256                 if (u->meta.id != t)
2257                         continue;
2258
2259                 if (!unit_can_serialize(u))
2260                         continue;
2261
2262                 /* Start marker */
2263                 fputs(u->meta.id, f);
2264                 fputc('\n', f);
2265
2266                 if ((r = unit_serialize(u, f, fds)) < 0)
2267                         return r;
2268         }
2269
2270         if (ferror(f))
2271                 return -EIO;
2272
2273         return 0;
2274 }
2275
2276 int manager_deserialize(Manager *m, FILE *f, FDSet *fds) {
2277         int r = 0;
2278
2279         assert(m);
2280         assert(f);
2281
2282         log_debug("Deserializing state...");
2283
2284         for (;;) {
2285                 Unit *u;
2286                 char name[UNIT_NAME_MAX+2];
2287
2288                 /* Start marker */
2289                 if (!fgets(name, sizeof(name), f)) {
2290                         if (feof(f))
2291                                 break;
2292
2293                         return -errno;
2294                 }
2295
2296                 char_array_0(name);
2297
2298                 if ((r = manager_load_unit(m, strstrip(name), NULL, &u)) < 0)
2299                         return r;
2300
2301                 if ((r = unit_deserialize(u, f, fds)) < 0)
2302                         return r;
2303         }
2304
2305         if (ferror(f))
2306                 return -EIO;
2307
2308         return 0;
2309 }
2310
2311 int manager_reload(Manager *m) {
2312         int r, q;
2313         FILE *f;
2314         FDSet *fds;
2315
2316         assert(m);
2317
2318         if ((r = manager_open_serialization(&f)) < 0)
2319                 return r;
2320
2321         if (!(fds = fdset_new())) {
2322                 r = -ENOMEM;
2323                 goto finish;
2324         }
2325
2326         if ((r = manager_serialize(m, f, fds)) < 0)
2327                 goto finish;
2328
2329         if (fseeko(f, 0, SEEK_SET) < 0) {
2330                 r = -errno;
2331                 goto finish;
2332         }
2333
2334         /* From here on there is no way back. */
2335         manager_clear_jobs_and_units(m);
2336
2337         /* First, enumerate what we can from all config files */
2338         if ((q = manager_enumerate(m)) < 0)
2339                 r = q;
2340
2341         /* Second, deserialize our stored data */
2342         if ((q = manager_deserialize(m, f, fds)) < 0)
2343                 r = q;
2344
2345         fclose(f);
2346         f = NULL;
2347
2348         /* Third, fire things up! */
2349         if ((q = manager_coldplug(m)) < 0)
2350                 r = q;
2351
2352 finish:
2353         if (f)
2354                 fclose(f);
2355
2356         if (fds)
2357                 fdset_free(fds);
2358
2359         return r;
2360 }
2361
2362 static const char* const manager_running_as_table[_MANAGER_RUNNING_AS_MAX] = {
2363         [MANAGER_INIT] = "init",
2364         [MANAGER_SYSTEM] = "system",
2365         [MANAGER_SESSION] = "session"
2366 };
2367
2368 DEFINE_STRING_TABLE_LOOKUP(manager_running_as, ManagerRunningAs);