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