|
| 1 | +""" |
| 2 | +Elasticsearch client utilities for FlexiRoaster. |
| 3 | +Handles log indexing and search/filter operations for execution analytics. |
| 4 | +""" |
| 5 | +import logging |
| 6 | +from typing import Optional, Dict, Any, List |
| 7 | + |
| 8 | +from elasticsearch import AsyncElasticsearch |
| 9 | + |
| 10 | +from config import settings |
| 11 | + |
| 12 | +logger = logging.getLogger(__name__) |
| 13 | + |
| 14 | + |
| 15 | +class ElasticsearchManager: |
| 16 | + """Manages Elasticsearch lifecycle and execution log indexing.""" |
| 17 | + |
| 18 | + def __init__(self) -> None: |
| 19 | + self._client: Optional[AsyncElasticsearch] = None |
| 20 | + self._available: bool = False |
| 21 | + |
| 22 | + @property |
| 23 | + def is_available(self) -> bool: |
| 24 | + return self._available |
| 25 | + |
| 26 | + async def initialize(self) -> bool: |
| 27 | + if not settings.ELASTICSEARCH_ENABLED: |
| 28 | + logger.info("Elasticsearch disabled via configuration") |
| 29 | + self._available = False |
| 30 | + return False |
| 31 | + |
| 32 | + try: |
| 33 | + auth = None |
| 34 | + if settings.ELASTICSEARCH_USERNAME and settings.ELASTICSEARCH_PASSWORD: |
| 35 | + auth = (settings.ELASTICSEARCH_USERNAME, settings.ELASTICSEARCH_PASSWORD) |
| 36 | + |
| 37 | + self._client = AsyncElasticsearch( |
| 38 | + hosts=[settings.ELASTICSEARCH_URL], |
| 39 | + basic_auth=auth, |
| 40 | + verify_certs=settings.ELASTICSEARCH_VERIFY_CERTS, |
| 41 | + request_timeout=settings.ELASTICSEARCH_REQUEST_TIMEOUT, |
| 42 | + ) |
| 43 | + |
| 44 | + await self._client.ping() |
| 45 | + await self.ensure_index() |
| 46 | + |
| 47 | + self._available = True |
| 48 | + logger.info("Elasticsearch initialized") |
| 49 | + return True |
| 50 | + except Exception as e: |
| 51 | + logger.warning(f"Elasticsearch unavailable, continuing without indexing: {e}") |
| 52 | + self._available = False |
| 53 | + return False |
| 54 | + |
| 55 | + async def close(self) -> None: |
| 56 | + if self._client: |
| 57 | + await self._client.close() |
| 58 | + self._available = False |
| 59 | + |
| 60 | + async def ensure_index(self) -> None: |
| 61 | + if not self._client: |
| 62 | + return |
| 63 | + |
| 64 | + index_name = settings.ELASTICSEARCH_LOGS_INDEX |
| 65 | + exists = await self._client.indices.exists(index=index_name) |
| 66 | + if exists: |
| 67 | + return |
| 68 | + |
| 69 | + await self._client.indices.create( |
| 70 | + index=index_name, |
| 71 | + mappings={ |
| 72 | + "properties": { |
| 73 | + "timestamp": {"type": "date"}, |
| 74 | + "execution_id": {"type": "keyword"}, |
| 75 | + "pipeline_id": {"type": "keyword"}, |
| 76 | + "stage_id": {"type": "keyword"}, |
| 77 | + "level": {"type": "keyword"}, |
| 78 | + "message": {"type": "text"}, |
| 79 | + "metadata": {"type": "object", "enabled": True}, |
| 80 | + } |
| 81 | + }, |
| 82 | + ) |
| 83 | + |
| 84 | + async def health_check(self) -> Dict[str, Any]: |
| 85 | + if not settings.ELASTICSEARCH_ENABLED: |
| 86 | + return {"status": "disabled"} |
| 87 | + |
| 88 | + if not self._client: |
| 89 | + return {"status": "disconnected"} |
| 90 | + |
| 91 | + try: |
| 92 | + health = await self._client.cluster.health() |
| 93 | + return { |
| 94 | + "status": "healthy", |
| 95 | + "cluster_status": health.get("status"), |
| 96 | + "number_of_nodes": health.get("number_of_nodes"), |
| 97 | + } |
| 98 | + except Exception as e: |
| 99 | + return {"status": "unhealthy", "error": str(e)} |
| 100 | + |
| 101 | + async def index_execution_log(self, document: Dict[str, Any]) -> bool: |
| 102 | + if not self._available or not self._client: |
| 103 | + return False |
| 104 | + |
| 105 | + try: |
| 106 | + await self._client.index(index=settings.ELASTICSEARCH_LOGS_INDEX, document=document) |
| 107 | + return True |
| 108 | + except Exception as e: |
| 109 | + logger.warning(f"Failed to index log in Elasticsearch: {e}") |
| 110 | + return False |
| 111 | + |
| 112 | + async def search_logs( |
| 113 | + self, |
| 114 | + query: str, |
| 115 | + pipeline_id: Optional[str] = None, |
| 116 | + execution_id: Optional[str] = None, |
| 117 | + levels: Optional[List[str]] = None, |
| 118 | + limit: int = 100, |
| 119 | + ) -> List[Dict[str, Any]]: |
| 120 | + if not self._available or not self._client: |
| 121 | + return [] |
| 122 | + |
| 123 | + filters = [] |
| 124 | + if pipeline_id: |
| 125 | + filters.append({"term": {"pipeline_id": pipeline_id}}) |
| 126 | + if execution_id: |
| 127 | + filters.append({"term": {"execution_id": execution_id}}) |
| 128 | + if levels: |
| 129 | + filters.append({"terms": {"level": levels}}) |
| 130 | + |
| 131 | + body: Dict[str, Any] = { |
| 132 | + "size": limit, |
| 133 | + "query": { |
| 134 | + "bool": { |
| 135 | + "must": [{"multi_match": {"query": query, "fields": ["message", "metadata.*"]}}], |
| 136 | + "filter": filters, |
| 137 | + } |
| 138 | + }, |
| 139 | + "sort": [{"timestamp": {"order": "desc"}}], |
| 140 | + } |
| 141 | + |
| 142 | + response = await self._client.search(index=settings.ELASTICSEARCH_LOGS_INDEX, body=body) |
| 143 | + return [hit.get("_source", {}) for hit in response.get("hits", {}).get("hits", [])] |
| 144 | + |
| 145 | + |
| 146 | +elasticsearch_manager = ElasticsearchManager() |
0 commit comments