o
    ưi>-                     @   st   d Z ddlZddlZddlZddlmZmZ ddlmZ ddl	m
Z
 ddlmZmZ ddlmZ G dd	 d	e
ZdS )
aU  
Azure Sentinel Integration - sends logs to Azure Log Analytics using Logs Ingestion API

Azure Sentinel uses Log Analytics workspaces for data storage. This integration sends
LiteLLM logs to the Log Analytics workspace using the Azure Monitor Logs Ingestion API.

Reference API: https://learn.microsoft.com/en-us/azure/azure-monitor/logs/logs-ingestion-api-overview

`async_log_success_event` - used by litellm proxy to send logs to Azure Sentinel
`async_log_failure_event` - used by litellm proxy to send failure logs to Azure Sentinel

For batching specific details see CustomBatchLogger class
    N)ListOptional)verbose_logger)CustomBatchLogger)get_async_httpx_clienthttpxSpecialProvider)StandardLoggingPayloadc                       s   e Zd ZdZ						ddee dee dee dee dee dee f fd	d
ZdefddZdd Zdd Z	dd Z
  ZS )AzureSentinelLoggerz_
    Logger that sends LiteLLM logs to Azure Sentinel via Azure Monitor Logs Ingestion API
    Ndcr_immutable_idstream_nameendpoint	tenant_id	client_idclient_secretc                    sH  t tjd| _|ptd| _|ptdd| _|ptd| _|p+tdp+td| _	|p8tdp8td	| _
|pEtd
pEtd| _| jsNtd| jsUtd| j	s\td| j
sctd| jsjtd| jd d| j d| j d| _d| _d| _d| _t | _t jdi |d| ji t|   g | _dS )a  
        Initialize Azure Sentinel logger using Logs Ingestion API

        Args:
            dcr_immutable_id (str, optional): Data Collection Rule (DCR) Immutable ID.
                If not provided, will use AZURE_SENTINEL_DCR_IMMUTABLE_ID env var.
            stream_name (str, optional): Stream name from DCR (e.g., "Custom-LiteLLM").
                If not provided, will use AZURE_SENTINEL_STREAM_NAME env var or default to "Custom-LiteLLM".
            endpoint (str, optional): Data Collection Endpoint (DCE) or DCR ingestion endpoint.
                If not provided, will use AZURE_SENTINEL_ENDPOINT env var.
            tenant_id (str, optional): Azure Tenant ID for OAuth2 authentication.
                If not provided, will use AZURE_SENTINEL_TENANT_ID or AZURE_TENANT_ID env var.
            client_id (str, optional): Azure Client ID (Application ID) for OAuth2 authentication.
                If not provided, will use AZURE_SENTINEL_CLIENT_ID or AZURE_CLIENT_ID env var.
            client_secret (str, optional): Azure Client Secret for OAuth2 authentication.
                If not provided, will use AZURE_SENTINEL_CLIENT_SECRET or AZURE_CLIENT_SECRET env var.
        )Zllm_providerZAZURE_SENTINEL_DCR_IMMUTABLE_IDZAZURE_SENTINEL_STREAM_NAMEzCustom-LiteLLMZAZURE_SENTINEL_ENDPOINTZAZURE_SENTINEL_TENANT_IDZAZURE_TENANT_IDZAZURE_SENTINEL_CLIENT_IDZAZURE_CLIENT_IDZAZURE_SENTINEL_CLIENT_SECRETZAZURE_CLIENT_SECRETzrAZURE_SENTINEL_DCR_IMMUTABLE_ID is required. Set it as an environment variable or pass dcr_immutable_id parameter.zbAZURE_SENTINEL_ENDPOINT is required. Set it as an environment variable or pass endpoint parameter.zwAZURE_SENTINEL_TENANT_ID or AZURE_TENANT_ID is required. Set it as an environment variable or pass tenant_id parameter.zwAZURE_SENTINEL_CLIENT_ID or AZURE_CLIENT_ID is required. Set it as an environment variable or pass client_id parameter.zAZURE_SENTINEL_CLIENT_SECRET or AZURE_CLIENT_SECRET is required. Set it as an environment variable or pass client_secret parameter./z/dataCollectionRules/z	/streams/z?api-version=2023-01-01z"https://monitor.azure.com/.defaultN
flush_lock )r   r   ZLoggingCallbackasync_httpx_clientosgetenvr
   r   r   r   r   r   
