]> git.ipfire.org Git - people/ms/systemd.git/blame - manager.c
manager: we are not interested in SIGPIPE/SIGTTIN
[people/ms/systemd.git] / 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>
60918275
LP
36
37#include "manager.h"
38#include "hashmap.h"
39#include "macro.h"
40#include "strv.h"
16354eff 41#include "log.h"
2a987ee8 42#include "util.h"
ea430986 43#include "ratelimit.h"
8e274523
LP
44#include "cgroup.h"
45#include "mount-setup.h"
e537352b 46#include "utmp-wtmp.h"
60918275 47
ce578209 48static int manager_setup_signals(Manager *m) {
9152c765
LP
49 sigset_t mask;
50 struct epoll_event ev;
60918275 51
ce578209
LP
52 assert(m);
53
ce578209
LP
54 assert_se(sigemptyset(&mask) == 0);
55 assert_se(sigaddset(&mask, SIGCHLD) == 0);
56 assert_se(sigaddset(&mask, SIGINT) == 0); /* Kernel sends us this on control-alt-del */
57 assert_se(sigaddset(&mask, SIGWINCH) == 0); /* Kernel sends us this on kbrequest (alt-arrowup) */
58 assert_se(sigaddset(&mask, SIGTERM) == 0);
59 assert_se(sigaddset(&mask, SIGHUP) == 0);
60 assert_se(sigaddset(&mask, SIGUSR1) == 0);
61 assert_se(sigaddset(&mask, SIGUSR2) == 0);
e1414003 62 assert_se(sigaddset(&mask, SIGPWR) == 0);
ce578209
LP
63 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
64
ef734fd6 65 m->signal_watch.type = WATCH_SIGNAL;
ce578209
LP
66 if ((m->signal_watch.fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0)
67 return -errno;
68
69 zero(ev);
70 ev.events = EPOLLIN;
71 ev.data.ptr = &m->signal_watch;
72
73 if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->signal_watch.fd, &ev) < 0)
74 return -errno;
75
e1414003
LP
76 if (m->running_as == MANAGER_INIT) {
77 /* Enable that we get SIGINT on control-alt-del */
78 if (reboot(RB_DISABLE_CAD) < 0)
79 log_warning("Failed to enable ctrl-alt-del handling: %s", strerror(errno));
80
81 /* Enable that we get SIGWINCH on kbrequest */
82 if (ioctl(0, KDSIGACCEPT, SIGWINCH) < 0)
83 log_warning("Failed to enable kbrequest handling: %s", strerror(errno));
84 }
85
ce578209
LP
86 return 0;
87}
88
036643a2
LP
89static char** session_dirs(void) {
90 const char *home, *e;
91 char *config_home = NULL, *data_home = NULL;
92 char **config_dirs = NULL, **data_dirs = NULL;
93 char **r = NULL, **t;
94
95 /* Implement the mechanisms defined in
96 *
97 * http://standards.freedesktop.org/basedir-spec/basedir-spec-0.6.html
98 *
99 * We look in both the config and the data dirs because we
100 * want to encourage that distributors ship their unit files
101 * as data, and allow overriding as configuration.
102 */
103
104 home = getenv("HOME");
105
106 if ((e = getenv("XDG_CONFIG_HOME"))) {
107 if (asprintf(&config_home, "%s/systemd/session", e) < 0)
108 goto fail;
109
110 } else if (home) {
111 if (asprintf(&config_home, "%s/.config/systemd/session", home) < 0)
112 goto fail;
113 }
114
115 if ((e = getenv("XDG_CONFIG_DIRS")))
116 config_dirs = strv_split(e, ":");
117 else
118 config_dirs = strv_new("/etc/xdg", NULL);
119
120 if (!config_dirs)
121 goto fail;
122
123 if ((e = getenv("XDG_DATA_HOME"))) {
124 if (asprintf(&data_home, "%s/systemd/session", e) < 0)
125 goto fail;
126
127 } else if (home) {
128 if (asprintf(&data_home, "%s/.local/share/systemd/session", home) < 0)
129 goto fail;
130 }
131
132 if ((e = getenv("XDG_DATA_DIRS")))
133 data_dirs = strv_split(e, ":");
134 else
135 data_dirs = strv_new("/usr/local/share", "/usr/share", NULL);
136
137 if (!data_dirs)
138 goto fail;
139
140 /* Now merge everything we found. */
141 if (config_home) {
142 if (!(t = strv_append(r, config_home)))
143 goto fail;
144 strv_free(r);
145 r = t;
146 }
147
148 if (!(t = strv_merge_concat(r, config_dirs, "/systemd/session")))
149 goto finish;
150 strv_free(r);
151 r = t;
152
153 if (!(t = strv_append(r, SESSION_CONFIG_UNIT_PATH)))
154 goto fail;
155 strv_free(r);
156 r = t;
157
158 if (data_home) {
159 if (!(t = strv_append(r, data_home)))
160 goto fail;
161 strv_free(r);
162 r = t;
163 }
164
165 if (!(t = strv_merge_concat(r, data_dirs, "/systemd/session")))
166 goto fail;
167 strv_free(r);
168 r = t;
169
170 if (!(t = strv_append(r, SESSION_DATA_UNIT_PATH)))
171 goto fail;
172 strv_free(r);
173 r = t;
174
175 if (!strv_path_make_absolute_cwd(r))
176 goto fail;
177
178finish:
179 free(config_home);
180 strv_free(config_dirs);
181 free(data_home);
182 strv_free(data_dirs);
183
184 return r;
185
186fail:
187 strv_free(r);
188 r = NULL;
189 goto finish;
190}
191
192static int manager_find_paths(Manager *m) {
193 const char *e;
194 char *t;
23a177ef 195
036643a2
LP
196 assert(m);
197
198 /* First priority is whatever has been passed to us via env
199 * vars */
200 if ((e = getenv("SYSTEMD_UNIT_PATH")))
201 if (!(m->unit_path = split_path_and_make_absolute(e)))
202 return -ENOMEM;
203
204 if (strv_isempty(m->unit_path)) {
205
206 /* Nothing is set, so let's figure something out. */
207 strv_free(m->unit_path);
208
209 if (m->running_as == MANAGER_SESSION) {
210 if (!(m->unit_path = session_dirs()))
211 return -ENOMEM;
212 } else
213 if (!(m->unit_path = strv_new(
214 SYSTEM_CONFIG_UNIT_PATH, /* /etc/systemd/system/ */
215 SYSTEM_DATA_UNIT_PATH, /* /lib/systemd/system/ */
216 NULL)))
217 return -ENOMEM;
218 }
219
e1414003 220 if (m->running_as == MANAGER_INIT) {
036643a2
LP
221 /* /etc/init.d/ compativility does not matter to users */
222
223 if ((e = getenv("SYSTEMD_SYSVINIT_PATH")))
224 if (!(m->sysvinit_path = split_path_and_make_absolute(e)))
225 return -ENOMEM;
226
227 if (strv_isempty(m->sysvinit_path)) {
228 strv_free(m->sysvinit_path);
229
230 if (!(m->sysvinit_path = strv_new(
231 SYSTEM_SYSVINIT_PATH, /* /etc/init.d/ */
232 NULL)))
233 return -ENOMEM;
234 }
0571e011
LP
235
236 if ((e = getenv("SYSTEMD_SYSVRCND_PATH")))
237 if (!(m->sysvrcnd_path = split_path_and_make_absolute(e)))
238 return -ENOMEM;
239
240 if (strv_isempty(m->sysvrcnd_path)) {
241 strv_free(m->sysvrcnd_path);
242
243 if (!(m->sysvrcnd_path = strv_new(
244 SYSTEM_SYSVRCND_PATH, /* /etc/rcN.d/ */
245 NULL)))
246 return -ENOMEM;
247 }
036643a2
LP
248 }
249
250 strv_uniq(m->unit_path);
251 strv_uniq(m->sysvinit_path);
0571e011 252 strv_uniq(m->sysvrcnd_path);
036643a2
LP
253
254 assert(!strv_isempty(m->unit_path));
255 if (!(t = strv_join(m->unit_path, "\n\t")))
256 return -ENOMEM;
257 log_debug("Looking for unit files in:\n\t%s", t);
258 free(t);
259
260 if (!strv_isempty(m->sysvinit_path)) {
261
262 if (!(t = strv_join(m->sysvinit_path, "\n\t")))
263 return -ENOMEM;
264
265 log_debug("Looking for SysV init scripts in:\n\t%s", t);
266 free(t);
267 } else
268 log_debug("Ignoring SysV init scripts.");
269
0571e011
LP
270 if (!strv_isempty(m->sysvrcnd_path)) {
271
272 if (!(t = strv_join(m->sysvrcnd_path, "\n\t")))
273 return -ENOMEM;
274
275 log_debug("Looking for SysV rcN.d links in:\n\t%s", t);
276 free(t);
277 } else
278 log_debug("Ignoring SysV rcN.d links.");
279
036643a2
LP
280 return 0;
281}
282
a5dab5ce 283int manager_new(ManagerRunningAs running_as, Manager **_m) {
ce578209 284 Manager *m;
8e274523
LP
285 int r = -ENOMEM;
286
287 assert(_m);
a5dab5ce
LP
288 assert(running_as >= 0);
289 assert(running_as < _MANAGER_RUNNING_AS_MAX);
ce578209 290
60918275 291 if (!(m = new0(Manager, 1)))
8e274523 292 return -ENOMEM;
60918275 293
e537352b
LP
294 m->boot_timestamp = now(CLOCK_REALTIME);
295
a5dab5ce 296 m->running_as = running_as;
f94ea366 297 m->signal_watch.fd = m->mount_watch.fd = m->udev_watch.fd = m->epoll_fd = -1;
ea430986 298 m->current_job_id = 1; /* start as id #1, so that we can leave #0 around as "null-like" value */
9152c765 299
87f0e418 300 if (!(m->units = hashmap_new(string_hash_func, string_compare_func)))
60918275
LP
301 goto fail;
302
303 if (!(m->jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
304 goto fail;
305
e5b5ae50 306 if (!(m->transaction_jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
60918275
LP
307 goto fail;
308
9152c765
LP
309 if (!(m->watch_pids = hashmap_new(trivial_hash_func, trivial_compare_func)))
310 goto fail;
311
8e274523
LP
312 if (!(m->cgroup_bondings = hashmap_new(string_hash_func, string_compare_func)))
313 goto fail;
314
9152c765
LP
315 if ((m->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0)
316 goto fail;
317
8e274523 318 if ((r = manager_find_paths(m)) < 0)
e1414003
LP
319 goto fail;
320
8e274523
LP
321 if ((r = manager_setup_signals(m)) < 0)
322 goto fail;
323
8e274523 324 if ((r = manager_setup_cgroup(m)) < 0)
9152c765
LP
325 goto fail;
326
f278026d
LP
327 /* Try to connect to the busses, if possible. */
328 if ((r = bus_init_system(m)) < 0 ||
329 (r = bus_init_api(m)) < 0)
ea430986
LP
330 goto fail;
331
8e274523
LP
332 *_m = m;
333 return 0;
60918275
LP
334
335fail:
336 manager_free(m);
8e274523 337 return r;
60918275
LP
338}
339
23a177ef
LP
340static unsigned manager_dispatch_cleanup_queue(Manager *m) {
341 Meta *meta;
342 unsigned n = 0;
343
344 assert(m);
345
346 while ((meta = m->cleanup_queue)) {
347 assert(meta->in_cleanup_queue);
348
349 unit_free(UNIT(meta));
350 n++;
351 }
352
353 return n;
354}
355
60918275 356void manager_free(Manager *m) {
7824bbeb 357 UnitType c;
87f0e418 358 Unit *u;
e5b5ae50 359 Job *j;
60918275
LP
360
361 assert(m);
362
87f0e418 363 while ((j = hashmap_first(m->transaction_jobs)))
e5b5ae50
LP
364 job_free(j);
365
87f0e418
LP
366 while ((u = hashmap_first(m->units)))
367 unit_free(u);
368
23a177ef
LP
369 manager_dispatch_cleanup_queue(m);
370
7824bbeb
LP
371 for (c = 0; c < _UNIT_TYPE_MAX; c++)
372 if (unit_vtable[c]->shutdown)
373 unit_vtable[c]->shutdown(m);
374
8e274523
LP
375 manager_shutdown_cgroup(m);
376
f278026d
LP
377 bus_done_api(m);
378 bus_done_system(m);
ea430986 379
87f0e418 380 hashmap_free(m->units);
60918275 381 hashmap_free(m->jobs);
e5b5ae50 382 hashmap_free(m->transaction_jobs);
9152c765
LP
383 hashmap_free(m->watch_pids);
384
385 if (m->epoll_fd >= 0)
386 close_nointr(m->epoll_fd);
acbb0225
LP
387 if (m->signal_watch.fd >= 0)
388 close_nointr(m->signal_watch.fd);
60918275 389
036643a2
LP
390 strv_free(m->unit_path);
391 strv_free(m->sysvinit_path);
0571e011 392 strv_free(m->sysvrcnd_path);
036643a2 393
8e274523
LP
394 free(m->cgroup_controller);
395 free(m->cgroup_hierarchy);
396
397 assert(hashmap_isempty(m->cgroup_bondings));
398 hashmap_free(m->cgroup_bondings);
399
60918275
LP
400 free(m);
401}
402
f50e0a01
LP
403int manager_coldplug(Manager *m) {
404 int r;
405 UnitType c;
406 Iterator i;
407 Unit *u;
408 char *k;
409
410 assert(m);
411
412 /* First, let's ask every type to load all units from
413 * disk/kernel that it might know */
414 for (c = 0; c < _UNIT_TYPE_MAX; c++)
415 if (unit_vtable[c]->enumerate)
416 if ((r = unit_vtable[c]->enumerate(m)) < 0)
417 return r;
418
419 manager_dispatch_load_queue(m);
420
421 /* Then, let's set up their initial state. */
422 HASHMAP_FOREACH_KEY(u, k, m->units, i) {
423
424 /* ignore aliases */
425 if (unit_id(u) != k)
426 continue;
427
428 if (UNIT_VTABLE(u)->coldplug)
429 if ((r = UNIT_VTABLE(u)->coldplug(u)) < 0)
430 return r;
431 }
432
e537352b
LP
433 /* Now that the initial devices are available, let's see if we
434 * can write the utmp file */
435 manager_write_utmp_reboot(m);
436
f50e0a01
LP
437 return 0;
438}
439
23a177ef 440static void transaction_delete_job(Manager *m, Job *j, bool delete_dependencies) {
302d0040
LP
441 assert(m);
442 assert(j);
443
1ffba6fe
LP
444 /* Deletes one job from the transaction */
445
23a177ef 446 manager_transaction_unlink_job(m, j, delete_dependencies);
302d0040 447
ac1135be 448 if (!j->installed)
302d0040
LP
449 job_free(j);
450}
451
87f0e418 452static void transaction_delete_unit(Manager *m, Unit *u) {
1ffba6fe
LP
453 Job *j;
454
87f0e418 455 /* Deletes all jobs associated with a certain unit from the
1ffba6fe
LP
456 * transaction */
457
87f0e418 458 while ((j = hashmap_get(m->transaction_jobs, u)))
23a177ef 459 transaction_delete_job(m, j, true);
1ffba6fe
LP
460}
461
f04fa1d5
LP
462static void transaction_clean_dependencies(Manager *m) {
463 Iterator i;
464 Job *j;
465
466 assert(m);
467
468 /* Drops all dependencies of all installed jobs */
469
470 HASHMAP_FOREACH(j, m->jobs, i) {
471 while (j->subject_list)
472 job_dependency_free(j->subject_list);
473 while (j->object_list)
474 job_dependency_free(j->object_list);
475 }
476
477 assert(!m->transaction_anchor);
478}
479
11dd41ce
LP
480static void transaction_abort(Manager *m) {
481 Job *j;
482
483 assert(m);
11dd41ce 484
e5b5ae50 485 while ((j = hashmap_first(m->transaction_jobs)))
ac1135be 486 if (j->installed)
23a177ef 487 transaction_delete_job(m, j, true);
e5b5ae50
LP
488 else
489 job_free(j);
490
491 assert(hashmap_isempty(m->transaction_jobs));
f04fa1d5
LP
492
493 transaction_clean_dependencies(m);
e5b5ae50
LP
494}
495
496static void transaction_find_jobs_that_matter_to_anchor(Manager *m, Job *j, unsigned generation) {
497 JobDependency *l;
498
499 assert(m);
500
87f0e418 501 /* A recursive sweep through the graph that marks all units
1ffba6fe
LP
502 * that matter to the anchor job, i.e. are directly or
503 * indirectly a dependency of the anchor job via paths that
504 * are fully marked as mattering. */
505
44d8db9e
LP
506 if (j)
507 l = j->subject_list;
508 else
509 l = m->transaction_anchor;
510
511 LIST_FOREACH(subject, l, l) {
e5b5ae50
LP
512
513 /* This link does not matter */
514 if (!l->matters)
515 continue;
516
87f0e418 517 /* This unit has already been marked */
e5b5ae50
LP
518 if (l->object->generation == generation)
519 continue;
520
521 l->object->matters_to_anchor = true;
522 l->object->generation = generation;
523
524 transaction_find_jobs_that_matter_to_anchor(m, l->object, generation);
525 }
526}
527
7fad411c 528static void transaction_merge_and_delete_job(Manager *m, Job *j, Job *other, JobType t) {
e5b5ae50
LP
529 JobDependency *l, *last;
530
531 assert(j);
532 assert(other);
87f0e418 533 assert(j->unit == other->unit);
ac1135be 534 assert(!j->installed);
e5b5ae50 535
1ffba6fe
LP
536 /* Merges 'other' into 'j' and then deletes j. */
537
e5b5ae50
LP
538 j->type = t;
539 j->state = JOB_WAITING;
5cb5a6ff 540 j->forced = j->forced || other->forced;
e5b5ae50
LP
541
542 j->matters_to_anchor = j->matters_to_anchor || other->matters_to_anchor;
543
544 /* Patch us in as new owner of the JobDependency objects */
545 last = NULL;
44d8db9e 546 LIST_FOREACH(subject, l, other->subject_list) {
e5b5ae50
LP
547 assert(l->subject == other);
548 l->subject = j;
549 last = l;
550 }
551
552 /* Merge both lists */
553 if (last) {
554 last->subject_next = j->subject_list;
555 if (j->subject_list)
556 j->subject_list->subject_prev = last;
557 j->subject_list = other->subject_list;
558 }
559
560 /* Patch us in as new owner of the JobDependency objects */
561 last = NULL;
44d8db9e 562 LIST_FOREACH(object, l, other->object_list) {
e5b5ae50
LP
563 assert(l->object == other);
564 l->object = j;
565 last = l;
566 }
567
568 /* Merge both lists */
569 if (last) {
570 last->object_next = j->object_list;
571 if (j->object_list)
572 j->object_list->object_prev = last;
573 j->object_list = other->object_list;
574 }
575
e5b5ae50
LP
576 /* Kill the other job */
577 other->subject_list = NULL;
578 other->object_list = NULL;
23a177ef 579 transaction_delete_job(m, other, true);
e5b5ae50
LP
580}
581
5cb5a6ff 582static int delete_one_unmergeable_job(Manager *m, Job *j) {
1ffba6fe
LP
583 Job *k;
584
585 assert(j);
586
587 /* Tries to delete one item in the linked list
588 * j->transaction_next->transaction_next->... that conflicts
589 * whith another one, in an attempt to make an inconsistent
590 * transaction work. */
591
592 /* We rely here on the fact that if a merged with b does not
593 * merge with c, either a or b merge with c neither */
034c6ed7
LP
594 LIST_FOREACH(transaction, j, j)
595 LIST_FOREACH(transaction, k, j->transaction_next) {
1ffba6fe
LP
596 Job *d;
597
598 /* Is this one mergeable? Then skip it */
5cb5a6ff 599 if (job_type_is_mergeable(j->type, k->type))
1ffba6fe
LP
600 continue;
601
602 /* Ok, we found two that conflict, let's see if we can
603 * drop one of them */
604 if (!j->matters_to_anchor)
605 d = j;
606 else if (!k->matters_to_anchor)
607 d = k;
608 else
609 return -ENOEXEC;
610
611 /* Ok, we can drop one, so let's do so. */
23a177ef
LP
612 log_debug("Trying to fix job merging by deleting job %s/%s", unit_id(d->unit), job_type_to_string(d->type));
613 transaction_delete_job(m, d, true);
1ffba6fe
LP
614 return 0;
615 }
616
617 return -EINVAL;
618}
619
e5b5ae50 620static int transaction_merge_jobs(Manager *m) {
11dd41ce 621 Job *j;
034c6ed7 622 Iterator i;
e5b5ae50
LP
623 int r;
624
625 assert(m);
626
1ffba6fe
LP
627 /* First step, check whether any of the jobs for one specific
628 * task conflict. If so, try to drop one of them. */
034c6ed7 629 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1ffba6fe
LP
630 JobType t;
631 Job *k;
632
633 t = j->type;
034c6ed7 634 LIST_FOREACH(transaction, k, j->transaction_next) {
1ffba6fe
LP
635 if ((r = job_type_merge(&t, k->type)) >= 0)
636 continue;
637
638 /* OK, we could not merge all jobs for this
639 * action. Let's see if we can get rid of one
640 * of them */
641
5cb5a6ff 642 if ((r = delete_one_unmergeable_job(m, j)) >= 0)
1ffba6fe
LP
643 /* Ok, we managed to drop one, now
644 * let's ask our callers to call us
645 * again after garbage collecting */
646 return -EAGAIN;
647
648 /* We couldn't merge anything. Failure */
649 return r;
650 }
651 }
652
653 /* Second step, merge the jobs. */
034c6ed7 654 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
e5b5ae50
LP
655 JobType t = j->type;
656 Job *k;
657
e094e853 658 /* Merge all transactions */
034c6ed7 659 LIST_FOREACH(transaction, k, j->transaction_next)
1ffba6fe 660 assert_se(job_type_merge(&t, k->type) == 0);
e5b5ae50 661
5cb5a6ff 662 /* If an active job is mergeable, merge it too */
87f0e418
LP
663 if (j->unit->meta.job)
664 job_type_merge(&t, j->unit->meta.job->type); /* Might fail. Which is OK */
e094e853 665
e5b5ae50 666 while ((k = j->transaction_next)) {
ac1135be 667 if (j->installed) {
7fad411c 668 transaction_merge_and_delete_job(m, k, j, t);
e5b5ae50
LP
669 j = k;
670 } else
7fad411c 671 transaction_merge_and_delete_job(m, j, k, t);
e5b5ae50
LP
672 }
673
674 assert(!j->transaction_next);
675 assert(!j->transaction_prev);
676 }
677
7fad411c 678 return 0;
e5b5ae50
LP
679}
680
23a177ef
LP
681static void transaction_drop_redundant(Manager *m) {
682 bool again;
683
684 assert(m);
685
686 /* Goes through the transaction and removes all jobs that are
687 * a noop */
688
689 do {
690 Job *j;
691 Iterator i;
692
693 again = false;
694
695 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
696 bool changes_something = false;
697 Job *k;
698
699 LIST_FOREACH(transaction, k, j) {
700
701 if (!job_is_anchor(k) &&
702 job_type_is_redundant(k->type, unit_active_state(k->unit)))
703 continue;
704
705 changes_something = true;
706 break;
707 }
708
709 if (changes_something)
710 continue;
711
712 log_debug("Found redundant job %s/%s, dropping.", unit_id(j->unit), job_type_to_string(j->type));
713 transaction_delete_job(m, j, false);
714 again = true;
715 break;
716 }
717
718 } while (again);
719}
720
87f0e418
LP
721static bool unit_matters_to_anchor(Unit *u, Job *j) {
722 assert(u);
1ffba6fe
LP
723 assert(!j->transaction_prev);
724
87f0e418 725 /* Checks whether at least one of the jobs for this unit
1ffba6fe
LP
726 * matters to the anchor. */
727
034c6ed7 728 LIST_FOREACH(transaction, j, j)
1ffba6fe
LP
729 if (j->matters_to_anchor)
730 return true;
731
732 return false;
733}
734
e5b5ae50 735static int transaction_verify_order_one(Manager *m, Job *j, Job *from, unsigned generation) {
034c6ed7 736 Iterator i;
87f0e418 737 Unit *u;
11dd41ce 738 int r;
e5b5ae50
LP
739
740 assert(m);
741 assert(j);
1ffba6fe
LP
742 assert(!j->transaction_prev);
743
744 /* Does a recursive sweep through the ordering graph, looking
745 * for a cycle. If we find cycle we try to break it. */
e5b5ae50 746
7fad411c 747 /* Did we find a cycle? */
e5b5ae50
LP
748 if (j->marker && j->generation == generation) {
749 Job *k;
750
751 /* So, we already have been here. We have a
1ffba6fe
LP
752 * cycle. Let's try to break it. We go backwards in
753 * our path and try to find a suitable job to
754 * remove. We use the marker to find our way back,
755 * since smart how we are we stored our way back in
756 * there. */
e5b5ae50 757
23a177ef 758 log_debug("Found ordering cycle on %s/%s", unit_id(j->unit), job_type_to_string(j->type));
9f04bd52 759
e5b5ae50 760 for (k = from; k; k = (k->generation == generation ? k->marker : NULL)) {
1ffba6fe 761
23a177ef 762 log_debug("Walked on cycle path to %s/%s", unit_id(k->unit), job_type_to_string(k->type));
9f04bd52 763
ac1135be 764 if (!k->installed &&
87f0e418 765 !unit_matters_to_anchor(k->unit, k)) {
1ffba6fe
LP
766 /* Ok, we can drop this one, so let's
767 * do so. */
87f0e418
LP
768 log_debug("Breaking order cycle by deleting job %s/%s", unit_id(k->unit), job_type_to_string(k->type));
769 transaction_delete_unit(m, k->unit);
e5b5ae50
LP
770 return -EAGAIN;
771 }
772
773 /* Check if this in fact was the beginning of
7fad411c 774 * the cycle */
e5b5ae50
LP
775 if (k == j)
776 break;
777 }
778
9f04bd52
LP
779 log_debug("Unable to break cycle");
780
1ffba6fe 781 return -ENOEXEC;
e5b5ae50
LP
782 }
783
1ffba6fe
LP
784 /* Make the marker point to where we come from, so that we can
785 * find our way backwards if we want to break a cycle */
e5b5ae50
LP
786 j->marker = from;
787 j->generation = generation;
788
1ffba6fe 789 /* We assume that the the dependencies are bidirectional, and
87f0e418
LP
790 * hence can ignore UNIT_AFTER */
791 SET_FOREACH(u, j->unit->meta.dependencies[UNIT_BEFORE], i) {
e5b5ae50
LP
792 Job *o;
793
87f0e418
LP
794 /* Is there a job for this unit? */
795 if (!(o = hashmap_get(m->transaction_jobs, u)))
1ffba6fe
LP
796
797 /* Ok, there is no job for this in the
798 * transaction, but maybe there is already one
799 * running? */
87f0e418 800 if (!(o = u->meta.job))
e5b5ae50
LP
801 continue;
802
803 if ((r = transaction_verify_order_one(m, o, j, generation)) < 0)
804 return r;
805 }
806
9f04bd52
LP
807 /* Ok, let's backtrack, and remember that this entry is not on
808 * our path anymore. */
809 j->marker = NULL;
810
e5b5ae50
LP
811 return 0;
812}
813
814static int transaction_verify_order(Manager *m, unsigned *generation) {
1ffba6fe
LP
815 Job *j;
816 int r;
034c6ed7 817 Iterator i;
1ffba6fe 818
e5b5ae50
LP
819 assert(m);
820 assert(generation);
821
1ffba6fe
LP
822 /* Check if the ordering graph is cyclic. If it is, try to fix
823 * that up by dropping one of the jobs. */
e5b5ae50 824
034c6ed7 825 HASHMAP_FOREACH(j, m->transaction_jobs, i)
1ffba6fe
LP
826 if ((r = transaction_verify_order_one(m, j, NULL, (*generation)++)) < 0)
827 return r;
e5b5ae50
LP
828
829 return 0;
830}
831
832static void transaction_collect_garbage(Manager *m) {
833 bool again;
834
835 assert(m);
836
1ffba6fe
LP
837 /* Drop jobs that are not required by any other job */
838
e5b5ae50 839 do {
034c6ed7 840 Iterator i;
e5b5ae50
LP
841 Job *j;
842
843 again = false;
844
034c6ed7 845 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
e5b5ae50
LP
846 if (j->object_list)
847 continue;
848
87f0e418 849 log_debug("Garbage collecting job %s/%s", unit_id(j->unit), job_type_to_string(j->type));
23a177ef 850 transaction_delete_job(m, j, true);
e5b5ae50
LP
851 again = true;
852 break;
853 }
854
855 } while (again);
856}
857
858static int transaction_is_destructive(Manager *m, JobMode mode) {
034c6ed7 859 Iterator i;
e5b5ae50 860 Job *j;
11dd41ce
LP
861
862 assert(m);
11dd41ce 863
e5b5ae50
LP
864 /* Checks whether applying this transaction means that
865 * existing jobs would be replaced */
11dd41ce 866
034c6ed7 867 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
e094e853
LP
868
869 /* Assume merged */
870 assert(!j->transaction_prev);
871 assert(!j->transaction_next);
872
87f0e418
LP
873 if (j->unit->meta.job &&
874 j->unit->meta.job != j &&
875 !job_type_is_superset(j->type, j->unit->meta.job->type))
e5b5ae50 876 return -EEXIST;
e094e853 877 }
11dd41ce 878
e5b5ae50
LP
879 return 0;
880}
881
e094e853
LP
882static void transaction_minimize_impact(Manager *m) {
883 bool again;
884 assert(m);
885
886 /* Drops all unnecessary jobs that reverse already active jobs
887 * or that stop a running service. */
888
889 do {
890 Job *j;
034c6ed7 891 Iterator i;
e094e853
LP
892
893 again = false;
894
034c6ed7
LP
895 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
896 LIST_FOREACH(transaction, j, j) {
c20cae32 897 bool stops_running_service, changes_existing_job;
e094e853
LP
898
899 /* If it matters, we shouldn't drop it */
900 if (j->matters_to_anchor)
901 continue;
902
903 /* Would this stop a running service?
904 * Would this change an existing job?
905 * If so, let's drop this entry */
c20cae32
LP
906
907 stops_running_service =
908 j->type == JOB_STOP && UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(j->unit));
909
910 changes_existing_job =
911 j->unit->meta.job && job_type_is_conflicting(j->type, j->unit->meta.job->state);
912
913 if (!stops_running_service && !changes_existing_job)
e094e853
LP
914 continue;
915
c20cae32
LP
916 if (stops_running_service)
917 log_debug("%s/%s would stop a running service.", unit_id(j->unit), job_type_to_string(j->type));
918
919 if (changes_existing_job)
920 log_debug("%s/%s would change existing job.", unit_id(j->unit), job_type_to_string(j->type));
921
e094e853 922 /* Ok, let's get rid of this */
c20cae32
LP
923 log_debug("Deleting %s/%s to minimize impact.", unit_id(j->unit), job_type_to_string(j->type));
924
23a177ef 925 transaction_delete_job(m, j, true);
e094e853
LP
926 again = true;
927 break;
928 }
929
930 if (again)
931 break;
932 }
933
934 } while (again);
935}
936
e5b5ae50 937static int transaction_apply(Manager *m, JobMode mode) {
034c6ed7 938 Iterator i;
e5b5ae50
LP
939 Job *j;
940 int r;
941
1ffba6fe
LP
942 /* Moves the transaction jobs to the set of active jobs */
943
034c6ed7 944 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
e094e853
LP
945 /* Assume merged */
946 assert(!j->transaction_prev);
947 assert(!j->transaction_next);
948
ac1135be 949 if (j->installed)
e5b5ae50
LP
950 continue;
951
952 if ((r = hashmap_put(m->jobs, UINT32_TO_PTR(j->id), j)) < 0)
11dd41ce
LP
953 goto rollback;
954 }
955
e5b5ae50 956 while ((j = hashmap_steal_first(m->transaction_jobs))) {
ac1135be 957 if (j->installed)
e5b5ae50
LP
958 continue;
959
87f0e418
LP
960 if (j->unit->meta.job)
961 job_free(j->unit->meta.job);
11dd41ce 962
87f0e418 963 j->unit->meta.job = j;
ac1135be 964 j->installed = true;
11dd41ce 965
e5b5ae50
LP
966 /* We're fully installed. Now let's free data we don't
967 * need anymore. */
968
969 assert(!j->transaction_next);
970 assert(!j->transaction_prev);
971
c1e1601e
LP
972 job_add_to_run_queue(j);
973 job_add_to_dbus_queue(j);
01184e04
LP
974 }
975
976 /* As last step, kill all remaining job dependencies. */
f04fa1d5 977 transaction_clean_dependencies(m);
1ffba6fe 978
11dd41ce
LP
979 return 0;
980
981rollback:
982
034c6ed7 983 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
ac1135be 984 if (j->installed)
e5b5ae50
LP
985 continue;
986
987 hashmap_remove(m->jobs, UINT32_TO_PTR(j->id));
988 }
989
990 return r;
991}
992
e5b5ae50
LP
993static int transaction_activate(Manager *m, JobMode mode) {
994 int r;
995 unsigned generation = 1;
996
997 assert(m);
998
999 /* This applies the changes recorded in transaction_jobs to
1000 * the actual list of jobs, if possible. */
1001
1002 /* First step: figure out which jobs matter */
1003 transaction_find_jobs_that_matter_to_anchor(m, NULL, generation++);
1004
e094e853
LP
1005 /* Second step: Try not to stop any running services if
1006 * we don't have to. Don't try to reverse running
1007 * jobs if we don't have to. */
1008 transaction_minimize_impact(m);
1009
23a177ef
LP
1010 /* Third step: Drop redundant jobs */
1011 transaction_drop_redundant(m);
1012
1ffba6fe 1013 for (;;) {
23a177ef 1014 /* Fourth step: Let's remove unneeded jobs that might
1ffba6fe
LP
1015 * be lurking. */
1016 transaction_collect_garbage(m);
e5b5ae50 1017
23a177ef 1018 /* Fifth step: verify order makes sense and correct
1ffba6fe
LP
1019 * cycles if necessary and possible */
1020 if ((r = transaction_verify_order(m, &generation)) >= 0)
1021 break;
e5b5ae50 1022
9f04bd52
LP
1023 if (r != -EAGAIN) {
1024 log_debug("Requested transaction contains an unfixable cyclic ordering dependency: %s", strerror(-r));
1ffba6fe 1025 goto rollback;
9f04bd52 1026 }
e5b5ae50 1027
1ffba6fe
LP
1028 /* Let's see if the resulting transaction ordering
1029 * graph is still cyclic... */
1030 }
1031
1032 for (;;) {
23a177ef 1033 /* Sixth step: let's drop unmergeable entries if
1ffba6fe
LP
1034 * necessary and possible, merge entries we can
1035 * merge */
1036 if ((r = transaction_merge_jobs(m)) >= 0)
1037 break;
1038
9f04bd52
LP
1039 if (r != -EAGAIN) {
1040 log_debug("Requested transaction contains unmergable jobs: %s", strerror(-r));
1ffba6fe 1041 goto rollback;
9f04bd52 1042 }
1ffba6fe 1043
23a177ef 1044 /* Seventh step: an entry got dropped, let's garbage
1ffba6fe
LP
1045 * collect its dependencies. */
1046 transaction_collect_garbage(m);
1047
1048 /* Let's see if the resulting transaction still has
5cb5a6ff 1049 * unmergeable entries ... */
1ffba6fe
LP
1050 }
1051
23a177ef
LP
1052 /* Eights step: Drop redundant jobs again, if the merging now allows us to drop more. */
1053 transaction_drop_redundant(m);
1054
1055 /* Ninth step: check whether we can actually apply this */
e5b5ae50 1056 if (mode == JOB_FAIL)
9f04bd52
LP
1057 if ((r = transaction_is_destructive(m, mode)) < 0) {
1058 log_debug("Requested transaction contradicts existing jobs: %s", strerror(-r));
e5b5ae50 1059 goto rollback;
9f04bd52 1060 }
e5b5ae50 1061
23a177ef 1062 /* Tenth step: apply changes */
9f04bd52
LP
1063 if ((r = transaction_apply(m, mode)) < 0) {
1064 log_debug("Failed to apply transaction: %s", strerror(-r));
e5b5ae50 1065 goto rollback;
9f04bd52 1066 }
e5b5ae50
LP
1067
1068 assert(hashmap_isempty(m->transaction_jobs));
1069 assert(!m->transaction_anchor);
1070
1071 return 0;
11dd41ce 1072
e5b5ae50 1073rollback:
11dd41ce
LP
1074 transaction_abort(m);
1075 return r;
1076}
1077
87f0e418 1078static Job* transaction_add_one_job(Manager *m, JobType type, Unit *unit, bool force, bool *is_new) {
e5b5ae50 1079 Job *j, *f;
60918275
LP
1080 int r;
1081
1082 assert(m);
87f0e418 1083 assert(unit);
60918275 1084
e5b5ae50
LP
1085 /* Looks for an axisting prospective job and returns that. If
1086 * it doesn't exist it is created and added to the prospective
1087 * jobs list. */
60918275 1088
87f0e418 1089 f = hashmap_get(m->transaction_jobs, unit);
60918275 1090
034c6ed7 1091 LIST_FOREACH(transaction, j, f) {
87f0e418 1092 assert(j->unit == unit);
60918275 1093
e5b5ae50
LP
1094 if (j->type == type) {
1095 if (is_new)
1096 *is_new = false;
1097 return j;
1098 }
1099 }
60918275 1100
87f0e418
LP
1101 if (unit->meta.job && unit->meta.job->type == type)
1102 j = unit->meta.job;
1103 else if (!(j = job_new(m, type, unit)))
e5b5ae50 1104 return NULL;
60918275 1105
e5b5ae50
LP
1106 j->generation = 0;
1107 j->marker = NULL;
1108 j->matters_to_anchor = false;
5cb5a6ff 1109 j->forced = force;
60918275 1110
034c6ed7
LP
1111 LIST_PREPEND(Job, transaction, f, j);
1112
87f0e418 1113 if ((r = hashmap_replace(m->transaction_jobs, unit, f)) < 0) {
034c6ed7
LP
1114 job_free(j);
1115 return NULL;
1116 }
1117
e5b5ae50
LP
1118 if (is_new)
1119 *is_new = true;
60918275 1120
23a177ef
LP
1121 log_debug("Added job %s/%s to transaction.", unit_id(unit), job_type_to_string(type));
1122
e5b5ae50
LP
1123 return j;
1124}
11dd41ce 1125
23a177ef 1126void manager_transaction_unlink_job(Manager *m, Job *j, bool delete_dependencies) {
e5b5ae50
LP
1127 assert(m);
1128 assert(j);
11dd41ce 1129
e5b5ae50
LP
1130 if (j->transaction_prev)
1131 j->transaction_prev->transaction_next = j->transaction_next;
1132 else if (j->transaction_next)
87f0e418 1133 hashmap_replace(m->transaction_jobs, j->unit, j->transaction_next);
e5b5ae50 1134 else
87f0e418 1135 hashmap_remove_value(m->transaction_jobs, j->unit, j);
e5b5ae50
LP
1136
1137 if (j->transaction_next)
1138 j->transaction_next->transaction_prev = j->transaction_prev;
1139
1140 j->transaction_prev = j->transaction_next = NULL;
1141
1142 while (j->subject_list)
1143 job_dependency_free(j->subject_list);
1e198baf
LP
1144
1145 while (j->object_list) {
1146 Job *other = j->object_list->matters ? j->object_list->subject : NULL;
1147
e5b5ae50 1148 job_dependency_free(j->object_list);
1e198baf 1149
23a177ef 1150 if (other && delete_dependencies) {
5cb5a6ff 1151 log_debug("Deleting job %s/%s as dependency of job %s/%s",
87f0e418
LP
1152 unit_id(other->unit), job_type_to_string(other->type),
1153 unit_id(j->unit), job_type_to_string(j->type));
23a177ef 1154 transaction_delete_job(m, other, delete_dependencies);
1e198baf
LP
1155 }
1156 }
e5b5ae50
LP
1157}
1158
87f0e418 1159static int transaction_add_job_and_dependencies(Manager *m, JobType type, Unit *unit, Job *by, bool matters, bool force, Job **_ret) {
e5b5ae50 1160 Job *ret;
034c6ed7 1161 Iterator i;
87f0e418 1162 Unit *dep;
e5b5ae50
LP
1163 int r;
1164 bool is_new;
1165
1166 assert(m);
1167 assert(type < _JOB_TYPE_MAX);
87f0e418 1168 assert(unit);
e5b5ae50 1169
87f0e418 1170 if (unit->meta.load_state != UNIT_LOADED)
21b293e8
LP
1171 return -EINVAL;
1172
87f0e418 1173 if (!unit_job_is_applicable(unit, type))
cd2dbd7d
LP
1174 return -EBADR;
1175
e5b5ae50 1176 /* First add the job. */
87f0e418 1177 if (!(ret = transaction_add_one_job(m, type, unit, force, &is_new)))
e5b5ae50
LP
1178 return -ENOMEM;
1179
1180 /* Then, add a link to the job. */
1181 if (!job_dependency_new(by, ret, matters))
1182 return -ENOMEM;
1183
1184 if (is_new) {
1185 /* Finally, recursively add in all dependencies. */
1186 if (type == JOB_START || type == JOB_RELOAD_OR_START) {
87f0e418 1187 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES], i)
542563ba 1188 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, true, force, NULL)) < 0 && r != -EBADR)
e5b5ae50 1189 goto fail;
87f0e418 1190 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_SOFT_REQUIRES], i)
542563ba 1191 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, !force, force, NULL)) < 0 && r != -EBADR)
e5b5ae50 1192 goto fail;
87f0e418 1193 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_WANTS], i)
8b44eabf
LP
1194 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, false, force, NULL)) < 0)
1195 log_warning("Cannot add dependency job for unit %s, ignoring: %s", unit_id(dep), strerror(-r));
87f0e418 1196 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE], i)
542563ba 1197 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, true, force, NULL)) < 0 && r != -EBADR)
e5b5ae50 1198 goto fail;
87f0e418 1199 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_SOFT_REQUISITE], i)
542563ba 1200 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, !force, force, NULL)) < 0 && r != -EBADR)
e5b5ae50 1201 goto fail;
87f0e418 1202 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_CONFLICTS], i)
542563ba 1203 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, dep, ret, true, force, NULL)) < 0 && r != -EBADR)
e5b5ae50
LP
1204 goto fail;
1205
1206 } else if (type == JOB_STOP || type == JOB_RESTART || type == JOB_TRY_RESTART) {
1207
87f0e418 1208 SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRED_BY], i)
542563ba 1209 if ((r = transaction_add_job_and_dependencies(m, type, dep, ret, true, force, NULL)) < 0 && r != -EBADR)
e5b5ae50
LP
1210 goto fail;
1211 }
1212
1213 /* JOB_VERIFY_STARTED, JOB_RELOAD require no dependency handling */
1214 }
60918275 1215
c0dafa48
LP
1216 if (_ret)
1217 *_ret = ret;
1218
60918275
LP
1219 return 0;
1220
1221fail:
e5b5ae50
LP
1222 return r;
1223}
1224
87f0e418 1225int manager_add_job(Manager *m, JobType type, Unit *unit, JobMode mode, bool force, Job **_ret) {
e5b5ae50
LP
1226 int r;
1227 Job *ret;
1228
1229 assert(m);
1230 assert(type < _JOB_TYPE_MAX);
87f0e418 1231 assert(unit);
e5b5ae50 1232 assert(mode < _JOB_MODE_MAX);
60918275 1233
9f04bd52
LP
1234 log_debug("Trying to enqueue job %s/%s", unit_id(unit), job_type_to_string(type));
1235
c0dafa48 1236 if ((r = transaction_add_job_and_dependencies(m, type, unit, NULL, true, force, &ret)) < 0) {
11dd41ce 1237 transaction_abort(m);
e5b5ae50
LP
1238 return r;
1239 }
11dd41ce 1240
e5b5ae50
LP
1241 if ((r = transaction_activate(m, mode)) < 0)
1242 return r;
1243
c0dafa48 1244 log_debug("Enqueued job %s/%s as %u", unit_id(unit), job_type_to_string(type), (unsigned) ret->id);
f50e0a01 1245
e5b5ae50
LP
1246 if (_ret)
1247 *_ret = ret;
60918275 1248
e5b5ae50
LP
1249 return 0;
1250}
60918275 1251
28247076
LP
1252int manager_add_job_by_name(Manager *m, JobType type, const char *name, JobMode mode, bool force, Job **_ret) {
1253 Unit *unit;
1254 int r;
1255
1256 assert(m);
1257 assert(type < _JOB_TYPE_MAX);
1258 assert(name);
1259 assert(mode < _JOB_MODE_MAX);
1260
1261 if ((r = manager_load_unit(m, name, &unit)) < 0)
1262 return r;
1263
1264 return manager_add_job(m, type, unit, mode, force, _ret);
1265}
1266
60918275
LP
1267Job *manager_get_job(Manager *m, uint32_t id) {
1268 assert(m);
1269
1270 return hashmap_get(m->jobs, UINT32_TO_PTR(id));
1271}
1272
87f0e418 1273Unit *manager_get_unit(Manager *m, const char *name) {
60918275
LP
1274 assert(m);
1275 assert(name);
1276
87f0e418 1277 return hashmap_get(m->units, name);
60918275
LP
1278}
1279
c1e1601e 1280unsigned manager_dispatch_load_queue(Manager *m) {
60918275 1281 Meta *meta;
c1e1601e 1282 unsigned n = 0;
60918275
LP
1283
1284 assert(m);
1285
223dabab
LP
1286 /* Make sure we are not run recursively */
1287 if (m->dispatching_load_queue)
c1e1601e 1288 return 0;
223dabab
LP
1289
1290 m->dispatching_load_queue = true;
1291
87f0e418 1292 /* Dispatches the load queue. Takes a unit from the queue and
60918275
LP
1293 * tries to load its data until the queue is empty */
1294
1295 while ((meta = m->load_queue)) {
034c6ed7
LP
1296 assert(meta->in_load_queue);
1297
87f0e418 1298 unit_load(UNIT(meta));
c1e1601e 1299 n++;
60918275
LP
1300 }
1301
223dabab 1302 m->dispatching_load_queue = false;
c1e1601e 1303 return n;
60918275
LP
1304}
1305
0301abf4 1306int manager_load_unit(Manager *m, const char *path, Unit **_ret) {
87f0e418 1307 Unit *ret;
60918275 1308 int r;
0301abf4 1309 const char *name;
60918275
LP
1310
1311 assert(m);
0301abf4 1312 assert(path);
60918275 1313 assert(_ret);
60918275 1314
223dabab 1315 /* This will load the service information files, but not actually
0301abf4
LP
1316 * start any services or anything. */
1317
1318 name = file_name_from_path(path);
60918275 1319
87f0e418 1320 if ((ret = manager_get_unit(m, name))) {
034c6ed7
LP
1321 *_ret = ret;
1322 return 0;
1323 }
60918275 1324
87f0e418 1325 if (!(ret = unit_new(m)))
60918275
LP
1326 return -ENOMEM;
1327
0301abf4 1328 if (is_path(path)) {
6be1e7d5 1329 if (!(ret->meta.fragment_path = strdup(path))) {
0301abf4
LP
1330 unit_free(ret);
1331 return -ENOMEM;
1332 }
1333 }
1334
87f0e418
LP
1335 if ((r = unit_add_name(ret, name)) < 0) {
1336 unit_free(ret);
1ffba6fe 1337 return r;
60918275
LP
1338 }
1339
87f0e418 1340 unit_add_to_load_queue(ret);
c1e1601e
LP
1341 unit_add_to_dbus_queue(ret);
1342
f50e0a01 1343 manager_dispatch_load_queue(m);
60918275 1344
23a177ef 1345 *_ret = unit_follow_merge(ret);
60918275
LP
1346 return 0;
1347}
a66d02c3 1348
cea8e32e 1349void manager_dump_jobs(Manager *s, FILE *f, const char *prefix) {
034c6ed7 1350 Iterator i;
a66d02c3
LP
1351 Job *j;
1352
1353 assert(s);
1354 assert(f);
1355
034c6ed7 1356 HASHMAP_FOREACH(j, s->jobs, i)
cea8e32e 1357 job_dump(j, f, prefix);
a66d02c3
LP
1358}
1359
87f0e418 1360void manager_dump_units(Manager *s, FILE *f, const char *prefix) {
034c6ed7 1361 Iterator i;
87f0e418 1362 Unit *u;
11dd41ce 1363 const char *t;
a66d02c3
LP
1364
1365 assert(s);
1366 assert(f);
1367
87f0e418
LP
1368 HASHMAP_FOREACH_KEY(u, t, s->units, i)
1369 if (unit_id(u) == t)
1370 unit_dump(u, f, prefix);
a66d02c3 1371}
7fad411c
LP
1372
1373void manager_clear_jobs(Manager *m) {
1374 Job *j;
1375
1376 assert(m);
1377
1378 transaction_abort(m);
1379
1380 while ((j = hashmap_first(m->jobs)))
1381 job_free(j);
1382}
83c60c9f 1383
c1e1601e 1384unsigned manager_dispatch_run_queue(Manager *m) {
83c60c9f 1385 Job *j;
c1e1601e 1386 unsigned n = 0;
83c60c9f 1387
034c6ed7 1388 if (m->dispatching_run_queue)
c1e1601e 1389 return 0;
034c6ed7
LP
1390
1391 m->dispatching_run_queue = true;
9152c765 1392
034c6ed7 1393 while ((j = m->run_queue)) {
ac1135be 1394 assert(j->installed);
034c6ed7
LP
1395 assert(j->in_run_queue);
1396
1397 job_run_and_invalidate(j);
c1e1601e 1398 n++;
9152c765 1399 }
034c6ed7
LP
1400
1401 m->dispatching_run_queue = false;
c1e1601e
LP
1402 return n;
1403}
1404
1405unsigned manager_dispatch_dbus_queue(Manager *m) {
1406 Job *j;
1407 Meta *meta;
1408 unsigned n = 0;
1409
1410 assert(m);
1411
1412 if (m->dispatching_dbus_queue)
1413 return 0;
1414
1415 m->dispatching_dbus_queue = true;
1416
1417 while ((meta = m->dbus_unit_queue)) {
23a177ef 1418 assert(meta->in_dbus_queue);
c1e1601e 1419
23a177ef 1420 bus_unit_send_change_signal(UNIT(meta));
c1e1601e
LP
1421 n++;
1422 }
1423
1424 while ((j = m->dbus_job_queue)) {
1425 assert(j->in_dbus_queue);
1426
1427 bus_job_send_change_signal(j);
1428 n++;
1429 }
1430
1431 m->dispatching_dbus_queue = false;
1432 return n;
9152c765
LP
1433}
1434
034c6ed7 1435static int manager_dispatch_sigchld(Manager *m) {
9152c765
LP
1436 assert(m);
1437
1438 for (;;) {
1439 siginfo_t si;
87f0e418 1440 Unit *u;
9152c765
LP
1441
1442 zero(si);
acbb0225
LP
1443 if (waitid(P_ALL, 0, &si, WEXITED|WNOHANG) < 0) {
1444
1445 if (errno == ECHILD)
1446 break;
1447
9152c765 1448 return -errno;
acbb0225 1449 }
9152c765
LP
1450
1451 if (si.si_pid == 0)
1452 break;
1453
034c6ed7
LP
1454 if (si.si_code != CLD_EXITED && si.si_code != CLD_KILLED && si.si_code != CLD_DUMPED)
1455 continue;
1456
94f04347 1457 log_debug("child %llu died (code=%s, status=%i)", (long long unsigned) si.si_pid, sigchld_code_to_string(si.si_code), si.si_status);
acbb0225 1458
87f0e418 1459 if (!(u = hashmap_remove(m->watch_pids, UINT32_TO_PTR(si.si_pid))))
9152c765
LP
1460 continue;
1461
6c1a0478
LP
1462 log_debug("child %llu belongs to %s", (long long unsigned) si.si_pid, unit_id(u));
1463
87f0e418 1464 UNIT_VTABLE(u)->sigchld_event(u, si.si_pid, si.si_code, si.si_status);
9152c765
LP
1465 }
1466
1467 return 0;
1468}
1469
28247076
LP
1470static void manager_start_target(Manager *m, const char *name) {
1471 int r;
1472
1473 if ((r = manager_add_job_by_name(m, JOB_START, name, JOB_REPLACE, true, NULL)) < 0)
1474 log_error("Failed to enqueue %s job: %s", name, strerror(-r));
1475}
1476
b9cd2ec1 1477static int manager_process_signal_fd(Manager *m, bool *quit) {
9152c765
LP
1478 ssize_t n;
1479 struct signalfd_siginfo sfsi;
1480 bool sigchld = false;
1481
1482 assert(m);
1483
1484 for (;;) {
acbb0225 1485 if ((n = read(m->signal_watch.fd, &sfsi, sizeof(sfsi))) != sizeof(sfsi)) {
9152c765
LP
1486
1487 if (n >= 0)
1488 return -EIO;
1489
1490 if (errno == EAGAIN)
acbb0225 1491 break;
9152c765
LP
1492
1493 return -errno;
1494 }
1495
b9cd2ec1
LP
1496 switch (sfsi.ssi_signo) {
1497
7072ced8
LP
1498 case SIGCHLD: {
1499 char *name = NULL;
1500
1501 get_process_name(sfsi.ssi_pid, &name);
1502 log_debug("Got SIGCHLD for process %llu (%s)", (unsigned long long) sfsi.ssi_pid, strna(name));
1503 free(name);
1504
9152c765 1505 sigchld = true;
b9cd2ec1 1506 break;
7072ced8 1507 }
b9cd2ec1
LP
1508
1509 case SIGINT:
6632c602 1510 case SIGTERM:
84e9af1e 1511
28247076
LP
1512 if (m->running_as == MANAGER_INIT) {
1513 manager_start_target(m, SPECIAL_CTRL_ALT_DEL_TARGET);
84e9af1e
LP
1514 break;
1515 }
1516
28247076
LP
1517 *quit = true;
1518 return 0;
84e9af1e 1519
28247076 1520 case SIGWINCH:
84e9af1e 1521
28247076
LP
1522 if (m->running_as == MANAGER_INIT)
1523 manager_start_target(m, SPECIAL_KBREQUEST_TARGET);
84e9af1e 1524
28247076
LP
1525 /* This is a nop on non-init */
1526 break;
84e9af1e 1527
28247076
LP
1528 case SIGPWR:
1529 if (m->running_as == MANAGER_INIT)
1530 manager_start_target(m, SPECIAL_SIGPWR_TARGET);
84e9af1e 1531
28247076 1532 /* This is a nop on non-init */
84e9af1e 1533 break;
6632c602 1534
0398f3da
LP
1535 case SIGUSR1:
1536
1537 printf("→ By units:\n");
1538 manager_dump_units(m, stdout, "\t");
1539
1540 printf("→ By jobs:\n");
1541 manager_dump_jobs(m, stdout, "\t");
1542
1543 break;
1544
6632c602
LP
1545 default:
1546 log_info("Got unhandled signal <%s>.", strsignal(sfsi.ssi_signo));
b9cd2ec1 1547 }
9152c765
LP
1548 }
1549
1550 if (sigchld)
034c6ed7
LP
1551 return manager_dispatch_sigchld(m);
1552
1553 return 0;
1554}
1555
b9cd2ec1 1556static int process_event(Manager *m, struct epoll_event *ev, bool *quit) {
034c6ed7 1557 int r;
acbb0225 1558 Watch *w;
034c6ed7
LP
1559
1560 assert(m);
1561 assert(ev);
1562
acbb0225 1563 assert(w = ev->data.ptr);
034c6ed7 1564
acbb0225 1565 switch (w->type) {
034c6ed7 1566
ef734fd6 1567 case WATCH_SIGNAL:
034c6ed7 1568
acbb0225 1569 /* An incoming signal? */
f94ea366 1570 if (ev->events != EPOLLIN)
acbb0225 1571 return -EINVAL;
034c6ed7 1572
b9cd2ec1 1573 if ((r = manager_process_signal_fd(m, quit)) < 0)
acbb0225 1574 return r;
034c6ed7 1575
acbb0225 1576 break;
034c6ed7 1577
acbb0225 1578 case WATCH_FD:
034c6ed7 1579
acbb0225 1580 /* Some fd event, to be dispatched to the units */
ea430986 1581 UNIT_VTABLE(w->data.unit)->fd_event(w->data.unit, w->fd, ev->events, w);
acbb0225 1582 break;
034c6ed7 1583
acbb0225
LP
1584 case WATCH_TIMER: {
1585 uint64_t v;
1586 ssize_t k;
034c6ed7 1587
acbb0225 1588 /* Some timer event, to be dispatched to the units */
be888ebb 1589 if ((k = read(w->fd, &v, sizeof(v))) != sizeof(v)) {
034c6ed7 1590
acbb0225
LP
1591 if (k < 0 && (errno == EINTR || errno == EAGAIN))
1592 break;
034c6ed7 1593
acbb0225 1594 return k < 0 ? -errno : -EIO;
034c6ed7
LP
1595 }
1596
ea430986 1597 UNIT_VTABLE(w->data.unit)->timer_event(w->data.unit, v, w);
acbb0225
LP
1598 break;
1599 }
1600
ef734fd6
LP
1601 case WATCH_MOUNT:
1602 /* Some mount table change, intended for the mount subsystem */
1603 mount_fd_event(m, ev->events);
1604 break;
1605
f94ea366
LP
1606 case WATCH_UDEV:
1607 /* Some notification from udev, intended for the device subsystem */
1608 device_fd_event(m, ev->events);
1609 break;
1610
ea430986
LP
1611 case WATCH_DBUS_WATCH:
1612 bus_watch_event(m, w, ev->events);
1613 break;
1614
1615 case WATCH_DBUS_TIMEOUT:
1616 bus_timeout_event(m, w, ev->events);
1617 break;
1618
acbb0225
LP
1619 default:
1620 assert_not_reached("Unknown epoll event type.");
034c6ed7 1621 }
9152c765
LP
1622
1623 return 0;
1624}
1625
1626int manager_loop(Manager *m) {
1627 int r;
b9cd2ec1 1628 bool quit = false;
9152c765 1629
ea430986
LP
1630 RATELIMIT_DEFINE(rl, 1*USEC_PER_SEC, 1000);
1631
9152c765
LP
1632 assert(m);
1633
23a177ef 1634 do {
957ca890
LP
1635 struct epoll_event event;
1636 int n;
9152c765 1637
ea430986
LP
1638 if (!ratelimit_test(&rl)) {
1639 /* Yay, something is going seriously wrong, pause a little */
1640 log_warning("Looping too fast. Throttling execution a little.");
1641 sleep(1);
1642 }
1643
23a177ef
LP
1644 if (manager_dispatch_cleanup_queue(m) > 0)
1645 continue;
1646
c1e1601e
LP
1647 if (manager_dispatch_load_queue(m) > 0)
1648 continue;
034c6ed7 1649
c1e1601e
LP
1650 if (manager_dispatch_run_queue(m) > 0)
1651 continue;
1652
1653 if (bus_dispatch(m) > 0)
1654 continue;
1655
1656 if (manager_dispatch_dbus_queue(m) > 0)
ea430986 1657 continue;
ea430986 1658
957ca890 1659 if ((n = epoll_wait(m->epoll_fd, &event, 1, -1)) < 0) {
9152c765
LP
1660
1661 if (errno == -EINTR)
1662 continue;
1663
1664 return -errno;
1665 }
1666
957ca890 1667 assert(n == 1);
b9cd2ec1 1668
957ca890
LP
1669 if ((r = process_event(m, &event, &quit)) < 0)
1670 return r;
23a177ef 1671 } while (!quit);
957ca890 1672
23a177ef 1673 return 0;
83c60c9f 1674}
ea430986
LP
1675
1676int manager_get_unit_from_dbus_path(Manager *m, const char *s, Unit **_u) {
1677 char *n;
1678 Unit *u;
1679
1680 assert(m);
1681 assert(s);
1682 assert(_u);
1683
1684 if (!startswith(s, "/org/freedesktop/systemd1/unit/"))
1685 return -EINVAL;
1686
1687 if (!(n = bus_path_unescape(s+31)))
1688 return -ENOMEM;
1689
1690 u = manager_get_unit(m, n);
1691 free(n);
1692
1693 if (!u)
1694 return -ENOENT;
1695
1696 *_u = u;
1697
1698 return 0;
1699}
86fbf370
LP
1700
1701int manager_get_job_from_dbus_path(Manager *m, const char *s, Job **_j) {
1702 Job *j;
1703 unsigned id;
1704 int r;
1705
1706 assert(m);
1707 assert(s);
1708 assert(_j);
1709
1710 if (!startswith(s, "/org/freedesktop/systemd1/job/"))
1711 return -EINVAL;
1712
1713 if ((r = safe_atou(s + 30, &id)) < 0)
1714 return r;
1715
1716 if (!(j = manager_get_job(m, id)))
1717 return -ENOENT;
1718
1719 *_j = j;
1720
1721 return 0;
1722}
dfcd764e 1723
e537352b
LP
1724static bool manager_utmp_good(Manager *m) {
1725 int r;
1726
1727 assert(m);
1728
1729 if ((r = mount_path_is_mounted(m, _PATH_UTMPX)) <= 0) {
1730
1731 if (r < 0)
1732 log_warning("Failed to determine whether " _PATH_UTMPX " is mounted: %s", strerror(-r));
1733
1734 return false;
1735 }
1736
1737 return true;
1738}
1739
1740void manager_write_utmp_reboot(Manager *m) {
1741 int r;
1742
1743 assert(m);
1744
1745 if (m->utmp_reboot_written)
1746 return;
1747
1748 if (m->running_as != MANAGER_INIT)
1749 return;
1750
1751 if (!manager_utmp_good(m))
1752 return;
1753
1754 if ((r = utmp_put_reboot(m->boot_timestamp)) < 0) {
1755
1756 if (r != -ENOENT && r != -EROFS)
1757 log_warning("Failed to write utmp/wtmp: %s", strerror(-r));
1758
1759 return;
1760 }
1761
1762 m->utmp_reboot_written = true;
1763}
1764
1765void manager_write_utmp_runlevel(Manager *m, Unit *u) {
1766 int runlevel, r;
1767
1768 assert(m);
1769 assert(u);
1770
1771 if (u->meta.type != UNIT_TARGET)
1772 return;
1773
1774 if (m->running_as != MANAGER_INIT)
1775 return;
1776
1777 if (!manager_utmp_good(m))
1778 return;
1779
1780 if ((runlevel = target_get_runlevel(TARGET(u))) <= 0)
1781 return;
1782
1783 if ((r = utmp_put_runlevel(0, runlevel, 0)) < 0) {
1784
1785 if (r != -ENOENT && r != -EROFS)
1786 log_warning("Failed to write utmp/wtmp: %s", strerror(-r));
1787 }
1788}
1789
dfcd764e
LP
1790static const char* const manager_running_as_table[_MANAGER_RUNNING_AS_MAX] = {
1791 [MANAGER_INIT] = "init",
1792 [MANAGER_SYSTEM] = "system",
036643a2 1793 [MANAGER_SESSION] = "session"
dfcd764e
LP
1794};
1795
1796DEFINE_STRING_TABLE_LOOKUP(manager_running_as, ManagerRunningAs);