File size: 10,961 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
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
#!/usr/bin/env python3
"""
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 = {}  # run_id -> ticket_key mapping
        
    async def connect(self) -> bool:
        """Connect to NATS and Jira"""
        try:
            # Connect to NATS
            await self.nats_client.connect(servers=self.nats_servers)
            print("βœ… Connected to NATS")
            
            # Test Jira connection
            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()
        
        # Only create tickets for Class-A runs
        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}")
        
        # Extract run data for ticket creation
        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()
        
        # Add comment without changing status
        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
        
        # Extract performance metrics
        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', [])
        }
        
        # Add metrics as comment
        self.jira_client.add_run_metrics(ticket_key, metrics)
        
        # Update status based on success
        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')
            
            # Route to appropriate handler
            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:
            # Subscribe to DTO events
            await self.nats_client.subscribe("dto.events.>", cb=self.process_event)
            print("βœ… Started Jira automation - listening for DTO events")
            
            # Keep running
            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}")

# CLI entry point
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")
        
        # Sync existing tickets
        await automation.sync_existing_tickets()
        
        # Start automation
        await automation.start_automation()
    else:
        print("❌ Failed to start automation")

if __name__ == "__main__":
    asyncio.run(main())