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