Skip to content

Commit

Permalink
Add black linter
Browse files Browse the repository at this point in the history
  • Loading branch information
codingjoe committed Sep 2, 2022
1 parent 3242044 commit f6aafac
Show file tree
Hide file tree
Showing 55 changed files with 475 additions and 335 deletions.
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ jobs:
matrix:
lint-command:
- bandit -r . -x ./tests
- black --check --diff .
- flake8 .
- isort --check-only --diff .
- pydocstyle .
Expand Down
2 changes: 1 addition & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
except ImportError:
sphinx_rtd_theme = None

master_doc = 'index'
master_doc = "index"

if sphinx_rtd_theme:
html_theme = "sphinx_rtd_theme"
Expand Down
4 changes: 2 additions & 2 deletions health_check/backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

from health_check.exceptions import HealthCheckException

logger = logging.getLogger('health-check')
logger = logging.getLogger("health-check")


class BaseHealthCheckBackend:
Expand Down Expand Up @@ -54,7 +54,7 @@ def add_error(self, error, cause=None):
def pretty_status(self):
if self.errors:
return "\n".join(str(e) for e in self.errors)
return _('working')
return _("working")

@property
def status(self):
Expand Down
2 changes: 1 addition & 1 deletion health_check/cache/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import django

if django.VERSION < (3, 2):
default_app_config = 'health_check.cache.apps.HealthCheckConfig'
default_app_config = "health_check.cache.apps.HealthCheckConfig"
2 changes: 1 addition & 1 deletion health_check/cache/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@


class HealthCheckConfig(AppConfig):
name = 'health_check.cache'
name = "health_check.cache"

def ready(self):
from .backends import CacheBackend
Expand Down
8 changes: 3 additions & 5 deletions health_check/cache/backends.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
from django.core.cache import CacheKeyWarning, caches

from health_check.backends import BaseHealthCheckBackend
from health_check.exceptions import (
ServiceReturnedUnexpectedResult, ServiceUnavailable
)
from health_check.exceptions import ServiceReturnedUnexpectedResult, ServiceUnavailable


class CacheBackend(BaseHealthCheckBackend):
def __init__(self, backend='default'):
def __init__(self, backend="default"):
super().__init__()
self.backend = backend

Expand All @@ -18,7 +16,7 @@ def check_status(self):
cache = caches[self.backend]

try:
cache.set('djangohealtcheck_test', 'itworks')
cache.set("djangohealtcheck_test", "itworks")
if not cache.get("djangohealtcheck_test") == "itworks":
raise ServiceUnavailable("Cache key does not match")
except CacheKeyWarning as e:
Expand Down
8 changes: 4 additions & 4 deletions health_check/conf.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from django.conf import settings

HEALTH_CHECK = getattr(settings, 'HEALTH_CHECK', {})
HEALTH_CHECK.setdefault('DISK_USAGE_MAX', 90)
HEALTH_CHECK.setdefault('MEMORY_MIN', 100)
HEALTH_CHECK.setdefault('WARNINGS_AS_ERRORS', True)
HEALTH_CHECK = getattr(settings, "HEALTH_CHECK", {})
HEALTH_CHECK.setdefault("DISK_USAGE_MAX", 90)
HEALTH_CHECK.setdefault("MEMORY_MIN", 100)
HEALTH_CHECK.setdefault("WARNINGS_AS_ERRORS", True)
2 changes: 1 addition & 1 deletion health_check/contrib/celery/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import django

if django.VERSION < (3, 2):
default_app_config = 'health_check.contrib.celery.apps.HealthCheckConfig'
default_app_config = "health_check.contrib.celery.apps.HealthCheckConfig"
11 changes: 7 additions & 4 deletions health_check/contrib/celery/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,23 @@


class HealthCheckConfig(AppConfig):
name = 'health_check.contrib.celery'
name = "health_check.contrib.celery"

def ready(self):
from .backends import CeleryHealthCheck

