adaptai / platform /dbops /tools /health_guard.py
ADAPT-Chase's picture
Add files using upload-large-folder tool
503b0e9 verified
#!/usr/bin/env python3
import json, os, subprocess, time, glob, socket, getpass
DBOPS_ROOT = os.environ.get("DBOPS_ROOT", "/data/adaptai/platform/dbops")
SOCK = f"unix://{DBOPS_ROOT}/run/supervisor.sock"
HEALTH_DIR = f"{DBOPS_ROOT}/run/health"
AUDIT_DIR = f"{DBOPS_ROOT}/logs/audit"
AUDIT_FILE = os.path.join(AUDIT_DIR, "health-guard.audit.log")
# Dependency gates: if any upstream is red, stop dependents
GATES = {
"dragonfly": ["qdrant", "janusgraph"],
"redis_cluster": ["qdrant", "janusgraph"],
"scylla": ["janusgraph"],
}
# Auto-recovery settings
GREEN_STABLE_SECONDS = int(os.environ.get("HG_GREEN_STABLE_SECONDS", "30"))
RESTART_BACKOFF_SECONDS = int(os.environ.get("HG_RESTART_BACKOFF_SECONDS", "60"))
MAX_RESTARTS = int(os.environ.get("HG_MAX_RESTARTS", "3"))
RESTART_WINDOW_SECONDS = int(os.environ.get("HG_RESTART_WINDOW_SECONDS", "600"))
ENABLE_AUTOSTART = os.environ.get("HG_ENABLE_AUTOSTART", "1") in ("1", "true", "TRUE", "yes", "YES")
STATE = {
"upstream": {}, # svc -> { last_health: str, last_change: float, last_green: float }
"dep_backoff": {}, # dep -> next_allowed_restart_ts
"dep_restarts": {}, # dep -> [timestamps]
}
def supctl(cmd):
return subprocess.run(["supervisorctl", "-s", SOCK] + cmd, capture_output=True, text=True)
def sup_status():
out = supctl(["status"]).stdout.strip().splitlines()
st = {}
for line in out:
# Format: name RUNNING pid ... or STOPPED
parts = line.split()
if not parts:
continue
name = parts[0]
status = parts[1] if len(parts) > 1 else "UNKNOWN"
st[name] = status
return st
def ensure_audit_dir():
try:
os.makedirs(AUDIT_DIR, exist_ok=True)
except Exception:
pass
def audit(event: str, payload: dict):
ensure_audit_dir()
rec = {
"ts": time.time(),
"event": event,
"host": socket.gethostname(),
"user": getpass.getuser(),
}
rec.update(payload)
try:
with open(AUDIT_FILE, "a") as f:
f.write(json.dumps(rec) + "\n")
except Exception:
pass
def read_health():
statuses = {}
for path in glob.glob(os.path.join(HEALTH_DIR, "*.json")):
try:
with open(path) as f:
data = json.load(f)
svc = data.get("service")
if svc:
statuses[svc] = data
except Exception:
pass
return statuses
def is_red(status):
return status.get("health") == "red"
def now():
return time.time()
def update_upstream_state(upstream, s):
ts = now()
u = STATE["upstream"].setdefault(upstream, {"last_health": None, "last_change": ts, "last_green": 0.0})
h = s.get("health") if s else None
if h != u["last_health"]:
u["last_change"] = ts
u["last_health"] = h
if h == "green":
u["last_green"] = ts
def enforce(statuses):
# Update upstream state memory
for upstream in GATES.keys():
update_upstream_state(upstream, statuses.get(upstream))
sup_st = sup_status()
# Stop dependents if upstream red
for upstream, dependents in GATES.items():
s = statuses.get(upstream, {})
if is_red(s):
for dep in dependents:
supctl(["stop", dep])
audit("stop_dependent", {"upstream": upstream, "dependent": dep, "reason": "upstream_red"})
# Start dependents when upstream is green and stable
ts = now()
for upstream, dependents in GATES.items():
u = STATE["upstream"].get(upstream, {})
if not u or u.get("last_health") != "green":
continue
if ts - u.get("last_green", 0) < GREEN_STABLE_SECONDS:
continue # require stability window
if not ENABLE_AUTOSTART:
continue
for dep in dependents:
# Backoff control
next_ts = STATE["dep_backoff"].get(dep, 0)
if ts < next_ts:
continue
# Start only if not running
dep_status = sup_st.get(dep, "UNKNOWN")
if dep_status not in ("RUNNING",):
# rate limiting
hist = STATE["dep_restarts"].setdefault(dep, [])
# prune old
hist = [t for t in hist if ts - t < RESTART_WINDOW_SECONDS]
STATE["dep_restarts"][dep] = hist
if len(hist) >= MAX_RESTARTS:
audit("skip_restart_rate_limited", {"dependent": dep, "upstream": upstream, "window_s": RESTART_WINDOW_SECONDS, "max": MAX_RESTARTS})
continue
supctl(["start", dep])
hist.append(ts)
STATE["dep_backoff"][dep] = ts + RESTART_BACKOFF_SECONDS
audit("start_dependent", {"dependent": dep, "upstream": upstream, "reason": "upstream_green_stable", "stable_s": GREEN_STABLE_SECONDS})
def main():
while True:
st = read_health()
enforce(st)
time.sleep(15)
if __name__ == "__main__":
main()