#!/usr/bin/env python3 """ DTO Syncthing Client - Manages distributed file synchronization for Class B/C transfers Provides automated setup and monitoring of Syncthing mirrors for non-critical data """ import os import json import requests from typing import Dict, Any, Optional, List from datetime import datetime, timezone from pathlib import Path import subprocess import time class DTOSyncthingClient: def __init__(self, api_key: Optional[str] = None, host: str = "localhost", port: int = 8384): self.host = host self.port = port self.api_key = api_key or os.getenv('SYNCTHING_API_KEY') self.base_url = f"http://{self.host}:{self.port}/rest" self.headers = { 'Content-Type': 'application/json', 'X-API-Key': self.api_key } if self.api_key else {} self.config_dir = Path("/data/adaptai/platform/dataops/dto/syncthing") def test_connection(self) -> bool: """Test Syncthing API connectivity""" if not self.api_key: print("❌ Syncthing API key not configured") return False try: response = requests.get( f"{self.base_url}/system/ping", headers=self.headers, timeout=10 ) if response.status_code == 200: system_info = self.get_system_status() print(f"✅ Connected to Syncthing {system_info.get('version', 'unknown')}") return True else: print(f"❌ Syncthing connection failed: {response.status_code}") return False except Exception as e: print(f"❌ Error connecting to Syncthing: {e}") return False def get_system_status(self) -> Dict[str, Any]: """Get Syncthing system status""" try: response = requests.get( f"{self.base_url}/system/status", headers=self.headers ) if response.status_code == 200: return response.json() else: return {} except Exception as e: print(f"❌ Error getting system status: {e}") return {} def get_device_id(self) -> Optional[str]: """Get this Syncthing instance's device ID""" try: status = self.get_system_status() return status.get('myID') except Exception as e: print(f"❌ Error getting device ID: {e}") return None def add_device(self, device_id: str, device_name: str, introducer: bool = False) -> bool: """Add a device to Syncthing configuration""" try: # Get current config config_response = requests.get( f"{self.base_url}/system/config", headers=self.headers ) if config_response.status_code != 200: print(f"❌ Failed to get config: {config_response.status_code}") return False config = config_response.json() # Check if device already exists for device in config.get('devices', []): if device['deviceID'] == device_id: print(f"ℹ️ Device {device_name} already exists") return True # Add new device new_device = { 'deviceID': device_id, 'name': device_name, 'addresses': ['dynamic'], 'compression': 'metadata', 'certName': '', 'introducer': introducer, 'skipIntroductionRemovals': False, 'introducedBy': '', 'paused': False, 'allowedNetworks': [], 'autoAcceptFolders': False, 'maxSendKbps': 0, 'maxRecvKbps': 0, 'ignoredFolders': [], 'pendingFolders': [], 'maxRequestKiB': 0 } config['devices'].append(new_device) # Update config update_response = requests.post( f"{self.base_url}/system/config", headers=self.headers, data=json.dumps(config) ) if update_response.status_code == 200: print(f"✅ Added device: {device_name} ({device_id})") return True else: print(f"❌ Failed to add device: {update_response.status_code}") return False except Exception as e: print(f"❌ Error adding device: {e}") return False def create_folder(self, folder_id: str, folder_path: str, device_ids: List[str], folder_type: str = "sendreceive", rescan_interval: int = 3600) -> bool: """Create a shared folder in Syncthing""" try: # Get current config config_response = requests.get( f"{self.base_url}/system/config", headers=self.headers ) if config_response.status_code != 200: print(f"❌ Failed to get config: {config_response.status_code}") return False config = config_response.json() # Check if folder already exists for folder in config.get('folders', []): if folder['id'] == folder_id: print(f"ℹ️ Folder {folder_id} already exists") return True # Ensure directory exists Path(folder_path).mkdir(parents=True, exist_ok=True) # Create devices list for folder devices = [{'deviceID': device_id, 'introducedBy': '', 'encryptionPassword': ''} for device_id in device_ids] # Add new folder new_folder = { 'id': folder_id, 'label': folder_id, 'filesystemType': 'basic', 'path': folder_path, 'type': folder_type, 'devices': devices, 'rescanIntervalS': rescan_interval, 'fsWatcherEnabled': True, 'fsWatcherDelayS': 10, 'ignorePerms': False, 'autoNormalize': True, 'minDiskFree': {'value': 1, 'unit': '%'}, 'versioning': { 'type': 'simple', 'params': {'keep': '5'} }, 'copiers': 0, 'pullerMaxPendingKiB': 0, 'hashers': 0, 'order': 'random', 'ignoreDelete': False, 'scanProgressIntervalS': 0, 'pullerPauseS': 0, 'maxConflicts': 10, 'disableSparseFiles': False, 'disableTempIndexes': False, 'paused': False, 'weakHashThresholdPct': 25, 'markerName': '.stfolder' } config['folders'].append(new_folder) # Update config update_response = requests.post( f"{self.base_url}/system/config", headers=self.headers, data=json.dumps(config) ) if update_response.status_code == 200: print(f"✅ Created folder: {folder_id} -> {folder_path}") return True else: print(f"❌ Failed to create folder: {update_response.status_code}") return False except Exception as e: print(f"❌ Error creating folder: {e}") return False def get_folder_status(self, folder_id: str) -> Dict[str, Any]: """Get status of a specific folder""" try: response = requests.get( f"{self.base_url}/db/status", headers=self.headers, params={'folder': folder_id} ) if response.status_code == 200: return response.json() else: return {} except Exception as e: print(f"❌ Error getting folder status: {e}") return {} def get_folder_completion(self, folder_id: str, device_id: str) -> Dict[str, Any]: """Get folder completion status for a specific device""" try: response = requests.get( f"{self.base_url}/db/completion", headers=self.headers, params={'folder': folder_id, 'device': device_id} ) if response.status_code == 200: return response.json() else: return {} except Exception as e: print(f"❌ Error getting folder completion: {e}") return {} def setup_dto_mirror(self, mirror_config: Dict[str, Any]) -> bool: """Set up DTO data mirror for Class B/C transfers""" try: mirror_name = mirror_config['name'] source_path = mirror_config['source_path'] mirror_devices = mirror_config['devices'] data_class = mirror_config.get('data_class', 'CLASS_B') print(f"🔄 Setting up DTO mirror: {mirror_name}") # Create folder ID based on mirror name and data class folder_id = f"dto-{data_class.lower()}-{mirror_name}" # Add all devices if not already present for device in mirror_devices: device_id = device['device_id'] device_name = device['name'] self.add_device(device_id, device_name) # Create shared folder device_ids = [device['device_id'] for device in mirror_devices] folder_created = self.create_folder( folder_id, source_path, device_ids, folder_type='sendreceive', rescan_interval=1800 # 30 minutes for Class B/C ) if folder_created: print(f"✅ DTO mirror setup completed: {mirror_name}") # Wait for initial scan print("🔍 Waiting for initial folder scan...") time.sleep(10) # Get initial status status = self.get_folder_status(folder_id) if status: print(f"📊 Initial scan: {status.get('localFiles', 0)} files, " f"{status.get('localBytes', 0) / (1024**3):.2f} GB") return True else: print(f"❌ Failed to setup mirror: {mirror_name}") return False except Exception as e: print(f"❌ Error setting up mirror: {e}") return False def monitor_sync_progress(self, folder_id: str, device_ids: List[str]) -> Dict[str, Any]: """Monitor synchronization progress across devices""" try: sync_status = { 'folder_id': folder_id, 'timestamp': datetime.now(timezone.utc).isoformat(), 'devices': {} } # Get folder status folder_status = self.get_folder_status(folder_id) sync_status['folder_status'] = folder_status # Get completion status for each device for device_id in device_ids: completion = self.get_folder_completion(folder_id, device_id) sync_status['devices'][device_id] = { 'completion_percent': completion.get('completion', 0), 'bytes_total': completion.get('globalBytes', 0), 'bytes_done': completion.get('needBytes', 0), 'items_total': completion.get('globalItems', 0), 'items_done': completion.get('needItems', 0) } return sync_status except Exception as e: print(f"❌ Error monitoring sync progress: {e}") return {} def get_sync_statistics(self) -> Dict[str, Any]: """Get overall synchronization statistics""" try: # Get system statistics stats_response = requests.get( f"{self.base_url}/system/status", headers=self.headers ) if stats_response.status_code != 200: return {} stats = stats_response.json() # Get connections info connections_response = requests.get( f"{self.base_url}/system/connections", headers=self.headers ) connections = {} if connections_response.status_code == 200: connections = connections_response.json() return { 'system_stats': stats, 'connections': connections, 'timestamp': datetime.now(timezone.utc).isoformat() } except Exception as e: print(f"❌ Error getting sync statistics: {e}") return {} def pause_folder(self, folder_id: str) -> bool: """Pause synchronization for a folder""" try: response = requests.post( f"{self.base_url}/db/pause", headers=self.headers, params={'folder': folder_id} ) if response.status_code == 200: print(f"⏸️ Paused folder: {folder_id}") return True else: print(f"❌ Failed to pause folder: {response.status_code}") return False except Exception as e: print(f"❌ Error pausing folder: {e}") return False def resume_folder(self, folder_id: str) -> bool: """Resume synchronization for a folder""" try: response = requests.post( f"{self.base_url}/db/resume", headers=self.headers, params={'folder': folder_id} ) if response.status_code == 200: print(f"▶️ Resumed folder: {folder_id}") return True else: print(f"❌ Failed to resume folder: {response.status_code}") return False except Exception as e: print(f"❌ Error resuming folder: {e}") return False def scan_folder(self, folder_id: str) -> bool: """Trigger manual scan of a folder""" try: response = requests.post( f"{self.base_url}/db/scan", headers=self.headers, params={'folder': folder_id} ) if response.status_code == 200: print(f"🔍 Triggered scan for folder: {folder_id}") return True else: print(f"❌ Failed to scan folder: {response.status_code}") return False except Exception as e: print(f"❌ Error scanning folder: {e}") return False # Test function def test_syncthing_integration(): """Test Syncthing integration with mock mirror setup""" client = DTOSyncthingClient() if not client.test_connection(): print("❌ Syncthing integration test failed (expected without proper setup)") return False # Test mirror setup test_mirror = { 'name': 'test-research-data', 'source_path': '/data/adaptai/platform/dataops/dto/test/class_b', 'data_class': 'CLASS_B', 'devices': [ { 'device_id': 'ABCDEFG-HIJKLMN-OPQRSTU-VWXYZ12-3456789-ABCDEFG-HIJKLMN-OPQRSTU', 'name': 'vast1-mirror' }, { 'device_id': 'BCDEFGH-IJKLMNO-PQRSTUV-WXYZ123-456789A-BCDEFGH-IJKLMNO-PQRSTUV', 'name': 'vast2-mirror' } ] } # Create test directory Path(test_mirror['source_path']).mkdir(parents=True, exist_ok=True) # Setup mirror if client.setup_dto_mirror(test_mirror): print("✅ Syncthing mirror setup test completed") # Test monitoring device_ids = [device['device_id'] for device in test_mirror['devices']] sync_status = client.monitor_sync_progress('dto-class_b-test-research-data', device_ids) if sync_status: print("✅ Sync monitoring test completed") return True else: print("❌ Failed to setup test mirror") return False if __name__ == "__main__": print("Testing DTO Syncthing Integration...") print("=" * 50) test_syncthing_integration() print("\nTo use Syncthing integration, set these environment variables:") print("export SYNCTHING_API_KEY=your-api-key") print("And ensure Syncthing is running on localhost:8384")