Skip to main content

Classic Health Checks

PyPI version License: MIT

Простая реализация проверки работоспособности сервиса (liveness probe) через обновление временной метки файла.

Этот пакет предоставляет задачу, которая может быть запущена в отдельном потоке или гринлете для периодического обновления файла на диске. Внешние системы мониторинга, такие как Kubernetes или systemd, могут отслеживать время последнего изменения этого файла, чтобы убедиться, что сервис активен и не завис.

Установка

pip install classic-health-checks

Использование (Usage)

Вот минимальный пример использования HealthCheck в отдельном потоке.

Использование с gevent

Для использования с gevent убедитесь, что он установлен:

pip install gevent

HealthCheck легко интегрируется с gevent. Инициализируем и запускаем run в гринлете.

import gevent
from gevent.monkey import patch_all

patch_all()

import logging
from pydantic_settings import BaseSettings
from classic.health_checks import HealthCheck, HealthCheckSettingsMixin

# Настройте базовый логгер
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

class AppSettings(HealthCheckSettingsMixin, BaseSettings):
   ...

settings = AppSettings(HEALTHCHECK_FILE_PATH='/tmp/healthcheck')

# 1. Создаем экземпляр

health_check = HealthCheck(
    logger=logger,
    settings=settings,
)

# 2. Запускаем HealthCheck и другие задачи в своих гринлетах

# Псевдо-задачи для примера
class LongRunningTask:
    def __init__(self, name: str):
        self.name = name
    def run(self):
        logger.info(f"Задача '{self.name}' запущена.")
        while True:
            gevent.sleep(60)

task1 = LongRunningTask("Обработчик сообщений")
task2 = LongRunningTask("Сборщик метрик")

all_greenlets = [
    gevent.spawn(health_check.run),
    gevent.spawn(task1.run),
    gevent.spawn(task2.run),
]

logger.info(f"Запущено {len(all_greenlets)} гринлетов, включая HealthCheck.")

# 3. Ожидаем завершения всех задач и обрабатываем остановку
try:
    gevent.joinall(all_greenlets, raise_error=True)
except (KeyboardInterrupt, SystemExit):
    logger.info("Получен сигнал остановки, завершаем все гринлеты...")
    gevent.killall(all_greenlets)
    logger.info("Приложение остановлено.")

Подсказка: "Сигнал остановки" обычно отправляется нажатием Ctrl+C в терминале, где запущен скрипт.

Интеграция с Kubernetes

Вы можете использовать этот механизм для настройки livenessProbe в вашем Helm-чарте:

# ... внутри spec.template.spec.containers[]
# Добавляем переменную окружения, чтобы она была доступна в livenessProbe
env:
- name: HEALTHCHECK_FILE_PATH
  value: /tmp/my_app_healthy
  
  
envsFromSecret:
  secret-envs:
    ...
livenessProbe:
  exec:
    command:
    - /bin/sh
    - -c
    - "[ $(($(date +%s) - $(stat -c %Y $HEALTHCHECK_FILE_PATH))) -le 10 ]"
  periodSeconds: 10
  initialDelaySeconds: 30
  failureThreshold: 3

Metadata

Release files for classic-health-checks 0.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for classic-health-checks 0.1.1
File Size Uploaded Provenance
classic_health_checks-0.1.1.tar.gz 5.8 kB With provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for classic-health-checks 0.1.1
File Interpreter ABI Platform
classic_health_checks-0.1.1-py3-none-any.whl Python 3 none any Details

Total release size: 12.0 kB

Release files / classic_health_checks-0.1.1.tar.gz

Download URL classic_health_checks-0.1.1.tar.gz
Size 5.8 kB
Tags Source
SHA-256 checksum
How to use checksums
3cab6b71a30f7efa03b1ffa6567d92b658c7b7a5a6599c8ed155e6d4d575d42f
BLAKE2b-256 checksum
How to use checksums
4e90813b5c7358382217802174e9d16b8779ee9e0e49f0795f827017aef4125a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.7

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Feb 21, 2026.

Transparency log

Release files / classic_health_checks-0.1.1-py3-none-any.whl

Download URL classic_health_checks-0.1.1-py3-none-any.whl
Size 6.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
d9da2d09b054f675bba3a381571b841d8a09c07764eac5c25bc31fd5431ff685
BLAKE2b-256 checksum
How to use checksums
da65d6b0279c702eda56492e5a9aa572ac5fa70d96f4cb2901e0b727e3a279ce
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.7

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Feb 21, 2026.

Transparency log

Security for classic-health-checks 0.1.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

All 2 files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for classic_health_checks-0.1.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Feb 21, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page