跳转到主要内容

在数据库、队列服务器、celery进程等服务上运行检查。

项目描述

django-health-check

version pyversion djversion license

此项目检查各种条件,并在检测到异常行为时提供报告。

以下健康检查包含在此项目中

  • 缓存
  • 数据库
  • 存储
  • 磁盘和内存利用率(通过psutil
  • AWS S3存储
  • Celery任务队列
  • Celery ping
  • RabbitMQ
  • 迁移

编写您自己的自定义健康检查也非常快速和简单。

我们也很喜欢贡献,所以不要害怕提交拉取请求。

用例

主要预期用例是通过HTTP(S)监控条件,响应以HTML和JSON格式提供。当你收到包含一个或多个问题的响应时,你可以决定适当的行动方案,这可能包括生成通知和/或自动用新节点替换失败的节点。如果你在高可用环境中监控健康状态,该环境具有负载均衡器,并且从多个节点返回响应,请注意,某些检查(例如,磁盘和内存使用情况)将返回特定于负载均衡器选择的节点的响应。

支持版本

我们官方只支持Python的最新版本以及Django的最新版本和最新的Django LTS版本。

安装

首先,安装django-health-check

$ pip install django-health-check

将健康检查器添加到您想要使用的URL

    urlpatterns = [
        # ...
        path(r'ht/', include('health_check.urls')),
    ]

health_check应用程序添加到您的INSTALLED_APPS

    INSTALLED_APPS = [
        # ...
        'health_check',                             # required
        'health_check.db',                          # stock Django health checkers
        'health_check.cache',
        'health_check.storage',
        'health_check.contrib.migrations',
        'health_check.contrib.celery',              # requires celery
        'health_check.contrib.celery_ping',         # requires celery
        'health_check.contrib.psutil',              # disk and memory utilization; requires psutil
        'health_check.contrib.s3boto3_storage',     # requires boto3 and S3BotoStorage backend
        'health_check.contrib.rabbitmq',            # requires RabbitMQ broker
        'health_check.contrib.redis',               # requires Redis broker
    ]

注意:如果使用boto 2.x.x,请使用health_check.contrib.s3boto_storage

(可选) 如果使用psutil应用程序,您可以配置磁盘和内存阈值设置;否则假设以下默认值。如果您想禁用这些检查中的一个,请将其值设置为None

    HEALTH_CHECK = {
        'DISK_USAGE_MAX': 90,  # percent
        'MEMORY_MIN': 100,    # in MB
    }

要使用健康检查子集,指定子集名称并将其与相关的健康检查服务相关联以利用健康检查子集。

    HEALTH_CHECK = {
        # .....
        "SUBSETS": {
            "startup-probe": ["MigrationsHealthCheck", "DatabaseBackend"],
            "liveness-probe": ["DatabaseBackend"],
            "<SUBSET_NAME>": ["<Health_Check_Service_Name>"]
        },
        # .....
    }

要仅执行特定的健康检查子集

curl -X GET -H "Accept: application/json" http://www.example.com/ht/startup-probe/

如果使用数据库检查,请运行迁移

$ django-admin migrate

要使用RabbitMQ健康检查,请确保在django.conf.settings中有一个名为BROKER_URL的变量,其具有连接到您的rabbit服务器所需的格式。例如

    BROKER_URL = "amqp://myuser:mypassword@localhost:5672/myvhost"

要使用Redis健康检查,请确保在django.conf.settings中有一个名为REDIS_URL的变量,其具有连接到您的redis服务器所需的格式。例如

    REDIS_URL = "redis://localhost:6370"

缓存健康检查尝试在缓存后端中写入和读取特定的键。可以通过将HEALTHCHECK_CACHE_KEY设置为另一个值来自定义它

    HEALTHCHECK_CACHE_KEY = "custom_healthcheck_key"

设置监控

您可以使用Pingdom、StatusCake或其他uptime robots等工具来监控服务状态。如果所有检查都通过,则/ht/端点将以HTTP 200响应,如果任何测试失败,则返回HTTP 500。

如果您想要机器可读的状态报告,可以通过将Accept HTTP头设置为application/json或通过传递查询参数format=json来请求/ht/端点。

后端将返回一个JSON响应

    $ curl -v -X GET -H "Accept: application/json" http://www.example.com/ht/

    > GET /ht/ HTTP/1.1
    > Host: www.example.com
    > Accept: application/json
    >
    < HTTP/1.1 200 OK
    < Content-Type: application/json

    {
        "CacheBackend": "working",
        "DatabaseBackend": "working",
        "S3BotoStorageHealthCheck": "working"
    }

    $ curl -v -X GET http://www.example.com/ht/?format=json

    > GET /ht/?format=json HTTP/1.1
    > Host: www.example.com
    >
    < HTTP/1.1 200 OK
    < Content-Type: application/json

    {
        "CacheBackend": "working",
        "DatabaseBackend": "working",
        "S3BotoStorageHealthCheck": "working"
    }

编写自定义健康检查

编写健康检查既快又简单

    from health_check.backends import BaseHealthCheckBackend

    class MyHealthCheckBackend(BaseHealthCheckBackend):
        #: The status endpoints will respond with a 200 status code
        #: even if the check errors.
        critical_service = False

        def check_status(self):
            # The test code goes here.
            # You can use `self.add_error` or
            # raise a `HealthCheckException`,
            # similar to Django's form validation.
            pass

        def identifier(self):
            return self.__class__.__name__  # Display name on the endpoint.

编写自定义检查后,将其注册到您的应用配置中

    from django.apps import AppConfig

    from health_check.plugins import plugin_dir

    class MyAppConfig(AppConfig):
        name = 'my_app'

        def ready(self):
            from .backends import MyHealthCheckBackend
            plugin_dir.register(MyHealthCheckBackend)

确保您编写检查的应用程序已注册到您的INSTALLED_APPS

自定义输出

您可以通过从 health_check.views 中的 MainView 继承并自定义 template_namegetrender_to_responserender_to_response_json 属性来定制 HTML 或 JSON 渲染。

    # views.py
    from health_check.views import MainView

    class HealthCheckCustomView(MainView):
        template_name = 'myapp/health_check_dashboard.html'  # customize the used templates

        def get(self, request, *args, **kwargs):
            plugins = []
            status = 200 # needs to be filled status you need
            # ...
            if 'application/json' in request.META.get('HTTP_ACCEPT', ''):
                return self.render_to_response_json(plugins, status)
            return self.render_to_response(plugins, status)

        def render_to_response(self, plugins, status):       # customize HTML output
            return HttpResponse('COOL' if status == 200 else 'SWEATY', status=status)

        def render_to_response_json(self, plugins, status):  # customize JSON output
            return JsonResponse(
                {str(p.identifier()): 'COOL' if status == 200 else 'SWEATY' for p in plugins},
                status=status
            )

    # urls.py
    import views

    urlpatterns = [
        # ...
        path(r'ht/', views.HealthCheckCustomView.as_view(), name='health_check_custom'),
    ]

Django 命令

您可以通过命令行运行 Django 命令 health_check 来执行您的健康检查,或者像下面这样定期通过 cron 执行:

    django-admin health_check

这将产生以下输出

    DatabaseHealthCheck      ... working
    CustomHealthCheck        ... unavailable: Something went wrong!

与 HTTP 版本类似,如果发生严重错误,命令将以退出代码 1 退出。

其他资源

  • django-watchman 是一个包,它以稍微不同的方式执行一些相同的事情。

项目详情


发布历史 发布通知 | RSS 源

下载文件

下载您平台上的文件。如果您不确定要选择哪一个,请了解更多关于 安装包 的信息。

源代码分发

django_health_check-3.18.3.tar.gz (20.9 kB 查看哈希)

上传时间 源代码

构建分发

django_health_check-3.18.3-py2.py3-none-any.whl (30.3 kB 查看哈希)

上传时间 Python 2 Python 3

由以下支持