manager.c revision d379d44255469f03994832ab5821bf1b9034f4dc
/*-*- 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 <errno.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <fcntl.h>
#include <dirent.h>
#ifdef HAVE_AUDIT
#include <libaudit.h>
#endif
#include "sd-daemon.h"
#include "sd-messages.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 "unit-name.h"
#include "missing.h"
#include "rm-rf.h"
#include "path-lookup.h"
#include "special.h"
#include "exit-status.h"
#include "virt.h"
#include "watchdog.h"
#include "path-util.h"
#include "audit-fd.h"
#include "boot-timestamps.h"
#include "env-util.h"
#include "bus-common-errors.h"
#include "bus-error.h"
#include "bus-util.h"
#include "bus-kernel.h"
#include "time-util.h"
#include "process-util.h"
#include "terminal-util.h"
#include "signal-util.h"
#include "dbus.h"
#include "dbus-unit.h"
#include "dbus-job.h"
#include "dbus-manager.h"
#include "manager.h"
#include "transaction.h"
/* Initial delay and the interval for printing status messages about running jobs */
#define JOBS_IN_PROGRESS_PERIOD_DIVISOR 3
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_run_generators(Manager *m);
static void manager_undo_generators(Manager *m);
static void manager_watch_jobs_in_progress(Manager *m) {
int r;
assert(m);
if (m->jobs_in_progress_event_source)
return;
r = sd_event_add_time(
m->event,
next, 0,
if (r < 0)
return;
(void) sd_event_source_set_description(m->jobs_in_progress_event_source, "manager-jobs-in-progress");
}
#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);
}
}
assert(m);
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);
assert(m->n_running_jobs > 0);
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)
"%sA %s job is running for %s (%s / %s)",
job_type_to_string(j->type),
unit_description(j->unit),
}
static int have_ask_password(void) {
if (!dir) {
return false;
else
return -errno;
}
for (;;) {
errno = 0;
return -errno;
if (!de)
return false;
return true;
}
}
assert(m);
m->have_ask_password = have_ask_password();
if (m->have_ask_password < 0)
/* Log error but continue. Negative have_ask_password
* is treated as unknown status. */
return 0;
}
static void manager_close_ask_password(Manager *m) {
assert(m);
m->have_ask_password = -EINVAL;
}
static int manager_check_ask_password(Manager *m) {
int r;
assert(m);
if (!m->ask_password_event_source) {
assert(m->ask_password_inotify_fd < 0);
if (m->ask_password_inotify_fd < 0)
if (inotify_add_watch(m->ask_password_inotify_fd, "/run/systemd/ask-password", IN_CREATE|IN_DELETE|IN_MOVE) < 0) {
return -errno;
}
if (r < 0) {
return -errno;
}
/* Queries might have been added meanwhile... */
m->ask_password_inotify_fd, EPOLLIN, m);
}
return m->have_ask_password;
}
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_event_source, m->idle_pipe[2], EPOLLIN, manager_dispatch_idle_pipe_fd, m);
if (r < 0)
return log_error_errno(r, "Failed to watch idle pipe: %m");
return 0;
}
static void manager_close_idle_pipe(Manager *m) {
assert(m);
safe_close_pair(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);
if (m->test_run)
return 0;
/* 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)
if (timerfd_settime(m->time_change_fd, TFD_TIMER_ABSTIME|TFD_TIMER_CANCEL_ON_SET, &its, NULL) < 0) {
return 0;
}
r = sd_event_add_io(m->event, &m->time_change_event_source, m->time_change_fd, EPOLLIN, manager_dispatch_time_change_fd, m);
if (r < 0)
return log_error_errno(r, "Failed to create time change event source: %m");
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. */
if (fd < 0) {
/* Support systems without virtual console */
} else {
/* Enable that we get SIGWINCH on kbrequest */
}
return 0;
}
static int manager_setup_signals(Manager *m) {
.sa_handler = SIG_DFL,
};
int r;
assert(m);
/* We make liberal use of realtime signals here. On
* on hppa, see below), between SIGRTMIN+0 ... SIGRTMIN+30
* (aka SIGRTMAX). */
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 */
/* ... space for more special targets ... */
/* ... space for more immediate system state changes ... */
/* .. one free signal here ... */
#if !defined(__hppa64__) && !defined(__hppa__)
/* Apparently Linux on hppa has fewer RT
* signals (SIGRTMAX is SIGRTMIN+25 there),
* hence let's not try to make use of them
* here. Since these commands are accessible
* by different means and only really a safety
* net, the missing functionality on hppa
* shouldn't matter. */
/* ... one free signal here SIGRTMIN+30 ... */
#endif
-1);
if (m->signal_fd < 0)
return -errno;
r = sd_event_add_io(m->event, &m->signal_event_source, m->signal_fd, EPOLLIN, manager_dispatch_signal_fd, m);
if (r < 0)
return r;
/* Process signals a bit earlier than the rest of things, but
* later than notify_fd processing, so that the notify
* message belongs, before we reap the process. */
if (r < 0)
return r;
if (m->running_as == MANAGER_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 == MANAGER_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;
}
static const char * const unit_log_fields[_MANAGER_RUNNING_AS_MAX] = {
[MANAGER_SYSTEM] = "UNIT=",
[MANAGER_USER] = "USER_UNIT=",
};
static const char * const unit_log_format_strings[_MANAGER_RUNNING_AS_MAX] = {
[MANAGER_SYSTEM] = "UNIT=%s",
[MANAGER_USER] = "USER_UNIT=%s",
};
Manager *m;
int r;
assert(running_as >= 0);
if (!m)
return -ENOMEM;
#ifdef ENABLE_EFI
#endif
m->running_as = running_as;
/* Prepare log fields we can use for structured logging */
m->ask_password_inotify_fd = -1;
m->first_boot = -1;
/* Reboot immediately if the user hits C-A-D more often than 7x per 2s */
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;
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) {
int r;
if (m->test_run)
return 0;
if (m->notify_fd < 0) {
union sockaddr_union sa = {
};
static const int one = 1;
/* First free all secondary fields */
if (fd < 0)
if (m->running_as == MANAGER_SYSTEM)
else {
const char *e;
e = getenv("XDG_RUNTIME_DIR");
if (!e) {
return -EINVAL;
}
}
if (!m->notify_socket)
return log_oom();
(void) unlink(m->notify_socket);
if (r < 0)
if (r < 0)
fd = -1;
}
if (!m->notify_event_source) {
r = sd_event_add_io(m->event, &m->notify_event_source, m->notify_fd, EPOLLIN, manager_dispatch_notify_fd, m);
if (r < 0)
return log_error_errno(r, "Failed to allocate notify event source: %m");
/* Process signals a bit earlier than SIGCHLD, so that we can
* still identify to which service an exit message belongs */
if (r < 0)
return log_error_errno(r, "Failed to set priority of notify event source: %m");
}
return 0;
}
static int manager_setup_kdbus(Manager *m) {
_cleanup_free_ char *p = NULL;
assert(m);
return 0;
if (!is_kdbus_available())
return -ESOCKTNOSUPPORT;
m->running_as == MANAGER_SYSTEM, &p);
if (m->kdbus_fd < 0)
log_debug("Successfully set up kdbus on %s", p);
return 0;
}
bool try_bus_connect;
assert(m);
if (m->test_run)
return 0;
m->kdbus_fd >= 0 ||
reexecuting ||
/* Try to connect to the buses, 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++;
if (u->id)
log_unit_debug(u, "Collecting.");
}
}
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;
}
UnitType c;
int i;
if (!m)
return NULL;
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_pids1);
hashmap_free(m->watch_pids2);
hashmap_free(m->watch_bus);
set_free(m->startup_units);
set_free(m->failed_units);
safe_close(m->signal_fd);
safe_close(m->notify_fd);
safe_close(m->time_change_fd);
safe_close(m->kdbus_fd);
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_MAX; i++)
free(m);
return NULL;
}
int manager_enumerate(Manager *m) {
int r = 0;
UnitType c;
assert(m);
* that it might know */
for (c = 0; c < _UNIT_TYPE_MAX; c++) {
int q;
if (!unit_type_supported(c)) {
continue;
}
if (!unit_vtable[c]->enumerate)
continue;
q = unit_vtable[c]->enumerate(m);
if (q < 0)
r = q;
}
return r;
}
static void manager_coldplug(Manager *m) {
Iterator i;
Unit *u;
char *k;
int r;
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;
r = unit_coldplug(u);
if (r < 0)
}
}
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) {
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:
log_error_errno(r, "Failed to build unit path cache: %m");
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 = manager_run_generators(m);
if (r < 0)
return r;
r = lookup_paths_init(
&m->lookup_paths, m->running_as, true,
NULL,
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)
/* 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 == 0)
r = q;
}
/* We might have deserialized the notify fd, but if we didn't
* then let's create the bus now */
q = manager_setup_notify(m);
if (q < 0 && r == 0)
r = q;
/* 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! */
manager_coldplug(m);
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 sd_bus_error_setf(e, BUS_ERROR_NO_ISOLATION, "Operation refused, unit may not be isolated.");
log_unit_debug(unit, "Trying to enqueue job %s/%s/%s", unit->id, job_type_to_string(type), job_mode_to_string(mode));
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 void manager_invoke_notify_message(Manager *m, Unit *u, pid_t pid, char *buf, size_t n, FDSet *fds) {
assert(m);
assert(u);
assert(n > 0);
if (!tags) {
log_oom();
return;
}
if (UNIT_VTABLE(u)->notify_message)
else
log_unit_debug(u, "Got notification message for unit. Ignoring.");
}
static int manager_dispatch_notify_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
ssize_t n;
int r;
assert(m);
log_warning("Got unexpected poll event for notify fd.");
return 0;
}
for (;;) {
};
union {
CMSG_SPACE(sizeof(int) * NOTIFY_FD_MAX)];
} control = {};
.msg_iovlen = 1,
.msg_control = &control,
.msg_controllen = sizeof(control),
};
bool found = false;
unsigned n_fds = 0;
if (n < 0) {
break;
return -errno;
}
}
}
if (n_fds > 0) {
if (r < 0) {
return log_oom();
}
}
log_warning("Received notify message without valid credentials. Ignoring.");
continue;
}
log_warning("Received notify message exceeded maximum size. Ignoring.");
continue;
}
buf[n] = 0;
/* Notify every unit that might be interested, but try
* to avoid notifying the same one multiple times. */
if (u1) {
found = true;
}
found = true;
}
found = true;
}
if (!found)
if (fdset_size(fds) > 0)
log_warning("Got auxiliary fds with notification message, closing all.");
}
return 0;
}
assert(m);
assert(u);
}
static int manager_dispatch_sigchld(Manager *m) {
assert(m);
for (;;) {
/* 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, it might be multiple... */
if (u1)
}
/* And now, we actually reap the zombie. */
continue;
return -errno;
}
}
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;
int r;
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;
}
&sfsi);
case SIGCHLD:
sigchld = true;
break;
case SIGTERM:
if (m->running_as == MANAGER_SYSTEM) {
/* This is for compatibility with the
* original sysvinit */
m->exit_code = MANAGER_REEXECUTE;
break;
}
/* Fall through */
case SIGINT:
if (m->running_as == MANAGER_SYSTEM) {
/* If the user presses C-A-D more than
* 7 times within 2s, we reboot
* immediately. */
if (ratelimit_test(&m->ctrl_alt_del_ratelimit))
else {
log_notice("Ctrl-Alt-Del was pressed more than 7 times within 2s, rebooting immediately.");
status_printf(NULL, true, false, "Ctrl-Alt-Del was pressed more than 7 times within 2s, rebooting immediately.");
m->exit_code = MANAGER_REBOOT;
}
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 == MANAGER_SYSTEM)
/* This is a nop on non-init */
break;
case SIGPWR:
if (m->running_as == MANAGER_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) {
break;
}
manager_dump_units(m, f, "\t");
manager_dump_jobs(m, f, "\t");
r = fflush_and_check(f);
if (r < 0) {
log_warning_errno(r, "Failed to write status stream: %m");
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 == MANAGER_USER) {
m->exit_code = MANAGER_EXIT;
return 0;
}
/* This is a nop on init */
break;
case 26:
case 29: /* compatibility: used to be mapped to LOG_TARGET_SYSLOG_OR_KMSG */
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;
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);
LOG_MESSAGE("Time has been changed"),
NULL);
/* Restart the watch */
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_OK;
/* 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_OK) {
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 log_error_errno(r, "Failed to run event loop: %m");
}
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
_cleanup_free_ char *p = NULL;
const char *msg;
int audit_fd, r;
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 != MANAGER_SYSTEM)
return;
if (u->type != UNIT_SERVICE)
return;
r = unit_name_to_prefix_and_instance(u->id, &p);
if (r < 0) {
log_error_errno(r, "Failed to extract prefix and instance of unit name: %m");
return;
}
/* We aren't allowed to send audit messages?
* Then let's not retry again. */
else
}
#endif
}
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 != MANAGER_SYSTEM)
return;
if (detect_container() > 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) {
return;
}
if (connect(fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + 1 + strlen(sa.un.sun_path+1)) < 0) {
return;
}
log_oom();
return;
}
errno = 0;
}
const char *path;
int fd = -1;
FILE *f;
if (fd < 0)
return -errno;
if (!f) {
safe_close(fd);
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_track_serialize(m->subscribed, f);
fputc('\n', f);
HASHMAP_FOREACH_KEY(u, t, m->units, i) {
if (u->id != t)
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 (r < 0)
goto finish;
if (!e) {
r = -ENOMEM;
goto finish;
}
strv_free(m->environment);
m->environment = e;
} else if (startswith(l, "notify-fd=")) {
int fd;
else {
safe_close(m->notify_fd);
}
} 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 {
safe_close(m->kdbus_fd);
}
} else {
int k;
k = bus_track_deserialize_item(&m->deserialized_subscribed, l);
if (k < 0)
log_debug_errno(k, "Failed to deserialize bus tracker object: %m");
else if (k == 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 = manager_run_generators(m);
if (q < 0 && r >= 0)
r = q;
q = lookup_paths_init(
&m->lookup_paths, m->running_as, true,
NULL,
if (q < 0 && r >= 0)
r = q;
/* First, enumerate what we can from all config files */
q = manager_enumerate(m);
if (q < 0 && r >= 0)
r = q;
/* Second, deserialize our stored data */
q = manager_deserialize(m, f, fds);
if (q < 0 && r >= 0)
r = q;
fclose(f);
f = NULL;
/* Re-register notify_fd as event source */
q = manager_setup_notify(m);
if (q < 0 && r >= 0)
r = q;
/* Third, fire things up! */
manager_coldplug(m);
assert(m->n_reloading > 0);
m->n_reloading--;
m->send_reloading_done = true;
return r;
}
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);
}
static void manager_notify_finished(Manager *m) {
char userspace[FORMAT_TIMESPAN_MAX], initrd[FORMAT_TIMESPAN_MAX], kernel[FORMAT_TIMESPAN_MAX], sum[FORMAT_TIMESPAN_MAX];
if (m->test_run)
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)) {
LOG_MESSAGE("Startup finished in %s (kernel) + %s (initrd) + %s (userspace) = %s.",
NULL);
} else {
initrd_usec = 0;
LOG_MESSAGE("Startup finished in %s (kernel) + %s (userspace) = %s.",
NULL);
}
} else {
LOG_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\n"
"STATUS=Startup finished in %s.",
}
void manager_check_finished(Manager *m) {
assert(m);
if (m->n_reloading > 0)
return;
/* Verify that we are actually running currently. Initially
* the exit code is set to invalid, and during operation it is
* then set to MANAGER_OK */
if (m->exit_code != MANAGER_OK)
return;
if (hashmap_size(m->jobs) > 0) {
if (m->jobs_in_progress_event_source)
/* Ignore any failure, this is only for feedback */
(void) sd_event_source_set_time(m->jobs_in_progress_event_source, now(CLOCK_MONOTONIC) + JOBS_IN_PROGRESS_WAIT_USEC);
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;
/* No need to update ask password status when we're going non-interactive */
/* This is no longer the first boot */
manager_set_first_boot(m, false);
if (dual_timestamp_is_set(&m->finish_timestamp))
return;
}
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_errno(r, "Failed to create generator directory %s: %m", p);
free(p);
return r;
}
} else if (m->running_as == MANAGER_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_errno(r, "Failed to create generator directory %s: %m", p);
free(p);
return r;
}
} else {
/* systemd --system --test */
if (!p)
return log_oom();
if (!mkdtemp(p)) {
p);
free(p);
return -errno;
}
}
*generator = p;
return 0;
}
assert(m);
if (!*generator)
return;
return;
}
static int manager_run_generators(Manager *m) {
const char *argv[5];
char **path;
int r;
assert(m);
if (m->test_run)
return 0;
if (!paths)
return log_oom();
/* Optimize by skipping the whole process by not creating output directories
* if no generators are found. */
if (r == 0)
goto found;
}
return 0;
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);
return r;
}
assert(m);
if (!*generator)
return;
}
static 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) {
strv_free(a);
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_MAX; 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 != MANAGER_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 != MANAGER_SYSTEM)
return;
m->show_status = mode;
if (mode > 0)
touch("/run/systemd/show-status");
else
unlink("/run/systemd/show-status");
}
assert(m);
if (m->running_as != MANAGER_SYSTEM)
return false;
if (m->no_console_output)
return false;
return false;
/* If we cannot find out the status properly, just proceed. */
return false;
if (m->show_status > 0)
return true;
return false;
}
void manager_set_first_boot(Manager *m, bool b) {
assert(m);
if (m->running_as != MANAGER_SYSTEM)
return;
if (m->first_boot != (int) b) {
if (b)
(void) touch("/run/systemd/first-boot");
else
(void) unlink("/run/systemd/first-boot");
}
m->first_boot = b;
}
void manager_status_printf(Manager *m, StatusType type, const char *status, const char *format, ...) {
/* If m is NULL, assume we're after shutdown and let the messages through. */
if (m && !manager_get_show_status(m, type))
return;
/* XXX We should totally drop the check for ephemeral here
* and thus effectively make 'Type=idle' pointless. */
return;
}
_cleanup_free_ char *p = NULL;
int r;
assert(m);
if (r < 0)
return r;
found = manager_get_unit(m, p);
if (!found) {
return 0;
}
return 1;
}
assert(m);
}
const char *manager_get_runtime_prefix(Manager *m) {
assert(m);
return m->running_as == MANAGER_SYSTEM ?
"/run" :
getenv("XDG_RUNTIME_DIR");
}
unsigned size;
int r;
assert(m);
if (failed) {
if (r < 0)
return log_oom();
if (set_put(m->failed_units, u) < 0)
return log_oom();
} else
(void) set_remove(m->failed_units, u);
return 0;
}
Unit *u;
assert(m);
/* Did we ever finish booting? If not then we are still starting up */
if (!dual_timestamp_is_set(&m->finish_timestamp)) {
u = manager_get_unit(m, SPECIAL_BASIC_TARGET);
if (!u || !UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u)))
return MANAGER_INITIALIZING;
return MANAGER_STARTING;
}
/* Is the special shutdown target queued? If so, we are in shutdown state */
u = manager_get_unit(m, SPECIAL_SHUTDOWN_TARGET);
if (u && u->job && IN_SET(u->job->type, JOB_START, JOB_RESTART, JOB_TRY_RESTART, JOB_RELOAD_OR_START))
return MANAGER_STOPPING;
/* Are the rescue or emergency targets active or queued? If so we are in maintenance state */
u = manager_get_unit(m, SPECIAL_RESCUE_TARGET);
if (u && (UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)) ||
return MANAGER_MAINTENANCE;
u = manager_get_unit(m, SPECIAL_EMERGENCY_TARGET);
if (u && (UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)) ||
return MANAGER_MAINTENANCE;
/* Are there any failed units? If so, we are in degraded mode */
if (set_size(m->failed_units) > 0)
return MANAGER_DEGRADED;
return MANAGER_RUNNING;
}
static const char *const manager_state_table[_MANAGER_STATE_MAX] = {
[MANAGER_INITIALIZING] = "initializing",
[MANAGER_STARTING] = "starting",
[MANAGER_RUNNING] = "running",
[MANAGER_DEGRADED] = "degraded",
[MANAGER_MAINTENANCE] = "maintenance",
[MANAGER_STOPPING] = "stopping",
};