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