
    ɯeiK                    z   d dl mZ d dlZd dlZd dlZd dlZd dlmZ d dlm	Z	 d dl
mZ d dlmZ ddlmZ dd	lmZmZ dd
lmZ ddlmZmZ ddlmZmZ ddlmZ  ej:                  e      ZdZ dZ!dZ" edddg      Z# edg d      Z$ edg d      Z% G d d      Z& G d d      Z'e'jP                  jR                  e'jT                  jR                  e'jV                  jR                  e'jX                  jR                  e'jZ                  jR                  fZ. G d de%      Z/ G d de/      Z0 G d d e/      Z1 G d! d"      Z2y)#    )annotationsN)
namedtuple)Queue)Lock)Any   )OK)CLIENT_NAMESNOWFLAKE_CONNECTOR_VERSION)SecretDetector)TelemetryFieldgenerate_telemetry_data_dict)ENABLE_TELEMETRY_LOGrt_plain_logger)requests
      TelemetryAPIurlapi_keyTelemetryServer)namer   r   TelemetryEventBaser   tagsurgentvaluec                  H    e Zd Z edd      Z edd      Z edd      Zy)	TelemetryAPIEndpointz?https://sfctest.client-telemetry.snowflakecomputing.com/enqueue(rRNY3EPNsB4U89XYuqsZKa7TSxb9QVX93yNM4tS6)r   r   z>https://sfcdev.client-telemetry.snowflakecomputing.com/enqueue(kyTKLWpEZSaJnrzTZ63I96QXZHKsgfqbaGmAaIWfz7https://client-telemetry.snowflakecomputing.com/enqueue(wLpEKqnLOW9tGNwTjab5N611YQApOb3t9xOnE1rXN)__name__
__module____qualname__r   SFCTESTSFCDEVPROD     c/var/www/html/glpi_dashboard/venv/lib/python3.12/site-packages/snowflake/connector/telemetry_oob.pyr   r   !   s6    M:G L:F E:Dr*   r   c                      e Zd Z edej
                  j                  ej
                  j                        Z edej
                  j                  ej
                  j                        Z	 edej                  j                  ej                  j                        Z edej                  j                  ej                  j                        Z edej                  j                  ej                  j                        Zy)TelemetryServerDeploymentsdevregqa1preprod3prodN)r#   r$   r%   r   r   r&   r   r   DEVREGr'   QA1PREPROD3r(   r)   r*   r+   r-   r-   0   s    
#++//1E1M1M1U1UC #++//1E1M1M1U1UC #**..0D0K0K0S0SC (//335I5P5P5X5XH $))--/C/H/H/P/PDr*   r-   c                  (    e Zd ZdZd Zd Zd Zd Zy)TelemetryEventzBase class for log and metric telemetry events.

    This class has all of the logic except for the 'type' of the telemetry event.
    That must be defined by the child class.
    c                    t         )zGets the telemetry event type.)NotImplementedErrorselfs    r+   get_typezTelemetryEvent.get_typeR   s    !!r*   c                   t               }| j                  |d<   | j                  |d<   | j                  |d<   | j	                         |d<   |j                  t        t        j                               t        j                  j                  t        j                  j                        j                  d      j                  d      | j                         dd	       |S )
z'Transform this event into a dictionary.NameUrgentValueTagsN)tzinfoz%Y-%m-%d %H:%M:%Sr   )UUID
Created_OnTypeSchemaVersion)dictr   r   r   generate_tagsupdatestruuiduuid4datetimenowtimezoneutcreplacestrftimer=   )r<   events     r+   to_dictzTelemetryEvent.to_dictV   s    		f++hg**,fDJJL)&//33H4E4E4I4IJ%-.!"		
 r*   c                ~    | j                   }|r/|D ]*  }|j                  dd      dk(  s|j                  d      c S  y)z9Gets the deployment field specified in tags if it exists.r?   N
