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