|
|
|
|
|
""" |
|
|
DTO Crash Notifier - Handles service crashes and sends notifications |
|
|
Supervisor event listener for crash detection and alerting |
|
|
""" |
|
|
|
|
|
import sys |
|
|
import os |
|
|
import json |
|
|
import asyncio |
|
|
from datetime import datetime, timezone |
|
|
from supervisor import childutils |
|
|
from nats.aio.client import Client as NATS |
|
|
|
|
|
class DTOCrashNotifier: |
|
|
def __init__(self): |
|
|
self.critical_services = [ |
|
|
'dto-nats-server', |
|
|
'dto-dragonfly-node1', |
|
|
'dto-dragonfly-node2', |
|
|
'dto-dragonfly-node3', |
|
|
'dto-janusgraph' |
|
|
] |
|
|
self.nats_servers = ["nats://localhost:4222"] |
|
|
self.nats_client = None |
|
|
|
|
|
async def connect_nats(self): |
|
|
"""Connect to NATS for event publishing""" |
|
|
try: |
|
|
self.nats_client = NATS() |
|
|
await self.nats_client.connect(servers=self.nats_servers) |
|
|
return True |
|
|
except Exception as e: |
|
|
print(f"NATS connection failed: {e}") |
|
|
return False |
|
|
|
|
|
def get_crash_severity(self, process_name: str, exit_code: int) -> str: |
|
|
"""Determine crash severity based on process and exit code""" |
|
|
if process_name in self.critical_services: |
|
|
return 'critical' |
|
|
elif exit_code in [1, 2, 130, 143]: |
|
|
return 'warning' |
|
|
else: |
|
|
return 'info' |
|
|
|
|
|
def get_restart_recommendation(self, process_name: str, exit_code: int) -> str: |
|
|
"""Get restart recommendation based on crash type""" |
|
|
if exit_code == 0: |
|
|
return 'normal_exit' |
|
|
elif exit_code in [1, 2]: |
|
|
return 'automatic_restart' |
|
|
elif exit_code in [130, 143]: |
|
|
return 'manual_investigation' |
|
|
elif exit_code == 137: |
|
|
return 'check_memory_limits' |
|
|
else: |
|
|
return 'investigate_logs' |
|
|
|
|
|
async def send_crash_notification(self, crash_data: dict): |
|
|
"""Send crash notification via NATS""" |
|
|
if not self.nats_client: |
|
|
if not await self.connect_nats(): |
|
|
return False |
|
|
|
|
|
try: |
|
|
|
|
|
await self.nats_client.publish( |
|
|
"dto.events.alerts.service_crash", |
|
|
json.dumps(crash_data).encode() |
|
|
) |
|
|
|
|
|
|
|
|
if crash_data['severity'] in ['critical', 'warning']: |
|
|
slack_alert = { |
|
|
'event_type': 'SERVICE_CRASH', |
|
|
'title': f"DTO Service Crash: {crash_data['process_name']}", |
|
|
'message': f"Service {crash_data['process_name']} crashed with exit code {crash_data['exit_code']}", |
|
|
'severity': crash_data['severity'], |
|
|
'timestamp': crash_data['timestamp'] |
|
|
} |
|
|
|
|
|
await self.nats_client.publish( |
|
|
"dto.events.slack.urgent_alert", |
|
|
json.dumps(slack_alert).encode() |
|
|
) |
|
|
|
|
|
return True |
|
|
|
|
|
except Exception as e: |
|
|
print(f"Failed to send crash notification: {e}") |
|
|
return False |
|
|
|
|
|
def log_crash_details(self, crash_data: dict): |
|
|
"""Log crash details to file""" |
|
|
log_file = "/data/adaptai/platform/dataops/dto/logs/service-crashes.log" |
|
|
|
|
|
try: |
|
|
with open(log_file, 'a') as f: |
|
|
f.write(f"{datetime.now().isoformat()} - {json.dumps(crash_data)}\n") |
|
|
except Exception as e: |
|
|
print(f"Failed to write crash log: {e}") |
|
|
|
|
|
def generate_crash_report(self, process_name: str, exit_code: int, pid: int) -> dict: |
|
|
"""Generate comprehensive crash report""" |
|
|
crash_data = { |
|
|
'event_type': 'SERVICE_CRASH', |
|
|
'process_name': process_name, |
|
|
'pid': pid, |
|
|
'exit_code': exit_code, |
|
|
'severity': self.get_crash_severity(process_name, exit_code), |
|
|
'restart_recommendation': self.get_restart_recommendation(process_name, exit_code), |
|
|
'timestamp': datetime.now(timezone.utc).isoformat(), |
|
|
'is_critical_service': process_name in self.critical_services |
|
|
} |
|
|
|
|
|
|
|
|
if exit_code == 0: |
|
|
crash_data['description'] = "Service exited normally" |
|
|
elif exit_code == 1: |
|
|
crash_data['description'] = "General error - check service logs" |
|
|
elif exit_code == 2: |
|
|
crash_data['description'] = "Misuse of shell command" |
|
|
elif exit_code == 130: |
|
|
crash_data['description'] = "Service terminated by SIGINT (Ctrl+C)" |
|
|
elif exit_code == 137: |
|
|
crash_data['description'] = "Service killed by SIGKILL - possible OOM" |
|
|
elif exit_code == 143: |
|
|
crash_data['description'] = "Service terminated by SIGTERM" |
|
|
else: |
|
|
crash_data['description'] = f"Service exited with unknown code {exit_code}" |
|
|
|
|
|
return crash_data |
|
|
|
|
|
async def handle_crash(self, headers: dict, payload: str): |
|
|
"""Handle service crash event""" |
|
|
process_name = headers.get('processname', 'unknown') |
|
|
event_name = headers.get('eventname', 'unknown') |
|
|
pid = int(headers.get('pid', 0)) |
|
|
|
|
|
|
|
|
try: |
|
|
payload_data = dict(token.split(':') for token in payload.split() if ':' in token) |
|
|
exit_code = int(payload_data.get('expected', -1)) |
|
|
except: |
|
|
exit_code = -1 |
|
|
|
|
|
if event_name == 'PROCESS_STATE_EXITED': |
|
|
print(f"Service crash detected: {process_name} (PID {pid}) exited with code {exit_code}") |
|
|
|
|
|
|
|
|
crash_data = self.generate_crash_report(process_name, exit_code, pid) |
|
|
|
|
|
|
|
|
self.log_crash_details(crash_data) |
|
|
|
|
|
|
|
|
await self.send_crash_notification(crash_data) |
|
|
|
|
|
|
|
|
print(f"Crash Report: {process_name}") |
|
|
print(f" Exit Code: {exit_code}") |
|
|
print(f" Severity: {crash_data['severity']}") |
|
|
print(f" Recommendation: {crash_data['restart_recommendation']}") |
|
|
print(f" Description: {crash_data['description']}") |
|
|
|
|
|
|
|
|
if process_name in self.critical_services: |
|
|
print(f"CRITICAL: {process_name} is a critical service!") |
|
|
print(" Impact: DTO operations may be degraded") |
|
|
print(" Action: Immediate investigation required") |
|
|
|
|
|
async def run_async(self): |
|
|
"""Async supervisor event listener loop""" |
|
|
print("Starting DTO Crash Notifier...") |
|
|
print(f"Monitoring critical services: {', '.join(self.critical_services)}") |
|
|
|
|
|
|
|
|
await self.connect_nats() |
|
|
|
|
|
while True: |
|
|
try: |
|
|
|
|
|
headers, payload = childutils.listener.wait(sys.stdin, sys.stdout) |
|
|
|
|
|
|
|
|
await self.handle_crash(headers, payload) |
|
|
|
|
|
|
|
|
childutils.listener.ok(sys.stdout) |
|
|
|
|
|
except KeyboardInterrupt: |
|
|
print("Crash notifier stopped") |
|
|
break |
|
|
except Exception as e: |
|
|
print(f"Crash notifier error: {e}") |
|
|
childutils.listener.fail(sys.stdout) |
|
|
|
|
|
|
|
|
if self.nats_client: |
|
|
await self.nats_client.close() |
|
|
|
|
|
def run(self): |
|
|
"""Main entry point - run async loop""" |
|
|
asyncio.run(self.run_async()) |
|
|
|
|
|
if __name__ == "__main__": |
|
|
notifier = DTOCrashNotifier() |
|
|
notifier.run() |