ValueErrorrstripapi_endpointoauth_scopeoauth_tokenoauth_token_expires_atasyncioLockr   super__init__create_taskZperiodic_flush	log_queue)selfr
   r   r   r   r   r   kwargs	__class__r   i/home/app/Keep/.python/lib/python3.10/site-packages/litellm/integrations/azure_sentinel/azure_sentinel.pyr   "   sb    

zAzureSentinelLogger.__init__returnc                    s  ddl }| jr| jr|  | jd k r| jS | jdus J d| jdus)J d| jdus2J dd| j d}| j| j| jd	d
}| jj||ddidI dH }|j	dkrbt
d|j	 d|j | }|d| _|dd}| jsyt
dddl }|  | | _| jS )z
        Get OAuth2 Bearer token for Azure Monitor Logs Ingestion API

        Returns:
            Bearer token string
        r   N<   ztenant_id is requiredzclient_id is requiredzclient_secret is requiredz"https://login.microsoftonline.com/z/oauth2/v2.0/tokenZclient_credentials)r   r   scopeZ
grant_typeContent-Typez!application/x-www-form-urlencodedurldataheaders   zFailed to get OAuth2 token:  - Zaccess_token
expires_ini  z2OAuth2 token response did not contain access_token)timer   r   r   r   r   r   r   poststatus_code	Exceptiontextjsonget)r"   r2   Z	token_urlZ
token_dataresponseZtoken_responser1   r   r   r&   _get_oauth_tokenx   sD   
z$AzureSentinelLogger._get_oauth_tokenc              
         z3t d| |dd}|du rt d W dS | j| t| j| jkr2|  I dH  W dS W dS  t	yV } zt 
dt| dt   W Y d}~dS d}~ww )a"  
        Async Log success events to Azure Sentinel

        - Gets StandardLoggingPayload from kwargs
        - Adds to batch queue
        - Flushes based on CustomBatchLogger settings

        Raises:
            Raises a NON Blocking verbose_logger.exception if an error occurs
        z>Azure Sentinel: Logging - Enters logging function for model %sstandard_logging_objectN;Azure Sentinel: standard_logging_object not found in kwargsAzure Sentinel Layer Error - 
r   debugr8   warningr!   appendlenZ
batch_sizeasync_send_batchr5   	exceptionstr	traceback
format_excr"   r#   Zresponse_obj
start_timeend_timeZstandard_logging_payloader   r   r&   async_log_success_event   s,   z+AzureSentinelLogger.async_log_success_eventc              
      r;   )a"  
        Async Log failure events to Azure Sentinel

        - Gets StandardLoggingPayload from kwargs
        - Adds to batch queue
        - Flushes based on CustomBatchLogger settings

        Raises:
            Raises a NON Blocking verbose_logger.exception if an error occurs
        zFAzure Sentinel: Logging - Enters failure logging function for model %sr<   Nr=   r>   r?   r@   rJ   r   r   r&   async_log_failure_event   s.   z+AzureSentinelLogger.async_log_failure_eventc              
      s8  zzb| j sW W | j   dS tdt| j  ddlm} |  I dH }|| j }d| dd}| jj	| j
|d|d	I dH }|jd
vr\td|j|j td|j d|j td|j W n! ty } ztdt| dt   W Y d}~nd}~ww W | j   dS W | j   dS | j   w )z
        Sends the batch of logs to Azure Monitor Logs Ingestion API

        Raises:
            Raises a NON Blocking verbose_logger.exception if an error occurs
        Nz)Azure Sentinel - about to flush %s eventsr   )
safe_dumpszBearer zapplication/json)Authorizationr*   zutf-8r+   )r/      z5Azure Sentinel API error: status_code=%s, response=%sz'Failed to send logs to Azure Sentinel: r0   z1Azure Sentinel: Response from API status_code: %sz)Azure Sentinel Error sending batch API - r?   )r!   clearr   rA   rD   Z*litellm.litellm_core_utils.safe_json_dumpsrP   r:   r   r3   r   encoder4   errorr6   r5   rF   rG   rH   rI   )r"   rP   Zbearer_tokenbodyr.   r9   rM   r   r   r&   rE      sP   .



z$AzureSentinelLogger.async_send_batch)NNNNNN)__name__
__module____qualname____doc__r   rG   r   r:   rN   rO   rE   __classcell__r   r   r$   r&   r	      s2    V8$%r	   )rZ   r   r   rH   typingr   r   Zlitellm._loggingr   Z(litellm.integrations.custom_batch_loggerr   Z&litellm.llms.custom_httpx.http_handlerr   r   Zlitellm.types.utilsr   r	   r   r   r   r&   <module>   s    