#!/usr/bin/env python3 """ DTO Jira Client - Automates ticket creation for Class-A data transfer runs """ import os import json from typing import Dict, Any, Optional, List from datetime import datetime, timezone import requests from requests.auth import HTTPBasicAuth class DTOJiraClient: def __init__(self, server_url: Optional[str] = None, username: Optional[str] = None, api_token: Optional[str] = None): self.server_url = server_url or os.getenv('JIRA_SERVER_URL') self.username = username or os.getenv('JIRA_USERNAME') self.api_token = api_token or os.getenv('JIRA_API_TOKEN') self.auth = HTTPBasicAuth(self.username, self.api_token) if self.username and self.api_token else None self.headers = { 'Content-Type': 'application/json', 'Accept': 'application/json' } def test_connection(self) -> bool: """Test Jira API connectivity""" if not self.auth or not self.server_url: print("❌ Jira credentials not configured") return False try: response = requests.get( f"{self.server_url}/rest/api/3/myself", auth=self.auth, headers=self.headers, timeout=10 ) if response.status_code == 200: print("✅ Connected to Jira API") return True else: print(f"❌ Jira connection failed: {response.status_code}") return False except Exception as e: print(f"❌ Error connecting to Jira: {e}") return False def create_class_a_ticket(self, run_data: Dict[str, Any]) -> Optional[str]: """Create Jira ticket for Class-A data transfer run""" if not self.auth: print("❌ Jira not configured") return None run_id = run_data.get('run_id', 'unknown') manifest_path = run_data.get('manifest_path', 'N/A') data_size_gb = round(run_data.get('data_size_bytes', 0) / (1024**3), 2) initiated_by = run_data.get('initiated_by', 'system') environment = run_data.get('environment', 'staging') # Format ticket summary and description summary = f"Class-A Data Transfer: {run_id}" description = f""" *Automated Class-A Data Transfer Ticket* *Run Details:* • Run ID: {run_id} • Manifest: {manifest_path} • Data Size: {data_size_gb} GB • Environment: {environment.upper()} • Initiated By: {initiated_by} • Created: {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M UTC')} *Pre-flight Checklist:* - [ ] Manifest validation completed - [ ] Source data integrity verified - [ ] Target storage capacity confirmed - [ ] Network bandwidth reserved - [ ] Approval workflow triggered *Post-transfer Validation:* - [ ] Checksum verification passed - [ ] Data lineage recorded - [ ] Performance metrics logged - [ ] Cleanup procedures executed *Links:* • DTO Dashboard: https://dto.adapt.ai/runs/{run_id} • Logs: /data/adaptai/platform/dataops/dto/logs/{run_id}/ This ticket tracks the execution and validation of a Class-A data transfer operation. """.strip() # Create ticket payload ticket_data = { "fields": { "project": {"key": "DTO"}, "summary": summary, "description": { "type": "doc", "version": 1, "content": [ { "type": "paragraph", "content": [ {"type": "text", "text": description} ] } ] }, "issuetype": {"name": "Task"}, "priority": {"name": "High"}, "labels": [ "dto", "class-a", "data-transfer", f"env-{environment}", f"run-{run_id}" ], "customfield_10001": run_id, # DTO Run ID custom field "customfield_10002": data_size_gb, # Data Size GB custom field "components": [{"name": "Data Transfer Operations"}] } } try: response = requests.post( f"{self.server_url}/rest/api/3/issue", auth=self.auth, headers=self.headers, data=json.dumps(ticket_data), timeout=30 ) if response.status_code == 201: ticket_key = response.json()['key'] print(f"✅ Created Jira ticket: {ticket_key} for run {run_id}") return ticket_key else: print(f"❌ Failed to create ticket: {response.status_code} - {response.text}") return None except Exception as e: print(f"❌ Error creating Jira ticket: {e}") return None def update_ticket_status(self, ticket_key: str, status: str, comment: Optional[str] = None) -> bool: """Update ticket status based on run progress""" if not self.auth: return False # Map DTO statuses to Jira transitions status_transitions = { "in_progress": "Start Progress", "validation": "Move to Validation", "completed": "Done", "failed": "Move to Failed", "rolled_back": "Reopen" } transition_name = status_transitions.get(status) if not transition_name: print(f"❌ Unknown status: {status}") return False try: # Get available transitions transitions_response = requests.get( f"{self.server_url}/rest/api/3/issue/{ticket_key}/transitions", auth=self.auth, headers=self.headers ) if transitions_response.status_code != 200: print(f"❌ Failed to get transitions: {transitions_response.status_code}") return False transitions = transitions_response.json()['transitions'] transition_id = None for transition in transitions: if transition['name'].lower() == transition_name.lower(): transition_id = transition['id'] break if not transition_id: print(f"❌ Transition '{transition_name}' not available") return False # Perform transition transition_data = { "transition": {"id": transition_id} } if comment: transition_data["update"] = { "comment": [ { "add": { "body": { "type": "doc", "version": 1, "content": [ { "type": "paragraph", "content": [ {"type": "text", "text": comment} ] } ] } } } ] } response = requests.post( f"{self.server_url}/rest/api/3/issue/{ticket_key}/transitions", auth=self.auth, headers=self.headers, data=json.dumps(transition_data) ) if response.status_code == 204: print(f"✅ Updated ticket {ticket_key} to {status}") return True else: print(f"❌ Failed to update ticket: {response.status_code}") return False except Exception as e: print(f"❌ Error updating ticket: {e}") return False def add_run_metrics(self, ticket_key: str, metrics: Dict[str, Any]) -> bool: """Add performance metrics as ticket comment""" if not self.auth: return False throughput = metrics.get('average_throughput_mbps', 0) duration = metrics.get('total_duration_seconds', 0) data_size_gb = metrics.get('data_size_gb', 0) duration_str = f"{duration//3600}h {(duration%3600)//60}m {duration%60}s" comment_text = f""" *Run Completed - Performance Metrics:* • Average Throughput: {throughput:.1f} MB/s • Total Duration: {duration_str} • Data Transferred: {data_size_gb:.2f} GB • Transfer Method: {metrics.get('transfer_method', 'ssh+dd')} • Validation: {'✅ PASSED' if metrics.get('validation_passed') else '❌ FAILED'} *Artifacts Generated:* {chr(10).join(f'• {artifact}' for artifact in metrics.get('artifacts', []))} """.strip() comment_data = { "body": { "type": "doc", "version": 1, "content": [ { "type": "paragraph", "content": [ {"type": "text", "text": comment_text} ] } ] } } try: response = requests.post( f"{self.server_url}/rest/api/3/issue/{ticket_key}/comment", auth=self.auth, headers=self.headers, data=json.dumps(comment_data) ) if response.status_code == 201: print(f"✅ Added metrics to ticket {ticket_key}") return True else: print(f"❌ Failed to add comment: {response.status_code}") return False except Exception as e: print(f"❌ Error adding metrics: {e}") return False def link_to_confluence_report(self, ticket_key: str, confluence_url: str) -> bool: """Link Confluence post-run report to ticket""" if not self.auth: return False link_data = { "object": { "url": confluence_url, "title": f"Post-Run Report: {ticket_key}", "summary": "Detailed post-run analysis and validation report" } } try: response = requests.post( f"{self.server_url}/rest/api/3/issue/{ticket_key}/remotelink", auth=self.auth, headers=self.headers, data=json.dumps(link_data) ) if response.status_code == 201: print(f"✅ Linked Confluence report to {ticket_key}") return True else: print(f"❌ Failed to link report: {response.status_code}") return False except Exception as e: print(f"❌ Error linking report: {e}") return False def get_class_a_tickets(self, status: Optional[str] = None) -> List[Dict[str, Any]]: """Get all Class-A transfer tickets""" if not self.auth: return [] jql = "project = DTO AND labels = class-a" if status: jql += f" AND status = '{status}'" try: response = requests.get( f"{self.server_url}/rest/api/3/search", auth=self.auth, headers=self.headers, params={ 'jql': jql, 'fields': 'key,summary,status,created,updated,customfield_10001', 'maxResults': 100 } ) if response.status_code == 200: issues = response.json()['issues'] return [ { 'key': issue['key'], 'summary': issue['fields']['summary'], 'status': issue['fields']['status']['name'], 'run_id': issue['fields'].get('customfield_10001'), 'created': issue['fields']['created'], 'updated': issue['fields']['updated'] } for issue in issues ] else: print(f"❌ Failed to get tickets: {response.status_code}") return [] except Exception as e: print(f"❌ Error getting tickets: {e}") return [] # Test function def test_jira_integration(): """Test Jira integration with mock Class-A run""" client = DTOJiraClient() if not client.test_connection(): print("❌ Jira integration test failed (expected without proper credentials)") return False # Test ticket creation test_run = { 'run_id': 'test-class-a-001', 'manifest_path': '/manifests/class_a/critical_dataset.yaml', 'data_size_bytes': 536870912000, # 500 GB 'initiated_by': 'data-engineer', 'environment': 'production' } ticket_key = client.create_class_a_ticket(test_run) if ticket_key: # Test status update client.update_ticket_status(ticket_key, "in_progress", "Data transfer initiated. Monitoring performance...") # Test metrics addition test_metrics = { 'average_throughput_mbps': 847.3, 'total_duration_seconds': 6480, 'data_size_gb': 500.0, 'transfer_method': 'ssh+dd', 'validation_passed': True, 'artifacts': [ '/logs/test-class-a-001.log', '/reports/test-class-a-001.pdf', '/checksums/test-class-a-001.sha256' ] } client.add_run_metrics(ticket_key, test_metrics) client.update_ticket_status(ticket_key, "completed", "Data transfer completed successfully. All validations passed.") print(f"✅ Jira integration test completed for ticket: {ticket_key}") return True return False if __name__ == "__main__": print("Testing DTO Jira Integration...") print("=" * 50) test_jira_integration() print("\nTo use Jira integration, set these environment variables:") print("export JIRA_SERVER_URL=https://your-domain.atlassian.net") print("export JIRA_USERNAME=your-email@company.com") print("export JIRA_API_TOKEN=your-api-token")