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