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