| |
| """ |
| 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" |
| |
| |
| self.generated_path.mkdir(exist_ok=True) |
| self.templates_path.mkdir(exist_ok=True) |
| self.schema_path.mkdir(exist_ok=True) |
| |
| |
| 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) |
| |
| |
| 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 |
| |
| |
| if self.manifest['apiVersion'] != 'dto/v1': |
| print(f"β Unsupported API version: {self.manifest['apiVersion']}") |
| return False |
| |
| |
| if not self._validate_port_conflicts(): |
| return False |
| |
| |
| 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: |
| |
| self._create_supervisord_template() |
| |
| template = self.jinja_env.get_template('supervisord.conf.j2') |
| |
| |
| 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') |
| } |
| |
| |
| if environment in self.manifest.get('environments', {}): |
| context['env_config'] = self.manifest['environments'][environment] |
| |
| |
| config_content = template.render(**context) |
| |
| |
| 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: |
| |
| 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) |
| |
| |
| 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_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_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() |