#!/usr/bin/env python3 """ DTO Memory Monitor - Monitors memory usage of DTO services Supervisor event listener for memory monitoring and alerting """ import sys import os import psutil import json from datetime import datetime, timezone from supervisor import childutils class DTOMemoryMonitor: def __init__(self): self.memory_thresholds = { 'warning': 80, # 80% memory usage 'critical': 90, # 90% memory usage } self.process_limits = { 'dto-dragonfly-node1': 8 * 1024 * 1024 * 1024, # 8GB 'dto-dragonfly-node2': 8 * 1024 * 1024 * 1024, # 8GB 'dto-dragonfly-node3': 8 * 1024 * 1024 * 1024, # 8GB 'dto-janusgraph': 16 * 1024 * 1024 * 1024, # 16GB 'dto-lineage-handler': 1 * 1024 * 1024 * 1024, # 1GB 'dto-slack-automation': 512 * 1024 * 1024, # 512MB 'dto-jira-automation': 512 * 1024 * 1024, # 512MB 'dto-confluence-automation': 512 * 1024 * 1024, # 512MB } def get_process_memory_info(self, pid: int) -> dict: """Get memory information for a process""" try: process = psutil.Process(pid) memory_info = process.memory_info() memory_percent = process.memory_percent() return { 'pid': pid, 'memory_rss': memory_info.rss, 'memory_vms': memory_info.vms, 'memory_percent': memory_percent, 'memory_rss_mb': memory_info.rss / (1024 * 1024), 'timestamp': datetime.now(timezone.utc).isoformat() } except (psutil.NoSuchProcess, psutil.AccessDenied): return None def check_memory_threshold(self, process_name: str, memory_bytes: int) -> str: """Check if process memory exceeds thresholds""" limit = self.process_limits.get(process_name) if not limit: return 'normal' usage_percent = (memory_bytes / limit) * 100 if usage_percent >= self.memory_thresholds['critical']: return 'critical' elif usage_percent >= self.memory_thresholds['warning']: return 'warning' else: return 'normal' def send_memory_alert(self, process_name: str, pid: int, memory_info: dict, alert_level: str): """Send memory alert via supervisor stdout""" alert_data = { 'event_type': 'MEMORY_ALERT', 'process_name': process_name, 'pid': pid, 'alert_level': alert_level, 'memory_info': memory_info, 'timestamp': datetime.now(timezone.utc).isoformat() } # Write to supervisor stdout for logging print(f"MEMORY_ALERT: {json.dumps(alert_data)}") sys.stdout.flush() # Also write to separate memory log log_file = "/data/adaptai/platform/dataops/dto/logs/memory-alerts.log" try: with open(log_file, 'a') as f: f.write(f"{datetime.now().isoformat()} - {json.dumps(alert_data)}\n") except Exception as e: print(f"Failed to write memory alert log: {e}") def monitor_process(self, headers: dict, payload: str): """Monitor a process memory usage""" process_name = headers.get('processname', 'unknown') event_name = headers.get('eventname', 'unknown') pid = int(headers.get('pid', 0)) if event_name == 'PROCESS_STATE_RUNNING' and pid > 0: memory_info = self.get_process_memory_info(pid) if memory_info: alert_level = self.check_memory_threshold( process_name, memory_info['memory_rss'] ) # Log memory usage print(f"Memory check: {process_name} (PID {pid}) - " f"{memory_info['memory_rss_mb']:.1f}MB - {alert_level}") # Send alert if threshold exceeded if alert_level in ['warning', 'critical']: self.send_memory_alert(process_name, pid, memory_info, alert_level) # If critical, log additional system info if alert_level == 'critical': system_memory = psutil.virtual_memory() print(f"CRITICAL: System memory usage: {system_memory.percent}% " f"({system_memory.used / (1024**3):.1f}GB used)") def run(self): """Main supervisor event listener loop""" print("Starting DTO Memory Monitor...") print(f"Monitoring thresholds: Warning {self.memory_thresholds['warning']}%, " f"Critical {self.memory_thresholds['critical']}%") while True: try: # Read supervisor event headers, payload = childutils.listener.wait(sys.stdin, sys.stdout) # Monitor the process self.monitor_process(headers, payload) # Acknowledge the event childutils.listener.ok(sys.stdout) except KeyboardInterrupt: print("Memory monitor stopped") break except Exception as e: print(f"Memory monitor error: {e}") childutils.listener.fail(sys.stdout) if __name__ == "__main__": monitor = DTOMemoryMonitor() monitor.run()