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