]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/manager.c
man: fix man page chapter in Makefile.am
[thirdparty/systemd.git] / src / core / manager.c
CommitLineData
d6c9574f 1/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
60918275 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
5430f7f2
LP
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
a7334b09
LP
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
5430f7f2 16 Lesser General Public License for more details.
a7334b09 17
5430f7f2 18 You should have received a copy of the GNU Lesser General Public License
a7334b09
LP
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>
30#include <sys/poll.h>
e1414003
LP
31#include <sys/reboot.h>
32#include <sys/ioctl.h>
33#include <linux/kd.h>
80876c20
LP
34#include <termios.h>
35#include <fcntl.h>
a16e1123
LP
36#include <sys/types.h>
37#include <sys/stat.h>
fe51822e 38#include <dirent.h>
830f6caa
LP
39
40#ifdef HAVE_AUDIT
4927fcae 41#include <libaudit.h>
830f6caa 42#endif
60918275 43
81527be1
LP
44#include <systemd/sd-daemon.h>
45
60918275 46#include "manager.h"
75778e21 47#include "transaction.h"
60918275
LP
48#include "hashmap.h"
49#include "macro.h"
50#include "strv.h"
16354eff 51#include "log.h"
2a987ee8 52#include "util.h"
49e942b2 53#include "mkdir.h"
ea430986 54#include "ratelimit.h"
8e274523
LP
55#include "cgroup.h"
56#include "mount-setup.h"
9e2f7c11 57#include "unit-name.h"
4139c1b2
LP
58#include "dbus-unit.h"
59#include "dbus-job.h"
1137a57c 60#include "missing.h"
84e3543e 61#include "path-lookup.h"
514f4ef5 62#include "special.h"
398ef8ba 63#include "bus-errors.h"
d06dacd0 64#include "exit-status.h"
5dc4c17f 65#include "virt.h"
e96d6be7 66#include "watchdog.h"
b59e2465 67#include "cgroup-util.h"
9eb977db 68#include "path-util.h"
60918275 69
701cc384
LP
70/* As soon as 16 units are in our GC queue, make sure to run a gc sweep */
71#define GC_QUEUE_ENTRIES_MAX 16
72
73/* As soon as 5s passed since a unit was added to our GC queue, make sure to run a gc sweep */
94b6dfa2 74#define GC_QUEUE_USEC_MAX (10*USEC_PER_SEC)
701cc384 75
8c47c732 76/* Where clients shall send notification messages to */
29252e9e 77#define NOTIFY_SOCKET "@/org/freedesktop/systemd1/notify"
8c47c732
LP
78
79static int manager_setup_notify(Manager *m) {
80 union {
81 struct sockaddr sa;
82 struct sockaddr_un un;
83 } sa;
84 struct epoll_event ev;
29252e9e 85 int one = 1;
8c47c732
LP
86
87 assert(m);
88
89 m->notify_watch.type = WATCH_NOTIFY;
29252e9e
LP
90 m->notify_watch.fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
91 if (m->notify_watch.fd < 0) {
8c47c732
LP
92 log_error("Failed to allocate notification socket: %m");
93 return -errno;
94 }
95
96 zero(sa);
97 sa.sa.sa_family = AF_UNIX;
98
a821caaa 99 if (getpid() != 1)
29252e9e
LP
100 snprintf(sa.un.sun_path, sizeof(sa.un.sun_path), NOTIFY_SOCKET "/%llu", random_ull());
101 else
102 strncpy(sa.un.sun_path, NOTIFY_SOCKET, sizeof(sa.un.sun_path));
8c47c732 103
29252e9e 104 sa.un.sun_path[0] = 0;
1d6702e8 105
29252e9e 106 if (bind(m->notify_watch.fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + 1 + strlen(sa.un.sun_path+1)) < 0) {
8c47c732
LP
107 log_error("bind() failed: %m");
108 return -errno;
109 }
110
111 if (setsockopt(m->notify_watch.fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one)) < 0) {
112 log_error("SO_PASSCRED failed: %m");
113 return -errno;
114 }
115
116 zero(ev);
117 ev.events = EPOLLIN;
118 ev.data.ptr = &m->notify_watch;
119
120 if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->notify_watch.fd, &ev) < 0)
121 return -errno;
122
29252e9e
LP
123 sa.un.sun_path[0] = '@';
124 m->notify_socket = strdup(sa.un.sun_path);
125 if (!m->notify_socket)
8c47c732
LP
126 return -ENOMEM;
127
b2bb3dbe
LP
128 log_debug("Using notification socket %s", m->notify_socket);
129
8c47c732
LP
130 return 0;
131}
132
80876c20 133static int enable_special_signals(Manager *m) {
4466ee6a 134 int fd;
80876c20
LP
135
136 assert(m);
137
a41b539e
LP
138 /* Enable that we get SIGINT on control-alt-del. In containers
139 * this will fail with EPERM, so ignore that. */
140 if (reboot(RB_DISABLE_CAD) < 0 && errno != EPERM)
80876c20
LP
141 log_warning("Failed to enable ctrl-alt-del handling: %m");
142
a41b539e
LP
143 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
144 if (fd < 0) {
145 /* Support systems without virtual console */
146 if (fd != -ENOENT)
147 log_warning("Failed to open /dev/tty0: %m");
148 } else {
80876c20
LP
149 /* Enable that we get SIGWINCH on kbrequest */
150 if (ioctl(fd, KDSIGACCEPT, SIGWINCH) < 0)
151 log_warning("Failed to enable kbrequest handling: %s", strerror(errno));
152
153 close_nointr_nofail(fd);
154 }
155
156 return 0;
157}
158
ce578209 159static int manager_setup_signals(Manager *m) {
9152c765
LP
160 sigset_t mask;
161 struct epoll_event ev;
57c0c30e 162 struct sigaction sa;
60918275 163
ce578209
LP
164 assert(m);
165
57c0c30e
LP
166 /* We are not interested in SIGSTOP and friends. */
167 zero(sa);
168 sa.sa_handler = SIG_DFL;
169 sa.sa_flags = SA_NOCLDSTOP|SA_RESTART;
170 assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);
171
ce578209 172 assert_se(sigemptyset(&mask) == 0);
7d793605
LP
173
174 sigset_add_many(&mask,
175 SIGCHLD, /* Child died */
176 SIGTERM, /* Reexecute daemon */
177 SIGHUP, /* Reload configuration */
178 SIGUSR1, /* systemd/upstart: reconnect to D-Bus */
179 SIGUSR2, /* systemd: dump status */
180 SIGINT, /* Kernel sends us this on control-alt-del */
181 SIGWINCH, /* Kernel sends us this on kbrequest (alt-arrowup) */
182 SIGPWR, /* Some kernel drivers and upsd send us this on power failure */
183 SIGRTMIN+0, /* systemd: start default.target */
0003d1ab 184 SIGRTMIN+1, /* systemd: isolate rescue.target */
7d793605
LP
185 SIGRTMIN+2, /* systemd: isolate emergency.target */
186 SIGRTMIN+3, /* systemd: start halt.target */
187 SIGRTMIN+4, /* systemd: start poweroff.target */
188 SIGRTMIN+5, /* systemd: start reboot.target */
0003d1ab
LP
189 SIGRTMIN+6, /* systemd: start kexec.target */
190 SIGRTMIN+13, /* systemd: Immediate halt */
191 SIGRTMIN+14, /* systemd: Immediate poweroff */
192 SIGRTMIN+15, /* systemd: Immediate reboot */
193 SIGRTMIN+16, /* systemd: Immediate kexec */
0658666b
LP
194 SIGRTMIN+20, /* systemd: enable status messages */
195 SIGRTMIN+21, /* systemd: disable status messages */
253ee27a
LP
196 SIGRTMIN+22, /* systemd: set log level to LOG_DEBUG */
197 SIGRTMIN+23, /* systemd: set log level to LOG_INFO */
4cfa2c99 198 SIGRTMIN+26, /* systemd: set log target to journal-or-kmsg */
253ee27a
LP
199 SIGRTMIN+27, /* systemd: set log target to console */
200 SIGRTMIN+28, /* systemd: set log target to kmsg */
201 SIGRTMIN+29, /* systemd: set log target to syslog-or-kmsg */
7d793605 202 -1);
ce578209
LP
203 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
204
ef734fd6 205 m->signal_watch.type = WATCH_SIGNAL;
ce578209
LP
206 if ((m->signal_watch.fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0)
207 return -errno;
208
209 zero(ev);
210 ev.events = EPOLLIN;
211 ev.data.ptr = &m->signal_watch;
212
213 if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->signal_watch.fd, &ev) < 0)
214 return -errno;
215
a3d4e06d 216 if (m->running_as == MANAGER_SYSTEM)
80876c20 217 return enable_special_signals(m);
e1414003 218
ce578209
LP
219 return 0;
220}
221
71ecc858
LP
222static void manager_strip_environment(Manager *m) {
223 assert(m);
224
225 /* Remove variables from the inherited set that are part of
226 * the container interface:
227 * http://www.freedesktop.org/wiki/Software/systemd/ContainerInterface */
228 strv_remove_prefix(m->environment, "container=");
229 strv_remove_prefix(m->environment, "container_");
230
231 /* Remove variables from the inherited set that are part of
232 * the initrd interface:
233 * http://www.freedesktop.org/wiki/Software/systemd/InitrdInterface */
234 strv_remove_prefix(m->environment, "RD_");
235}
236
9e58ff9c 237int manager_new(ManagerRunningAs running_as, Manager **_m) {
ce578209 238 Manager *m;
8e274523
LP
239 int r = -ENOMEM;
240
241 assert(_m);
a5dab5ce
LP
242 assert(running_as >= 0);
243 assert(running_as < _MANAGER_RUNNING_AS_MAX);
ce578209 244
60918275 245 if (!(m = new0(Manager, 1)))
8e274523 246 return -ENOMEM;
60918275 247
63983207 248 dual_timestamp_get(&m->startup_timestamp);
e537352b 249
a5dab5ce 250 m->running_as = running_as;
cbd37330 251 m->name_data_slot = m->conn_data_slot = m->subscribed_data_slot = -1;
a16e1123 252 m->exit_code = _MANAGER_EXIT_CODE_INVALID;
33be102a 253 m->pin_cgroupfs_fd = -1;
f2b68789 254 m->idle_pipe[0] = m->idle_pipe[1] = -1;
80876c20 255
4927fcae
LP
256#ifdef HAVE_AUDIT
257 m->audit_fd = -1;
258#endif
259
4e434314 260 m->signal_watch.fd = m->mount_watch.fd = m->udev_watch.fd = m->epoll_fd = m->dev_autofs_fd = m->swap_watch.fd = -1;
ea430986 261 m->current_job_id = 1; /* start as id #1, so that we can leave #0 around as "null-like" value */
9152c765 262
71ecc858
LP
263 m->environment = strv_copy(environ);
264 if (!m->environment)
1137a57c
LP
265 goto fail;
266
71ecc858
LP
267 manager_strip_environment(m);
268
88f06645
LP
269 if (running_as == MANAGER_SYSTEM) {
270 m->default_controllers = strv_new("cpu", NULL);
271 if (!m->default_controllers)
272 goto fail;
273 }
06d4c99a 274
87f0e418 275 if (!(m->units = hashmap_new(string_hash_func, string_compare_func)))
60918275
LP
276 goto fail;
277
278 if (!(m->jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
279 goto fail;
280
9152c765
LP
281 if (!(m->watch_pids = hashmap_new(trivial_hash_func, trivial_compare_func)))
282 goto fail;
283
8e274523
LP
284 if (!(m->cgroup_bondings = hashmap_new(string_hash_func, string_compare_func)))
285 goto fail;
286
05e343b7
LP
287 if (!(m->watch_bus = hashmap_new(string_hash_func, string_compare_func)))
288 goto fail;
289
9152c765
LP
290 if ((m->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0)
291 goto fail;
292
8e274523
LP
293 if ((r = manager_setup_signals(m)) < 0)
294 goto fail;
295
8e274523 296 if ((r = manager_setup_cgroup(m)) < 0)
9152c765
LP
297 goto fail;
298
8c47c732
LP
299 if ((r = manager_setup_notify(m)) < 0)
300 goto fail;
301
f278026d 302 /* Try to connect to the busses, if possible. */
3996fbe2 303 if ((r = bus_init(m, running_as != MANAGER_SYSTEM)) < 0)
ea430986
LP
304 goto fail;
305
e543deae 306#ifdef HAVE_AUDIT
5a8d081c
JN
307 if ((m->audit_fd = audit_open()) < 0 &&
308 /* If the kernel lacks netlink or audit support,
309 * don't worry about it. */
310 errno != EAFNOSUPPORT && errno != EPROTONOSUPPORT)
4927fcae 311 log_error("Failed to connect to audit log: %m");
e543deae 312#endif
4927fcae 313
72bc8d00
LP
314 m->taint_usr = dir_is_empty("/usr") > 0;
315
8e274523
LP
316 *_m = m;
317 return 0;
60918275
LP
318
319fail:
320 manager_free(m);
8e274523 321 return r;
60918275
LP
322}
323
23a177ef 324static unsigned manager_dispatch_cleanup_queue(Manager *m) {
595ed347 325 Unit *u;
23a177ef
LP
326 unsigned n = 0;
327
328 assert(m);
329
595ed347
MS
330 while ((u = m->cleanup_queue)) {
331 assert(u->in_cleanup_queue);
23a177ef 332
595ed347 333 unit_free(u);
23a177ef
LP
334 n++;
335 }
336
337 return n;
338}
339
eced69b3 340enum {
35b8ca3a 341 GC_OFFSET_IN_PATH, /* This one is on the path we were traveling */
eced69b3
LP
342 GC_OFFSET_UNSURE, /* No clue */
343 GC_OFFSET_GOOD, /* We still need this unit */
344 GC_OFFSET_BAD, /* We don't need this unit anymore */
345 _GC_OFFSET_MAX
346};
347
348static void unit_gc_sweep(Unit *u, unsigned gc_marker) {
701cc384
LP
349 Iterator i;
350 Unit *other;
eced69b3 351 bool is_bad;
701cc384
LP
352
353 assert(u);
354
ac155bb8
MS
355 if (u->gc_marker == gc_marker + GC_OFFSET_GOOD ||
356 u->gc_marker == gc_marker + GC_OFFSET_BAD ||
357 u->gc_marker == gc_marker + GC_OFFSET_IN_PATH)
701cc384
LP
358 return;
359
ac155bb8 360 if (u->in_cleanup_queue)
701cc384
LP
361 goto bad;
362
363 if (unit_check_gc(u))
364 goto good;
365
ac155bb8 366 u->gc_marker = gc_marker + GC_OFFSET_IN_PATH;
eced69b3
LP
367
368 is_bad = true;
369
ac155bb8 370 SET_FOREACH(other, u->dependencies[UNIT_REFERENCED_BY], i) {
701cc384
LP
371 unit_gc_sweep(other, gc_marker);
372
ac155bb8 373 if (other->gc_marker == gc_marker + GC_OFFSET_GOOD)
701cc384 374 goto good;
eced69b3 375
ac155bb8 376 if (other->gc_marker != gc_marker + GC_OFFSET_BAD)
eced69b3 377 is_bad = false;
701cc384
LP
378 }
379
eced69b3
LP
380 if (is_bad)
381 goto bad;
382
383 /* We were unable to find anything out about this entry, so
384 * let's investigate it later */
ac155bb8 385 u->gc_marker = gc_marker + GC_OFFSET_UNSURE;
eced69b3
LP
386 unit_add_to_gc_queue(u);
387 return;
388
701cc384 389bad:
eced69b3
LP
390 /* We definitely know that this one is not useful anymore, so
391 * let's mark it for deletion */
ac155bb8 392 u->gc_marker = gc_marker + GC_OFFSET_BAD;
eced69b3 393 unit_add_to_cleanup_queue(u);
701cc384
LP
394 return;
395
396good:
ac155bb8 397 u->gc_marker = gc_marker + GC_OFFSET_GOOD;
701cc384
LP
398}
399
400static unsigned manager_dispatch_gc_queue(Manager *m) {
595ed347 401 Unit *u;
701cc384 402 unsigned n = 0;
eced69b3 403 unsigned gc_marker;
701cc384
LP
404
405 assert(m);
406
407 if ((m->n_in_gc_queue < GC_QUEUE_ENTRIES_MAX) &&
408 (m->gc_queue_timestamp <= 0 ||
409 (m->gc_queue_timestamp + GC_QUEUE_USEC_MAX) > now(CLOCK_MONOTONIC)))
410 return 0;
411
412 log_debug("Running GC...");
413
eced69b3
LP
414 m->gc_marker += _GC_OFFSET_MAX;
415 if (m->gc_marker + _GC_OFFSET_MAX <= _GC_OFFSET_MAX)
c9c0cadb 416 m->gc_marker = 1;
701cc384 417
eced69b3
LP
418 gc_marker = m->gc_marker;
419
595ed347
MS
420 while ((u = m->gc_queue)) {
421 assert(u->in_gc_queue);
701cc384 422
595ed347 423 unit_gc_sweep(u, gc_marker);
eced69b3 424
595ed347
MS
425 LIST_REMOVE(Unit, gc_queue, m->gc_queue, u);
426 u->in_gc_queue = false;
701cc384
LP
427
428 n++;
429
595ed347
MS
430 if (u->gc_marker == gc_marker + GC_OFFSET_BAD ||
431 u->gc_marker == gc_marker + GC_OFFSET_UNSURE) {
432 log_debug("Collecting %s", u->id);
433 u->gc_marker = gc_marker + GC_OFFSET_BAD;
434 unit_add_to_cleanup_queue(u);
701cc384
LP
435 }
436 }
437
438 m->n_in_gc_queue = 0;
439 m->gc_queue_timestamp = 0;
440
441 return n;
442}
443
a16e1123 444static void manager_clear_jobs_and_units(Manager *m) {
a16e1123 445 Unit *u;
60918275
LP
446
447 assert(m);
448
87f0e418
LP
449 while ((u = hashmap_first(m->units)))
450 unit_free(u);
964e0949
LP
451
452 manager_dispatch_cleanup_queue(m);
453
454 assert(!m->load_queue);
455 assert(!m->run_queue);
456 assert(!m->dbus_unit_queue);
457 assert(!m->dbus_job_queue);
458 assert(!m->cleanup_queue);
459 assert(!m->gc_queue);
460
964e0949
LP
461 assert(hashmap_isempty(m->jobs));
462 assert(hashmap_isempty(m->units));
a16e1123
LP
463}
464
465void manager_free(Manager *m) {
466 UnitType c;
c93ff2e9 467 int i;
87f0e418 468
a16e1123
LP
469 assert(m);
470
471 manager_clear_jobs_and_units(m);
23a177ef 472
7824bbeb
LP
473 for (c = 0; c < _UNIT_TYPE_MAX; c++)
474 if (unit_vtable[c]->shutdown)
475 unit_vtable[c]->shutdown(m);
476
a16e1123
LP
477 /* If we reexecute ourselves, we keep the root cgroup
478 * around */
c6c18be3 479 manager_shutdown_cgroup(m, m->exit_code != MANAGER_REEXECUTE);
8e274523 480
5a1e9937
LP
481 manager_undo_generators(m);
482
5e8d1c9a 483 bus_done(m);
ea430986 484
87f0e418 485 hashmap_free(m->units);
60918275 486 hashmap_free(m->jobs);
9152c765 487 hashmap_free(m->watch_pids);
05e343b7 488 hashmap_free(m->watch_bus);
9152c765
LP
489
490 if (m->epoll_fd >= 0)
a16e1123 491 close_nointr_nofail(m->epoll_fd);
acbb0225 492 if (m->signal_watch.fd >= 0)
a16e1123 493 close_nointr_nofail(m->signal_watch.fd);
8c47c732
LP
494 if (m->notify_watch.fd >= 0)
495 close_nointr_nofail(m->notify_watch.fd);
60918275 496
4927fcae
LP
497#ifdef HAVE_AUDIT
498 if (m->audit_fd >= 0)
499 audit_close(m->audit_fd);
500#endif
501
c952c6ec
LP
502 free(m->notify_socket);
503
84e3543e 504 lookup_paths_free(&m->lookup_paths);
1137a57c 505 strv_free(m->environment);
036643a2 506
06d4c99a
LP
507 strv_free(m->default_controllers);
508
8e274523 509 hashmap_free(m->cgroup_bondings);
c6c18be3 510 set_free_free(m->unit_path_cache);
33be102a 511
f2b68789
LP
512 close_pipe(m->idle_pipe);
513
664f88a7
LP
514 free(m->switch_root);
515 free(m->switch_root_init);
516
c93ff2e9
FC
517 for (i = 0; i < RLIMIT_NLIMITS; i++)
518 free(m->rlimit[i]);
519
60918275
LP
520 free(m);
521}
522
a16e1123
LP
523int manager_enumerate(Manager *m) {
524 int r = 0, q;
f50e0a01 525 UnitType c;
f50e0a01
LP
526
527 assert(m);
528
a16e1123
LP
529 /* Let's ask every type to load all units from disk/kernel
530 * that it might know */
f50e0a01
LP
531 for (c = 0; c < _UNIT_TYPE_MAX; c++)
532 if (unit_vtable[c]->enumerate)
a16e1123
LP
533 if ((q = unit_vtable[c]->enumerate(m)) < 0)
534 r = q;
f50e0a01
LP
535
536 manager_dispatch_load_queue(m);
a16e1123
LP
537 return r;
538}
539
540int manager_coldplug(Manager *m) {
541 int r = 0, q;
542 Iterator i;
543 Unit *u;
544 char *k;
545
546 assert(m);
f50e0a01
LP
547
548 /* Then, let's set up their initial state. */
549 HASHMAP_FOREACH_KEY(u, k, m->units, i) {
550
551 /* ignore aliases */
ac155bb8 552 if (u->id != k)
f50e0a01
LP
553 continue;
554
cca098b0
LP
555 if ((q = unit_coldplug(u)) < 0)
556 r = q;
f50e0a01
LP
557 }
558
a16e1123
LP
559 return r;
560}
561
fe51822e
LP
562static void manager_build_unit_path_cache(Manager *m) {
563 char **i;
564 DIR *d = NULL;
565 int r;
566
567 assert(m);
568
569 set_free_free(m->unit_path_cache);
570
571 if (!(m->unit_path_cache = set_new(string_hash_func, string_compare_func))) {
572 log_error("Failed to allocate unit path cache.");
573 return;
574 }
575
576 /* This simply builds a list of files we know exist, so that
577 * we don't always have to go to disk */
578
579 STRV_FOREACH(i, m->lookup_paths.unit_path) {
580 struct dirent *de;
581
582 if (!(d = opendir(*i))) {
583 log_error("Failed to open directory: %m");
584 continue;
585 }
586
587 while ((de = readdir(d))) {
588 char *p;
589
590 if (ignore_file(de->d_name))
591 continue;
592
44d91056
LP
593 p = join(streq(*i, "/") ? "" : *i, "/", de->d_name, NULL);
594 if (!p) {
fe51822e
LP
595 r = -ENOMEM;
596 goto fail;
597 }
598
599 if ((r = set_put(m->unit_path_cache, p)) < 0) {
600 free(p);
601 goto fail;
602 }
603 }
604
605 closedir(d);
606 d = NULL;
607 }
608
609 return;
610
611fail:
612 log_error("Failed to build unit path cache: %s", strerror(-r));
613
614 set_free_free(m->unit_path_cache);
615 m->unit_path_cache = NULL;
616
617 if (d)
618 closedir(d);
619}
620
a16e1123
LP
621int manager_startup(Manager *m, FILE *serialization, FDSet *fds) {
622 int r, q;
623
624 assert(m);
625
5a1e9937
LP
626 manager_run_generators(m);
627
07719a21
LP
628 r = lookup_paths_init(
629 &m->lookup_paths, m->running_as, true,
630 m->generator_unit_path,
631 m->generator_unit_path_early,
632 m->generator_unit_path_late);
633 if (r < 0)
634 return r;
635
fe51822e
LP
636 manager_build_unit_path_cache(m);
637
9f611ad8
LP
638 /* If we will deserialize make sure that during enumeration
639 * this is already known, so we increase the counter here
640 * already */
641 if (serialization)
a7556052 642 m->n_reloading ++;
9f611ad8 643
a16e1123
LP
644 /* First, enumerate what we can from all config files */
645 r = manager_enumerate(m);
646
647 /* Second, deserialize if there is something to deserialize */
07719a21
LP
648 if (serialization) {
649 q = manager_deserialize(m, serialization, fds);
650 if (q < 0)
a16e1123 651 r = q;
07719a21 652 }
a16e1123
LP
653
654 /* Third, fire things up! */
07719a21
LP
655 q = manager_coldplug(m);
656 if (q < 0)
a16e1123
LP
657 r = q;
658
9f611ad8 659 if (serialization) {
a7556052
LP
660 assert(m->n_reloading > 0);
661 m->n_reloading --;
9f611ad8
LP
662 }
663
a16e1123 664 return r;
f50e0a01
LP
665}
666
398ef8ba 667int manager_add_job(Manager *m, JobType type, Unit *unit, JobMode mode, bool override, DBusError *e, Job **_ret) {
e5b5ae50 668 int r;
7527cb52 669 Transaction *tr;
e5b5ae50
LP
670
671 assert(m);
672 assert(type < _JOB_TYPE_MAX);
87f0e418 673 assert(unit);
e5b5ae50 674 assert(mode < _JOB_MODE_MAX);
60918275 675
398ef8ba
LP
676 if (mode == JOB_ISOLATE && type != JOB_START) {
677 dbus_set_error(e, BUS_ERROR_INVALID_JOB_MODE, "Isolate is only valid for start.");
c497c7a9 678 return -EINVAL;
398ef8ba 679 }
c497c7a9 680
ac155bb8 681 if (mode == JOB_ISOLATE && !unit->allow_isolate) {
2528a7a6
LP
682 dbus_set_error(e, BUS_ERROR_NO_ISOLATION, "Operation refused, unit may not be isolated.");
683 return -EPERM;
684 }
685
ac155bb8 686 log_debug("Trying to enqueue job %s/%s/%s", unit->id, job_type_to_string(type), job_mode_to_string(mode));
9f04bd52 687
e0209d83
MS
688 job_type_collapse(&type, unit);
689
7527cb52
MS
690 tr = transaction_new();
691 if (!tr)
692 return -ENOMEM;
11dd41ce 693
7527cb52
MS
694 r = transaction_add_job_and_dependencies(tr, type, unit, NULL, true, override, false,
695 mode == JOB_IGNORE_DEPENDENCIES || mode == JOB_IGNORE_REQUIREMENTS,
b94fbd30 696 mode == JOB_IGNORE_DEPENDENCIES, e);
7527cb52
MS
697 if (r < 0)
698 goto tr_abort;
c497c7a9 699
7527cb52
MS
700 if (mode == JOB_ISOLATE) {
701 r = transaction_add_isolate_jobs(tr, m);
702 if (r < 0)
703 goto tr_abort;
704 }
705
706 r = transaction_activate(tr, m, mode, e);
707 if (r < 0)
708 goto tr_abort;
e5b5ae50 709
b94fbd30 710 log_debug("Enqueued job %s/%s as %u", unit->id, job_type_to_string(type), (unsigned) tr->anchor_job->id);
f50e0a01 711
e5b5ae50 712 if (_ret)
b94fbd30 713 *_ret = tr->anchor_job;
60918275 714
7527cb52 715 transaction_free(tr);
e5b5ae50 716 return 0;
7527cb52
MS
717
718tr_abort:
719 transaction_abort(tr);
720 transaction_free(tr);
721 return r;
e5b5ae50 722}
60918275 723
398ef8ba 724int manager_add_job_by_name(Manager *m, JobType type, const char *name, JobMode mode, bool override, DBusError *e, Job **_ret) {
28247076
LP
725 Unit *unit;
726 int r;
727
728 assert(m);
729 assert(type < _JOB_TYPE_MAX);
730 assert(name);
731 assert(mode < _JOB_MODE_MAX);
732
398ef8ba 733 if ((r = manager_load_unit(m, name, NULL, NULL, &unit)) < 0)
28247076
LP
734 return r;
735
398ef8ba 736 return manager_add_job(m, type, unit, mode, override, e, _ret);
28247076
LP
737}
738
60918275
LP
739Job *manager_get_job(Manager *m, uint32_t id) {
740 assert(m);
741
742 return hashmap_get(m->jobs, UINT32_TO_PTR(id));
743}
744
87f0e418 745Unit *manager_get_unit(Manager *m, const char *name) {
60918275
LP
746 assert(m);
747 assert(name);
748
87f0e418 749 return hashmap_get(m->units, name);
60918275
LP
750}
751
c1e1601e 752unsigned manager_dispatch_load_queue(Manager *m) {
595ed347 753 Unit *u;
c1e1601e 754 unsigned n = 0;
60918275
LP
755
756 assert(m);
757
223dabab
LP
758 /* Make sure we are not run recursively */
759 if (m->dispatching_load_queue)
c1e1601e 760 return 0;
223dabab
LP
761
762 m->dispatching_load_queue = true;
763
87f0e418 764 /* Dispatches the load queue. Takes a unit from the queue and
60918275
LP
765 * tries to load its data until the queue is empty */
766
595ed347
MS
767 while ((u = m->load_queue)) {
768 assert(u->in_load_queue);
034c6ed7 769
595ed347 770 unit_load(u);
c1e1601e 771 n++;
60918275
LP
772 }
773
223dabab 774 m->dispatching_load_queue = false;
c1e1601e 775 return n;
60918275
LP
776}
777
398ef8ba 778int manager_load_unit_prepare(Manager *m, const char *name, const char *path, DBusError *e, Unit **_ret) {
87f0e418 779 Unit *ret;
7d17cfbc 780 UnitType t;
60918275
LP
781 int r;
782
783 assert(m);
9e2f7c11 784 assert(name || path);
60918275 785
db06e3b6
LP
786 /* This will prepare the unit for loading, but not actually
787 * load anything from disk. */
0301abf4 788
398ef8ba
LP
789 if (path && !is_path(path)) {
790 dbus_set_error(e, BUS_ERROR_INVALID_PATH, "Path %s is not absolute.", path);
9e2f7c11 791 return -EINVAL;
398ef8ba 792 }
9e2f7c11
LP
793
794 if (!name)
9eb977db 795 name = path_get_file_name(path);
9e2f7c11 796
7d17cfbc
MS
797 t = unit_name_to_type(name);
798
5f739699 799 if (t == _UNIT_TYPE_INVALID || !unit_name_is_valid(name, false)) {
398ef8ba 800 dbus_set_error(e, BUS_ERROR_INVALID_NAME, "Unit name %s is not valid.", name);
9e2f7c11 801 return -EINVAL;
398ef8ba 802 }
60918275 803
7d17cfbc
MS
804 ret = manager_get_unit(m, name);
805 if (ret) {
034c6ed7 806 *_ret = ret;
413d6313 807 return 1;
034c6ed7 808 }
60918275 809
7d17cfbc
MS
810 ret = unit_new(m, unit_vtable[t]->object_size);
811 if (!ret)
60918275
LP
812 return -ENOMEM;
813
7d17cfbc 814 if (path) {
ac155bb8
MS
815 ret->fragment_path = strdup(path);
816 if (!ret->fragment_path) {
0301abf4
LP
817 unit_free(ret);
818 return -ENOMEM;
819 }
7d17cfbc 820 }
0301abf4 821
87f0e418
LP
822 if ((r = unit_add_name(ret, name)) < 0) {
823 unit_free(ret);
1ffba6fe 824 return r;
60918275
LP
825 }
826
87f0e418 827 unit_add_to_load_queue(ret);
c1e1601e 828 unit_add_to_dbus_queue(ret);
949061f0 829 unit_add_to_gc_queue(ret);
c1e1601e 830
db06e3b6
LP
831 if (_ret)
832 *_ret = ret;
833
834 return 0;
835}
836
398ef8ba 837int manager_load_unit(Manager *m, const char *name, const char *path, DBusError *e, Unit **_ret) {
db06e3b6
LP
838 int r;
839
840 assert(m);
841
842 /* This will load the service information files, but not actually
843 * start any services or anything. */
844
398ef8ba 845 if ((r = manager_load_unit_prepare(m, name, path, e, _ret)) != 0)
db06e3b6
LP
846 return r;
847
f50e0a01 848 manager_dispatch_load_queue(m);
60918275 849
9e2f7c11 850 if (_ret)
413d6313 851 *_ret = unit_follow_merge(*_ret);
9e2f7c11 852
60918275
LP
853 return 0;
854}
a66d02c3 855
cea8e32e 856void manager_dump_jobs(Manager *s, FILE *f, const char *prefix) {
034c6ed7 857 Iterator i;
a66d02c3
LP
858 Job *j;
859
860 assert(s);
861 assert(f);
862
034c6ed7 863 HASHMAP_FOREACH(j, s->jobs, i)
cea8e32e 864 job_dump(j, f, prefix);
a66d02c3
LP
865}
866
87f0e418 867void manager_dump_units(Manager *s, FILE *f, const char *prefix) {
034c6ed7 868 Iterator i;
87f0e418 869 Unit *u;
11dd41ce 870 const char *t;
a66d02c3
LP
871
872 assert(s);
873 assert(f);
874
87f0e418 875 HASHMAP_FOREACH_KEY(u, t, s->units, i)
ac155bb8 876 if (u->id == t)
87f0e418 877 unit_dump(u, f, prefix);
a66d02c3 878}
7fad411c
LP
879
880void manager_clear_jobs(Manager *m) {
881 Job *j;
882
883 assert(m);
884
7fad411c 885 while ((j = hashmap_first(m->jobs)))
5273510e
MS
886 /* No need to recurse. We're cancelling all jobs. */
887 job_finish_and_invalidate(j, JOB_CANCELED, false);
7fad411c 888}
83c60c9f 889
c1e1601e 890unsigned manager_dispatch_run_queue(Manager *m) {
83c60c9f 891 Job *j;
c1e1601e 892 unsigned n = 0;
83c60c9f 893
034c6ed7 894 if (m->dispatching_run_queue)
c1e1601e 895 return 0;
034c6ed7
LP
896
897 m->dispatching_run_queue = true;
9152c765 898
034c6ed7 899 while ((j = m->run_queue)) {
ac1135be 900 assert(j->installed);
034c6ed7
LP
901 assert(j->in_run_queue);
902
903 job_run_and_invalidate(j);
c1e1601e 904 n++;
9152c765 905 }
034c6ed7
LP
906
907 m->dispatching_run_queue = false;
c1e1601e
LP
908 return n;
909}
910
911unsigned manager_dispatch_dbus_queue(Manager *m) {
912 Job *j;
595ed347 913 Unit *u;
c1e1601e
LP
914 unsigned n = 0;
915
916 assert(m);
917
918 if (m->dispatching_dbus_queue)
919 return 0;
920
921 m->dispatching_dbus_queue = true;
922
595ed347
MS
923 while ((u = m->dbus_unit_queue)) {
924 assert(u->in_dbus_queue);
c1e1601e 925
595ed347 926 bus_unit_send_change_signal(u);
c1e1601e
LP
927 n++;
928 }
929
930 while ((j = m->dbus_job_queue)) {
931 assert(j->in_dbus_queue);
932
933 bus_job_send_change_signal(j);
934 n++;
935 }
936
937 m->dispatching_dbus_queue = false;
938 return n;
9152c765
LP
939}
940
8c47c732
LP
941static int manager_process_notify_fd(Manager *m) {
942 ssize_t n;
943
944 assert(m);
945
946 for (;;) {
947 char buf[4096];
948 struct msghdr msghdr;
949 struct iovec iovec;
950 struct ucred *ucred;
951 union {
952 struct cmsghdr cmsghdr;
953 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
954 } control;
955 Unit *u;
956 char **tags;
957
958 zero(iovec);
959 iovec.iov_base = buf;
960 iovec.iov_len = sizeof(buf)-1;
961
962 zero(control);
963 zero(msghdr);
964 msghdr.msg_iov = &iovec;
965 msghdr.msg_iovlen = 1;
966 msghdr.msg_control = &control;
967 msghdr.msg_controllen = sizeof(control);
968
969 if ((n = recvmsg(m->notify_watch.fd, &msghdr, MSG_DONTWAIT)) <= 0) {
970 if (n >= 0)
971 return -EIO;
972
f6144808 973 if (errno == EAGAIN || errno == EINTR)
8c47c732
LP
974 break;
975
976 return -errno;
977 }
978
979 if (msghdr.msg_controllen < CMSG_LEN(sizeof(struct ucred)) ||
980 control.cmsghdr.cmsg_level != SOL_SOCKET ||
981 control.cmsghdr.cmsg_type != SCM_CREDENTIALS ||
982 control.cmsghdr.cmsg_len != CMSG_LEN(sizeof(struct ucred))) {
983 log_warning("Received notify message without credentials. Ignoring.");
984 continue;
985 }
986
987 ucred = (struct ucred*) CMSG_DATA(&control.cmsghdr);
988
c6c18be3 989 if (!(u = hashmap_get(m->watch_pids, LONG_TO_PTR(ucred->pid))))
8c47c732
LP
990 if (!(u = cgroup_unit_by_pid(m, ucred->pid))) {
991 log_warning("Cannot find unit for notify message of PID %lu.", (unsigned long) ucred->pid);
992 continue;
993 }
994
8c40acf7
LP
995 assert((size_t) n < sizeof(buf));
996 buf[n] = 0;
8c47c732
LP
997 if (!(tags = strv_split(buf, "\n\r")))
998 return -ENOMEM;
999
ac155bb8 1000 log_debug("Got notification message for unit %s", u->id);
8c47c732
LP
1001
1002 if (UNIT_VTABLE(u)->notify_message)
c952c6ec 1003 UNIT_VTABLE(u)->notify_message(u, ucred->pid, tags);
8c47c732
LP
1004
1005 strv_free(tags);
1006 }
1007
1008 return 0;
1009}
1010
034c6ed7 1011static int manager_dispatch_sigchld(Manager *m) {
9152c765
LP
1012 assert(m);
1013
1014 for (;;) {
1015 siginfo_t si;
87f0e418 1016 Unit *u;
8c47c732 1017 int r;
9152c765
LP
1018
1019 zero(si);
4112df16
LP
1020
1021 /* First we call waitd() for a PID and do not reap the
1022 * zombie. That way we can still access /proc/$PID for
1023 * it while it is a zombie. */
1024 if (waitid(P_ALL, 0, &si, WEXITED|WNOHANG|WNOWAIT) < 0) {
acbb0225
LP
1025
1026 if (errno == ECHILD)
1027 break;
1028
4112df16
LP
1029 if (errno == EINTR)
1030 continue;
1031
9152c765 1032 return -errno;
acbb0225 1033 }
9152c765 1034
4112df16 1035 if (si.si_pid <= 0)
9152c765
LP
1036 break;
1037
15d5d9d9 1038 if (si.si_code == CLD_EXITED || si.si_code == CLD_KILLED || si.si_code == CLD_DUMPED) {
4112df16
LP
1039 char *name = NULL;
1040
87d2c1ff 1041 get_process_comm(si.si_pid, &name);
bb00e604 1042 log_debug("Got SIGCHLD for process %lu (%s)", (unsigned long) si.si_pid, strna(name));
4112df16
LP
1043 free(name);
1044 }
1045
8c47c732
LP
1046 /* Let's flush any message the dying child might still
1047 * have queued for us. This ensures that the process
1048 * still exists in /proc so that we can figure out
1049 * which cgroup and hence unit it belongs to. */
1050 if ((r = manager_process_notify_fd(m)) < 0)
1051 return r;
1052
1053 /* And now figure out the unit this belongs to */
c6c18be3 1054 if (!(u = hashmap_get(m->watch_pids, LONG_TO_PTR(si.si_pid))))
8c47c732
LP
1055 u = cgroup_unit_by_pid(m, si.si_pid);
1056
4112df16
LP
1057 /* And now, we actually reap the zombie. */
1058 if (waitid(P_PID, si.si_pid, &si, WEXITED) < 0) {
1059 if (errno == EINTR)
1060 continue;
1061
1062 return -errno;
1063 }
1064
034c6ed7
LP
1065 if (si.si_code != CLD_EXITED && si.si_code != CLD_KILLED && si.si_code != CLD_DUMPED)
1066 continue;
1067
bb00e604
LP
1068 log_debug("Child %lu died (code=%s, status=%i/%s)",
1069 (long unsigned) si.si_pid,
4112df16
LP
1070 sigchld_code_to_string(si.si_code),
1071 si.si_status,
d06dacd0
LP
1072 strna(si.si_code == CLD_EXITED
1073 ? exit_status_to_string(si.si_status, EXIT_STATUS_FULL)
1074 : signal_to_string(si.si_status)));
acbb0225 1075
8c47c732 1076 if (!u)
9152c765
LP
1077 continue;
1078
ac155bb8 1079 log_debug("Child %lu belongs to %s", (long unsigned) si.si_pid, u->id);
6c1a0478 1080
c6c18be3 1081 hashmap_remove(m->watch_pids, LONG_TO_PTR(si.si_pid));
87f0e418 1082 UNIT_VTABLE(u)->sigchld_event(u, si.si_pid, si.si_code, si.si_status);
9152c765
LP
1083 }
1084
1085 return 0;
1086}
1087
7d793605 1088static int manager_start_target(Manager *m, const char *name, JobMode mode) {
28247076 1089 int r;
398ef8ba
LP
1090 DBusError error;
1091
1092 dbus_error_init(&error);
1093
af2d49f7 1094 log_debug("Activating special unit %s", name);
1e001f52 1095
398ef8ba
LP
1096 if ((r = manager_add_job_by_name(m, JOB_START, name, mode, true, &error, NULL)) < 0)
1097 log_error("Failed to enqueue %s job: %s", name, bus_error(&error, r));
28247076 1098
398ef8ba 1099 dbus_error_free(&error);
a1b256b0
LP
1100
1101 return r;
28247076
LP
1102}
1103
a16e1123 1104static int manager_process_signal_fd(Manager *m) {
9152c765
LP
1105 ssize_t n;
1106 struct signalfd_siginfo sfsi;
1107 bool sigchld = false;
1108
1109 assert(m);
1110
1111 for (;;) {
acbb0225 1112 if ((n = read(m->signal_watch.fd, &sfsi, sizeof(sfsi))) != sizeof(sfsi)) {
9152c765
LP
1113
1114 if (n >= 0)
1115 return -EIO;
1116
63090775 1117 if (errno == EINTR || errno == EAGAIN)
acbb0225 1118 break;
9152c765
LP
1119
1120 return -errno;
1121 }
1122
67370238
LP
1123 if (sfsi.ssi_pid > 0) {
1124 char *p = NULL;
1125
87d2c1ff 1126 get_process_comm(sfsi.ssi_pid, &p);
dfa7f7e1 1127
67370238 1128 log_debug("Received SIG%s from PID %lu (%s).",
4e240ab0 1129 signal_to_string(sfsi.ssi_signo),
67370238
LP
1130 (unsigned long) sfsi.ssi_pid, strna(p));
1131 free(p);
1132 } else
4e240ab0 1133 log_debug("Received SIG%s.", signal_to_string(sfsi.ssi_signo));
1e001f52 1134
b9cd2ec1
LP
1135 switch (sfsi.ssi_signo) {
1136
4112df16 1137 case SIGCHLD:
9152c765 1138 sigchld = true;
b9cd2ec1
LP
1139 break;
1140
6632c602 1141 case SIGTERM:
a3d4e06d 1142 if (m->running_as == MANAGER_SYSTEM) {
db06e3b6
LP
1143 /* This is for compatibility with the
1144 * original sysvinit */
e11dc4a2 1145 m->exit_code = MANAGER_REEXECUTE;
a1b256b0
LP
1146 break;
1147 }
84e9af1e 1148
a1b256b0 1149 /* Fall through */
e11dc4a2
LP
1150
1151 case SIGINT:
a3d4e06d 1152 if (m->running_as == MANAGER_SYSTEM) {
7d793605 1153 manager_start_target(m, SPECIAL_CTRL_ALT_DEL_TARGET, JOB_REPLACE);
84e9af1e
LP
1154 break;
1155 }
1156
a1b256b0 1157 /* Run the exit target if there is one, if not, just exit. */
0003d1ab 1158 if (manager_start_target(m, SPECIAL_EXIT_TARGET, JOB_REPLACE) < 0) {
a1b256b0
LP
1159 m->exit_code = MANAGER_EXIT;
1160 return 0;
1161 }
1162
1163 break;
84e9af1e 1164
28247076 1165 case SIGWINCH:
a3d4e06d 1166 if (m->running_as == MANAGER_SYSTEM)
7d793605 1167 manager_start_target(m, SPECIAL_KBREQUEST_TARGET, JOB_REPLACE);
84e9af1e 1168
28247076
LP
1169 /* This is a nop on non-init */
1170 break;
84e9af1e 1171
28247076 1172 case SIGPWR:
a3d4e06d 1173 if (m->running_as == MANAGER_SYSTEM)
7d793605 1174 manager_start_target(m, SPECIAL_SIGPWR_TARGET, JOB_REPLACE);
84e9af1e 1175
28247076 1176 /* This is a nop on non-init */
84e9af1e 1177 break;
6632c602 1178
1005d14f 1179 case SIGUSR1: {
57ee42ce
LP
1180 Unit *u;
1181
1182 u = manager_get_unit(m, SPECIAL_DBUS_SERVICE);
1183
1184 if (!u || UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u))) {
1185 log_info("Trying to reconnect to bus...");
3996fbe2 1186 bus_init(m, true);
57ee42ce
LP
1187 }
1188
1189 if (!u || !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u))) {
1190 log_info("Loading D-Bus service...");
7d793605 1191 manager_start_target(m, SPECIAL_DBUS_SERVICE, JOB_REPLACE);
57ee42ce
LP
1192 }
1193
1194 break;
1195 }
1196
2149e37c
LP
1197 case SIGUSR2: {
1198 FILE *f;
1199 char *dump = NULL;
1200 size_t size;
1201
1202 if (!(f = open_memstream(&dump, &size))) {
1203 log_warning("Failed to allocate memory stream.");
1204 break;
1205 }
1206
1207 manager_dump_units(m, f, "\t");
1208 manager_dump_jobs(m, f, "\t");
1209
1210 if (ferror(f)) {
1211 fclose(f);
1212 free(dump);
1213 log_warning("Failed to write status stream");
1214 break;
1215 }
1216
1217 fclose(f);
1218 log_dump(LOG_INFO, dump);
1219 free(dump);
1220
1005d14f 1221 break;
2149e37c 1222 }
1005d14f 1223
a16e1123
LP
1224 case SIGHUP:
1225 m->exit_code = MANAGER_RELOAD;
1226 break;
1227
7d793605 1228 default: {
253ee27a 1229
0003d1ab
LP
1230 /* Starting SIGRTMIN+0 */
1231 static const char * const target_table[] = {
7d793605
LP
1232 [0] = SPECIAL_DEFAULT_TARGET,
1233 [1] = SPECIAL_RESCUE_TARGET,
f057408c 1234 [2] = SPECIAL_EMERGENCY_TARGET,
7d793605
LP
1235 [3] = SPECIAL_HALT_TARGET,
1236 [4] = SPECIAL_POWEROFF_TARGET,
0003d1ab
LP
1237 [5] = SPECIAL_REBOOT_TARGET,
1238 [6] = SPECIAL_KEXEC_TARGET
1239 };
1240
1241 /* Starting SIGRTMIN+13, so that target halt and system halt are 10 apart */
1242 static const ManagerExitCode code_table[] = {
1243 [0] = MANAGER_HALT,
1244 [1] = MANAGER_POWEROFF,
1245 [2] = MANAGER_REBOOT,
1246 [3] = MANAGER_KEXEC
7d793605
LP
1247 };
1248
1249 if ((int) sfsi.ssi_signo >= SIGRTMIN+0 &&
0003d1ab 1250 (int) sfsi.ssi_signo < SIGRTMIN+(int) ELEMENTSOF(target_table)) {
764e9b5f
MS
1251 int idx = (int) sfsi.ssi_signo - SIGRTMIN;
1252 manager_start_target(m, target_table[idx],
1253 (idx == 1 || idx == 2) ? JOB_ISOLATE : JOB_REPLACE);
7d793605
LP
1254 break;
1255 }
1256
0003d1ab
LP
1257 if ((int) sfsi.ssi_signo >= SIGRTMIN+13 &&
1258 (int) sfsi.ssi_signo < SIGRTMIN+13+(int) ELEMENTSOF(code_table)) {
1259 m->exit_code = code_table[sfsi.ssi_signo - SIGRTMIN - 13];
1260 break;
1261 }
1262
0658666b
LP
1263 switch (sfsi.ssi_signo - SIGRTMIN) {
1264
1265 case 20:
1266 log_debug("Enabling showing of status.");
27d340c7 1267 manager_set_show_status(m, true);
0658666b
LP
1268 break;
1269
1270 case 21:
1271 log_debug("Disabling showing of status.");
27d340c7 1272 manager_set_show_status(m, false);
0658666b
LP
1273 break;
1274
253ee27a
LP
1275 case 22:
1276 log_set_max_level(LOG_DEBUG);
1277 log_notice("Setting log level to debug.");
1278 break;
1279
1280 case 23:
1281 log_set_max_level(LOG_INFO);
1282 log_notice("Setting log level to info.");
1283 break;
1284
4cfa2c99
LP
1285 case 26:
1286 log_set_target(LOG_TARGET_JOURNAL_OR_KMSG);
1287 log_notice("Setting log target to journal-or-kmsg.");
1288 break;
1289
253ee27a
LP
1290 case 27:
1291 log_set_target(LOG_TARGET_CONSOLE);
1292 log_notice("Setting log target to console.");
1293 break;
1294
1295 case 28:
1296 log_set_target(LOG_TARGET_KMSG);
1297 log_notice("Setting log target to kmsg.");
1298 break;
1299
1300 case 29:
1301 log_set_target(LOG_TARGET_SYSLOG_OR_KMSG);
1302 log_notice("Setting log target to syslog-or-kmsg.");
1303 break;
1304
0658666b 1305 default:
4e240ab0 1306 log_warning("Got unhandled signal <%s>.", signal_to_string(sfsi.ssi_signo));
0658666b 1307 }
b9cd2ec1 1308 }
7d793605 1309 }
9152c765
LP
1310 }
1311
1312 if (sigchld)
034c6ed7
LP
1313 return manager_dispatch_sigchld(m);
1314
1315 return 0;
1316}
1317
a16e1123 1318static int process_event(Manager *m, struct epoll_event *ev) {
034c6ed7 1319 int r;
acbb0225 1320 Watch *w;
034c6ed7
LP
1321
1322 assert(m);
1323 assert(ev);
1324
3df5bf61 1325 assert_se(w = ev->data.ptr);
034c6ed7 1326
40dde66f
LP
1327 if (w->type == WATCH_INVALID)
1328 return 0;
1329
acbb0225 1330 switch (w->type) {
034c6ed7 1331
ef734fd6 1332 case WATCH_SIGNAL:
034c6ed7 1333
acbb0225 1334 /* An incoming signal? */
f94ea366 1335 if (ev->events != EPOLLIN)
acbb0225 1336 return -EINVAL;
034c6ed7 1337
a16e1123 1338 if ((r = manager_process_signal_fd(m)) < 0)
acbb0225 1339 return r;
034c6ed7 1340
acbb0225 1341 break;
034c6ed7 1342
8c47c732
LP
1343 case WATCH_NOTIFY:
1344
1345 /* An incoming daemon notification event? */
1346 if (ev->events != EPOLLIN)
1347 return -EINVAL;
1348
1349 if ((r = manager_process_notify_fd(m)) < 0)
1350 return r;
1351
1352 break;
1353
acbb0225 1354 case WATCH_FD:
034c6ed7 1355
acbb0225 1356 /* Some fd event, to be dispatched to the units */
ea430986 1357 UNIT_VTABLE(w->data.unit)->fd_event(w->data.unit, w->fd, ev->events, w);
acbb0225 1358 break;
034c6ed7 1359
faf919f1
LP
1360 case WATCH_UNIT_TIMER:
1361 case WATCH_JOB_TIMER: {
acbb0225
LP
1362 uint64_t v;
1363 ssize_t k;
034c6ed7 1364
acbb0225 1365 /* Some timer event, to be dispatched to the units */
be888ebb 1366 if ((k = read(w->fd, &v, sizeof(v))) != sizeof(v)) {
034c6ed7 1367
acbb0225
LP
1368 if (k < 0 && (errno == EINTR || errno == EAGAIN))
1369 break;
034c6ed7 1370
acbb0225 1371 return k < 0 ? -errno : -EIO;
034c6ed7
LP
1372 }
1373
faf919f1
LP
1374 if (w->type == WATCH_UNIT_TIMER)
1375 UNIT_VTABLE(w->data.unit)->timer_event(w->data.unit, v, w);
1376 else
1377 job_timer_event(w->data.job, v, w);
acbb0225
LP
1378 break;
1379 }
1380
ef734fd6
LP
1381 case WATCH_MOUNT:
1382 /* Some mount table change, intended for the mount subsystem */
1383 mount_fd_event(m, ev->events);
1384 break;
1385
4e434314
LP
1386 case WATCH_SWAP:
1387 /* Some swap table change, intended for the swap subsystem */
1388 swap_fd_event(m, ev->events);
1389 break;
1390
f94ea366
LP
1391 case WATCH_UDEV:
1392 /* Some notification from udev, intended for the device subsystem */
1393 device_fd_event(m, ev->events);
1394 break;
1395
ea430986
LP
1396 case WATCH_DBUS_WATCH:
1397 bus_watch_event(m, w, ev->events);
1398 break;
1399
1400 case WATCH_DBUS_TIMEOUT:
1401 bus_timeout_event(m, w, ev->events);
1402 break;
1403
acbb0225 1404 default:
c5fd1e57 1405 log_error("event type=%i", w->type);
acbb0225 1406 assert_not_reached("Unknown epoll event type.");
034c6ed7 1407 }
9152c765
LP
1408
1409 return 0;
1410}
1411
1412int manager_loop(Manager *m) {
1413 int r;
9152c765 1414
fac9f8df 1415 RATELIMIT_DEFINE(rl, 1*USEC_PER_SEC, 50000);
ea430986 1416
9152c765 1417 assert(m);
a16e1123 1418 m->exit_code = MANAGER_RUNNING;
9152c765 1419
fe51822e
LP
1420 /* Release the path cache */
1421 set_free_free(m->unit_path_cache);
1422 m->unit_path_cache = NULL;
1423
b0c918b9
LP
1424 manager_check_finished(m);
1425
a4312405
LP
1426 /* There might still be some zombies hanging around from
1427 * before we were exec()'ed. Leat's reap them */
e96d6be7
LP
1428 r = manager_dispatch_sigchld(m);
1429 if (r < 0)
a4312405
LP
1430 return r;
1431
a16e1123 1432 while (m->exit_code == MANAGER_RUNNING) {
957ca890
LP
1433 struct epoll_event event;
1434 int n;
c757a65b 1435 int wait_msec = -1;
9152c765 1436
c757a65b 1437 if (m->runtime_watchdog > 0 && m->running_as == MANAGER_SYSTEM)
e96d6be7
LP
1438 watchdog_ping();
1439
ea430986
LP
1440 if (!ratelimit_test(&rl)) {
1441 /* Yay, something is going seriously wrong, pause a little */
1442 log_warning("Looping too fast. Throttling execution a little.");
1443 sleep(1);
e96d6be7 1444 continue;
ea430986
LP
1445 }
1446
37a8e683 1447 if (manager_dispatch_load_queue(m) > 0)
23a177ef
LP
1448 continue;
1449
37a8e683 1450 if (manager_dispatch_run_queue(m) > 0)
701cc384
LP
1451 continue;
1452
37a8e683 1453 if (bus_dispatch(m) > 0)
c1e1601e 1454 continue;
034c6ed7 1455
37a8e683 1456 if (manager_dispatch_cleanup_queue(m) > 0)
c1e1601e
LP
1457 continue;
1458
37a8e683 1459 if (manager_dispatch_gc_queue(m) > 0)
c1e1601e
LP
1460 continue;
1461
1462 if (manager_dispatch_dbus_queue(m) > 0)
ea430986 1463 continue;
ea430986 1464
e04aad61
LP
1465 if (swap_dispatch_reload(m) > 0)
1466 continue;
1467
c757a65b
LP
1468 /* Sleep for half the watchdog time */
1469 if (m->runtime_watchdog > 0 && m->running_as == MANAGER_SYSTEM) {
1470 wait_msec = (int) (m->runtime_watchdog / 2 / USEC_PER_MSEC);
1471 if (wait_msec <= 0)
1472 wait_msec = 1;
1473 } else
1474 wait_msec = -1;
1475
e96d6be7
LP
1476 n = epoll_wait(m->epoll_fd, &event, 1, wait_msec);
1477 if (n < 0) {
9152c765 1478
6089f4a9 1479 if (errno == EINTR)
9152c765
LP
1480 continue;
1481
1482 return -errno;
e96d6be7
LP
1483 } else if (n == 0)
1484 continue;
9152c765 1485
957ca890 1486 assert(n == 1);
b9cd2ec1 1487
e96d6be7
LP
1488 r = process_event(m, &event);
1489 if (r < 0)
957ca890 1490 return r;
a16e1123 1491 }
957ca890 1492
a16e1123 1493 return m->exit_code;
83c60c9f 1494}
ea430986 1495
80fbf05e 1496int manager_load_unit_from_dbus_path(Manager *m, const char *s, DBusError *e, Unit **_u) {
ea430986
LP
1497 char *n;
1498 Unit *u;
80fbf05e 1499 int r;
ea430986
LP
1500
1501 assert(m);
1502 assert(s);
1503 assert(_u);
1504
1505 if (!startswith(s, "/org/freedesktop/systemd1/unit/"))
1506 return -EINVAL;
1507
80fbf05e
MS
1508 n = bus_path_unescape(s+31);
1509 if (!n)
ea430986
LP
1510 return -ENOMEM;
1511
80fbf05e 1512 r = manager_load_unit(m, n, NULL, e, &u);
ea430986
LP
1513 free(n);
1514
80fbf05e
MS
1515 if (r < 0)
1516 return r;
ea430986
LP
1517
1518 *_u = u;
1519
1520 return 0;
1521}
86fbf370
LP
1522
1523int manager_get_job_from_dbus_path(Manager *m, const char *s, Job **_j) {
1524 Job *j;
1525 unsigned id;
1526 int r;
1527
1528 assert(m);
1529 assert(s);
1530 assert(_j);
1531
1532 if (!startswith(s, "/org/freedesktop/systemd1/job/"))
1533 return -EINVAL;
1534
1535 if ((r = safe_atou(s + 30, &id)) < 0)
1536 return r;
1537
1538 if (!(j = manager_get_job(m, id)))
1539 return -ENOENT;
1540
1541 *_j = j;
1542
1543 return 0;
1544}
dfcd764e 1545
4927fcae 1546void manager_send_unit_audit(Manager *m, Unit *u, int type, bool success) {
e537352b 1547
4927fcae
LP
1548#ifdef HAVE_AUDIT
1549 char *p;
e537352b 1550
4927fcae 1551 if (m->audit_fd < 0)
e537352b
LP
1552 return;
1553
bbd3a7ba
LP
1554 /* Don't generate audit events if the service was already
1555 * started and we're just deserializing */
a7556052 1556 if (m->n_reloading > 0)
bbd3a7ba
LP
1557 return;
1558
f1dd0c3f
LP
1559 if (m->running_as != MANAGER_SYSTEM)
1560 return;
1561
ac155bb8 1562 if (u->type != UNIT_SERVICE)
f1dd0c3f
LP
1563 return;
1564
ac155bb8 1565 if (!(p = unit_name_to_prefix_and_instance(u->id))) {
4927fcae 1566 log_error("Failed to allocate unit name for audit message: %s", strerror(ENOMEM));
e537352b
LP
1567 return;
1568 }
1569
391ade86 1570 if (audit_log_user_comm_message(m->audit_fd, type, "", p, NULL, NULL, NULL, success) < 0) {
391ade86
LP
1571 if (errno == EPERM) {
1572 /* We aren't allowed to send audit messages?
44785992 1573 * Then let's not retry again. */
391ade86
LP
1574 audit_close(m->audit_fd);
1575 m->audit_fd = -1;
44785992
LP
1576 } else
1577 log_warning("Failed to send audit message: %m");
391ade86 1578 }
e537352b 1579
4927fcae
LP
1580 free(p);
1581#endif
e537352b 1582
e537352b
LP
1583}
1584
e983b760
LP
1585void manager_send_unit_plymouth(Manager *m, Unit *u) {
1586 int fd = -1;
1587 union sockaddr_union sa;
1588 int n = 0;
1589 char *message = NULL;
e983b760
LP
1590
1591 /* Don't generate plymouth events if the service was already
1592 * started and we're just deserializing */
a7556052 1593 if (m->n_reloading > 0)
e983b760
LP
1594 return;
1595
1596 if (m->running_as != MANAGER_SYSTEM)
1597 return;
1598
ac155bb8
MS
1599 if (u->type != UNIT_SERVICE &&
1600 u->type != UNIT_MOUNT &&
1601 u->type != UNIT_SWAP)
e983b760
LP
1602 return;
1603
1604 /* We set SOCK_NONBLOCK here so that we rather drop the
1605 * message then wait for plymouth */
1606 if ((fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0)) < 0) {
1607 log_error("socket() failed: %m");
1608 return;
1609 }
1610
1611 zero(sa);
1612 sa.sa.sa_family = AF_UNIX;
96707269
LP
1613 strncpy(sa.un.sun_path+1, "/org/freedesktop/plymouthd", sizeof(sa.un.sun_path)-1);
1614 if (connect(fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + 1 + strlen(sa.un.sun_path+1)) < 0) {
e983b760
LP
1615
1616 if (errno != EPIPE &&
1617 errno != EAGAIN &&
1618 errno != ENOENT &&
1619 errno != ECONNREFUSED &&
1620 errno != ECONNRESET &&
1621 errno != ECONNABORTED)
1622 log_error("connect() failed: %m");
1623
1624 goto finish;
1625 }
1626
ac155bb8 1627 if (asprintf(&message, "U\002%c%s%n", (int) (strlen(u->id) + 1), u->id, &n) < 0) {
e983b760
LP
1628 log_error("Out of memory");
1629 goto finish;
1630 }
1631
1632 errno = 0;
bd40a2d8 1633 if (write(fd, message, n + 1) != n + 1) {
e983b760
LP
1634
1635 if (errno != EPIPE &&
1636 errno != EAGAIN &&
1637 errno != ENOENT &&
1638 errno != ECONNREFUSED &&
1639 errno != ECONNRESET &&
1640 errno != ECONNABORTED)
1641 log_error("Failed to write Plymouth message: %m");
1642
1643 goto finish;
1644 }
1645
1646finish:
1647 if (fd >= 0)
1648 close_nointr_nofail(fd);
1649
1650 free(message);
1651}
1652
05e343b7
LP
1653void manager_dispatch_bus_name_owner_changed(
1654 Manager *m,
1655 const char *name,
1656 const char* old_owner,
1657 const char *new_owner) {
1658
1659 Unit *u;
1660
1661 assert(m);
1662 assert(name);
1663
1664 if (!(u = hashmap_get(m->watch_bus, name)))
1665 return;
1666
1667 UNIT_VTABLE(u)->bus_name_owner_change(u, name, old_owner, new_owner);
1668}
1669
1670void manager_dispatch_bus_query_pid_done(
1671 Manager *m,
1672 const char *name,
1673 pid_t pid) {
1674
1675 Unit *u;
1676
1677 assert(m);
1678 assert(name);
1679 assert(pid >= 1);
1680
1681 if (!(u = hashmap_get(m->watch_bus, name)))
1682 return;
1683
1684 UNIT_VTABLE(u)->bus_query_pid_done(u, name, pid);
1685}
1686
d8d5ab98 1687int manager_open_serialization(Manager *m, FILE **_f) {
b925e726 1688 char *path = NULL;
a16e1123
LP
1689 mode_t saved_umask;
1690 int fd;
1691 FILE *f;
1692
1693 assert(_f);
1694
b925e726 1695 if (m->running_as == MANAGER_SYSTEM)
2b583ce6 1696 asprintf(&path, "/run/systemd/dump-%lu-XXXXXX", (unsigned long) getpid());
b925e726
LP
1697 else
1698 asprintf(&path, "/tmp/systemd-dump-%lu-XXXXXX", (unsigned long) getpid());
d8d5ab98 1699
b925e726
LP
1700 if (!path)
1701 return -ENOMEM;
a16e1123
LP
1702
1703 saved_umask = umask(0077);
1704 fd = mkostemp(path, O_RDWR|O_CLOEXEC);
1705 umask(saved_umask);
1706
1707 if (fd < 0) {
1708 free(path);
1709 return -errno;
1710 }
1711
1712 unlink(path);
1713
1714 log_debug("Serializing state to %s", path);
1715 free(path);
1716
da19d5c1 1717 if (!(f = fdopen(fd, "w+")))
a16e1123
LP
1718 return -errno;
1719
1720 *_f = f;
1721
1722 return 0;
1723}
1724
1725int manager_serialize(Manager *m, FILE *f, FDSet *fds) {
1726 Iterator i;
1727 Unit *u;
1728 const char *t;
1729 int r;
1730
1731 assert(m);
1732 assert(f);
1733 assert(fds);
1734
a7556052 1735 m->n_reloading ++;
38c52d46 1736
01d67b43
LP
1737 fprintf(f, "current-job-id=%i\n", m->current_job_id);
1738 fprintf(f, "taint-usr=%s\n", yes_no(m->taint_usr));
33c5fae9
LP
1739 fprintf(f, "n-installed-jobs=%u\n", m->n_installed_jobs);
1740 fprintf(f, "n-failed-jobs=%u\n", m->n_failed_jobs);
01d67b43 1741
e9ddabc2 1742 dual_timestamp_serialize(f, "initrd-timestamp", &m->initrd_timestamp);
f38ed060 1743
26a1efdf 1744 if (!in_initrd()) {
f38ed060
HH
1745 dual_timestamp_serialize(f, "startup-timestamp", &m->startup_timestamp);
1746 dual_timestamp_serialize(f, "finish-timestamp", &m->finish_timestamp);
1747 }
47a483a1 1748
f2382a94
LP
1749 fputc('\n', f);
1750
a16e1123 1751 HASHMAP_FOREACH_KEY(u, t, m->units, i) {
ac155bb8 1752 if (u->id != t)
a16e1123
LP
1753 continue;
1754
1755 if (!unit_can_serialize(u))
1756 continue;
1757
1758 /* Start marker */
ac155bb8 1759 fputs(u->id, f);
a16e1123
LP
1760 fputc('\n', f);
1761
38c52d46 1762 if ((r = unit_serialize(u, f, fds)) < 0) {
a7556052 1763 m->n_reloading --;
a16e1123 1764 return r;
38c52d46 1765 }
a16e1123
LP
1766 }
1767
a7556052
LP
1768 assert(m->n_reloading > 0);
1769 m->n_reloading --;
38c52d46 1770
a16e1123
LP
1771 if (ferror(f))
1772 return -EIO;
1773
b23de6af
LP
1774 r = bus_fdset_add_all(m, fds);
1775 if (r < 0)
1776 return r;
1777
a16e1123
LP
1778 return 0;
1779}
1780
1781int manager_deserialize(Manager *m, FILE *f, FDSet *fds) {
1782 int r = 0;
1783
1784 assert(m);
1785 assert(f);
1786
1787 log_debug("Deserializing state...");
1788
a7556052 1789 m->n_reloading ++;
82c64bf5 1790
10f8e83c 1791 for (;;) {
20c03b7b 1792 char line[LINE_MAX], *l;
10f8e83c
LP
1793
1794 if (!fgets(line, sizeof(line), f)) {
1795 if (feof(f))
1796 r = 0;
1797 else
1798 r = -errno;
1799
1800 goto finish;
1801 }
1802
1803 char_array_0(line);
1804 l = strstrip(line);
1805
1806 if (l[0] == 0)
1807 break;
1808
01d67b43
LP
1809 if (startswith(l, "current-job-id=")) {
1810 uint32_t id;
1811
1812 if (safe_atou32(l+15, &id) < 0)
1813 log_debug("Failed to parse current job id value %s", l+15);
1814 else
1815 m->current_job_id = MAX(m->current_job_id, id);
33c5fae9
LP
1816 } else if (startswith(l, "n-installed-jobs=")) {
1817 uint32_t n;
1818
1819 if (safe_atou32(l+17, &n) < 0)
1820 log_debug("Failed to parse installed jobs counter %s", l+17);
1821 else
1822 m->n_installed_jobs += n;
1823 } else if (startswith(l, "n-failed-jobs=")) {
1824 uint32_t n;
1825
1826 if (safe_atou32(l+14, &n) < 0)
1827 log_debug("Failed to parse failed jobs counter %s", l+14);
1828 else
1829 m->n_failed_jobs += n;
01d67b43
LP
1830 } else if (startswith(l, "taint-usr=")) {
1831 int b;
1832
1833 if ((b = parse_boolean(l+10)) < 0)
1834 log_debug("Failed to parse taint /usr flag %s", l+10);
1835 else
1836 m->taint_usr = m->taint_usr || b;
1837 } else if (startswith(l, "initrd-timestamp="))
e9ddabc2
LP
1838 dual_timestamp_deserialize(l+17, &m->initrd_timestamp);
1839 else if (startswith(l, "startup-timestamp="))
799fd0fd 1840 dual_timestamp_deserialize(l+18, &m->startup_timestamp);
10717a1a 1841 else if (startswith(l, "finish-timestamp="))
799fd0fd 1842 dual_timestamp_deserialize(l+17, &m->finish_timestamp);
10717a1a 1843 else
10f8e83c
LP
1844 log_debug("Unknown serialization item '%s'", l);
1845 }
1846
a16e1123
LP
1847 for (;;) {
1848 Unit *u;
1849 char name[UNIT_NAME_MAX+2];
1850
1851 /* Start marker */
1852 if (!fgets(name, sizeof(name), f)) {
1853 if (feof(f))
10f8e83c
LP
1854 r = 0;
1855 else
1856 r = -errno;
a16e1123 1857
82c64bf5 1858 goto finish;
a16e1123
LP
1859 }
1860
1861 char_array_0(name);
1862
398ef8ba 1863 if ((r = manager_load_unit(m, strstrip(name), NULL, NULL, &u)) < 0)
82c64bf5 1864 goto finish;
a16e1123
LP
1865
1866 if ((r = unit_deserialize(u, f, fds)) < 0)
82c64bf5 1867 goto finish;
a16e1123
LP
1868 }
1869
10f8e83c 1870finish:
82c64bf5
LP
1871 if (ferror(f)) {
1872 r = -EIO;
1873 goto finish;
1874 }
a16e1123 1875
a7556052
LP
1876 assert(m->n_reloading > 0);
1877 m->n_reloading --;
82c64bf5
LP
1878
1879 return r;
a16e1123
LP
1880}
1881
1882int manager_reload(Manager *m) {
1883 int r, q;
1884 FILE *f;
1885 FDSet *fds;
1886
1887 assert(m);
1888
07719a21
LP
1889 r = manager_open_serialization(m, &f);
1890 if (r < 0)
a16e1123
LP
1891 return r;
1892
a7556052 1893 m->n_reloading ++;
38c52d46 1894
07719a21
LP
1895 fds = fdset_new();
1896 if (!fds) {
a7556052 1897 m->n_reloading --;
a16e1123
LP
1898 r = -ENOMEM;
1899 goto finish;
1900 }
1901
07719a21
LP
1902 r = manager_serialize(m, f, fds);
1903 if (r < 0) {
a7556052 1904 m->n_reloading --;
a16e1123 1905 goto finish;
38c52d46 1906 }
a16e1123
LP
1907
1908 if (fseeko(f, 0, SEEK_SET) < 0) {
a7556052 1909 m->n_reloading --;
a16e1123
LP
1910 r = -errno;
1911 goto finish;
1912 }
1913
1914 /* From here on there is no way back. */
1915 manager_clear_jobs_and_units(m);
5a1e9937 1916 manager_undo_generators(m);
84e3543e 1917 lookup_paths_free(&m->lookup_paths);
2ded0c04 1918
07719a21 1919 /* Find new unit paths */
5a1e9937
LP
1920 manager_run_generators(m);
1921
07719a21
LP
1922 q = lookup_paths_init(
1923 &m->lookup_paths, m->running_as, true,
1924 m->generator_unit_path,
1925 m->generator_unit_path_early,
1926 m->generator_unit_path_late);
1927 if (q < 0)
1928 r = q;
1929
5a1e9937
LP
1930 manager_build_unit_path_cache(m);
1931
a16e1123 1932 /* First, enumerate what we can from all config files */
07719a21
LP
1933 q = manager_enumerate(m);
1934 if (q < 0)
a16e1123
LP
1935 r = q;
1936
1937 /* Second, deserialize our stored data */
07719a21
LP
1938 q = manager_deserialize(m, f, fds);
1939 if (q < 0)
a16e1123
LP
1940 r = q;
1941
1942 fclose(f);
1943 f = NULL;
1944
1945 /* Third, fire things up! */
07719a21
LP
1946 q = manager_coldplug(m);
1947 if (q < 0)
a16e1123
LP
1948 r = q;
1949
a7556052
LP
1950 assert(m->n_reloading > 0);
1951 m->n_reloading--;
9f611ad8 1952
a16e1123
LP
1953finish:
1954 if (f)
1955 fclose(f);
1956
1957 if (fds)
1958 fdset_free(fds);
1959
1960 return r;
1961}
1962
9e58ff9c
LP
1963bool manager_is_booting_or_shutting_down(Manager *m) {
1964 Unit *u;
1965
1966 assert(m);
1967
1968 /* Is the initial job still around? */
bacbccb7 1969 if (manager_get_job(m, m->default_unit_job_id))
9e58ff9c
LP
1970 return true;
1971
1972 /* Is there a job for the shutdown target? */
27d340c7
LP
1973 u = manager_get_unit(m, SPECIAL_SHUTDOWN_TARGET);
1974 if (u)
ac155bb8 1975 return !!u->job;
9e58ff9c
LP
1976
1977 return false;
1978}
1979
fdf20a31 1980void manager_reset_failed(Manager *m) {
5632e374
LP
1981 Unit *u;
1982 Iterator i;
1983
1984 assert(m);
1985
1986 HASHMAP_FOREACH(u, m->units, i)
fdf20a31 1987 unit_reset_failed(u);
5632e374
LP
1988}
1989
8f6df3fa
LP
1990bool manager_unit_pending_inactive(Manager *m, const char *name) {
1991 Unit *u;
1992
1993 assert(m);
1994 assert(name);
1995
1996 /* Returns true if the unit is inactive or going down */
8f6df3fa
LP
1997 if (!(u = manager_get_unit(m, name)))
1998 return true;
1999
18ffdfda 2000 return unit_pending_inactive(u);
8f6df3fa
LP
2001}
2002
b0c918b9 2003void manager_check_finished(Manager *m) {
e9ddabc2 2004 char userspace[FORMAT_TIMESPAN_MAX], initrd[FORMAT_TIMESPAN_MAX], kernel[FORMAT_TIMESPAN_MAX], sum[FORMAT_TIMESPAN_MAX];
7ea07dcd 2005 usec_t kernel_usec, initrd_usec, userspace_usec, total_usec;
b0c918b9
LP
2006
2007 assert(m);
2008
f2b68789 2009 if (hashmap_size(m->jobs) > 0)
b0c918b9
LP
2010 return;
2011
f2b68789
LP
2012 /* Notify Type=idle units that we are done now */
2013 close_pipe(m->idle_pipe);
2014
af6da548
LP
2015 /* Turn off confirm spawn now */
2016 m->confirm_spawn = false;
2017
f2b68789 2018 if (dual_timestamp_is_set(&m->finish_timestamp))
b0c918b9
LP
2019 return;
2020
2021 dual_timestamp_get(&m->finish_timestamp);
2022
e03ae661
LP
2023 if (m->running_as == MANAGER_SYSTEM && detect_container(NULL) <= 0) {
2024
18fa6b27
LP
2025 userspace_usec = m->finish_timestamp.monotonic - m->startup_timestamp.monotonic;
2026 total_usec = m->finish_timestamp.monotonic;
2027
e9ddabc2 2028 if (dual_timestamp_is_set(&m->initrd_timestamp)) {
18fa6b27
LP
2029
2030 kernel_usec = m->initrd_timestamp.monotonic;
2031 initrd_usec = m->startup_timestamp.monotonic - m->initrd_timestamp.monotonic;
2032
e9ddabc2 2033 log_info("Startup finished in %s (kernel) + %s (initrd) + %s (userspace) = %s.",
18fa6b27
LP
2034 format_timespan(kernel, sizeof(kernel), kernel_usec),
2035 format_timespan(initrd, sizeof(initrd), initrd_usec),
2036 format_timespan(userspace, sizeof(userspace), userspace_usec),
2037 format_timespan(sum, sizeof(sum), total_usec));
2038 } else {
2039 kernel_usec = m->startup_timestamp.monotonic;
2040 initrd_usec = 0;
2041
e9ddabc2 2042 log_info("Startup finished in %s (kernel) + %s (userspace) = %s.",
18fa6b27
LP
2043 format_timespan(kernel, sizeof(kernel), kernel_usec),
2044 format_timespan(userspace, sizeof(userspace), userspace_usec),
2045 format_timespan(sum, sizeof(sum), total_usec));
2046 }
2047 } else {
2048 userspace_usec = initrd_usec = kernel_usec = 0;
2049 total_usec = m->finish_timestamp.monotonic - m->startup_timestamp.monotonic;
2050
b0c918b9 2051 log_debug("Startup finished in %s.",
18fa6b27
LP
2052 format_timespan(sum, sizeof(sum), total_usec));
2053 }
b0c918b9 2054
18fa6b27 2055 bus_broadcast_finished(m, kernel_usec, initrd_usec, userspace_usec, total_usec);
530345e7
LP
2056
2057 sd_notifyf(false,
2058 "READY=1\nSTATUS=Startup finished in %s.",
2059 format_timespan(sum, sizeof(sum), total_usec));
b0c918b9
LP
2060}
2061
07719a21
LP
2062static int create_generator_dir(Manager *m, char **generator, const char *name) {
2063 char *p;
2064 int r;
2065
2066 assert(m);
2067 assert(generator);
2068 assert(name);
2069
2070 if (*generator)
2071 return 0;
2072
2073 if (m->running_as == MANAGER_SYSTEM && getpid() == 1) {
2074
2075 p = strappend("/run/systemd/", name);
2076 if (!p) {
2077 log_error("Out of memory");
2078 return -ENOMEM;
2079 }
2080
d2e54fae 2081 r = mkdir_p_label(p, 0755);
07719a21
LP
2082 if (r < 0) {
2083 log_error("Failed to create generator directory: %s", strerror(-r));
2084 free(p);
2085 return r;
2086 }
2087 } else {
2088 p = join("/tmp/systemd-", name, ".XXXXXX", NULL);
2089 if (!p) {
2090 log_error("Out of memory");
2091 return -ENOMEM;
2092 }
2093
2094 if (!mkdtemp(p)) {
2095 free(p);
2096 log_error("Failed to create generator directory: %m");
2097 return -errno;
2098 }
2099 }
2100
2101 *generator = p;
2102 return 0;
2103}
2104
2105static void trim_generator_dir(Manager *m, char **generator) {
2106 assert(m);
2107 assert(generator);
2108
2109 if (!*generator)
2110 return;
2111
2112 if (rmdir(*generator) >= 0) {
2113 free(*generator);
2114 *generator = NULL;
2115 }
2116
2117 return;
2118}
2119
5a1e9937
LP
2120void manager_run_generators(Manager *m) {
2121 DIR *d = NULL;
5a1e9937 2122 const char *generator_path;
07719a21 2123 const char *argv[5];
07f8a4aa 2124 mode_t u;
07719a21 2125 int r;
5a1e9937
LP
2126
2127 assert(m);
2128
af2d49f7 2129 generator_path = m->running_as == MANAGER_SYSTEM ? SYSTEM_GENERATOR_PATH : USER_GENERATOR_PATH;
07719a21
LP
2130 d = opendir(generator_path);
2131 if (!d) {
5a1e9937
LP
2132 if (errno == ENOENT)
2133 return;
2134
2135 log_error("Failed to enumerate generator directory: %m");
2136 return;
2137 }
2138
07719a21
LP
2139 r = create_generator_dir(m, &m->generator_unit_path, "generator");
2140 if (r < 0)
2141 goto finish;
f1d19aa4 2142
07719a21
LP
2143 r = create_generator_dir(m, &m->generator_unit_path_early, "generator.early");
2144 if (r < 0)
2145 goto finish;
5a1e9937 2146
07719a21
LP
2147 r = create_generator_dir(m, &m->generator_unit_path_late, "generator.late");
2148 if (r < 0)
2149 goto finish;
5a1e9937 2150
83cc030f
LP
2151 argv[0] = NULL; /* Leave this empty, execute_directory() will fill something in */
2152 argv[1] = m->generator_unit_path;
07719a21
LP
2153 argv[2] = m->generator_unit_path_early;
2154 argv[3] = m->generator_unit_path_late;
2155 argv[4] = NULL;
5a1e9937 2156
07f8a4aa 2157 u = umask(0022);
83cc030f 2158 execute_directory(generator_path, d, (char**) argv);
07f8a4aa 2159 umask(u);
5a1e9937 2160
07719a21
LP
2161 trim_generator_dir(m, &m->generator_unit_path);
2162 trim_generator_dir(m, &m->generator_unit_path_early);
2163 trim_generator_dir(m, &m->generator_unit_path_late);
5a1e9937
LP
2164
2165finish:
2166 if (d)
2167 closedir(d);
5a1e9937
LP
2168}
2169
07719a21 2170static void remove_generator_dir(Manager *m, char **generator) {
5a1e9937 2171 assert(m);
07719a21 2172 assert(generator);
5a1e9937 2173
07719a21 2174 if (!*generator)
5a1e9937
LP
2175 return;
2176
07719a21
LP
2177 strv_remove(m->lookup_paths.unit_path, *generator);
2178 rm_rf(*generator, false, true, false);
5a1e9937 2179
07719a21
LP
2180 free(*generator);
2181 *generator = NULL;
2182}
2183
2184void manager_undo_generators(Manager *m) {
2185 assert(m);
2186
2187 remove_generator_dir(m, &m->generator_unit_path);
2188 remove_generator_dir(m, &m->generator_unit_path_early);
2189 remove_generator_dir(m, &m->generator_unit_path_late);
5a1e9937
LP
2190}
2191
06d4c99a
LP
2192int manager_set_default_controllers(Manager *m, char **controllers) {
2193 char **l;
2194
2195 assert(m);
2196
9156e799
LP
2197 l = strv_copy(controllers);
2198 if (!l)
06d4c99a
LP
2199 return -ENOMEM;
2200
2201 strv_free(m->default_controllers);
2202 m->default_controllers = l;
2203
b59e2465 2204 cg_shorten_controllers(m->default_controllers);
9156e799 2205
06d4c99a
LP
2206 return 0;
2207}
2208
c93ff2e9
FC
2209int manager_set_default_rlimits(Manager *m, struct rlimit **default_rlimit) {
2210 int i;
2211
2212 assert(m);
2213
2214 for (i = 0; i < RLIMIT_NLIMITS; i++) {
07719a21
LP
2215 if (!default_rlimit[i])
2216 continue;
c93ff2e9 2217
07719a21
LP
2218 m->rlimit[i] = newdup(struct rlimit, default_rlimit[i], 1);
2219 if (!m->rlimit[i])
2220 return -ENOMEM;
c93ff2e9
FC
2221 }
2222
2223 return 0;
2224}
2225
4cfa2c99 2226void manager_recheck_journal(Manager *m) {
f1dd0c3f
LP
2227 Unit *u;
2228
2229 assert(m);
2230
2231 if (m->running_as != MANAGER_SYSTEM)
2232 return;
2233
731a676c
LP
2234 u = manager_get_unit(m, SPECIAL_JOURNALD_SOCKET);
2235 if (u && SOCKET(u)->state != SOCKET_RUNNING) {
4cfa2c99 2236 log_close_journal();
731a676c 2237 return;
f1dd0c3f
LP
2238 }
2239
731a676c
LP
2240 u = manager_get_unit(m, SPECIAL_JOURNALD_SERVICE);
2241 if (u && SERVICE(u)->state != SERVICE_RUNNING) {
4cfa2c99 2242 log_close_journal();
731a676c
LP
2243 return;
2244 }
f1dd0c3f 2245
731a676c
LP
2246 /* Hmm, OK, so the socket is fully up and the service is up
2247 * too, then let's make use of the thing. */
f1dd0c3f
LP
2248 log_open();
2249}
2250
27d340c7
LP
2251void manager_set_show_status(Manager *m, bool b) {
2252 assert(m);
2253
2254 if (m->running_as != MANAGER_SYSTEM)
2255 return;
2256
2257 m->show_status = b;
2258
2259 if (b)
2260 touch("/run/systemd/show-status");
2261 else
2262 unlink("/run/systemd/show-status");
2263}
2264
2265bool manager_get_show_status(Manager *m) {
2266 assert(m);
2267
2268 if (m->running_as != MANAGER_SYSTEM)
2269 return false;
2270
2271 if (m->show_status)
2272 return true;
2273
2274 /* If Plymouth is running make sure we show the status, so
2275 * that there's something nice to see when people press Esc */
2276
2277 return plymouth_running();
2278}
2279
dfcd764e 2280static const char* const manager_running_as_table[_MANAGER_RUNNING_AS_MAX] = {
dfcd764e 2281 [MANAGER_SYSTEM] = "system",
af2d49f7 2282 [MANAGER_USER] = "user"
dfcd764e
LP
2283};
2284
2285DEFINE_STRING_TABLE_LOOKUP(manager_running_as, ManagerRunningAs);