|
|
|
|
|
""" |
|
|
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 = {} |
|
|
|
|
|
|
|
|
try: |
|
|
subprocess.run(['supervisord', '--version'], capture_output=True, check=True) |
|
|
checks['supervisord'] = True |
|
|
except (subprocess.CalledProcessError, FileNotFoundError): |
|
|
checks['supervisord'] = False |
|
|
|
|
|
|
|
|
try: |
|
|
subprocess.run(['nats-server', '--version'], capture_output=True, check=True) |
|
|
checks['nats_server'] = True |
|
|
except (subprocess.CalledProcessError, FileNotFoundError): |
|
|
checks['nats_server'] = False |
|
|
|
|
|
|
|
|
try: |
|
|
subprocess.run(['dragonfly', '--version'], capture_output=True, check=True) |
|
|
checks['dragonfly'] = True |
|
|
except (subprocess.CalledProcessError, FileNotFoundError): |
|
|
checks['dragonfly'] = False |
|
|
|
|
|
|
|
|
try: |
|
|
import nats |
|
|
import redis |
|
|
import psutil |
|
|
checks['python_packages'] = True |
|
|
except ImportError: |
|
|
checks['python_packages'] = False |
|
|
|
|
|
|
|
|
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: |
|
|
|
|
|
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}") |
|
|
|
|
|
|
|
|
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: |
|
|
|
|
|
result = subprocess.run(['pgrep', '-f', 'supervisord'], capture_output=True) |
|
|
if result.returncode == 0: |
|
|
print("βΉοΈ Supervisord is already running") |
|
|
return True |
|
|
|
|
|
|
|
|
cmd = [ |
|
|
'supervisord', |
|
|
'-c', str(self.supervisor_config), |
|
|
'-n' |
|
|
] |
|
|
|
|
|
print(f"π Starting supervisord with config: {self.supervisor_config}") |
|
|
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
|
|
|
|
|
|
|
|
time.sleep(3) |
|
|
|
|
|
|
|
|
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)}") |
|
|
|
|
|
|
|
|
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 = psutil.virtual_memory() |
|
|
|
|
|
|
|
|
dto_disk = psutil.disk_usage(str(self.dto_root)) |
|
|
|
|
|
|
|
|
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() |
|
|
} |
|
|
|
|
|
|
|
|
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') |
|
|
|
|
|
|
|
|
subparsers.add_parser('setup', help='Setup DTO environment') |
|
|
|
|
|
|
|
|
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') |
|
|
|
|
|
|
|
|
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') |
|
|
|
|
|
|
|
|
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_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) |
|
|
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() |