Source code for smarter.apps.dashboard.views.views.api.service_health

"""
API view for the Dashboard "Service Health" React component.

This module provides a lightweight JSON endpoint consumed by the Service Health
React widget on the main dashboard page. It returns version and environment
metadata for the running Smarter platform so that operators can quickly verify
which versions of core dependencies are active, along with the results of live
checks of the backing services: the database, the cache, the Celery task broker,
and the Celery workers.

Classes:
    ServiceHealthView: Authenticated POST endpoint that returns platform
        version and environment metadata as a JSON response.

Example:
    Wire up the view in your URL configuration::

        from smarter.apps.dashboard.views.views.api.service_health import ServiceHealthView

        urlpatterns = [
            path("service-health/", ServiceHealthView.as_view(), name="service_health"),
        ]
"""

from http import HTTPStatus
from typing import Callable
from uuid import uuid4

from cache_results import cache_results, lazy_cache
from django.db import connection
from django.http import JsonResponse
from django.http.request import HttpRequest

from smarter.common.conf import smarter_settings
from smarter.lib import json, logging
from smarter.lib.django.views import (
    SmarterAuthenticatedWebView,
)

logger = logging.getSmarterLogger(__name__)

CELERY_PING_TIMEOUT = 0.5  # seconds. the widget loads asynchronously, but should not hang.
HEALTH_CHECKS_CACHE_TIMEOUT = 60  # seconds. one run of the checks serves every dashboard for a minute.


