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