deploymentrA   Unknown)r   get)r<   r   tags      r+   get_deploymentzTelemetryEvent.get_deploymenti   sD    yy ,7764(L8777++, r*   c                N   t               }| j                  rbt        | j                        dkD  rJ| j                  j                         D ]-  \  }}|	t	        |      |t	        |      j                         <   / t        j                         }t        |t        j                  j                  <   t	        t              |t        j                  j                  <   |j                  j                  |t        j                   j                  <   |j#                         |t        j$                  j                  <   |j&                  ret        |j&                        dkD  rM|j&                  j                         D ]0  \  }}|	t	        |      |dt	        |      j                         z   <   2 |S )z^Generates the tags to send as part of the telemetry event. Parts of the tags are user defined.r   ctx_)rH   r   lenitemsrK   lowerTelemetryServiceget_instancer
   r   KEY_OOB_DRIVERr   r   KEY_OOB_VERSIONrW   r   #KEY_OOB_TELEMETRY_SERVER_DEPLOYMENTget_connection_stringKEY_OOB_CONNECTION_STRINGcontext)r<   r   kv	telemetrys        r+   rI   zTelemetryEvent.generate_tagss   sM   v99TYY!+		) 21=+.q6DQ(2 %113	4?^**001589T5U^++112  %% 	^??EEF ++- 	^55;;< Y%6%6!7!!;!))//1 ;1=47FD#a&,,.01; r*   N)r#   r$   r%   __doc__r=   rU   r[   rI   r)   r*   r+   r8   r8   K   s    "&r*   r8   c                      e Zd ZddZy)TelemetryLogEventc                     y)NLogr)   r;   s    r+   r=   zTelemetryLogEvent.get_type   s    r*   NreturnrK   r#   r$   r%   r=   r)   r*   r+   rn   rn      s    r*   rn   c                      e Zd ZddZy)TelemetryMetricEventc                     y)NMetricr)   r;   s    r+   r=   zTelemetryMetricEvent.get_type   s    r*   Nrq   rs   r)   r*   r+   ru   ru      s    r*   ru   c                  (   e Zd ZdZ e       Zed d       Zd!dZd!dZ	e
d"d       Zd!dZd!dZe
d        Ze
d#d	       Zej                   d!d
       Ze
