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