adaptai / platform /dataops /dto /services /health_monitor.py
ADAPT-Chase's picture
Add files using upload-large-folder tool
fd357f4 verified
raw
history blame
14.3 kB
#!/usr/bin/env python3
"""
DTO Health Monitor - Monitors service health and publishes status events
Integrates with supervisord to track service lifecycle and performance
"""
import asyncio
import json
import psutil
import time
from typing import Dict, Any, List
from datetime import datetime, timezone
from nats.aio.client import Client as NATS
import subprocess
import requests
class DTOHealthMonitor:
def __init__(self, nats_servers: list = ["nats://localhost:4222"]):
self.nats_servers = nats_servers
self.nats_client = NATS()
self.check_interval = 30 # 30 seconds
self.services = {
'nats': {'port': 4222, 'type': 'infrastructure'},
'dragonfly-node1': {'port': 18000, 'type': 'cache'},
'dragonfly-node2': {'port': 18001, 'type': 'cache'},
'dragonfly-node3': {'port': 18002, 'type': 'cache'},
'janusgraph': {'port': 8182, 'type': 'graph'},
'scylla': {'port': 9042, 'type': 'database'},
'elasticsearch': {'port': 9200, 'type': 'search'}
}
async def connect(self) -> bool:
"""Connect to NATS for health event publishing"""
try:
await self.nats_client.connect(servers=self.nats_servers)
print("βœ… Health monitor connected to NATS")
return True
except Exception as e:
print(f"❌ Health monitor NATS connection failed: {e}")
return False
def check_port_health(self, port: int) -> bool:
"""Check if a service port is responding"""
try:
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(5)
result = sock.connect_ex(('localhost', port))
sock.close()
return result == 0
except Exception:
return False
def check_supervisor_status(self) -> Dict[str, Any]:
"""Check supervisord service status"""
try:
result = subprocess.run([
'supervisorctl', '-c', '/data/adaptai/platform/dataops/dto/services/supervisord.conf',
'status'
], capture_output=True, text=True, timeout=10)
if result.returncode == 0:
services = {}
for line in result.stdout.strip().split('\n'):
if line.strip():
parts = line.split()
if len(parts) >= 2:
service_name = parts[0]
status = parts[1]
services[service_name] = {
'status': status,
'running': status == 'RUNNING'
}
return services
else:
print(f"❌ Supervisorctl error: {result.stderr}")
return {}
except Exception as e:
print(f"❌ Error checking supervisor status: {e}")
return {}
def get_system_metrics(self) -> Dict[str, Any]:
"""Get system resource metrics"""
try:
# CPU usage
cpu_percent = psutil.cpu_percent(interval=1)
# Memory usage
memory = psutil.virtual_memory()
# Disk usage for DTO data directory
dto_disk = psutil.disk_usage('/data/adaptai/platform/dataops/dto')
# Network I/O
network = psutil.net_io_counters()
return {
'cpu_percent': cpu_percent,
'memory_percent': memory.percent,
'memory_available_gb': memory.available / (1024**3),
'memory_used_gb': memory.used / (1024**3),
'disk_free_gb': dto_disk.free / (1024**3),
'disk_used_gb': dto_disk.used / (1024**3),
'disk_percent': (dto_disk.used / dto_disk.total) * 100,
'network_bytes_sent': network.bytes_sent,
'network_bytes_recv': network.bytes_recv,
'timestamp': datetime.now(timezone.utc).isoformat()
}
except Exception as e:
print(f"❌ Error getting system metrics: {e}")
return {}
def check_dragonfly_cluster_health(self) -> Dict[str, Any]:
"""Check Dragonfly cluster health"""
cluster_health = {
'healthy_nodes': 0,
'total_nodes': 3,
'node_status': {}
}
for i in range(1, 4):
port = 18000 + i - 1
node_name = f"node{i}"
try:
# Simple connection test
if self.check_port_health(port):
cluster_health['healthy_nodes'] += 1
cluster_health['node_status'][node_name] = {
'status': 'healthy',
'port': port,
'last_check': datetime.now(timezone.utc).isoformat()
}
else:
cluster_health['node_status'][node_name] = {
'status': 'unhealthy',
'port': port,
'last_check': datetime.now(timezone.utc).isoformat()
}
except Exception as e:
cluster_health['node_status'][node_name] = {
'status': 'error',
'port': port,
'error': str(e),
'last_check': datetime.now(timezone.utc).isoformat()
}
cluster_health['cluster_healthy'] = cluster_health['healthy_nodes'] >= 2
return cluster_health
def check_janusgraph_health(self) -> Dict[str, Any]:
"""Check JanusGraph health"""
try:
if self.check_port_health(8182):
# Try to connect via Gremlin
try:
# Simple WebSocket connection test
import websocket
ws = websocket.create_connection("ws://localhost:8182/gremlin", timeout=5)
ws.close()
return {
'status': 'healthy',
'port': 8182,
'gremlin_endpoint': 'available',
'last_check': datetime.now(timezone.utc).isoformat()
}
except Exception as ws_error:
return {
'status': 'degraded',
'port': 8182,
'gremlin_endpoint': 'unavailable',
'error': str(ws_error),
'last_check': datetime.now(timezone.utc).isoformat()
}
else:
return {
'status': 'unhealthy',
'port': 8182,
'last_check': datetime.now(timezone.utc).isoformat()
}
except Exception as e:
return {
'status': 'error',
'error': str(e),
'last_check': datetime.now(timezone.utc).isoformat()
}
async def check_integration_health(self) -> Dict[str, Any]:
"""Check health of integration services"""
integrations = {
'slack': {'healthy': False, 'last_activity': None},
'jira': {'healthy': False, 'last_activity': None},
'confluence': {'healthy': False, 'last_activity': None}
}
try:
# Check if integration services are responsive
# This could be enhanced to actually test API connectivity
supervisor_status = self.check_supervisor_status()
slack_running = supervisor_status.get('dto-slack-automation', {}).get('running', False)
jira_running = supervisor_status.get('dto-jira-automation', {}).get('running', False)
confluence_running = supervisor_status.get('dto-confluence-automation', {}).get('running', False)
integrations['slack']['healthy'] = slack_running
integrations['jira']['healthy'] = jira_running
integrations['confluence']['healthy'] = confluence_running
return integrations
except Exception as e:
print(f"❌ Error checking integration health: {e}")
return integrations
async def publish_health_event(self, health_data: Dict[str, Any]):
"""Publish comprehensive health status event"""
try:
health_event = {
'event_id': f"health-check-{int(time.time())}",
'event_type': 'HEALTH_CHECK',
'timestamp': datetime.now(timezone.utc).isoformat(),
'health_data': health_data
}
await self.nats_client.publish(
"dto.events.health.status",
json.dumps(health_event).encode()
)
# Also publish specific alerts for unhealthy services
for service_name, service_data in health_data.get('services', {}).items():
if not service_data.get('healthy', True):
alert_event = {
'event_id': f"service-alert-{service_name}-{int(time.time())}",
'event_type': 'SERVICE_UNHEALTHY',
'timestamp': datetime.now(timezone.utc).isoformat(),
'service_name': service_name,
'service_data': service_data,
'severity': 'critical' if service_data.get('type') == 'infrastructure' else 'warning'
}
await self.nats_client.publish(
"dto.events.alerts.service_unhealthy",
json.dumps(alert_event).encode()
)
except Exception as e:
print(f"❌ Error publishing health event: {e}")
async def perform_health_check(self):
"""Perform comprehensive health check"""
print(f"πŸ” Performing health check at {datetime.now(timezone.utc).strftime('%H:%M:%S UTC')}")
# Get supervisor service status
supervisor_status = self.check_supervisor_status()
# Check individual service health
service_health = {}
# Infrastructure services
service_health['nats'] = {
'healthy': self.check_port_health(4222),
'type': 'infrastructure',
'port': 4222,
'supervisor_status': supervisor_status.get('dto-nats-server', {})
}
# Dragonfly cluster
dragonfly_health = self.check_dragonfly_cluster_health()
service_health['dragonfly'] = {
'healthy': dragonfly_health['cluster_healthy'],
'type': 'cache',
'cluster_data': dragonfly_health
}
# JanusGraph
janusgraph_health = self.check_janusgraph_health()
service_health['janusgraph'] = {
'healthy': janusgraph_health['status'] == 'healthy',
'type': 'graph',
'service_data': janusgraph_health
}
# External dependencies
service_health['scylla'] = {
'healthy': self.check_port_health(9042),
'type': 'database',
'port': 9042
}
service_health['elasticsearch'] = {
'healthy': self.check_port_health(9200),
'type': 'search',
'port': 9200
}
# Integration services
integration_health = await self.check_integration_health()
service_health.update(integration_health)
# System metrics
system_metrics = self.get_system_metrics()
# Compile comprehensive health data
health_data = {
'overall_healthy': all(s.get('healthy', False) for s in service_health.values()),
'services': service_health,
'system_metrics': system_metrics,
'supervisor_services': supervisor_status,
'check_timestamp': datetime.now(timezone.utc).isoformat()
}
# Report health status
healthy_services = sum(1 for s in service_health.values() if s.get('healthy', False))
total_services = len(service_health)
print(f"πŸ“Š Health Check Results: {healthy_services}/{total_services} services healthy")
if not health_data['overall_healthy']:
unhealthy_services = [name for name, data in service_health.items() if not data.get('healthy', False)]
print(f"⚠️ Unhealthy services: {', '.join(unhealthy_services)}")
# Publish health event
await self.publish_health_event(health_data)
return health_data
async def start_monitoring(self):
"""Start continuous health monitoring"""
try:
print("πŸ₯ Starting DTO Health Monitor")
print(f"Check interval: {self.check_interval} seconds")
print("Monitoring services: NATS, Dragonfly, JanusGraph, ScyllaDB, Elasticsearch, Integrations")
while True:
try:
await self.perform_health_check()
await asyncio.sleep(self.check_interval)
except Exception as e:
print(f"❌ Health check error: {e}")
await asyncio.sleep(self.check_interval)
except KeyboardInterrupt:
print("\nπŸ›‘ Stopping health monitor...")
except Exception as e:
print(f"❌ Health monitor error: {e}")
finally:
await self.nats_client.close()
# CLI entry point
async def main():
monitor = DTOHealthMonitor()
if await monitor.connect():
await monitor.start_monitoring()
else:
print("❌ Failed to start health monitor")
if __name__ == "__main__":
asyncio.run(main())