-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreadiness.py
More file actions
66 lines (53 loc) · 2.04 KB
/
Copy pathreadiness.py
File metadata and controls
66 lines (53 loc) · 2.04 KB
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
'''Module to check the readiness of the stored information'''
import json
import requests
import redis
from app.opensense import get_temperature
from app.config import create_redis_client
redis_client, REDIS_AVAILABLE = create_redis_client()
def check_caching():
'''Check if caching content is older than 5 minutes'''
if not REDIS_AVAILABLE:
return True
try:
cache_key = "temperature_data"
ttl = redis_client.ttl(cache_key)
if ttl in (-2, -1):
return True
return False
except redis.RedisError as e:
print(f"Redis error while checking cache: {e}")
return True
def reachable_boxes():
'''Check if more than 50% of sensor boxes are reachable'''
try:
_, sensor_stats = get_temperature()
total_boxes = sensor_stats.get('total_sensors', 0)
unreachable = sensor_stats.get('null_count', 0)
# No sensors configured => treat as healthy
if total_boxes == 0:
return 200
percentage_unreachable = (unreachable / total_boxes) * 100
# Fail only if strictly more than 50% are unreachable
if percentage_unreachable > 50:
return 400
return 200
except (json.JSONDecodeError, requests.exceptions.RequestException, redis.RedisError) as e:
print(f"Error checking reachable boxes: {e}")
return 200
except (ValueError, TypeError, KeyError) as e:
print(f"Data error checking reachable boxes: {e}")
return 400
def readiness_check():
'''Combined readiness check for the /readyz endpoint'''
try:
boxes_status = reachable_boxes()
cache_is_old = check_caching()
# Only fail if BOTH conditions are bad
if boxes_status == 400 and cache_is_old:
return 503
return 200
except redis.RedisError as e:
# If Redis is completely unavailable, still allow the service to be ready
print(f"Redis error during readiness check: {e}")
return 200