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