File size: 9,354 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
#!/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)