|
| 1 | +import requests |
| 2 | +from typing import Dict, Any, Tuple |
| 3 | +from datetime import datetime, timedelta, timezone |
| 4 | + |
| 5 | +from ..base import ObservabilityProvider |
| 6 | +from ...config import DatadogConfig |
| 7 | + |
| 8 | + |
| 9 | +class DatadogConnector(ObservabilityProvider): |
| 10 | + """ |
| 11 | + Connector for interacting with the Datadog API. |
| 12 | + """ |
| 13 | + |
| 14 | + def __init__(self, name: str, config: Dict[str, Any]): |
| 15 | + """ |
| 16 | + Initializes the connector and validates its specific configuration. |
| 17 | + """ |
| 18 | + super().__init__(name, config) |
| 19 | + self.validated_config = DatadogConfig(**self.config) |
| 20 | + self.api_base_url = f"https://api.{self.validated_config.site}" |
| 21 | + self.headers = { |
| 22 | + "DD-API-KEY": self.validated_config.api_key.get_secret_value(), |
| 23 | + "DD-APPLICATION-KEY": self.validated_config.app_key.get_secret_value(), |
| 24 | + "Content-Type": "application/json", |
| 25 | + } |
| 26 | + |
| 27 | + def test_connection(self) -> Tuple[bool, str]: |
| 28 | + """ |
| 29 | + Validates the Datadog API and App keys by making a lightweight API call. |
| 30 | + """ |
| 31 | + try: |
| 32 | + # The validate endpoint is designed for this purpose |
| 33 | + response = requests.get( |
| 34 | + f"{self.api_base_url}/api/v1/validate", headers=self.headers, timeout=10 |
| 35 | + ) |
| 36 | + response.raise_for_status() |
| 37 | + if response.json().get("valid"): |
| 38 | + return True, "Datadog connection successful and keys are valid." |
| 39 | + else: |
| 40 | + return ( |
| 41 | + False, |
| 42 | + "Datadog connection failed: The provided keys are not valid.", |
| 43 | + ) |
| 44 | + except requests.exceptions.HTTPError as e: |
| 45 | + if e.response.status_code in [401, 403]: |
| 46 | + return False, "Connection failed: Invalid Datadog API or App Key." |
| 47 | + return False, f"Connection failed: HTTP {e.response.status_code} error." |
| 48 | + except requests.exceptions.RequestException as e: |
| 49 | + return False, f"Connection failed: Network error - {e}." |
| 50 | + |
| 51 | + def fetch_logs(self, query: str, time_window_minutes: int = 15) -> str: |
| 52 | + """ |
| 53 | + Fetches and formats logs from Datadog Logs. |
| 54 | +
|
| 55 | + Args: |
| 56 | + query (str): The search query to execute (e.g., 'service:api-checkout status:error'). |
| 57 | + time_window_minutes (int): The number of minutes to look back for logs. |
| 58 | +
|
| 59 | + Returns: |
| 60 | + A formatted string of log lines or an error/empty message. |
| 61 | + """ |
| 62 | + url = f"{self.api_base_url}/api/v2/logs/events/search" |
| 63 | + print(f"-> Fetching logs from Datadog with query: '{query}'...") |
| 64 | + |
| 65 | + now = datetime.now(timezone.utc) |
| 66 | + from_time = now - timedelta(minutes=time_window_minutes) |
| 67 | + |
| 68 | + payload = { |
| 69 | + "filter": { |
| 70 | + "query": query, |
| 71 | + "from": from_time.isoformat(), |
| 72 | + "to": now.isoformat(), |
| 73 | + }, |
| 74 | + "sort": "-timestamp", |
| 75 | + "page": { |
| 76 | + "limit": 25 # Limit to the most recent 25 logs to keep context concise |
| 77 | + }, |
| 78 | + } |
| 79 | + |
| 80 | + try: |
| 81 | + response = requests.post( |
| 82 | + url, headers=self.headers, json=payload, timeout=15 |
| 83 | + ) |
| 84 | + response.raise_for_status() |
| 85 | + logs = response.json().get("data", []) |
| 86 | + |
| 87 | + if not logs: |
| 88 | + return f"No logs found in Datadog for query '{query}' in the last {time_window_minutes} minutes." |
| 89 | + |
| 90 | + summaries = [ |
| 91 | + f"- [{log['attributes'].get('status', 'INFO').upper()}] {log['attributes'].get('message', '')}" |
| 92 | + for log in logs |
| 93 | + ] |
| 94 | + print(f" ...found {len(logs)} log entries.") |
| 95 | + return "\n".join(summaries) |
| 96 | + except requests.exceptions.HTTPError as e: |
| 97 | + return f"Error: Could not fetch logs from Datadog. HTTP {e.response.status_code}." |
| 98 | + except requests.exceptions.RequestException as e: |
| 99 | + return f"Error: Network issue while fetching logs from Datadog: {e}" |
0 commit comments