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