JoelEmmanuelCloud commented on code in PR #76410:
URL: https://github.com/apache/airflow/pull/76410#discussion_r4687807589
##########
airflow-core/src/airflow/api/common/airflow_health.py:
##########
@@ -170,6 +224,84 @@ def _dag_processor_detailed_status(jobs: list[Job]) ->
DetailedHealthStatus:
return _coverage_status(expected, covered)
+@lru_cache
+def _configured_executor_keys() -> set[str]:
+ """
+ Return the key each configured executor that implements a health check
would be recorded under.
+
+ Most executors don't override
:meth:`~airflow.executors.base_executor.BaseExecutor.get_health`,
+ so this deliberately excludes them rather than counting every configured
executor: an executor
+ that was never going to report anything isn't a gap in coverage, and a
deployment where nothing
+ implements a health check should see no ``executor`` block at all in
``/monitor/health``, not an
+ ``unhealthy`` one.
+
+ Also empty when ``executor_health_check_interval`` is 0: the scheduler
records no ``ExecutorJob``
+ rows in that case either, so nothing would ever cover an expected key and
``/monitor/health`` would
+ report the executor DOWN forever instead of omitting the block.
+
+ Cached: this calls
:meth:`~airflow.executors.executor_loader.ExecutorLoader.import_executor_cls`,
+ which imports every configured executor class, and the configured
executors can't change while the
+ process runs. Without caching, an API server would redo those imports --
and reproduce any import
+ failure's warning and traceback -- on every single call to
``/monitor/health``. Team validation is
+ skipped (``validate_teams=False``), the same as ``connections.py`` does,
so a database hiccup on
+ the first call can't get cached as "no executors".
+ """
+ try:
+ if conf.getfloat("scheduler", "executor_health_check_interval",
fallback=30.0) <= 0:
+ return set()
+ names = ExecutorLoader.get_executor_names(validate_teams=False)
+ except Exception:
+ # A health probe must not fail on malformed executor config; callers
fall back to liveness only.
+ log.warning("Could not read the executor configuration", exc_info=True)
+ return set()
+
+ keys = set()
+ for name in names:
+ try:
+ executor_cls, _ = ExecutorLoader.import_executor_cls(name)
+ except Exception:
+ log.warning("Could not import configured executor %s",
name.module_path, exc_info=True)
+ continue
+ if executor_cls.overrides_get_health():
+ keys.add(repr(name))
+ return keys
+
+
+def _executor_detailed_status(
+ jobs: list[Job], live_scheduler_ids: set[int] | None = None
+) -> DetailedHealthStatus:
+ """
+ Status from configured-executor coverage: each configured executor is its
own partition.
+
+ A shared executor backend (e.g. one Celery broker) can be reachable from
one scheduler and not
+ another, so coverage is decided per live, currently-owned row rather than
by any single row for
+ that executor key: one scheduler finding it down is real signal, not noise
an unrelated healthy
+ row should paper over.
+
+ ``live_scheduler_ids`` is forwarded to :func:`_live_executor_jobs`; see
its docstring.
+ """
+ expected = _configured_executor_keys()
+ if not expected:
+ return _liveness_status(jobs)
+
+ covered: set[str] = set()
+ unhealthy: set[str] = set()
+ seen: set[str] = set()
+ for job in _live_executor_jobs(jobs, live_scheduler_ids):
+ if not job.executor_class or job.executor_class not in expected:
+ continue
+ seen.add(job.executor_class)
+ if job.health_check_result == HealthCheckResult.HEALTHY:
+ covered.add(job.executor_class)
+ elif job.health_check_result == HealthCheckResult.UNHEALTHY:
+ unhealthy.add(job.executor_class)
+ expected = expected - (seen - covered - unhealthy)
+ if not expected:
+ return _liveness_status(jobs)
Review Comment:
fixed, both fallbacks now use the filtered live job list instead of the raw
one.
##########
airflow-core/src/airflow/api/common/airflow_health.py:
##########
@@ -272,4 +434,12 @@ def get_airflow_health() -> dict[str, Any]:
},
}
+ if report_executor_health:
+ airflow_health_status["executor"] = {
Review Comment:
added a section for it.
##########
airflow-core/src/airflow/api/common/airflow_health.py:
##########
@@ -120,6 +123,57 @@ def _dag_processor_instance_health(job: Job) -> dict[str,
Any]:
}
+@lru_cache
+def _configured_executor_names() -> dict[str, ExecutorName]:
+ """
+ Map every configured executor's health key to its ``ExecutorName``, for
display purposes.
+
+ Cached for the same reason :func:`_configured_executor_keys` is: the
configured executors can't
+ change while the process runs.
+ """
+ try:
+ return {repr(name): name for name in
ExecutorLoader.get_executor_names(validate_teams=False)}
+ except Exception:
+ # A health probe must not fail on malformed executor config; the row's
own key is still shown.
+ log.warning("Could not read the executor configuration", exc_info=True)
+ return {}
+
+
+def _executor_instance_health(job: Job) -> dict[str, Any]:
+ # job.executor_class is the internal identity key (e.g.
":CeleryExecutor:"), not the name the user
+ # configured. Reporting the alias or module path they wrote in [core]
executor instead is a better
+ # user experience; the key itself is only shown as a fallback, e.g. for a
since-reconfigured executor.
+ name = _configured_executor_names().get(job.executor_class) if
job.executor_class else None
+ return {
+ **_job_instance_health(job, "latest_executor_heartbeat"),
+ "executor": (name.alias or name.module_path) if name else
job.executor_class,
+ "team_names": job.team_names,
+ "health_check_result": job.health_check_result,
+ }
+
+
+def _live_scheduler_job_ids() -> set[int]:
Review Comment:
done, removed _live_scheduler_job_ids and made the parameter required.
##########
airflow-core/src/airflow/jobs/scheduler_job_runner.py:
##########
@@ -456,6 +498,193 @@ def __init__(
def heartbeat_callback(self, *, session: Session = NEW_SESSION) -> None:
stats.incr("scheduler_heartbeat", 1, 1)
+ def _check_executor_health(self) -> None:
+ """
+ Kick off a health check for each reporting executor, in the background.
+
+ Called on its own timer (``[scheduler]
executor_health_check_interval``), independent of the
+ scheduling loop and of each executor's own
:meth:`~airflow.executors.base_executor.BaseExecutor.heartbeat`.
+ A new check for a given executor is skipped while its previous check
is still running, so a
+ slow or hung dependency can only ever delay that executor's own health
being updated, never
+ pile up work or block this (or any other) scheduler tick.
+
+ ``get_health()`` is passed a timeout, but an implementation that
ignores it can still leave its
+ check thread running forever. Once a running check is a few intervals
old, it's reported as
+ stalled: the scheduler records UNHEALTHY itself, since a check that
hasn't answered isn't
+ still-healthy, and logs and emits a metric so the stall is visible. If
the stuck call does
+ eventually return, its result overwrites this one.
+ """
+ for executor in self.executors:
+ key = _executor_health_key(executor)
+ if key not in self._executor_health_keys:
+ continue
+ thread, started = self._executor_health_check_threads.get(key,
(None, 0.0))
+ if thread is not None and thread.is_alive():
+ stall_after = (
+ self._executor_health_check_interval *
self._executor_health_check_stall_after_intervals
+ )
+ if time.monotonic() - started > stall_after:
+ if key not in self._stalled_health_checks:
+ self._stalled_health_checks.add(key)
+ self.log.warning("Health check for executor %s has
stopped responding", key)
+ stats.incr(
+ "scheduler.executor_health_check.stalled",
+ tags=prune_dict(
+ {"executor": type(executor).__name__,
"team_name": executor.team_name}
+ ),
+ )
+ try:
+ self._record_executor_health_result(key,
HealthCheckResult.UNHEALTHY)
+ except Exception:
+ self.log.exception("Failed to record health check
result for executor %s", key)
+ else:
+ self.log.debug(
+ "Skipping health check for executor %s, the previous
check hasn't finished", key
+ )
+ continue
+ self._stalled_health_checks.discard(key)
+ thread = threading.Thread(
+ target=self._run_executor_health_check,
+ args=(executor, key),
+ name=f"executor-health-check-{key}",
+ daemon=True,
+ )
+ thread.start()
+ self._executor_health_check_threads[key] = (thread,
time.monotonic())
+
+ def _join_executor_health_check_threads(self) -> None:
+ """
+ Wait for any in-flight executor health check before this scheduler's
ExecutorJob rows are closed.
+
+ A check still running at that point can no longer revive a row -- only
the main thread ever
+ creates one -- but joining first still keeps it from writing a result
onto a row the scheduler
+ has already closed. All threads share one deadline, so shutdown is
bounded by the timeout once,
+ not once per hung check.
+ """
+ deadline = time.monotonic() + self._executor_health_check_timeout
+ for thread, _ in self._executor_health_check_threads.values():
+ thread.join(timeout=max(deadline - time.monotonic(), 0))
Review Comment:
fixed, stalled checks are skipped now, they're not coming back.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]