File size: 2,177 Bytes
efc36ce
 
 
e19b795
 
 
a967435
e19b795
4c47414
e19b795
 
 
efc36ce
e19b795
 
 
 
efc36ce
 
e19b795
 
 
 
 
 
 
 
efc36ce
 
 
e19b795
 
3d237cb
e19b795
efc36ce
 
e19b795
 
 
fb7cbb3
 
 
 
 
 
 
efc36ce
fb7cbb3
 
 
 
 
 
 
 
 
 
 
efc36ce
 
 
3d237cb
fb7cbb3
 
e19b795
3d237cb
f10736f
efc36ce
e19b795
efc36ce
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# Very simple and important file, uesd to check the api health, if it return 200 everything is great, otherwise, there is an issue.
# This file is being used mostly in HTTP and not websockets.
# Health check is being used for example by docker, to check is dependencies are working fine, if not, he might restart.

from http import HTTPStatus
from datetime import datetime
from fastapi import APIRouter, Response, Request

from api.routers.metrics import active_cameras

router = APIRouter()


@router.get("/")
@router.get("/live")
async def live_check(response: Response):
    """
    Prove that the process is running, No logic requried here.
    Confirming that the server is not dead.
    It is fails, container killed and restarted..
    Has to be very cheap.
    """
    response.status_code = HTTPStatus.OK
    # TODO you can add also some prometheus info here.
    return {
        "status": "live",
        "active_cameras": active_cameras._value.get(),
        "timestamp": datetime.now().isoformat(),
    }


@router.get("/ready")
async def ready_check(response: Response, request: Request):
    """
    Checck if parts work here, ex. are data readable.
    Are data readable here.
    Also can this instance accept traffic right now, or send them to another healthy instance.
    """

    checks = {}
    healthy = True

    # Check redis server
    try:
        await request.app.state.redis.ping()
        checks["redis"] = "Good"
    except Exception:
        checks["redis"] = "unreachable"
        healthy = False

    # Model Check
    try:
        assert request.app.state.detection_model is not None
        checks["detection_model"] = "Good"
    except Exception:
        checks["detection_model"] = "can't load"
        healthy = False

    checks["active_cameras"] = list(
        await request.app.state.redis.smembers("cameras:active")
    )

    response.status_code = HTTPStatus.OK if healthy else HTTPStatus.SERVICE_UNAVAILABLE

    return {
        "status": "ready" if healthy else "degraded",
        "checks": checks,
        "timestamp": datetime.now().isoformat(),  # Sending the time also is a good practise
        "version": "1.0.0",
    }