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