HALF ECHO LEARN / REFERENCE COLLECTION
v262.2src/core/unit.c
Git blob: 1de634c975a3311494dacb28ce1bb5e67261717a
Lines 6001–7000 of 7,295
assert(u);
assert(c);
if (u->exported_log_ratelimit_interval)
return 0;
if (c->log_ratelimit.interval == 0)
return 0;
const char *p = strjoina("/run/systemd/units/log-rate-limit-interval:", u->id);
char buf[DECIMAL_STR_MAX(c->log_ratelimit.interval)];
xsprintf(buf, "%" PRIu64, c->log_ratelimit.interval);
r = symlink_atomic(buf, p);
if (r < 0)
return log_unit_debug_errno(u, r, "Failed to create log rate limit interval symlink %s: %m", p);
u->exported_log_ratelimit_interval = true;
return 0;
}
static int unit_export_log_ratelimit_burst(Unit *u, const ExecContext *c) {
int r;
assert(u);
assert(c);
if (u->exported_log_ratelimit_burst)
return 0;
if (c->log_ratelimit.burst == 0)
return 0;
const char *p = strjoina("/run/systemd/units/log-rate-limit-burst:", u->id);
char buf[DECIMAL_STR_MAX(c->log_ratelimit.burst)];
xsprintf(buf, "%u", c->log_ratelimit.burst);
r = symlink_atomic(buf, p);
if (r < 0)
return log_unit_debug_errno(u, r, "Failed to create log rate limit burst symlink %s: %m", p);
u->exported_log_ratelimit_burst = true;
return 0;
}
void unit_export_state_files(Unit *u) {
const ExecContext *c;
assert(u);
if (!u->id)
return;
if (MANAGER_IS_TEST_RUN(u->manager))
return;
/* Exports a couple of unit properties to /run/systemd/units/, so that journald can quickly query this data
* from there. Ideally, journald would use IPC to query this, like everybody else, but that's hard, as long as
* the IPC system itself and PID 1 also log to the journal.
*
* Note that these files really shouldn't be considered API for anyone else, as use a runtime file system as
* IPC replacement is not compatible with today's world of file system namespaces. However, this doesn't really
* apply to communication between the journal and systemd, as we assume that these two daemons live in the same
* namespace at least.
*
* Note that some of the "files" exported here are actually symlinks and not regular files. Symlinks work
* better for storing small bits of data, in particular as we can write them with two system calls, and read
* them with one. */
(void) unit_export_invocation_id(u);
if (!MANAGER_IS_SYSTEM(u->manager))
return;
c = unit_get_exec_context(u);
if (c) {
(void) unit_export_log_level_max(u, c->log_level_max, /* overwrite= */ false);
(void) unit_export_log_extra_fields(u, c);
(void) unit_export_log_ratelimit_interval(u, c);
(void) unit_export_log_ratelimit_burst(u, c);
}
}
void unit_unlink_state_files(Unit *u) {
const char *p;
assert(u);
if (!u->id)
return;
/* Undoes the effect of unit_export_state() */
if (u->exported_invocation_id) {
_cleanup_free_ char *invocation_path = NULL;
int r = unit_get_invocation_path(u, &invocation_path);
if (r >= 0) {
(void) unlink(invocation_path);
u->exported_invocation_id = false;
}
}
if (!MANAGER_IS_SYSTEM(u->manager))
return;
if (u->exported_log_level_max) {
p = strjoina("/run/systemd/units/log-level-max:", u->id);
(void) unlink(p);
u->exported_log_level_max = false;
}
if (u->exported_log_extra_fields) {
p = strjoina("/run/systemd/units/log-extra-fields:", u->id);
(void) unlink(p);
u->exported_log_extra_fields = false;
}
if (u->exported_log_ratelimit_interval) {
p = strjoina("/run/systemd/units/log-rate-limit-interval:", u->id);
(void) unlink(p);
u->exported_log_ratelimit_interval = false;
}
if (u->exported_log_ratelimit_burst) {
p = strjoina("/run/systemd/units/log-rate-limit-burst:", u->id);
(void) unlink(p);
u->exported_log_ratelimit_burst = false;
}
}
int unit_set_debug_invocation(Unit *u, bool enable) {
int r;
assert(u);
if (u->debug_invocation == enable)
return 0; /* Nothing to do */
u->debug_invocation = enable;
/* Ensure that the new log level is exported for the journal, in place of the previous one */
if (u->exported_log_level_max) {
const ExecContext *ec = unit_get_exec_context(u);
if (ec) {
r = unit_export_log_level_max(u, enable ? LOG_PRI(LOG_DEBUG) : ec->log_level_max, /* overwrite= */ true);
if (r < 0)
return r;
}
}
return 1;
}
int unit_prepare_exec(Unit *u) {
int r;
assert(u);
/* Prepares everything so that we can fork of a process for this unit */
r = unit_realize_cgroup(u);
if (r < 0)
return r;
CGroupRuntime *crt = unit_get_cgroup_runtime(u);
if (crt && crt->reset_accounting) {
(void) unit_reset_accounting(u);
crt->reset_accounting = false;
}
unit_export_state_files(u);
r = unit_setup_exec_runtime(u);
if (r < 0)
return r;
return 0;
}
static int unit_log_leftover_process_start(const PidRef *pid, int sig, void *userdata) {
const Unit *u = ASSERT_PTR(userdata);
_cleanup_free_ char *comm = NULL;
assert(pidref_is_set(pid));
(void) pidref_get_comm(pid, &comm);
if (ignore_leftover_process(comm))
return 0;
/* During start we print a warning */
log_unit_warning(u,
"Found left-over process " PID_FMT " (%s) in control group while starting unit. Ignoring.\n"
"This usually indicates unclean termination of a previous run, or service implementation deficiencies.",
pid->pid, strna(comm));
return 1;
}
static int unit_log_leftover_process_stop(const PidRef *pid, int sig, void *userdata) {
const Unit *u = ASSERT_PTR(userdata);
_cleanup_free_ char *comm = NULL;
assert(pidref_is_set(pid));
(void) pidref_get_comm(pid, &comm);
if (ignore_leftover_process(comm))
return 0;
/* During stop we only print an informational message */
log_unit_info(u,
"Unit process " PID_FMT " (%s) remains running after unit stopped.",
pid->pid, strna(comm));
return 1;
}
int unit_warn_leftover_processes(Unit *u, bool start) {
_cleanup_free_ char *cgroup = NULL;
int r;
assert(u);
r = unit_get_cgroup_path_with_fallback(u, &cgroup);
if (r < 0)
return r;
return cg_kill_recursive(
cgroup,
/* sig= */ 0,
/* flags= */ 0,
/* killed_pids= */ NULL,
start ? unit_log_leftover_process_start : unit_log_leftover_process_stop,
u);
}
bool unit_needs_console(Unit *u) {
ExecContext *ec;
UnitActiveState state;
assert(u);
state = unit_active_state(u);
if (UNIT_IS_INACTIVE_OR_FAILED(state))
return false;
if (UNIT_VTABLE(u)->needs_console)
return UNIT_VTABLE(u)->needs_console(u);
/* If this unit type doesn't implement this call, let's use a generic fallback implementation: */
ec = unit_get_exec_context(u);
if (!ec)
return false;
return exec_context_may_touch_console(ec);
}
int unit_pid_attachable(Unit *u, PidRef *pid, sd_bus_error *reterr_error) {
int r;
assert(u);
/* Checks whether the specified PID is generally good for attaching, i.e. a valid PID, not our manager itself,
* and not a kernel thread either */
/* First, a simple range check */
if (!pidref_is_set(pid))
return sd_bus_error_set(reterr_error, SD_BUS_ERROR_INVALID_ARGS, "Process identifier is not valid.");
/* Some extra safety check */
if (pid->pid == 1 || pidref_is_self(pid))
return sd_bus_error_setf(reterr_error, SD_BUS_ERROR_INVALID_ARGS, "Process " PID_FMT " is a manager process, refusing.", pid->pid);
/* Don't even begin to bother with kernel threads */
r = pidref_is_kernel_thread(pid);
if (r == -ESRCH)
return sd_bus_error_setf(reterr_error, SD_BUS_ERROR_UNIX_PROCESS_ID_UNKNOWN, "Process with ID " PID_FMT " does not exist.", pid->pid);
if (r < 0)
return sd_bus_error_set_errnof(reterr_error, r, "Failed to determine whether process " PID_FMT " is a kernel thread: %m", pid->pid);
if (r > 0)
return sd_bus_error_setf(reterr_error, SD_BUS_ERROR_INVALID_ARGS, "Process " PID_FMT " is a kernel thread, refusing.", pid->pid);
return 0;
}
int unit_get_log_level_max(const Unit *u) {
if (u) {
if (u->debug_invocation)
return LOG_DEBUG;
ExecContext *ec = unit_get_exec_context(u);
if (ec && ec->log_level_max >= 0)
return ec->log_level_max;
}
return log_get_max_level();
}
bool unit_log_level_test(const Unit *u, int level) {
assert(u);
return LOG_PRI(level) <= unit_get_log_level_max(u);
}
void unit_log_success(Unit *u) {
assert(u);
/* Let's show message "Deactivated successfully" in debug mode (when manager is user) rather than in info mode.
* This message has low information value for regular users and it might be a bit overwhelming on a system with
* a lot of devices. */
log_unit_struct(u,
MANAGER_IS_USER(u->manager) ? LOG_DEBUG : LOG_INFO,
LOG_MESSAGE_ID(SD_MESSAGE_UNIT_SUCCESS_STR),
LOG_UNIT_INVOCATION_ID(u),
LOG_UNIT_MESSAGE(u, "Deactivated successfully."));
}
void unit_log_failure(Unit *u, const char *result) {
assert(u);
assert(result);
log_unit_struct(u, LOG_WARNING,
LOG_MESSAGE_ID(SD_MESSAGE_UNIT_FAILURE_RESULT_STR),
LOG_UNIT_INVOCATION_ID(u),
LOG_UNIT_MESSAGE(u, "Failed with result '%s'.", result),
LOG_ITEM("UNIT_RESULT=%s", result));
}
void unit_log_skip(Unit *u, const char *result) {
assert(u);
assert(result);
log_unit_struct(u, LOG_INFO,
LOG_MESSAGE_ID(SD_MESSAGE_UNIT_SKIPPED_STR),
LOG_UNIT_INVOCATION_ID(u),
LOG_UNIT_MESSAGE(u, "Skipped due to '%s'.", result),
LOG_ITEM("UNIT_RESULT=%s", result));
}
void unit_log_process_exit(
Unit *u,
const char *kind,
const char *command,
bool success,
int code,
int status) {
int level;
assert(u);
assert(kind);
/* If this is a successful exit, let's log about the exit code on DEBUG level. If this is a failure
* and the process exited on its own via exit(), then let's make this a NOTICE, under the assumption
* that the service already logged the reason at a higher log level on its own. Otherwise, make it a
* WARNING. */
if (success)
level = LOG_DEBUG;
else if (code == CLD_EXITED)
level = LOG_NOTICE;
else
level = LOG_WARNING;
log_unit_struct(u, level,
LOG_MESSAGE_ID(SD_MESSAGE_UNIT_PROCESS_EXIT_STR),
LOG_UNIT_MESSAGE(u, "%s exited, code=%s, status=%i/%s%s",
kind,
sigchld_code_to_string(code), status,
strna(code == CLD_EXITED
? exit_status_to_string(status, EXIT_STATUS_FULL)
: signal_to_string(status)),
success ? " (success)" : ""),
LOG_ITEM("EXIT_CODE=%s", sigchld_code_to_string(code)),
LOG_ITEM("EXIT_STATUS=%i", status),
LOG_ITEM("COMMAND=%s", strna(command)),
LOG_UNIT_INVOCATION_ID(u));
}
int unit_exit_status(Unit *u) {
assert(u);
/* Returns the exit status to propagate for the most recent cycle of this unit. Returns a value in the range
* 0…255 if there's something to propagate. EOPNOTSUPP if the concept does not apply to this unit type, ENODATA
* if no data is currently known (for example because the unit hasn't deactivated yet) and EBADE if the main
* service process has exited abnormally (signal/coredump). */
if (!UNIT_VTABLE(u)->exit_status)
return -EOPNOTSUPP;
return UNIT_VTABLE(u)->exit_status(u);
}
int unit_failure_action_exit_status(Unit *u) {
int r;
assert(u);
/* Returns the exit status to propagate on failure, or an error if there's nothing to propagate */
if (u->failure_action_exit_status >= 0)
return u->failure_action_exit_status;
r = unit_exit_status(u);
if (r == -EBADE) /* Exited, but not cleanly (i.e. by signal or such) */
return EXIT_EXCEPTION;
return r;
}
int unit_success_action_exit_status(Unit *u) {
int r;
assert(u);
/* Returns the exit status to propagate on success, or an error if there's nothing to propagate */
if (u->success_action_exit_status >= 0)
return u->success_action_exit_status;
r = unit_exit_status(u);
if (r == -EBADE) /* Exited, but not cleanly (i.e. by signal or such) */
return EXIT_EXCEPTION;
return r;
}
int unit_test_trigger_loaded(Unit *u) {
Unit *trigger;
/* Tests whether the unit to trigger is loaded */
trigger = UNIT_TRIGGER(u);
if (!trigger)
return log_unit_error_errno(u, SYNTHETIC_ERRNO(ENOENT),
"Refusing to start, no unit to trigger.");
if (trigger->load_state != UNIT_LOADED)
return log_unit_error_errno(u, SYNTHETIC_ERRNO(ENOENT),
"Refusing to start, unit %s to trigger not loaded.", trigger->id);
return 0;
}
void unit_destroy_runtime_data(Unit *u, const ExecContext *context, bool destroy_runtime_dir) {
assert(u);
assert(u->manager);
assert(context);
/* EXEC_PRESERVE_RESTART is handled via unit_release_resources()! */
if (destroy_runtime_dir && context->runtime_directory_preserve_mode == EXEC_PRESERVE_NO)
exec_context_destroy_runtime_directory(context, u->manager->prefix[EXEC_DIRECTORY_RUNTIME]);
exec_context_destroy_credentials(context, u->manager->prefix[EXEC_DIRECTORY_RUNTIME], u->id);
exec_context_destroy_mount_ns_dir(u);
}
int unit_clean(Unit *u, ExecCleanMask mask) {
UnitActiveState state;
assert(u);
/* Special return values:
*
* -EOPNOTSUPP → cleaning not supported for this unit type
* -EUNATCH → cleaning not defined for this resource type
* -EBUSY → unit currently can't be cleaned since it's running or not properly loaded, or has
* a job queued or similar
*/
if (!UNIT_VTABLE(u)->clean)
return -EOPNOTSUPP;
if (mask == 0)
return -EUNATCH;
if (u->load_state != UNIT_LOADED)
return -EBUSY;
if (u->job)
return -EBUSY;
state = unit_active_state(u);
if (state != UNIT_INACTIVE)
return -EBUSY;
return UNIT_VTABLE(u)->clean(u, mask);
}
int unit_can_clean(Unit *u, ExecCleanMask *ret) {
assert(u);
assert(ret);
if (!UNIT_VTABLE(u)->clean ||
u->load_state != UNIT_LOADED) {
*ret = 0;
return 0;
}
/* When the clean() method is set, can_clean() really should be set too */
assert(UNIT_VTABLE(u)->can_clean);
return UNIT_VTABLE(u)->can_clean(u, ret);
}
bool unit_can_start_refuse_manual(Unit *u) {
return unit_can_start(u) && !u->refuse_manual_start;
}
bool unit_can_stop_refuse_manual(Unit *u) {
return unit_can_stop(u) && !u->refuse_manual_stop;
}
bool unit_can_isolate_refuse_manual(Unit *u) {
return unit_can_isolate(u) && !u->refuse_manual_start;
}
void unit_next_freezer_state(Unit *u, FreezerAction action, FreezerState *ret_next, FreezerState *ret_objective) {
FreezerState current, parent, next, objective;
assert(u);
assert(action >= 0);
assert(action < _FREEZER_ACTION_MAX);
assert(ret_next);
assert(ret_objective);
/* This function determines the correct freezer state transitions for a unit
* given the action being requested. It returns the next state, and also the "objective",
* which is either FREEZER_FROZEN or FREEZER_RUNNING, depending on what actual state we
* ultimately want to achieve. */
current = u->freezer_state;
Unit *slice = UNIT_GET_SLICE(u);
if (slice)
parent = slice->freezer_state;
else
parent = FREEZER_RUNNING;
switch (action) {
case FREEZER_FREEZE:
/* We always "promote" a freeze initiated by parent into a normal freeze */
if (IN_SET(current, FREEZER_FROZEN, FREEZER_FROZEN_BY_PARENT))
next = FREEZER_FROZEN;
else
next = FREEZER_FREEZING;
break;
case FREEZER_THAW:
/* Thawing is the most complicated operation here, because we can't thaw a unit
* if its parent is frozen. So we instead "demote" a normal freeze into a freeze
* initiated by parent if the parent is frozen */
if (IN_SET(current, FREEZER_RUNNING, FREEZER_THAWING,
FREEZER_FREEZING_BY_PARENT, FREEZER_FROZEN_BY_PARENT)) /* Should usually be refused by unit_freezer_action */
next = current;
else if (current == FREEZER_FREEZING) {
if (IN_SET(parent, FREEZER_RUNNING, FREEZER_THAWING))
next = FREEZER_THAWING;
else
next = FREEZER_FREEZING_BY_PARENT;
} else if (current == FREEZER_FROZEN) {
if (IN_SET(parent, FREEZER_RUNNING, FREEZER_THAWING))
next = FREEZER_THAWING;
else
next = FREEZER_FROZEN_BY_PARENT;
} else
assert_not_reached();
break;
case FREEZER_PARENT_FREEZE:
/* We need to avoid accidentally demoting units frozen manually */
if (IN_SET(current, FREEZER_FREEZING, FREEZER_FROZEN, FREEZER_FROZEN_BY_PARENT))
next = current;
else
next = FREEZER_FREEZING_BY_PARENT;
break;
case FREEZER_PARENT_THAW:
/* We don't want to thaw units from a parent if they were frozen
* manually, so for such units this action is a no-op */
if (IN_SET(current, FREEZER_RUNNING, FREEZER_FREEZING, FREEZER_FROZEN))
next = current;
else
next = FREEZER_THAWING;
break;
default:
assert_not_reached();
}
objective = freezer_state_objective(next);
assert(IN_SET(objective, FREEZER_RUNNING, FREEZER_FROZEN));
*ret_next = next;
*ret_objective = objective;
}
bool unit_can_freeze(const Unit *u) {
assert(u);
if (unit_has_name(u, SPECIAL_ROOT_SLICE) || unit_has_name(u, SPECIAL_INIT_SCOPE))
return false;
if (UNIT_VTABLE(u)->can_freeze)
return UNIT_VTABLE(u)->can_freeze(u);
return UNIT_VTABLE(u)->freezer_action;
}
void unit_set_freezer_state(Unit *u, FreezerState state) {
assert(u);
assert(state >= 0);
assert(state < _FREEZER_STATE_MAX);
if (u->freezer_state == state)
return;
log_unit_debug(u, "Freezer state changed %s -> %s",
freezer_state_to_string(u->freezer_state), freezer_state_to_string(state));
u->freezer_state = state;
unit_add_to_dbus_queue(u);
}
void unit_freezer_complete(Unit *u, FreezerState kernel_state) {
bool expected;
assert(u);
assert(IN_SET(kernel_state, FREEZER_RUNNING, FREEZER_FROZEN));
expected = IN_SET(u->freezer_state, FREEZER_RUNNING, FREEZER_THAWING) == (kernel_state == FREEZER_RUNNING);
unit_set_freezer_state(u, expected ? freezer_state_finish(u->freezer_state) : kernel_state);
log_unit_info(u, "Unit now %s.", u->freezer_state == FREEZER_RUNNING ? "thawed" :
freezer_state_to_string(u->freezer_state));
/* If the cgroup's final state is against what's requested by us, report as canceled. */
bus_unit_send_pending_freezer_message(u, /* canceled= */ !expected);
}
int unit_freezer_action(Unit *u, FreezerAction action) {
UnitActiveState s;
int r;
assert(u);
assert(IN_SET(action, FREEZER_FREEZE, FREEZER_THAW));
if (!unit_can_freeze(u))
return -EOPNOTSUPP;
if (u->job)
return -EBUSY;
if (u->load_state != UNIT_LOADED)
return -EHOSTDOWN;
s = unit_active_state(u);
if (s != UNIT_ACTIVE)
return -EHOSTDOWN;
if (action == FREEZER_FREEZE && IN_SET(u->freezer_state, FREEZER_FREEZING, FREEZER_FREEZING_BY_PARENT))
return -EALREADY;
if (action == FREEZER_THAW && u->freezer_state == FREEZER_THAWING)
return -EALREADY;
if (action == FREEZER_THAW && IN_SET(u->freezer_state, FREEZER_FREEZING_BY_PARENT, FREEZER_FROZEN_BY_PARENT))
return -EDEADLK;
r = UNIT_VTABLE(u)->freezer_action(u, action);
if (r <= 0)
return r;
assert(IN_SET(u->freezer_state, FREEZER_FREEZING, FREEZER_FREEZING_BY_PARENT, FREEZER_THAWING));
return 1;
}
Condition *unit_find_failed_condition(Unit *u) {
Condition *failed_trigger = NULL;
bool has_succeeded_trigger = false;
if (u->condition_result)
return NULL;
LIST_FOREACH(conditions, c, u->conditions)
if (c->trigger) {
if (c->result == CONDITION_SUCCEEDED)
has_succeeded_trigger = true;
else if (!failed_trigger)
failed_trigger = c;
} else if (c->result != CONDITION_SUCCEEDED)
return c;
return failed_trigger && !has_succeeded_trigger ? failed_trigger : NULL;
}
int unit_can_live_mount(Unit *u, sd_bus_error *reterr_error) {
assert(u);
if (!UNIT_VTABLE(u)->live_mount)
return sd_bus_error_setf(
reterr_error,
SD_BUS_ERROR_NOT_SUPPORTED,
"Live mounting not supported by unit type '%s'",
unit_type_to_string(u->type));
if (u->load_state != UNIT_LOADED)
return sd_bus_error_setf(
reterr_error,
BUS_ERROR_NO_SUCH_UNIT,
"Unit '%s' not loaded, cannot live mount",
u->id);
if (!UNIT_VTABLE(u)->can_live_mount)
return 0;
return UNIT_VTABLE(u)->can_live_mount(u, reterr_error);
}
int unit_live_mount(
Unit *u,
const char *src,
const char *dst,
sd_bus_message *message,
MountInNamespaceFlags flags,
const MountOptions *options,
sd_bus_error *reterr_error) {
assert(u);
assert(UNIT_VTABLE(u)->live_mount);
if (!UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u))) {
log_unit_debug(u, "Unit not active, cannot perform live mount.");
return sd_bus_error_setf(
reterr_error,
BUS_ERROR_UNIT_INACTIVE,
"Live mounting '%s' on '%s' for unit '%s' cannot be scheduled: unit not active",
src,
dst,
u->id);
}
if (unit_active_state(u) == UNIT_REFRESHING) {
log_unit_debug(u, "Unit already live mounting, refusing further requests.");
return sd_bus_error_setf(
reterr_error,
BUS_ERROR_UNIT_BUSY,
"Live mounting '%s' on '%s' for unit '%s' cannot be scheduled: another live mount in progress",
src,
dst,
u->id);
}
if (u->job) {
log_unit_debug(u, "Unit already has a job in progress, cannot live mount");
return sd_bus_error_setf(
reterr_error,
BUS_ERROR_UNIT_BUSY,
"Live mounting '%s' on '%s' for unit '%s' cannot be scheduled: another operation in progress",
src,
dst,
u->id);
}
return UNIT_VTABLE(u)->live_mount(u, src, dst, message, flags, options, reterr_error);
}
static const char* const collect_mode_table[_COLLECT_MODE_MAX] = {
[COLLECT_INACTIVE] = "inactive",
[COLLECT_INACTIVE_OR_FAILED] = "inactive-or-failed",
};
DEFINE_STRING_TABLE_LOOKUP(collect_mode, CollectMode);
Unit* unit_has_dependency(const Unit *u, UnitDependencyAtom atom, Unit *other) {
Unit *i;
assert(u);
/* Checks if the unit has a dependency on 'other' with the specified dependency atom. If 'other' is
* NULL checks if the unit has *any* dependency of that atom. Returns 'other' if found (or if 'other'
* is NULL the first entry found), or NULL if not found. */
UNIT_FOREACH_DEPENDENCY(i, u, atom)
if (!other || other == i)
return i;
return NULL;
}
int unit_get_dependency_array(const Unit *u, UnitDependencyAtom atom, Unit ***ret_array) {
_cleanup_free_ Unit **array = NULL;
size_t n = 0;
Unit *other;
assert(u);
assert(ret_array);
/* Gets a list of units matching a specific atom as array. This is useful when iterating through
* dependencies while modifying them: the array is an "atomic snapshot" of sorts, that can be read
* while the dependency table is continuously updated. */
UNIT_FOREACH_DEPENDENCY(other, u, atom) {
if (!GREEDY_REALLOC(array, n + 1))
return -ENOMEM;
array[n++] = other;
}
*ret_array = TAKE_PTR(array);
assert(n <= INT_MAX);
return (int) n;
}
int unit_get_transitive_dependency_set(Unit *u, UnitDependencyAtom atom, Set **ret) {
_cleanup_set_free_ Set *units = NULL, *queue = NULL;
Unit *other;
int r;
assert(u);
assert(ret);
/* Similar to unit_get_dependency_array(), but also search the same dependency in other units. */
do {
UNIT_FOREACH_DEPENDENCY(other, u, atom) {
r = set_ensure_put(&units, NULL, other);
if (r < 0)
return r;
if (r == 0)
continue;
r = set_ensure_put(&queue, NULL, other);
if (r < 0)
return r;
}
} while ((u = set_steal_first(queue)));
*ret = TAKE_PTR(units);
return 0;
}
int unit_arm_timer(
Unit *u,
sd_event_source **source,
bool relative,
usec_t usec,
sd_event_time_handler_t handler) {
int r;
assert(u);
assert(source);
assert(handler);
if (*source) {
if (usec == USEC_INFINITY)
return sd_event_source_set_enabled(*source, SD_EVENT_OFF);
r = (relative ? sd_event_source_set_time_relative : sd_event_source_set_time)(*source, usec);
if (r < 0)
return r;
return sd_event_source_set_enabled(*source, SD_EVENT_ONESHOT);
}
if (usec == USEC_INFINITY)
return 0;
r = (relative ? sd_event_add_time_relative : sd_event_add_time)(
u->manager->event,
source,
CLOCK_MONOTONIC,
usec, 0,
handler,
u);
if (r < 0)
return r;
const char *d = strjoina(unit_type_to_string(u->type), "-timer");
(void) sd_event_source_set_description(*source, d);
return 0;
}
bool unit_passes_filter(Unit *u, char * const *states, char * const *patterns) {
assert(u);
if (!strv_isempty(states)) {
char * const *unit_states = STRV_MAKE(
unit_load_state_to_string(u->load_state),
unit_active_state_to_string(unit_active_state(u)),
unit_sub_state_to_string(u));
if (!strv_overlap(states, unit_states))
return false;
}
return strv_fnmatch_or_empty(patterns, u->id, FNM_NOESCAPE);
}
static int unit_get_nice(Unit *u) {
ExecContext *ec;
ec = unit_get_exec_context(u);
return ec ? ec->nice : 0;
}
static uint64_t unit_get_cpu_weight(Unit *u) {
CGroupContext *cc;
cc = unit_get_cgroup_context(u);
return cc ? cgroup_context_cpu_weight(cc, manager_state(u->manager)) : CGROUP_WEIGHT_DEFAULT;
}
int unit_get_exec_quota_stats(Unit *u, ExecContext *c, ExecDirectoryType dt, uint64_t *ret_usage, uint64_t *ret_limit) {
int r;
_cleanup_close_ int fd = -EBADF;
_cleanup_free_ char *p = NULL, *pp = NULL;
assert(u);
assert(c);
assert(ret_usage);
assert(ret_limit);
if (c->directories[dt].n_items == 0) {
*ret_usage = UINT64_MAX;
*ret_limit = UINT64_MAX;
return 0;
}
ExecDirectoryItem *i = &c->directories[dt].items[0];
p = path_join(u->manager->prefix[dt], i->path);
if (!p)
return log_oom_debug();
if (exec_directory_is_private(c, dt)) {
pp = path_join(u->manager->prefix[dt], "private", i->path);
if (!pp)
return log_oom_debug();
}
const char *target_dir = pp ?: p;
fd = open(target_dir, O_PATH | O_CLOEXEC | O_DIRECTORY);
if (fd < 0)
return log_unit_debug_errno(u, errno, "Failed to get exec quota stats: %m");
uint32_t proj_id;
r = read_fs_xattr_fd(fd, /* ret_xflags= */ NULL, &proj_id);
if (r < 0)
return log_unit_debug_errno(u, r, "Failed to get project ID for exec quota stats: %m");
struct dqblk req;
r = quota_query_proj_id(fd, proj_id, &req);
if (r <= 0)
return log_unit_debug_errno(u, r, "Failed to query project ID for exec quota stats: %m");
*ret_usage = req.dqb_curspace;
*ret_limit = req.dqb_bhardlimit * QIF_DQBLKSIZE;
return r;
}
int unit_compare_priority(Unit *a, Unit *b) {
int ret;
ret = CMP(a->type, b->type);
if (ret != 0)
return -ret;
ret = CMP(unit_get_cpu_weight(a), unit_get_cpu_weight(b));
if (ret != 0)
return -ret;
ret = CMP(unit_get_nice(a), unit_get_nice(b));
if (ret != 0)
return ret;
return strcmp(a->id, b->id);
}
const char* unit_log_field(const Unit *u) {
return MANAGER_IS_SYSTEM(ASSERT_PTR(u)->manager) ? "UNIT=" : "USER_UNIT=";
}
const char* unit_invocation_log_field(const Unit *u) {
return MANAGER_IS_SYSTEM(ASSERT_PTR(u)->manager) ? "INVOCATION_ID=" : "USER_INVOCATION_ID=";
}
const ActivationDetailsVTable * const activation_details_vtable[_UNIT_TYPE_MAX] = {
[UNIT_PATH] = &activation_details_path_vtable,
[UNIT_TIMER] = &activation_details_timer_vtable,
};