#!/usr/bin/env python3 """ Deployment Validation Script Validates the complete deployment of the MCP AI Data Scientist system. Checks configuration, connectivity, and functionality of all components. """ import asyncio import aiohttp import json import os import sys import time import subprocess from typing import Dict, List, Optional, Tuple from dataclasses import dataclass import logging @dataclass class ValidationResult: """Result of a validation check.""" check_name: str passed: bool message: str details: Optional[Dict] = None class DeploymentValidator: """Validates MCP AI Data Scientist deployment.""" def __init__(self): self.logger = self._setup_logging() self.results: List[ValidationResult] = [] def _setup_logging(self) -> logging.Logger: """Setup logging configuration.""" logger = logging.getLogger("deployment_validator") logger.setLevel(logging.INFO) if not logger.handlers: handler = logging.StreamHandler() formatter = logging.Formatter( '%(asctime)s - %(levelname)s - %(message)s' ) handler.setFormatter(formatter) logger.addHandler(handler) return logger def add_result(self, check_name: str, passed: bool, message: str, details: Optional[Dict] = None): """Add validation result.""" result = ValidationResult(check_name, passed, message, details) self.results.append(result) status = "✅ PASS" if passed else "❌ FAIL" self.logger.info(f"{status} - {check_name}: {message}") def validate_prerequisites(self) -> bool: """Validate deployment prerequisites.""" self.logger.info("Validating prerequisites...") # Check Docker try: result = subprocess.run(["docker", "--version"], capture_output=True, text=True) if result.returncode == 0: self.add_result("Docker Installation", True, f"Docker found: {result.stdout.strip()}") else: self.add_result("Docker Installation", False, "Docker not found or not working") return False except FileNotFoundError: self.add_result("Docker Installation", False, "Docker command not found") return False # Check Docker Compose try: result = subprocess.run(["docker-compose", "--version"], capture_output=True, text=True) if result.returncode == 0: self.add_result("Docker Compose Installation", True, f"Docker Compose found: {result.stdout.strip()}") else: self.add_result("Docker Compose Installation", False, "Docker Compose not found or not working") return False except FileNotFoundError: self.add_result("Docker Compose Installation", False, "Docker Compose command not found") return False return True def validate_configuration_files(self) -> bool: """Validate configuration files exist and are valid.""" self.logger.info("Validating configuration files...") required_files = [ "docker-compose.yml", ".env", "requirements.txt" ] all_valid = True for file in required_files: if os.path.exists(file): self.add_result(f"Configuration File: {file}", True, f"File exists") else: self.add_result(f"Configuration File: {file}", False, f"File missing") all_valid = False # Validate docker-compose.yml syntax try: result = subprocess.run( ["docker-compose", "config"], capture_output=True, text=True ) if result.returncode == 0: self.add_result("Docker Compose Syntax", True, "Configuration is valid") else: self.add_result("Docker Compose Syntax", False, f"Syntax error: {result.stderr}") all_valid = False except Exception as e: self.add_result("Docker Compose Syntax", False, f"Validation failed: {str(e)}") all_valid = False return all_valid def validate_environment_variables(self) -> bool: """Validate required environment variables.""" self.logger.info("Validating environment variables...") required_vars = [ "SUPABASE_URL", "SUPABASE_ANON_KEY", "SUPABASE_SERVICE_ROLE_KEY", "CLERK_SECRET_KEY", "CLERK_PUBLISHABLE_KEY", "GEMINI_API_KEY" ] all_valid = True # Load .env file env_vars = {} if os.path.exists(".env"): with open(".env", "r") as f: for line in f: line = line.strip() if line and not line.startswith("#") and "=" in line: key, value = line.split("=", 1) env_vars[key] = value for var in required_vars: if var in env_vars and env_vars[var] and env_vars[var] != f"your-{var.lower().replace('_', '-')}-here": self.add_result(f"Environment Variable: {var}", True, "Variable is set") else: self.add_result(f"Environment Variable: {var}", False, "Variable missing or not configured") all_valid = False return all_valid def validate_docker_images(self) -> bool: """Validate Docker images can be built.""" self.logger.info("Validating Docker images...") try: # Build images result = subprocess.run( ["docker-compose", "build"], capture_output=True, text=True, timeout=300 # 5 minute timeout ) if result.returncode == 0: self.add_result("Docker Image Build", True, "All images built successfully") return True else: self.add_result("Docker Image Build", False, f"Build failed: {result.stderr}") return False except subprocess.TimeoutExpired: self.add_result("Docker Image Build", False, "Build timed out after 5 minutes") return False except Exception as e: self.add_result("Docker Image Build", False, f"Build error: {str(e)}") return False async def validate_service_startup(self) -> bool: """Validate services start up correctly.""" self.logger.info("Validating service startup...") try: # Start services result = subprocess.run( ["docker-compose", "up", "-d"], capture_output=True, text=True ) if result.returncode != 0: self.add_result("Service Startup", False, f"Failed to start services: {result.stderr}") return False # Wait for services to start self.logger.info("Waiting for services to start...") await asyncio.sleep(30) # Check if containers are running result = subprocess.run( ["docker-compose", "ps", "--format", "json"], capture_output=True, text=True ) if result.returncode == 0: running_services = [] for line in result.stdout.strip().split('\n'): if line: try: container = json.loads(line) if container['State'] == 'running': running_services.append(container['Service']) except json.JSONDecodeError: continue if len(running_services) >= 6: # At least 6 services should be running self.add_result("Service Startup", True, f"{len(running_services)} services running") return True else: self.add_result("Service Startup", False, f"Only {len(running_services)} services running") return False else: self.add_result("Service Startup", False, "Failed to check service status") return False except Exception as e: self.add_result("Service Startup", False, f"Startup validation error: {str(e)}") return False async def validate_service_health(self) -> bool: """Validate service health endpoints.""" self.logger.info("Validating service health...") health_checks = [ ("Orchestrator Health", "http://localhost:8000/health"), ("Streamlit Health", "http://localhost:8501/_stcore/health") ] all_healthy = True for check_name, url in health_checks: try: async with aiohttp.ClientSession() as session: async with session.get(url, timeout=10) as response: if response.status == 200: self.add_result(check_name, True, f"Service healthy (status: {response.status})") else: self.add_result(check_name, False, f"Unhealthy status: {response.status}") all_healthy = False except asyncio.TimeoutError: self.add_result(check_name, False, "Health check timed out") all_healthy = False except Exception as e: self.add_result(check_name, False, f"Health check failed: {str(e)}") all_healthy = False return all_healthy async def validate_mcp_connectivity(self) -> bool: """Validate MCP server connectivity.""" self.logger.info("Validating MCP server connectivity...") mcp_servers = [ ("Data Cleaning MCP", 3001), ("Hypothesis Testing MCP", 3002), ("Preprocessing MCP", 3003), ("Feature Engineering MCP", 3004), ("Model Training MCP", 3005), ("Action Generation MCP", 3006) ] all_connected = True for server_name, port in mcp_servers: try: import socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(5) result = sock.connect_ex(("localhost", port)) sock.close() if result == 0: self.add_result(f"{server_name} Connectivity", True, f"Port {port} accessible") else: self.add_result(f"{server_name} Connectivity", False, f"Port {port} not accessible") all_connected = False except Exception as e: self.add_result(f"{server_name} Connectivity", False, f"Connection test failed: {str(e)}") all_connected = False return all_connected async def validate_api_endpoints(self) -> bool: """Validate key API endpoints.""" self.logger.info("Validating API endpoints...") endpoints = [ ("API Documentation", "http://localhost:8000/docs"), ("API OpenAPI Spec", "http://localhost:8000/openapi.json"), ("Health Endpoint", "http://localhost:8000/health") ] all_valid = True for endpoint_name, url in endpoints: try: async with aiohttp.ClientSession() as session: async with session.get(url, timeout=10) as response: if response.status == 200: self.add_result(f"API Endpoint: {endpoint_name}", True, f"Endpoint accessible (status: {response.status})") else: self.add_result(f"API Endpoint: {endpoint_name}", False, f"Endpoint returned status: {response.status}") all_valid = False except Exception as e: self.add_result(f"API Endpoint: {endpoint_name}", False, f"Endpoint test failed: {str(e)}") all_valid = False return all_valid def validate_security_configuration(self) -> bool: """Validate security configuration.""" self.logger.info("Validating security configuration...") # Check for security-related environment variables security_vars = ["CLERK_SECRET_KEY", "SUPABASE_SERVICE_ROLE_KEY"] all_secure = True # Load .env file env_vars = {} if os.path.exists(".env"): with open(".env", "r") as f: for line in f: line = line.strip() if line and not line.startswith("#") and "=" in line: key, value = line.split("=", 1) env_vars[key] = value for var in security_vars: if var in env_vars and env_vars[var]: # Check if it's not a placeholder if "your-" not in env_vars[var].lower() and "placeholder" not in env_vars[var].lower(): self.add_result(f"Security Config: {var}", True, "Security variable configured") else: self.add_result(f"Security Config: {var}", False, "Security variable appears to be placeholder") all_secure = False else: self.add_result(f"Security Config: {var}", False, "Security variable not configured") all_secure = False # Check for debug mode in production debug_enabled = env_vars.get("FASTAPI_DEBUG", "false").lower() == "true" if debug_enabled: self.add_result("Security Config: Debug Mode", False, "Debug mode is enabled (security risk)") all_secure = False else: self.add_result("Security Config: Debug Mode", True, "Debug mode is disabled") return all_secure def cleanup_test_deployment(self): """Clean up test deployment.""" self.logger.info("Cleaning up test deployment...") try: subprocess.run(["docker-compose", "down"], capture_output=True) self.logger.info("Test deployment cleaned up") except Exception as e: self.logger.warning(f"Cleanup failed: {str(e)}") def generate_report(self) -> Dict: """Generate validation report.""" passed_count = sum(1 for r in self.results if r.passed) total_count = len(self.results) report = { "timestamp": time.strftime("%Y-%m-%d %H:%M:%S"), "overall_status": "PASS" if passed_count == total_count else "FAIL", "summary": { "total_checks": total_count, "passed": passed_count, "failed": total_count - passed_count, "success_rate": f"{(passed_count / total_count * 100):.1f}%" if total_count > 0 else "0%" }, "results": [ { "check": r.check_name, "status": "PASS" if r.passed else "FAIL", "message": r.message, "details": r.details } for r in self.results ] } return report def print_report(self): """Print validation report.""" report = self.generate_report() print("\n" + "="*80) print("DEPLOYMENT VALIDATION REPORT") print("="*80) print(f"Timestamp: {report['timestamp']}") print(f"Overall Status: {report['overall_status']}") print(f"Success Rate: {report['summary']['success_rate']}") print(f"Checks: {report['summary']['passed']}/{report['summary']['total_checks']} passed") print() # Group results by category categories = {} for result in self.results: category = result.check_name.split(":")[0] if ":" in result.check_name else "General" if category not in categories: categories[category] = [] categories[category].append(result) for category, results in categories.items(): print(f"{category.upper()}:") print("-" * 40) for result in results: status_icon = "✅" if result.passed else "❌" print(f" {status_icon} {result.check_name}: {result.message}") print() if report['overall_status'] == "FAIL": print("RECOMMENDATIONS:") print("-" * 40) failed_results = [r for r in self.results if not r.passed] for result in failed_results: print(f"• Fix {result.check_name}: {result.message}") print() async def run_full_validation(self, cleanup: bool = True) -> bool: """Run complete deployment validation.""" self.logger.info("Starting deployment validation...") try: # Step 1: Prerequisites if not self.validate_prerequisites(): return False # Step 2: Configuration if not self.validate_configuration_files(): return False # Step 3: Environment variables if not self.validate_environment_variables(): return False # Step 4: Security configuration self.validate_security_configuration() # Step 5: Docker images if not self.validate_docker_images(): return False # Step 6: Service startup if not await self.validate_service_startup(): return False # Step 7: Service health await self.validate_service_health() # Step 8: MCP connectivity await self.validate_mcp_connectivity() # Step 9: API endpoints await self.validate_api_endpoints() return True finally: if cleanup: self.cleanup_test_deployment() async def main(): """Main function.""" import argparse parser = argparse.ArgumentParser(description="Validate MCP AI Data Scientist deployment") parser.add_argument("--no-cleanup", action="store_true", help="Don't clean up test deployment") parser.add_argument("--output", "-o", help="Output report to JSON file") args = parser.parse_args() validator = DeploymentValidator() try: success = await validator.run_full_validation(cleanup=not args.no_cleanup) # Print report validator.print_report() # Save report if requested if args.output: report = validator.generate_report() with open(args.output, 'w') as f: json.dump(report, f, indent=2) print(f"Report saved to {args.output}") # Exit with appropriate code sys.exit(0 if success else 1) except KeyboardInterrupt: validator.logger.info("Validation interrupted by user") validator.cleanup_test_deployment() sys.exit(1) except Exception as e: validator.logger.error(f"Validation failed with error: {str(e)}") validator.cleanup_test_deployment() sys.exit(1) if __name__ == "__main__": asyncio.run(main())