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