|
|
|
|
|
""" |
|
|
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 = {} |
|
|
self.sync_jobs = {} |
|
|
|
|
|
|
|
|
self.mirror_configs = { |
|
|
'CLASS_B': { |
|
|
'rescan_interval': 1800, |
|
|
'folder_type': 'sendreceive', |
|
|
'versioning_keep': 3, |
|
|
'priority': 'low' |
|
|
}, |
|
|
'CLASS_C': { |
|
|
'rescan_interval': 3600, |
|
|
'folder_type': 'sendreceive', |
|
|
'versioning_keep': 5, |
|
|
'priority': 'background' |
|
|
} |
|
|
} |
|
|
|
|
|
async def connect(self) -> bool: |
|
|
"""Connect to NATS and Syncthing""" |
|
|
try: |
|
|
|
|
|
await self.nats_client.connect(servers=self.nats_servers) |
|
|
print("β
Connected to NATS for Syncthing automation") |
|
|
|
|
|
|
|
|
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') |
|
|
|
|
|
|
|
|
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: |
|
|
|
|
|
mirror_config = await self.parse_manifest_for_mirrors(manifest_path, data_class) |
|
|
|
|
|
if mirror_config: |
|
|
|
|
|
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}") |
|
|
|
|
|
|
|
|
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: |
|
|
|
|
|
|
|
|
|
|
|
base_path = f"/data/adaptai/platform/dataops/dto/mirrors/{data_class.lower()}" |
|
|
|
|
|
|
|
|
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)""" |
|
|
|
|
|
|
|
|
import hashlib |
|
|
hash_obj = hashlib.md5(hostname.encode()) |
|
|
hex_hash = hash_obj.hexdigest().upper() |
|
|
|
|
|
|
|
|
device_id = '-'.join([hex_hash[i:i+7] for i in range(0, len(hex_hash), 7)]) |
|
|
return device_id[:63] |
|
|
|
|
|
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: |
|
|
|
|
|
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}" |
|
|
|
|
|
|
|
|
Path(run_mirror_config['source_path']).mkdir(parents=True, exist_ok=True) |
|
|
|
|
|
|
|
|
success = self.syncthing_client.setup_dto_mirror(run_mirror_config) |
|
|
|
|
|
if success: |
|
|
|
|
|
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}") |
|
|
|
|
|
|
|
|
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: |
|
|
|
|
|
device_ids = [device['device_id'] for device in mirror_config['devices']] |
|
|
|
|
|
|
|
|
sync_status = self.syncthing_client.monitor_sync_progress(folder_id, device_ids) |
|
|
|
|
|
if sync_status: |
|
|
|
|
|
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'] |
|
|
|
|
|
|
|
|
final_stats = self.syncthing_client.get_sync_statistics() |
|
|
|
|
|
|
|
|
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 |
|
|
|
|
|
|
|
|
|
|
|
if final_status != 'SUCCESS': |
|
|
self.syncthing_client.pause_folder(folder_id) |
|
|
print(f"βΈοΈ Paused sync for failed run: {run_id}") |
|
|
else: |
|
|
|
|
|
self.syncthing_client.scan_folder(folder_id) |
|
|
print(f"π Triggered final sync scan for run: {run_id}") |
|
|
|
|
|
|
|
|
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...") |
|
|
|
|
|
|
|
|
sync_stats = self.syncthing_client.get_sync_statistics() |
|
|
|
|
|
if sync_stats: |
|
|
|
|
|
connections = sync_stats.get('connections', {}) |
|
|
|
|
|
|
|
|
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 |
|
|
|
|
|
|
|
|
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') |
|
|
|
|
|
|
|
|
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: |
|
|
|
|
|
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: |
|
|
|
|
|
await self.nats_client.subscribe("dto.events.>", cb=self.process_event) |
|
|
print("β
Started Syncthing automation - listening for DTO events") |
|
|
|
|
|
|
|
|
async def periodic_health_check(): |
|
|
while True: |
|
|
await asyncio.sleep(300) |
|
|
await self.monitor_sync_health() |
|
|
|
|
|
|
|
|
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) |
|
|
|
|
|
|
|
|
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()) |