| |
| """ |
| 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') |
| |
| |
| 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() |
| |
| |
| 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, |
| "customfield_10002": data_size_gb, |
| "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 |
| |
| |
| 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: |
| |
| 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 |
| |
| |
| 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 [] |
|
|
| |
| 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_run = { |
| 'run_id': 'test-class-a-001', |
| 'manifest_path': '/manifests/class_a/critical_dataset.yaml', |
| 'data_size_bytes': 536870912000, |
| 'initiated_by': 'data-engineer', |
| 'environment': 'production' |
| } |
| |
| ticket_key = client.create_class_a_ticket(test_run) |
| |
| if ticket_key: |
| |
| client.update_ticket_status(ticket_key, "in_progress", |
| "Data transfer initiated. Monitoring performance...") |
| |
| |
| 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") |