File size: 4,755 Bytes
7df213d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from flask import Flask, request, jsonify
import os
import logging
import signal
import atexit
from datetime import datetime
import traceback
from pathlib import Path
from typing import Dict, Any, List, Optional
import json
import socket
from shared_model import SharedModel

class BaseAgent:
    def __init__(self, name: str, port: Optional[int] = None):
        self.name = name
        self.app = Flask(name)
        self.logger = logging.getLogger(name)
        
        # Initialize state
        self.is_healthy = True
        self.start_time = datetime.now()
        self.pid = os.getpid()
        
        # Initialize tools registry
        self.tools = {}
        self.shared_model = SharedModel.get_instance()
        
        # Setup port
        self.port = port or self._setup_port()
        
        # Register cleanup handlers
        self._register_cleanup_handlers()
        
        # Register standard routes
        self.register_routes()
        
        self.logger.info(f"Initialized {name} agent on port {self.port} with PID {self.pid}")
        
    def _setup_port(self) -> int:
        """Setup and register port for the agent"""
        try:
            # Try to load from config first
            port_file = Path(__file__).parent / "data" / "agent_ports.json"
            port_file.parent.mkdir(exist_ok=True)
            
            if port_file.exists():
                with open(port_file) as f:
                    ports = json.load(f)
                    if self.name in ports:
                        # Verify port is still available
                        if self._is_port_available(ports[self.name]):
                            return ports[self.name]
            
            # Find new available port
            port = self._find_available_port()
            
            # Save to config
            ports = {}
            if port_file.exists():
                with open(port_file) as f:
                    ports = json.load(f)
            
            ports[self.name] = port
            
            with open(port_file, 'w') as f:
                json.dump(ports, f, indent=2)
                
            return port
            
        except Exception as e:
            self.logger.error(f"Error setting up port: {str(e)}")
            # Fall back to random available port
            return self._find_available_port()
            
    def _is_port_available(self, port: int) -> bool:
        """Check if a port is available"""
        try:
            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
                s.bind(('localhost', port))
                return True
        except:
            return False
            
    def _find_available_port(self, start: int = 8001, end: int = 8999) -> int:
        """Find an available port in the given range"""
        for port in range(start, end + 1):
            if port not in self.shared_model.active_ports and self._is_port_available(port):
                return port
        raise RuntimeError("No available ports found")
        
    def _register_cleanup_handlers(self):
        """Register cleanup handlers for graceful shutdown"""
        def cleanup():
            self.logger.info(f"Cleaning up {self.name} agent...")
            self.is_healthy = False
            
        atexit.register(cleanup)
        signal.signal(signal.SIGTERM, lambda *args: cleanup())
        signal.signal(signal.SIGINT, lambda *args: cleanup())
        
    def register_routes(self):
        """Register standard HTTP routes"""
        @self.app.route('/health', methods=['GET'])
        def health_check():
            return jsonify({
                'status': 'healthy' if self.is_healthy else 'unhealthy',
                'uptime': str(datetime.now() - self.start_time),
                'pid': self.pid
            })
            
        @self.app.route('/execute', methods=['POST'])
        def execute():
            try:
                data = request.get_json()
                result = self.process_request(data)
                return jsonify(result)
            except Exception as e:
                self.logger.error(f"Error processing request: {traceback.format_exc()}")
                return jsonify({
                    'error': str(e),
                    'status': 'error'
                }), 500
                
    def process_request(self, data: Dict[str, Any]) -> Dict[str, Any]:
        """Process incoming requests - to be implemented by child classes"""
        raise NotImplementedError("Child classes must implement process_request")
        
    def run(self):
        """Start the agent"""
        self.shared_model.register_agent(self.name, self.port)
        self.app.run(host='0.0.0.0', port=self.port)