HALF ECHO LEARN / REFERENCE COLLECTION
v262.2src/core/unit.c
Git blob: 1de634c975a3311494dacb28ce1bb5e67261717a
Lines 2001–3000 of 7,295
if (following) {
log_unit_debug(u, "Redirecting start request from %s to %s.", u->id, following->id);
return unit_start(following, details);
}
/* Check to make sure the unit isn't frozen */
if (u->freezer_state != FREEZER_RUNNING)
return -EDEADLK;
/* Check our ability to start early so that ratelimited or already starting/started units don't
* cause us to enter a busy loop. */
if (UNIT_VTABLE(u)->test_startable) {
r = UNIT_VTABLE(u)->test_startable(u);
if (r <= 0)
return r;
}
/* If it is stopped, but we cannot start it, then fail */
if (!UNIT_VTABLE(u)->start)
return -EBADR;
if (UNIT_IS_INACTIVE_OR_FAILED(state)) {
Slice *slice = SLICE(UNIT_GET_SLICE(u));
if (slice) {
/* Check hard concurrency limit. Note this is partially redundant, we already checked
* this when enqueuing jobs. However, between the time when we enqueued this and the
* time we are dispatching the queue the configuration might have changed, hence
* check here again */
if (slice_concurrency_hard_max_reached(slice, u))
return -ETOOMANYREFS;
/* Also check soft concurrenty limit, and return EAGAIN so that the job is kept in
* the queue */
if (slice_concurrency_soft_max_reached(slice, u))
return -EAGAIN; /* Try again, keep in queue */
/* Check activating concurrency limit to pace concurrent startups */
if (slice_activating_concurrency_max_reached(slice, u))
return -EAGAIN; /* Try again, keep in queue */
}
}
/* We don't suppress calls to ->start() here when we are already starting, to allow this request to
* be used as a "hurry up" call, for example when the unit is in some "auto restart" state where it
* waits for a holdoff timer to elapse before it will start again. */
unit_add_to_dbus_queue(u);
if (!u->activation_details) /* Older details object wins */
u->activation_details = activation_details_ref(details);
return UNIT_VTABLE(u)->start(u);
}
bool unit_can_start(Unit *u) {
assert(u);
if (u->load_state != UNIT_LOADED)
return false;
if (!unit_type_supported(u->type))
return false;
/* Scope units may be started only once */
if (UNIT_VTABLE(u)->once_only && dual_timestamp_is_set(&u->inactive_exit_timestamp))
return false;
return !!UNIT_VTABLE(u)->start;
}
bool unit_can_isolate(Unit *u) {
assert(u);
return unit_can_start(u) &&
u->allow_isolate;
}
/* Errors:
* -EBADR: This unit type does not support stopping.
* -EALREADY: Unit is already stopped.
* -EAGAIN: An operation is already in progress. Retry later.
* -EDEADLK: Unit is frozen
*/
int unit_stop(Unit *u) {
UnitActiveState state;
Unit *following;
assert(u);
state = unit_active_state(u);
if (UNIT_IS_INACTIVE_OR_FAILED(state))
return -EALREADY;
following = unit_following(u);
if (following) {
log_unit_debug(u, "Redirecting stop request from %s to %s.", u->id, following->id);
return unit_stop(following);
}
/* Check to make sure the unit isn't frozen */
if (u->freezer_state != FREEZER_RUNNING)
return -EDEADLK;
if (!UNIT_VTABLE(u)->stop)
return -EBADR;
unit_add_to_dbus_queue(u);
return UNIT_VTABLE(u)->stop(u);
}
bool unit_can_stop(Unit *u) {
assert(u);
/* Note: if we return true here, it does not mean that the unit may be successfully stopped.
* Extrinsic units follow external state and they may stop following external state changes
* (hence we return true here), but an attempt to do this through the manager will fail. */
if (!unit_type_supported(u->type))
return false;
if (u->perpetual)
return false;
return !!UNIT_VTABLE(u)->stop;
}
/* Errors:
* -EBADR: This unit type does not support reloading.
* -ENOEXEC: Unit is not started.
* -EAGAIN: An operation is already in progress. Retry later.
* -EDEADLK: Unit is frozen.
*/
int unit_reload(Unit *u) {
UnitActiveState state;
Unit *following;
assert(u);
if (u->load_state != UNIT_LOADED)
return -EINVAL;
if (!unit_can_reload(u))
return -EBADR;
state = unit_active_state(u);
if (IN_SET(state, UNIT_RELOADING, UNIT_REFRESHING))
/* "refreshing" means some resources in the unit namespace is being updated. Unlike reload,
* the unit processes aren't made aware of refresh. Let's put the job back to queue
* in both cases, as refresh typically takes place before reload and it's better to wait
* for it rather than failing. */
return -EAGAIN;
if (state != UNIT_ACTIVE)
return log_unit_warning_errno(u, SYNTHETIC_ERRNO(ENOEXEC), "Unit cannot be reloaded because it is inactive.");
following = unit_following(u);
if (following) {
log_unit_debug(u, "Redirecting reload request from %s to %s.", u->id, following->id);
return unit_reload(following);
}
/* Check to make sure the unit isn't frozen */
if (u->freezer_state != FREEZER_RUNNING)
return -EDEADLK;
unit_add_to_dbus_queue(u);
if (!UNIT_VTABLE(u)->reload) {
/* Unit doesn't have a reload function, but we need to propagate the reload anyway */
unit_notify(u, unit_active_state(u), unit_active_state(u), /* reload_success= */ true);
return 0;
}
return UNIT_VTABLE(u)->reload(u);
}
bool unit_can_reload(Unit *u) {
assert(u);
if (UNIT_VTABLE(u)->can_reload)
return UNIT_VTABLE(u)->can_reload(u);
if (unit_has_dependency(u, UNIT_ATOM_PROPAGATES_RELOAD_TO, NULL))
return true;
return UNIT_VTABLE(u)->reload;
}
bool unit_is_unneeded(Unit *u) {
Unit *other;
assert(u);
if (!u->stop_when_unneeded)
return false;
/* Don't clean up while the unit is transitioning or is even inactive. */
if (unit_active_state(u) != UNIT_ACTIVE)
return false;
if (u->job)
return false;
UNIT_FOREACH_DEPENDENCY(other, u, UNIT_ATOM_PINS_STOP_WHEN_UNNEEDED) {
/* If a dependent unit has a job queued, is active or transitioning, or is marked for
* restart, then don't clean this one up. */
if (other->job)
return false;
if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other)))
return false;
if (unit_will_restart(other))
return false;
}
return true;
}
bool unit_is_upheld_by_active(Unit *u, Unit **ret_culprit) {
Unit *other;
assert(u);
/* Checks if the unit needs to be started because it currently is not running, but some other unit
* that is active declared an Uphold= dependencies on it */
if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(u)) || u->job) {
if (ret_culprit)
*ret_culprit = NULL;
return false;
}
UNIT_FOREACH_DEPENDENCY(other, u, UNIT_ATOM_START_STEADILY) {
if (other->job)
continue;
if (UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(other))) {
if (ret_culprit)
*ret_culprit = other;
return true;
}
}
if (ret_culprit)
*ret_culprit = NULL;
return false;
}
bool unit_is_bound_by_inactive(Unit *u, Unit **ret_culprit) {
Unit *other;
assert(u);
/* Checks whether this unit is bound to another unit that is inactive, i.e. whether we should stop
* because the other unit is down. */
if (unit_active_state(u) != UNIT_ACTIVE || u->job) {
/* Don't clean up while the unit is transitioning or is even inactive. */
if (ret_culprit)
*ret_culprit = NULL;
return false;
}
UNIT_FOREACH_DEPENDENCY(other, u, UNIT_ATOM_CANNOT_BE_ACTIVE_WITHOUT) {
if (other->job)
continue;
if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other))) {
if (ret_culprit)
*ret_culprit = other;
return true;
}
}
if (ret_culprit)
*ret_culprit = NULL;
return false;
}
static void check_unneeded_dependencies(Unit *u) {
Unit *other;
assert(u);
/* Add all units this unit depends on to the queue that processes StopWhenUnneeded= behaviour. */
UNIT_FOREACH_DEPENDENCY(other, u, UNIT_ATOM_ADD_STOP_WHEN_UNNEEDED_QUEUE)
unit_submit_to_stop_when_unneeded_queue(other);
}
static void check_uphold_dependencies(Unit *u) {
Unit *other;
assert(u);
/* Add all units this unit depends on to the queue that processes Uphold= behaviour. */
UNIT_FOREACH_DEPENDENCY(other, u, UNIT_ATOM_ADD_START_WHEN_UPHELD_QUEUE)
unit_submit_to_start_when_upheld_queue(other);
}
static void check_bound_by_dependencies(Unit *u) {
Unit *other;
assert(u);
/* Add all units this unit depends on to the queue that processes BindsTo= stop behaviour. */
UNIT_FOREACH_DEPENDENCY(other, u, UNIT_ATOM_ADD_CANNOT_BE_ACTIVE_WITHOUT_QUEUE)
unit_submit_to_stop_when_bound_queue(other);
}
static void retroactively_start_dependencies(Unit *u) {
Unit *other;
assert(u);
assert(UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)));
UNIT_FOREACH_DEPENDENCY_SAFE(other, u, UNIT_ATOM_RETROACTIVE_START_REPLACE) /* Requires= + BindsTo= */
if (!unit_has_dependency(u, UNIT_ATOM_AFTER, other) &&
!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
(void) manager_add_job(u->manager, JOB_START, other, JOB_REPLACE, /* reterr_error= */ NULL, /* ret= */ NULL);
UNIT_FOREACH_DEPENDENCY_SAFE(other, u, UNIT_ATOM_RETROACTIVE_START_FAIL) /* Wants= */
if (!unit_has_dependency(u, UNIT_ATOM_AFTER, other) &&
!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
(void) manager_add_job(u->manager, JOB_START, other, JOB_FAIL, /* reterr_error= */ NULL, /* ret= */ NULL);
UNIT_FOREACH_DEPENDENCY_SAFE(other, u, UNIT_ATOM_RETROACTIVE_STOP_ON_START) /* Conflicts= (and inverse) */
if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
(void) manager_add_job(u->manager, JOB_STOP, other, JOB_REPLACE, /* reterr_error= */ NULL, /* ret= */ NULL);
}
static void retroactively_stop_dependencies(Unit *u) {
Unit *other;
assert(u);
assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)));
/* Pull down units which are bound to us recursively if enabled */
UNIT_FOREACH_DEPENDENCY_SAFE(other, u, UNIT_ATOM_RETROACTIVE_STOP_ON_STOP) /* BoundBy= */
if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
(void) manager_add_job(u->manager, JOB_STOP, other, JOB_REPLACE, /* reterr_error= */ NULL, /* ret= */ NULL);
}
void unit_start_on_termination_deps(Unit *u, UnitDependencyAtom atom) {
const char *dependency_name = NULL;
JobMode job_mode = _JOB_MODE_INVALID;
unsigned n_jobs = 0;
int r;
/* Act on OnFailure= and OnSuccess= dependencies */
assert(u);
assert(u->manager);
assert(IN_SET(atom, UNIT_ATOM_ON_SUCCESS, UNIT_ATOM_ON_FAILURE));
FOREACH_ELEMENT(setting, on_termination_settings)
if (atom == setting->atom) {
job_mode = *(JobMode*) ((uint8_t*) u + setting->job_mode_offset);
dependency_name = setting->dependency_name;
break;
}
assert(dependency_name);
Unit *other;
UNIT_FOREACH_DEPENDENCY_SAFE(other, u, atom) {
_cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
if (n_jobs == 0)
log_unit_info(u, "Triggering %s dependencies.", dependency_name);
r = manager_add_job(u->manager, JOB_START, other, job_mode, &error, /* ret= */ NULL);
if (r < 0)
log_unit_warning_errno(u, r, "Failed to enqueue %s%s job, ignoring: %s",
dependency_name, other->id, bus_error_message(&error, r));
n_jobs++;
}
if (n_jobs > 0)
log_unit_debug(u, "Triggering %s dependencies done (%u %s).",
dependency_name, n_jobs, n_jobs == 1 ? "job" : "jobs");
}
void unit_trigger_notify(Unit *u) {
Unit *other;
assert(u);
UNIT_FOREACH_DEPENDENCY_SAFE(other, u, UNIT_ATOM_TRIGGERED_BY)
if (UNIT_VTABLE(other)->trigger_notify)
UNIT_VTABLE(other)->trigger_notify(other, u);
}
static int raise_level(int log_level, bool condition_info, bool condition_notice) {
if (condition_notice && log_level > LOG_NOTICE)
return LOG_NOTICE;
if (condition_info && log_level > LOG_INFO)
return LOG_INFO;
return log_level;
}
static int unit_log_resources(Unit *u) {
static const struct {
const char *journal_field;
const char *message_suffix;
} memory_fields[_CGROUP_MEMORY_ACCOUNTING_METRIC_CACHED_LAST + 1] = {
[CGROUP_MEMORY_PEAK] = { "MEMORY_PEAK", "memory peak" },
[CGROUP_MEMORY_SWAP_PEAK] = { "MEMORY_SWAP_PEAK", "memory swap peak" },
}, ip_fields[_CGROUP_IP_ACCOUNTING_METRIC_MAX] = {
[CGROUP_IP_INGRESS_BYTES] = { "IP_METRIC_INGRESS_BYTES", "incoming IP traffic" },
[CGROUP_IP_EGRESS_BYTES] = { "IP_METRIC_EGRESS_BYTES", "outgoing IP traffic" },
[CGROUP_IP_INGRESS_PACKETS] = { "IP_METRIC_INGRESS_PACKETS", NULL },
[CGROUP_IP_EGRESS_PACKETS] = { "IP_METRIC_EGRESS_PACKETS", NULL },
}, io_fields[_CGROUP_IO_ACCOUNTING_METRIC_MAX] = {
[CGROUP_IO_READ_BYTES] = { "IO_METRIC_READ_BYTES", "read from disk" },
[CGROUP_IO_WRITE_BYTES] = { "IO_METRIC_WRITE_BYTES", "written to disk" },
[CGROUP_IO_READ_OPERATIONS] = { "IO_METRIC_READ_OPERATIONS", NULL },
[CGROUP_IO_WRITE_OPERATIONS] = { "IO_METRIC_WRITE_OPERATIONS", NULL },
};
struct iovec *iovec = NULL;
size_t n_iovec = 0;
_cleanup_free_ char *message = NULL, *t = NULL;
nsec_t cpu_nsec = NSEC_INFINITY;
int log_level = LOG_DEBUG; /* May be raised if resources consumed over a threshold */
assert(u);
CLEANUP_ARRAY(iovec, n_iovec, iovec_array_free);
iovec = new(struct iovec, 1 + (_CGROUP_MEMORY_ACCOUNTING_METRIC_CACHED_LAST + 1) +
_CGROUP_IP_ACCOUNTING_METRIC_MAX + _CGROUP_IO_ACCOUNTING_METRIC_MAX + 4);
if (!iovec)
return log_oom();
/* Invoked whenever a unit enters failed or dead state. Logs information about consumed resources if resource
* accounting was enabled for a unit. It does this in two ways: a friendly human-readable string with reduced
* information and the complete data in structured fields. */
(void) unit_get_cpu_usage(u, &cpu_nsec);
if (cpu_nsec != NSEC_INFINITY) {
/* Format the CPU time for inclusion in the structured log message */
if (asprintf(&t, "CPU_USAGE_NSEC=%" PRIu64, cpu_nsec) < 0)
return log_oom();
iovec[n_iovec++] = IOVEC_MAKE_STRING(TAKE_PTR(t));
/* Format the CPU time for inclusion in the human language message string */
if (dual_timestamp_is_set(&u->inactive_exit_timestamp) &&
dual_timestamp_is_set(&u->inactive_enter_timestamp)) {
usec_t wall_clock_usec = usec_sub_unsigned(u->inactive_enter_timestamp.monotonic, u->inactive_exit_timestamp.monotonic);
if (strextendf_with_separator(&message, ", ",
"Consumed %s CPU time over %s wall clock time",
FORMAT_TIMESPAN(cpu_nsec / NSEC_PER_USEC, USEC_PER_MSEC),
FORMAT_TIMESPAN(wall_clock_usec, USEC_PER_MSEC)) < 0)
return log_oom();
} else {
if (strextendf_with_separator(&message, ", ",
"Consumed %s CPU time",
FORMAT_TIMESPAN(cpu_nsec / NSEC_PER_USEC, USEC_PER_MSEC)) < 0)
return log_oom();
}
log_level = raise_level(log_level,
cpu_nsec > MENTIONWORTHY_CPU_NSEC,
cpu_nsec > NOTICEWORTHY_CPU_NSEC);
}
for (CGroupMemoryAccountingMetric metric = 0; metric <= _CGROUP_MEMORY_ACCOUNTING_METRIC_CACHED_LAST; metric++) {
uint64_t value = UINT64_MAX;
assert(memory_fields[metric].journal_field);
assert(memory_fields[metric].message_suffix);
(void) unit_get_memory_accounting(u, metric, &value);
if (value == UINT64_MAX)
continue;
if (asprintf(&t, "%s=%" PRIu64, memory_fields[metric].journal_field, value) < 0)
return log_oom();
iovec[n_iovec++] = IOVEC_MAKE_STRING(TAKE_PTR(t));
/* If value is 0, we don't log it in the MESSAGE= field. */
if (value == 0)
continue;
if (strextendf_with_separator(&message, ", ", "%s %s",
FORMAT_BYTES(value), memory_fields[metric].message_suffix) < 0)
return log_oom();
log_level = raise_level(log_level,
value > MENTIONWORTHY_MEMORY_BYTES,
value > NOTICEWORTHY_MEMORY_BYTES);
}
for (CGroupIOAccountingMetric k = 0; k < _CGROUP_IO_ACCOUNTING_METRIC_MAX; k++) {
uint64_t value = UINT64_MAX;
assert(io_fields[k].journal_field);
(void) unit_get_io_accounting(u, k, &value);
if (value == UINT64_MAX)
continue;
/* Format IO accounting data for inclusion in the structured log message */
if (asprintf(&t, "%s=%" PRIu64, io_fields[k].journal_field, value) < 0)
return log_oom();
iovec[n_iovec++] = IOVEC_MAKE_STRING(TAKE_PTR(t));
/* If value is 0, we don't log it in the MESSAGE= field. */
if (value == 0)
continue;
/* Format the IO accounting data for inclusion in the human language message string, but only
* for the bytes counters (and not for the operations counters) */
if (io_fields[k].message_suffix) {
if (strextendf_with_separator(&message, ", ", "%s %s",
FORMAT_BYTES(value), io_fields[k].message_suffix) < 0)
return log_oom();
log_level = raise_level(log_level,
value > MENTIONWORTHY_IO_BYTES,
value > NOTICEWORTHY_IO_BYTES);
}
}
for (CGroupIPAccountingMetric m = 0; m < _CGROUP_IP_ACCOUNTING_METRIC_MAX; m++) {
uint64_t value = UINT64_MAX;
assert(ip_fields[m].journal_field);
(void) unit_get_ip_accounting(u, m, &value);
if (value == UINT64_MAX)
continue;
/* Format IP accounting data for inclusion in the structured log message */
if (asprintf(&t, "%s=%" PRIu64, ip_fields[m].journal_field, value) < 0)
return log_oom();
iovec[n_iovec++] = IOVEC_MAKE_STRING(TAKE_PTR(t));
/* If value is 0, we don't log it in the MESSAGE= field. */
if (value == 0)
continue;
/* Format the IP accounting data for inclusion in the human language message string, but only
* for the bytes counters (and not for the packets counters) */
if (ip_fields[m].message_suffix) {
if (strextendf_with_separator(&message, ", ", "%s %s",
FORMAT_BYTES(value), ip_fields[m].message_suffix) < 0)
return log_oom();
log_level = raise_level(log_level,
value > MENTIONWORTHY_IP_BYTES,
value > NOTICEWORTHY_IP_BYTES);
}
}
/* This check is here because it is the earliest point following all possible log_level assignments.
* (If log_level is assigned anywhere after this point, move this check.) */
if (!unit_log_level_test(u, log_level))
return 0;
/* Is there any accounting data available at all? */
if (n_iovec == 0) {
assert(!message);
return 0;
}
t = strjoin("MESSAGE=", u->id, ": ", message ?: "Completed", ".");
if (!t)
return log_oom();
iovec[n_iovec++] = IOVEC_MAKE_STRING(TAKE_PTR(t));
if (!set_iovec_string_field(iovec, &n_iovec, "MESSAGE_ID=", SD_MESSAGE_UNIT_RESOURCES_STR))
return log_oom();
if (!set_iovec_string_field(iovec, &n_iovec, unit_log_field(u), u->id))
return log_oom();
if (!set_iovec_string_field(iovec, &n_iovec, unit_invocation_log_field(u), u->invocation_id_string))
return log_oom();
log_unit_struct_iovec(u, log_level, iovec, n_iovec);
return 0;
}
static void unit_update_on_console(Unit *u) {
bool b;
assert(u);
b = unit_needs_console(u);
if (u->on_console == b)
return;
u->on_console = b;
if (b)
manager_ref_console(u->manager);
else
manager_unref_console(u->manager);
}
static void unit_emit_audit_start(Unit *u) {
assert(u);
if (UNIT_VTABLE(u)->audit_start_message_type <= 0)
return;
/* Write audit record if we have just finished starting up */
manager_send_unit_audit(u->manager, u, UNIT_VTABLE(u)->audit_start_message_type, /* success= */ true);
u->in_audit = true;
}
static void unit_emit_audit_stop(Unit *u, UnitActiveState state) {
assert(u);
if (UNIT_VTABLE(u)->audit_start_message_type <= 0)
return;
if (u->in_audit) {
/* Write audit record if we have just finished shutting down */
manager_send_unit_audit(u->manager, u, UNIT_VTABLE(u)->audit_stop_message_type, /* success= */ state == UNIT_INACTIVE);
u->in_audit = false;
} else {
/* Hmm, if there was no start record written write it now, so that we always have a nice pair */
manager_send_unit_audit(u->manager, u, UNIT_VTABLE(u)->audit_start_message_type, /* success= */ state == UNIT_INACTIVE);
if (state == UNIT_INACTIVE)
manager_send_unit_audit(u->manager, u, UNIT_VTABLE(u)->audit_stop_message_type, /* success= */ true);
}
}
static bool unit_process_job(Job *j, UnitActiveState ns, bool reload_success) {
bool unexpected = false;
assert(j);
assert(j->installed);
if (j->state == JOB_WAITING)
/* So we reached a different state for this job. Let's see if we can run it now if it failed previously
* due to EAGAIN. */
job_add_to_run_queue(j);
/* Let's check whether the unit's new state constitutes a finished job, or maybe contradicts a running job and
* hence needs to invalidate jobs. */
switch (j->type) {
case JOB_START:
case JOB_VERIFY_ACTIVE:
if (UNIT_IS_ACTIVE_OR_RELOADING(ns))
job_finish_and_invalidate(j, JOB_DONE, /* recursive= */ true, /* already= */ false);
else if (j->state == JOB_RUNNING && ns != UNIT_ACTIVATING) {
unexpected = true;
if (UNIT_IS_INACTIVE_OR_FAILED(ns))
job_finish_and_invalidate(j, ns == UNIT_FAILED ? JOB_FAILED : JOB_DONE, /* recursive= */ true, /* already= */ false);
}
break;
case JOB_RELOAD:
if (j->state == JOB_RUNNING) {
if (ns == UNIT_ACTIVE)
job_finish_and_invalidate(j, reload_success ? JOB_DONE : JOB_FAILED, /* recursive= */ true, /* already= */ false);
else if (!IN_SET(ns, UNIT_ACTIVATING, UNIT_RELOADING, UNIT_REFRESHING)) {
unexpected = true;
job_finish_and_invalidate(j, reload_success ? JOB_CANCELED : JOB_FAILED, /* recursive= */ true, /* already= */ false);
}
}
break;
case JOB_STOP:
case JOB_RESTART:
if (UNIT_IS_INACTIVE_OR_FAILED(ns))
job_finish_and_invalidate(j, JOB_DONE, /* recursive= */ true, /* already= */ false);
else if (j->state == JOB_RUNNING && ns != UNIT_DEACTIVATING) {
unexpected = true;
job_finish_and_invalidate(j, JOB_FAILED, /* recursive= */ true, /* already= */ false);
}
break;
default:
assert_not_reached();
}
return unexpected;
}
static void unit_recursive_add_to_run_queue(Unit *u) {
assert(u);
if (u->job)
job_add_to_run_queue(u->job);
Unit *child;
UNIT_FOREACH_DEPENDENCY(child, u, UNIT_ATOM_SLICE_OF) {
if (!child->job)
continue;
unit_recursive_add_to_run_queue(child);
}
}
static void unit_check_concurrency_limit(Unit *u) {
assert(u);
Unit *slice = UNIT_GET_SLICE(u);
if (!slice)
return;
/* If a unit was stopped, maybe it has pending siblings (or children thereof) that can be started now.
* Walk up the slice hierarchy and re-dispatch for each ancestor that has a limit configured. */
for (Unit *s = slice; s; s = UNIT_GET_SLICE(s)) {
if (SLICE(s)->concurrency_soft_max != UINT_MAX ||
SLICE(s)->activating_concurrency_max != UINT_MAX) {
Unit *member;
UNIT_FOREACH_DEPENDENCY(member, s, UNIT_ATOM_SLICE_OF) {
if (member == u)
continue;
unit_recursive_add_to_run_queue(member);
}
}
}
}
void unit_notify(Unit *u, UnitActiveState os, UnitActiveState ns, bool reload_success) {
assert(u);
assert(os < _UNIT_ACTIVE_STATE_MAX);
assert(ns < _UNIT_ACTIVE_STATE_MAX);
/* Note that this is called for all low-level state changes, even if they might map to the same high-level
* UnitActiveState! That means that ns == os is an expected behavior here. For example: if a mount point is
* remounted this function will be called too! */
Manager *m = ASSERT_PTR(u->manager);
/* Let's enqueue the change signal early. In case this unit has a job associated we want that this unit is in
* the bus queue, so that any job change signal queued will force out the unit change signal first. */
unit_add_to_dbus_queue(u);
/* Update systemd-oomd on the property/state change.
*
* Always send an update if the unit is going into an inactive state so systemd-oomd knows to
* stop monitoring.
* Also send an update whenever the unit goes active; this is to handle a case where an override file
* sets one of the ManagedOOM*= properties to "kill", then later removes it. systemd-oomd needs to
* know to stop monitoring when the unit changes from "kill" -> "auto" on daemon-reload, but we don't
* have the information on the property. Thus, indiscriminately send an update. */
if (os != ns && (UNIT_IS_INACTIVE_OR_FAILED(ns) || UNIT_IS_ACTIVE_OR_RELOADING(ns)))
(void) manager_varlink_send_managed_oom_update(u);
/* Update timestamps for state changes */
if (!MANAGER_IS_RELOADING(m)) {
dual_timestamp_now(&u->state_change_timestamp);
if (UNIT_IS_INACTIVE_OR_FAILED(os) && !UNIT_IS_INACTIVE_OR_FAILED(ns))
u->inactive_exit_timestamp = u->state_change_timestamp;
else if (!UNIT_IS_INACTIVE_OR_FAILED(os) && UNIT_IS_INACTIVE_OR_FAILED(ns))
u->inactive_enter_timestamp = u->state_change_timestamp;
if (!UNIT_IS_ACTIVE_OR_RELOADING(os) && UNIT_IS_ACTIVE_OR_RELOADING(ns))
u->active_enter_timestamp = u->state_change_timestamp;
else if (UNIT_IS_ACTIVE_OR_RELOADING(os) && !UNIT_IS_ACTIVE_OR_RELOADING(ns))
u->active_exit_timestamp = u->state_change_timestamp;
}
/* Keep track of failed units */
(void) manager_update_failed_units(m, u, ns == UNIT_FAILED);
/* Make sure the cgroup and state files are always removed when we become inactive */
if (UNIT_IS_INACTIVE_OR_FAILED(ns)) {
SET_FLAG(u->markers,
(1u << UNIT_MARKER_NEEDS_RELOAD)|(1u << UNIT_MARKER_NEEDS_RESTART)|(1u << UNIT_MARKER_NEEDS_STOP),
false);
unit_prune_cgroup(u);
unit_unlink_state_files(u);
} else if (UNIT_IS_ACTIVE_OR_ACTIVATING(ns))
SET_FLAG(u->markers, 1u << UNIT_MARKER_NEEDS_START, false);
else if (ns != os && ns == UNIT_RELOADING)
SET_FLAG(u->markers, 1u << UNIT_MARKER_NEEDS_RELOAD, false);
unit_update_on_console(u);
if (!MANAGER_IS_RELOADING(m)) {
bool unexpected;
/* Let's propagate state changes to the job */
if (u->job)
unexpected = unit_process_job(u->job, ns, reload_success);
else
unexpected = true;
/* If this state change happened without being requested by a job, then let's retroactively start or
* stop dependencies. We skip that step when deserializing, since we don't want to create any
* additional jobs just because something is already activated. */
if (unexpected) {
if (UNIT_IS_INACTIVE_OR_FAILED(os) && UNIT_IS_ACTIVE_OR_ACTIVATING(ns))
retroactively_start_dependencies(u);
else if (UNIT_IS_ACTIVE_OR_ACTIVATING(os) && UNIT_IS_INACTIVE_OR_DEACTIVATING(ns))
retroactively_stop_dependencies(u);
}
if (UNIT_IS_ACTIVE_OR_RELOADING(ns) && !UNIT_IS_ACTIVE_OR_RELOADING(os)) {
/* This unit just finished starting up */
unit_emit_audit_start(u);
manager_send_unit_plymouth(m, u);
manager_send_unit_supervisor(m, u, /* active= */ true);
} else if (UNIT_IS_INACTIVE_OR_FAILED(ns) && !UNIT_IS_INACTIVE_OR_FAILED(os)) {
/* This unit just stopped/failed. */
unit_emit_audit_stop(u, ns);
manager_send_unit_supervisor(m, u, /* active= */ false);
unit_log_resources(u);
}
if (ns == UNIT_INACTIVE && !IN_SET(os, UNIT_FAILED, UNIT_INACTIVE, UNIT_MAINTENANCE))
unit_start_on_termination_deps(u, UNIT_ATOM_ON_SUCCESS);
else if (ns != os && ns == UNIT_FAILED)
unit_start_on_termination_deps(u, UNIT_ATOM_ON_FAILURE);
}
manager_recheck_journal(m);
manager_recheck_dbus(m);
unit_trigger_notify(u);
if (!MANAGER_IS_RELOADING(m)) {
const char *reason;
if (os != UNIT_FAILED && ns == UNIT_FAILED) {
reason = strjoina("unit ", u->id, " failed");
emergency_action(m, u->failure_action, EMERGENCY_ACTION_WARN|EMERGENCY_ACTION_SLEEP_5S|EMERGENCY_ACTION_IS_FAILURE, u->reboot_arg, unit_failure_action_exit_status(u), reason);
} else if (!UNIT_IS_INACTIVE_OR_FAILED(os) && ns == UNIT_INACTIVE) {
reason = strjoina("unit ", u->id, " succeeded");
emergency_action(m, u->success_action, /* flags= */ 0, u->reboot_arg, unit_success_action_exit_status(u), reason);
}
}
/* And now, add the unit or depending units to various queues that will act on the new situation if
* needed. These queues generally check for continuous state changes rather than events (like most of
* the state propagation above), and do work deferred instead of instantly, since they typically
* don't want to run during reloading, and usually involve checking combined state of multiple units
* at once. */
if (UNIT_IS_INACTIVE_OR_FAILED(ns)) {
/* Stop unneeded units and bound-by units regardless if going down was expected or not */
check_unneeded_dependencies(u);
check_bound_by_dependencies(u);
/* Maybe someone wants us to remain up? */
unit_submit_to_start_when_upheld_queue(u);
/* Maybe the unit should be GC'ed now? */
unit_add_to_gc_queue(u);
/* Maybe we can release some resources now? */
unit_submit_to_release_resources_queue(u);
/* Maybe the concurrency limits now allow dispatching of another start job in this slice? */
unit_check_concurrency_limit(u);
/* Maybe someone else has been waiting for us to stop? */
m->may_dispatch_stop_notify_queue = true;
} else if (UNIT_IS_ACTIVE_OR_RELOADING(ns)) {
/* Start uphold units regardless if going up was expected or not */
check_uphold_dependencies(u);
/* Maybe we finished startup and are now ready for being stopped because unneeded? */
unit_submit_to_stop_when_unneeded_queue(u);
/* Maybe we finished startup, but something we needed has vanished? Let's die then. (This happens
* when something BindsTo= to a Type=oneshot unit, as these units go directly from starting to
* inactive, without ever entering started.) */
unit_submit_to_stop_when_bound_queue(u);
/* Maybe the activating concurrency limits now allow dispatching of another start job in this slice? */
unit_check_concurrency_limit(u);
}
/* When a unit leaves the activating state (to deactivating, inactive, or active), it frees up a slot for
* ActivatingConcurrencyMax. Re-dispatch queued starts. */
if (os == UNIT_ACTIVATING && ns != UNIT_ACTIVATING)
unit_check_concurrency_limit(u);
}
int unit_watch_pidref(Unit *u, const PidRef *pid, bool exclusive) {
_cleanup_(pidref_freep) PidRef *pid_dup = NULL;
int r;
/* Adds a specific PID to the set of PIDs this unit watches. */
assert(u);
assert(pidref_is_set(pid));
/* Caller might be sure that this PID belongs to this unit only. Let's take this
* opportunity to remove any stalled references to this PID as they can be created
* easily (when watching a process which is not our direct child). */
if (exclusive)
manager_unwatch_pidref(u->manager, pid);
if (set_contains(u->pids, pid)) { /* early exit if already being watched */
assert(!exclusive);
return 0;
}
r = pidref_dup(pid, &pid_dup);
if (r < 0)
return r;
/* First, insert into the set of PIDs maintained by the unit */
r = set_ensure_put(&u->pids, &pidref_hash_ops_free, pid_dup);
if (r < 0)
return r;
pid = TAKE_PTR(pid_dup); /* continue with our copy now that we have installed it properly in our set */
/* Second, insert it into the simple global table, see if that works */
r = hashmap_ensure_put(&u->manager->watch_pids, &pidref_hash_ops, pid, u);
if (r != -EEXIST)
return r;
/* OK, the key is already assigned to a different unit. That's fine, then add us via the second
* hashmap that points to an array. */
PidRef *old_pid = NULL;
Unit **array = hashmap_get2(u->manager->watch_pids_more, pid, (void**) &old_pid);
/* Count entries in array */
size_t n = 0;
for (; array && array[n]; n++)
;
/* Allocate a new array */
_cleanup_free_ Unit **new_array = new(Unit*, n + 2);
if (!new_array)
return -ENOMEM;
/* Append us to the end */
memcpy_safe(new_array, array, sizeof(Unit*) * n);
new_array[n] = u;
new_array[n+1] = NULL;
/* Add or replace the old array */
r = hashmap_ensure_replace(&u->manager->watch_pids_more, &pidref_hash_ops, old_pid ?: pid, new_array);
if (r < 0)
return r;
TAKE_PTR(new_array); /* Now part of the hash table */
free(array); /* Which means we can now delete the old version */
return 0;
}
void unit_unwatch_pidref(Unit *u, const PidRef *pid) {
assert(u);
assert(pidref_is_set(pid));
/* Remove from the set we maintain for this unit. (And destroy the returned pid eventually) */
_cleanup_(pidref_freep) PidRef *pid1 = set_remove(u->pids, pid);
if (!pid1)
return; /* Early exit if this PID was never watched by us */
/* First let's drop the unit from the simple hash table, if it is included there */
PidRef *pid2 = NULL;
Unit *uu = hashmap_get2(u->manager->watch_pids, pid, (void**) &pid2);
/* Quick validation: iff we are in the watch_pids table then the PidRef object must be the same as in our local pids set */
assert((uu == u) == (pid1 == pid2));
if (uu == u)
/* OK, we are in the first table. Let's remove it there then, and we are done already. */
assert_se(hashmap_remove_value(u->manager->watch_pids, pid2, uu));
else {
/* We weren't in the first table, then let's consult the 2nd table that points to an array */
PidRef *pid3 = NULL;
Unit **array = hashmap_get2(u->manager->watch_pids_more, pid, (void**) &pid3);
/* Let's iterate through the array, dropping our own entry */
size_t m = 0, n = 0;
for (; array && array[n]; n++)
if (array[n] != u)
array[m++] = array[n];
if (n == m)
return; /* Not there */