d#d       Zej                   d!d       Ze
d        Zej                   d!d       Ze
d$d       Zej                   d!d       Ze
d%d       Zej                   d!d       Zd"dZd Zd!dZd!dZd!dZd!dZ	 	 	 	 d&	 	 	 d'dZ	 	 	 	 	 	 	 d(	 	 	 d'dZ	 	 d)	 	 	 	 	 	 	 	 	 d*dZd!dZd Zd!dZ d Z!y)+ra   Nc                    | j                   5  | j                   |         ddd       | j                  S # 1 sw Y   | j                  S xY w)zStatic access method.N)_TelemetryService__lock_init_TelemetryService__instance)clss    r+   rb   zTelemetryService.get_instance   sB     __ 	~~%	 ~~	 ~~s	   5A	c                   t         j                  t        d      | t         _        d| _        t	               | _        t        | _        t        | _	        t               | _        t               | _        t        j                  | _        y)zVirtually private constructor.NzThis class is a singleton!F)ra   r{   	Exception_enabledr   _queueDEFAULT_BATCH_SIZE
batch_size)DEFAULT_NUM_OF_RETRY_TO_TRIGGER_TELEMETRY!num_of_retry_to_trigger_telemetryrH   rh   connection_paramsr-   r(   rW   r;   s    r+   __init__zTelemetryService.__init__   sg    &&2899*.'g,5 	. v!%499r*   c                D    	 | j                          y# t        $ r Y yw xY w)zDTries to flush all events left in the queue. Ignores all exceptions.N)closer~   r;   s    r+   __del__zTelemetryService.__del__   s"    	JJL 		s    	c                     y)z0Whether the Telemetry service is enabled or not.Fr)   r;   s    r+   enabledzTelemetryService.enabled   s     r*   c                    d| _         y)zEnable Telemetry Service.FNr   r;   s    r+   enablezTelemetryService.enable   	    r*   c                    d| _         y)zDisable Telemetry Service.FNr   r;   s    r+   disablezTelemetryService.disable   r   r*   c                    | j                   S )z5Get the queue that holds all of the telemetry events.)r   r;   s    r+   queuezTelemetryService.queue   s     {{r*   c                    | j                   S )z.Returns the context of the current connection._contextr;   s    r+   rh   zTelemetryService.context   s     }}r*   c                    || _         y)z+Sets the context of the current connection.Nr   r<   r   s     r+   rh   zTelemetryService.context   s     r*   c                    | j                   S )z>Returns the connection parameters from the current connection._connection_paramsr;   s    r+   r   z"TelemetryService.connection_params   s     &&&r*   c                    || _         y)z;Sets the connection parameters from the current connection.Nr   r   s     r+   r   z"TelemetryService.connection_params   s     #(r*   c                    | j                   S )z-Returns the batch size for uploading results._batch_sizer;   s    r+   r   zTelemetryService.batch_size        r*   c                    || _         y)z*Sets the batch size for uploading results.Nr   r   s     r+   r   zTelemetryService.batch_size        !r*   c                    | j                   S )zFReturns the number of HTTP retries before we submit a telemetry event."_num_of_retry_to_trigger_telemetryr;   s    r+   r   z2TelemetryService.num_of_retry_to_trigger_telemetry   s     666r*   c                    || _         y)zCSets the number of HTTP retries before we submit a telemetry event.Nr   r   s     r+   r   z2TelemetryService.num_of_retry_to_trigger_telemetry   s     38/r*   c                    | j                   S )zHReturns the deployment that we are sending the telemetry information to._deploymentr;   s    r+   rW   zTelemetryService.deployment   r   r*   c                    || _         y)zESets the deployment that we are sending the telemetry information to.Nr   r   s     r+   rW   zTelemetryService.deployment   r   r*   c                :    | j                   j                  t        v S )z2Returns whether or not this deployment is enabled.)rW   r   ENABLED_DEPLOYMENTSr;   s    r+   is_deployment_enabledz&TelemetryService.is_deployment_enabled   s    ##':::r*   c                    | j                   j                  dd      dz   | j                   j                  dd      z   dz   t        | j                   j                  dd            z   S )z-Returns the URL used to connect to Snowflake.protocol z://host:port)r   rY   rK   r;   s    r+   rf   z&TelemetryService.get_connection_string  sn     ""&&z26$$((45  $((,,VR89	:	
r*   c                   | j                   sy| j                  j                  |       | j                  j                         | j                  kD  s|j
                  r%| j                         }|y| j                  |       yy)zdAdds a telemetry event to the queue. If the event is urgent, upload all telemetry events right away.N)r   r   putqsizer   r   export_queue_to_string_upload_payload)r<   rT   payloads      r+   addzTelemetryService.add  se    ||

u::/5<<113G  )	 4@r*   c                    | j                   sy| j                  j                         s%| j                         }|y| j	                  |       yy)zJFlushes all telemetry events in the queue and submit them to the back-end.N)r   r   emptyr   r   )r<   r   s     r+   flushzTelemetryService.flush  sE    ||zz!113G  )	 "r*   c                    | j                  |       t               | _        |j                         D ]#  \  }}d|vsd|vsd|vs|| j                  |<   % y)zKUpdates the telemetry service context. Remove any passwords or credentials.passwordpasscode
privateKeyN)configure_deploymentrH   rh   r_   )r<   r   keyr   s       r+   update_contextzTelemetryService.update_context%  s\    !!"34v+113 	*JC#%c) +$)S!	*r*   c                *   || _         | j                   j                  d      r| j                   j                  d      nd}| j                   j                  d      r| j                   j                  d      nd}| j                   j                  dd      }t        j                  }d|v sd|v r-t        j                  }|dk(  rLt        j
                  }|| _        yd	|v sd	|v rt        j                  }|| _        yd
