@@ -97,16 +97,16 @@ def discover_cluster_name(instance: Any, connection_id: str) -> Optional[str]:
9797 Caches result with TTL to avoid repeated API calls.
9898 """
9999 try :
100- cached = _get_cached_cluster_name (connection_id )
101- if cached :
100+ if cached := _get_cached_cluster_name (connection_id ):
102101 return cached
103102
104103 # perform_request is already instrumented; the span_name == "elasticsearch"
105104 # guard inside it prevents recursive tracing of this info() call.
106105 if hasattr (instance , "info" ):
107106 try :
108- cluster_name = _extract_cluster_name_from_response (instance .info ())
109- if cluster_name :
107+ if cluster_name := _extract_cluster_name_from_response (
108+ instance .info ()
109+ ):
110110 _store_cluster_name (connection_id , cluster_name )
111111 return cluster_name
112112 except Exception as e :
@@ -156,8 +156,7 @@ def collect_connection_info(
156156 Uses caching to optimize performance.
157157 """
158158 try :
159- connection_id = get_connection_id (instance )
160- if not connection_id :
159+ if not (connection_id := get_connection_id (instance )):
161160 return
162161
163162 cached = _connection_cache [connection_id ]
@@ -207,8 +206,7 @@ def extract_index_from_url(url: str) -> Optional[str]:
207206 """Extract index name from URL path"""
208207 try :
209208 # Match pattern: /index_name/...
210- match = INDEX_PATTERN .match (url )
211- if match :
209+ if match := INDEX_PATTERN .match (url ):
212210 index = match .group (1 )
213211 # Filter out special endpoints
214212 if not index .startswith ("_" ):
@@ -223,8 +221,7 @@ def extract_document_id_from_url(url: str) -> Optional[str]:
223221 Pattern: /index/_doc/document_id
224222 """
225223 try :
226- match = DOCUMENT_ID_PATTERN .match (url )
227- if match :
224+ if match := DOCUMENT_ID_PATTERN .match (url ):
228225 return match .group (1 )
229226 except Exception :
230227 logger .debug ("extract_document_id_from_url error:" , exc_info = True )
@@ -263,6 +260,56 @@ def detect_action_from_url(method: str, url: str) -> str:
263260 logger .debug ("detect_action_from_url error:" , exc_info = True )
264261 return method .lower ()
265262
263+ def _process_multi_operation (
264+ span : "InstanaSpan" ,
265+ action : str ,
266+ body : Optional [Any ],
267+ params : Optional [dict [str , Any ]],
268+ ) -> bool :
269+ """Handle Elasticsearch multi-operation actions."""
270+ if action == "mget" :
271+ process_mget_params (span , body , params )
272+ return True
273+ if action == "msearch" :
274+ process_msearch_params (span , body )
275+ return True
276+ if action == "bulk" :
277+ process_bulk_params (span , body )
278+ return True
279+ return False
280+
281+ def _extract_query_string (body : Any ) -> str :
282+ """Convert a request body to a query string."""
283+ if isinstance (body , dict ):
284+ return json .dumps (body )
285+ if isinstance (body , str ):
286+ return body
287+ return str (body )
288+
289+ def _set_search_query_attribute (span : "InstanaSpan" , body : Any ) -> None :
290+ """Set the search query span attribute when possible."""
291+ try :
292+ query_str = _extract_query_string (body )
293+ span .set_attribute ("elasticsearch.query" , shorten_query_string (query_str ))
294+ except Exception :
295+ logger .debug ("extract query error:" , exc_info = True )
296+
297+ def _set_request_param_attributes (
298+ span : "InstanaSpan" ,
299+ params : Optional [dict [str , Any ]],
300+ index : Optional [str ],
301+ doc_id : Optional [str ],
302+ ) -> None :
303+ """Set span attributes derived from request params."""
304+ if not params :
305+ return
306+ if not index and "index" in params :
307+ index_param = to_string_es_multi_parameter (params .get ("index" ))
308+ if index_param :
309+ span .set_attribute ("elasticsearch.index" , index_param )
310+ if not doc_id and "id" in params :
311+ span .set_attribute ("elasticsearch.id" , str (params ["id" ]))
312+
266313 def extract_params_from_request (
267314 span : "InstanaSpan" ,
268315 method : str ,
@@ -278,54 +325,21 @@ def extract_params_from_request(
278325 action = detect_action_from_url (method , url )
279326 span .set_attribute ("elasticsearch.action" , action )
280327
281- # Handle multi-operations with specialized processors
282- if action == "mget" :
283- process_mget_params (span , body , params )
284- return
285- elif action == "msearch" :
286- process_msearch_params (span , body )
287- return
288- elif action == "bulk" :
289- process_bulk_params (span , body )
328+ if _process_multi_operation (span , action , body , params ):
290329 return
291330
292- # Standard single operations
293- # Extract index from URL
294331 index = extract_index_from_url (url )
295332 if index :
296333 span .set_attribute ("elasticsearch.index" , index )
297334
298- # Extract document ID from URL
299335 doc_id = extract_document_id_from_url (url )
300336 if doc_id :
301337 span .set_attribute ("elasticsearch.id" , doc_id )
302338
303- # Extract query from body for search operations
304339 if action == "search" and body :
305- try :
306- if isinstance (body , dict ):
307- query_str = json .dumps (body )
308- elif isinstance (body , str ):
309- query_str = body
310- else :
311- query_str = str (body )
312-
313- shortened_query = shorten_query_string (query_str )
314- span .set_attribute ("elasticsearch.query" , shortened_query )
315- except Exception :
316- logger .debug ("extract query error:" , exc_info = True )
317-
318- # Handle params if provided
319- if params :
320- # Extract index from params if not in URL
321- if not index and "index" in params :
322- index_param = to_string_es_multi_parameter (params .get ("index" ))
323- if index_param :
324- span .set_attribute ("elasticsearch.index" , index_param )
340+ _set_search_query_attribute (span , body )
325341
326- # Extract document ID from params
327- if not doc_id and "id" in params :
328- span .set_attribute ("elasticsearch.id" , str (params ["id" ]))
342+ _set_request_param_attributes (span , params , index , doc_id )
329343
330344 except Exception :
331345 logger .debug ("extract_params_from_request error:" , exc_info = True )
@@ -658,6 +672,7 @@ def perform_request_with_instana(
658672 except Exception as exc :
659673 span .record_exception (exc )
660674 span .set_attribute ("elasticsearch.error" , str (exc ))
675+ raise
661676
662677 # ---------------------------------------------------------------------------
663678 # Async Client Instrumentation
@@ -671,8 +686,7 @@ async def _async_discover_cluster_name(
671686 Reuses the shared cache helpers; only the instance.info() call is awaited.
672687 """
673688 try :
674- cached = _get_cached_cluster_name (connection_id )
675- if cached :
689+ if cached := _get_cached_cluster_name (connection_id ):
676690 return cached
677691
678692 if hasattr (instance , "info" ):
@@ -702,8 +716,7 @@ async def _async_collect_connection_info(
702716 Reuses shared helpers; only cluster discovery is awaited.
703717 """
704718 try :
705- connection_id = get_connection_id (instance )
706- if not connection_id :
719+ if not (connection_id := get_connection_id (instance )):
707720 return
708721
709722 cached = _connection_cache [connection_id ]
@@ -789,6 +802,7 @@ async def async_perform_request_with_instana(
789802 except Exception as exc :
790803 span .record_exception (exc )
791804 span .set_attribute ("elasticsearch.error" , str (exc ))
805+ raise
792806
793807 logger .debug ("Instrumenting elasticsearch" )
794808
0 commit comments