#!/usr/bin/env python3 """ DTO Service Manager - Management interface for DTO services Provides unified control over all DTO infrastructure components """ import os import sys import subprocess import time import json from typing import Dict, Any, List, Optional from datetime import datetime from pathlib import Path class DTOServiceManager: def __init__(self): self.dto_root = Path("/data/adaptai/platform/dataops/dto") self.supervisor_config = self.dto_root / "services" / "supervisord.conf" self.log_dir = self.dto_root / "logs" self.services = [ 'dto-nats-server', 'dto-dragonfly-node1', 'dto-dragonfly-node2', 'dto-dragonfly-node3', 'dto-janusgraph', 'dto-lineage-handler', 'dto-slack-automation', 'dto-jira-automation', 'dto-confluence-automation', 'dto-jira-webhooks', 'dto-health-monitor' ] self.service_groups = { 'infrastructure': ['dto-nats-server', 'dto-dragonfly-node1', 'dto-dragonfly-node2', 'dto-dragonfly-node3', 'dto-janusgraph'], 'integrations': ['dto-lineage-handler', 'dto-slack-automation', 'dto-jira-automation', 'dto-confluence-automation', 'dto-jira-webhooks'], 'monitoring': ['dto-health-monitor'] } def run_supervisorctl(self, command: str, service: Optional[str] = None) -> subprocess.CompletedProcess: """Run supervisorctl command""" cmd = [ 'supervisorctl', '-c', str(self.supervisor_config), command ] if service: cmd.append(service) return subprocess.run(cmd, capture_output=True, text=True, timeout=30) def check_prerequisites(self) -> Dict[str, bool]: """Check if prerequisites are installed and configured""" checks = {} # Check if supervisord is installed try: subprocess.run(['supervisord', '--version'], capture_output=True, check=True) checks['supervisord'] = True except (subprocess.CalledProcessError, FileNotFoundError): checks['supervisord'] = False # Check if NATS server is available try: subprocess.run(['nats-server', '--version'], capture_output=True, check=True) checks['nats_server'] = True except (subprocess.CalledProcessError, FileNotFoundError): checks['nats_server'] = False # Check if Dragonfly is available try: subprocess.run(['dragonfly', '--version'], capture_output=True, check=True) checks['dragonfly'] = True except (subprocess.CalledProcessError, FileNotFoundError): checks['dragonfly'] = False # Check if required Python packages are installed try: import nats import redis import psutil checks['python_packages'] = True except ImportError: checks['python_packages'] = False # Check if directories exist checks['dto_directories'] = all([ self.dto_root.exists(), self.log_dir.exists(), (self.dto_root / "cache").exists(), (self.dto_root / "events").exists() ]) return checks def setup_environment(self) -> bool: """Set up DTO environment and directories""" try: # Create required directories directories = [ self.log_dir, self.dto_root / "cache" / "dragonfly_data" / "node1", self.dto_root / "cache" / "dragonfly_data" / "node2", self.dto_root / "cache" / "dragonfly_data" / "node3", self.dto_root / "cache" / "backups", self.dto_root / "services" ] for directory in directories: directory.mkdir(parents=True, exist_ok=True) print(f"✅ Created directory: {directory}") # Set permissions os.chmod(self.log_dir, 0o755) os.chmod(self.dto_root / "services", 0o755) print("✅ DTO environment setup completed") return True except Exception as e: print(f"❌ Failed to setup environment: {e}") return False def start_supervisord(self) -> bool: """Start supervisord daemon""" try: # Check if supervisord is already running result = subprocess.run(['pgrep', '-f', 'supervisord'], capture_output=True) if result.returncode == 0: print("ℹ️ Supervisord is already running") return True # Start supervisord cmd = [ 'supervisord', '-c', str(self.supervisor_config), '-n' # Don't daemonize for better control ] print(f"🚀 Starting supervisord with config: {self.supervisor_config}") process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # Give it time to start time.sleep(3) # Check if it's running if process.poll() is None: print("✅ Supervisord started successfully") return True else: stdout, stderr = process.communicate() print(f"❌ Supervisord failed to start: {stderr}") return False except Exception as e: print(f"❌ Error starting supervisord: {e}") return False def stop_supervisord(self) -> bool: """Stop supervisord daemon""" try: result = self.run_supervisorctl('shutdown') if result.returncode == 0: print("✅ Supervisord stopped successfully") return True else: print(f"❌ Failed to stop supervisord: {result.stderr}") return False except Exception as e: print(f"❌ Error stopping supervisord: {e}") return False def get_service_status(self, service: Optional[str] = None) -> Dict[str, Any]: """Get status of DTO services""" try: result = self.run_supervisorctl('status', service) if result.returncode != 0: return {'error': result.stderr} services = {} for line in result.stdout.strip().split('\n'): if line.strip(): parts = line.split() if len(parts) >= 2: service_name = parts[0] status = parts[1] services[service_name] = { 'status': status, 'running': status == 'RUNNING', 'line': line.strip() } return services except Exception as e: return {'error': str(e)} def start_service(self, service: str) -> bool: """Start a specific service""" try: result = self.run_supervisorctl('start', service) if result.returncode == 0: print(f"✅ Started service: {service}") return True else: print(f"❌ Failed to start {service}: {result.stderr}") return False except Exception as e: print(f"❌ Error starting {service}: {e}") return False def stop_service(self, service: str) -> bool: """Stop a specific service""" try: result = self.run_supervisorctl('stop', service) if result.returncode == 0: print(f"✅ Stopped service: {service}") return True else: print(f"❌ Failed to stop {service}: {result.stderr}") return False except Exception as e: print(f"❌ Error stopping {service}: {e}") return False def restart_service(self, service: str) -> bool: """Restart a specific service""" try: result = self.run_supervisorctl('restart', service) if result.returncode == 0: print(f"✅ Restarted service: {service}") return True else: print(f"❌ Failed to restart {service}: {result.stderr}") return False except Exception as e: print(f"❌ Error restarting {service}: {e}") return False def start_group(self, group_name: str) -> bool: """Start a group of services""" if group_name not in self.service_groups: print(f"❌ Unknown service group: {group_name}") return False services = self.service_groups[group_name] success = True print(f"🚀 Starting {group_name} services: {', '.join(services)}") for service in services: if not self.start_service(service): success = False return success def stop_group(self, group_name: str) -> bool: """Stop a group of services""" if group_name not in self.service_groups: print(f"❌ Unknown service group: {group_name}") return False services = self.service_groups[group_name] success = True print(f"🛑 Stopping {group_name} services: {', '.join(services)}") # Stop in reverse order for service in reversed(services): if not self.stop_service(service): success = False return success def show_logs(self, service: str, lines: int = 50) -> str: """Show logs for a service""" log_file = self.log_dir / f"{service.replace('dto-', '')}.log" if not log_file.exists(): return f"Log file not found: {log_file}" try: result = subprocess.run(['tail', '-n', str(lines), str(log_file)], capture_output=True, text=True) return result.stdout except Exception as e: return f"Error reading log: {e}" def get_system_info(self) -> Dict[str, Any]: """Get system information relevant to DTO""" try: import psutil # Memory info memory = psutil.virtual_memory() # Disk info for DTO directory dto_disk = psutil.disk_usage(str(self.dto_root)) # CPU info cpu_count = psutil.cpu_count() cpu_percent = psutil.cpu_percent(interval=1) return { 'memory': { 'total_gb': memory.total / (1024**3), 'available_gb': memory.available / (1024**3), 'used_percent': memory.percent }, 'disk': { 'total_gb': dto_disk.total / (1024**3), 'free_gb': dto_disk.free / (1024**3), 'used_percent': (dto_disk.used / dto_disk.total) * 100 }, 'cpu': { 'count': cpu_count, 'usage_percent': cpu_percent } } except Exception as e: return {'error': str(e)} def health_check(self) -> Dict[str, Any]: """Perform comprehensive health check""" health = { 'timestamp': datetime.now().isoformat(), 'prerequisites': self.check_prerequisites(), 'services': self.get_service_status(), 'system': self.get_system_info() } # Calculate overall health prereq_ok = all(health['prerequisites'].values()) services_ok = all(s.get('running', False) for s in health['services'].values() if isinstance(s, dict)) health['overall_healthy'] = prereq_ok and services_ok return health def main(): """CLI interface for DTO service management""" import argparse parser = argparse.ArgumentParser(description='DTO Service Manager') subparsers = parser.add_subparsers(dest='command', help='Available commands') # Setup command subparsers.add_parser('setup', help='Setup DTO environment') # Service management commands subparsers.add_parser('start', help='Start supervisord and all services') subparsers.add_parser('stop', help='Stop all services and supervisord') subparsers.add_parser('status', help='Show service status') subparsers.add_parser('health', help='Perform health check') # Individual service commands start_parser = subparsers.add_parser('start-service', help='Start specific service') start_parser.add_argument('service', help='Service name') stop_parser = subparsers.add_parser('stop-service', help='Stop specific service') stop_parser.add_argument('service', help='Service name') restart_parser = subparsers.add_parser('restart-service', help='Restart specific service') restart_parser.add_argument('service', help='Service name') # Group commands start_group_parser = subparsers.add_parser('start-group', help='Start service group') start_group_parser.add_argument('group', choices=['infrastructure', 'integrations', 'monitoring']) stop_group_parser = subparsers.add_parser('stop-group', help='Stop service group') stop_group_parser.add_argument('group', choices=['infrastructure', 'integrations', 'monitoring']) # Logs command logs_parser = subparsers.add_parser('logs', help='Show service logs') logs_parser.add_argument('service', help='Service name') logs_parser.add_argument('--lines', type=int, default=50, help='Number of lines to show') args = parser.parse_args() if not args.command: parser.print_help() return manager = DTOServiceManager() if args.command == 'setup': print("🔧 Setting up DTO environment...") if manager.setup_environment(): print("✅ DTO environment setup completed") else: print("❌ DTO environment setup failed") elif args.command == 'start': print("🚀 Starting DTO services...") if manager.start_supervisord(): time.sleep(5) # Give services time to start status = manager.get_service_status() print(f"\n📊 Service Status:") for service, info in status.items(): if isinstance(info, dict): print(f" {service}: {info['status']}") elif args.command == 'stop': print("🛑 Stopping DTO services...") manager.stop_supervisord() elif args.command == 'status': status = manager.get_service_status() print("📊 DTO Service Status:") for service, info in status.items(): if isinstance(info, dict): print(f" {service}: {info['status']}") else: print(f"Error: {info}") elif args.command == 'health': health = manager.health_check() print("🏥 DTO Health Check:") print(f"Overall Healthy: {'✅' if health['overall_healthy'] else '❌'}") print(f"\nPrerequisites:") for check, status in health['prerequisites'].items(): print(f" {check}: {'✅' if status else '❌'}") print(f"\nServices:") for service, info in health['services'].items(): if isinstance(info, dict): print(f" {service}: {'✅' if info['running'] else '❌'} {info['status']}") elif args.command == 'start-service': manager.start_service(args.service) elif args.command == 'stop-service': manager.stop_service(args.service) elif args.command == 'restart-service': manager.restart_service(args.service) elif args.command == 'start-group': manager.start_group(args.group) elif args.command == 'stop-group': manager.stop_group(args.group) elif args.command == 'logs': logs = manager.show_logs(args.service, args.lines) print(f"📄 Logs for {args.service}:") print(logs) if __name__ == "__main__": main()