File size: 5,646 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
#!/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()