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