|v rt        j                  }|| _        y)zEDetermines which deployment we are sending Telemetry OOB messages to.accountr   r   r   Nr/   locali  r0   r1   )	r   rY   r-   r(   r4   r3   r5   r6   rW   )r<   r   r   r   r   rW   s         r+   r   z%TelemetryService.configure_deployment2  s   !2 %%)))4 ""&&y1 	 %%))&1 ""&&v. 	
 %%))&$7 044
D=GtO377Jt|7;;
 % d]ew.377J % 43<<J$r*   c                   |
t               }	 | j                  rd}|&t        |      |t        j                  j
                  <   |||t        j                  j
                  <   |
t               }||t        j                  j
                  <   t        ||||      }| j                  |       yy# t        $ r t        j                  dd       Y yw xY w)z?Logs an OCSP Exception and adds it to the queue to be uploaded.NOCSPExceptionr   zFailed to log OCSP exceptionTexc_info)rH   r   rK   r   KEY_OOB_EXCEPTION_MESSAGEr   KEY_OOB_EXCEPTION_STACK_TRACEKEY_OOB_EVENT_TYPErn   r   r~   loggerdebug)	r<   
event_typetelemetry_data	exceptionstack_tracer   r   
event_name	log_events	            r+   log_ocsp_exceptionz#TelemetryService.log_ocsp_exceptionN  s     <6D	H||,
(I #>#K#K#Q#QR * $ #&DDJJ <6D@J^66<<=-#$v^	 #) *  	HLL7$LG	Hs   BB. . CCc                   |
t               }	 | j                  r!d}t        t        j                  j
                  | d| t        j                  j
                  |t        j                  j
                  |id      }|r|j                         |t        j                  j
                  <   t        |j                        |t        j                  j
                  <   |j                  r2t        |j                        }||t        j                  j
                  <   |r&t        |      |t        j                  j
                  <   |r&t        |      |t        j                   j
                  <   |	r&t        |	      |t        j"                  j
                  <   |
r|
|t        j$                  j
                  <   |
t               }||t        j                  j
                  <   t        |      |t        j                  j
                  <   ||t        j                  j
                  <   t'        ||||      }| j)                  |       yy# t*        $ r t,        j/                  dd       Y yw xY w)	zCLogs an HTTP Request error and adds it to the queue to be uploaded.N T)	from_dictis_oob_telemetryr   r   r   r   z Failed to log HTTP request errorr   )rH   r   r   r   KEY_OOB_REQUESTr   KEY_OOB_SQL_STATEKEY_OOB_ERROR_CODEjsonKEY_OOB_RESPONSErK   reasonKEY_OOB_RESPONSE_STATUS_LINEstatus_codeKEY_OOB_RESPONSE_STATUS_CODEKEY_OOB_RETRY_TIMEOUTKEY_OOB_RETRY_COUNTr   r   rn   r   r~   r   r   )r<   r   r   methodsqlstateerrnoresponseretry_timeoutretry_countr   r   r   r   response_status_coder   r   s                   r+   log_http_request_errorz'TelemetryService.log_http_request_errort  s0     <6D9	L||')$!=&66<<#>O&88>>&99??
 &*"   #>#B#B#H#HI
 HOO, #&CCII  ++/283G3G/H, 1 '*GGMM !QT%RN>#G#G#M#MN OR#PN>#E#E#K#KL I #>#K#K#Q#QR  $ #&DDJJ <6D ) ^@@FFG @C8}^55;;<@E^66<<=-#$nV	 #k l  	LLL;dLK	Ls   H-H= = I I c                    |
