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