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