t               }	 | j                  r!t        ||||      }| j                  |       yy# t        $ r t
        j                  dd       Y yw xY w)z2Sends any type of exception through OOB telemetry.Nr   zFailed to log general exceptionTr   )rH   r   rn   r   r~   r   r   )r<   r   r   r   r   r   s         r+   log_general_exceptionz&TelemetryService.log_general_exception  sg     <6D	K||-#$nV	 #	 
  	KLL:TLJ	Ks   ,<  AAc                   d}d}	 | j                         sBt        j                  d| j                  j                         	 t        j                  d|       yt        j                  d|        t
        rt        j                  d|        t        j                         5 }d| j                  j                  d}|j                  | j                  j                  ||t        	      }|j                  t        k(  rWt        j                   |j"                        j%                  d
d      t        k(  r!t        j                  d|j                         n"t        j                  d|j                         d}ddd       t        j                  d|       y# 1 sw Y    xY w# t&        $ r,}t        j                  d|t)        |             d}Y d}~Sd}~ww xY w# t        j                  d|       w xY w)z{Uploads the JSON-formatted string payload to the telemetry backend.

        Ignore any exceptions that may arise.
        TNz Skip the disabled deployment: %szTelemetry request success=%sz%Sending OOB telemetry data. Payload: z!OOB telemetry data being sent is zapplication/json)zContent-typez	x-api-key)dataheaderstimeout
statusCoder   z$telemetry server request success: %dz"telemetry server request error: %dFz?Telemetry request failed, Exception response: %s, exception: %s)r   r   r   rW   r   r   r   r   Sessionr   postr   REQUEST_TIMEOUTr   r	   r   loadstextrY   r~   rK   )r<   r   successr   sessionr   es          r+   r   z TelemetryService._upload_payload  s   
 )	B--/?AUAUVL LL7AK LL@	JK#%%(I'&ST !!# $w$6!%!8!8 #<<OO'' #+	 (  ((B.

8==155lAF"LLL>@T@T LL<h>R>R $G-$> LL7A?$ $.  	LLQA
 G	 LL7AsI   :F  A
F  "CF5F  FF   	G)"GG GG G0c                   t               }| j                  j                         sR|j                  | j                  j	                         j                                | j                  j                         sR	 t        j                  |      }t        j                  |      \  }}}|S # t        $ r( t        j                  dt        |      z  d       d}Y Kw xY w)zQExports all events in the queue into a JSON formatted string with secrets masked.ziFailed to generate a JSON dump from the passed in telemetry OOB events. String representation of logs: %sTr   N)listr   r   appendrY   rU   r   dumpsr~   r   r   rK   r   mask_secrets)r<   logsr   _masked_texts        r+   r   z'TelemetryService.export_queue_to_string  s    v++##%KK)1134 ++##%	jj&G +77@;  	LL{d)  
 G	s   8B( (.CCc                D    | j                          | j                          y)zCloses the telemetry service.N)r   r   r;   s    r+   r   zTelemetryService.close  s    

r*   c                6    | j                   j                         S )zReturns the size of the queue.)r   r   r;   s    r+   sizezTelemetryService.size  s    zz!!r*   )rr   ra   )rr   None)rr   bool)rr   zdict[str, Any])rr   int)r<   r   rr   z
Any | None)NNNF)r   r  rr   r  )NNNNNNF)NF)
r   rK   r   rH   r   zdict | Noner   zbool | Nonerr   r  )"r#   r$   r%   r{   r   rz   classmethodrb   r   r   propertyr   r   r   r   rh   setterr   r   r   rW   r   rf   r   r   r   r   r   r   r   r   r   r   r
  r)   r*   r+   ra   ra      s   J&K :        ^^  ' ' ( (     ! ! 7 7 '--8 .8     ! !;

*	**%@ $H $H 
$HZ KL KL 
KLb !#KK K 	K
 K 
K(0Bd$
"r*   ra   )3
__future__r   rN   r   loggingrL   collectionsr   r   r   	threadingr   typingr   compatr	   descriptionr
   r   secret_detectorr   rk   r   r   	test_utilr   r   vendoredr   	getLoggerr#   r   r   r   r   r   r   r   r   r-   r3   r   r4   r5   r6   r(   r   r8   rn   ru   ra   r)   r*   r+   <module>r     s"   "     "     A + C < 			8	$ ,. ).5)*<=.0JK= 
  & ""''""''""'''',,##(( @' @F 
> 
H" H"r*   