HALF ECHO LEARN / REFERENCE COLLECTION
v262.2src/core/job.c
Git blob: 70e14b517f7349dcc2d04bde5cc0adb1209b29d1
Lines 1001–1757 of 1,757
UNIT_FOREACH_DEPENDENCY(other, u, match_atom) {
Job *j = other->job;
if (!j)
continue;
if (!IN_SET(j->type, JOB_START, JOB_VERIFY_ACTIVE))
continue;
job_finish_and_invalidate(j, JOB_DEPENDENCY, true, false);
}
}
int job_finish_and_invalidate(Job *j, JobResult result, bool recursive, bool already) {
Unit *u, *other;
JobType t;
assert(j);
assert(j->installed);
assert(j->type < _JOB_TYPE_MAX_IN_TRANSACTION);
u = j->unit;
t = j->type;
j->result = result;
job_set_state(j, JOB_FINISHED);
log_unit_debug(u, "Job %" PRIu32 " %s/%s finished, result=%s",
j->id, u->id, job_type_to_string(t), job_result_to_string(result));
/* If this job did nothing to the respective unit we don't log the status message */
if (!already)
job_emit_done_message(u, j->id, t, result);
/* Patch restart jobs so that they become normal start jobs */
if (result == JOB_DONE && t == JOB_RESTART) {
job_change_type(j, JOB_START);
job_set_state(j, JOB_WAITING);
job_add_to_dbus_queue(j);
job_add_to_run_queue(j);
job_add_to_gc_queue(j);
goto finish;
}
if (IN_SET(result, JOB_FAILED, JOB_INVALID, JOB_FROZEN, JOB_CONCURRENCY))
j->manager->n_failed_jobs++;
job_uninstall(j);
job_free(j);
/* Fail depending jobs on failure */
if (result != JOB_DONE && recursive) {
if (IN_SET(t, JOB_START, JOB_VERIFY_ACTIVE))
job_fail_dependencies(u, UNIT_ATOM_PROPAGATE_START_FAILURE);
else if (t == JOB_STOP)
job_fail_dependencies(u, UNIT_ATOM_PROPAGATE_STOP_FAILURE);
}
/* A special check to make sure we take down anything RequisiteOf= if we aren't active. This is when
* the verify-active job merges with a satisfying job type, and then loses its invalidation effect,
* as the result there is JOB_DONE for the start job we merged into, while we should be failing the
* depending job if the said unit isn't in fact active. Oneshots are an example of this, where going
* directly from activating to inactive is success.
*
* This happens when you use ConditionXYZ= in a unit too, since in that case the job completes with
* the JOB_DONE result, but the unit never really becomes active. Note that such a case still
* involves merging:
*
* A start job waits for something else, and a verify-active comes in and merges in the installed
* job. Then, later, when it becomes runnable, it finishes with JOB_DONE result as execution on
* conditions not being met is skipped, breaking our dependency semantics.
*
* Also, depending on if start job waits or not, the merging may or may not happen (the verify-active
* job may trigger after it finishes), so you get undeterministic results without this check.
*/
if (result == JOB_DONE && recursive &&
IN_SET(t, JOB_START, JOB_RELOAD) &&
!UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u)))
job_fail_dependencies(u, UNIT_ATOM_PROPAGATE_INACTIVE_START_AS_FAILURE);
/* Trigger OnFailure= dependencies manually here. We need to do that because a failed job might not
* cause a unit state change. Note that we don't treat JOB_CANCELED as failure in this context.
* And JOB_FAILURE is already handled by the unit itself (unit_notify). */
if (IN_SET(result, JOB_TIMEOUT, JOB_DEPENDENCY)) {
log_unit_struct(u, LOG_NOTICE,
LOG_ITEM("JOB_TYPE=%s", job_type_to_string(t)),
LOG_ITEM("JOB_RESULT=%s", job_result_to_string(result)),
LOG_UNIT_MESSAGE(u, "Job %s/%s failed with result '%s'.",
u->id,
job_type_to_string(t),
job_result_to_string(result)));
unit_start_on_termination_deps(u, UNIT_ATOM_ON_FAILURE);
}
unit_trigger_notify(u);
finish:
/* Try to start the next jobs that can be started */
UNIT_FOREACH_DEPENDENCY(other, u, UNIT_ATOM_AFTER)
if (other->job) {
job_add_to_run_queue(other->job);
job_add_to_gc_queue(other->job);
}
UNIT_FOREACH_DEPENDENCY(other, u, UNIT_ATOM_BEFORE)
if (other->job) {
job_add_to_run_queue(other->job);
job_add_to_gc_queue(other->job);
}
/* Ensure that when an upheld/unneeded/bound unit activation job fails we requeue it, if it still
* necessary. If there are no state changes in the triggerer, it would not be retried otherwise. */
unit_submit_to_start_when_upheld_queue(u);
unit_submit_to_stop_when_bound_queue(u);
unit_submit_to_stop_when_unneeded_queue(u);
/* All jobs might have finished, let's see */
if (u->manager->may_dispatch_stop_notify_queue == 0)
u->manager->may_dispatch_stop_notify_queue = -1;
manager_check_finished(u->manager);
return 0;
}
static int job_dispatch_timer(sd_event_source *s, uint64_t monotonic, void *userdata) {
Job *j = ASSERT_PTR(userdata);
Unit *u;
assert(s == j->timer_event_source);
log_unit_warning(j->unit, "Job %s/%s timed out.", j->unit->id, job_type_to_string(j->type));
u = j->unit;
job_finish_and_invalidate(j, JOB_TIMEOUT, true, false);
emergency_action(
u->manager,
u->job_timeout_action,
EMERGENCY_ACTION_IS_WATCHDOG|EMERGENCY_ACTION_WARN|EMERGENCY_ACTION_SLEEP_5S|EMERGENCY_ACTION_IS_FAILURE,
u->job_timeout_reboot_arg,
/* exit_status= */ -1,
"job timed out");
return 0;
}
int job_start_timer(Job *j, bool job_running) {
int r;
usec_t timeout_time, old_timeout_time;
if (job_running) {
j->begin_running_usec = now(CLOCK_MONOTONIC);
if (j->unit->job_running_timeout == USEC_INFINITY)
return 0;
timeout_time = usec_add(j->begin_running_usec, j->unit->job_running_timeout);
if (j->timer_event_source) {
/* Update only if JobRunningTimeoutSec= results in earlier timeout */
r = sd_event_source_get_time(j->timer_event_source, &old_timeout_time);
if (r < 0)
return r;
if (old_timeout_time <= timeout_time)
return 0;
return sd_event_source_set_time(j->timer_event_source, timeout_time);
}
} else {
if (j->timer_event_source)
return 0;
j->begin_usec = now(CLOCK_MONOTONIC);
if (j->unit->job_timeout == USEC_INFINITY)
return 0;
timeout_time = usec_add(j->begin_usec, j->unit->job_timeout);
}
r = sd_event_add_time(
j->manager->event,
&j->timer_event_source,
CLOCK_MONOTONIC,
timeout_time, 0,
job_dispatch_timer, j);
if (r < 0)
return r;
(void) sd_event_source_set_description(j->timer_event_source, "job-start");
return 0;
}
void job_add_to_run_queue(Job *j) {
int r;
assert(j);
assert(j->installed);
if (j->in_run_queue)
return;
r = prioq_put(j->manager->run_queue, j, &j->run_queue_idx);
if (r < 0)
log_warning_errno(r, "Failed to put job in run queue, ignoring: %m");
else
j->in_run_queue = true;
manager_trigger_run_queue(j->manager);
}
void job_add_to_dbus_queue(Job *j) {
assert(j);
assert(j->installed);
if (j->in_dbus_queue)
return;
/* We don't check if anybody is subscribed here, since this
* job might just have been created and not yet assigned to a
* connection/client. */
LIST_PREPEND(dbus_queue, j->manager->dbus_job_queue, j);
j->in_dbus_queue = true;
}
char* job_dbus_path(Job *j) {
char *p;
assert(j);
if (asprintf(&p, "/org/freedesktop/systemd1/job/%"PRIu32, j->id) < 0)
return NULL;
return p;
}
int job_serialize(Job *j, FILE *f) {
assert(j);
assert(f);
(void) serialize_item_format(f, "job-id", "%u", j->id);
(void) serialize_item(f, "job-type", job_type_to_string(j->type));
(void) serialize_item(f, "job-state", job_state_to_string(j->state));
(void) serialize_bool(f, "job-irreversible", j->irreversible);
(void) serialize_bool(f, "job-sent-dbus-new-signal", j->sent_dbus_new_signal);
(void) serialize_bool(f, "job-ignore-order", j->ignore_order);
if (j->begin_usec > 0)
(void) serialize_usec(f, "job-begin", j->begin_usec);
if (j->begin_running_usec > 0)
(void) serialize_usec(f, "job-begin-running", j->begin_running_usec);
bus_track_serialize(j->bus_track, f, "subscribed");
activation_details_serialize(j->activation_details, f);
/* End marker */
fputc('\n', f);
return 0;
}
int job_deserialize(Job *j, FILE *f) {
int r;
assert(j);
assert(f);
for (;;) {
_cleanup_free_ char *l = NULL;
size_t k;
const char *v;
r = deserialize_read_line(f, &l);
if (r < 0)
return r;
if (r == 0) /* eof or end marker */
break;
k = strcspn(l, "=");
if (l[k] == '=') {
l[k] = 0;
v = l+k+1;
} else
v = l+k;
if (streq(l, "job-id")) {
if (safe_atou32(v, &j->id) < 0)
log_debug("Failed to parse job id value: %s", v);
} else if (streq(l, "job-type")) {
JobType t;
t = job_type_from_string(v);
if (t < 0)
log_debug("Failed to parse job type: %s", v);
else if (t >= _JOB_TYPE_MAX_IN_TRANSACTION)
log_debug("Cannot deserialize job of type: %s", v);
else
j->type = t;
} else if (streq(l, "job-state")) {
JobState s;
s = job_state_from_string(v);
if (s < 0)
log_debug("Failed to parse job state: %s", v);
else
job_set_state(j, s);
} else if (streq(l, "job-irreversible")) {
int b;
b = parse_boolean(v);
if (b < 0)
log_debug("Failed to parse job irreversible flag: %s", v);
else
j->irreversible = j->irreversible || b;
} else if (streq(l, "job-sent-dbus-new-signal")) {
int b;
b = parse_boolean(v);
if (b < 0)
log_debug("Failed to parse job sent_dbus_new_signal flag: %s", v);
else
j->sent_dbus_new_signal = j->sent_dbus_new_signal || b;
} else if (streq(l, "job-ignore-order")) {
int b;
b = parse_boolean(v);
if (b < 0)
log_debug("Failed to parse job ignore_order flag: %s", v);
else
j->ignore_order = j->ignore_order || b;
} else if (streq(l, "job-begin"))
(void) deserialize_usec(v, &j->begin_usec);
else if (streq(l, "job-begin-running"))
(void) deserialize_usec(v, &j->begin_running_usec);
else if (streq(l, "subscribed")) {
if (strv_extend(&j->deserialized_clients, v) < 0)
return log_oom();
} else if (startswith(l, "activation-details")) {
if (activation_details_deserialize(l, v, &j->activation_details) < 0)
log_debug("Failed to parse job ActivationDetails element: %s", v);
} else
log_debug("Unknown job serialization key: %s", l);
}
return 0;
}
int job_coldplug(Job *j) {
int r;
usec_t timeout_time = USEC_INFINITY;
assert(j);
/* After deserialization is complete and the bus connection
* set up again, let's start watching our subscribers again */
(void) bus_job_coldplug_bus_track(j);
if (j->state == JOB_WAITING)
job_add_to_run_queue(j);
/* Maybe due to new dependencies we don't actually need this job anymore? */
job_add_to_gc_queue(j);
/* Create timer only when job began or began running and the respective timeout is finite.
* Follow logic of job_start_timer() if both timeouts are finite */
if (j->begin_usec == 0)
return 0;
if (j->unit->job_timeout != USEC_INFINITY)
timeout_time = usec_add(j->begin_usec, j->unit->job_timeout);
if (timestamp_is_set(j->begin_running_usec))
timeout_time = MIN(timeout_time, usec_add(j->begin_running_usec, j->unit->job_running_timeout));
if (timeout_time == USEC_INFINITY)
return 0;
j->timer_event_source = sd_event_source_disable_unref(j->timer_event_source);
r = sd_event_add_time(
j->manager->event,
&j->timer_event_source,
CLOCK_MONOTONIC,
timeout_time, 0,
job_dispatch_timer, j);
if (r < 0)
log_debug_errno(r, "Failed to restart timeout for job: %m");
(void) sd_event_source_set_description(j->timer_event_source, "job-timeout");
return r;
}
void job_shutdown_magic(Job *j) {
assert(j);
assert(j->manager);
/* The shutdown target gets some special treatment here: we
* tell the kernel to begin with flushing its disk caches, to
* optimize shutdown time a bit. Ideally we wouldn't hardcode
* this magic into PID 1. However all other processes aren't
* options either since they'd exit much sooner than PID 1 and
* asynchronous sync() would cause their exit to be
* delayed. */
if (j->type != JOB_START)
return;
if (!unit_has_name(j->unit, SPECIAL_SHUTDOWN_TARGET))
return;
/* This is the very beginning of the shutdown phase, so take the timestamp here */
dual_timestamp_now(j->manager->timestamps + MANAGER_TIMESTAMP_SHUTDOWN_START);
if (!MANAGER_IS_SYSTEM(j->manager))
return;
/* In case messages on console has been disabled on boot */
j->manager->no_console_output = false;
manager_invalidate_startup_units(j->manager);
if (detect_container() > 0)
return;
(void) asynchronous_sync(NULL);
}
int job_get_timeout(Job *j, usec_t *ret) {
usec_t x = USEC_INFINITY, y = USEC_INFINITY;
Unit *u = ASSERT_PTR(ASSERT_PTR(j)->unit);
int r;
assert(ret);
if (j->timer_event_source) {
r = sd_event_source_get_time(j->timer_event_source, &x);
if (r < 0)
return r;
}
if (UNIT_VTABLE(u)->get_timeout) {
r = UNIT_VTABLE(u)->get_timeout(u, &y);
if (r < 0)
return r;
}
if (x == USEC_INFINITY && y == USEC_INFINITY) {
*ret = 0;
return 0;
}
*ret = MIN(x, y);
return 1;
}
bool job_may_gc(Job *j) {
Unit *other;
assert(j);
assert(j->manager);
/* Checks whether this job should be GC'ed away. We only do this for jobs of units that have no effect on their
* own and just track external state. For now the only unit type that qualifies for this are .device units.
* Returns true if the job can be collected. */
if (!UNIT_VTABLE(j->unit)->gc_jobs)
return false;
/* Make sure to send out pending D-Bus events before we unload the unit */
if (j->in_dbus_queue)
return false;
if (sd_bus_track_count(j->bus_track) > 0)
return false;
/* FIXME: So this is a bit ugly: for now we don't properly track references made via private bus connections
* (because it's nasty, as sd_bus_track doesn't apply to it). We simply remember that the job was once
* referenced by one, and reset this whenever we notice that no private bus connections are around. This means
* the GC is a bit too conservative when it comes to jobs created by private bus connections. */
if (j->ref_by_private_bus) {
if (set_isempty(j->manager->private_buses))
j->ref_by_private_bus = false;
else
return false;
}
if (j->type == JOB_NOP)
return false;
/* The logic is inverse to job_is_runnable, we cannot GC as long as we block any job. */
UNIT_FOREACH_DEPENDENCY(other, j->unit, UNIT_ATOM_BEFORE)
if (other->job && job_compare(j, other->job, UNIT_ATOM_BEFORE) < 0)
return false;
UNIT_FOREACH_DEPENDENCY(other, j->unit, UNIT_ATOM_AFTER)
if (other->job && job_compare(j, other->job, UNIT_ATOM_AFTER) < 0)
return false;
return true;
}
void job_add_to_gc_queue(Job *j) {
assert(j);
assert(j->manager);
if (j->in_gc_queue)
return;
if (!job_may_gc(j))
return;
LIST_PREPEND(gc_queue, j->manager->gc_job_queue, j);
j->in_gc_queue = true;
}
static int job_compare_id(Job * const *a, Job * const *b) {
/* This is called from qsort()s inner loops. Correctly implemented qsort will never pass NULL so we
just suppress the check via POINTER_MAY_BE_NULL instead of assert() to avoid the runtime cost. */
POINTER_MAY_BE_NULL(a);
POINTER_MAY_BE_NULL(b);
return CMP((*a)->id, (*b)->id);
}
static size_t sort_job_list(Job **list, size_t n) {
Job *previous = NULL;
size_t a, b;
/* Order by numeric IDs */
typesafe_qsort(list, n, job_compare_id);
/* Filter out duplicates */
for (a = 0, b = 0; a < n; a++) {
if (previous == list[a])
continue;
previous = list[b++] = list[a];
}
return b;
}
int job_get_before(Job *j, Job*** ret) {
_cleanup_free_ Job** list = NULL;
Unit *other = NULL;
size_t n = 0;
/* Returns a list of all pending jobs that need to finish before this job may be started. */
assert(j);
assert(ret);
if (j->ignore_order) {
*ret = NULL;
return 0;
}
UNIT_FOREACH_DEPENDENCY(other, j->unit, UNIT_ATOM_AFTER) {
if (!other->job)
continue;
if (job_compare(j, other->job, UNIT_ATOM_AFTER) <= 0)
continue;
if (!GREEDY_REALLOC(list, n+1))
return -ENOMEM;
list[n++] = other->job;
}
UNIT_FOREACH_DEPENDENCY(other, j->unit, UNIT_ATOM_BEFORE) {
if (!other->job)
continue;
if (job_compare(j, other->job, UNIT_ATOM_BEFORE) <= 0)
continue;
if (!GREEDY_REALLOC(list, n+1))
return -ENOMEM;
list[n++] = other->job;
}
n = sort_job_list(list, n);
*ret = TAKE_PTR(list);
return (int) n;
}
int job_get_after(Job *j, Job*** ret) {
_cleanup_free_ Job** list = NULL;
Unit *other = NULL;
size_t n = 0;
assert(j);
assert(ret);
/* Returns a list of all pending jobs that are waiting for this job to finish. */
UNIT_FOREACH_DEPENDENCY(other, j->unit, UNIT_ATOM_BEFORE) {
if (!other->job)
continue;
if (other->job->ignore_order)
continue;
if (job_compare(j, other->job, UNIT_ATOM_BEFORE) >= 0)
continue;
if (!GREEDY_REALLOC(list, n+1))
return -ENOMEM;
list[n++] = other->job;
}
UNIT_FOREACH_DEPENDENCY(other, j->unit, UNIT_ATOM_AFTER) {
if (!other->job)
continue;
if (other->job->ignore_order)
continue;
if (job_compare(j, other->job, UNIT_ATOM_AFTER) >= 0)
continue;
if (!GREEDY_REALLOC(list, n+1))
return -ENOMEM;
list[n++] = other->job;
}
n = sort_job_list(list, n);
*ret = TAKE_PTR(list);
return (int) n;
}
static const char* const job_state_table[_JOB_STATE_MAX] = {
[JOB_WAITING] = "waiting",
[JOB_RUNNING] = "running",
[JOB_FINISHED] = "finished",
};
DEFINE_STRING_TABLE_LOOKUP(job_state, JobState);
static const char* const job_type_table[_JOB_TYPE_MAX] = {
[JOB_START] = "start",
[JOB_VERIFY_ACTIVE] = "verify-active",
[JOB_STOP] = "stop",
[JOB_RELOAD] = "reload",
[JOB_RELOAD_OR_START] = "reload-or-start",
[JOB_RESTART] = "restart",
[JOB_TRY_RESTART] = "try-restart",
[JOB_TRY_RELOAD] = "try-reload",
[JOB_NOP] = "nop",
};
DEFINE_STRING_TABLE_LOOKUP(job_type, JobType);
static const char* const job_result_table[_JOB_RESULT_MAX] = {
[JOB_DONE] = "done",
[JOB_CANCELED] = "canceled",
[JOB_TIMEOUT] = "timeout",
[JOB_FAILED] = "failed",
[JOB_DEPENDENCY] = "dependency",
[JOB_SKIPPED] = "skipped",
[JOB_INVALID] = "invalid",
[JOB_ASSERT] = "assert",
[JOB_UNSUPPORTED] = "unsupported",
[JOB_COLLECTED] = "collected",
[JOB_ONCE] = "once",
[JOB_FROZEN] = "frozen",
[JOB_CONCURRENCY] = "concurrency",
};
DEFINE_STRING_TABLE_LOOKUP(job_result, JobResult);
const char* job_type_to_access_method(JobType t) {
assert(t >= 0);
assert(t < _JOB_TYPE_MAX);
if (IN_SET(t, JOB_START, JOB_RESTART, JOB_TRY_RESTART))
return "start";
else if (t == JOB_STOP)
return "stop";
else
return "reload";
}
/*
* assume_dep assumed dependency between units (a is before/after b)
*
* Returns
* 0 jobs are independent,
* >0 a should run after b,
* <0 a should run before b,
*
* The logic means that for a service a and a service b where b.After=a:
*
* start a + start b → 1st step start a, 2nd step start b
* start a + stop b → 1st step stop b, 2nd step start a
* stop a + start b → 1st step stop a, 2nd step start b
* stop a + stop b → 1st step stop b, 2nd step stop a
*
* This has the side effect that restarts are properly synchronized too.
*/
int job_compare(Job *a, Job *b, UnitDependencyAtom assume_dep) {
assert(a);
assert(b);
assert(a->type < _JOB_TYPE_MAX_IN_TRANSACTION);
assert(b->type < _JOB_TYPE_MAX_IN_TRANSACTION);
assert(IN_SET(assume_dep, UNIT_ATOM_AFTER, UNIT_ATOM_BEFORE));
/* Trivial cases first */
if (a->type == JOB_NOP || b->type == JOB_NOP)
return 0;
if (a->ignore_order || b->ignore_order)
return 0;
if (assume_dep == UNIT_ATOM_AFTER)
return -job_compare(b, a, UNIT_ATOM_BEFORE);
/* Let's make it simple, JOB_STOP goes always first (in case both ua and ub stop, then ub's stop goes
* first anyway). JOB_RESTART is JOB_STOP in disguise (before it is patched to JOB_START). */
if (IN_SET(b->type, JOB_STOP, JOB_RESTART))
return 1;
else
return -1;
}
void job_set_activation_details(Job *j, ActivationDetails *info) {
/* Existing (older) ActivationDetails win, newer ones are discarded. */
if (!j || j->activation_details || !info)
return; /* Nothing to do. */
j->activation_details = activation_details_ref(info);
}