if hasattr(settings, "HEALTHCHECK_CELERY_TIMEOUT"):
warnings.warn(
"HEALTHCHECK_CELERY_TIMEOUT is depricated and may be removed in the "
"future. Please use HEALTHCHECK_CELERY_RESULT_TIMEOUT and "
"HEALTHCHECK_CELERY_QUEUE_TIMEOUT instead.",
DeprecationWarning
DeprecationWarning,
)

for queue in current_app.amqp.queues:
celery_class_name = 'CeleryHealthCheck' + queue.title()
celery_class_name = "CeleryHealthCheck" + queue.title()

celery_class = type(celery_class_name, (CeleryHealthCheck,), {'queue': queue})
celery_class = type(
celery_class_name, (CeleryHealthCheck,), {"queue": queue}
)
plugin_dir.register(celery_class)
41 changes: 27 additions & 14 deletions health_check/contrib/celery/backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,36 +2,49 @@
from django.conf import settings

from health_check.backends import BaseHealthCheckBackend
from health_check.exceptions import (
ServiceReturnedUnexpectedResult, ServiceUnavailable
)
from health_check.exceptions import ServiceReturnedUnexpectedResult, ServiceUnavailable

from .tasks import add


class CeleryHealthCheck(BaseHealthCheckBackend):
def check_status(self):
timeout = getattr(settings, 'HEALTHCHECK_CELERY_TIMEOUT', 3)
result_timeout = getattr(settings, 'HEALTHCHECK_CELERY_RESULT_TIMEOUT', timeout)
queue_timeout = getattr(settings, 'HEALTHCHECK_CELERY_QUEUE_TIMEOUT', timeout)
timeout = getattr(settings, "HEALTHCHECK_CELERY_TIMEOUT", 3)
result_timeout = getattr(settings, "HEALTHCHECK_CELERY_RESULT_TIMEOUT", timeout)
queue_timeout = getattr(settings, "HEALTHCHECK_CELERY_QUEUE_TIMEOUT", timeout)

try:
result = add.apply_async(
args=[4, 4],
expires=queue_timeout,
queue=self.queue
args=[4, 4], expires=queue_timeout, queue=self.queue
)
result.get(timeout=result_timeout)
if result.result != 8:
self.add_error(ServiceReturnedUnexpectedResult("Celery returned wrong result"))
self.add_error(
ServiceReturnedUnexpectedResult("Celery returned wrong result")
)
except IOError as e:
self.add_error(ServiceUnavailable("IOError"), e)
except NotImplementedError as e:
self.add_error(ServiceUnavailable("NotImplementedError: Make sure CELERY_RESULT_BACKEND is set"), e)
self.add_error(
ServiceUnavailable(
"NotImplementedError: Make sure CELERY_RESULT_BACKEND is set"
),
e,
)
except TaskRevokedError as e:
self.add_error(ServiceUnavailable("TaskRevokedError: The task was revoked, likely because it spent "
"too long in the queue"), e)
self.add_error(
ServiceUnavailable(
"TaskRevokedError: The task was revoked, likely because it spent "
"too long in the queue"
),
e,
)
except TimeoutError as e:
self.add_error(ServiceUnavailable("TimeoutError: The task took too long to return a result"), e)
self.add_error(
ServiceUnavailable(
"TimeoutError: The task took too long to return a result"
),
e,
)
except BaseException as e:
self.add_error(ServiceUnavailable("Unknown error"), e)
2 changes: 1 addition & 1 deletion health_check/contrib/celery_ping/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import django

if django.VERSION < (3, 2):
default_app_config = 'health_check.contrib.celery_ping.apps.HealthCheckConfig'
default_app_config = "health_check.contrib.celery_ping.apps.HealthCheckConfig"
2 changes: 1 addition & 1 deletion health_check/contrib/celery_ping/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@


class HealthCheckConfig(AppConfig):
name = 'health_check.contrib.celery_ping'
name = "health_check.contrib.celery_ping"

def ready(self):
from .backends import CeleryPingHealthCheck
Expand Down
2 changes: 1 addition & 1 deletion health_check/contrib/migrations/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import django

if django.VERSION < (3, 2):
default_app_config = 'health_check.contrib.migrations.apps.HealthCheckConfig'
default_app_config = "health_check.contrib.migrations.apps.HealthCheckConfig"
3 changes: 1 addition & 2 deletions health_check/contrib/migrations/backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,11 @@


