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