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