class MigrationsHealthCheck(BaseHealthCheckBackend):

def get_migration_plan(self, executor):
return executor.migration_plan(executor.loader.graph.leaf_nodes())

def check_status(self):
db_alias = getattr(settings, 'HEALTHCHECK_MIGRATIONS_DB', DEFAULT_DB_ALIAS)
db_alias = getattr(settings, "HEALTHCHECK_MIGRATIONS_DB", DEFAULT_DB_ALIAS)
try:
executor = MigrationExecutor(connections[db_alias])
plan = self.get_migration_plan(executor)
Expand Down
2 changes: 1 addition & 1 deletion health_check/contrib/psutil/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import django

if django.VERSION < (3, 2):
default_app_config = 'health_check.contrib.psutil.apps.HealthCheckConfig'
default_app_config = "health_check.contrib.psutil.apps.HealthCheckConfig"
18 changes: 11 additions & 7 deletions health_check/contrib/psutil/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,25 @@


class HealthCheckConfig(AppConfig):
name = 'health_check.contrib.psutil'
name = "health_check.contrib.psutil"

def ready(self):
from .backends import DiskUsage, MemoryUsage

# Ensure checks haven't been explicitly disabled before registering
if (hasattr(settings, 'HEALTH_CHECK') and
('DISK_USAGE_MAX' in settings.HEALTH_CHECK) and
(settings.HEALTH_CHECK['DISK_USAGE_MAX'] is None)):
if (
hasattr(settings, "HEALTH_CHECK")
and ("DISK_USAGE_MAX" in settings.HEALTH_CHECK)
and (settings.HEALTH_CHECK["DISK_USAGE_MAX"] is None)
):
pass
else:
plugin_dir.register(DiskUsage)
if (hasattr(settings, 'HEALTH_CHECK') and
('DISK_USAGE_MAX' in settings.HEALTH_CHECK) and
(settings.HEALTH_CHECK['MEMORY_MIN'] is None)):
if (
hasattr(settings, "HEALTH_CHECK")
and ("DISK_USAGE_MAX" in settings.HEALTH_CHECK)
and (settings.HEALTH_CHECK["MEMORY_MIN"] is None)
):
pass
else:
plugin_dir.register(MemoryUsage)
22 changes: 11 additions & 11 deletions health_check/contrib/psutil/backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,23 @@

from health_check.backends import BaseHealthCheckBackend
from health_check.conf import HEALTH_CHECK
from health_check.exceptions import (
ServiceReturnedUnexpectedResult, ServiceWarning
)
from health_check.exceptions import ServiceReturnedUnexpectedResult, ServiceWarning

host = socket.gethostname()

DISK_USAGE_MAX = HEALTH_CHECK['DISK_USAGE_MAX']
MEMORY_MIN = HEALTH_CHECK['MEMORY_MIN']
DISK_USAGE_MAX = HEALTH_CHECK["DISK_USAGE_MAX"]
MEMORY_MIN = HEALTH_CHECK["MEMORY_MIN"]


class DiskUsage(BaseHealthCheckBackend):
def check_status(self):
try:
du = psutil.disk_usage('/')
du = psutil.disk_usage("/")
if DISK_USAGE_MAX and du.percent >= DISK_USAGE_MAX:
raise ServiceWarning(
"{host} {percent}% disk usage exceeds {disk_usage}%".format(
host=host, percent=du.percent, disk_usage=DISK_USAGE_MAX)
host=host, percent=du.percent, disk_usage=DISK_USAGE_MAX
)
)
except ValueError as e:
self.add_error(ServiceReturnedUnexpectedResult("ValueError"), e)
Expand All @@ -33,12 +32,13 @@ def check_status(self):
try:
memory = psutil.virtual_memory()
if MEMORY_MIN and memory.available < (MEMORY_MIN * 1024 * 1024):
locale.setlocale(locale.LC_ALL, '')
avail = '{:n}'.format(int(memory.available / 1024 / 1024))
threshold = '{:n}'.format(MEMORY_MIN)
locale.setlocale(locale.LC_ALL, "")
avail = "{:n}".format(int(memory.available / 1024 / 1024))
threshold = "{:n}".format(MEMORY_MIN)
raise ServiceWarning(
"{host} {avail} MB available RAM below {threshold} MB".format(
host=host, avail=avail, threshold=threshold)
host=host, avail=avail, threshold=threshold
)
)
except ValueError as e:
self.add_error(ServiceReturnedUnexpectedResult("ValueError"), e)
2 changes: 1 addition & 1 deletion health_check/contrib/rabbitmq/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import django

