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
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
#!/usr/bin/env python3
"""
DTO Generator - Generates supervisord configs, runbooks, and validation artifacts
Compliant with OPERATING_AGREEMENT.md standards for manifest-driven infrastructure
"""

import os
import sys
import yaml
import json
from pathlib import Path
from jinja2 import Environment, FileSystemLoader
from datetime import datetime
from typing import Dict, Any, List

class DTOGenerator:
    def __init__(self, manifest_path: str = "dto_manifest.yaml"):
        self.root_path = Path(__file__).parent
        self.manifest_path = self.root_path / manifest_path
        self.templates_path = self.root_path / "templates"
        self.generated_path = self.root_path / "generated"
        self.schema_path = self.root_path / "schema"
        
        # Ensure directories exist
        self.generated_path.mkdir(exist_ok=True)
        self.templates_path.mkdir(exist_ok=True)
        self.schema_path.mkdir(exist_ok=True)
        
        # Load manifest
        if not self.manifest_path.exists():
            raise FileNotFoundError(f"DTO manifest not found: {self.manifest_path}")
            
        with open(self.manifest_path, 'r') as f:
            self.manifest = yaml.safe_load(f)
        
        # Setup Jinja2
        self.jinja_env = Environment(loader=FileSystemLoader(str(self.templates_path)))
    
    def validate_manifest(self) -> bool:
        """Validate DTO manifest against schema"""
        print("πŸ” Validating DTO manifest...")
        
        required_fields = ['apiVersion', 'kind', 'metadata', 'services', 'slo_specifications']
        for field in required_fields:
            if field not in self.manifest:
                print(f"❌ Missing required field: {field}")
                return False
        
        # Validate API version
        if self.manifest['apiVersion'] != 'dto/v1':
            print(f"❌ Unsupported API version: {self.manifest['apiVersion']}")
            return False
        
        # Validate port conflicts
        if not self._validate_port_conflicts():
            return False
        
        # Validate SLO tiers
        if not self._validate_slo_compliance():
            return False
        
        print("βœ… DTO manifest validation passed")
        return True
    
    def _validate_port_conflicts(self) -> bool:
        """Check for port conflicts across services"""
        used_ports = set()
        
        for category in ['infrastructure', 'applications', 'monitoring']:
            if category in self.manifest['services']:
                for service in self.manifest['services'][category]:
                    for port in service.get('ports', []):
                        if port in used_ports:
                            print(f"❌ Port conflict detected: {port} used by multiple services")
                            return False
                        used_ports.add(port)
        
        return True
    
    def _validate_slo_compliance(self) -> bool:
        """Validate SLO tier assignments"""
        valid_tiers = set(self.manifest['slo_specifications'].keys())
        
        for category in ['infrastructure', 'applications', 'monitoring']:
            if category in self.manifest['services']:
                for service in self.manifest['services'][category]:
                    slo_tier = service.get('slo_tier')
                    if slo_tier not in valid_tiers:
                        print(f"❌ Invalid SLO tier '{slo_tier}' for service {service['name']}")
                        return False
        
        return True
    
    def generate_supervisord_config(self, environment: str = "production") -> bool:
        """Generate supervisord configuration from manifest"""
        print(f"πŸ”§ Generating supervisord config for {environment}...")
        
        try:
            # Create supervisord template if it doesn't exist
            self._create_supervisord_template()
            
            template = self.jinja_env.get_template('supervisord.conf.j2')
            
            # Prepare template context
            context = {
                'manifest': self.manifest,
                'environment': environment,
                'generated_timestamp': datetime.now().isoformat(),
                'generated_by': 'DTO Generator v1.0',
                'base_path': str(self.root_path),
                'log_path': str(self.root_path / 'logs'),
                'services_path': str(self.root_path / 'services')
            }
            
            # Add environment-specific overlays
            if environment in self.manifest.get('environments', {}):
                context['env_config'] = self.manifest['environments'][environment]
            
            # Generate config
            config_content = template.render(**context)
            
            # Write to generated directory
            output_path = self.generated_path / f"supervisord-{environment}.conf"
            with open(output_path, 'w') as f:
                f.write(config_content)
            
            print(f"βœ… Generated supervisord config: {output_path}")
            return True
            
        except Exception as e:
            print(f"❌ Failed to generate supervisord config: {e}")
            return False
    
    def _create_supervisord_template(self):
        """Create default supervisord template if it doesn't exist"""
        template_path = self.templates_path / "supervisord.conf.j2"
        
        if not template_path.exists():
            template_content = '''# Generated Supervisord Configuration
# Environment: {{ environment }}
# Generated: {{ generated_timestamp }}
# Generated by: {{ generated_by }}

[unix_http_server]
file={{ services_path }}/supervisor.sock
chmod=0700

[supervisord]
logfile={{ log_path }}/supervisord.log
logfile_maxbytes=50MB
logfile_backups=10
loglevel=info
pidfile={{ services_path }}/supervisord.pid
nodaemon=false
minfds=1024
minprocs=200

[rpcinterface:supervisor]
supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface

[supervisorctl]
serverurl=unix://{{ services_path }}/supervisor.sock

{% for category, services in manifest.services.items() %}
# {{ category|title }} Services
{% for service in services %}
[program:{{ service.name }}]
{% if service.type == 'message-broker' and service.name == 'dto-nats-server' %}
command=/usr/local/bin/nats-server -c {{ base_path }}/events/nats/config.yaml
directory={{ base_path }}/events/nats
{% elif service.type == 'cache-cluster' and service.name == 'dto-dragonfly-cluster' %}
# Dragonfly cluster handled by separate node configs
{% elif service.type == 'graph-database' and service.name == 'dto-janusgraph' %}
command=/opt/janusgraph/bin/janusgraph-server.sh {{ base_path }}/lineage/janusgraph_config.properties
directory=/opt/janusgraph
{% else %}
command=/usr/bin/python3 {{ base_path }}/{{ service.name.replace('dto-', '').replace('-', '_') }}.py
directory={{ base_path }}/{{ service.name.replace('dto-', '').split('-')[0] }}
{% endif %}
user=adaptai
autostart=true
autorestart=true
redirect_stderr=true
stdout_logfile={{ log_path }}/{{ service.name.replace('dto-', '') }}.log
stdout_logfile_maxbytes=10MB
stdout_logfile_backups=5
{% if service.slo_tier == 'critical' %}
priority={{ 100 + loop.index }}
startsecs=10
startretries=2
{% elif service.slo_tier == 'high' %}
priority={{ 300 + loop.index }}
startsecs=5
startretries=3
{% else %}
priority={{ 400 + loop.index }}
startsecs=5
startretries=5
{% endif %}
environment=PYTHONPATH="{{ base_path }}"
{% if service.dependencies %}
# Dependencies: {{ service.dependencies|join(', ') }}
{% endif %}

{% endfor %}
{% endfor %}

# Service groups for management
{% for category, services in manifest.services.items() %}
[group:dto-{{ category }}]
programs={{ services|map(attribute='name')|join(',') }}
priority={{ 999 - loop.index0 }}

{% endfor %}'''

            with open(template_path, 'w') as f:
                f.write(template_content)
    
    def generate_runbooks(self) -> bool:
        """Generate operational runbooks for each service"""
        print("πŸ“š Generating operational runbooks...")
        
        try:
            # Create runbook template if it doesn't exist
            self._create_runbook_template()
            
            template = self.jinja_env.get_template('runbook.md.j2')
            runbooks_path = self.root_path / "docs" / "runbooks"
            runbooks_path.mkdir(parents=True, exist_ok=True)
            
            # Generate runbook for each service
            for category, services in self.manifest['services'].items():
                for service in services:
                    context = {
                        'service': service,
                        'category': category,
                        'manifest': self.manifest,
                        'slo_spec': self.manifest['slo_specifications'][service['slo_tier']],
                        'generated_timestamp': datetime.now().isoformat()
                    }
                    
                    runbook_content = template.render(**context)
                    runbook_path = runbooks_path / f"{service['name']}-runbook.md"
                    
                    with open(runbook_path, 'w') as f:
                        f.write(runbook_content)
                    
                    print(f"βœ… Generated runbook: {runbook_path}")
            
            return True
            
        except Exception as e:
            print(f"❌ Failed to generate runbooks: {e}")
            return False
    
    def _create_runbook_template(self):
        """Create default runbook template"""
        template_path = self.templates_path / "runbook.md.j2"
        
        if not template_path.exists():
            template_content = '''# {{ service.name }} Operational Runbook

**Generated:** {{ generated_timestamp }}  
**Service Category:** {{ category }}  
**SLO Tier:** {{ service.slo_tier }}  

## Service Overview

- **Name:** {{ service.name }}
- **Type:** {{ service.type }}
- **Runtime:** {{ service.runtime }}
- **Dependencies:** {% if service.dependencies %}{{ service.dependencies|join(', ') }}{% else %}None{% endif %}

## SLO Requirements

- **Availability:** {{ slo_spec.availability }}%
- **Latency P99:** {{ slo_spec.latency_p99 }}
- **Recovery Time:** {{ slo_spec.recovery_time }}
- **Max Downtime:** {{ slo_spec.max_downtime }}

## Port Configuration

{% if service.ports %}
{% for port in service.ports %}
- Port {{ port }}: {{ service.type }} service
{% endfor %}
{% else %}
No external ports configured.
{% endif %}

## Health Checks

### Manual Health Check
```bash
# Check service status
supervisorctl status {{ service.name }}

# View recent logs
tail -f /data/adaptai/platform/dataops/dto/logs/{{ service.name.replace('dto-', '') }}.log
```

### Automated Monitoring
- Health monitor endpoint: http://localhost:8090/health/{{ service.name }}
- Metrics available in Prometheus format

## Troubleshooting

### Common Issues

1. **Service Won't Start**
   - Check dependencies are running
   - Verify configuration files exist
   - Check file permissions
   - Review supervisord logs

2. **Performance Issues**
   - Monitor CPU and memory usage
   - Check for resource limits
   - Review SLO compliance metrics

3. **Connection Issues**
   - Verify port availability
   - Check firewall rules
   - Test network connectivity

### Recovery Procedures

1. **Restart Service**
   ```bash
   supervisorctl restart {{ service.name }}
   ```

2. **Full Recovery**
   ```bash
   supervisorctl stop {{ service.name }}
   # Investigate logs and fix issues
   supervisorctl start {{ service.name }}
   ```

3. **Emergency Escalation**
   - Critical services require immediate attention
   - Contact: dto-team@adapt.ai
   - Slack: #dto-alerts

## Configuration Files

{% if service.type == 'message-broker' %}
- NATS config: `/data/adaptai/platform/dataops/dto/events/nats/config.yaml`
{% elif service.type == 'cache-cluster' %}
- Dragonfly config: `/data/adaptai/platform/dataops/dto/cache/dragonfly_config.yaml`
{% elif service.type == 'graph-database' %}
- JanusGraph config: `/data/adaptai/platform/dataops/dto/lineage/janusgraph_config.properties`
{% endif %}

## Maintenance Windows

- **Planned maintenance:** Coordinate with dto-team
- **Emergency maintenance:** Follow incident response procedures
- **SLO impact:** Document any SLO violations

---
*This runbook is auto-generated from the DTO manifest. Do not edit manually.*'''

            with open(template_path, 'w') as f:
                f.write(template_content)
    
    def generate_ci_validation_schema(self) -> bool:
        """Generate CI validation schemas"""
        print("πŸ” Generating CI validation schemas...")
        
        try:
            # Port conflict validation schema
            port_schema = {
                "type": "object",
                "properties": {
                    "used_ports": {
                        "type": "array",
                        "items": {"type": "integer"},
                        "uniqueItems": True
                    }
                }
            }
            
            schema_file = self.schema_path / "port_validation.json"
            with open(schema_file, 'w') as f:
                json.dump(port_schema, f, indent=2)
            
            # SLO compliance schema
            slo_schema = {
                "type": "object",
                "properties": {
                    "services": {
                        "type": "array",
                        "items": {
                            "type": "object",
                            "properties": {
                                "name": {"type": "string"},
                                "slo_tier": {"enum": ["critical", "high", "standard"]},
                                "compliance_status": {"type": "boolean"}
                            },
                            "required": ["name", "slo_tier", "compliance_status"]
                        }
                    }
                }
            }
            
            slo_file = self.schema_path / "slo_compliance.json"
            with open(slo_file, 'w') as f:
                json.dump(slo_schema, f, indent=2)
            
            print("βœ… Generated CI validation schemas")
            return True
            
        except Exception as e:
            print(f"❌ Failed to generate validation schemas: {e}")
            return False
    
    def generate_all(self, environment: str = "production") -> bool:
        """Generate all artifacts"""
        print(f"πŸš€ Generating all DTO artifacts for {environment}...")
        
        success = True
        success &= self.validate_manifest()
        success &= self.generate_supervisord_config(environment)
        success &= self.generate_runbooks()
        success &= self.generate_ci_validation_schema()
        
        if success:
            print("βœ… All DTO artifacts generated successfully")
            print(f"πŸ“ Generated files location: {self.generated_path}")
            print(f"πŸ“š Runbooks location: {self.root_path}/docs/runbooks/")
        else:
            print("❌ Some artifacts failed to generate")
        
        return success

def main():
    """CLI entry point"""
    import argparse
    
    parser = argparse.ArgumentParser(description='DTO Generator - Generate infrastructure from manifests')
    parser.add_argument('--environment', '-e', default='production', 
                       choices=['development', 'staging', 'production'],
                       help='Target environment')
    parser.add_argument('--validate-only', action='store_true',
                       help='Only validate manifest, do not generate')
    parser.add_argument('--manifest', '-m', default='dto_manifest.yaml',
                       help='Path to DTO manifest file')
    
    args = parser.parse_args()
    
    try:
        generator = DTOGenerator(args.manifest)
        
        if args.validate_only:
            success = generator.validate_manifest()
        else:
            success = generator.generate_all(args.environment)
        
        sys.exit(0 if success else 1)
        
    except Exception as e:
        print(f"❌ DTO Generator failed: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main()