| |
| """ |
| DTO Jira Automation - Event-driven Jira ticket management |
| Listens to NATS events and automatically manages Jira tickets for Class-A runs |
| """ |
|
|
| import asyncio |
| import json |
| from typing import Dict, Any, Optional |
| from datetime import datetime |
|
|
| from nats.aio.client import Client as NATS |
| from jira_client import DTOJiraClient |
|
|
| class DTOJiraAutomation: |
| def __init__(self, nats_servers: list = ["nats://localhost:4222"]): |
| self.nats_servers = nats_servers |
| self.nats_client = NATS() |
| self.jira_client = DTOJiraClient() |
| self.ticket_cache = {} |
| |
| async def connect(self) -> bool: |
| """Connect to NATS and Jira""" |
| try: |
| |
| await self.nats_client.connect(servers=self.nats_servers) |
| print("β
Connected to NATS") |
| |
| |
| if not self.jira_client.test_connection(): |
| print("β οΈ Jira not available - running in monitoring mode only") |
| |
| return True |
| |
| except Exception as e: |
| print(f"β Connection failed: {e}") |
| return False |
| |
| async def handle_run_planned(self, event_data: Dict[str, Any]): |
| """Handle RUN_PLANNED event - create Jira ticket for Class-A runs""" |
| run_id = event_data.get('run_id') |
| data_class = event_data.get('data_class', '').upper() |
| |
| |
| if data_class != 'CLASS_A': |
| print(f"βΉοΈ Skipping ticket creation for {data_class} run: {run_id}") |
| return |
| |
| print(f"π« Creating Jira ticket for Class-A run: {run_id}") |
| |
| |
| run_data = { |
| 'run_id': run_id, |
| 'manifest_path': event_data.get('manifest_path'), |
| 'data_size_bytes': event_data.get('data_size_bytes'), |
| 'initiated_by': event_data.get('initiated_by'), |
| 'environment': event_data.get('environment'), |
| 'estimated_duration': event_data.get('estimated_duration') |
| } |
| |
| ticket_key = self.jira_client.create_class_a_ticket(run_data) |
| |
| if ticket_key: |
| self.ticket_cache[run_id] = ticket_key |
| print(f"β
Created ticket {ticket_key} for run {run_id}") |
| else: |
| print(f"β Failed to create ticket for run {run_id}") |
| |
| async def handle_preflight_passed(self, event_data: Dict[str, Any]): |
| """Handle PREFLIGHT_PASSED event - update ticket status""" |
| run_id = event_data.get('run_id') |
| ticket_key = self.ticket_cache.get(run_id) |
| |
| if not ticket_key: |
| print(f"βΉοΈ No ticket found for run: {run_id}") |
| return |
| |
| comment = f"Pre-flight checks completed successfully for run {run_id}" |
| self.jira_client.update_ticket_status(ticket_key, "in_progress", comment) |
| print(f"β
Updated ticket {ticket_key} - preflight passed") |
| |
| async def handle_preflight_failed(self, event_data: Dict[str, Any]): |
| """Handle PREFLIGHT_FAILED event - mark ticket as failed""" |
| run_id = event_data.get('run_id') |
| ticket_key = self.ticket_cache.get(run_id) |
| |
| if not ticket_key: |
| return |
| |
| error_details = event_data.get('error_details', 'Pre-flight validation failed') |
| comment = f"Pre-flight checks failed for run {run_id}: {error_details}" |
| |
| self.jira_client.update_ticket_status(ticket_key, "failed", comment) |
| print(f"β Updated ticket {ticket_key} - preflight failed") |
| |
| async def handle_transfer_started(self, event_data: Dict[str, Any]): |
| """Handle TRANSFER_STARTED event - add progress comment""" |
| run_id = event_data.get('run_id') |
| ticket_key = self.ticket_cache.get(run_id) |
| |
| if not ticket_key: |
| return |
| |
| transfer_method = event_data.get('transfer_method', 'unknown') |
| source_host = event_data.get('source_host', 'unknown') |
| target_host = event_data.get('target_host', 'unknown') |
| |
| comment = f""" |
| Data transfer started for run {run_id}: |
| β’ Method: {transfer_method} |
| β’ Source: {source_host} |
| β’ Target: {target_host} |
| β’ Started: {datetime.now().strftime('%Y-%m-%d %H:%M UTC')} |
| """.strip() |
| |
| self.jira_client.update_ticket_status(ticket_key, "in_progress", comment) |
| print(f"π Updated ticket {ticket_key} - transfer started") |
| |
| async def handle_slo_breach(self, event_data: Dict[str, Any]): |
| """Handle SLO_BREACH event - add urgent comment""" |
| run_id = event_data.get('run_id') |
| ticket_key = self.ticket_cache.get(run_id) |
| |
| if not ticket_key: |
| return |
| |
| sli_name = event_data.get('sli_name') |
| expected_value = event_data.get('expected_value') |
| actual_value = event_data.get('actual_value') |
| breach_duration = event_data.get('breach_duration_seconds', 0) |
| |
| comment = f""" |
| π¨ SLO BREACH DETECTED for run {run_id}: |
| β’ SLI: {sli_name} |
| β’ Expected: {expected_value} |
| β’ Actual: {actual_value} |
| β’ Breach Duration: {breach_duration}s |
| β’ Timestamp: {datetime.now().strftime('%Y-%m-%d %H:%M UTC')} |
| |
| Manual intervention may be required. |
| """.strip() |
| |
| |
| response = self.jira_client.add_run_metrics(ticket_key, { |
| 'slo_breach': True, |
| 'breach_details': comment |
| }) |
| |
| print(f"π¨ Added SLO breach alert to ticket {ticket_key}") |
| |
| async def handle_run_completed(self, event_data: Dict[str, Any]): |
| """Handle RUN_COMPLETED event - add metrics and close ticket""" |
| run_id = event_data.get('run_id') |
| ticket_key = self.ticket_cache.get(run_id) |
| |
| if not ticket_key: |
| return |
| |
| |
| metrics = { |
| 'average_throughput_mbps': event_data.get('average_throughput_mbps'), |
| 'total_duration_seconds': event_data.get('total_duration_seconds'), |
| 'data_size_gb': event_data.get('data_size_bytes', 0) / (1024**3), |
| 'transfer_method': event_data.get('transfer_method'), |
| 'validation_passed': event_data.get('validation_passed'), |
| 'artifacts': event_data.get('artifacts', []) |
| } |
| |
| |
| self.jira_client.add_run_metrics(ticket_key, metrics) |
| |
| |
| if event_data.get('final_status') == 'SUCCESS': |
| self.jira_client.update_ticket_status(ticket_key, "completed", |
| "Run completed successfully. All validations passed.") |
| print(f"β
Completed ticket {ticket_key} - run successful") |
| else: |
| self.jira_client.update_ticket_status(ticket_key, "failed", |
| f"Run failed: {event_data.get('error_message', 'Unknown error')}") |
| print(f"β Failed ticket {ticket_key} - run unsuccessful") |
| |
| async def handle_run_rolled_back(self, event_data: Dict[str, Any]): |
| """Handle ROLLBACK_COMPLETED event - reopen ticket""" |
| run_id = event_data.get('run_id') |
| ticket_key = self.ticket_cache.get(run_id) |
| |
| if not ticket_key: |
| return |
| |
| reason = event_data.get('rollback_reason', 'Manual rollback requested') |
| comment = f""" |
| π Rollback completed for run {run_id}: |
| β’ Reason: {reason} |
| β’ Rollback Time: {datetime.now().strftime('%Y-%m-%d %H:%M UTC')} |
| β’ Status: Data restored to previous state |
| """.strip() |
| |
| self.jira_client.update_ticket_status(ticket_key, "rolled_back", comment) |
| print(f"π Reopened ticket {ticket_key} - rollback completed") |
| |
| async def process_event(self, msg): |
| """Process incoming NATS event""" |
| try: |
| event_data = json.loads(msg.data.decode()) |
| event_type = event_data.get('event_type') |
| |
| |
| handlers = { |
| 'RUN_PLANNED': self.handle_run_planned, |
| 'PREFLIGHT_PASSED': self.handle_preflight_passed, |
| 'PREFLIGHT_FAILED': self.handle_preflight_failed, |
| 'TRANSFER_STARTED': self.handle_transfer_started, |
| 'SLO_BREACH': self.handle_slo_breach, |
| 'RUN_COMPLETED': self.handle_run_completed, |
| 'ROLLBACK_COMPLETED': self.handle_run_rolled_back |
| } |
| |
| handler = handlers.get(event_type) |
| if handler: |
| await handler(event_data) |
| else: |
| print(f"βΉοΈ No handler for event type: {event_type}") |
| |
| except Exception as e: |
| print(f"β Error processing event: {e}") |
| |
| async def start_automation(self): |
| """Start listening for DTO events""" |
| try: |
| |
| await self.nats_client.subscribe("dto.events.>", cb=self.process_event) |
| print("β
Started Jira automation - listening for DTO events") |
| |
| |
| while True: |
| await asyncio.sleep(1) |
| |
| except KeyboardInterrupt: |
| print("\nπ Stopping Jira automation...") |
| except Exception as e: |
| print(f"β Automation error: {e}") |
| finally: |
| await self.nats_client.close() |
| |
| async def sync_existing_tickets(self): |
| """Sync existing Jira tickets with run cache""" |
| try: |
| tickets = self.jira_client.get_class_a_tickets(status="In Progress") |
| |
| for ticket in tickets: |
| run_id = ticket.get('run_id') |
| if run_id: |
| self.ticket_cache[run_id] = ticket['key'] |
| print(f"π Synced ticket {ticket['key']} -> run {run_id}") |
| |
| print(f"β
Synced {len(tickets)} existing tickets") |
| |
| except Exception as e: |
| print(f"β Error syncing tickets: {e}") |
|
|
| |
| async def main(): |
| automation = DTOJiraAutomation() |
| |
| if await automation.connect(): |
| print("π« DTO Jira Automation started") |
| print("Monitoring events: RUN_PLANNED, PREFLIGHT_*, TRANSFER_STARTED, SLO_BREACH, RUN_COMPLETED, ROLLBACK_COMPLETED") |
| print("Press Ctrl+C to stop\n") |
| |
| |
| await automation.sync_existing_tickets() |
| |
| |
| await automation.start_automation() |
| else: |
| print("β Failed to start automation") |
|
|
| if __name__ == "__main__": |
| asyncio.run(main()) |