| |
| """ |
| JanusGraph Serialization Fix - Resolves Kryo serialization issues |
| Implements proper serialization configuration and troubleshooting |
| """ |
|
|
| import os |
| import json |
| import subprocess |
| from typing import Dict, Any, List |
| from pathlib import Path |
|
|
| class JanusGraphSerializationFix: |
| def __init__(self, janusgraph_home: str = "/opt/janusgraph"): |
| self.janusgraph_home = Path(janusgraph_home) |
| self.config_path = self.janusgraph_home / "conf" / "janusgraph.properties" |
| |
| def diagnose_serialization_issues(self) -> Dict[str, Any]: |
| """Diagnose common JanusGraph serialization problems""" |
| issues = { |
| 'kryo_version_mismatch': False, |
| 'missing_serializers': [], |
| 'buffer_size_issues': False, |
| 'class_not_found_errors': [], |
| 'recommendations': [] |
| } |
| |
| try: |
| |
| log_files = list(self.janusgraph_home.glob("logs/*.log")) |
| |
| for log_file in log_files: |
| if log_file.exists(): |
| with open(log_file, 'r') as f: |
| log_content = f.read() |
| |
| |
| if "KryoSerializationException" in log_content: |
| issues['kryo_version_mismatch'] = True |
| issues['recommendations'].append("Switch to JSON serialization") |
| |
| |
| if "ClassNotFoundException" in log_content: |
| |
| import re |
| class_errors = re.findall(r'ClassNotFoundException: ([^\s]+)', log_content) |
| issues['class_not_found_errors'].extend(class_errors) |
| issues['recommendations'].append("Add missing serializer classes") |
| |
| |
| if "Buffer overflow" in log_content or "BufferUnderflowException" in log_content: |
| issues['buffer_size_issues'] = True |
| issues['recommendations'].append("Increase serialization buffer size") |
| |
| |
| if self.config_path.exists(): |
| with open(self.config_path, 'r') as f: |
| config_content = f.read() |
| |
| if "KryoSerializer" in config_content: |
| issues['recommendations'].append("Replace KryoSerializer with StandardSerializer") |
| |
| if "storage.serializer.buffer-size" not in config_content: |
| issues['recommendations'].append("Configure explicit buffer size") |
| |
| print("β
Serialization diagnosis completed") |
| return issues |
| |
| except Exception as e: |
| print(f"β Error diagnosing serialization: {e}") |
| return issues |
| |
| def apply_serialization_fixes(self) -> bool: |
| """Apply serialization fixes to JanusGraph configuration""" |
| try: |
| |
| fixed_config = self.generate_fixed_config() |
| |
| |
| if self.config_path.exists(): |
| backup_path = self.config_path.with_suffix('.properties.backup') |
| subprocess.run(['cp', str(self.config_path), str(backup_path)], check=True) |
| print(f"β
Backed up original config to {backup_path}") |
| |
| |
| with open(self.config_path, 'w') as f: |
| f.write(fixed_config) |
| |
| print(f"β
Applied serialization fixes to {self.config_path}") |
| |
| |
| self.create_custom_serializer() |
| |
| return True |
| |
| except Exception as e: |
| print(f"β Error applying fixes: {e}") |
| return False |
| |
| def generate_fixed_config(self) -> str: |
| """Generate JanusGraph configuration with serialization fixes""" |
| config = """# JanusGraph Configuration with Serialization Fixes |
| # Resolves Kryo serialization issues for DTO lineage tracking |
| |
| # === STORAGE BACKEND === |
| storage.backend=cassandra |
| storage.hostname=localhost |
| storage.port=9042 |
| storage.cassandra.keyspace=dto_lineage |
| storage.cassandra.replication-factor=2 |
| |
| # === SERIALIZATION FIXES === |
| # FIX 1: Use StandardSerializer instead of KryoSerializer |
| storage.serializer=org.janusgraph.graphdb.serializer.StandardSerializer |
| |
| # FIX 2: Disable problematic Kryo serialization |
| storage.serializer.class=org.janusgraph.graphdb.serializer.StandardSerializer |
| |
| # FIX 3: Increase buffer sizes to prevent overflow |
| storage.serializer.buffer-size=51200 |
| storage.buffer-size=2048 |
| |
| # FIX 4: Enable parallel operations with proper serialization |
| storage.parallel-backend-ops=true |
| storage.serializer.parallel-backend-ops=true |
| |
| # === INDEX BACKEND === |
| index.search.backend=elasticsearch |
| index.search.hostname=localhost |
| index.search.port=9200 |
| index.search.elasticsearch.index-name=dto_lineage |
| |
| # === GREMLIN SERVER CONFIG === |
| # FIX 5: Use JSON serialization for Gremlin WebSocket |
| gremlin.server.serializers=application/json |
| gremlin.server.serializer.config.ioRegistries=[org.janusgraph.graphdb.tinkerpop.JanusGraphIoRegistry] |
| |
| # === CACHE SETTINGS === |
| cache.db-cache=true |
| cache.db-cache-size=0.25 |
| cache.db-cache-time=180000 |
| cache.db-cache-clean-wait=20 |
| |
| # === TRANSACTION SETTINGS === |
| storage.transactions=true |
| storage.lock.retry=3 |
| storage.setup-wait=60000 |
| |
| # === PERFORMANCE TUNING === |
| storage.batch-loading=false |
| storage.read-time=10000 |
| storage.write-time=100000 |
| |
| # === SCHEMA SETTINGS === |
| schema.default=none |
| schema.constraints=true |
| |
| # === LOGGING === |
| log4j.rootLogger=WARN, stdout |
| log4j.appender.stdout=org.apache.log4j.ConsoleAppender |
| log4j.appender.stdout.layout=org.apache.log4j.PatternLayout |
| log4j.appender.stdout.layout.ConversionPattern=%d{HH:mm:ss} %-5p %c{1} - %m%n |
| |
| # === METRICS === |
| metrics.enabled=true |
| metrics.prefix=dto.lineage |
| """ |
| return config |
| |
| def create_custom_serializer(self) -> bool: |
| """Create custom serializer for DTO-specific data types""" |
| try: |
| serializer_dir = self.janusgraph_home / "lib" / "dto" |
| serializer_dir.mkdir(parents=True, exist_ok=True) |
| |
| |
| java_code = ''' |
| package ai.adapt.dto.serialization; |
| |
| import org.janusgraph.core.attribute.AttributeSerializer; |
| import org.janusgraph.diskstorage.ScanBuffer; |
| import org.janusgraph.diskstorage.WriteBuffer; |
| import org.janusgraph.graphdb.database.serialize.attribute.StringSerializer; |
| |
| /** |
| * Custom serializer for DTO data types |
| * Handles specific DTO objects with proper serialization |
| */ |
| public class DTOCustomSerializer implements AttributeSerializer<String> { |
| |
| private final StringSerializer stringSerializer = new StringSerializer(); |
| |
| @Override |
| public String read(ScanBuffer buffer) { |
| return stringSerializer.read(buffer); |
| } |
| |
| @Override |
| public void write(WriteBuffer buffer, String attribute) { |
| stringSerializer.write(buffer, attribute); |
| } |
| |
| @Override |
| public String convert(Object value) { |
| if (value == null) return null; |
| return value.toString(); |
| } |
| } |
| ''' |
| |
| java_file = serializer_dir / "DTOCustomSerializer.java" |
| with open(java_file, 'w') as f: |
| f.write(java_code) |
| |
| print(f"β
Created custom serializer: {java_file}") |
| |
| |
| try: |
| classpath = str(self.janusgraph_home / "lib" / "*") |
| subprocess.run([ |
| 'javac', '-cp', classpath, |
| str(java_file) |
| ], check=True, capture_output=True) |
| print("β
Compiled custom serializer") |
| except (subprocess.CalledProcessError, FileNotFoundError): |
| print("β οΈ Could not compile serializer (javac not available)") |
| |
| return True |
| |
| except Exception as e: |
| print(f"β Error creating custom serializer: {e}") |
| return False |
| |
| def test_serialization_fix(self) -> bool: |
| """Test if serialization issues are resolved""" |
| try: |
| |
| from dto_lineage_client import DTOLineageClient |
| |
| client = DTOLineageClient() |
| |
| |
| if client.connect(): |
| print("β
JanusGraph connection successful with fixed serialization") |
| |
| |
| test_vertex_id = client.record_dataset( |
| "/test/serialization_fix.dat", |
| "sha256:test123", |
| 1024, |
| "TEST", |
| "development" |
| ) |
| |
| if test_vertex_id: |
| print("β
Serialization test successful - vertex creation works") |
| client.close() |
| return True |
| else: |
| print("β Serialization test failed - vertex creation failed") |
| client.close() |
| return False |
| else: |
| print("β JanusGraph connection failed - serialization issues persist") |
| return False |
| |
| except Exception as e: |
| print(f"β Serialization test error: {e}") |
| return False |
| |
| def create_troubleshooting_guide(self) -> str: |
| """Create troubleshooting guide for serialization issues""" |
| guide = """ |
| # JanusGraph Serialization Troubleshooting Guide |
| |
| ## Common Issues and Solutions |
| |
| ### 1. KryoSerializationException |
| **Symptoms:** ClassCastException, buffer overflow errors |
| **Solution:** Switch to StandardSerializer |
| ``` |
| storage.serializer=org.janusgraph.graphdb.serializer.StandardSerializer |
| ``` |
| |
| ### 2. Buffer Overflow Issues |
| **Symptoms:** BufferUnderflowException, incomplete data |
| **Solution:** Increase buffer sizes |
| ``` |
| storage.serializer.buffer-size=51200 |
| storage.buffer-size=2048 |
| ``` |
| |
| ### 3. WebSocket Connection Issues |
| **Symptoms:** Gremlin client connection failures |
| **Solution:** Use JSON serialization for WebSocket |
| ``` |
| gremlin.server.serializers=application/json |
| ``` |
| |
| ### 4. Class Not Found Errors |
| **Symptoms:** ClassNotFoundException during serialization |
| **Solution:** Add custom serializers and proper classpath |
| |
| ### 5. Performance Issues |
| **Symptoms:** Slow serialization/deserialization |
| **Solution:** Enable parallel operations |
| ``` |
| storage.parallel-backend-ops=true |
| storage.serializer.parallel-backend-ops=true |
| ``` |
| |
| ## Diagnostic Commands |
| |
| 1. Check JanusGraph logs: |
| ```bash |
| tail -f /opt/janusgraph/logs/janusgraph.log |
| ``` |
| |
| 2. Test connectivity: |
| ```python |
| from dto_lineage_client import DTOLineageClient |
| client = DTOLineageClient() |
| client.connect() |
| ``` |
| |
| 3. Validate configuration: |
| ```bash |
| /opt/janusgraph/bin/janusgraph.sh start |
| ``` |
| |
| ## Recovery Steps |
| |
| 1. Stop JanusGraph server |
| 2. Backup current configuration |
| 3. Apply serialization fixes |
| 4. Clear problematic cache/data if needed |
| 5. Restart JanusGraph |
| 6. Test connectivity |
| |
| ## Prevention |
| |
| 1. Always use StandardSerializer for new deployments |
| 2. Set explicit buffer sizes |
| 3. Use JSON serialization for client connections |
| 4. Monitor logs for serialization warnings |
| """ |
| |
| guide_path = self.janusgraph_home / "SERIALIZATION_TROUBLESHOOTING.md" |
| with open(guide_path, 'w') as f: |
| f.write(guide) |
| |
| print(f"β
Created troubleshooting guide: {guide_path}") |
| return str(guide_path) |
|
|
| def main(): |
| """Main function to fix JanusGraph serialization issues""" |
| print("π§ JanusGraph Serialization Fix") |
| print("=" * 50) |
| |
| fixer = JanusGraphSerializationFix() |
| |
| |
| print("1. Diagnosing serialization issues...") |
| issues = fixer.diagnose_serialization_issues() |
| |
| if issues['recommendations']: |
| print(f"Found {len(issues['recommendations'])} issues to fix:") |
| for recommendation in issues['recommendations']: |
| print(f" β’ {recommendation}") |
| else: |
| print("No serialization issues detected") |
| |
| |
| print("\n2. Applying serialization fixes...") |
| if fixer.apply_serialization_fixes(): |
| print("β
Serialization fixes applied successfully") |
| else: |
| print("β Failed to apply fixes") |
| return False |
| |
| |
| print("\n3. Creating troubleshooting guide...") |
| guide_path = fixer.create_troubleshooting_guide() |
| |
| |
| print("\n4. Testing serialization fixes...") |
| if fixer.test_serialization_fix(): |
| print("β
Serialization fixes verified successfully") |
| print("\nJanusGraph is now ready for DTO lineage tracking!") |
| else: |
| print("β Serialization issues persist") |
| print(f"See troubleshooting guide: {guide_path}") |
| |
| return True |
|
|
| if __name__ == "__main__": |
| main() |