#!/usr/bin/env python3 """ DTO Jira Webhooks - Handle Jira webhook events for bidirectional integration Receives webhooks from Jira and publishes events to NATS """ import json import hmac import hashlib from typing import Dict, Any, Optional from datetime import datetime from flask import Flask, request, jsonify from nats.aio.client import Client as NATS import asyncio import threading app = Flask(__name__) class DTOJiraWebhookHandler: def __init__(self, webhook_secret: Optional[str] = None, nats_servers: list = ["nats://localhost:4222"]): self.webhook_secret = webhook_secret self.nats_servers = nats_servers self.nats_client = None self.loop = None async def connect_nats(self): """Connect to NATS for event publishing""" try: self.nats_client = NATS() await self.nats_client.connect(servers=self.nats_servers) print("✅ Connected to NATS for webhook publishing") return True except Exception as e: print(f"❌ NATS connection failed: {e}") return False def verify_webhook_signature(self, payload: bytes, signature: str) -> bool: """Verify Jira webhook signature""" if not self.webhook_secret: return True # Skip verification if no secret configured expected_signature = hmac.new( self.webhook_secret.encode('utf-8'), payload, hashlib.sha256 ).hexdigest() return hmac.compare_digest(f"sha256={expected_signature}", signature) async def publish_dto_event(self, event_type: str, event_data: Dict[str, Any]): """Publish event to DTO NATS stream""" if not self.nats_client: return False try: event_payload = { 'event_id': f"jira-{datetime.now().isoformat()}", 'event_type': event_type, 'timestamp': datetime.now().isoformat(), 'source': 'jira-webhook', **event_data } await self.nats_client.publish( f"dto.events.jira.{event_type.lower()}", json.dumps(event_payload).encode() ) print(f"✅ Published {event_type} event to NATS") return True except Exception as e: print(f"❌ Error publishing event: {e}") return False def extract_run_id_from_ticket(self, issue_data: Dict[str, Any]) -> Optional[str]: """Extract DTO run ID from Jira ticket""" # Try custom field first custom_fields = issue_data.get('fields', {}) run_id = custom_fields.get('customfield_10001') # DTO Run ID field if run_id: return run_id # Fallback: extract from labels labels = custom_fields.get('labels', []) for label in labels: if label.startswith('run-'): return label[4:] # Remove 'run-' prefix # Fallback: extract from summary summary = custom_fields.get('summary', '') if 'Class-A Data Transfer:' in summary: parts = summary.split(':') if len(parts) > 1: return parts[1].strip() return None async def handle_issue_updated(self, webhook_data: Dict[str, Any]): """Handle Jira issue updated webhook""" issue = webhook_data.get('issue', {}) changelog = webhook_data.get('changelog', {}) # Check if this is a DTO ticket labels = issue.get('fields', {}).get('labels', []) if 'dto' not in labels or 'class-a' not in labels: return run_id = self.extract_run_id_from_ticket(issue) if not run_id: print("⚠️ Could not extract run ID from ticket") return # Process status changes for item in changelog.get('items', []): if item.get('field') == 'status': old_status = item.get('fromString') new_status = item.get('toString') print(f"📊 Ticket status changed: {old_status} -> {new_status} for run {run_id}") # Map Jira status changes to DTO events if new_status.lower() == 'cancelled': await self.publish_dto_event('MANUAL_CANCELLATION_REQUESTED', { 'run_id': run_id, 'ticket_key': issue.get('key'), 'cancelled_by': webhook_data.get('user', {}).get('displayName'), 'cancellation_time': datetime.now().isoformat() }) elif new_status.lower() == 'blocked': await self.publish_dto_event('MANUAL_INTERVENTION_REQUIRED', { 'run_id': run_id, 'ticket_key': issue.get('key'), 'blocked_by': webhook_data.get('user', {}).get('displayName'), 'block_reason': 'Manual block via Jira ticket' }) async def handle_comment_created(self, webhook_data: Dict[str, Any]): """Handle new comment on DTO ticket""" issue = webhook_data.get('issue', {}) comment = webhook_data.get('comment', {}) # Check if this is a DTO ticket labels = issue.get('fields', {}).get('labels', []) if 'dto' not in labels or 'class-a' not in labels: return run_id = self.extract_run_id_from_ticket(issue) if not run_id: return comment_body = comment.get('body', '') comment_author = comment.get('author', {}).get('displayName', 'Unknown') # Check for rollback requests in comments if 'rollback' in comment_body.lower() or 'abort' in comment_body.lower(): await self.publish_dto_event('ROLLBACK_REQUESTED', { 'run_id': run_id, 'ticket_key': issue.get('key'), 'requested_by': comment_author, 'request_reason': comment_body[:200], # First 200 chars 'request_time': datetime.now().isoformat() }) print(f"🔄 Rollback requested via Jira comment for run {run_id}") def process_webhook(self, webhook_data: Dict[str, Any]) -> Dict[str, Any]: """Process Jira webhook synchronously""" webhook_event = webhook_data.get('webhookEvent') if not webhook_event: return {'status': 'error', 'message': 'No webhook event type'} # Queue async processing if webhook_event == 'jira:issue_updated': asyncio.run_coroutine_threadsafe( self.handle_issue_updated(webhook_data), self.loop ) elif webhook_event == 'comment_created': asyncio.run_coroutine_threadsafe( self.handle_comment_created(webhook_data), self.loop ) else: print(f"ℹ️ Unhandled webhook event: {webhook_event}") return {'status': 'success', 'message': 'Webhook processed'} # Global webhook handler webhook_handler = DTOJiraWebhookHandler() @app.route('/webhook/jira', methods=['POST']) def handle_jira_webhook(): """Flask endpoint for Jira webhooks""" try: # Verify signature if configured signature = request.headers.get('X-Hub-Signature-256', '') if not webhook_handler.verify_webhook_signature(request.data, signature): return jsonify({'error': 'Invalid signature'}), 401 # Process webhook webhook_data = request.get_json() result = webhook_handler.process_webhook(webhook_data) return jsonify(result), 200 except Exception as e: print(f"❌ Webhook processing error: {e}") return jsonify({'error': 'Internal server error'}), 500 @app.route('/health', methods=['GET']) def health_check(): """Health check endpoint""" return jsonify({ 'status': 'healthy', 'service': 'dto-jira-webhooks', 'timestamp': datetime.now().isoformat() }) def run_async_setup(): """Setup async components in background thread""" loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) webhook_handler.loop = loop async def setup(): await webhook_handler.connect_nats() # Keep the loop running try: while True: await asyncio.sleep(1) except Exception as e: print(f"❌ Async loop error: {e}") loop.run_until_complete(setup()) if __name__ == '__main__': print("🎫 Starting DTO Jira Webhook Handler...") # Start async components in background async_thread = threading.Thread(target=run_async_setup, daemon=True) async_thread.start() print("✅ Webhook handler ready") print("📬 Listening for Jira webhooks at /webhook/jira") print("🏥 Health check available at /health") # Start Flask app app.run(host='0.0.0.0', port=5000, debug=False)