File size: 14,467 Bytes
56c063a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
#!/usr/bin/env python3
"""

System Startup Script for MCP AI Data Scientist

Coordinates the startup of all system components in the correct order.

"""

import asyncio
import logging
import sys
import os
import time
import subprocess
import signal
from pathlib import Path
from typing import Dict, List, Optional
from datetime import datetime

# Add project root to path
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from shared.config import settings
from shared.integration_coordinator import integration_coordinator
from shared.monitoring import monitoring_system, get_logger
from shared.error_handling import error_handler, ErrorContext


class SystemManager:
    """Manages the startup and shutdown of all system components."""
    
    def __init__(self):
        self.logger = get_logger("system_manager")
        self.processes: Dict[str, subprocess.Popen] = {}
        self.shutdown_requested = False
        
        # Setup signal handlers
        signal.signal(signal.SIGINT, self._signal_handler)
        signal.signal(signal.SIGTERM, self._signal_handler)
    
    def _signal_handler(self, signum, frame):
        """Handle shutdown signals."""
        self.logger.info(f"Received signal {signum}, initiating shutdown...")
        self.shutdown_requested = True
    
    async def start_system(self) -> bool:
        """Start all system components."""
        
        self.logger.info("πŸš€ Starting MCP AI Data Scientist System...")
        
        try:
            # Step 1: Initialize system via integration coordinator
            self.logger.info("πŸ“‹ Initializing system components...")
            success = await integration_coordinator.initialize_system()
            
            if not success:
                self.logger.error("❌ System initialization failed")
                return False
            
            # Step 2: Start MCP servers
            await self._start_mcp_servers()
            
            # Step 3: Start orchestrator
            await self._start_orchestrator()
            
            # Step 4: Start Streamlit UI (optional)
            if self._should_start_streamlit():
                await self._start_streamlit()
            
            # Step 5: Run health checks
            await self._run_health_checks()
            
            self.logger.info("βœ… System startup completed successfully")
            self.logger.info("🌐 System is ready to accept requests")
            
            return True
            
        except Exception as e:
            self.logger.error(f"❌ System startup failed: {e}")
            
            # Handle startup error
            await error_handler.handle_error(
                e,
                ErrorContext(
                    component="system_manager",
                    operation="start_system"
                )
            )
            
            return False
    
    async def _start_mcp_servers(self):
        """Start all MCP servers."""
        
        self.logger.info("πŸ”Œ Starting MCP servers...")
        
        mcp_servers = [
            ("data_cleaning", "mcp_servers/data_cleaning/run_server.py"),
            ("hypothesis_testing", "mcp_servers/hypothesis_testing/run_server.py"),
            ("preprocessing", "mcp_servers/preprocessing/run_server.py"),
            ("feature_engineering", "mcp_servers/feature_engineering/run_server.py"),
            ("model_training", "mcp_servers/model_training/run_server.py"),
            ("action_generation", "mcp_servers/action_generation/run_server.py")
        ]
        
        for server_name, script_path in mcp_servers:
            try:
                script_full_path = project_root / script_path
                
                if not script_full_path.exists():
                    self.logger.warning(f"⚠️ MCP server script not found: {script_path}")
                    continue
                
                # Start server process
                process = subprocess.Popen(
                    [sys.executable, str(script_full_path)],
                    stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE,
                    cwd=project_root
                )
                
                self.processes[server_name] = process
                self.logger.info(f"βœ… Started MCP server: {server_name} (PID: {process.pid})")
                
                # Give server time to start
                await asyncio.sleep(1)
                
            except Exception as e:
                self.logger.error(f"❌ Failed to start MCP server {server_name}: {e}")
    
    async def _start_orchestrator(self):
        """Start the orchestrator service."""
        
        self.logger.info("🎼 Starting orchestrator...")
        
        try:
            orchestrator_script = project_root / "orchestrator" / "main.py"
            
            if not orchestrator_script.exists():
                raise Exception("Orchestrator script not found")
            
            # Start orchestrator process
            process = subprocess.Popen(
                [sys.executable, "-m", "orchestrator.main"],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                cwd=project_root
            )
            
            self.processes["orchestrator"] = process
            self.logger.info(f"βœ… Started orchestrator (PID: {process.pid})")
            
            # Wait for orchestrator to be ready
            await self._wait_for_service("orchestrator", f"http://localhost:{settings.fastapi_port}/health")
            
        except Exception as e:
            self.logger.error(f"❌ Failed to start orchestrator: {e}")
            raise
    
    async def _start_streamlit(self):
        """Start the Streamlit UI."""
        
        self.logger.info("🎨 Starting Streamlit UI...")
        
        try:
            streamlit_script = project_root / "streamlit_app" / "main.py"
            
            if not streamlit_script.exists():
                raise Exception("Streamlit script not found")
            
            # Start Streamlit process
            process = subprocess.Popen(
                [
                    sys.executable, "-m", "streamlit", "run",
                    str(streamlit_script),
                    "--server.port", "8501",
                    "--server.address", "0.0.0.0"
                ],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                cwd=project_root
            )
            
            self.processes["streamlit"] = process
            self.logger.info(f"βœ… Started Streamlit UI (PID: {process.pid})")
            self.logger.info("🌐 Streamlit UI available at: http://localhost:8501")
            
        except Exception as e:
            self.logger.error(f"❌ Failed to start Streamlit: {e}")
    
    def _should_start_streamlit(self) -> bool:
        """Check if Streamlit should be started."""
        
        # Check command line arguments
        if "--no-ui" in sys.argv:
            return False
        
        # Check environment variable
        if os.getenv("NO_STREAMLIT", "").lower() in ["true", "1", "yes"]:
            return False
        
        return True
    
    async def _wait_for_service(self, service_name: str, health_url: str, timeout: int = 30):
        """Wait for a service to be ready."""
        
        import requests
        
        start_time = time.time()
        
        while time.time() - start_time < timeout:
            try:
                response = requests.get(health_url, timeout=5)
                if response.status_code == 200:
                    self.logger.info(f"βœ… {service_name} is ready")
                    return
            except:
                pass
            
            await asyncio.sleep(1)
        
        raise Exception(f"{service_name} did not become ready within {timeout} seconds")
    
    async def _run_health_checks(self):
        """Run comprehensive health checks."""
        
        self.logger.info("πŸ₯ Running health checks...")
        
        try:
            # Check orchestrator health
            import requests
            
            health_url = f"http://localhost:{settings.fastapi_port}/health/detailed"
            response = requests.get(health_url, timeout=10)
            
            if response.status_code == 200:
                health_data = response.json()
                
                if health_data.get("status") == "healthy":
                    self.logger.info("βœ… All health checks passed")
                else:
                    self.logger.warning("⚠️ Some health checks failed")
                    self.logger.warning(f"Health status: {health_data}")
            else:
                self.logger.warning(f"⚠️ Health check returned status {response.status_code}")
                
        except Exception as e:
            self.logger.error(f"❌ Health check failed: {e}")
    
    async def monitor_system(self):
        """Monitor system health and processes."""
        
        self.logger.info("πŸ‘οΈ Starting system monitoring...")
        
        while not self.shutdown_requested:
            try:
                # Check process health
                dead_processes = []
                
                for name, process in self.processes.items():
                    if process.poll() is not None:
                        dead_processes.append(name)
                        self.logger.error(f"πŸ’€ Process {name} has died (exit code: {process.returncode})")
                
                # Remove dead processes
                for name in dead_processes:
                    del self.processes[name]
                
                # If critical processes died, initiate shutdown
                if "orchestrator" in dead_processes:
                    self.logger.error("🚨 Critical process (orchestrator) died, initiating shutdown")
                    self.shutdown_requested = True
                
                await asyncio.sleep(10)  # Check every 10 seconds
                
            except Exception as e:
                self.logger.error(f"Error in system monitoring: {e}")
                await asyncio.sleep(10)
    
    async def shutdown_system(self):
        """Gracefully shutdown all system components."""
        
        self.logger.info("πŸ›‘ Shutting down system...")
        
        try:
            # Shutdown processes in reverse order
            shutdown_order = ["streamlit", "orchestrator"] + [
                name for name in self.processes.keys()
                if name not in ["streamlit", "orchestrator"]
            ]
            
            for process_name in shutdown_order:
                if process_name in self.processes:
                    process = self.processes[process_name]
                    
                    self.logger.info(f"πŸ›‘ Stopping {process_name}...")
                    
                    # Try graceful shutdown first
                    process.terminate()
                    
                    try:
                        # Wait for graceful shutdown
                        process.wait(timeout=10)
                        self.logger.info(f"βœ… {process_name} stopped gracefully")
                    except subprocess.TimeoutExpired:
                        # Force kill if graceful shutdown fails
                        self.logger.warning(f"⚠️ Force killing {process_name}")
                        process.kill()
                        process.wait()
            
            # Shutdown integration coordinator
            await integration_coordinator.shutdown_system()
            
            self.logger.info("βœ… System shutdown completed")
            
        except Exception as e:
            self.logger.error(f"Error during shutdown: {e}")
    
    def print_system_info(self):
        """Print system information and access URLs."""
        
        print("\n" + "="*80)
        print("πŸ€– MCP AI DATA SCIENTIST SYSTEM")
        print("="*80)
        print(f"🎼 Orchestrator API: http://localhost:{settings.fastapi_port}")
        print(f"πŸ“Š API Documentation: http://localhost:{settings.fastapi_port}/docs")
        print(f"πŸ₯ Health Check: http://localhost:{settings.fastapi_port}/health")
        
        if "streamlit" in self.processes:
            print(f"🎨 Streamlit UI: http://localhost:8501")
        
        print(f"πŸ“ Logs: {settings.log_file}")
        print("\nRunning processes:")
        
        for name, process in self.processes.items():
            status = "running" if process.poll() is None else f"stopped (exit code: {process.returncode})"
            print(f"  β€’ {name}: PID {process.pid} - {status}")
        
        print("\nπŸ’‘ Press Ctrl+C to shutdown the system")
        print("="*80)


async def main():
    """Main entry point."""
    
    system_manager = SystemManager()
    
    try:
        # Parse command line arguments
        if "--help" in sys.argv or "-h" in sys.argv:
            print("MCP AI Data Scientist System Startup")
            print("Usage: python scripts/start_system.py [options]")
            print("Options:")
            print("  --no-ui    Don't start Streamlit UI")
            print("  --help     Show this help message")
            return
        
        # Start system
        success = await system_manager.start_system()
        
        if not success:
            print("❌ Failed to start system")
            sys.exit(1)
        
        # Print system information
        system_manager.print_system_info()
        
        # Monitor system
        await system_manager.monitor_system()
        
    except KeyboardInterrupt:
        print("\nπŸ›‘ Shutdown requested by user")
    except Exception as e:
        print(f"❌ System error: {e}")
        sys.exit(1)
    finally:
        # Shutdown system
        await system_manager.shutdown_system()


if __name__ == "__main__":
    asyncio.run(main())