if django.VERSION < (3, 2):
default_app_config = 'health_check.contrib.rabbitmq.apps.HealthCheckConfig'
default_app_config = "health_check.contrib.rabbitmq.apps.HealthCheckConfig"
14 changes: 12 additions & 2 deletions health_check/contrib/rabbitmq/backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,20 @@ def check_status(self):
with Connection(broker_url) as conn:
conn.connect() # exceptions may be raised upon calling connect
except ConnectionRefusedError as e:
self.add_error(ServiceUnavailable("Unable to connect to RabbitMQ: Connection was refused."), e)
self.add_error(
ServiceUnavailable(
"Unable to connect to RabbitMQ: Connection was refused."
),
e,
)

except AccessRefused as e:
self.add_error(ServiceUnavailable("Unable to connect to RabbitMQ: Authentication error."), e)
self.add_error(
ServiceUnavailable(
"Unable to connect to RabbitMQ: Authentication error."
),
e,
)

except IOError as e:
self.add_error(ServiceUnavailable("IOError"), e)
Expand Down
2 changes: 1 addition & 1 deletion health_check/contrib/redis/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import django

if django.VERSION < (3, 2):
default_app_config = 'health_check.contrib.redis.apps.HealthCheckConfig'
default_app_config = "health_check.contrib.redis.apps.HealthCheckConfig"
17 changes: 13 additions & 4 deletions health_check/contrib/redis/backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
class RedisHealthCheck(BaseHealthCheckBackend):
"""Health check for Redis."""

redis_url = getattr(settings, "REDIS_URL", 'redis://localhost/1')
redis_url = getattr(settings, "REDIS_URL", "redis://localhost/1")

def check_status(self):
"""Check Redis service by pinging the redis instance with a redis connection."""
Expand All @@ -24,11 +24,20 @@ def check_status(self):
with from_url(self.redis_url) as conn:
conn.ping() # exceptions may be raised upon ping
except ConnectionRefusedError as e:
self.add_error(ServiceUnavailable("Unable to connect to Redis: Connection was refused."), e)
self.add_error(
ServiceUnavailable(
"Unable to connect to Redis: Connection was refused."
),
e,
)
except exceptions.TimeoutError as e:
self.add_error(ServiceUnavailable("Unable to connect to Redis: Timeout."), e)
self.add_error(
ServiceUnavailable("Unable to connect to Redis: Timeout."), e
)
except exceptions.ConnectionError as e:
self.add_error(ServiceUnavailable("Unable to connect to Redis: Connection Error"), e)
self.add_error(
ServiceUnavailable("Unable to connect to Redis: Connection Error"), e
)
except BaseException as e:
self.add_error(ServiceUnavailable("Unknown error"), e)
else:
Expand Down
2 changes: 1 addition & 1 deletion health_check/contrib/s3boto3_storage/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import django

if django.VERSION < (3, 2):
default_app_config = 'health_check.contrib.s3boto3_storage.apps.HealthCheckConfig'
default_app_config = "health_check.contrib.s3boto3_storage.apps.HealthCheckConfig"
3 changes: 2 additions & 1 deletion health_check/contrib/s3boto3_storage/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@


class HealthCheckConfig(AppConfig):
name = 'health_check.contrib.s3boto3_storage'
name = "health_check.contrib.s3boto3_storage"

def ready(self):
from .backends import S3Boto3StorageHealthCheck

plugin_dir.register(S3Boto3StorageHealthCheck)

0 comments on commit f6aafac

Please sign in to comment.