]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/manager.c
macro: make sure we can use IN_SET() also with complex function calls as first argument
[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 25#include <signal.h>
9152c765
LP
26#include <sys/wait.h>
27#include <unistd.h>
28#include <sys/poll.h>
e1414003
LP
29#include <sys/reboot.h>
30#include <sys/ioctl.h>
31#include <linux/kd.h>
80876c20
LP
32#include <termios.h>
33#include <fcntl.h>
a16e1123
LP
34#include <sys/types.h>
35#include <sys/stat.h>
fe51822e 36#include <dirent.h>
8742514c 37#include <sys/timerfd.h>
830f6caa
LP
38
39#ifdef HAVE_AUDIT
4927fcae 40#include <libaudit.h>
830f6caa 41#endif
60918275 42
718db961
LP
43#include "sd-daemon.h"
44#include "sd-id128.h"
45#include "sd-messages.h"
81527be1 46
60918275 47#include "manager.h"
75778e21 48#include "transaction.h"
60918275
LP
49#include "hashmap.h"
50#include "macro.h"
51#include "strv.h"
16354eff 52#include "log.h"
2a987ee8 53#include "util.h"
49e942b2 54#include "mkdir.h"
ea430986 55#include "ratelimit.h"
e21fea24 56#include "locale-setup.h"
8e274523 57#include "mount-setup.h"
9e2f7c11 58#include "unit-name.h"
1137a57c 59#include "missing.h"
84e3543e 60#include "path-lookup.h"
514f4ef5 61#include "special.h"
d06dacd0 62#include "exit-status.h"
5dc4c17f 63#include "virt.h"
e96d6be7 64#include "watchdog.h"
b59e2465 65#include "cgroup-util.h"
9eb977db 66#include "path-util.h"
c1165f82 67#include "audit-fd.h"
c51d84dc 68#include "boot-timestamps.h"
8b55b8c4 69#include "env-util.h"
718db961
LP
70#include "bus-errors.h"
71#include "bus-error.h"
72#include "bus-util.h"
73#include "dbus.h"
74#include "dbus-unit.h"
75#include "dbus-job.h"
76#include "dbus-manager.h"
e3dd987c 77#include "bus-kernel.h"
60918275 78
701cc384 79/* As soon as 5s passed since a unit was added to our GC queue, make sure to run a gc sweep */
94b6dfa2 80#define GC_QUEUE_USEC_MAX (10*USEC_PER_SEC)
701cc384 81
03b717a3 82/* Initial delay and the interval for printing status messages about running jobs */
fd08a840
ZJS
83#define JOBS_IN_PROGRESS_WAIT_USEC (5*USEC_PER_SEC)
84#define JOBS_IN_PROGRESS_PERIOD_USEC (USEC_PER_SEC / 3)
03b717a3
MS
85#define JOBS_IN_PROGRESS_PERIOD_DIVISOR 3
86
8c47c732 87/* Where clients shall send notification messages to */
29252e9e 88#define NOTIFY_SOCKET "@/org/freedesktop/systemd1/notify"
8c47c732 89
c3e31c7b
ZJS
90#define TIME_T_MAX (time_t)((1UL << ((sizeof(time_t) << 3) - 1)) - 1)
91
718db961
LP
92static int manager_dispatch_notify_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
93static int manager_dispatch_signal_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
94static int manager_dispatch_time_change_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
95static int manager_dispatch_idle_pipe_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
96static int manager_dispatch_jobs_in_progress(sd_event_source *source, usec_t usec, void *userdata);
752b5905 97static int manager_dispatch_run_queue(sd_event_source *source, void *userdata);
718db961 98
03b717a3 99static int manager_watch_jobs_in_progress(Manager *m) {
e5723c89
ZJS
100 usec_t next;
101
718db961 102 assert(m);
03b717a3 103
718db961 104 if (m->jobs_in_progress_event_source)
03b717a3
MS
105 return 0;
106
e5723c89 107 next = now(CLOCK_MONOTONIC) + JOBS_IN_PROGRESS_WAIT_USEC;
151b9b96 108 return sd_event_add_monotonic(m->event, &m->jobs_in_progress_event_source, next, 0, manager_dispatch_jobs_in_progress, m);
03b717a3
MS
109}
110
718db961 111#define CYLON_BUFFER_EXTRA (2*(sizeof(ANSI_RED_ON)-1) + sizeof(ANSI_HIGHLIGHT_RED_ON)-1 + 2*(sizeof(ANSI_HIGHLIGHT_OFF)-1))
03b717a3 112
03b717a3
MS
113static void draw_cylon(char buffer[], size_t buflen, unsigned width, unsigned pos) {
114 char *p = buffer;
115
116 assert(buflen >= CYLON_BUFFER_EXTRA + width + 1);
117 assert(pos <= width+1); /* 0 or width+1 mean that the center light is behind the corner */
118
119 if (pos > 1) {
6282c859
MS
120 if (pos > 2)
121 p = mempset(p, ' ', pos-2);
5052495b 122 p = stpcpy(p, ANSI_RED_ON);
03b717a3
MS
123 *p++ = '*';
124 }
125
126 if (pos > 0 && pos <= width) {
5052495b 127 p = stpcpy(p, ANSI_HIGHLIGHT_RED_ON);
03b717a3
MS
128 *p++ = '*';
129 }
130
5052495b 131 p = stpcpy(p, ANSI_HIGHLIGHT_OFF);
03b717a3
MS
132
133 if (pos < width) {
5052495b 134 p = stpcpy(p, ANSI_RED_ON);
03b717a3 135 *p++ = '*';
6282c859
MS
136 if (pos < width-1)
137 p = mempset(p, ' ', width-1-pos);
51d122af 138 strcpy(p, ANSI_HIGHLIGHT_OFF);
03b717a3 139 }
03b717a3
MS
140}
141
cb8ccb22 142void manager_flip_auto_status(Manager *m, bool enable) {
f755e3b7
LP
143 assert(m);
144
cb8ccb22
ZJS
145 if (enable) {
146 if (m->show_status == SHOW_STATUS_AUTO)
147 manager_set_show_status(m, SHOW_STATUS_TEMPORARY);
148 } else {
149 if (m->show_status == SHOW_STATUS_TEMPORARY)
150 manager_set_show_status(m, SHOW_STATUS_AUTO);
151 }
152}
153
03b717a3 154static void manager_print_jobs_in_progress(Manager *m) {
718db961 155 _cleanup_free_ char *job_of_n = NULL;
03b717a3
MS
156 Iterator i;
157 Job *j;
03b717a3
MS
158 unsigned counter = 0, print_nr;
159 char cylon[6 + CYLON_BUFFER_EXTRA + 1];
160 unsigned cylon_pos;
8bb310c3
ZJS
161 char time[FORMAT_TIMESPAN_MAX], limit[FORMAT_TIMESPAN_MAX] = "no limit";
162 uint64_t x;
03b717a3 163
718db961
LP
164 assert(m);
165
cb8ccb22 166 manager_flip_auto_status(m, true);
d450b6f2 167
03b717a3
MS
168 print_nr = (m->jobs_in_progress_iteration / JOBS_IN_PROGRESS_PERIOD_DIVISOR) % m->n_running_jobs;
169
170 HASHMAP_FOREACH(j, m->jobs, i)
171 if (j->state == JOB_RUNNING && counter++ == print_nr)
172 break;
173
e970a72e
MS
174 /* m->n_running_jobs must be consistent with the contents of m->jobs,
175 * so the above loop must have succeeded in finding j. */
176 assert(counter == print_nr + 1);
51d122af 177 assert(j);
5a82a91a 178
03b717a3
MS
179 cylon_pos = m->jobs_in_progress_iteration % 14;
180 if (cylon_pos >= 8)
181 cylon_pos = 14 - cylon_pos;
182 draw_cylon(cylon, sizeof(cylon), 6, cylon_pos);
183
8bb310c3
ZJS
184 m->jobs_in_progress_iteration++;
185
03b717a3
MS
186 if (m->n_running_jobs > 1)
187 if (asprintf(&job_of_n, "(%u of %u) ", counter, m->n_running_jobs) < 0)
188 job_of_n = NULL;
189
8bb310c3
ZJS
190 format_timespan(time, sizeof(time), now(CLOCK_MONOTONIC) - j->begin_usec, 1*USEC_PER_SEC);
191 if (job_get_timeout(j, &x) > 0)
192 format_timespan(limit, sizeof(limit), x - j->begin_usec, 1*USEC_PER_SEC);
193
6b02bce7 194 manager_status_printf(m, true, cylon,
8bb310c3
ZJS
195 "%sA %s job is running for %s (%s / %s)",
196 strempty(job_of_n),
197 job_type_to_string(j->type),
198 unit_description(j->unit),
199 time, limit);
03b717a3 200
03b717a3
MS
201}
202
31a7eb86 203static int manager_watch_idle_pipe(Manager *m) {
31a7eb86
ZJS
204 int r;
205
718db961
LP
206 assert(m);
207
208 if (m->idle_pipe_event_source)
31a7eb86
ZJS
209 return 0;
210
211 if (m->idle_pipe[2] < 0)
212 return 0;
213
151b9b96 214 r = sd_event_add_io(m->event, &m->idle_pipe_event_source, m->idle_pipe[2], EPOLLIN, manager_dispatch_idle_pipe_fd, m);
718db961
LP
215 if (r < 0) {
216 log_error("Failed to watch idle pipe: %s", strerror(-r));
217 return r;
31a7eb86
ZJS
218 }
219
31a7eb86 220 return 0;
31a7eb86
ZJS
221}
222
718db961
LP
223static void manager_close_idle_pipe(Manager *m) {
224 assert(m);
31a7eb86 225
718db961
LP
226 close_pipe(m->idle_pipe);
227 close_pipe(m->idle_pipe + 2);
31a7eb86
ZJS
228}
229
8742514c 230static int manager_setup_time_change(Manager *m) {
718db961 231 int r;
b92bea5d
ZJS
232
233 /* We only care for the cancellation event, hence we set the
234 * timeout to the latest possible value. */
235 struct itimerspec its = {
236 .it_value.tv_sec = TIME_T_MAX,
237 };
8742514c 238
718db961
LP
239 assert(m);
240 assert_cc(sizeof(time_t) == sizeof(TIME_T_MAX));
8742514c
LP
241
242 /* Uses TFD_TIMER_CANCEL_ON_SET to get notifications whenever
243 * CLOCK_REALTIME makes a jump relative to CLOCK_MONOTONIC */
244
718db961
LP
245 m->time_change_fd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK|TFD_CLOEXEC);
246 if (m->time_change_fd < 0) {
8742514c
LP
247 log_error("Failed to create timerfd: %m");
248 return -errno;
249 }
250
718db961 251 if (timerfd_settime(m->time_change_fd, TFD_TIMER_ABSTIME|TFD_TIMER_CANCEL_ON_SET, &its, NULL) < 0) {
8742514c 252 log_debug("Failed to set up TFD_TIMER_CANCEL_ON_SET, ignoring: %m");
718db961
LP
253 close_nointr_nofail(m->time_change_fd);
254 m->time_change_fd = -1;
8742514c
LP
255 return 0;
256 }
257
151b9b96 258 r = sd_event_add_io(m->event, &m->time_change_event_source, m->time_change_fd, EPOLLIN, manager_dispatch_time_change_fd, m);
718db961
LP
259 if (r < 0) {
260 log_error("Failed to create time change event source: %s", strerror(-r));
261 return r;
8742514c
LP
262 }
263
264 log_debug("Set up TFD_TIMER_CANCEL_ON_SET timerfd.");
265
266 return 0;
267}
268
80876c20 269static int enable_special_signals(Manager *m) {
718db961 270 _cleanup_close_ int fd = -1;
80876c20
LP
271
272 assert(m);
273
a41b539e 274 /* Enable that we get SIGINT on control-alt-del. In containers
c9999773
LP
275 * this will fail with EPERM (older) or EINVAL (newer), so
276 * ignore that. */
277 if (reboot(RB_DISABLE_CAD) < 0 && errno != EPERM && errno != EINVAL)
80876c20
LP
278 log_warning("Failed to enable ctrl-alt-del handling: %m");
279
a41b539e
LP
280 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
281 if (fd < 0) {
282 /* Support systems without virtual console */
283 if (fd != -ENOENT)
284 log_warning("Failed to open /dev/tty0: %m");
285 } else {
80876c20
LP
286 /* Enable that we get SIGWINCH on kbrequest */
287 if (ioctl(fd, KDSIGACCEPT, SIGWINCH) < 0)
f5f6d0e2 288 log_warning("Failed to enable kbrequest handling: %m");
80876c20
LP
289 }
290
291 return 0;
292}
293
ce578209 294static int manager_setup_signals(Manager *m) {
b92bea5d
ZJS
295 struct sigaction sa = {
296 .sa_handler = SIG_DFL,
297 .sa_flags = SA_NOCLDSTOP|SA_RESTART,
298 };
718db961
LP
299 sigset_t mask;
300 int r;
60918275 301
ce578209
LP
302 assert(m);
303
57c0c30e 304 /* We are not interested in SIGSTOP and friends. */
57c0c30e
LP
305 assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);
306
ce578209 307 assert_se(sigemptyset(&mask) == 0);
7d793605
LP
308
309 sigset_add_many(&mask,
310 SIGCHLD, /* Child died */
311 SIGTERM, /* Reexecute daemon */
312 SIGHUP, /* Reload configuration */
313 SIGUSR1, /* systemd/upstart: reconnect to D-Bus */
314 SIGUSR2, /* systemd: dump status */
315 SIGINT, /* Kernel sends us this on control-alt-del */
316 SIGWINCH, /* Kernel sends us this on kbrequest (alt-arrowup) */
317 SIGPWR, /* Some kernel drivers and upsd send us this on power failure */
318 SIGRTMIN+0, /* systemd: start default.target */
0003d1ab 319 SIGRTMIN+1, /* systemd: isolate rescue.target */
7d793605
LP
320 SIGRTMIN+2, /* systemd: isolate emergency.target */
321 SIGRTMIN+3, /* systemd: start halt.target */
322 SIGRTMIN+4, /* systemd: start poweroff.target */
323 SIGRTMIN+5, /* systemd: start reboot.target */
0003d1ab
LP
324 SIGRTMIN+6, /* systemd: start kexec.target */
325 SIGRTMIN+13, /* systemd: Immediate halt */
326 SIGRTMIN+14, /* systemd: Immediate poweroff */
327 SIGRTMIN+15, /* systemd: Immediate reboot */
328 SIGRTMIN+16, /* systemd: Immediate kexec */
0658666b
LP
329 SIGRTMIN+20, /* systemd: enable status messages */
330 SIGRTMIN+21, /* systemd: disable status messages */
253ee27a
LP
331 SIGRTMIN+22, /* systemd: set log level to LOG_DEBUG */
332 SIGRTMIN+23, /* systemd: set log level to LOG_INFO */
600b704e 333 SIGRTMIN+24, /* systemd: Immediate exit (--user only) */
4cfa2c99 334 SIGRTMIN+26, /* systemd: set log target to journal-or-kmsg */
253ee27a
LP
335 SIGRTMIN+27, /* systemd: set log target to console */
336 SIGRTMIN+28, /* systemd: set log target to kmsg */
337 SIGRTMIN+29, /* systemd: set log target to syslog-or-kmsg */
7d793605 338 -1);
ce578209
LP
339 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
340
718db961
LP
341 m->signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
342 if (m->signal_fd < 0)
ce578209
LP
343 return -errno;
344
151b9b96 345 r = sd_event_add_io(m->event, &m->signal_event_source, m->signal_fd, EPOLLIN, manager_dispatch_signal_fd, m);
718db961
LP
346 if (r < 0)
347 return r;
ce578209 348
fa28bc2d
LP
349 /* Process signals a bit earlier than the rest of things, but
350 * later that notify_fd processing, so that the notify
351 * processing can still figure out to which process/service a
352 * message belongs, before we reap the process. */
29083707
LP
353 r = sd_event_source_set_priority(m->signal_event_source, -5);
354 if (r < 0)
355 return r;
356
67445f4e 357 if (m->running_as == SYSTEMD_SYSTEM)
80876c20 358 return enable_special_signals(m);
e1414003 359
ce578209
LP
360 return 0;
361}
362
f069efb4
LP
363static void manager_clean_environment(Manager *m) {
364 assert(m);
365
366 /* Let's remove some environment variables that we
367 * need ourselves to communicate with our clients */
368 strv_env_unset_many(
369 m->environment,
370 "NOTIFY_SOCKET",
371 "MAINPID",
372 "MANAGERPID",
373 "LISTEN_PID",
374 "LISTEN_FDS",
375 "WATCHDOG_PID",
376 "WATCHDOG_USEC",
377 NULL);
378}
379
e21fea24 380static int manager_default_environment(Manager *m) {
71ecc858
LP
381 assert(m);
382
e21fea24
KS
383 if (m->running_as == SYSTEMD_SYSTEM) {
384 /* The system manager always starts with a clean
385 * environment for its children. It does not import
386 * the kernel or the parents exported variables.
387 *
388 * The initial passed environ is untouched to keep
389 * /proc/self/environ valid; it is used for tagging
390 * the init process inside containers. */
43638332
ZJS
391 m->environment = strv_new("PATH=" DEFAULT_PATH,
392 NULL);
e21fea24
KS
393
394 /* Import locale variables LC_*= from configuration */
395 locale_setup(&m->environment);
43d03a83 396 } else {
e21fea24
KS
397 /* The user manager passes its own environment
398 * along to its children. */
399 m->environment = strv_copy(environ);
43d03a83
LP
400 }
401
e21fea24
KS
402 if (!m->environment)
403 return -ENOMEM;
8b55b8c4 404
f069efb4 405 manager_clean_environment(m);
9d5a3757
LP
406 strv_sort(m->environment);
407
e21fea24 408 return 0;
71ecc858
LP
409}
410
e3dd987c 411int manager_new(SystemdRunningAs running_as, Manager **_m) {
ce578209 412 Manager *m;
e3dd987c 413 int r;
8e274523
LP
414
415 assert(_m);
a5dab5ce 416 assert(running_as >= 0);
67445f4e 417 assert(running_as < _SYSTEMD_RUNNING_AS_MAX);
ce578209 418
915b3753
LP
419 m = new0(Manager, 1);
420 if (!m)
8e274523 421 return -ENOMEM;
60918275 422
4f8d551f
ZC
423#ifdef ENABLE_EFI
424 if (detect_container(NULL) <= 0)
c51d84dc 425 boot_timestamps(&m->userspace_timestamp, &m->firmware_timestamp, &m->loader_timestamp);
4f8d551f
ZC
426#endif
427
a5dab5ce 428 m->running_as = running_as;
a16e1123 429 m->exit_code = _MANAGER_EXIT_CODE_INVALID;
80876c20 430
718db961 431 m->idle_pipe[0] = m->idle_pipe[1] = m->idle_pipe[2] = m->idle_pipe[3] = -1;
8742514c 432
e3dd987c 433 m->pin_cgroupfs_fd = m->notify_fd = m->signal_fd = m->time_change_fd = m->dev_autofs_fd = m->private_listen_fd = m->kdbus_fd = -1;
ea430986 434 m->current_job_id = 1; /* start as id #1, so that we can leave #0 around as "null-like" value */
9152c765 435
e21fea24
KS
436 r = manager_default_environment(m);
437 if (r < 0)
1137a57c
LP
438 goto fail;
439
718db961
LP
440 r = hashmap_ensure_allocated(&m->units, string_hash_func, string_compare_func);
441 if (r < 0)
60918275
LP
442 goto fail;
443
718db961
LP
444 r = hashmap_ensure_allocated(&m->jobs, trivial_hash_func, trivial_compare_func);
445 if (r < 0)
60918275
LP
446 goto fail;
447
718db961
LP
448 r = hashmap_ensure_allocated(&m->cgroup_unit, string_hash_func, string_compare_func);
449 if (r < 0)
9152c765
LP
450 goto fail;
451
718db961
LP
452 r = hashmap_ensure_allocated(&m->watch_bus, string_hash_func, string_compare_func);
453 if (r < 0)
05e343b7
LP
454 goto fail;
455
f755e3b7
LP
456 r = set_ensure_allocated(&m->failed_units, trivial_hash_func, trivial_compare_func);
457 if (r < 0)
458 goto fail;
459
718db961
LP
460 r = sd_event_default(&m->event);
461 if (r < 0)
8742514c
LP
462 goto fail;
463
151b9b96 464 r = sd_event_add_defer(m->event, &m->run_queue_event_source, manager_dispatch_run_queue, m);
752b5905
LP
465 if (r < 0)
466 goto fail;
467
468 r = sd_event_source_set_priority(m->run_queue_event_source, SD_EVENT_PRIORITY_IDLE);
469 if (r < 0)
470 goto fail;
471
472 r = sd_event_source_set_enabled(m->run_queue_event_source, SD_EVENT_OFF);
473 if (r < 0)
474 goto fail;
475
8742514c
LP
476 r = manager_setup_signals(m);
477 if (r < 0)
9152c765
LP
478 goto fail;
479
8742514c
LP
480 r = manager_setup_cgroup(m);
481 if (r < 0)
8e274523
LP
482 goto fail;
483
8742514c
LP
484 r = manager_setup_time_change(m);
485 if (r < 0)
8c47c732
LP
486 goto fail;
487
9670d583
LP
488 m->udev = udev_new();
489 if (!m->udev) {
490 r = -ENOMEM;
491 goto fail;
492 }
493
d86f9d52
LP
494 /* Note that we set up neither kdbus, nor the notify fd
495 * here. We do that after deserialization, since they might
496 * have gotten serialized across the reexec. */
497
72bc8d00
LP
498 m->taint_usr = dir_is_empty("/usr") > 0;
499
8e274523
LP
500 *_m = m;
501 return 0;
60918275
LP
502
503fail:
504 manager_free(m);
8e274523 505 return r;
60918275
LP
506}
507
d86f9d52
LP
508static int manager_setup_notify(Manager *m) {
509 union {
510 struct sockaddr sa;
511 struct sockaddr_un un;
512 } sa = {
513 .sa.sa_family = AF_UNIX,
514 };
515 int one = 1, r;
516
517 if (m->notify_fd < 0) {
518 _cleanup_close_ int fd = -1;
519
520 /* First free all secondary fields */
521 free(m->notify_socket);
522 m->notify_socket = NULL;
523 m->notify_event_source = sd_event_source_unref(m->notify_event_source);
524
525 fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
526 if (fd < 0) {
527 log_error("Failed to allocate notification socket: %m");
528 return -errno;
529 }
530
531 if (getpid() != 1 || detect_container(NULL) > 0)
9bf3b535 532 snprintf(sa.un.sun_path, sizeof(sa.un.sun_path), NOTIFY_SOCKET "/%" PRIx64, random_u64());
d86f9d52
LP
533 else
534 strncpy(sa.un.sun_path, NOTIFY_SOCKET, sizeof(sa.un.sun_path));
535 sa.un.sun_path[0] = 0;
536
537 r = bind(fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + 1 + strlen(sa.un.sun_path+1));
538 if (r < 0) {
539 log_error("bind() failed: %m");
540 return -errno;
541 }
542
543 r = setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
544 if (r < 0) {
545 log_error("SO_PASSCRED failed: %m");
546 return -errno;
547 }
548
549 sa.un.sun_path[0] = '@';
550 m->notify_socket = strdup(sa.un.sun_path);
551 if (!m->notify_socket)
552 return log_oom();
553
554 m->notify_fd = fd;
555 fd = -1;
556
557 log_debug("Using notification socket %s", m->notify_socket);
558 }
559
560 if (!m->notify_event_source) {
151b9b96 561 r = sd_event_add_io(m->event, &m->notify_event_source, m->notify_fd, EPOLLIN, manager_dispatch_notify_fd, m);
d86f9d52
LP
562 if (r < 0) {
563 log_error("Failed to allocate notify event source: %s", strerror(-r));
564 return -errno;
565 }
566
567 /* Process signals a bit earlier than SIGCHLD, so that we can
568 * still identify to which service an exit message belongs */
569 r = sd_event_source_set_priority(m->notify_event_source, -7);
570 if (r < 0) {
571 log_error("Failed to set priority of notify event source: %s", strerror(-r));
572 return r;
573 }
574 }
575
576 return 0;
577}
578
579static int manager_setup_kdbus(Manager *m) {
5bf348d7 580#ifdef ENABLE_KDBUS
d86f9d52 581 _cleanup_free_ char *p = NULL;
5bf348d7 582#endif
d86f9d52 583
5bf348d7 584#ifdef ENABLE_KDBUS
d86f9d52
LP
585 assert(m);
586
d86f9d52
LP
587 if (m->kdbus_fd >= 0)
588 return 0;
589
f2769777 590 m->kdbus_fd = bus_kernel_create_bus(m->running_as == SYSTEMD_SYSTEM ? "system" : "user", m->running_as == SYSTEMD_SYSTEM, &p);
d86f9d52
LP
591 if (m->kdbus_fd < 0) {
592 log_debug("Failed to set up kdbus: %s", strerror(-m->kdbus_fd));
593 return m->kdbus_fd;
594 }
595
596 log_debug("Successfully set up kdbus on %s", p);
597
598 /* Create the namespace directory here, so that the contents
599 * of that directory is not visible to non-root users. This is
600 * necessary to ensure that users cannot get access to busses
601 * of virtualized users when no UID namespacing is used. */
88c59cb3 602 if (m->running_as == SYSTEMD_SYSTEM)
486e99a3 603 mkdir_p_label("/dev/kdbus/domain", 0700);
d86f9d52
LP
604#endif
605
606 return 0;
607}
608
609static int manager_connect_bus(Manager *m, bool reexecuting) {
610 bool try_bus_connect;
611
612 assert(m);
613
614 try_bus_connect =
615 m->kdbus_fd >= 0 ||
616 reexecuting ||
617 (m->running_as == SYSTEMD_USER && getenv("DBUS_SESSION_BUS_ADDRESS"));
618
619 /* Try to connect to the busses, if possible. */
620 return bus_init(m, try_bus_connect);
621}
622
23a177ef 623static unsigned manager_dispatch_cleanup_queue(Manager *m) {
595ed347 624 Unit *u;
23a177ef
LP
625 unsigned n = 0;
626
627 assert(m);
628
595ed347
MS
629 while ((u = m->cleanup_queue)) {
630 assert(u->in_cleanup_queue);
23a177ef 631
595ed347 632 unit_free(u);
23a177ef
LP
633 n++;
634 }
635
636 return n;
637}
638
eced69b3 639enum {
35b8ca3a 640 GC_OFFSET_IN_PATH, /* This one is on the path we were traveling */
eced69b3
LP
641 GC_OFFSET_UNSURE, /* No clue */
642 GC_OFFSET_GOOD, /* We still need this unit */
643 GC_OFFSET_BAD, /* We don't need this unit anymore */
644 _GC_OFFSET_MAX
645};
646
647static void unit_gc_sweep(Unit *u, unsigned gc_marker) {
701cc384
LP
648 Iterator i;
649 Unit *other;
eced69b3 650 bool is_bad;
701cc384
LP
651
652 assert(u);
653
ac155bb8
MS
654 if (u->gc_marker == gc_marker + GC_OFFSET_GOOD ||
655 u->gc_marker == gc_marker + GC_OFFSET_BAD ||
656 u->gc_marker == gc_marker + GC_OFFSET_IN_PATH)
701cc384
LP
657 return;
658
ac155bb8 659 if (u->in_cleanup_queue)
701cc384
LP
660 goto bad;
661
662 if (unit_check_gc(u))
663 goto good;
664
ac155bb8 665 u->gc_marker = gc_marker + GC_OFFSET_IN_PATH;
eced69b3
LP
666
667 is_bad = true;
668
ac155bb8 669 SET_FOREACH(other, u->dependencies[UNIT_REFERENCED_BY], i) {
701cc384
LP
670 unit_gc_sweep(other, gc_marker);
671
ac155bb8 672 if (other->gc_marker == gc_marker + GC_OFFSET_GOOD)
701cc384 673 goto good;
eced69b3 674
ac155bb8 675 if (other->gc_marker != gc_marker + GC_OFFSET_BAD)
eced69b3 676 is_bad = false;
701cc384
LP
677 }
678
eced69b3
LP
679 if (is_bad)
680 goto bad;
681
682 /* We were unable to find anything out about this entry, so
683 * let's investigate it later */
ac155bb8 684 u->gc_marker = gc_marker + GC_OFFSET_UNSURE;
eced69b3
LP
685 unit_add_to_gc_queue(u);
686 return;
687
701cc384 688bad:
eced69b3
LP
689 /* We definitely know that this one is not useful anymore, so
690 * let's mark it for deletion */
ac155bb8 691 u->gc_marker = gc_marker + GC_OFFSET_BAD;
eced69b3 692 unit_add_to_cleanup_queue(u);
701cc384
LP
693 return;
694
695good:
ac155bb8 696 u->gc_marker = gc_marker + GC_OFFSET_GOOD;
701cc384
LP
697}
698
699static unsigned manager_dispatch_gc_queue(Manager *m) {
595ed347 700 Unit *u;
701cc384 701 unsigned n = 0;
eced69b3 702 unsigned gc_marker;
701cc384
LP
703
704 assert(m);
705
cf1265e1 706 /* log_debug("Running GC..."); */
701cc384 707
eced69b3
LP
708 m->gc_marker += _GC_OFFSET_MAX;
709 if (m->gc_marker + _GC_OFFSET_MAX <= _GC_OFFSET_MAX)
c9c0cadb 710 m->gc_marker = 1;
701cc384 711
eced69b3
LP
712 gc_marker = m->gc_marker;
713
595ed347
MS
714 while ((u = m->gc_queue)) {
715 assert(u->in_gc_queue);
701cc384 716
595ed347 717 unit_gc_sweep(u, gc_marker);
eced69b3 718
71fda00f 719 LIST_REMOVE(gc_queue, m->gc_queue, u);
595ed347 720 u->in_gc_queue = false;
701cc384
LP
721
722 n++;
723
595ed347
MS
724 if (u->gc_marker == gc_marker + GC_OFFSET_BAD ||
725 u->gc_marker == gc_marker + GC_OFFSET_UNSURE) {
66870f90 726 log_debug_unit(u->id, "Collecting %s", u->id);
595ed347
MS
727 u->gc_marker = gc_marker + GC_OFFSET_BAD;
728 unit_add_to_cleanup_queue(u);
701cc384
LP
729 }
730 }
731
732 m->n_in_gc_queue = 0;
701cc384
LP
733
734 return n;
735}
736
a16e1123 737static void manager_clear_jobs_and_units(Manager *m) {
a16e1123 738 Unit *u;
60918275
LP
739
740 assert(m);
741
87f0e418
LP
742 while ((u = hashmap_first(m->units)))
743 unit_free(u);
964e0949
LP
744
745 manager_dispatch_cleanup_queue(m);
746
747 assert(!m->load_queue);
748 assert(!m->run_queue);
749 assert(!m->dbus_unit_queue);
750 assert(!m->dbus_job_queue);
751 assert(!m->cleanup_queue);
752 assert(!m->gc_queue);
753
964e0949
LP
754 assert(hashmap_isempty(m->jobs));
755 assert(hashmap_isempty(m->units));
9e9e2b72
MS
756
757 m->n_on_console = 0;
758 m->n_running_jobs = 0;
a16e1123
LP
759}
760
761void manager_free(Manager *m) {
762 UnitType c;
c93ff2e9 763 int i;
87f0e418 764
a16e1123
LP
765 assert(m);
766
767 manager_clear_jobs_and_units(m);
23a177ef 768
7824bbeb
LP
769 for (c = 0; c < _UNIT_TYPE_MAX; c++)
770 if (unit_vtable[c]->shutdown)
771 unit_vtable[c]->shutdown(m);
772
a16e1123
LP
773 /* If we reexecute ourselves, we keep the root cgroup
774 * around */
c6c18be3 775 manager_shutdown_cgroup(m, m->exit_code != MANAGER_REEXECUTE);
8e274523 776
5a1e9937
LP
777 manager_undo_generators(m);
778
5e8d1c9a 779 bus_done(m);
ea430986 780
87f0e418 781 hashmap_free(m->units);
60918275 782 hashmap_free(m->jobs);
5ba6985b
LP
783 hashmap_free(m->watch_pids1);
784 hashmap_free(m->watch_pids2);
05e343b7 785 hashmap_free(m->watch_bus);
9152c765 786
f755e3b7
LP
787 set_free(m->failed_units);
788
718db961
LP
789 sd_event_source_unref(m->signal_event_source);
790 sd_event_source_unref(m->notify_event_source);
791 sd_event_source_unref(m->time_change_event_source);
792 sd_event_source_unref(m->jobs_in_progress_event_source);
793 sd_event_source_unref(m->idle_pipe_event_source);
752b5905 794 sd_event_source_unref(m->run_queue_event_source);
718db961
LP
795
796 if (m->signal_fd >= 0)
797 close_nointr_nofail(m->signal_fd);
798 if (m->notify_fd >= 0)
799 close_nointr_nofail(m->notify_fd);
800 if (m->time_change_fd >= 0)
801 close_nointr_nofail(m->time_change_fd);
e3dd987c
LP
802 if (m->kdbus_fd >= 0)
803 close_nointr_nofail(m->kdbus_fd);
718db961
LP
804
805 manager_close_idle_pipe(m);
806
9670d583 807 udev_unref(m->udev);
718db961 808 sd_event_unref(m->event);
60918275 809
c952c6ec
LP
810 free(m->notify_socket);
811
84e3543e 812 lookup_paths_free(&m->lookup_paths);
1137a57c 813 strv_free(m->environment);
036643a2 814
4ad49000 815 hashmap_free(m->cgroup_unit);
c6c18be3 816 set_free_free(m->unit_path_cache);
33be102a 817
664f88a7
LP
818 free(m->switch_root);
819 free(m->switch_root_init);
820
517d56b1 821 for (i = 0; i < _RLIMIT_MAX; i++)
c93ff2e9
FC
822 free(m->rlimit[i]);
823
a57f7e2c
LP
824 assert(hashmap_isempty(m->units_requiring_mounts_for));
825 hashmap_free(m->units_requiring_mounts_for);
826
60918275
LP
827 free(m);
828}
829
a16e1123
LP
830int manager_enumerate(Manager *m) {
831 int r = 0, q;
f50e0a01 832 UnitType c;
f50e0a01
LP
833
834 assert(m);
835
a16e1123
LP
836 /* Let's ask every type to load all units from disk/kernel
837 * that it might know */
f50e0a01 838 for (c = 0; c < _UNIT_TYPE_MAX; c++)
a57f7e2c
LP
839 if (unit_vtable[c]->enumerate) {
840 q = unit_vtable[c]->enumerate(m);
841 if (q < 0)
a16e1123 842 r = q;
a57f7e2c 843 }
f50e0a01
LP
844
845 manager_dispatch_load_queue(m);
a16e1123
LP
846 return r;
847}
848
9588bc32 849static int manager_coldplug(Manager *m) {
8f8f05a9 850 int r = 0;
a16e1123
LP
851 Iterator i;
852 Unit *u;
853 char *k;
854
855 assert(m);
f50e0a01
LP
856
857 /* Then, let's set up their initial state. */
858 HASHMAP_FOREACH_KEY(u, k, m->units, i) {
8f8f05a9 859 int q;
f50e0a01
LP
860
861 /* ignore aliases */
ac155bb8 862 if (u->id != k)
f50e0a01
LP
863 continue;
864
8f8f05a9
LP
865 q = unit_coldplug(u);
866 if (q < 0)
cca098b0 867 r = q;
f50e0a01
LP
868 }
869
a16e1123
LP
870 return r;
871}
872
fe51822e
LP
873static void manager_build_unit_path_cache(Manager *m) {
874 char **i;
7fd1b19b 875 _cleanup_free_ DIR *d = NULL;
fe51822e
LP
876 int r;
877
878 assert(m);
879
880 set_free_free(m->unit_path_cache);
881
874310b7
ZJS
882 m->unit_path_cache = set_new(string_hash_func, string_compare_func);
883 if (!m->unit_path_cache) {
fe51822e
LP
884 log_error("Failed to allocate unit path cache.");
885 return;
886 }
887
888 /* This simply builds a list of files we know exist, so that
889 * we don't always have to go to disk */
890
891 STRV_FOREACH(i, m->lookup_paths.unit_path) {
892 struct dirent *de;
893
bd0af849
ZJS
894 d = opendir(*i);
895 if (!d) {
874310b7
ZJS
896 if (errno != ENOENT)
897 log_error("Failed to open directory %s: %m", *i);
fe51822e
LP
898 continue;
899 }
900
901 while ((de = readdir(d))) {
902 char *p;
903
904 if (ignore_file(de->d_name))
905 continue;
906
b7def684 907 p = strjoin(streq(*i, "/") ? "" : *i, "/", de->d_name, NULL);
44d91056 908 if (!p) {
fe51822e
LP
909 r = -ENOMEM;
910 goto fail;
911 }
912
ef42202a
ZJS
913 r = set_consume(m->unit_path_cache, p);
914 if (r < 0)
fe51822e 915 goto fail;
fe51822e
LP
916 }
917
918 closedir(d);
919 d = NULL;
920 }
921
922 return;
923
924fail:
925 log_error("Failed to build unit path cache: %s", strerror(-r));
926
927 set_free_free(m->unit_path_cache);
928 m->unit_path_cache = NULL;
fe51822e
LP
929}
930
9588bc32
LP
931
932static int manager_distribute_fds(Manager *m, FDSet *fds) {
933 Unit *u;
934 Iterator i;
935 int r;
936
937 assert(m);
938
939 HASHMAP_FOREACH(u, m->units, i) {
940
941 if (fdset_size(fds) <= 0)
942 break;
943
944 if (UNIT_VTABLE(u)->distribute_fds) {
945 r = UNIT_VTABLE(u)->distribute_fds(u, fds);
946 if (r < 0)
947 return r;
948 }
949 }
950
951 return 0;
952}
953
a16e1123
LP
954int manager_startup(Manager *m, FILE *serialization, FDSet *fds) {
955 int r, q;
956
957 assert(m);
958
518d10e9 959 dual_timestamp_get(&m->generators_start_timestamp);
5a1e9937 960 manager_run_generators(m);
518d10e9 961 dual_timestamp_get(&m->generators_finish_timestamp);
5a1e9937 962
07719a21
LP
963 r = lookup_paths_init(
964 &m->lookup_paths, m->running_as, true,
965 m->generator_unit_path,
966 m->generator_unit_path_early,
967 m->generator_unit_path_late);
968 if (r < 0)
969 return r;
970
fe51822e
LP
971 manager_build_unit_path_cache(m);
972
9f611ad8
LP
973 /* If we will deserialize make sure that during enumeration
974 * this is already known, so we increase the counter here
975 * already */
976 if (serialization)
a7556052 977 m->n_reloading ++;
9f611ad8 978
a16e1123 979 /* First, enumerate what we can from all config files */
718db961 980 dual_timestamp_get(&m->units_load_start_timestamp);
a16e1123 981 r = manager_enumerate(m);
718db961 982 dual_timestamp_get(&m->units_load_finish_timestamp);
a16e1123
LP
983
984 /* Second, deserialize if there is something to deserialize */
07719a21
LP
985 if (serialization) {
986 q = manager_deserialize(m, serialization, fds);
987 if (q < 0)
a16e1123 988 r = q;
07719a21 989 }
a16e1123 990
01e10de3
LP
991 /* Any fds left? Find some unit which wants them. This is
992 * useful to allow container managers to pass some file
993 * descriptors to us pre-initialized. This enables
994 * socket-based activation of entire containers. */
995 if (fdset_size(fds) > 0) {
996 q = manager_distribute_fds(m, fds);
997 if (q < 0)
998 r = q;
999 }
1000
d86f9d52
LP
1001 /* We might have deserialized the notify fd, but if we didn't
1002 * then let's create the bus now */
1003 manager_setup_notify(m);
1004
e3dd987c
LP
1005 /* We might have deserialized the kdbus control fd, but if we
1006 * didn't, then let's create the bus now. */
1007 manager_setup_kdbus(m);
1008 manager_connect_bus(m, !!serialization);
8f8f05a9 1009 bus_track_coldplug(m, &m->subscribed, &m->deserialized_subscribed);
e3dd987c 1010
a16e1123 1011 /* Third, fire things up! */
07719a21
LP
1012 q = manager_coldplug(m);
1013 if (q < 0)
a16e1123
LP
1014 r = q;
1015
9f611ad8 1016 if (serialization) {
a7556052
LP
1017 assert(m->n_reloading > 0);
1018 m->n_reloading --;
71445ae7
LP
1019
1020 /* Let's wait for the UnitNew/JobNew messages being
1021 * sent, before we notify that the reload is
1022 * finished */
1023 m->send_reloading_done = true;
9f611ad8
LP
1024 }
1025
a16e1123 1026 return r;
f50e0a01
LP
1027}
1028
718db961 1029int manager_add_job(Manager *m, JobType type, Unit *unit, JobMode mode, bool override, sd_bus_error *e, Job **_ret) {
e5b5ae50 1030 int r;
7527cb52 1031 Transaction *tr;
e5b5ae50
LP
1032
1033 assert(m);
1034 assert(type < _JOB_TYPE_MAX);
87f0e418 1035 assert(unit);
e5b5ae50 1036 assert(mode < _JOB_MODE_MAX);
60918275 1037
398ef8ba 1038 if (mode == JOB_ISOLATE && type != JOB_START) {
718db961 1039 sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS, "Isolate is only valid for start.");
c497c7a9 1040 return -EINVAL;
398ef8ba 1041 }
c497c7a9 1042
ac155bb8 1043 if (mode == JOB_ISOLATE && !unit->allow_isolate) {
718db961 1044 sd_bus_error_setf(e, BUS_ERROR_NO_ISOLATION, "Operation refused, unit may not be isolated.");
2528a7a6
LP
1045 return -EPERM;
1046 }
1047
66870f90
ZJS
1048 log_debug_unit(unit->id,
1049 "Trying to enqueue job %s/%s/%s", unit->id,
1050 job_type_to_string(type), job_mode_to_string(mode));
9f04bd52 1051
e0209d83
MS
1052 job_type_collapse(&type, unit);
1053
23ade460 1054 tr = transaction_new(mode == JOB_REPLACE_IRREVERSIBLY);
7527cb52
MS
1055 if (!tr)
1056 return -ENOMEM;
11dd41ce 1057
7527cb52
MS
1058 r = transaction_add_job_and_dependencies(tr, type, unit, NULL, true, override, false,
1059 mode == JOB_IGNORE_DEPENDENCIES || mode == JOB_IGNORE_REQUIREMENTS,
b94fbd30 1060 mode == JOB_IGNORE_DEPENDENCIES, e);
7527cb52
MS
1061 if (r < 0)
1062 goto tr_abort;
c497c7a9 1063
7527cb52
MS
1064 if (mode == JOB_ISOLATE) {
1065 r = transaction_add_isolate_jobs(tr, m);
1066 if (r < 0)
1067 goto tr_abort;
1068 }
1069
1070 r = transaction_activate(tr, m, mode, e);
1071 if (r < 0)
1072 goto tr_abort;
e5b5ae50 1073
66870f90
ZJS
1074 log_debug_unit(unit->id,
1075 "Enqueued job %s/%s as %u", unit->id,
1076 job_type_to_string(type), (unsigned) tr->anchor_job->id);
f50e0a01 1077
e5b5ae50 1078 if (_ret)
b94fbd30 1079 *_ret = tr->anchor_job;
60918275 1080
7527cb52 1081 transaction_free(tr);
e5b5ae50 1082 return 0;
7527cb52
MS
1083
1084tr_abort:
1085 transaction_abort(tr);
1086 transaction_free(tr);
1087 return r;
e5b5ae50 1088}
60918275 1089
718db961 1090int manager_add_job_by_name(Manager *m, JobType type, const char *name, JobMode mode, bool override, sd_bus_error *e, Job **_ret) {
28247076
LP
1091 Unit *unit;
1092 int r;
1093
1094 assert(m);
1095 assert(type < _JOB_TYPE_MAX);
1096 assert(name);
1097 assert(mode < _JOB_MODE_MAX);
1098
c3090674
LP
1099 r = manager_load_unit(m, name, NULL, NULL, &unit);
1100 if (r < 0)
28247076
LP
1101 return r;
1102
398ef8ba 1103 return manager_add_job(m, type, unit, mode, override, e, _ret);
28247076
LP
1104}
1105
60918275
LP
1106Job *manager_get_job(Manager *m, uint32_t id) {
1107 assert(m);
1108
1109 return hashmap_get(m->jobs, UINT32_TO_PTR(id));
1110}
1111
87f0e418 1112Unit *manager_get_unit(Manager *m, const char *name) {
60918275
LP
1113 assert(m);
1114 assert(name);
1115
87f0e418 1116 return hashmap_get(m->units, name);
60918275
LP
1117}
1118
c1e1601e 1119unsigned manager_dispatch_load_queue(Manager *m) {
595ed347 1120 Unit *u;
c1e1601e 1121 unsigned n = 0;
60918275
LP
1122
1123 assert(m);
1124
223dabab
LP
1125 /* Make sure we are not run recursively */
1126 if (m->dispatching_load_queue)
c1e1601e 1127 return 0;
223dabab
LP
1128
1129 m->dispatching_load_queue = true;
1130
87f0e418 1131 /* Dispatches the load queue. Takes a unit from the queue and
60918275
LP
1132 * tries to load its data until the queue is empty */
1133
595ed347
MS
1134 while ((u = m->load_queue)) {
1135 assert(u->in_load_queue);
034c6ed7 1136
595ed347 1137 unit_load(u);
c1e1601e 1138 n++;
60918275
LP
1139 }
1140
223dabab 1141 m->dispatching_load_queue = false;
c1e1601e 1142 return n;
60918275
LP
1143}
1144
c2756a68
LP
1145int manager_load_unit_prepare(
1146 Manager *m,
1147 const char *name,
1148 const char *path,
718db961 1149 sd_bus_error *e,
c2756a68
LP
1150 Unit **_ret) {
1151
87f0e418 1152 Unit *ret;
7d17cfbc 1153 UnitType t;
60918275
LP
1154 int r;
1155
1156 assert(m);
9e2f7c11 1157 assert(name || path);
60918275 1158
db06e3b6
LP
1159 /* This will prepare the unit for loading, but not actually
1160 * load anything from disk. */
0301abf4 1161
718db961
LP
1162 if (path && !is_path(path))
1163 return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS, "Path %s is not absolute.", path);
9e2f7c11
LP
1164
1165 if (!name)
2b6bf07d 1166 name = basename(path);
9e2f7c11 1167
7d17cfbc
MS
1168 t = unit_name_to_type(name);
1169
f78e6385 1170 if (t == _UNIT_TYPE_INVALID || !unit_name_is_valid(name, TEMPLATE_INVALID))
718db961 1171 return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS, "Unit name %s is not valid.", name);
60918275 1172
7d17cfbc
MS
1173 ret = manager_get_unit(m, name);
1174 if (ret) {
034c6ed7 1175 *_ret = ret;
413d6313 1176 return 1;
034c6ed7 1177 }
60918275 1178
7d17cfbc
MS
1179 ret = unit_new(m, unit_vtable[t]->object_size);
1180 if (!ret)
60918275
LP
1181 return -ENOMEM;
1182
7d17cfbc 1183 if (path) {
ac155bb8
MS
1184 ret->fragment_path = strdup(path);
1185 if (!ret->fragment_path) {
0301abf4
LP
1186 unit_free(ret);
1187 return -ENOMEM;
1188 }
7d17cfbc 1189 }
0301abf4 1190
1058cbf2
ZJS
1191 r = unit_add_name(ret, name);
1192 if (r < 0) {
87f0e418 1193 unit_free(ret);
1ffba6fe 1194 return r;
60918275
LP
1195 }
1196
87f0e418 1197 unit_add_to_load_queue(ret);
c1e1601e 1198 unit_add_to_dbus_queue(ret);
949061f0 1199 unit_add_to_gc_queue(ret);
c1e1601e 1200
db06e3b6
LP
1201 if (_ret)
1202 *_ret = ret;
1203
1204 return 0;
1205}
1206
c2756a68
LP
1207int manager_load_unit(
1208 Manager *m,
1209 const char *name,
1210 const char *path,
718db961 1211 sd_bus_error *e,
c2756a68
LP
1212 Unit **_ret) {
1213
db06e3b6
LP
1214 int r;
1215
1216 assert(m);
1217
1218 /* This will load the service information files, but not actually
1219 * start any services or anything. */
1220
c3090674
LP
1221 r = manager_load_unit_prepare(m, name, path, e, _ret);
1222 if (r != 0)
db06e3b6
LP
1223 return r;
1224
f50e0a01 1225 manager_dispatch_load_queue(m);
60918275 1226
9e2f7c11 1227 if (_ret)
413d6313 1228 *_ret = unit_follow_merge(*_ret);
9e2f7c11 1229
60918275
LP
1230 return 0;
1231}
a66d02c3 1232
cea8e32e 1233void manager_dump_jobs(Manager *s, FILE *f, const char *prefix) {
034c6ed7 1234 Iterator i;
a66d02c3
LP
1235 Job *j;
1236
1237 assert(s);
1238 assert(f);
1239
034c6ed7 1240 HASHMAP_FOREACH(j, s->jobs, i)
cea8e32e 1241 job_dump(j, f, prefix);
a66d02c3
LP
1242}
1243
87f0e418 1244void manager_dump_units(Manager *s, FILE *f, const char *prefix) {
034c6ed7 1245 Iterator i;
87f0e418 1246 Unit *u;
11dd41ce 1247 const char *t;
a66d02c3
LP
1248
1249 assert(s);
1250 assert(f);
1251
87f0e418 1252 HASHMAP_FOREACH_KEY(u, t, s->units, i)
ac155bb8 1253 if (u->id == t)
87f0e418 1254 unit_dump(u, f, prefix);
a66d02c3 1255}
7fad411c
LP
1256
1257void manager_clear_jobs(Manager *m) {
1258 Job *j;
1259
1260 assert(m);
1261
7fad411c 1262 while ((j = hashmap_first(m->jobs)))
5273510e
MS
1263 /* No need to recurse. We're cancelling all jobs. */
1264 job_finish_and_invalidate(j, JOB_CANCELED, false);
7fad411c 1265}
83c60c9f 1266
752b5905
LP
1267static int manager_dispatch_run_queue(sd_event_source *source, void *userdata) {
1268 Manager *m = userdata;
83c60c9f 1269 Job *j;
034c6ed7 1270
752b5905
LP
1271 assert(source);
1272 assert(m);
9152c765 1273
034c6ed7 1274 while ((j = m->run_queue)) {
ac1135be 1275 assert(j->installed);
034c6ed7
LP
1276 assert(j->in_run_queue);
1277
1278 job_run_and_invalidate(j);
9152c765 1279 }
034c6ed7 1280
a0b64226 1281 if (m->n_running_jobs > 0)
03b717a3
MS
1282 manager_watch_jobs_in_progress(m);
1283
31a7eb86
ZJS
1284 if (m->n_on_console > 0)
1285 manager_watch_idle_pipe(m);
1286
752b5905 1287 return 1;
c1e1601e
LP
1288}
1289
9588bc32 1290static unsigned manager_dispatch_dbus_queue(Manager *m) {
c1e1601e 1291 Job *j;
595ed347 1292 Unit *u;
c1e1601e
LP
1293 unsigned n = 0;
1294
1295 assert(m);
1296
1297 if (m->dispatching_dbus_queue)
1298 return 0;
1299
1300 m->dispatching_dbus_queue = true;
1301
595ed347
MS
1302 while ((u = m->dbus_unit_queue)) {
1303 assert(u->in_dbus_queue);
c1e1601e 1304
595ed347 1305 bus_unit_send_change_signal(u);
c1e1601e
LP
1306 n++;
1307 }
1308
1309 while ((j = m->dbus_job_queue)) {
1310 assert(j->in_dbus_queue);
1311
1312 bus_job_send_change_signal(j);
1313 n++;
1314 }
1315
1316 m->dispatching_dbus_queue = false;
71445ae7
LP
1317
1318 if (m->send_reloading_done) {
1319 m->send_reloading_done = false;
1320
718db961 1321 bus_manager_send_reloading(m, false);
71445ae7
LP
1322 }
1323
718db961
LP
1324 if (m->queued_message)
1325 bus_send_queued_message(m);
1326
c1e1601e 1327 return n;
9152c765
LP
1328}
1329
5ba6985b
LP
1330static void manager_invoke_notify_message(Manager *m, Unit *u, pid_t pid, char *buf, size_t n) {
1331 _cleanup_strv_free_ char **tags = NULL;
1332
1333 assert(m);
1334 assert(u);
1335 assert(buf);
1336 assert(n > 0);
1337
1338 tags = strv_split(buf, "\n\r");
1339 if (!tags) {
1340 log_oom();
1341 return;
1342 }
1343
1344 log_debug_unit(u->id, "Got notification message for unit %s", u->id);
1345
1346 if (UNIT_VTABLE(u)->notify_message)
1347 UNIT_VTABLE(u)->notify_message(u, pid, tags);
1348}
1349
718db961
LP
1350static int manager_dispatch_notify_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
1351 Manager *m = userdata;
8c47c732
LP
1352 ssize_t n;
1353
1354 assert(m);
718db961
LP
1355 assert(m->notify_fd == fd);
1356
1357 if (revents != EPOLLIN) {
1358 log_warning("Got unexpected poll event for notify fd.");
1359 return 0;
1360 }
8c47c732
LP
1361
1362 for (;;) {
1363 char buf[4096];
b92bea5d
ZJS
1364 struct iovec iovec = {
1365 .iov_base = buf,
1366 .iov_len = sizeof(buf)-1,
1367 };
5ba6985b 1368 bool found = false;
b92bea5d 1369
8c47c732
LP
1370 union {
1371 struct cmsghdr cmsghdr;
1372 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
b92bea5d
ZJS
1373 } control = {};
1374
1375 struct msghdr msghdr = {
1376 .msg_iov = &iovec,
1377 .msg_iovlen = 1,
1378 .msg_control = &control,
1379 .msg_controllen = sizeof(control),
1380 };
1381 struct ucred *ucred;
8c47c732 1382 Unit *u;
8c47c732 1383
718db961 1384 n = recvmsg(m->notify_fd, &msghdr, MSG_DONTWAIT);
bd0af849 1385 if (n <= 0) {
b92bea5d 1386 if (n == 0)
8c47c732
LP
1387 return -EIO;
1388
f6144808 1389 if (errno == EAGAIN || errno == EINTR)
8c47c732
LP
1390 break;
1391
1392 return -errno;
1393 }
1394
1395 if (msghdr.msg_controllen < CMSG_LEN(sizeof(struct ucred)) ||
1396 control.cmsghdr.cmsg_level != SOL_SOCKET ||
1397 control.cmsghdr.cmsg_type != SCM_CREDENTIALS ||
1398 control.cmsghdr.cmsg_len != CMSG_LEN(sizeof(struct ucred))) {
1399 log_warning("Received notify message without credentials. Ignoring.");
1400 continue;
1401 }
1402
1403 ucred = (struct ucred*) CMSG_DATA(&control.cmsghdr);
1404
8c40acf7
LP
1405 assert((size_t) n < sizeof(buf));
1406 buf[n] = 0;
8c47c732 1407
5ba6985b
LP
1408 u = manager_get_unit_by_pid(m, ucred->pid);
1409 if (u) {
1410 manager_invoke_notify_message(m, u, ucred->pid, buf, n);
1411 found = true;
1412 }
1413
1414 u = hashmap_get(m->watch_pids1, LONG_TO_PTR(ucred->pid));
1415 if (u) {
1416 manager_invoke_notify_message(m, u, ucred->pid, buf, n);
1417 found = true;
1418 }
1419
1420 u = hashmap_get(m->watch_pids2, LONG_TO_PTR(ucred->pid));
1421 if (u) {
1422 manager_invoke_notify_message(m, u, ucred->pid, buf, n);
1423 found = true;
1424 }
8c47c732 1425
5ba6985b
LP
1426 if (!found)
1427 log_warning("Cannot find unit for notify message of PID "PID_FMT".", ucred->pid);
8c47c732
LP
1428 }
1429
1430 return 0;
1431}
1432
5ba6985b
LP
1433static void invoke_sigchld_event(Manager *m, Unit *u, siginfo_t *si) {
1434 assert(m);
1435 assert(u);
1436 assert(si);
1437
1438 log_debug_unit(u->id, "Child "PID_FMT" belongs to %s", si->si_pid, u->id);
1439
1440 unit_unwatch_pid(u, si->si_pid);
1441 UNIT_VTABLE(u)->sigchld_event(u, si->si_pid, si->si_code, si->si_status);
1442}
1443
034c6ed7 1444static int manager_dispatch_sigchld(Manager *m) {
9152c765
LP
1445 assert(m);
1446
1447 for (;;) {
b92bea5d 1448 siginfo_t si = {};
9152c765 1449
4112df16
LP
1450 /* First we call waitd() for a PID and do not reap the
1451 * zombie. That way we can still access /proc/$PID for
1452 * it while it is a zombie. */
1453 if (waitid(P_ALL, 0, &si, WEXITED|WNOHANG|WNOWAIT) < 0) {
acbb0225
LP
1454
1455 if (errno == ECHILD)
1456 break;
1457
4112df16
LP
1458 if (errno == EINTR)
1459 continue;
1460
9152c765 1461 return -errno;
acbb0225 1462 }
9152c765 1463
4112df16 1464 if (si.si_pid <= 0)
9152c765
LP
1465 break;
1466
15d5d9d9 1467 if (si.si_code == CLD_EXITED || si.si_code == CLD_KILLED || si.si_code == CLD_DUMPED) {
7fd1b19b 1468 _cleanup_free_ char *name = NULL;
5ba6985b 1469 Unit *u;
4112df16 1470
87d2c1ff 1471 get_process_comm(si.si_pid, &name);
4112df16 1472
5ba6985b
LP
1473 log_debug("Child "PID_FMT" (%s) died (code=%s, status=%i/%s)",
1474 si.si_pid, strna(name),
1475 sigchld_code_to_string(si.si_code),
1476 si.si_status,
1477 strna(si.si_code == CLD_EXITED
1478 ? exit_status_to_string(si.si_status, EXIT_STATUS_FULL)
1479 : signal_to_string(si.si_status)));
1480
1481 /* And now figure out the unit this belongs
1482 * to, it might be multiple... */
4ad49000 1483 u = manager_get_unit_by_pid(m, si.si_pid);
5ba6985b
LP
1484 if (u)
1485 invoke_sigchld_event(m, u, &si);
1486 u = hashmap_get(m->watch_pids1, LONG_TO_PTR(si.si_pid));
1487 if (u)
1488 invoke_sigchld_event(m, u, &si);
1489 u = hashmap_get(m->watch_pids2, LONG_TO_PTR(si.si_pid));
1490 if (u)
1491 invoke_sigchld_event(m, u, &si);
1492 }
8c47c732 1493
4112df16
LP
1494 /* And now, we actually reap the zombie. */
1495 if (waitid(P_PID, si.si_pid, &si, WEXITED) < 0) {
1496 if (errno == EINTR)
1497 continue;
1498
1499 return -errno;
1500 }
9152c765
LP
1501 }
1502
1503 return 0;
1504}
1505
7d793605 1506static int manager_start_target(Manager *m, const char *name, JobMode mode) {
718db961 1507 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
28247076 1508 int r;
398ef8ba 1509
66870f90 1510 log_debug_unit(name, "Activating special unit %s", name);
1e001f52 1511
bd0af849
ZJS
1512 r = manager_add_job_by_name(m, JOB_START, name, mode, true, &error, NULL);
1513 if (r < 0)
718db961 1514 log_error_unit(name, "Failed to enqueue %s job: %s", name, bus_error_message(&error, r));
a1b256b0
LP
1515
1516 return r;
28247076
LP
1517}
1518
718db961
LP
1519static int manager_dispatch_signal_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
1520 Manager *m = userdata;
9152c765
LP
1521 ssize_t n;
1522 struct signalfd_siginfo sfsi;
1523 bool sigchld = false;
1524
1525 assert(m);
718db961
LP
1526 assert(m->signal_fd == fd);
1527
1528 if (revents != EPOLLIN) {
1529 log_warning("Got unexpected events from signal file descriptor.");
1530 return 0;
1531 }
9152c765
LP
1532
1533 for (;;) {
718db961 1534 n = read(m->signal_fd, &sfsi, sizeof(sfsi));
57cb4adf 1535 if (n != sizeof(sfsi)) {
9152c765
LP
1536
1537 if (n >= 0)
1538 return -EIO;
1539
63090775 1540 if (errno == EINTR || errno == EAGAIN)
acbb0225 1541 break;
9152c765
LP
1542
1543 return -errno;
1544 }
1545
4daf54a8
ZJS
1546 log_received_signal(sfsi.ssi_signo == SIGCHLD ||
1547 (sfsi.ssi_signo == SIGTERM && m->running_as == SYSTEMD_USER)
1548 ? LOG_DEBUG : LOG_INFO,
1549 &sfsi);
1e001f52 1550
b9cd2ec1
LP
1551 switch (sfsi.ssi_signo) {
1552
4112df16 1553 case SIGCHLD:
9152c765 1554 sigchld = true;
b9cd2ec1
LP
1555 break;
1556
6632c602 1557 case SIGTERM:
67445f4e 1558 if (m->running_as == SYSTEMD_SYSTEM) {
db06e3b6
LP
1559 /* This is for compatibility with the
1560 * original sysvinit */
e11dc4a2 1561 m->exit_code = MANAGER_REEXECUTE;
a1b256b0
LP
1562 break;
1563 }
84e9af1e 1564
a1b256b0 1565 /* Fall through */
e11dc4a2
LP
1566
1567 case SIGINT:
67445f4e 1568 if (m->running_as == SYSTEMD_SYSTEM) {
f49fd1d5 1569 manager_start_target(m, SPECIAL_CTRL_ALT_DEL_TARGET, JOB_REPLACE_IRREVERSIBLY);
84e9af1e
LP
1570 break;
1571 }
1572
a1b256b0 1573 /* Run the exit target if there is one, if not, just exit. */
0003d1ab 1574 if (manager_start_target(m, SPECIAL_EXIT_TARGET, JOB_REPLACE) < 0) {
a1b256b0
LP
1575 m->exit_code = MANAGER_EXIT;
1576 return 0;
1577 }
1578
1579 break;
84e9af1e 1580
28247076 1581 case SIGWINCH:
67445f4e 1582 if (m->running_as == SYSTEMD_SYSTEM)
7d793605 1583 manager_start_target(m, SPECIAL_KBREQUEST_TARGET, JOB_REPLACE);
84e9af1e 1584
28247076
LP
1585 /* This is a nop on non-init */
1586 break;
84e9af1e 1587
28247076 1588 case SIGPWR:
67445f4e 1589 if (m->running_as == SYSTEMD_SYSTEM)
7d793605 1590 manager_start_target(m, SPECIAL_SIGPWR_TARGET, JOB_REPLACE);
84e9af1e 1591
28247076 1592 /* This is a nop on non-init */
84e9af1e 1593 break;
6632c602 1594
1005d14f 1595 case SIGUSR1: {
57ee42ce
LP
1596 Unit *u;
1597
1598 u = manager_get_unit(m, SPECIAL_DBUS_SERVICE);
1599
1600 if (!u || UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u))) {
1601 log_info("Trying to reconnect to bus...");
3996fbe2 1602 bus_init(m, true);
57ee42ce
LP
1603 }
1604
1605 if (!u || !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u))) {
1606 log_info("Loading D-Bus service...");
7d793605 1607 manager_start_target(m, SPECIAL_DBUS_SERVICE, JOB_REPLACE);
57ee42ce
LP
1608 }
1609
1610 break;
1611 }
1612
2149e37c 1613 case SIGUSR2: {
718db961
LP
1614 _cleanup_free_ char *dump = NULL;
1615 _cleanup_fclose_ FILE *f = NULL;
2149e37c
LP
1616 size_t size;
1617
718db961
LP
1618 f = open_memstream(&dump, &size);
1619 if (!f) {
2149e37c
LP
1620 log_warning("Failed to allocate memory stream.");
1621 break;
1622 }
1623
1624 manager_dump_units(m, f, "\t");
1625 manager_dump_jobs(m, f, "\t");
1626
1627 if (ferror(f)) {
2149e37c
LP
1628 log_warning("Failed to write status stream");
1629 break;
1630 }
1631
b2cdc666
DM
1632 if (fflush(f)) {
1633 log_warning("Failed to flush status stream");
1634 break;
1635 }
1636
2149e37c 1637 log_dump(LOG_INFO, dump);
1005d14f 1638 break;
2149e37c 1639 }
1005d14f 1640
a16e1123
LP
1641 case SIGHUP:
1642 m->exit_code = MANAGER_RELOAD;
1643 break;
1644
7d793605 1645 default: {
253ee27a 1646
0003d1ab
LP
1647 /* Starting SIGRTMIN+0 */
1648 static const char * const target_table[] = {
7d793605
LP
1649 [0] = SPECIAL_DEFAULT_TARGET,
1650 [1] = SPECIAL_RESCUE_TARGET,
f057408c 1651 [2] = SPECIAL_EMERGENCY_TARGET,
7d793605
LP
1652 [3] = SPECIAL_HALT_TARGET,
1653 [4] = SPECIAL_POWEROFF_TARGET,
0003d1ab
LP
1654 [5] = SPECIAL_REBOOT_TARGET,
1655 [6] = SPECIAL_KEXEC_TARGET
1656 };
1657
1658 /* Starting SIGRTMIN+13, so that target halt and system halt are 10 apart */
1659 static const ManagerExitCode code_table[] = {
1660 [0] = MANAGER_HALT,
1661 [1] = MANAGER_POWEROFF,
1662 [2] = MANAGER_REBOOT,
1663 [3] = MANAGER_KEXEC
7d793605
LP
1664 };
1665
1666 if ((int) sfsi.ssi_signo >= SIGRTMIN+0 &&
0003d1ab 1667 (int) sfsi.ssi_signo < SIGRTMIN+(int) ELEMENTSOF(target_table)) {
764e9b5f
MS
1668 int idx = (int) sfsi.ssi_signo - SIGRTMIN;
1669 manager_start_target(m, target_table[idx],
1670 (idx == 1 || idx == 2) ? JOB_ISOLATE : JOB_REPLACE);
7d793605
LP
1671 break;
1672 }
1673
0003d1ab
LP
1674 if ((int) sfsi.ssi_signo >= SIGRTMIN+13 &&
1675 (int) sfsi.ssi_signo < SIGRTMIN+13+(int) ELEMENTSOF(code_table)) {
1676 m->exit_code = code_table[sfsi.ssi_signo - SIGRTMIN - 13];
1677 break;
1678 }
1679
0658666b
LP
1680 switch (sfsi.ssi_signo - SIGRTMIN) {
1681
1682 case 20:
1683 log_debug("Enabling showing of status.");
d450b6f2 1684 manager_set_show_status(m, SHOW_STATUS_YES);
0658666b
LP
1685 break;
1686
1687 case 21:
1688 log_debug("Disabling showing of status.");
d450b6f2 1689 manager_set_show_status(m, SHOW_STATUS_NO);
0658666b
LP
1690 break;
1691
253ee27a
LP
1692 case 22:
1693 log_set_max_level(LOG_DEBUG);
1694 log_notice("Setting log level to debug.");
1695 break;
1696
1697 case 23:
1698 log_set_max_level(LOG_INFO);
1699 log_notice("Setting log level to info.");
1700 break;
1701
600b704e
LP
1702 case 24:
1703 if (m->running_as == SYSTEMD_USER) {
1704 m->exit_code = MANAGER_EXIT;
1705 return 0;
1706 }
1707
1708 /* This is a nop on init */
1709 break;
1710
4cfa2c99
LP
1711 case 26:
1712 log_set_target(LOG_TARGET_JOURNAL_OR_KMSG);
1713 log_notice("Setting log target to journal-or-kmsg.");
1714 break;
1715
253ee27a
LP
1716 case 27:
1717 log_set_target(LOG_TARGET_CONSOLE);
1718 log_notice("Setting log target to console.");
1719 break;
1720
1721 case 28:
1722 log_set_target(LOG_TARGET_KMSG);
1723 log_notice("Setting log target to kmsg.");
1724 break;
1725
1726 case 29:
1727 log_set_target(LOG_TARGET_SYSLOG_OR_KMSG);
1728 log_notice("Setting log target to syslog-or-kmsg.");
1729 break;
1730
0658666b 1731 default:
4e240ab0 1732 log_warning("Got unhandled signal <%s>.", signal_to_string(sfsi.ssi_signo));
0658666b 1733 }
b9cd2ec1 1734 }
7d793605 1735 }
9152c765
LP
1736 }
1737
1738 if (sigchld)
7b77ed8c 1739 manager_dispatch_sigchld(m);
034c6ed7
LP
1740
1741 return 0;
1742}
1743
718db961
LP
1744static int manager_dispatch_time_change_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
1745 Manager *m = userdata;
1746 Iterator i;
1747 Unit *u;
034c6ed7
LP
1748
1749 assert(m);
718db961 1750 assert(m->time_change_fd == fd);
034c6ed7 1751
718db961
LP
1752 log_struct(LOG_INFO,
1753 MESSAGE_ID(SD_MESSAGE_TIME_CHANGE),
1754 "MESSAGE=Time has been changed",
1755 NULL);
034c6ed7 1756
718db961
LP
1757 /* Restart the watch */
1758 m->time_change_event_source = sd_event_source_unref(m->time_change_event_source);
acbb0225 1759
718db961
LP
1760 close_nointr_nofail(m->time_change_fd);
1761 m->time_change_fd = -1;
ef734fd6 1762
718db961 1763 manager_setup_time_change(m);
4e434314 1764
718db961
LP
1765 HASHMAP_FOREACH(u, m->units, i)
1766 if (UNIT_VTABLE(u)->time_change)
1767 UNIT_VTABLE(u)->time_change(u);
ea430986 1768
718db961
LP
1769 return 0;
1770}
ea430986 1771
718db961
LP
1772static int manager_dispatch_idle_pipe_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
1773 Manager *m = userdata;
8742514c 1774
718db961
LP
1775 assert(m);
1776 assert(m->idle_pipe[2] == fd);
8742514c 1777
718db961 1778 m->no_console_output = m->n_on_console > 0;
03b717a3 1779
718db961
LP
1780 m->idle_pipe_event_source = sd_event_source_unref(m->idle_pipe_event_source);
1781 manager_close_idle_pipe(m);
03b717a3 1782
718db961
LP
1783 return 0;
1784}
31a7eb86 1785
718db961
LP
1786static int manager_dispatch_jobs_in_progress(sd_event_source *source, usec_t usec, void *userdata) {
1787 Manager *m = userdata;
fd08a840
ZJS
1788 int r;
1789 uint64_t next;
31a7eb86 1790
718db961 1791 assert(m);
fd08a840 1792 assert(source);
9152c765 1793
718db961 1794 manager_print_jobs_in_progress(m);
fd08a840
ZJS
1795
1796 next = now(CLOCK_MONOTONIC) + JOBS_IN_PROGRESS_PERIOD_USEC;
1797 r = sd_event_source_set_time(source, next);
1798 if (r < 0)
1799 return r;
1800
1801 return sd_event_source_set_enabled(source, SD_EVENT_ONESHOT);
9152c765
LP
1802}
1803
1804int manager_loop(Manager *m) {
1805 int r;
9152c765 1806
fac9f8df 1807 RATELIMIT_DEFINE(rl, 1*USEC_PER_SEC, 50000);
ea430986 1808
9152c765 1809 assert(m);
f755e3b7 1810 m->exit_code = MANAGER_OK;
9152c765 1811
fe51822e
LP
1812 /* Release the path cache */
1813 set_free_free(m->unit_path_cache);
1814 m->unit_path_cache = NULL;
1815
b0c918b9
LP
1816 manager_check_finished(m);
1817
a4312405 1818 /* There might still be some zombies hanging around from
f3669545 1819 * before we were exec()'ed. Let's reap them. */
e96d6be7
LP
1820 r = manager_dispatch_sigchld(m);
1821 if (r < 0)
a4312405
LP
1822 return r;
1823
f755e3b7 1824 while (m->exit_code == MANAGER_OK) {
718db961 1825 usec_t wait_usec;
9152c765 1826
67445f4e 1827 if (m->runtime_watchdog > 0 && m->running_as == SYSTEMD_SYSTEM)
e96d6be7
LP
1828 watchdog_ping();
1829
ea430986
LP
1830 if (!ratelimit_test(&rl)) {
1831 /* Yay, something is going seriously wrong, pause a little */
1832 log_warning("Looping too fast. Throttling execution a little.");
1833 sleep(1);
e96d6be7 1834 continue;
ea430986
LP
1835 }
1836
37a8e683 1837 if (manager_dispatch_load_queue(m) > 0)
23a177ef
LP
1838 continue;
1839
cf1265e1 1840 if (manager_dispatch_gc_queue(m) > 0)
701cc384
LP
1841 continue;
1842
cf1265e1 1843 if (manager_dispatch_cleanup_queue(m) > 0)
c1e1601e 1844 continue;
034c6ed7 1845
cf1265e1 1846 if (manager_dispatch_cgroup_queue(m) > 0)
c1e1601e
LP
1847 continue;
1848
c1e1601e 1849 if (manager_dispatch_dbus_queue(m) > 0)
ea430986 1850 continue;
ea430986 1851
c757a65b 1852 /* Sleep for half the watchdog time */
67445f4e 1853 if (m->runtime_watchdog > 0 && m->running_as == SYSTEMD_SYSTEM) {
718db961
LP
1854 wait_usec = m->runtime_watchdog / 2;
1855 if (wait_usec <= 0)
1856 wait_usec = 1;
c757a65b 1857 } else
718db961 1858 wait_usec = (usec_t) -1;
9152c765 1859
718db961
LP
1860 r = sd_event_run(m->event, wait_usec);
1861 if (r < 0) {
1862 log_error("Failed to run event loop: %s", strerror(-r));
957ca890 1863 return r;
718db961 1864 }
a16e1123 1865 }
957ca890 1866
a16e1123 1867 return m->exit_code;
83c60c9f 1868}
ea430986 1869
718db961 1870int manager_load_unit_from_dbus_path(Manager *m, const char *s, sd_bus_error *e, Unit **_u) {
ede3a796 1871 _cleanup_free_ char *n = NULL;
ea430986 1872 Unit *u;
80fbf05e 1873 int r;
ea430986
LP
1874
1875 assert(m);
1876 assert(s);
1877 assert(_u);
1878
ede3a796
LP
1879 r = unit_name_from_dbus_path(s, &n);
1880 if (r < 0)
1881 return r;
ea430986 1882
80fbf05e 1883 r = manager_load_unit(m, n, NULL, e, &u);
80fbf05e
MS
1884 if (r < 0)
1885 return r;
ea430986
LP
1886
1887 *_u = u;
1888
1889 return 0;
1890}
86fbf370
LP
1891
1892int manager_get_job_from_dbus_path(Manager *m, const char *s, Job **_j) {
718db961 1893 const char *p;
86fbf370 1894 unsigned id;
718db961 1895 Job *j;
86fbf370
LP
1896 int r;
1897
1898 assert(m);
1899 assert(s);
1900 assert(_j);
1901
718db961
LP
1902 p = startswith(s, "/org/freedesktop/systemd1/job/");
1903 if (!p)
86fbf370
LP
1904 return -EINVAL;
1905
718db961 1906 r = safe_atou(p, &id);
8742514c 1907 if (r < 0)
86fbf370
LP
1908 return r;
1909
8742514c
LP
1910 j = manager_get_job(m, id);
1911 if (!j)
86fbf370
LP
1912 return -ENOENT;
1913
1914 *_j = j;
1915
1916 return 0;
1917}
dfcd764e 1918
4927fcae 1919void manager_send_unit_audit(Manager *m, Unit *u, int type, bool success) {
e537352b 1920
4927fcae 1921#ifdef HAVE_AUDIT
2ba11090 1922 _cleanup_free_ char *p = NULL;
c1165f82 1923 int audit_fd;
e537352b 1924
c1165f82
LP
1925 audit_fd = get_audit_fd();
1926 if (audit_fd < 0)
e537352b
LP
1927 return;
1928
bbd3a7ba
LP
1929 /* Don't generate audit events if the service was already
1930 * started and we're just deserializing */
a7556052 1931 if (m->n_reloading > 0)
bbd3a7ba
LP
1932 return;
1933
67445f4e 1934 if (m->running_as != SYSTEMD_SYSTEM)
f1dd0c3f
LP
1935 return;
1936
ac155bb8 1937 if (u->type != UNIT_SERVICE)
f1dd0c3f
LP
1938 return;
1939
bd0af849
ZJS
1940 p = unit_name_to_prefix_and_instance(u->id);
1941 if (!p) {
66870f90
ZJS
1942 log_error_unit(u->id,
1943 "Failed to allocate unit name for audit message: %s", strerror(ENOMEM));
e537352b
LP
1944 return;
1945 }
1946
c1165f82 1947 if (audit_log_user_comm_message(audit_fd, type, "", p, NULL, NULL, NULL, success) < 0) {
391ade86
LP
1948 if (errno == EPERM) {
1949 /* We aren't allowed to send audit messages?
44785992 1950 * Then let's not retry again. */
c1165f82 1951 close_audit_fd();
44785992
LP
1952 } else
1953 log_warning("Failed to send audit message: %m");
391ade86 1954 }
4927fcae 1955#endif
e537352b 1956
e537352b
LP
1957}
1958
e983b760 1959void manager_send_unit_plymouth(Manager *m, Unit *u) {
2ba11090 1960 union sockaddr_union sa = {
49888ca9 1961 .un.sun_family = AF_UNIX,
2ba11090
ZJS
1962 .un.sun_path = "\0/org/freedesktop/plymouthd",
1963 };
1964
e983b760 1965 int n = 0;
2ba11090
ZJS
1966 _cleanup_free_ char *message = NULL;
1967 _cleanup_close_ int fd = -1;
e983b760
LP
1968
1969 /* Don't generate plymouth events if the service was already
1970 * started and we're just deserializing */
a7556052 1971 if (m->n_reloading > 0)
e983b760
LP
1972 return;
1973
67445f4e 1974 if (m->running_as != SYSTEMD_SYSTEM)
e983b760
LP
1975 return;
1976
3772995a
LP
1977 if (detect_container(NULL) > 0)
1978 return;
1979
ac155bb8
MS
1980 if (u->type != UNIT_SERVICE &&
1981 u->type != UNIT_MOUNT &&
1982 u->type != UNIT_SWAP)
e983b760
LP
1983 return;
1984
1985 /* We set SOCK_NONBLOCK here so that we rather drop the
1986 * message then wait for plymouth */
e62d8c39
ZJS
1987 fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
1988 if (fd < 0) {
e983b760
LP
1989 log_error("socket() failed: %m");
1990 return;
1991 }
1992
96707269 1993 if (connect(fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + 1 + strlen(sa.un.sun_path+1)) < 0) {
e983b760 1994
2ba11090 1995 if (!IN_SET(errno, EPIPE, EAGAIN, ENOENT, ECONNREFUSED, ECONNRESET, ECONNABORTED))
e983b760 1996 log_error("connect() failed: %m");
2ba11090 1997 return;
e983b760
LP
1998 }
1999
ac155bb8 2000 if (asprintf(&message, "U\002%c%s%n", (int) (strlen(u->id) + 1), u->id, &n) < 0) {
0d0f0c50 2001 log_oom();
2ba11090 2002 return;
e983b760
LP
2003 }
2004
2005 errno = 0;
2ba11090
ZJS
2006 if (write(fd, message, n + 1) != n + 1)
2007 if (!IN_SET(errno, EPIPE, EAGAIN, ENOENT, ECONNREFUSED, ECONNRESET, ECONNABORTED))
e983b760 2008 log_error("Failed to write Plymouth message: %m");
e983b760
LP
2009}
2010
05e343b7
LP
2011void manager_dispatch_bus_name_owner_changed(
2012 Manager *m,
2013 const char *name,
2014 const char* old_owner,
2015 const char *new_owner) {
2016
2017 Unit *u;
2018
2019 assert(m);
2020 assert(name);
2021
718db961
LP
2022 u = hashmap_get(m->watch_bus, name);
2023 if (!u)
05e343b7
LP
2024 return;
2025
2026 UNIT_VTABLE(u)->bus_name_owner_change(u, name, old_owner, new_owner);
2027}
2028
d8d5ab98 2029int manager_open_serialization(Manager *m, FILE **_f) {
8e33886e 2030 const char *path;
df28bc08 2031 int fd = -1;
a16e1123
LP
2032 FILE *f;
2033
2034 assert(_f);
2035
8e33886e
ZJS
2036 path = m->running_as == SYSTEMD_SYSTEM ? "/run/systemd" : "/tmp";
2037 fd = open_tmpfile(path, O_RDWR|O_CLOEXEC);
d86f9d52 2038 if (fd < 0)
a16e1123 2039 return -errno;
a16e1123 2040
a16e1123 2041 log_debug("Serializing state to %s", path);
a16e1123 2042
01e10de3 2043 f = fdopen(fd, "w+");
d86f9d52
LP
2044 if (!f) {
2045 close_nointr_nofail(fd);
a16e1123 2046 return -errno;
d86f9d52 2047 }
a16e1123
LP
2048
2049 *_f = f;
2050
2051 return 0;
2052}
2053
b3680f49 2054int manager_serialize(Manager *m, FILE *f, FDSet *fds, bool switching_root) {
a16e1123
LP
2055 Iterator i;
2056 Unit *u;
2057 const char *t;
4a9fd066 2058 char **e;
a16e1123
LP
2059 int r;
2060
2061 assert(m);
2062 assert(f);
2063 assert(fds);
2064
a7556052 2065 m->n_reloading ++;
38c52d46 2066
01d67b43
LP
2067 fprintf(f, "current-job-id=%i\n", m->current_job_id);
2068 fprintf(f, "taint-usr=%s\n", yes_no(m->taint_usr));
33c5fae9
LP
2069 fprintf(f, "n-installed-jobs=%u\n", m->n_installed_jobs);
2070 fprintf(f, "n-failed-jobs=%u\n", m->n_failed_jobs);
01d67b43 2071
915b3753 2072 dual_timestamp_serialize(f, "firmware-timestamp", &m->firmware_timestamp);
915b3753 2073 dual_timestamp_serialize(f, "loader-timestamp", &m->loader_timestamp);
718db961 2074 dual_timestamp_serialize(f, "kernel-timestamp", &m->kernel_timestamp);
e9ddabc2 2075 dual_timestamp_serialize(f, "initrd-timestamp", &m->initrd_timestamp);
f38ed060 2076
26a1efdf 2077 if (!in_initrd()) {
915b3753 2078 dual_timestamp_serialize(f, "userspace-timestamp", &m->userspace_timestamp);
f38ed060 2079 dual_timestamp_serialize(f, "finish-timestamp", &m->finish_timestamp);
718db961
LP
2080 dual_timestamp_serialize(f, "security-start-timestamp", &m->security_start_timestamp);
2081 dual_timestamp_serialize(f, "security-finish-timestamp", &m->security_finish_timestamp);
2082 dual_timestamp_serialize(f, "generators-start-timestamp", &m->generators_start_timestamp);
2083 dual_timestamp_serialize(f, "generators-finish-timestamp", &m->generators_finish_timestamp);
2084 dual_timestamp_serialize(f, "units-load-start-timestamp", &m->units_load_start_timestamp);
2085 dual_timestamp_serialize(f, "units-load-finish-timestamp", &m->units_load_finish_timestamp);
f38ed060 2086 }
47a483a1 2087
b3680f49
HH
2088 if (!switching_root) {
2089 STRV_FOREACH(e, m->environment) {
2090 _cleanup_free_ char *ce;
4a9fd066 2091
b3680f49 2092 ce = cescape(*e);
e3dd987c
LP
2093 if (!ce)
2094 return -ENOMEM;
2095
2096 fprintf(f, "env=%s\n", *e);
b3680f49 2097 }
4a9fd066
OS
2098 }
2099
d86f9d52
LP
2100 if (m->notify_fd >= 0) {
2101 int copy;
2102
2103 copy = fdset_put_dup(fds, m->notify_fd);
2104 if (copy < 0)
2105 return copy;
2106
2107 fprintf(f, "notify-fd=%i\n", copy);
2108 fprintf(f, "notify-socket=%s\n", m->notify_socket);
2109 }
2110
e3dd987c
LP
2111 if (m->kdbus_fd >= 0) {
2112 int copy;
2113
2114 copy = fdset_put_dup(fds, m->kdbus_fd);
2115 if (copy < 0)
2116 return copy;
2117
2118 fprintf(f, "kdbus-fd=%i\n", copy);
2119 }
2120
8f8f05a9 2121 bus_track_serialize(m->subscribed, f);
6fa48533 2122
f2382a94
LP
2123 fputc('\n', f);
2124
a16e1123 2125 HASHMAP_FOREACH_KEY(u, t, m->units, i) {
ac155bb8 2126 if (u->id != t)
a16e1123
LP
2127 continue;
2128
2129 if (!unit_can_serialize(u))
2130 continue;
2131
2132 /* Start marker */
ac155bb8 2133 fputs(u->id, f);
a16e1123
LP
2134 fputc('\n', f);
2135
6fa48533
LP
2136 r = unit_serialize(u, f, fds, !switching_root);
2137 if (r < 0) {
a7556052 2138 m->n_reloading --;
a16e1123 2139 return r;
38c52d46 2140 }
a16e1123
LP
2141 }
2142
a7556052
LP
2143 assert(m->n_reloading > 0);
2144 m->n_reloading --;
38c52d46 2145
a16e1123
LP
2146 if (ferror(f))
2147 return -EIO;
2148
b23de6af
LP
2149 r = bus_fdset_add_all(m, fds);
2150 if (r < 0)
2151 return r;
2152
a16e1123
LP
2153 return 0;
2154}
2155
2156int manager_deserialize(Manager *m, FILE *f, FDSet *fds) {
2157 int r = 0;
2158
2159 assert(m);
2160 assert(f);
2161
2162 log_debug("Deserializing state...");
2163
a7556052 2164 m->n_reloading ++;
82c64bf5 2165
10f8e83c 2166 for (;;) {
20c03b7b 2167 char line[LINE_MAX], *l;
10f8e83c
LP
2168
2169 if (!fgets(line, sizeof(line), f)) {
2170 if (feof(f))
2171 r = 0;
2172 else
2173 r = -errno;
2174
2175 goto finish;
2176 }
2177
2178 char_array_0(line);
2179 l = strstrip(line);
2180
2181 if (l[0] == 0)
2182 break;
2183
01d67b43
LP
2184 if (startswith(l, "current-job-id=")) {
2185 uint32_t id;
2186
2187 if (safe_atou32(l+15, &id) < 0)
2188 log_debug("Failed to parse current job id value %s", l+15);
2189 else
2190 m->current_job_id = MAX(m->current_job_id, id);
718db961 2191
33c5fae9
LP
2192 } else if (startswith(l, "n-installed-jobs=")) {
2193 uint32_t n;
2194
2195 if (safe_atou32(l+17, &n) < 0)
2196 log_debug("Failed to parse installed jobs counter %s", l+17);
2197 else
2198 m->n_installed_jobs += n;
718db961 2199
33c5fae9
LP
2200 } else if (startswith(l, "n-failed-jobs=")) {
2201 uint32_t n;
2202
2203 if (safe_atou32(l+14, &n) < 0)
2204 log_debug("Failed to parse failed jobs counter %s", l+14);
2205 else
2206 m->n_failed_jobs += n;
718db961 2207
01d67b43
LP
2208 } else if (startswith(l, "taint-usr=")) {
2209 int b;
2210
e3dd987c
LP
2211 b = parse_boolean(l+10);
2212 if (b < 0)
01d67b43
LP
2213 log_debug("Failed to parse taint /usr flag %s", l+10);
2214 else
2215 m->taint_usr = m->taint_usr || b;
718db961 2216
915b3753
LP
2217 } else if (startswith(l, "firmware-timestamp="))
2218 dual_timestamp_deserialize(l+19, &m->firmware_timestamp);
2219 else if (startswith(l, "loader-timestamp="))
2220 dual_timestamp_deserialize(l+17, &m->loader_timestamp);
2221 else if (startswith(l, "kernel-timestamp="))
2222 dual_timestamp_deserialize(l+17, &m->kernel_timestamp);
2223 else if (startswith(l, "initrd-timestamp="))
e9ddabc2 2224 dual_timestamp_deserialize(l+17, &m->initrd_timestamp);
915b3753
LP
2225 else if (startswith(l, "userspace-timestamp="))
2226 dual_timestamp_deserialize(l+20, &m->userspace_timestamp);
10717a1a 2227 else if (startswith(l, "finish-timestamp="))
799fd0fd 2228 dual_timestamp_deserialize(l+17, &m->finish_timestamp);
718db961
LP
2229 else if (startswith(l, "security-start-timestamp="))
2230 dual_timestamp_deserialize(l+25, &m->security_start_timestamp);
2231 else if (startswith(l, "security-finish-timestamp="))
2232 dual_timestamp_deserialize(l+26, &m->security_finish_timestamp);
2233 else if (startswith(l, "generators-start-timestamp="))
2234 dual_timestamp_deserialize(l+27, &m->generators_start_timestamp);
2235 else if (startswith(l, "generators-finish-timestamp="))
2236 dual_timestamp_deserialize(l+28, &m->generators_finish_timestamp);
2237 else if (startswith(l, "units-load-start-timestamp="))
2238 dual_timestamp_deserialize(l+27, &m->units_load_start_timestamp);
2239 else if (startswith(l, "units-load-finish-timestamp="))
2240 dual_timestamp_deserialize(l+28, &m->units_load_finish_timestamp);
4a9fd066
OS
2241 else if (startswith(l, "env=")) {
2242 _cleanup_free_ char *uce = NULL;
2243 char **e;
2244
2245 uce = cunescape(l+4);
2246 if (!uce) {
2247 r = -ENOMEM;
2248 goto finish;
2249 }
2250
2251 e = strv_env_set(m->environment, uce);
2252 if (!e) {
2253 r = -ENOMEM;
2254 goto finish;
2255 }
2256
2257 strv_free(m->environment);
2258 m->environment = e;
e3dd987c 2259
d86f9d52
LP
2260 } else if (startswith(l, "notify-fd=")) {
2261 int fd;
2262
2263 if (safe_atoi(l + 10, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2264 log_debug("Failed to parse notify fd: %s", l + 10);
2265 else {
be04cbca
LP
2266 if (m->notify_fd >= 0) {
2267 m->notify_event_source = sd_event_source_unref(m->notify_event_source);
d86f9d52 2268 close_nointr_nofail(m->notify_fd);
be04cbca 2269 }
d86f9d52
LP
2270
2271 m->notify_fd = fdset_remove(fds, fd);
2272 }
2273
2274 } else if (startswith(l, "notify-socket=")) {
2275 char *n;
2276
2277 n = strdup(l+14);
2278 if (!n) {
2279 r = -ENOMEM;
2280 goto finish;
2281 }
2282
2283 free(m->notify_socket);
2284 m->notify_socket = n;
2285
e3dd987c
LP
2286 } else if (startswith(l, "kdbus-fd=")) {
2287 int fd;
2288
8bf9fcf4 2289 if (safe_atoi(l + 9, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
e3dd987c
LP
2290 log_debug("Failed to parse kdbus fd: %s", l + 9);
2291 else {
2292 if (m->kdbus_fd >= 0)
2293 close_nointr_nofail(m->kdbus_fd);
2294
2295 m->kdbus_fd = fdset_remove(fds, fd);
2296 }
2297
8f8f05a9 2298 } else if (bus_track_deserialize_item(&m->deserialized_subscribed, l) == 0)
10f8e83c
LP
2299 log_debug("Unknown serialization item '%s'", l);
2300 }
2301
a16e1123
LP
2302 for (;;) {
2303 Unit *u;
2304 char name[UNIT_NAME_MAX+2];
2305
2306 /* Start marker */
2307 if (!fgets(name, sizeof(name), f)) {
2308 if (feof(f))
10f8e83c
LP
2309 r = 0;
2310 else
2311 r = -errno;
a16e1123 2312
82c64bf5 2313 goto finish;
a16e1123
LP
2314 }
2315
2316 char_array_0(name);
2317
bd0af849
ZJS
2318 r = manager_load_unit(m, strstrip(name), NULL, NULL, &u);
2319 if (r < 0)
82c64bf5 2320 goto finish;
a16e1123 2321
01e10de3
LP
2322 r = unit_deserialize(u, f, fds);
2323 if (r < 0)
82c64bf5 2324 goto finish;
a16e1123
LP
2325 }
2326
10f8e83c 2327finish:
145b1f79 2328 if (ferror(f))
82c64bf5 2329 r = -EIO;
a16e1123 2330
a7556052
LP
2331 assert(m->n_reloading > 0);
2332 m->n_reloading --;
82c64bf5
LP
2333
2334 return r;
a16e1123
LP
2335}
2336
2337int manager_reload(Manager *m) {
2338 int r, q;
51d122af
ZJS
2339 _cleanup_fclose_ FILE *f = NULL;
2340 _cleanup_fdset_free_ FDSet *fds = NULL;
a16e1123
LP
2341
2342 assert(m);
2343
07719a21
LP
2344 r = manager_open_serialization(m, &f);
2345 if (r < 0)
a16e1123
LP
2346 return r;
2347
a7556052 2348 m->n_reloading ++;
718db961 2349 bus_manager_send_reloading(m, true);
38c52d46 2350
07719a21
LP
2351 fds = fdset_new();
2352 if (!fds) {
a7556052 2353 m->n_reloading --;
51d122af 2354 return -ENOMEM;
a16e1123
LP
2355 }
2356
b3680f49 2357 r = manager_serialize(m, f, fds, false);
07719a21 2358 if (r < 0) {
a7556052 2359 m->n_reloading --;
51d122af 2360 return r;
38c52d46 2361 }
a16e1123
LP
2362
2363 if (fseeko(f, 0, SEEK_SET) < 0) {
a7556052 2364 m->n_reloading --;
51d122af 2365 return -errno;
a16e1123
LP
2366 }
2367
2368 /* From here on there is no way back. */
2369 manager_clear_jobs_and_units(m);
5a1e9937 2370 manager_undo_generators(m);
84e3543e 2371 lookup_paths_free(&m->lookup_paths);
2ded0c04 2372
07719a21 2373 /* Find new unit paths */
5a1e9937
LP
2374 manager_run_generators(m);
2375
07719a21
LP
2376 q = lookup_paths_init(
2377 &m->lookup_paths, m->running_as, true,
2378 m->generator_unit_path,
2379 m->generator_unit_path_early,
2380 m->generator_unit_path_late);
2381 if (q < 0)
2382 r = q;
2383
5a1e9937
LP
2384 manager_build_unit_path_cache(m);
2385
a16e1123 2386 /* First, enumerate what we can from all config files */
07719a21
LP
2387 q = manager_enumerate(m);
2388 if (q < 0)
a16e1123
LP
2389 r = q;
2390
2391 /* Second, deserialize our stored data */
07719a21
LP
2392 q = manager_deserialize(m, f, fds);
2393 if (q < 0)
a16e1123
LP
2394 r = q;
2395
2396 fclose(f);
2397 f = NULL;
2398
a2cc4a6c
ZJS
2399 /* Re-register notify_fd as event source */
2400 q = manager_setup_notify(m);
2401 if (q < 0)
2402 r = q;
2403
a16e1123 2404 /* Third, fire things up! */
07719a21
LP
2405 q = manager_coldplug(m);
2406 if (q < 0)
a16e1123
LP
2407 r = q;
2408
a7556052
LP
2409 assert(m->n_reloading > 0);
2410 m->n_reloading--;
9f611ad8 2411
71445ae7
LP
2412 m->send_reloading_done = true;
2413
a16e1123
LP
2414 return r;
2415}
2416
6084e22e 2417static bool manager_is_booting_or_shutting_down(Manager *m) {
9e58ff9c
LP
2418 Unit *u;
2419
2420 assert(m);
2421
2422 /* Is the initial job still around? */
bacbccb7 2423 if (manager_get_job(m, m->default_unit_job_id))
9e58ff9c
LP
2424 return true;
2425
2426 /* Is there a job for the shutdown target? */
27d340c7
LP
2427 u = manager_get_unit(m, SPECIAL_SHUTDOWN_TARGET);
2428 if (u)
ac155bb8 2429 return !!u->job;
9e58ff9c
LP
2430
2431 return false;
2432}
2433
c17ec25e
MS
2434bool manager_is_reloading_or_reexecuting(Manager *m) {
2435 assert(m);
2436
2437 return m->n_reloading != 0;
2438}
2439
fdf20a31 2440void manager_reset_failed(Manager *m) {
5632e374
LP
2441 Unit *u;
2442 Iterator i;
2443
2444 assert(m);
2445
2446 HASHMAP_FOREACH(u, m->units, i)
fdf20a31 2447 unit_reset_failed(u);
5632e374
LP
2448}
2449
31afa0a4 2450bool manager_unit_inactive_or_pending(Manager *m, const char *name) {
8f6df3fa
LP
2451 Unit *u;
2452
2453 assert(m);
2454 assert(name);
2455
2456 /* Returns true if the unit is inactive or going down */
bd0af849
ZJS
2457 u = manager_get_unit(m, name);
2458 if (!u)
8f6df3fa
LP
2459 return true;
2460
31afa0a4 2461 return unit_inactive_or_pending(u);
8f6df3fa
LP
2462}
2463
b0c918b9 2464void manager_check_finished(Manager *m) {
7ceba241 2465 char userspace[FORMAT_TIMESPAN_MAX], initrd[FORMAT_TIMESPAN_MAX], kernel[FORMAT_TIMESPAN_MAX], sum[FORMAT_TIMESPAN_MAX];
915b3753 2466 usec_t firmware_usec, loader_usec, kernel_usec, initrd_usec, userspace_usec, total_usec;
b0c918b9
LP
2467
2468 assert(m);
2469
a0b64226 2470 if (m->n_running_jobs == 0)
718db961 2471 m->jobs_in_progress_event_source = sd_event_source_unref(m->jobs_in_progress_event_source);
a0b64226 2472
828db5d8 2473 if (hashmap_size(m->jobs) > 0) {
f755e3b7 2474
fd08a840 2475 if (m->jobs_in_progress_event_source) {
f755e3b7
LP
2476 sd_event_source_set_time(m->jobs_in_progress_event_source,
2477 now(CLOCK_MONOTONIC) + JOBS_IN_PROGRESS_WAIT_USEC);
fd08a840 2478 }
f755e3b7 2479
b0c918b9 2480 return;
5b176ee0 2481 }
b0c918b9 2482
cb8ccb22 2483 manager_flip_auto_status(m, false);
d450b6f2 2484
f2b68789 2485 /* Notify Type=idle units that we are done now */
718db961
LP
2486 m->idle_pipe_event_source = sd_event_source_unref(m->idle_pipe_event_source);
2487 manager_close_idle_pipe(m);
f2b68789 2488
af6da548
LP
2489 /* Turn off confirm spawn now */
2490 m->confirm_spawn = false;
2491
f2b68789 2492 if (dual_timestamp_is_set(&m->finish_timestamp))
b0c918b9
LP
2493 return;
2494
2495 dual_timestamp_get(&m->finish_timestamp);
2496
67445f4e 2497 if (m->running_as == SYSTEMD_SYSTEM && detect_container(NULL) <= 0) {
e03ae661 2498
915b3753
LP
2499 /* Note that m->kernel_usec.monotonic is always at 0,
2500 * and m->firmware_usec.monotonic and
2501 * m->loader_usec.monotonic should be considered
2502 * negative values. */
2503
7ceba241
LP
2504 firmware_usec = m->firmware_timestamp.monotonic - m->loader_timestamp.monotonic;
2505 loader_usec = m->loader_timestamp.monotonic - m->kernel_timestamp.monotonic;
915b3753 2506 userspace_usec = m->finish_timestamp.monotonic - m->userspace_timestamp.monotonic;
7ceba241 2507 total_usec = m->firmware_timestamp.monotonic + m->finish_timestamp.monotonic;
18fa6b27 2508
e9ddabc2 2509 if (dual_timestamp_is_set(&m->initrd_timestamp)) {
18fa6b27 2510
915b3753
LP
2511 kernel_usec = m->initrd_timestamp.monotonic - m->kernel_timestamp.monotonic;
2512 initrd_usec = m->userspace_timestamp.monotonic - m->initrd_timestamp.monotonic;
18fa6b27 2513
81270860
LP
2514 if (!log_on_console())
2515 log_struct(LOG_INFO,
1ca6783f 2516 MESSAGE_ID(SD_MESSAGE_STARTUP_FINISHED),
ccd06097
ZJS
2517 "KERNEL_USEC="USEC_FMT, kernel_usec,
2518 "INITRD_USEC="USEC_FMT, initrd_usec,
2519 "USERSPACE_USEC="USEC_FMT, userspace_usec,
81270860 2520 "MESSAGE=Startup finished in %s (kernel) + %s (initrd) + %s (userspace) = %s.",
2fa4092c
LP
2521 format_timespan(kernel, sizeof(kernel), kernel_usec, USEC_PER_MSEC),
2522 format_timespan(initrd, sizeof(initrd), initrd_usec, USEC_PER_MSEC),
2523 format_timespan(userspace, sizeof(userspace), userspace_usec, USEC_PER_MSEC),
2524 format_timespan(sum, sizeof(sum), total_usec, USEC_PER_MSEC),
81270860 2525 NULL);
18fa6b27 2526 } else {
915b3753 2527 kernel_usec = m->userspace_timestamp.monotonic - m->kernel_timestamp.monotonic;
18fa6b27
LP
2528 initrd_usec = 0;
2529
81270860
LP
2530 if (!log_on_console())
2531 log_struct(LOG_INFO,
1ca6783f 2532 MESSAGE_ID(SD_MESSAGE_STARTUP_FINISHED),
ccd06097
ZJS
2533 "KERNEL_USEC="USEC_FMT, kernel_usec,
2534 "USERSPACE_USEC="USEC_FMT, userspace_usec,
81270860 2535 "MESSAGE=Startup finished in %s (kernel) + %s (userspace) = %s.",
2fa4092c
LP
2536 format_timespan(kernel, sizeof(kernel), kernel_usec, USEC_PER_MSEC),
2537 format_timespan(userspace, sizeof(userspace), userspace_usec, USEC_PER_MSEC),
2538 format_timespan(sum, sizeof(sum), total_usec, USEC_PER_MSEC),
81270860 2539 NULL);
18fa6b27
LP
2540 }
2541 } else {
915b3753
LP
2542 firmware_usec = loader_usec = initrd_usec = kernel_usec = 0;
2543 total_usec = userspace_usec = m->finish_timestamp.monotonic - m->userspace_timestamp.monotonic;
877d54e9 2544
81270860
LP
2545 if (!log_on_console())
2546 log_struct(LOG_INFO,
1ca6783f 2547 MESSAGE_ID(SD_MESSAGE_STARTUP_FINISHED),
ccd06097 2548 "USERSPACE_USEC="USEC_FMT, userspace_usec,
81270860 2549 "MESSAGE=Startup finished in %s.",
2fa4092c 2550 format_timespan(sum, sizeof(sum), total_usec, USEC_PER_MSEC),
81270860 2551 NULL);
18fa6b27 2552 }
b0c918b9 2553
718db961 2554 bus_manager_send_finished(m, firmware_usec, loader_usec, kernel_usec, initrd_usec, userspace_usec, total_usec);
530345e7
LP
2555
2556 sd_notifyf(false,
2557 "READY=1\nSTATUS=Startup finished in %s.",
2fa4092c 2558 format_timespan(sum, sizeof(sum), total_usec, USEC_PER_MSEC));
b0c918b9
LP
2559}
2560
07719a21
LP
2561static int create_generator_dir(Manager *m, char **generator, const char *name) {
2562 char *p;
2563 int r;
2564
2565 assert(m);
2566 assert(generator);
2567 assert(name);
2568
2569 if (*generator)
2570 return 0;
2571
67445f4e 2572 if (m->running_as == SYSTEMD_SYSTEM && getpid() == 1) {
fcc81ea3 2573 /* systemd --system, not running --test */
07719a21
LP
2574
2575 p = strappend("/run/systemd/", name);
0d0f0c50
SL
2576 if (!p)
2577 return log_oom();
07719a21 2578
fcc81ea3
KS
2579 r = mkdir_p_label(p, 0755);
2580 if (r < 0) {
2581 log_error("Failed to create generator directory %s: %s",
2582 p, strerror(-r));
2583 free(p);
2584 return r;
2585 }
2586 } else if (m->running_as == SYSTEMD_USER) {
2587 const char *s = NULL;
2588
2589 s = getenv("XDG_RUNTIME_DIR");
2590 if (!s)
2591 return -EINVAL;
2592 p = strjoin(s, "/systemd/", name, NULL);
2593 if (!p)
2594 return log_oom();
2595
d2e54fae 2596 r = mkdir_p_label(p, 0755);
07719a21 2597 if (r < 0) {
7ad94c71
ZJS
2598 log_error("Failed to create generator directory %s: %s",
2599 p, strerror(-r));
07719a21
LP
2600 free(p);
2601 return r;
2602 }
2603 } else {
fcc81ea3
KS
2604 /* systemd --system --test */
2605
b7def684 2606 p = strjoin("/tmp/systemd-", name, ".XXXXXX", NULL);
0d0f0c50
SL
2607 if (!p)
2608 return log_oom();
07719a21
LP
2609
2610 if (!mkdtemp(p)) {
7ad94c71
ZJS
2611 log_error("Failed to create generator directory %s: %m",
2612 p);
34bf0281 2613 free(p);
07719a21
LP
2614 return -errno;
2615 }
2616 }
2617
2618 *generator = p;
2619 return 0;
2620}
2621
2622static void trim_generator_dir(Manager *m, char **generator) {
2623 assert(m);
2624 assert(generator);
2625
2626 if (!*generator)
2627 return;
2628
2629 if (rmdir(*generator) >= 0) {
2630 free(*generator);
2631 *generator = NULL;
2632 }
2633
2634 return;
2635}
2636
5a1e9937 2637void manager_run_generators(Manager *m) {
718db961 2638 _cleanup_closedir_ DIR *d = NULL;
5a1e9937 2639 const char *generator_path;
07719a21 2640 const char *argv[5];
07719a21 2641 int r;
5a1e9937
LP
2642
2643 assert(m);
2644
67445f4e 2645 generator_path = m->running_as == SYSTEMD_SYSTEM ? SYSTEM_GENERATOR_PATH : USER_GENERATOR_PATH;
07719a21
LP
2646 d = opendir(generator_path);
2647 if (!d) {
5a1e9937
LP
2648 if (errno == ENOENT)
2649 return;
2650
7ad94c71
ZJS
2651 log_error("Failed to enumerate generator directory %s: %m",
2652 generator_path);
5a1e9937
LP
2653 return;
2654 }
2655
07719a21
LP
2656 r = create_generator_dir(m, &m->generator_unit_path, "generator");
2657 if (r < 0)
2658 goto finish;
f1d19aa4 2659
07719a21
LP
2660 r = create_generator_dir(m, &m->generator_unit_path_early, "generator.early");
2661 if (r < 0)
2662 goto finish;
5a1e9937 2663
07719a21
LP
2664 r = create_generator_dir(m, &m->generator_unit_path_late, "generator.late");
2665 if (r < 0)
2666 goto finish;
5a1e9937 2667
83cc030f
LP
2668 argv[0] = NULL; /* Leave this empty, execute_directory() will fill something in */
2669 argv[1] = m->generator_unit_path;
07719a21
LP
2670 argv[2] = m->generator_unit_path_early;
2671 argv[3] = m->generator_unit_path_late;
2672 argv[4] = NULL;
5a1e9937 2673
718db961 2674 RUN_WITH_UMASK(0022)
aa62a893 2675 execute_directory(generator_path, d, DEFAULT_TIMEOUT_USEC, (char**) argv);
5a1e9937 2676
718db961 2677finish:
07719a21
LP
2678 trim_generator_dir(m, &m->generator_unit_path);
2679 trim_generator_dir(m, &m->generator_unit_path_early);
2680 trim_generator_dir(m, &m->generator_unit_path_late);
5a1e9937
LP
2681}
2682
07719a21 2683static void remove_generator_dir(Manager *m, char **generator) {
5a1e9937 2684 assert(m);
07719a21 2685 assert(generator);
5a1e9937 2686
07719a21 2687 if (!*generator)
5a1e9937
LP
2688 return;
2689
07719a21
LP
2690 strv_remove(m->lookup_paths.unit_path, *generator);
2691 rm_rf(*generator, false, true, false);
5a1e9937 2692
07719a21
LP
2693 free(*generator);
2694 *generator = NULL;
2695}
2696
2697void manager_undo_generators(Manager *m) {
2698 assert(m);
2699
2700 remove_generator_dir(m, &m->generator_unit_path);
2701 remove_generator_dir(m, &m->generator_unit_path_early);
2702 remove_generator_dir(m, &m->generator_unit_path_late);
5a1e9937
LP
2703}
2704
718db961
LP
2705int manager_environment_add(Manager *m, char **minus, char **plus) {
2706 char **a = NULL, **b = NULL, **l;
97d0e5f8 2707 assert(m);
bcd8e6d1 2708
718db961 2709 l = m->environment;
bcd8e6d1 2710
718db961
LP
2711 if (!strv_isempty(minus)) {
2712 a = strv_env_delete(l, 1, minus);
2713 if (!a)
2714 return -ENOMEM;
2715
2716 l = a;
2717 }
2718
2719 if (!strv_isempty(plus)) {
2720 b = strv_env_merge(2, l, plus);
2721 if (!b)
2722 return -ENOMEM;
bcd8e6d1 2723
718db961
LP
2724 l = b;
2725 }
2726
2727 if (m->environment != l)
2728 strv_free(m->environment);
2729 if (a != l)
2730 strv_free(a);
2731 if (b != l)
2732 strv_free(b);
2733
f069efb4
LP
2734 m->environment = l;
2735 manager_clean_environment(m);
2736 strv_sort(m->environment);
2737
97d0e5f8
UTL
2738 return 0;
2739}
2740
c93ff2e9
FC
2741int manager_set_default_rlimits(Manager *m, struct rlimit **default_rlimit) {
2742 int i;
2743
2744 assert(m);
2745
517d56b1 2746 for (i = 0; i < _RLIMIT_MAX; i++) {
07719a21
LP
2747 if (!default_rlimit[i])
2748 continue;
c93ff2e9 2749
07719a21
LP
2750 m->rlimit[i] = newdup(struct rlimit, default_rlimit[i], 1);
2751 if (!m->rlimit[i])
2752 return -ENOMEM;
c93ff2e9
FC
2753 }
2754
2755 return 0;
2756}
2757
4cfa2c99 2758void manager_recheck_journal(Manager *m) {
f1dd0c3f
LP
2759 Unit *u;
2760
2761 assert(m);
2762
67445f4e 2763 if (m->running_as != SYSTEMD_SYSTEM)
f1dd0c3f
LP
2764 return;
2765
731a676c
LP
2766 u = manager_get_unit(m, SPECIAL_JOURNALD_SOCKET);
2767 if (u && SOCKET(u)->state != SOCKET_RUNNING) {
4cfa2c99 2768 log_close_journal();
731a676c 2769 return;
f1dd0c3f
LP
2770 }
2771
731a676c
LP
2772 u = manager_get_unit(m, SPECIAL_JOURNALD_SERVICE);
2773 if (u && SERVICE(u)->state != SERVICE_RUNNING) {
4cfa2c99 2774 log_close_journal();
731a676c
LP
2775 return;
2776 }
f1dd0c3f 2777
731a676c
LP
2778 /* Hmm, OK, so the socket is fully up and the service is up
2779 * too, then let's make use of the thing. */
f1dd0c3f
LP
2780 log_open();
2781}
2782
d450b6f2 2783void manager_set_show_status(Manager *m, ShowStatus mode) {
27d340c7 2784 assert(m);
d450b6f2 2785 assert(IN_SET(mode, SHOW_STATUS_AUTO, SHOW_STATUS_NO, SHOW_STATUS_YES, SHOW_STATUS_TEMPORARY));
27d340c7 2786
67445f4e 2787 if (m->running_as != SYSTEMD_SYSTEM)
27d340c7
LP
2788 return;
2789
d450b6f2 2790 m->show_status = mode;
27d340c7 2791
d450b6f2 2792 if (mode > 0)
27d340c7
LP
2793 touch("/run/systemd/show-status");
2794 else
2795 unlink("/run/systemd/show-status");
2796}
2797
6084e22e 2798static bool manager_get_show_status(Manager *m) {
27d340c7
LP
2799 assert(m);
2800
67445f4e 2801 if (m->running_as != SYSTEMD_SYSTEM)
27d340c7
LP
2802 return false;
2803
31a7eb86
ZJS
2804 if (m->no_console_output)
2805 return false;
2806
d450b6f2 2807 if (m->show_status > 0)
27d340c7
LP
2808 return true;
2809
2810 /* If Plymouth is running make sure we show the status, so
2811 * that there's something nice to see when people press Esc */
2812
2813 return plymouth_running();
2814}
68b29a9f 2815
984a2be4 2816void manager_status_printf(Manager *m, bool ephemeral, const char *status, const char *format, ...) {
25cee550
MS
2817 va_list ap;
2818
2819 if (!manager_get_show_status(m))
2820 return;
2821
03b717a3
MS
2822 /* XXX We should totally drop the check for ephemeral here
2823 * and thus effectively make 'Type=idle' pointless. */
2824 if (ephemeral && m->n_on_console > 0)
2825 return;
2826
25cee550
MS
2827 if (!manager_is_booting_or_shutting_down(m))
2828 return;
2829
2830 va_start(ap, format);
984a2be4 2831 status_vprintf(status, true, ephemeral, format, ap);
25cee550
MS
2832 va_end(ap);
2833}
2834
a57f7e2c
LP
2835int manager_get_unit_by_path(Manager *m, const char *path, const char *suffix, Unit **_found) {
2836 _cleanup_free_ char *p = NULL;
2837 Unit *found;
2838
2839 assert(m);
2840 assert(path);
2841 assert(suffix);
2842 assert(_found);
2843
2844 p = unit_name_from_path(path, suffix);
2845 if (!p)
2846 return -ENOMEM;
2847
2848 found = manager_get_unit(m, p);
2849 if (!found) {
2850 *_found = NULL;
2851 return 0;
2852 }
2853
2854 *_found = found;
2855 return 1;
2856}
2857
2858Set *manager_get_units_requiring_mounts_for(Manager *m, const char *path) {
2859 char p[strlen(path)+1];
2860
2861 assert(m);
2862 assert(path);
2863
2864 strcpy(p, path);
2865 path_kill_slashes(p);
2866
2867 return hashmap_get(m->units_requiring_mounts_for, streq(p, "/") ? "" : p);
2868}
e66cf1a3
LP
2869
2870const char *manager_get_runtime_prefix(Manager *m) {
f755e3b7 2871 assert(m);
e66cf1a3
LP
2872
2873 return m->running_as == SYSTEMD_SYSTEM ?
2874 "/run" :
2875 getenv("XDG_RUNTIME_DIR");
2876}
f755e3b7
LP
2877
2878ManagerState manager_state(Manager *m) {
2879 Unit *u;
2880
2881 assert(m);
2882
2883 /* Did we ever finish booting? If not then we are still starting up */
2884 if (!dual_timestamp_is_set(&m->finish_timestamp))
2885 return MANAGER_STARTING;
2886
2887 /* Is the special shutdown target queued? If so, we are in shutdown state */
2888 u = manager_get_unit(m, SPECIAL_SHUTDOWN_TARGET);
2889 if (u && u->job && IN_SET(u->job->type, JOB_START, JOB_RESTART, JOB_TRY_RESTART, JOB_RELOAD_OR_START))
2890 return MANAGER_STOPPING;
2891
2892 /* Are the rescue or emergency targets active or queued? If so we are in maintenance state */
2893 u = manager_get_unit(m, SPECIAL_RESCUE_TARGET);
2894 if (u && (UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)) ||
2895 (u->job && IN_SET(u->job->type, JOB_START, JOB_RESTART, JOB_TRY_RESTART, JOB_RELOAD_OR_START))))
2896 return MANAGER_MAINTENANCE;
2897
2898 u = manager_get_unit(m, SPECIAL_EMERGENCY_TARGET);
2899 if (u && (UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)) ||
2900 (u->job && IN_SET(u->job->type, JOB_START, JOB_RESTART, JOB_TRY_RESTART, JOB_RELOAD_OR_START))))
2901 return MANAGER_MAINTENANCE;
2902
2903 /* Are there any failed units? If so, we are in degraded mode */
2904 if (set_size(m->failed_units) > 0)
2905 return MANAGER_DEGRADED;
2906
2907 return MANAGER_RUNNING;
2908}
2909
2910static const char *const manager_state_table[_MANAGER_STATE_MAX] = {
2911 [MANAGER_STARTING] = "starting",
2912 [MANAGER_RUNNING] = "running",
2913 [MANAGER_DEGRADED] = "degraded",
2914 [MANAGER_MAINTENANCE] = "maintenance",
2915 [MANAGER_STOPPING] = "stopping",
2916};
2917
2918DEFINE_STRING_TABLE_LOOKUP(manager_state, ManagerState);