Skip to content

Commit

Permalink
feat: create healthchecks api (#133)
Browse files Browse the repository at this point in the history
create a new api route /health which return in json the status of the different services

Fixes: #67 Add a health endpoint
  • Loading branch information
Marc-AntoineA authored Jun 7, 2024
1 parent d1162e0 commit b351338
Show file tree
Hide file tree
Showing 5 changed files with 483 additions and 459 deletions.
11 changes: 10 additions & 1 deletion app/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

import elasticsearch
from elasticsearch_dsl import Search
from fastapi import FastAPI, HTTPException, Query, Request
from fastapi import FastAPI, HTTPException, Query, Request, Response
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse, PlainTextResponse
from fastapi.templating import Jinja2Templates
Expand Down Expand Up @@ -319,3 +319,12 @@ def html_search(
@app.get("/robots.txt", response_class=PlainTextResponse)
def robots_txt():
return """User-agent: *\nDisallow: /"""


@app.get("/health")
def healthcheck():
from app.health import health

message, status, _ = health.run()
logger.warning("HEALTH:", message, status)
return Response(content=message, status_code=status, media_type="application/json")
27 changes: 27 additions & 0 deletions app/health.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from healthcheck import HealthCheck

from app.utils import connection, get_logger

logger = get_logger(__name__)

health = HealthCheck()


def test_connect_redis():
logger.debug("health: testing redis connection")
client = connection.get_redis_client(socket_connect_timeout=5)
if client.ping():
return True, "Redis connection check succedded!"
return False, "Redis connection check failed!"


def test_connect_es():
logger.debug("health: testing es connection")
es = connection.get_es_client(timeout=5)
if es.ping():
return True, "es0 connection check succedded!"
return False, "es0 connection check failed!"


health.add_check(test_connect_redis)
health.add_check(test_connect_es)
3 changes: 2 additions & 1 deletion app/utils/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,10 @@ def get_es_client(**kwargs):
)


def get_redis_client() -> Redis:
def get_redis_client(**kwargs) -> Redis:
return Redis(
host=settings.redis_host,
port=settings.redis_port,
decode_responses=True,
**kwargs,
)
Loading

0 comments on commit b351338

Please sign in to comment.