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