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