manager.c revision e5723c894db1ead8a10ffb1800e53e9064656d7e
/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
/***
This file is part of systemd.
Copyright 2010 Lennart Poettering
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
systemd is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with systemd; If not, see <http://www.gnu.org/licenses/>.
***/
#include <assert.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <termios.h>
#include <fcntl.h>
#include <dirent.h>
#ifdef HAVE_AUDIT
#include <libaudit.h>
#endif
#include "sd-daemon.h"
#include "sd-id128.h"
#include "sd-messages.h"
#include "manager.h"
#include "transaction.h"
#include "hashmap.h"
#include "macro.h"
#include "strv.h"
#include "log.h"
#include "util.h"
#include "mkdir.h"
#include "ratelimit.h"
#include "locale-setup.h"
#include "mount-setup.h"
#include "unit-name.h"
#include "missing.h"
#include "path-lookup.h"
#include "special.h"
#include "exit-status.h"
#include "virt.h"
#include "watchdog.h"
#include "cgroup-util.h"
#include "path-util.h"
#include "audit-fd.h"
#include "boot-timestamps.h"
#include "env-util.h"
#include "bus-errors.h"
#include "bus-error.h"
#include "bus-util.h"
#include "dbus.h"
#include "dbus-unit.h"
#include "dbus-job.h"
#include "dbus-manager.h"
#include "bus-kernel.h"
/* As soon as 5s passed since a unit was added to our GC queue, make sure to run a gc sweep */
/* Initial delay and the interval for printing status messages about running jobs */
#define JOBS_IN_PROGRESS_PERIOD_DIVISOR 3
/* Where clients shall send notification messages to */
#define NOTIFY_SOCKET "@/org/freedesktop/systemd1/notify"
static int manager_dispatch_notify_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
static int manager_dispatch_signal_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
static int manager_dispatch_time_change_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
static int manager_dispatch_idle_pipe_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
static int manager_watch_jobs_in_progress(Manager *m) {
assert(m);
if (m->jobs_in_progress_event_source)
return 0;
return sd_event_add_monotonic(m->event, next, 0, manager_dispatch_jobs_in_progress, m, &m->jobs_in_progress_event_source);
}
#define CYLON_BUFFER_EXTRA (2*(sizeof(ANSI_RED_ON)-1) + sizeof(ANSI_HIGHLIGHT_RED_ON)-1 + 2*(sizeof(ANSI_HIGHLIGHT_OFF)-1))
char *p = buffer;
if (pos > 1) {
if (pos > 2)
p = stpcpy(p, ANSI_RED_ON);
*p++ = '*';
}
p = stpcpy(p, ANSI_HIGHLIGHT_RED_ON);
*p++ = '*';
}
p = stpcpy(p, ANSI_HIGHLIGHT_OFF);
p = stpcpy(p, ANSI_RED_ON);
*p++ = '*';
strcpy(p, ANSI_HIGHLIGHT_OFF);
}
}
if (enable) {
if (m->show_status == SHOW_STATUS_AUTO)
} else {
if (m->show_status == SHOW_STATUS_TEMPORARY)
}
}
static void manager_print_jobs_in_progress(Manager *m) {
Iterator i;
Job *j;
unsigned cylon_pos;
uint64_t x;
assert(m);
manager_flip_auto_status(m, true);
HASHMAP_FOREACH(j, m->jobs, i)
break;
/* m->n_running_jobs must be consistent with the contents of m->jobs,
* so the above loop must have succeeded in finding j. */
assert(j);
if (cylon_pos >= 8)
if (m->n_running_jobs > 1)
if (job_get_timeout(j, &x) > 0)
manager_status_printf(m, false, cylon,
"%sA %s job is running for %s (%s / %s)",
job_type_to_string(j->type),
unit_description(j->unit),
}
static int manager_watch_idle_pipe(Manager *m) {
int r;
assert(m);
if (m->idle_pipe_event_source)
return 0;
if (m->idle_pipe[2] < 0)
return 0;
r = sd_event_add_io(m->event, m->idle_pipe[2], EPOLLIN, manager_dispatch_idle_pipe_fd, m, &m->idle_pipe_event_source);
if (r < 0) {
return r;
}
return 0;
}
static void manager_close_idle_pipe(Manager *m) {
assert(m);
close_pipe(m->idle_pipe);
}
static int manager_setup_time_change(Manager *m) {
int r;
/* We only care for the cancellation event, hence we set the
* timeout to the latest possible value. */
struct itimerspec its = {
};
assert(m);
/* Uses TFD_TIMER_CANCEL_ON_SET to get notifications whenever
* CLOCK_REALTIME makes a jump relative to CLOCK_MONOTONIC */
if (m->time_change_fd < 0) {
log_error("Failed to create timerfd: %m");
return -errno;
}
if (timerfd_settime(m->time_change_fd, TFD_TIMER_ABSTIME|TFD_TIMER_CANCEL_ON_SET, &its, NULL) < 0) {
log_debug("Failed to set up TFD_TIMER_CANCEL_ON_SET, ignoring: %m");
m->time_change_fd = -1;
return 0;
}
r = sd_event_add_io(m->event, m->time_change_fd, EPOLLIN, manager_dispatch_time_change_fd, m, &m->time_change_event_source);
if (r < 0) {
return r;
}
log_debug("Set up TFD_TIMER_CANCEL_ON_SET timerfd.");
return 0;
}
static int enable_special_signals(Manager *m) {
assert(m);
/* Enable that we get SIGINT on control-alt-del. In containers
* this will fail with EPERM (older) or EINVAL (newer), so
* ignore that. */
log_warning("Failed to enable ctrl-alt-del handling: %m");
if (fd < 0) {
/* Support systems without virtual console */
log_warning("Failed to open /dev/tty0: %m");
} else {
/* Enable that we get SIGWINCH on kbrequest */
log_warning("Failed to enable kbrequest handling: %m");
}
return 0;
}
static int manager_setup_signals(Manager *m) {
.sa_handler = SIG_DFL,
};
int r;
assert(m);
/* We are not interested in SIGSTOP and friends. */
SIGCHLD, /* Child died */
SIGTERM, /* Reexecute daemon */
SIGHUP, /* Reload configuration */
SIGUSR2, /* systemd: dump status */
SIGINT, /* Kernel sends us this on control-alt-del */
SIGWINCH, /* Kernel sends us this on kbrequest (alt-arrowup) */
SIGPWR, /* Some kernel drivers and upsd send us this on power failure */
-1);
if (m->signal_fd < 0)
return -errno;
r = sd_event_add_io(m->event, m->signal_fd, EPOLLIN, manager_dispatch_signal_fd, m, &m->signal_event_source);
if (r < 0)
return r;
/* Process signals a bit earlier than the rest of things, but
* later that notify_fd processing, so that the notify
* message belongs, before we reap the process. */
if (r < 0)
return r;
if (m->running_as == SYSTEMD_SYSTEM)
return enable_special_signals(m);
return 0;
}
static void manager_clean_environment(Manager *m) {
assert(m);
/* Let's remove some environment variables that we
* need ourselves to communicate with our clients */
m->environment,
"NOTIFY_SOCKET",
"MAINPID",
"MANAGERPID",
"LISTEN_PID",
"LISTEN_FDS",
"WATCHDOG_PID",
"WATCHDOG_USEC",
NULL);
}
static int manager_default_environment(Manager *m) {
assert(m);
if (m->running_as == SYSTEMD_SYSTEM) {
/* The system manager always starts with a clean
* environment for its children. It does not import
* the kernel or the parents exported variables.
*
* The initial passed environ is untouched to keep
* the init process inside containers. */
NULL);
/* Import locale variables LC_*= from configuration */
locale_setup(&m->environment);
} else {
/* The user manager passes its own environment
* along to its children. */
}
if (!m->environment)
return -ENOMEM;
strv_sort(m->environment);
return 0;
}
Manager *m;
int r;
assert(running_as >= 0);
if (!m)
return -ENOMEM;
#ifdef ENABLE_EFI
if (detect_container(NULL) <= 0)
#endif
m->running_as = running_as;
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;
r = manager_default_environment(m);
if (r < 0)
goto fail;
if (r < 0)
goto fail;
if (r < 0)
goto fail;
if (r < 0)
goto fail;
if (r < 0)
goto fail;
if (r < 0)
goto fail;
r = sd_event_default(&m->event);
if (r < 0)
goto fail;
if (r < 0)
goto fail;
if (r < 0)
goto fail;
if (r < 0)
goto fail;
r = manager_setup_signals(m);
if (r < 0)
goto fail;
r = manager_setup_cgroup(m);
if (r < 0)
goto fail;
r = manager_setup_time_change(m);
if (r < 0)
goto fail;
if (!m->udev) {
r = -ENOMEM;
goto fail;
}
/* Note that we set up neither kdbus, nor the notify fd
* here. We do that after deserialization, since they might
* have gotten serialized across the reexec. */
*_m = m;
return 0;
fail:
manager_free(m);
return r;
}
static int manager_setup_notify(Manager *m) {
union {
struct sockaddr_un un;
} sa = {
};
int one = 1, r;
if (m->notify_fd < 0) {
/* First free all secondary fields */
free(m->notify_socket);
m->notify_socket = NULL;
if (fd < 0) {
log_error("Failed to allocate notification socket: %m");
return -errno;
}
else
if (r < 0) {
log_error("bind() failed: %m");
return -errno;
}
if (r < 0) {
log_error("SO_PASSCRED failed: %m");
return -errno;
}
if (!m->notify_socket)
return log_oom();
fd = -1;
}
if (!m->notify_event_source) {
r = sd_event_add_io(m->event, m->notify_fd, EPOLLIN, manager_dispatch_notify_fd, m, &m->notify_event_source);
if (r < 0) {
return -errno;
}
/* Process signals a bit earlier than SIGCHLD, so that we can
* still identify to which service an exit message belongs */
if (r < 0) {
return r;
}
}
return 0;
}
static int manager_setup_kdbus(Manager *m) {
#ifdef ENABLE_KDBUS
_cleanup_free_ char *p = NULL;
#endif
#ifdef ENABLE_KDBUS
assert(m);
if (m->kdbus_fd >= 0)
return 0;
m->kdbus_fd = bus_kernel_create_bus(m->running_as == SYSTEMD_SYSTEM ? "system" : "user", m->running_as == SYSTEMD_SYSTEM, &p);
if (m->kdbus_fd < 0) {
return m->kdbus_fd;
}
log_debug("Successfully set up kdbus on %s", p);
/* Create the namespace directory here, so that the contents
* of that directory is not visible to non-root users. This is
* necessary to ensure that users cannot get access to busses
* of virtualized users when no UID namespacing is used. */
if (m->running_as == SYSTEMD_SYSTEM)
#endif
return 0;
}
bool try_bus_connect;
assert(m);
m->kdbus_fd >= 0 ||
reexecuting ||
/* Try to connect to the busses, if possible. */
return bus_init(m, try_bus_connect);
}
static unsigned manager_dispatch_cleanup_queue(Manager *m) {
Unit *u;
unsigned n = 0;
assert(m);
while ((u = m->cleanup_queue)) {
assert(u->in_cleanup_queue);
unit_free(u);
n++;
}
return n;
}
enum {
GC_OFFSET_IN_PATH, /* This one is on the path we were traveling */
GC_OFFSET_UNSURE, /* No clue */
GC_OFFSET_GOOD, /* We still need this unit */
GC_OFFSET_BAD, /* We don't need this unit anymore */
};
Iterator i;
bool is_bad;
assert(u);
return;
if (u->in_cleanup_queue)
goto bad;
if (unit_check_gc(u))
goto good;
is_bad = true;
goto good;
is_bad = false;
}
if (is_bad)
goto bad;
/* We were unable to find anything out about this entry, so
* let's investigate it later */
return;
bad:
/* We definitely know that this one is not useful anymore, so
* let's mark it for deletion */
return;
good:
}
static unsigned manager_dispatch_gc_queue(Manager *m) {
Unit *u;
unsigned n = 0;
unsigned gc_marker;
assert(m);
/* log_debug("Running GC..."); */
m->gc_marker += _GC_OFFSET_MAX;
m->gc_marker = 1;
while ((u = m->gc_queue)) {
assert(u->in_gc_queue);
unit_gc_sweep(u, gc_marker);
u->in_gc_queue = false;
n++;
}
}
m->n_in_gc_queue = 0;
return n;
}
static void manager_clear_jobs_and_units(Manager *m) {
Unit *u;
assert(m);
while ((u = hashmap_first(m->units)))
unit_free(u);
assert(!m->load_queue);
assert(!m->dbus_unit_queue);
assert(!m->dbus_job_queue);
assert(!m->cleanup_queue);
m->n_on_console = 0;
m->n_running_jobs = 0;
}
void manager_free(Manager *m) {
UnitType c;
int i;
assert(m);
for (c = 0; c < _UNIT_TYPE_MAX; c++)
if (unit_vtable[c]->shutdown)
unit_vtable[c]->shutdown(m);
/* If we reexecute ourselves, we keep the root cgroup
* around */
bus_done(m);
hashmap_free(m->units);
hashmap_free(m->jobs);
hashmap_free(m->watch_pids);
hashmap_free(m->watch_bus);
if (m->signal_fd >= 0)
if (m->notify_fd >= 0)
if (m->time_change_fd >= 0)
if (m->kdbus_fd >= 0)
udev_unref(m->udev);
sd_event_unref(m->event);
free(m->notify_socket);
strv_free(m->environment);
hashmap_free(m->cgroup_unit);
free(m->switch_root);
free(m->switch_root_init);
for (i = 0; i < RLIMIT_NLIMITS; i++)
free(m);
}
int manager_enumerate(Manager *m) {
int r = 0, q;
UnitType c;
assert(m);
* that it might know */
for (c = 0; c < _UNIT_TYPE_MAX; c++)
if (unit_vtable[c]->enumerate) {
q = unit_vtable[c]->enumerate(m);
if (q < 0)
r = q;
}
return r;
}
static int manager_coldplug(Manager *m) {
int r = 0, q;
Iterator i;
Unit *u;
char *k;
assert(m);
/* Then, let's set up their initial state. */
HASHMAP_FOREACH_KEY(u, k, m->units, i) {
/* ignore aliases */
if (u->id != k)
continue;
if ((q = unit_coldplug(u)) < 0)
r = q;
}
return r;
}
static void manager_build_unit_path_cache(Manager *m) {
char **i;
int r;
assert(m);
if (!m->unit_path_cache) {
log_error("Failed to allocate unit path cache.");
return;
}
/* This simply builds a list of files we know exist, so that
* we don't always have to go to disk */
d = opendir(*i);
if (!d) {
log_error("Failed to open directory %s: %m", *i);
continue;
}
char *p;
continue;
if (!p) {
r = -ENOMEM;
goto fail;
}
r = set_consume(m->unit_path_cache, p);
if (r < 0)
goto fail;
}
closedir(d);
d = NULL;
}
return;
fail:
m->unit_path_cache = NULL;
}
Unit *u;
Iterator i;
int r;
assert(m);
HASHMAP_FOREACH(u, m->units, i) {
if (fdset_size(fds) <= 0)
break;
if (UNIT_VTABLE(u)->distribute_fds) {
if (r < 0)
return r;
}
}
return 0;
}
int r, q;
assert(m);
r = lookup_paths_init(
&m->lookup_paths, m->running_as, true,
if (r < 0)
return r;
/* If we will deserialize make sure that during enumeration
* this is already known, so we increase the counter here
* already */
if (serialization)
m->n_reloading ++;
/* First, enumerate what we can from all config files */
r = manager_enumerate(m);
/* Second, deserialize if there is something to deserialize */
if (serialization) {
if (q < 0)
r = q;
}
/* Any fds left? Find some unit which wants them. This is
* useful to allow container managers to pass some file
* descriptors to us pre-initialized. This enables
* socket-based activation of entire containers. */
if (fdset_size(fds) > 0) {
q = manager_distribute_fds(m, fds);
if (q < 0)
r = q;
}
/* We might have deserialized the notify fd, but if we didn't
* then let's create the bus now */
/* We might have deserialized the kdbus control fd, but if we
* didn't, then let's create the bus now. */
manager_connect_bus(m, !!serialization);
/* Third, fire things up! */
q = manager_coldplug(m);
if (q < 0)
r = q;
if (serialization) {
assert(m->n_reloading > 0);
m->n_reloading --;
* sent, before we notify that the reload is
* finished */
m->send_reloading_done = true;
}
return r;
}
int manager_add_job(Manager *m, JobType type, Unit *unit, JobMode mode, bool override, sd_bus_error *e, Job **_ret) {
int r;
assert(m);
return -EINVAL;
}
return -EPERM;
}
if (!tr)
return -ENOMEM;
mode == JOB_IGNORE_DEPENDENCIES, e);
if (r < 0)
goto tr_abort;
if (mode == JOB_ISOLATE) {
r = transaction_add_isolate_jobs(tr, m);
if (r < 0)
goto tr_abort;
}
if (r < 0)
goto tr_abort;
if (_ret)
return 0;
return r;
}
int manager_add_job_by_name(Manager *m, JobType type, const char *name, JobMode mode, bool override, sd_bus_error *e, Job **_ret) {
int r;
assert(m);
if (r < 0)
return r;
}
assert(m);
}
assert(m);
}
unsigned manager_dispatch_load_queue(Manager *m) {
Unit *u;
unsigned n = 0;
assert(m);
/* Make sure we are not run recursively */
if (m->dispatching_load_queue)
return 0;
m->dispatching_load_queue = true;
/* Dispatches the load queue. Takes a unit from the queue and
* tries to load its data until the queue is empty */
while ((u = m->load_queue)) {
assert(u->in_load_queue);
unit_load(u);
n++;
}
m->dispatching_load_queue = false;
return n;
}
Manager *m,
const char *name,
const char *path,
sd_bus_error *e,
UnitType t;
int r;
assert(m);
/* This will prepare the unit for loading, but not actually
* load anything from disk. */
if (!name)
t = unit_name_to_type(name);
if (ret) {
return 1;
}
if (!ret)
return -ENOMEM;
if (path) {
if (!ret->fragment_path) {
return -ENOMEM;
}
}
if (r < 0) {
return r;
}
if (_ret)
return 0;
}
int manager_load_unit(
Manager *m,
const char *name,
const char *path,
sd_bus_error *e,
int r;
assert(m);
/* This will load the service information files, but not actually
* start any services or anything. */
if (r != 0)
return r;
if (_ret)
return 0;
}
Iterator i;
Job *j;
assert(s);
assert(f);
HASHMAP_FOREACH(j, s->jobs, i)
}
Iterator i;
Unit *u;
const char *t;
assert(s);
assert(f);
HASHMAP_FOREACH_KEY(u, t, s->units, i)
if (u->id == t)
}
void manager_clear_jobs(Manager *m) {
Job *j;
assert(m);
while ((j = hashmap_first(m->jobs)))
/* No need to recurse. We're cancelling all jobs. */
job_finish_and_invalidate(j, JOB_CANCELED, false);
}
Job *j;
assert(m);
while ((j = m->run_queue)) {
assert(j->in_run_queue);
}
if (m->n_running_jobs > 0)
if (m->n_on_console > 0)
return 1;
}
static unsigned manager_dispatch_dbus_queue(Manager *m) {
Job *j;
Unit *u;
unsigned n = 0;
assert(m);
if (m->dispatching_dbus_queue)
return 0;
m->dispatching_dbus_queue = true;
while ((u = m->dbus_unit_queue)) {
assert(u->in_dbus_queue);
n++;
}
while ((j = m->dbus_job_queue)) {
assert(j->in_dbus_queue);
n++;
}
m->dispatching_dbus_queue = false;
if (m->send_reloading_done) {
m->send_reloading_done = false;
bus_manager_send_reloading(m, false);
}
if (m->queued_message)
return n;
}
static int manager_dispatch_notify_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
ssize_t n;
assert(m);
log_warning("Got unexpected poll event for notify fd.");
return 0;
}
for (;;) {
char buf[4096];
};
union {
} control = {};
.msg_iovlen = 1,
.msg_control = &control,
.msg_controllen = sizeof(control),
};
Unit *u;
if (n <= 0) {
if (n == 0)
return -EIO;
break;
return -errno;
}
log_warning("Received notify message without credentials. Ignoring.");
continue;
}
if (!u) {
if (!u) {
continue;
}
}
buf[n] = 0;
if (!tags)
return log_oom();
if (UNIT_VTABLE(u)->notify_message)
}
return 0;
}
static int manager_dispatch_sigchld(Manager *m) {
assert(m);
for (;;) {
Unit *u;
/* First we call waitd() for a PID and do not reap the
* zombie. That way we can still access /proc/$PID for
* it while it is a zombie. */
break;
continue;
return -errno;
}
break;
}
/* And now figure out the unit this belongs to */
if (!u)
/* And now, we actually reap the zombie. */
continue;
return -errno;
}
continue;
log_debug("Child %lu died (code=%s, status=%i/%s)",
if (!u)
continue;
log_debug_unit(u->id,
}
return 0;
}
int r;
if (r < 0)
return r;
}
static int manager_dispatch_signal_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
ssize_t n;
struct signalfd_siginfo sfsi;
bool sigchld = false;
assert(m);
log_warning("Got unexpected events from signal file descriptor.");
return 0;
}
for (;;) {
if (n != sizeof(sfsi)) {
if (n >= 0)
return -EIO;
break;
return -errno;
}
_cleanup_free_ char *p = NULL;
} else
"Received SIG%s.",
case SIGCHLD:
sigchld = true;
break;
case SIGTERM:
if (m->running_as == SYSTEMD_SYSTEM) {
/* This is for compatibility with the
* original sysvinit */
m->exit_code = MANAGER_REEXECUTE;
break;
}
/* Fall through */
case SIGINT:
if (m->running_as == SYSTEMD_SYSTEM) {
break;
}
/* Run the exit target if there is one, if not, just exit. */
m->exit_code = MANAGER_EXIT;
return 0;
}
break;
case SIGWINCH:
if (m->running_as == SYSTEMD_SYSTEM)
/* This is a nop on non-init */
break;
case SIGPWR:
if (m->running_as == SYSTEMD_SYSTEM)
/* This is a nop on non-init */
break;
case SIGUSR1: {
Unit *u;
u = manager_get_unit(m, SPECIAL_DBUS_SERVICE);
if (!u || UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u))) {
log_info("Trying to reconnect to bus...");
bus_init(m, true);
}
if (!u || !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u))) {
log_info("Loading D-Bus service...");
}
break;
}
case SIGUSR2: {
if (!f) {
log_warning("Failed to allocate memory stream.");
break;
}
manager_dump_units(m, f, "\t");
manager_dump_jobs(m, f, "\t");
if (ferror(f)) {
log_warning("Failed to write status stream");
break;
}
break;
}
case SIGHUP:
m->exit_code = MANAGER_RELOAD;
break;
default: {
/* Starting SIGRTMIN+0 */
static const char * const target_table[] = {
[0] = SPECIAL_DEFAULT_TARGET,
[1] = SPECIAL_RESCUE_TARGET,
[2] = SPECIAL_EMERGENCY_TARGET,
[3] = SPECIAL_HALT_TARGET,
[4] = SPECIAL_POWEROFF_TARGET,
[5] = SPECIAL_REBOOT_TARGET,
[6] = SPECIAL_KEXEC_TARGET
};
/* Starting SIGRTMIN+13, so that target halt and system halt are 10 apart */
static const ManagerExitCode code_table[] = {
[0] = MANAGER_HALT,
[1] = MANAGER_POWEROFF,
[2] = MANAGER_REBOOT,
[3] = MANAGER_KEXEC
};
break;
}
break;
}
case 20:
log_debug("Enabling showing of status.");
break;
case 21:
log_debug("Disabling showing of status.");
break;
case 22:
log_notice("Setting log level to debug.");
break;
case 23:
log_notice("Setting log level to info.");
break;
case 24:
if (m->running_as == SYSTEMD_USER) {
m->exit_code = MANAGER_EXIT;
return 0;
}
/* This is a nop on init */
break;
case 26:
log_notice("Setting log target to journal-or-kmsg.");
break;
case 27:
log_notice("Setting log target to console.");
break;
case 28:
log_notice("Setting log target to kmsg.");
break;
case 29:
log_notice("Setting log target to syslog-or-kmsg.");
break;
default:
}
}
}
}
if (sigchld)
return 0;
}
static int manager_dispatch_time_change_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
Iterator i;
Unit *u;
assert(m);
"MESSAGE=Time has been changed",
NULL);
/* Restart the watch */
m->time_change_fd = -1;
HASHMAP_FOREACH(u, m->units, i)
if (UNIT_VTABLE(u)->time_change)
UNIT_VTABLE(u)->time_change(u);
return 0;
}
static int manager_dispatch_idle_pipe_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
assert(m);
m->no_console_output = m->n_on_console > 0;
return 0;
}
static int manager_dispatch_jobs_in_progress(sd_event_source *source, usec_t usec, void *userdata) {
int r;
assert(m);
if (r < 0)
return r;
}
int manager_loop(Manager *m) {
int r;
assert(m);
m->exit_code = MANAGER_RUNNING;
/* Release the path cache */
m->unit_path_cache = NULL;
/* There might still be some zombies hanging around from
* before we were exec()'ed. Let's reap them. */
r = manager_dispatch_sigchld(m);
if (r < 0)
return r;
while (m->exit_code == MANAGER_RUNNING) {
if (!ratelimit_test(&rl)) {
/* Yay, something is going seriously wrong, pause a little */
log_warning("Looping too fast. Throttling execution a little.");
sleep(1);
continue;
}
if (manager_dispatch_load_queue(m) > 0)
continue;
if (manager_dispatch_gc_queue(m) > 0)
continue;
if (manager_dispatch_cleanup_queue(m) > 0)
continue;
if (manager_dispatch_cgroup_queue(m) > 0)
continue;
if (manager_dispatch_dbus_queue(m) > 0)
continue;
/* Sleep for half the watchdog time */
if (wait_usec <= 0)
wait_usec = 1;
} else
if (r < 0) {
return r;
}
}
return m->exit_code;
}
_cleanup_free_ char *n = NULL;
Unit *u;
int r;
assert(m);
assert(s);
r = unit_name_from_dbus_path(s, &n);
if (r < 0)
return r;
r = manager_load_unit(m, n, NULL, e, &u);
if (r < 0)
return r;
*_u = u;
return 0;
}
const char *p;
unsigned id;
Job *j;
int r;
assert(m);
assert(s);
p = startswith(s, "/org/freedesktop/systemd1/job/");
if (!p)
return -EINVAL;
if (r < 0)
return r;
j = manager_get_job(m, id);
if (!j)
return -ENOENT;
*_j = j;
return 0;
}
#ifdef HAVE_AUDIT
char *p;
int audit_fd;
audit_fd = get_audit_fd();
if (audit_fd < 0)
return;
/* Don't generate audit events if the service was already
* started and we're just deserializing */
if (m->n_reloading > 0)
return;
if (m->running_as != SYSTEMD_SYSTEM)
return;
if (u->type != UNIT_SERVICE)
return;
p = unit_name_to_prefix_and_instance(u->id);
if (!p) {
log_error_unit(u->id,
return;
}
/* We aren't allowed to send audit messages?
* Then let's not retry again. */
} else
log_warning("Failed to send audit message: %m");
}
free(p);
#endif
}
int fd = -1;
union sockaddr_union sa;
int n = 0;
/* Don't generate plymouth events if the service was already
* started and we're just deserializing */
if (m->n_reloading > 0)
return;
if (m->running_as != SYSTEMD_SYSTEM)
return;
if (detect_container(NULL) > 0)
return;
if (u->type != UNIT_SERVICE &&
u->type != UNIT_MOUNT &&
return;
/* We set SOCK_NONBLOCK here so that we rather drop the
* message then wait for plymouth */
if (fd < 0) {
log_error("socket() failed: %m");
return;
}
if (connect(fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + 1 + strlen(sa.un.sun_path+1)) < 0) {
errno != ECONNREFUSED &&
errno != ECONNRESET &&
errno != ECONNABORTED)
log_error("connect() failed: %m");
goto finish;
}
log_oom();
goto finish;
}
errno = 0;
errno != ECONNREFUSED &&
errno != ECONNRESET &&
errno != ECONNABORTED)
log_error("Failed to write Plymouth message: %m");
goto finish;
}
if (fd >= 0)
}
Manager *m,
const char *name,
const char* old_owner,
const char *new_owner) {
Unit *u;
assert(m);
if (!u)
return;
}
const char *path;
int fd = -1;
FILE *f;
if (fd < 0)
return -errno;
if (!f) {
return -errno;
}
*_f = f;
return 0;
}
Iterator i;
Unit *u;
const char *t;
char **e;
int r;
assert(m);
assert(f);
m->n_reloading ++;
if (!in_initrd()) {
}
if (!switching_root) {
STRV_FOREACH(e, m->environment) {
_cleanup_free_ char *ce;
if (!ce)
return -ENOMEM;
fprintf(f, "env=%s\n", *e);
}
}
if (m->notify_fd >= 0) {
int copy;
if (copy < 0)
return copy;
}
if (m->kdbus_fd >= 0) {
int copy;
if (copy < 0)
return copy;
}
bus_serialize(m, f);
fputc('\n', f);
HASHMAP_FOREACH_KEY(u, t, m->units, i) {
if (u->id != t)
continue;
if (!unit_can_serialize(u))
continue;
/* Start marker */
fputc('\n', f);
if (r < 0) {
m->n_reloading --;
return r;
}
}
assert(m->n_reloading > 0);
m->n_reloading --;
if (ferror(f))
return -EIO;
r = bus_fdset_add_all(m, fds);
if (r < 0)
return r;
return 0;
}
int r = 0;
assert(m);
assert(f);
log_debug("Deserializing state...");
m->n_reloading ++;
for (;;) {
if (feof(f))
r = 0;
else
r = -errno;
goto finish;
}
if (l[0] == 0)
break;
if (startswith(l, "current-job-id=")) {
else
} else if (startswith(l, "n-installed-jobs=")) {
uint32_t n;
if (safe_atou32(l+17, &n) < 0)
else
m->n_installed_jobs += n;
} else if (startswith(l, "n-failed-jobs=")) {
uint32_t n;
if (safe_atou32(l+14, &n) < 0)
else
m->n_failed_jobs += n;
} else if (startswith(l, "taint-usr=")) {
int b;
b = parse_boolean(l+10);
if (b < 0)
else
} else if (startswith(l, "firmware-timestamp="))
else if (startswith(l, "loader-timestamp="))
else if (startswith(l, "kernel-timestamp="))
else if (startswith(l, "initrd-timestamp="))
else if (startswith(l, "userspace-timestamp="))
else if (startswith(l, "finish-timestamp="))
else if (startswith(l, "security-start-timestamp="))
else if (startswith(l, "security-finish-timestamp="))
else if (startswith(l, "generators-start-timestamp="))
else if (startswith(l, "generators-finish-timestamp="))
else if (startswith(l, "units-load-start-timestamp="))
else if (startswith(l, "units-load-finish-timestamp="))
else if (startswith(l, "env=")) {
char **e;
if (!uce) {
r = -ENOMEM;
goto finish;
}
if (!e) {
r = -ENOMEM;
goto finish;
}
strv_free(m->environment);
m->environment = e;
} else if (startswith(l, "notify-fd=")) {
int fd;
else {
if (m->notify_fd >= 0) {
}
}
} else if (startswith(l, "notify-socket=")) {
char *n;
n = strdup(l+14);
if (!n) {
r = -ENOMEM;
goto finish;
}
free(m->notify_socket);
m->notify_socket = n;
} else if (startswith(l, "kdbus-fd=")) {
int fd;
else {
if (m->kdbus_fd >= 0)
}
} else if (bus_deserialize_item(m, l) == 0)
log_debug("Unknown serialization item '%s'", l);
}
for (;;) {
Unit *u;
/* Start marker */
if (feof(f))
r = 0;
else
r = -errno;
goto finish;
}
if (r < 0)
goto finish;
r = unit_deserialize(u, f, fds);
if (r < 0)
goto finish;
}
if (ferror(f))
r = -EIO;
assert(m->n_reloading > 0);
m->n_reloading --;
return r;
}
int manager_reload(Manager *m) {
int r, q;
assert(m);
r = manager_open_serialization(m, &f);
if (r < 0)
return r;
m->n_reloading ++;
bus_manager_send_reloading(m, true);
if (!fds) {
m->n_reloading --;
return -ENOMEM;
}
r = manager_serialize(m, f, fds, false);
if (r < 0) {
m->n_reloading --;
return r;
}
m->n_reloading --;
return -errno;
}
/* From here on there is no way back. */
/* Find new unit paths */
q = lookup_paths_init(
&m->lookup_paths, m->running_as, true,
if (q < 0)
r = q;
/* First, enumerate what we can from all config files */
q = manager_enumerate(m);
if (q < 0)
r = q;
/* Second, deserialize our stored data */
q = manager_deserialize(m, f, fds);
if (q < 0)
r = q;
fclose(f);
f = NULL;
/* Re-register notify_fd as event source */
q = manager_setup_notify(m);
if (q < 0)
r = q;
/* Third, fire things up! */
q = manager_coldplug(m);
if (q < 0)
r = q;
assert(m->n_reloading > 0);
m->n_reloading--;
m->send_reloading_done = true;
return r;
}
static bool manager_is_booting_or_shutting_down(Manager *m) {
Unit *u;
assert(m);
/* Is the initial job still around? */
if (manager_get_job(m, m->default_unit_job_id))
return true;
/* Is there a job for the shutdown target? */
u = manager_get_unit(m, SPECIAL_SHUTDOWN_TARGET);
if (u)
return !!u->job;
return false;
}
bool manager_is_reloading_or_reexecuting(Manager *m) {
assert(m);
return m->n_reloading != 0;
}
void manager_reset_failed(Manager *m) {
Unit *u;
Iterator i;
assert(m);
HASHMAP_FOREACH(u, m->units, i)
}
Unit *u;
assert(m);
/* Returns true if the unit is inactive or going down */
u = manager_get_unit(m, name);
if (!u)
return true;
return unit_inactive_or_pending(u);
}
void manager_check_finished(Manager *m) {
char userspace[FORMAT_TIMESPAN_MAX], initrd[FORMAT_TIMESPAN_MAX], kernel[FORMAT_TIMESPAN_MAX], sum[FORMAT_TIMESPAN_MAX];
assert(m);
if (m->n_running_jobs == 0)
if (hashmap_size(m->jobs) > 0) {
if (m->jobs_in_progress_event_source) {
}
return;
}
manager_flip_auto_status(m, false);
/* Notify Type=idle units that we are done now */
/* Turn off confirm spawn now */
m->confirm_spawn = false;
if (dual_timestamp_is_set(&m->finish_timestamp))
return;
/* Note that m->kernel_usec.monotonic is always at 0,
* and m->firmware_usec.monotonic and
* m->loader_usec.monotonic should be considered
* negative values. */
if (dual_timestamp_is_set(&m->initrd_timestamp)) {
if (!log_on_console())
"MESSAGE=Startup finished in %s (kernel) + %s (initrd) + %s (userspace) = %s.",
NULL);
} else {
initrd_usec = 0;
if (!log_on_console())
"MESSAGE=Startup finished in %s (kernel) + %s (userspace) = %s.",
NULL);
}
} else {
if (!log_on_console())
"MESSAGE=Startup finished in %s.",
NULL);
}
bus_manager_send_finished(m, firmware_usec, loader_usec, kernel_usec, initrd_usec, userspace_usec, total_usec);
sd_notifyf(false,
"READY=1\nSTATUS=Startup finished in %s.",
}
char *p;
int r;
assert(m);
if (*generator)
return 0;
/* systemd --system, not running --test */
if (!p)
return log_oom();
r = mkdir_p_label(p, 0755);
if (r < 0) {
log_error("Failed to create generator directory %s: %s",
p, strerror(-r));
free(p);
return r;
}
} else if (m->running_as == SYSTEMD_USER) {
const char *s = NULL;
s = getenv("XDG_RUNTIME_DIR");
if (!s)
return -EINVAL;
if (!p)
return log_oom();
r = mkdir_p_label(p, 0755);
if (r < 0) {
log_error("Failed to create generator directory %s: %s",
p, strerror(-r));
free(p);
return r;
}
} else {
/* systemd --system --test */
if (!p)
return log_oom();
if (!mkdtemp(p)) {
log_error("Failed to create generator directory %s: %m",
p);
free(p);
return -errno;
}
}
*generator = p;
return 0;
}
assert(m);
if (!*generator)
return;
}
return;
}
void manager_run_generators(Manager *m) {
const char *generator_path;
const char *argv[5];
int r;
assert(m);
d = opendir(generator_path);
if (!d) {
return;
log_error("Failed to enumerate generator directory %s: %m",
return;
}
if (r < 0)
goto finish;
if (r < 0)
goto finish;
if (r < 0)
goto finish;
RUN_WITH_UMASK(0022)
trim_generator_dir(m, &m->generator_unit_path);
}
assert(m);
if (!*generator)
return;
}
void manager_undo_generators(Manager *m) {
assert(m);
remove_generator_dir(m, &m->generator_unit_path);
}
assert(m);
l = m->environment;
if (!strv_isempty(minus)) {
if (!a)
return -ENOMEM;
l = a;
}
if (!strv_isempty(plus)) {
if (!b)
return -ENOMEM;
l = b;
}
if (m->environment != l)
strv_free(m->environment);
if (a != l)
strv_free(a);
if (b != l)
strv_free(b);
m->environment = l;
strv_sort(m->environment);
return 0;
}
int i;
assert(m);
for (i = 0; i < RLIMIT_NLIMITS; i++) {
if (!default_rlimit[i])
continue;
if (!m->rlimit[i])
return -ENOMEM;
}
return 0;
}
void manager_recheck_journal(Manager *m) {
Unit *u;
assert(m);
if (m->running_as != SYSTEMD_SYSTEM)
return;
u = manager_get_unit(m, SPECIAL_JOURNALD_SOCKET);
return;
}
u = manager_get_unit(m, SPECIAL_JOURNALD_SERVICE);
return;
}
/* Hmm, OK, so the socket is fully up and the service is up
* too, then let's make use of the thing. */
log_open();
}
assert(m);
if (m->running_as != SYSTEMD_SYSTEM)
return;
m->show_status = mode;
if (mode > 0)
touch("/run/systemd/show-status");
else
unlink("/run/systemd/show-status");
}
static bool manager_get_show_status(Manager *m) {
assert(m);
if (m->running_as != SYSTEMD_SYSTEM)
return false;
if (m->no_console_output)
return false;
if (m->show_status > 0)
return true;
/* If Plymouth is running make sure we show the status, so
* that there's something nice to see when people press Esc */
return plymouth_running();
}
void manager_status_printf(Manager *m, bool ephemeral, const char *status, const char *format, ...) {
if (!manager_get_show_status(m))
return;
/* XXX We should totally drop the check for ephemeral here
* and thus effectively make 'Type=idle' pointless. */
if (ephemeral && m->n_on_console > 0)
return;
if (!manager_is_booting_or_shutting_down(m))
return;
}
_cleanup_free_ char *p = NULL;
assert(m);
if (!p)
return -ENOMEM;
found = manager_get_unit(m, p);
if (!found) {
return 0;
}
return 1;
}
assert(m);
}