HALF ECHO LEARN / REFERENCE COLLECTION
v262.2src/core/manager.c
Git blob: e0aa34f4c11534f81d2a7e0a2a8c2aa218451eb3
Lines 2001–3000 of 5,689
if (!unit_name_is_valid(t->unit_id, UNIT_NAME_ANY))
continue;
(void) manager_dispatch_external_fd_to_unit(m, t->unit_id, t->fdname, t->index, TAKE_FD(fd), "LISTEN_FDS");
}
return 0;
}
static void manager_distribute_fds(Manager *m, FDSet *fds) {
Unit *u;
assert(m);
HASHMAP_FOREACH(u, m->units) {
if (fdset_isempty(fds))
break;
if (!UNIT_VTABLE(u)->distribute_fds)
continue;
UNIT_VTABLE(u)->distribute_fds(u, fds);
}
}
static bool manager_dbus_is_running(Manager *m, bool deserialized) {
Unit *u;
assert(m);
/* This checks whether the dbus instance we are supposed to expose our APIs on is up. We check both the socket
* and the service unit. If the 'deserialized' parameter is true we'll check the deserialized state of the unit
* rather than the current one. */
if (MANAGER_IS_TEST_RUN(m))
return false;
u = manager_get_unit(m, SPECIAL_DBUS_SOCKET);
if (!u)
return false;
if ((deserialized ? SOCKET(u)->deserialized_state : SOCKET(u)->state) != SOCKET_RUNNING)
return false;
u = manager_get_unit(m, SPECIAL_DBUS_SERVICE);
if (!u)
return false;
if (!IN_SET(deserialized ? SERVICE(u)->deserialized_state : SERVICE(u)->state,
SERVICE_RUNNING,
SERVICE_RUNNING_REVALIDATING,
SERVICE_REFRESH_EXTENSIONS,
SERVICE_REFRESH_CREDENTIALS,
SERVICE_RELOAD,
SERVICE_RELOAD_SIGNAL,
SERVICE_RELOAD_NOTIFY,
SERVICE_RELOAD_POST,
SERVICE_MOUNTING))
return false;
return true;
}
static void manager_setup_bus(Manager *m) {
assert(m);
if (MANAGER_IS_TEST_RUN(m))
return;
/* Let's set up our private bus connection now, unconditionally */
(void) bus_init_private(m);
/* If we are in --user mode also connect to the system bus now */
if (MANAGER_IS_USER(m))
(void) bus_init_system(m);
/* Let's connect to the bus now, but only if the unit is supposed to be up */
if (manager_dbus_is_running(m, MANAGER_IS_RELOADING(m))) {
(void) bus_init_api(m);
if (MANAGER_IS_SYSTEM(m))
(void) bus_init_system(m);
}
}
static void manager_preset_all(Manager *m) {
int r;
assert(m);
if (m->first_boot <= 0)
return;
if (!MANAGER_IS_SYSTEM(m))
return;
if (MANAGER_IS_TEST_RUN(m))
return;
/* If this is the first boot, and we are in the host system, then preset everything */
UnitFilePresetMode mode =
ENABLE_FIRST_BOOT_FULL_PRESET ? UNIT_FILE_PRESET_FULL : UNIT_FILE_PRESET_ENABLE_ONLY;
InstallChange *changes = NULL;
size_t n_changes = 0;
CLEANUP_ARRAY(changes, n_changes, install_changes_free);
log_info("Applying preset policy.");
r = unit_file_preset_all(RUNTIME_SCOPE_SYSTEM, /* file_flags= */ 0,
/* root_dir= */ NULL, mode, &changes, &n_changes);
r = install_changes_dump(r, "preset all", changes, n_changes, /* quiet= */ false);
if (r >= 0)
log_info("Populated /etc with preset unit settings.");
}
static void manager_ready(Manager *m) {
assert(m);
/* After having loaded everything, do the final round of catching up with what might have changed */
m->objective = MANAGER_OK; /* Tell everyone we are up now */
/* It might be safe to log to the journal now and connect to dbus */
manager_recheck_journal(m);
manager_recheck_dbus(m);
/* Let's finally catch up with any changes that took place while we were reloading/reexecing */
manager_catchup(m);
/* Create a file which will indicate when the manager started loading units the last time. */
if (MANAGER_IS_SYSTEM(m))
(void) touch_file("/run/systemd/systemd-units-load", false,
m->timestamps[MANAGER_TIMESTAMP_UNITS_LOAD].realtime ?: now(CLOCK_REALTIME),
UID_INVALID, GID_INVALID, 0444);
}
Manager* manager_reloading_start(Manager *m) {
m->n_reloading++;
dual_timestamp_now(m->timestamps + MANAGER_TIMESTAMP_UNITS_LOAD);
return m;
}
void manager_reloading_stopp(Manager **m) {
assert(m);
if (*m) {
assert((*m)->n_reloading > 0);
(*m)->n_reloading--;
}
}
static int manager_make_runtime_dir(Manager *m) {
int r;
assert(m);
_cleanup_free_ char *d = path_join(m->prefix[EXEC_DIRECTORY_RUNTIME], "systemd");
if (!d)
return log_oom();
r = mkdir_label(d, 0755);
if (r < 0 && r != -EEXIST)
return log_error_errno(r, "Failed to create directory '%s/': %m", d);
return 0;
}
int manager_startup(Manager *m, FILE *serialization, FDSet *fds, Hashmap *named_listen_fds, const char *root) {
int r;
assert(m);
r = manager_make_runtime_dir(m);
if (r < 0)
return r;
/* If we are running in test mode, we still want to run the generators,
* but we should not touch the real generator directories. */
r = lookup_paths_init_or_warn(&m->lookup_paths, m->runtime_scope,
MANAGER_IS_TEST_RUN(m) ? LOOKUP_PATHS_TEMPORARY_GENERATED : 0,
root);
if (r < 0)
return r;
dual_timestamp_now(m->timestamps + manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_GENERATORS_START));
r = manager_run_environment_generators(m);
if (r >= 0)
r = manager_run_generators(m);
dual_timestamp_now(m->timestamps + manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_GENERATORS_FINISH));
if (r < 0)
return r;
manager_preset_all(m);
lookup_paths_log(&m->lookup_paths);
{
/* This block is (optionally) done with the reloading counter bumped */
_unused_ _cleanup_(manager_reloading_stopp) Manager *reloading = NULL;
/* Make sure we don't have a left-over from a previous run */
if (!serialization)
(void) rm_rf(m->lookup_paths.transient, 0);
/* If we will deserialize make sure that during enumeration this is already known, so we increase the
* counter here already */
if (serialization)
reloading = manager_reloading_start(m);
/* First, enumerate what we can from all config files */
dual_timestamp_now(m->timestamps + manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_UNITS_LOAD_START));
manager_enumerate_perpetual(m);
manager_enumerate(m);
dual_timestamp_now(m->timestamps + manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_UNITS_LOAD_FINISH));
/* Second, deserialize if there is something to deserialize */
if (serialization) {
r = manager_deserialize(m, serialization, fds);
if (r < 0)
return log_error_errno(r, "Deserialization failed: %m");
}
if (m->previous_objective >= 0) {
if (IN_SET(m->previous_objective, MANAGER_REEXECUTE, MANAGER_SOFT_REBOOT, MANAGER_SWITCH_ROOT))
log_debug("Launching as effect of a '%s' operation.",
manager_objective_to_string(m->previous_objective));
else
log_warning("Got unexpected previous objective '%s', ignoring.",
manager_objective_to_string(m->previous_objective));
}
/* If we are in a new soft-reboot iteration bump the counter now before starting units, so
* that they can reliably read it. We get the previous objective from serialized state. */
if (m->previous_objective == MANAGER_SOFT_REBOOT)
m->soft_reboots_count++;
/* If a LUO (Live Update Orchestrator) session from a previous kexec is available, restore
* preserved file descriptors into the appropriate service fd stores now, before coldplug.
* Only do this when booting up (i.e., skip on reexec/soft reboot/etc.) */
if (m->previous_objective < 0)
(void) manager_luo_restore_fd_stores(m);
/* Pick up fds passed via the LISTEN_FDS=/LISTEN_FDNAMES= protocol that are tagged with a
* unit id ("unit-id|fdname"), and route them into the matching unit's fd store. Untagged
* fds remain in 'fds' and are handed to socket units below as before. */
(void) manager_distribute_listen_fds_named(m, named_listen_fds);
/* 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. */
manager_distribute_fds(m, fds);
/* We might have deserialized the notify fd, but if we didn't then let's create it now */
r = manager_setup_notify(m);
if (r < 0)
/* No sense to continue without notifications, our children would fail anyway. */
return r;
r = manager_setup_user_lookup_fd(m);
if (r < 0)
/* This shouldn't fail, except if things are really broken. */
return r;
r = manager_setup_handoff_timestamp_fd(m);
if (r < 0)
/* This shouldn't fail, except if things are really broken. */
return r;
r = manager_setup_pidref_transport_fd(m);
if (r < 0)
/* This shouldn't fail, except if things are really broken. */
return r;
/* Connect to the bus if we are good for it */
manager_setup_bus(m);
r = manager_varlink_init(m);
if (r < 0)
log_warning_errno(r, "Failed to set up Varlink, ignoring: %m");
/* Third, fire things up! */
manager_coldplug(m);
/* Clean up runtime objects */
manager_vacuum(m);
/* After deserialization, refresh the upstream JSON mapping memfd so the supervisor's
* view of our fd store stays consistent with the indices we just restored. */
(void) service_propagate_fd_store_mapping_upstream(m);
if (serialization)
/* Let's wait for the UnitNew/JobNew messages being sent, before we notify that the
* reload is finished */
m->send_reloading_done = true;
}
/* Set up RestrictFileSystemAccess= BPF LSM after deserialization (so we can detect deserialized link FDs)
* and before clearing switching_root (so we can close the initramfs trust window). This must
* run after set_manager_settings() has set m->restrict_filesystem_access. */
r = bpf_restrict_fsaccess_setup(m);
if (r < 0)
return r;
manager_ready(m);
manager_set_switching_root(m, false);
return 0;
}
int manager_add_jobs(
Manager *m,
JobType type,
char * const *names,
bool reload_if_possible,
JobMode mode,
TransactionAddFlags extra_flags,
Set *affected_jobs,
sd_bus_error *reterr_error,
Set *ret_jobs) {
_cleanup_(transaction_abort_and_freep) Transaction *tr = NULL;
Job *j;
int r;
assert(m);
assert(type >= 0 && type < _JOB_TYPE_MAX);
assert(!strv_isempty(names));
assert(mode >= 0 && mode < _JOB_MODE_MAX);
assert((extra_flags & ~_TRANSACTION_FLAGS_MASK_PUBLIC) == 0);
if (mode == JOB_ISOLATE && type != JOB_START)
return sd_bus_error_set(reterr_error, SD_BUS_ERROR_INVALID_ARGS, "Isolate is only valid for start.");
if (mode == JOB_TRIGGERING && type != JOB_STOP)
return sd_bus_error_set(reterr_error, SD_BUS_ERROR_INVALID_ARGS,
"--job-mode=triggering is only valid for stop.");
if (mode == JOB_RESTART_DEPENDENCIES && type != JOB_START)
return sd_bus_error_set(reterr_error, SD_BUS_ERROR_INVALID_ARGS,
"--job-mode=restart-dependencies is only valid for start.");
if (mode == JOB_ISOLATE && strv_length(names) > 1)
return sd_bus_error_set(reterr_error, SD_BUS_ERROR_NOT_SUPPORTED,
"Isolating more than one unit is not supported.");
tr = transaction_new(mode == JOB_REPLACE_IRREVERSIBLY, ++m->last_transaction_id);
if (!tr)
return -ENOMEM;
LOG_CONTEXT_PUSHF("TRANSACTION_ID=%" PRIu64, tr->id);
STRV_FOREACH(name, names) {
Unit *u;
JobType t = type;
JobType merged_type;
r = manager_load_unit(m, *name, NULL, reterr_error, &u);
if (r < 0)
return r;
if (mode == JOB_ISOLATE && !u->allow_isolate)
return sd_bus_error_setf(reterr_error, BUS_ERROR_NO_ISOLATION,
"Operation refused, unit %s may not be isolated.", u->id);
/* Per-unit validation and reload-if-possible mangling: units that can reload turn
* JOB_RESTART into JOB_RELOAD_OR_START and JOB_TRY_RESTART into JOB_TRY_RELOAD; others
* keep the original restart type. Also rejects manual start/stop on units that refuse
* it, etc. */
r = unit_queue_job_check_and_mangle_type(u, &t, reload_if_possible, reterr_error);
if (r < 0)
return r;
merged_type = job_type_collapse(t, u);
log_unit_debug(u, "Trying to enqueue job %s/%s/%s",
u->id, job_type_to_string(merged_type), job_mode_to_string(mode));
r = transaction_add_job_and_dependencies(
tr,
merged_type,
u,
/* by= */ NULL,
TRANSACTION_MATTERS |
(IN_SET(mode, JOB_IGNORE_DEPENDENCIES, JOB_IGNORE_REQUIREMENTS) ? TRANSACTION_IGNORE_REQUIREMENTS : 0) |
(mode == JOB_IGNORE_DEPENDENCIES ? TRANSACTION_IGNORE_ORDER : 0) |
(mode == JOB_RESTART_DEPENDENCIES ? TRANSACTION_PROPAGATE_START_AS_RESTART : 0) |
extra_flags,
reterr_error);
if (r < 0)
return r;
if (mode == JOB_TRIGGERING) {
r = transaction_add_triggering_jobs(tr, u);
if (r < 0)
return r;
}
}
if (mode == JOB_ISOLATE) {
r = transaction_add_isolate_jobs(tr, m);
if (r < 0)
return r;
}
r = transaction_activate(tr, m, mode, affected_jobs, reterr_error);
if (r < 0)
return r;
SET_FOREACH(j, tr->anchor_jobs)
log_unit_debug(j->unit,
"Enqueued job %s/%s as %u",
j->unit->id, job_type_to_string(j->type), (unsigned) j->id);
if (ret_jobs) {
/* The anchor_jobs set would be destroyed anyway, so steal the contents. */
r = set_move(ret_jobs, tr->anchor_jobs);
if (r < 0) {
/* On failure, still clear anchor_jobs so the cleanup handler doesn't trip the
* empty-set assertion in transaction_free(). */
set_clear(tr->anchor_jobs);
return r;
}
} else
/* tr->anchor_jobs tracks pointers to jobs that are now installed in the manager; clear
* it so transaction_free() doesn't trip its empty-set assertion. */
set_clear(tr->anchor_jobs);
tr = transaction_free(tr);
return 0;
}
int manager_add_job_full(
Manager *m,
JobType type,
Unit *unit,
JobMode mode,
TransactionAddFlags extra_flags,
Set *affected_jobs,
sd_bus_error *reterr_error,
Job **ret) {
_cleanup_(transaction_abort_and_freep) Transaction *tr = NULL;
int r;
assert(m);
assert(type >= 0 && type < _JOB_TYPE_MAX);
assert(unit);
assert(mode >= 0 && mode < _JOB_MODE_MAX);
assert((extra_flags & ~_TRANSACTION_FLAGS_MASK_PUBLIC) == 0);
if (mode == JOB_ISOLATE && type != JOB_START)
return sd_bus_error_set(reterr_error, SD_BUS_ERROR_INVALID_ARGS, "Isolate is only valid for start.");
if (mode == JOB_ISOLATE && !unit->allow_isolate)
return sd_bus_error_set(reterr_error, BUS_ERROR_NO_ISOLATION, "Operation refused, unit may not be isolated.");
if (mode == JOB_TRIGGERING && type != JOB_STOP)
return sd_bus_error_set(reterr_error, SD_BUS_ERROR_INVALID_ARGS, "--job-mode=triggering is only valid for stop.");
if (mode == JOB_RESTART_DEPENDENCIES && type != JOB_START)
return sd_bus_error_set(reterr_error, SD_BUS_ERROR_INVALID_ARGS, "--job-mode=restart-dependencies is only valid for start.");
tr = transaction_new(mode == JOB_REPLACE_IRREVERSIBLY, ++m->last_transaction_id);
if (!tr)
return -ENOMEM;
LOG_CONTEXT_PUSHF("TRANSACTION_ID=%" PRIu64, tr->id);
log_unit_debug(unit, "Trying to enqueue job %s/%s/%s", unit->id, job_type_to_string(type), job_mode_to_string(mode));
type = job_type_collapse(type, unit);
r = transaction_add_job_and_dependencies(
tr,
type,
unit,
/* by= */ NULL,
TRANSACTION_MATTERS |
(IN_SET(mode, JOB_IGNORE_DEPENDENCIES, JOB_IGNORE_REQUIREMENTS) ? TRANSACTION_IGNORE_REQUIREMENTS : 0) |
(mode == JOB_IGNORE_DEPENDENCIES ? TRANSACTION_IGNORE_ORDER : 0) |
(mode == JOB_RESTART_DEPENDENCIES ? TRANSACTION_PROPAGATE_START_AS_RESTART : 0) |
extra_flags,
reterr_error);
if (r < 0)
return r;
if (mode == JOB_ISOLATE) {
r = transaction_add_isolate_jobs(tr, m);
if (r < 0)
return r;
}
if (mode == JOB_TRIGGERING) {
r = transaction_add_triggering_jobs(tr, unit);
if (r < 0)
return r;
}
r = transaction_activate(tr, m, mode, affected_jobs, reterr_error);
if (r < 0)
return r;
Job *anchor = ASSERT_PTR(set_first(tr->anchor_jobs));
assert(set_size(tr->anchor_jobs) == 1);
log_unit_debug(unit,
"Enqueued job %s/%s as %u", unit->id,
job_type_to_string(type), (unsigned) anchor->id);
if (ret)
*ret = anchor;
/* anchor_jobs tracks pointers to jobs that are now installed in the manager; clear it so
* transaction_free() doesn't trip its empty-set assertion. */
set_clear(tr->anchor_jobs);
tr = transaction_free(tr);
return 0;
}
int manager_add_job(
Manager *m,
JobType type,
Unit *unit,
JobMode mode,
sd_bus_error *reterr_error,
Job **ret) {
return manager_add_job_full(m, type, unit, mode, 0, NULL, reterr_error, ret);
}
int manager_add_job_by_name(Manager *m, JobType type, const char *name, JobMode mode, Set *affected_jobs, sd_bus_error *e, Job **ret) {
Unit *unit = NULL; /* just to appease gcc, initialization is not really necessary */
int r;
assert(m);
assert(type < _JOB_TYPE_MAX);
assert(name);
assert(mode < _JOB_MODE_MAX);
r = manager_load_unit(m, name, NULL, NULL, &unit);
if (r < 0)
return r;
assert(unit);
return manager_add_job_full(m, type, unit, mode, /* extra_flags= */ 0, affected_jobs, e, ret);
}
static int manager_add_job_by_name_or_warn_with_fallback(
Manager *m,
JobType type,
const char *name,
const char *fallback,
JobMode mode,
Set *affected_jobs,
Job **ret) {
_cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
int r;
r = manager_add_job_by_name(m, type, name, mode, affected_jobs, &error, ret);
if (r == -ENOENT && fallback) {
log_debug_errno(r, "Failed to enqueue job %s/%s, fallback to %s: %s",
name, job_mode_to_string(mode), fallback, bus_error_message(&error, r));
sd_bus_error_free(&error);
name = fallback;
r = manager_add_job_by_name(m, type, name, mode, affected_jobs, &error, ret);
}
if (r < 0)
return log_warning_errno(r, "Failed to enqueue job %s/%s: %s",
name, job_mode_to_string(mode), bus_error_message(&error, r));
return r;
}
int manager_add_job_by_name_or_warn(Manager *m, JobType type, const char *name, JobMode mode, Set *affected_jobs, Job **ret) {
return manager_add_job_by_name_or_warn_with_fallback(m, type, name, /* fallback= */ NULL, mode, affected_jobs, ret);
}
int manager_propagate_reload(Manager *m, Unit *unit, JobMode mode, sd_bus_error *e) {
_cleanup_(transaction_abort_and_freep) Transaction *tr = NULL;
int r;
assert(m);
assert(unit);
assert(mode < _JOB_MODE_MAX);
assert(mode != JOB_ISOLATE); /* Isolate is only valid for start */
tr = transaction_new(mode == JOB_REPLACE_IRREVERSIBLY, ++m->last_transaction_id);
if (!tr)
return -ENOMEM;
LOG_CONTEXT_PUSHF("TRANSACTION_ID=%" PRIu64, tr->id);
/* We need an anchor job */
r = transaction_add_job_and_dependencies(tr, JOB_NOP, unit, NULL, TRANSACTION_IGNORE_REQUIREMENTS|TRANSACTION_IGNORE_ORDER, e);
if (r < 0)
return r;
/* Failure in adding individual dependencies is ignored, so this always succeeds. */
transaction_add_propagate_reload_jobs(
tr,
unit,
set_first(tr->anchor_jobs),
mode == JOB_IGNORE_DEPENDENCIES ? TRANSACTION_IGNORE_ORDER : 0);
/* Only activate the transaction if it contains jobs other than NOP anchor.
* Short-circuiting here avoids unnecessary processing, such as emitting D-Bus signals. */
if (hashmap_size(tr->jobs) <= 1)
return 0;
r = transaction_activate(tr, m, mode, NULL, e);
if (r < 0)
return r;
/* tr->anchor_jobs tracks pointers to jobs that are now installed in the manager, clear it */
set_clear(tr->anchor_jobs);
tr = transaction_free(tr);
return 0;
}
Job *manager_get_job(Manager *m, uint32_t id) {
assert(m);
return hashmap_get(m->jobs, UINT32_TO_PTR(id));
}
Unit *manager_get_unit(Manager *m, const char *name) {
assert(m);
assert(name);
return hashmap_get(m->units, name);
}
static int manager_dispatch_target_deps_queue(Manager *m) {
Unit *u;
int r = 0;
assert(m);
while ((u = LIST_POP(target_deps_queue, m->target_deps_queue))) {
_cleanup_free_ Unit **targets = NULL;
int n_targets;
assert(u->in_target_deps_queue);
u->in_target_deps_queue = false;
/* Take an "atomic" snapshot of dependencies here, as the call below will likely modify the
* dependencies, and we can't have it that hash tables we iterate through are modified while
* we are iterating through them. */
n_targets = unit_get_dependency_array(u, UNIT_ATOM_DEFAULT_TARGET_DEPENDENCIES, &targets);
if (n_targets < 0)
return n_targets;
FOREACH_ARRAY(i, targets, n_targets) {
r = unit_add_default_target_dependency(u, *i);
if (r < 0)
return r;
}
}
return r;
}
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;
/* Dispatch the units waiting for their target dependencies to be added now, as all targets that we know about
* should be loaded and have aliases resolved */
(void) manager_dispatch_target_deps_queue(m);
return n;
}
bool manager_unit_cache_should_retry_load(Unit *u) {
assert(u);
/* Automatic reloading from disk only applies to units which were not found sometime in the past, and
* the not-found stub is kept pinned in the unit graph by dependencies. For units that were
* previously loaded, we don't do automatic reloading, and daemon-reload is necessary to update. */
if (u->load_state != UNIT_NOT_FOUND)
return false;
/* The cache has been updated since the last time we tried to load the unit. There might be new
* fragment paths to read. */
if (u->manager->unit_cache_timestamp_hash != u->fragment_not_found_timestamp_hash)
return true;
/* The cache needs to be updated because there are modifications on disk. */
return !lookup_paths_timestamp_hash_same(&u->manager->lookup_paths, u->manager->unit_cache_timestamp_hash, NULL);
}
int manager_load_unit_prepare(
Manager *m,
const char *name,
const char *path,
sd_bus_error *e,
Unit **ret) {
_cleanup_(unit_freep) Unit *cleanup_unit = NULL;
_cleanup_free_ char *nbuf = NULL;
int r;
assert(m);
assert(ret);
assert(name || path);
/* This will prepare the unit for loading, but not actually load anything from disk. */
if (path && !path_is_absolute(path))
return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS, "Path %s is not absolute.", path);
if (!name) {
r = path_extract_filename(path, &nbuf);
if (r < 0)
return r;
if (r == O_DIRECTORY)
return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS, "Path '%s' refers to directory, refusing.", path);
name = nbuf;
}
UnitType t = unit_name_to_type(name);
if (t == _UNIT_TYPE_INVALID || !unit_name_is_valid(name, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE)) {
if (unit_name_is_valid(name, UNIT_NAME_TEMPLATE))
return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS, "Unit name %s is missing the instance name.", name);
return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS, "Unit name %s is not valid.", name);
}
Unit *unit = manager_get_unit(m, name);
if (unit) {
/* The time-based cache allows new units to be started without daemon-reload,
* but if they are already referenced (because of dependencies or ordering)
* then we have to force a load of the fragment. As an optimization, check
* first if anything in the usual paths was modified since the last time
* the cache was loaded. Also check if the last time an attempt to load the
* unit was made was before the most recent cache refresh, so that we know
* we need to try again — even if the cache is current, it might have been
* updated in a different context before we had a chance to retry loading
* this particular unit. */
if (manager_unit_cache_should_retry_load(unit))
unit->load_state = UNIT_STUB;
else {
*ret = unit;
return 0; /* The unit was already loaded */
}
} else {
unit = cleanup_unit = unit_new(m, unit_vtable[t]->object_size);
if (!unit)
return -ENOMEM;
}
if (path) {
r = free_and_strdup(&unit->fragment_path, path);
if (r < 0)
return r;
}
r = unit_add_name(unit, name);
if (r < 0)
return r;
unit_add_to_load_queue(unit);
unit_add_to_dbus_queue(unit);
unit_add_to_gc_queue(unit);
*ret = unit;
TAKE_PTR(cleanup_unit);
return 1; /* The unit was added the load queue */
}
int manager_load_unit(
Manager *m,
const char *name,
const char *path,
sd_bus_error *e,
Unit **ret) {
int r;
assert(m);
assert(ret);
/* This will load the unit config, but not actually start any services or anything. */
r = manager_load_unit_prepare(m, name, path, e, ret);
if (r <= 0)
return r;
/* Unit was newly loaded */
manager_dispatch_load_queue(m);
*ret = unit_follow_merge(*ret);
return 0;
}
int manager_load_startable_unit_or_warn(
Manager *m,
const char *name,
const char *path,
int log_level,
Unit **ret) {
/* Load a unit, make sure it loaded fully and is not masked. */
_cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
Unit *unit;
int r;
assert(ret);
r = manager_load_unit(m, name, path, &error, &unit);
if (r < 0)
return log_full_errno(log_level, r, "Failed to load %s %s: %s",
name ? "unit" : "unit file", name ?: path,
bus_error_message(&error, r));
r = bus_unit_validate_load_state(unit, &error);
if (r < 0)
return log_full_errno(log_level, r, "%s", bus_error_message(&error, r));
*ret = unit;
return 0;
}
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, false);
}
void manager_unwatch_pidref(Manager *m, const PidRef *pid) {
assert(m);
for (;;) {
Unit *u;
u = manager_get_unit_by_pidref_watching(m, pid);
if (!u)
break;
unit_unwatch_pidref(u, pid);
}
}
static int manager_dispatch_run_queue(sd_event_source *source, void *userdata) {
Manager *m = ASSERT_PTR(userdata);
Job *j;
assert(source);
while ((j = prioq_peek(m->run_queue))) {
assert(j->installed);
assert(j->in_run_queue);
(void) job_run_and_invalidate(j);
}
if (m->n_running_jobs > 0)
manager_watch_jobs_in_progress(m);
if (m->n_on_console > 0)
manager_watch_idle_pipe(m);
return 1;
}
void manager_trigger_run_queue(Manager *m) {
int r;
assert(m);
r = sd_event_source_set_enabled(
m->run_queue_event_source,
prioq_isempty(m->run_queue) ? SD_EVENT_OFF : SD_EVENT_ONESHOT);
if (r < 0)
log_warning_errno(r, "Failed to enable job run queue event source, ignoring: %m");
}
static unsigned manager_send_pending_reload_replies(Manager *m) {
unsigned n = 0;
assert(m);
if (m->pending_reload_message_dbus) {
bus_send_pending_reload_message(m);
n++;
}
if (m->pending_reload_message_vl) {
manager_varlink_send_pending_reload_message(m);
n++;
}
return n;
}
static unsigned manager_dispatch_dbus_queue(Manager *m) {
unsigned n = 0, budget;
Unit *u;
Job *j;
assert(m);
/* If the API bus is connected but not fully set up yet (see bus_init_api()), postpone
* dispatching the queue, otherwise subscribers restored from a previous reexec would miss
* messages. Reload replies are sent anyway: method_reload()/vl_method_reload_manager() rely on
* them being sent before the next request is dispatched, and holding them back until the bus
* is set up (which can take a long time while the bus daemon is still starting) lets a second
* Reload() arrive while the first reply is still pending. Hence in this window a reply goes
* out before the signals queued by its reload, also on private connections, which get those
* signals once the bus is set up. */
if (m->api_bus && !m->api_bus_ready)
return manager_send_pending_reload_replies(m);
/* When we are reloading, let's not wait with generating signals, since we need to exit the manager as quickly
* as we can. There's no point in throttling generation of signals in that case. */
if (MANAGER_IS_RELOADING(m) || m->send_reloading_done || m->pending_reload_message_dbus || m->pending_reload_message_vl)
budget = UINT_MAX; /* infinite budget in this case */
else {
/* Anything to do at all? */
if (!m->dbus_unit_queue && !m->dbus_job_queue)
return 0;
/* Do we have overly many messages queued at the moment? If so, let's not enqueue more on top, let's
* sit this cycle out, and process things in a later cycle when the queues got a bit emptier. */
if (manager_bus_n_queued_write(m) > MANAGER_BUS_BUSY_THRESHOLD)
return 0;
/* Only process a certain number of units/jobs per event loop iteration. Even if the bus queue wasn't
* overly full before this call we shouldn't increase it in size too wildly in one step, and we
* shouldn't monopolize CPU time with generating these messages. Note the difference in counting of
* this "budget" and the "threshold" above: the "budget" is decreased only once per generated message,
* regardless how many buses/direct connections it is enqueued on, while the "threshold" is applied to
* each queued instance of bus message, i.e. if the same message is enqueued to five buses/direct
* connections it will be counted five times. This difference in counting ("references"
* vs. "instances") is primarily a result of the fact that it's easier to implement it this way,
* however it also reflects the thinking that the "threshold" should put a limit on used queue memory,
* i.e. space, while the "budget" should put a limit on time. Also note that the "threshold" is
* currently chosen much higher than the "budget". */
budget = MANAGER_BUS_MESSAGE_BUDGET;
}
while (budget != 0 && (u = m->dbus_unit_queue)) {
assert(u->in_dbus_queue);
bus_unit_send_change_signal(u);
varlink_unit_send_change_signal(u);
n++;
if (budget != UINT_MAX)
budget--;
}
while (budget != 0 && (j = m->dbus_job_queue)) {
assert(j->in_dbus_queue);
bus_job_send_change_signal(j);
varlink_job_send_change_signal(j);
n++;
if (budget != UINT_MAX)
budget--;
}
if (m->send_reloading_done) {
m->send_reloading_done = false;
bus_manager_send_reloading(m, false);
n++;
}