Spaces:
Paused
Paused
Download scripts/start_system.py from VAH6002/ai_data_scientist: direct link, hf CLI and curl.
- Browser
- Download file 14.5 kB
-
https://huggingface.co/spaces/VAH6002/ai_data_scientist/resolve/main/scripts/start_system.py
- Command line
-
hf download hf://spaces/VAH6002/ai_data_scientist/scripts/start_system.py
-
curl -L -o start_system.py https://huggingface.co/spaces/VAH6002/ai_data_scientist/resolve/main/scripts/start_system.py
14.5 kB
| #!/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()) |