File size: 8,049 Bytes
fd357f4 |
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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 |
#!/usr/bin/env python3
"""
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]: # Common error codes
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]: # SIGINT, SIGTERM
return 'manual_investigation'
elif exit_code == 137: # SIGKILL
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:
# Publish crash event
await self.nats_client.publish(
"dto.events.alerts.service_crash",
json.dumps(crash_data).encode()
)
# Also publish to Slack-specific topic for immediate notification
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
}
# Add additional context
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))
# Parse payload for exit code
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}")
# Generate crash report
crash_data = self.generate_crash_report(process_name, exit_code, pid)
# Log crash details
self.log_crash_details(crash_data)
# Send notifications
await self.send_crash_notification(crash_data)
# Print crash summary
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']}")
# Special handling for critical services
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)}")
# Connect to NATS
await self.connect_nats()
while True:
try:
# Read supervisor event
headers, payload = childutils.listener.wait(sys.stdin, sys.stdout)
# Handle the crash
await self.handle_crash(headers, payload)
# Acknowledge the event
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)
# Clean up NATS connection
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() |