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