#!/usr/bin/env python3 """ DTO Syncthing Automation - Event-driven sync management for Class B/C transfers Automatically manages Syncthing mirrors based on DTO events and manifest requirements """ import asyncio import json from typing import Dict, Any, Optional, List from datetime import datetime, timezone from nats.aio.client import Client as NATS from syncthing_client import DTOSyncthingClient from pathlib import Path class DTOSyncthingAutomation: def __init__(self, nats_servers: list = ["nats://localhost:4222"]): self.nats_servers = nats_servers self.nats_client = NATS() self.syncthing_client = DTOSyncthingClient() self.active_mirrors = {} # Track active mirror configurations self.sync_jobs = {} # Track ongoing sync jobs # Default mirror configurations for different data classes self.mirror_configs = { 'CLASS_B': { 'rescan_interval': 1800, # 30 minutes 'folder_type': 'sendreceive', 'versioning_keep': 3, 'priority': 'low' }, 'CLASS_C': { 'rescan_interval': 3600, # 1 hour 'folder_type': 'sendreceive', 'versioning_keep': 5, 'priority': 'background' } } async def connect(self) -> bool: """Connect to NATS and Syncthing""" try: # Connect to NATS await self.nats_client.connect(servers=self.nats_servers) print("✅ Connected to NATS for Syncthing automation") # Test Syncthing connection if not self.syncthing_client.test_connection(): print("⚠️ Syncthing not available - running in monitoring mode only") return True except Exception as e: print(f"❌ Syncthing automation connection failed: {e}") return False async def handle_run_planned(self, event_data: Dict[str, Any]): """Handle RUN_PLANNED event - setup mirrors for Class B/C runs""" run_id = event_data.get('run_id') data_class = event_data.get('data_class', '').upper() manifest_path = event_data.get('manifest_path') environment = event_data.get('environment') # Only handle Class B and C transfers if data_class not in ['CLASS_B', 'CLASS_C']: print(f"ℹ️ Skipping Syncthing setup for {data_class} run: {run_id}") return print(f"🔄 Setting up Syncthing mirror for {data_class} run: {run_id}") try: # Load manifest to get mirror requirements mirror_config = await self.parse_manifest_for_mirrors(manifest_path, data_class) if mirror_config: # Setup Syncthing mirror mirror_setup = await self.setup_run_mirror(run_id, mirror_config, data_class, environment) if mirror_setup: self.active_mirrors[run_id] = mirror_config print(f"✅ Syncthing mirror configured for run: {run_id}") # Publish mirror setup event await self.publish_mirror_event('SYNCTHING_MIRROR_SETUP', { 'run_id': run_id, 'data_class': data_class, 'mirror_config': mirror_config, 'environment': environment }) else: print(f"❌ Failed to setup mirror for run: {run_id}") else: print(f"ℹ️ No mirror configuration required for run: {run_id}") except Exception as e: print(f"❌ Error setting up mirror for run {run_id}: {e}") async def parse_manifest_for_mirrors(self, manifest_path: str, data_class: str) -> Optional[Dict[str, Any]]: """Parse manifest file to extract mirror configuration""" try: # In a real implementation, this would parse YAML/JSON manifest # For now, create a default configuration based on data class base_path = f"/data/adaptai/platform/dataops/dto/mirrors/{data_class.lower()}" # Default mirror devices (would be configured per environment) default_devices = [ { 'device_id': self.get_device_id_for_host('vast1.adapt.ai'), 'name': 'vast1-mirror', 'role': 'primary' }, { 'device_id': self.get_device_id_for_host('vast2.adapt.ai'), 'name': 'vast2-mirror', 'role': 'secondary' } ] mirror_config = { 'name': f'{data_class.lower()}-auto-mirror', 'source_path': base_path, 'devices': default_devices, 'data_class': data_class, 'sync_mode': 'bidirectional', 'schedule': self.mirror_configs[data_class] } return mirror_config except Exception as e: print(f"❌ Error parsing manifest: {e}") return None def get_device_id_for_host(self, hostname: str) -> str: """Get Syncthing device ID for a hostname (mock implementation)""" # In real implementation, this would look up actual device IDs # For now, generate deterministic mock IDs import hashlib hash_obj = hashlib.md5(hostname.encode()) hex_hash = hash_obj.hexdigest().upper() # Format as Syncthing device ID (LUHN check digit format) device_id = '-'.join([hex_hash[i:i+7] for i in range(0, len(hex_hash), 7)]) return device_id[:63] # Syncthing device ID length limit async def setup_run_mirror(self, run_id: str, mirror_config: Dict[str, Any], data_class: str, environment: str) -> bool: """Set up Syncthing mirror for a specific run""" try: # Create run-specific mirror configuration run_mirror_config = mirror_config.copy() run_mirror_config['name'] = f"{run_id}-{data_class.lower()}" run_mirror_config['source_path'] = f"{mirror_config['source_path']}/{run_id}" # Ensure source directory exists Path(run_mirror_config['source_path']).mkdir(parents=True, exist_ok=True) # Setup mirror using Syncthing client success = self.syncthing_client.setup_dto_mirror(run_mirror_config) if success: # Store sync job details self.sync_jobs[run_id] = { 'folder_id': f"dto-{data_class.lower()}-{run_mirror_config['name']}", 'mirror_config': run_mirror_config, 'start_time': datetime.now(timezone.utc).isoformat(), 'status': 'active' } print(f"✅ Mirror setup completed for run: {run_id}") return True else: print(f"❌ Mirror setup failed for run: {run_id}") return False except Exception as e: print(f"❌ Error setting up run mirror: {e}") return False async def handle_transfer_started(self, event_data: Dict[str, Any]): """Handle TRANSFER_STARTED event - begin sync monitoring""" run_id = event_data.get('run_id') if run_id not in self.sync_jobs: return print(f"📊 Starting sync monitoring for run: {run_id}") # Begin monitoring sync progress await self.start_sync_monitoring(run_id) async def start_sync_monitoring(self, run_id: str): """Start monitoring synchronization progress""" if run_id not in self.sync_jobs: return sync_job = self.sync_jobs[run_id] folder_id = sync_job['folder_id'] mirror_config = sync_job['mirror_config'] try: # Get device IDs for monitoring device_ids = [device['device_id'] for device in mirror_config['devices']] # Monitor sync progress sync_status = self.syncthing_client.monitor_sync_progress(folder_id, device_ids) if sync_status: # Publish sync progress event await self.publish_mirror_event('SYNCTHING_SYNC_PROGRESS', { 'run_id': run_id, 'folder_id': folder_id, 'sync_status': sync_status }) print(f"📊 Sync progress monitored for run: {run_id}") except Exception as e: print(f"❌ Error monitoring sync for run {run_id}: {e}") async def handle_run_completed(self, event_data: Dict[str, Any]): """Handle RUN_COMPLETED event - finalize sync and cleanup""" run_id = event_data.get('run_id') final_status = event_data.get('final_status') if run_id not in self.sync_jobs: return print(f"🏁 Finalizing sync for completed run: {run_id}") try: sync_job = self.sync_jobs[run_id] folder_id = sync_job['folder_id'] # Get final sync statistics final_stats = self.syncthing_client.get_sync_statistics() # Update sync job status sync_job['status'] = 'completed' if final_status == 'SUCCESS' else 'failed' sync_job['end_time'] = datetime.now(timezone.utc).isoformat() sync_job['final_stats'] = final_stats # For Class B/C, keep the mirror active for ongoing sync # Only pause if the run failed if final_status != 'SUCCESS': self.syncthing_client.pause_folder(folder_id) print(f"⏸️ Paused sync for failed run: {run_id}") else: # Trigger final scan to ensure all data is synced self.syncthing_client.scan_folder(folder_id) print(f"🔍 Triggered final sync scan for run: {run_id}") # Publish sync completion event await self.publish_mirror_event('SYNCTHING_SYNC_COMPLETED', { 'run_id': run_id, 'folder_id': folder_id, 'final_status': final_status, 'sync_job': sync_job }) except Exception as e: print(f"❌ Error finalizing sync for run {run_id}: {e}") async def handle_sync_request(self, event_data: Dict[str, Any]): """Handle manual sync requests""" folder_id = event_data.get('folder_id') action = event_data.get('action', 'scan') if not folder_id: print("⚠️ No folder ID provided for sync request") return print(f"🔄 Processing sync request: {action} for folder {folder_id}") try: if action == 'scan': success = self.syncthing_client.scan_folder(folder_id) elif action == 'pause': success = self.syncthing_client.pause_folder(folder_id) elif action == 'resume': success = self.syncthing_client.resume_folder(folder_id) else: print(f"❌ Unknown sync action: {action}") return if success: await self.publish_mirror_event('SYNCTHING_ACTION_COMPLETED', { 'folder_id': folder_id, 'action': action, 'success': True }) except Exception as e: print(f"❌ Error processing sync request: {e}") async def monitor_sync_health(self): """Periodic sync health monitoring""" try: print("🏥 Monitoring Syncthing sync health...") # Get overall sync statistics sync_stats = self.syncthing_client.get_sync_statistics() if sync_stats: # Check for any sync issues connections = sync_stats.get('connections', {}) # Count connected vs disconnected devices connected_devices = 0 total_devices = 0 for device_id, connection in connections.get('connections', {}).items(): total_devices += 1 if connection.get('connected'): connected_devices += 1 # Publish health status health_event = { 'event_type': 'SYNCTHING_HEALTH_CHECK', 'timestamp': datetime.now(timezone.utc).isoformat(), 'connected_devices': connected_devices, 'total_devices': total_devices, 'connection_rate': connected_devices / total_devices if total_devices > 0 else 0, 'active_mirrors': len(self.sync_jobs), 'sync_stats': sync_stats } await self.publish_mirror_event('SYNCTHING_HEALTH_STATUS', health_event) if connected_devices < total_devices: print(f"⚠️ Sync health warning: {connected_devices}/{total_devices} devices connected") else: print(f"✅ Sync health OK: All {total_devices} devices connected") except Exception as e: print(f"❌ Error monitoring sync health: {e}") async def publish_mirror_event(self, event_type: str, event_data: Dict[str, Any]): """Publish Syncthing mirror event to NATS""" try: mirror_event = { 'event_id': f"syncthing-{event_type.lower()}-{int(datetime.now().timestamp())}", 'event_type': event_type, 'timestamp': datetime.now(timezone.utc).isoformat(), 'source': 'syncthing-automation', **event_data } await self.nats_client.publish( f"dto.events.syncthing.{event_type.lower()}", json.dumps(mirror_event).encode() ) print(f"📤 Published {event_type} event") except Exception as e: print(f"❌ Error publishing mirror event: {e}") async def process_event(self, msg): """Process incoming NATS event for Syncthing automation""" try: event_data = json.loads(msg.data.decode()) event_type = event_data.get('event_type') # Route to appropriate handler handlers = { 'RUN_PLANNED': self.handle_run_planned, 'TRANSFER_STARTED': self.handle_transfer_started, 'RUN_COMPLETED': self.handle_run_completed, 'SYNCTHING_SYNC_REQUEST': self.handle_sync_request } handler = handlers.get(event_type) if handler: await handler(event_data) else: # Log other events for debugging print(f"ℹ️ Syncthing automation ignoring event: {event_type}") except Exception as e: print(f"❌ Error processing Syncthing event: {e}") async def start_automation(self): """Start listening for DTO events and periodic monitoring""" try: # Subscribe to DTO events await self.nats_client.subscribe("dto.events.>", cb=self.process_event) print("✅ Started Syncthing automation - listening for DTO events") # Start periodic health monitoring async def periodic_health_check(): while True: await asyncio.sleep(300) # 5 minutes await self.monitor_sync_health() # Run both event processing and health monitoring await asyncio.gather( periodic_health_check(), self.keep_alive() ) except KeyboardInterrupt: print("\n🛑 Stopping Syncthing automation...") except Exception as e: print(f"❌ Syncthing automation error: {e}") finally: await self.nats_client.close() async def keep_alive(self): """Keep the automation running""" while True: await asyncio.sleep(1) # CLI entry point async def main(): automation = DTOSyncthingAutomation() if await automation.connect(): print("🔄 DTO Syncthing Automation started") print("Monitoring events: RUN_PLANNED, TRANSFER_STARTED, RUN_COMPLETED") print("Managing distributed mirrors for Class B/C data transfers") print("Press Ctrl+C to stop\n") await automation.start_automation() else: print("❌ Failed to start Syncthing automation") if __name__ == "__main__": asyncio.run(main())