[docs] def check_database() -> bool: """True if the database answers a trivial query.""" with connection.cursor() as cursor: cursor.execute("SELECT 1") return cursor.fetchone() == (1,)
[docs] def check_cache() -> bool: """True if a value written to the cache can be read back.""" key = f"smarter_service_health_{uuid4().hex}" lazy_cache.set(key, "ok", timeout=10) try: return lazy_cache.get(key) == "ok" finally: lazy_cache.delete(key)
[docs] def check_task_broker() -> bool: """True if the Celery broker accepts a connection.""" # pylint: disable=C0415 from smarter.lib.celery_conf import APP with APP.connection_for_read() as conn: conn.ensure_connection(max_retries=1) return True
[docs] def check_workers() -> bool: """True if at least one Celery worker answers a ping.""" # pylint: disable=C0415 from smarter.lib.celery_conf import APP return bool(APP.control.ping(timeout=CELERY_PING_TIMEOUT))
HEALTH_CHECKS: dict[str, Callable[[], bool]] = { "Database": check_database, "Cache": check_cache, "Task Broker": check_task_broker, "Workers": check_workers, } CHECK_DID_NOT_PASS = "the check ran, and did not pass" """The error of a check that returned False rather than raising, e.g. no Celery worker answered its ping."""
[docs] def run_health_checks() -> list[dict[str, object]]: """ Run each health check, and report a failure, or an exception, as unhealthy, with why. Each result has the check's ``name``, whether it is ``healthy``, and its ``error``: an empty string for a healthy check, the exception's class and message for one that raised, e.g. ``TimeoutError: Timeout connecting to server``, or :data:`CHECK_DID_NOT_PASS`. The error is for staff, e.g. Smarter Sysadmin's ``platform_status``: :class:`ServiceHealthView` leaves it out. :returns: One result per check of :data:`HEALTH_CHECKS`, in its order. """ retval = [] for name, check in HEALTH_CHECKS.items(): error = "" try: healthy = bool(check()) # pylint: disable=broad-except except Exception as e: logger.warning("health check %s failed: %s", name, e) healthy = False error = f"{type(e).__name__}: {e}" if not healthy and not error: error = CHECK_DID_NOT_PASS retval.append({"name": name, "healthy": healthy, "error": error}) return retval
[docs] def public_health_checks(checks: list[dict[str, object]]) -> list[dict[str, object]]: """ Return the health checks without their errors, for the dashboard's widget. An error can name internal hosts and services, which a dashboard user doesn't need. :param checks: The results of :func:`run_health_checks`. :returns: Each check's ``name``, and whether it is ``healthy``. """ public = [] for check in checks: public.append({"name": check["name"], "healthy": check["healthy"]}) return public
[docs] @cache_results(timeout=HEALTH_CHECKS_CACHE_TIMEOUT) def cached_health_checks() -> list[dict[str, object]]: """The results of :func:`run_health_checks`, cached for :data:`HEALTH_CHECKS_CACHE_TIMEOUT` seconds.""" return run_health_checks()
[docs] def wants_refresh(request: HttpRequest) -> bool: """ True if the request asks for the checks to run again now, with ``{"refresh": true}`` as its body. The dashboard's refresh button sends it. A missing or malformed body is not a refresh. :param request: The incoming HTTP POST request. :type request: django.http.HttpRequest :returns: Whether the body's ``refresh`` is true. :rtype: bool """ try: body = json.loads(request.body or b"{}") except (json.JSONDecodeError, UnicodeDecodeError): return False return isinstance(body, dict) and body.get("refresh") is True
[docs] def current_health_checks() -> list[dict[str, object]]: """ Return the results of the health checks, from the cache when it has them. The checks ping the database, the cache and the Celery workers, so every dashboard shares one run of them a minute. If the cache itself is down, reading it raises, and the checks run uncached, so that the Cache check reports the failure instead of the whole widget failing. :returns: The name of each check, and whether it passed. :rtype: list[dict[str, object]] """ try: return cached_health_checks() # pylint: disable=broad-except except Exception as e: logger.warning( "the cache failed, running the checks uncached: %s", e, ) return run_health_checks()
# pylint: disable=W0613
[docs] class ServiceHealthView(SmarterAuthenticatedWebView): """ Authenticated JSON API view that reports platform version and environment metadata. Extends :class:`~smarter.lib.django.views.SmarterAuthenticatedWebView` to restrict access to authenticated users. On a ``POST`` request the view reads version strings and environment information, and the url of the platform's source code repository, from :data:`~smarter.common.conf.smarter_settings`, runs the live :data:`HEALTH_CHECKS`, at most once a minute (see :func:`current_health_checks`), and returns them as a JSON object with an HTTP 200 status. A body of ``{"refresh": true}``, which the dashboard's refresh button sends, runs the checks again now. ``health_score`` is the percentage of checks that passed. Response shape: .. code-block:: json { "smarter_version": "1.2.3", "linux_distribution": "Ubuntu 22.04", "django_version": "4.2.0", "python_version": "3.11.0", "pydantic_version": "2.0.0", "drf_version": "3.14.0", "repository_url": "https://github.com/smarter-sh/smarter", "health_checks": [ {"name": "Database", "healthy": true}, {"name": "Cache", "healthy": true}, {"name": "Task Broker", "healthy": true}, {"name": "Workers", "healthy": false} ], "health_score": 75 } """ @property def formatted_class_name(self) -> str: """Returns the class name in a formatted string along with the name of this view.""" class_name = f"{__name__}.{ServiceHealthView.__name__}[{id(self)}]" return self.formatted_text(class_name)
[docs] def post(self, request: HttpRequest, *args, **kwargs) -> JsonResponse: """ Handle POST requests to return platform health metadata. :param request: The incoming HTTP POST request from the client. :type request: django.http.HttpRequest :param args: Additional positional arguments forwarded by the URL dispatcher. :param kwargs: Additional keyword arguments forwarded by the URL dispatcher. :returns: A JSON response containing platform version and environment metadata, and the results of the health checks. :rtype: django.http.JsonResponse """ if wants_refresh(request): logger.info("refreshing the health checks") cached_health_checks.invalidate() health_checks = public_health_checks(current_health_checks()) healthy = sum(1 for check in health_checks if check["healthy"]) retval = { "smarter_version": smarter_settings.version, "linux_distribution": smarter_settings.linux_distribution, "django_version": smarter_settings.django_version, "python_version": smarter_settings.python_version, "pydantic_version": smarter_settings.pydantic_version, "drf_version": smarter_settings.drf_version, "repository_url": smarter_settings.repository_url, "health_checks": health_checks, "health_score": round(healthy / len(health_checks) * 100), } return JsonResponse(retval, status=HTTPStatus.OK)