File size: 13,639 Bytes
fd357f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
#!/usr/bin/env python3
"""
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:
            # Check if JanusGraph is using incompatible Kryo version
            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()
                        
                        # Check for Kryo serialization errors
                        if "KryoSerializationException" in log_content:
                            issues['kryo_version_mismatch'] = True
                            issues['recommendations'].append("Switch to JSON serialization")
                        
                        # Check for class not found errors
                        if "ClassNotFoundException" in log_content:
                            # Extract class names
                            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")
                        
                        # Check for buffer size issues
                        if "Buffer overflow" in log_content or "BufferUnderflowException" in log_content:
                            issues['buffer_size_issues'] = True
                            issues['recommendations'].append("Increase serialization buffer size")
            
            # Check current configuration
            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:
            # Create fixed configuration
            fixed_config = self.generate_fixed_config()
            
            # Backup original 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}")
            
            # Write fixed configuration
            with open(self.config_path, 'w') as f:
                f.write(fixed_config)
            
            print(f"βœ… Applied serialization fixes to {self.config_path}")
            
            # Create custom serializer if needed
            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=cql
storage.hostname=localhost
storage.port=9042
storage.cql.keyspace=dto_lineage
storage.cql.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)
            
            # Create Java class for custom serializer
            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}")
            
            # Compile if javac is available
            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:
            # Import the lineage client to test connectivity
            from dto_lineage_client import DTOLineageClient
            
            client = DTOLineageClient()
            
            # Test connection with new serialization settings
            if client.connect():
                print("βœ… JanusGraph connection successful with fixed serialization")
                
                # Test basic operations
                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()
    
    # Step 1: Diagnose issues
    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")
    
    # Step 2: Apply fixes
    print("\n2. Applying serialization fixes...")
    if fixer.apply_serialization_fixes():
        print("βœ… Serialization fixes applied successfully")
    else:
        print("❌ Failed to apply fixes")
        return False
    
    # Step 3: Create troubleshooting guide
    print("\n3. Creating troubleshooting guide...")
    guide_path = fixer.create_troubleshooting_guide()
    
    # Step 4: Test fixes
    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()