|
|
|
|
|
""" |
|
|
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: |
|
|
|
|
|
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() |
|
|
|
|
|
|
|
|
for device in config.get('devices', []): |
|
|
if device['deviceID'] == device_id: |
|
|
print(f"βΉοΈ Device {device_name} already exists") |
|
|
return True |
|
|
|
|
|
|
|
|
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_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: |
|
|
|
|
|
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() |
|
|
|
|
|
|
|
|
for folder in config.get('folders', []): |
|
|
if folder['id'] == folder_id: |
|
|
print(f"βΉοΈ Folder {folder_id} already exists") |
|
|
return True |
|
|
|
|
|
|
|
|
Path(folder_path).mkdir(parents=True, exist_ok=True) |
|
|
|
|
|
|
|
|
devices = [{'deviceID': device_id, 'introducedBy': '', 'encryptionPassword': ''} |
|
|
for device_id in device_ids] |
|
|
|
|
|
|
|
|
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_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}") |
|
|
|
|
|
|
|
|
folder_id = f"dto-{data_class.lower()}-{mirror_name}" |
|
|
|
|
|
|
|
|
for device in mirror_devices: |
|
|
device_id = device['device_id'] |
|
|
device_name = device['name'] |
|
|
self.add_device(device_id, device_name) |
|
|
|
|
|
|
|
|
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 |
|
|
) |
|
|
|
|
|
if folder_created: |
|
|
print(f"β
DTO mirror setup completed: {mirror_name}") |
|
|
|
|
|
|
|
|
print("π Waiting for initial folder scan...") |
|
|
time.sleep(10) |
|
|
|
|
|
|
|
|
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': {} |
|
|
} |
|
|
|
|
|
|
|
|
folder_status = self.get_folder_status(folder_id) |
|
|
sync_status['folder_status'] = folder_status |
|
|
|
|
|
|
|
|
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: |
|
|
|
|
|
stats_response = requests.get( |
|
|
f"{self.base_url}/system/status", |
|
|
headers=self.headers |
|
|
) |
|
|
|
|
|
if stats_response.status_code != 200: |
|
|
return {} |
|
|
|
|
|
stats = stats_response.json() |
|
|
|
|
|
|
|
|
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 |
|
|
|
|
|
|
|
|
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 = { |
|
|
'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' |
|
|
} |
|
|
] |
|
|
} |
|
|
|
|
|
|
|
|
Path(test_mirror['source_path']).mkdir(parents=True, exist_ok=True) |
|
|
|
|
|
|
|
|
if client.setup_dto_mirror(test_mirror): |
|
|
print("β
Syncthing mirror setup test completed") |
|
|
|
|
|
|
|
|
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") |