
    PeuP                         d dl Z d dlZd dlZd dlZd dlmZmZmZ d dlm	Z
  ej                  e      Z G d d      Z G d d      Z G d d	      Z G d
 de      Z G d de      Z G d d      Z G d d      Zy)    N)ensure_bytesensure_unicodeurlparse)EXCEPTION_MAPc                   &    e Zd Zg dZd Zd Zd Zy)Monitor)zbefore-parameter-buildzrequest-createdzresponse-receivedz
after-callzafter-call-errorc                      || _         || _        y)zAbstraction for monitoring clients API calls

        :param adapter: An adapter that takes event emitter events
            and produces monitor events

        :param publisher: A publisher for generated monitor events
        N)_adapter
_publisher)selfadapter	publishers      5/usr/lib/python3/dist-packages/botocore/monitoring.py__init__zMonitor.__init__!   s      #    c                 ^    | j                   D ]  }|j                  || j                           y)z(Register an event emitter to the monitorN)_EVENTS_TO_REGISTERregister_lastcapture)r   event_emitterevent_to_registers      r   registerzMonitor.register,   s/    !%!9!9 	I''(94<<H	Ir   c                     	 | j                   j                  ||      }|r| j                  j                  |       yy# t        $ r#}t
        j                  d||d       Y d}~yd}~ww xY w)zCaptures an incoming event from the event emitter

        It will feed an event emitter event to the monitor's adaptor to create
        a monitor event and then publish that event to the monitor's publisher.
        z:Exception %s raised by client monitor in handling event %sT)exc_infoN)r
   feedr   publish	Exceptionloggerdebug)r   
event_namepayloadmonitor_eventes        r   r   zMonitor.capture1   si    
	 MM..z7CM''6  	LLL	   	s   9= 	A)A$$A)N)__name__
__module____qualname__r   r   r   r    r   r   r   r      s    	$I
r   r   c                   l    e Zd Zej                  fdZd Zd Zd Zd Zd Z	d Z
d Zd	 Zd
 Zd Zd Zy)MonitorEventAdapterc                     || _         y)zAdapts event emitter events to produce monitor events

        :type time: callable
        :param time: A callable that produces the current time
        N)_time)r   times     r   r   zMonitorEventAdapter.__init__E   s     
r   c                 0     | j                  |      di |S )a  Feed an event emitter event to generate a monitor event

        :type emitter_event_name: str
        :param emitter_event_name: The name of the event emitted

        :type emitter_payload: dict
        :param emitter_payload: The payload to associated to the event
            emitted

        :rtype: BaseMonitorEvent
        :returns: A monitor event based on the event emitter events
            fired
        r'   )_get_handler)r   emitter_event_nameemitter_payloads      r   r   zMonitorEventAdapter.feedM   s      5t  !34GGGr   c                 d    t        | d|j                  d      d   j                  dd      z         S )N_handle_.r   -_)getattrsplitreplace)r   r    s     r   r.   z MonitorEventAdapter._get_handler]   s6    *z//4Q7??SII
 	
r   c                 ~    t        |j                  j                  |j                  | j	                               |d<   y )Nservice	operation	timestampcurrent_api_call_event)APICallEventservice_model
service_id	wire_name_get_current_time)r   modelcontextkwargss       r   _handle_before_parameter_buildz2MonitorEventAdapter._handle_before_parameter_buildb   s4    ,8''22oo,,.-
()r   c                     |j                   }|d   j                  | j                               }|j                  |_        |j
                  |_        ||d<   y )Nr>   )r=   current_api_call_attempt_event)rE   new_api_call_attemptrC   headersrequest_headersurl)r   requestrF   rE   new_attempt_events        r   _handle_request_createdz+MonitorEventAdapter._handle_request_createdi   sY    //#$


)?)?)A

B 	 -4OO) '4E01r   c                     |j                  d      }| j                  |      |_        |2|d   d   |_        |d   d   |_        |j                  d      |_        |S ||_        |S )NrI   ResponseMetadataHTTPStatusCodeHTTPHeadersError)pop_get_latencylatencyhttp_status_coderesponse_headersgetparsed_errorwire_exception)r   parsed_responserE   	exceptionrF   attempt_events         r   _handle_response_receivedz-MonitorEventAdapter._handle_response_receivedr   s      $DE $ 1 1- @&-<".. M* .="..M* *9)<)<W)EM&  ,5M(r   c                 ^    |d   j                  dd      |d   _        | j                  |      S )NrR   MaxAttemptsReachedFr>   )r[   retries_exceeded_complete_api_call)r   rE   parsedrF   s       r   _handle_after_callz&MonitorEventAdapter._handle_after_call   s;    =C>

#"E
* 	(): &&w//r   c                 V    | j                  |      |d   _        | j                  |      S Nr>   )_is_retryable_exceptionrd   re   )r   rE   r_   rF   s       r   _handle_after_call_errorz,MonitorEventAdapter._handle_after_call_error   s3     "99)D 	$	

&&w//r   c                 :    t        |t        t        d               S )NGENERAL_CONNECTION_ERROR)
isinstancetupleRETRYABLE_EXCEPTIONS)r   r_   s     r   rj   z+MonitorEventAdapter._is_retryable_exception   s     u12LMN
 	
r   c                 T    |j                  d      }| j                  |      |_        |S ri   )rV   rW   rX   )r   rE   
call_events      r   re   z&MonitorEventAdapter._complete_api_call   s*    [[!9:
!..z:
r   c                 <    | j                         |j                  z
  S N)rC   r=   r   events     r   rW   z MonitorEventAdapter._get_latency   s    %%'%//99r   c                 :    t        | j                         dz        S )Ni  )intr+   r   s    r   rC   z%MonitorEventAdapter._get_current_time   s    4::<$&''r   N)r$   r%   r&   r,   r   r   r.   rG   rP   ra   rg   rk   rj   re   rW   rC   r'   r   r   r)   r)   D   sG     II H 


F"00


:(r   r)   c                       e Zd Zd Zd Zd Zy)BaseMonitorEventc                 .    || _         || _        || _        y)a  Base monitor event

        :type service: str
        :param service: A string identifying the service associated to
            the event

        :type operation: str
        :param operation: A string identifying the operation of service
            associated to the event

        :type timestamp: int
        :param timestamp: Epoch time in milliseconds from when the event began
        Nr:   )r   r;   r<   r=   s       r   r   zBaseMonitorEvent.__init__   s     ""r   c                 N    | j                   j                   d| j                  dS )N())	__class__r$   __dict__ry   s    r   __repr__zBaseMonitorEvent.__repr__   s%    ..))*!DMM+<A>>r   c                 b    t        || j                        r| j                  |j                  k(  S y)NF)rn   r   r   )r   others     r   __eq__zBaseMonitorEvent.__eq__   s&    eT^^,==ENN22r   N)r$   r%   r&   r   r   r   r'   r   r   r{   r{      s    #$?r   r{   c                   ,     e Zd Z	 	 	 d fd	Zd Z xZS )r?   c                 f    t         |   |||       || _        || _        |g | _        || _        y)a  Monitor event for a single API call

        This event corresponds to a single client method call, which includes
        every HTTP requests attempt made in order to complete the client call

        :type service: str
        :param service: A string identifying the service associated to
            the event

        :type operation: str
        :param operation: A string identifying the operation of service
            associated to the event

        :type timestamp: int
        :param timestamp: Epoch time in milliseconds from when the event began

        :type latency: int
        :param latency: The time in milliseconds to complete the client call

        :type attempts: list
        :param attempts: The list of APICallAttempts associated to the
            APICall

        :type retries_exceeded: bool
        :param retries_exceeded: True if API call exceeded retries. False
            otherwise
        r:   N)superr   rX   attemptsrd   )r   r;   r<   r=   rX   r   rd   r   s          r   r   zAPICallEvent.__init__   sD    H 	yI 	 	
  DM 0r   c                     t        | j                  | j                  |      }| j                  j	                  |       |S )zInstantiates APICallAttemptEvent associated to the APICallEvent

        :type timestamp: int
        :param timestamp: Epoch time in milliseconds to associate to the
            APICallAttemptEvent
        r:   )APICallAttemptEventr;   r<   r   append)r   r=   r`   s      r   rJ   z!APICallEvent.new_api_call_attempt   s7     ,LLDNNi
 	]+r   )NNF)r$   r%   r&   r   rJ   __classcell__r   s   @r   r?   r?      s     +1Zr   r?   c                   .     e Zd Z	 	 	 	 	 	 	 d fd	Z xZS )r   c                     t         |   |||       || _        || _        || _        || _        || _        |	| _        |
| _        y)a  Monitor event for a single API call attempt

        This event corresponds to a single HTTP request attempt in completing
        the entire client method call.

        :type service: str
        :param service: A string identifying the service associated to
            the event

        :type operation: str
        :param operation: A string identifying the operation of service
            associated to the event

        :type timestamp: int
        :param timestamp: Epoch time in milliseconds from when the HTTP request
            started

        :type latency: int
        :param latency: The time in milliseconds to complete the HTTP request
            whether it succeeded or failed

        :type url: str
        :param url: The URL the attempt was sent to

        :type http_status_code: int
        :param http_status_code: The HTTP status code of the HTTP response
            if there was a response

        :type request_headers: dict
        :param request_headers: The HTTP headers sent in making the HTTP
            request

        :type response_headers: dict
        :param response_headers: The HTTP headers returned in the HTTP response
            if there was a response

        :type parsed_error: dict
        :param parsed_error: The error parsed if the service returned an
            error back

        :type wire_exception: Exception
        :param wire_exception: The exception raised in sending the HTTP
            request (i.e. ConnectionError)
        r:   N)	r   r   rX   rM   rY   rL   rZ   r\   r]   )r   r;   r<   r=   rX   rM   rY   rL   rZ   r\   r]   r   s              r   r   zAPICallAttemptEvent.__init__   sW    r 	yI 	 	
  0. 0(,r   )NNNNNNN)r$   r%   r&   r   r   r   s   @r   r   r      s&     B- B-r   r   c                      e Zd ZdZdZdZdZdZddddZ e	j                  d	       e	j                  d
      dZg dZd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd  Z d! Z!d" Z"d# Z#d$ Z$d% Z%y&)'CSMSerializer         i   XAmznRequestIdXAmzRequestIdXAmzId2)zx-amzn-requestidzx-amz-request-idz
x-amz-id-2zSAWS4-HMAC-SHA256 Credential=(?P<access_key>\w+)/\d+/(?P<signing_region>[a-z0-9-]+)/zAWS (?P<access_key>\w+):)v4s3)r;   r<   r=   r   rX   rd   rM   rL   rY   rZ   r\   r]   c                 4    | j                  |       || _        y)zSerializes monitor events to CSM (Client Side Monitoring) format

        :type csm_client_id: str
        :param csm_client_id: The application identifier to associate
            to the serialized events
        N)_validate_client_idcsm_client_idr   r   s     r   r   zCSMSerializer.__init__d  s     	  /*r   c                 l    t        |      | j                  kD  rt        d| d| j                   d      y )Nz&The value provided for csm_client_id: z exceeds the maximum length of z characters)len_MAX_CLIENT_ID_LENGTH
ValueErrorr   s     r   r   z!CSMSerializer._validate_client_idn  sH    } : ::8 H))-)C)C(DKQ  ;r   c                    | j                  |      }| j                  |      }||d<   | j                  D ]*  }t        ||d      }| t        | d|z         |||       , t	        t        j                  |d            S )zSerializes a monitor event to the CSM format

        :type event: BaseMonitorEvent
        :param event: The event to serialize to bytes

        :rtype: bytes
        :returns: The CSM serialized form of the event
        TypeN_serialize_)
event_type),:)
separators)_get_base_event_dict_get_event_type_SERIALIZEABLE_EVENT_PROPERTIESr6   r   jsondumps)r   rv   
event_dictr   attrvalues         r   	serializezCSMSerializer.serializeu  s     ..u5
))%0
'
688 	DE4.E 3md23:*	 DJJzjIJJr   c                      d| j                   dS )N   )VersionClientId)r   ru   s     r   r   z"CSMSerializer._get_base_event_dict  s    **
 	
r   c                     ||d<   y )NServicer'   )r   r;   r   rF   s       r   _serialize_servicez CSMSerializer._serialize_service  s     '
9r   c                     ||d<   y )NApir'   )r   r<   r   rF   s       r   _serialize_operationz"CSMSerializer._serialize_operation  s    %
5r   c                     ||d<   y )N	Timestampr'   )r   r=   r   rF   s       r   _serialize_timestampz"CSMSerializer._serialize_timestamp  s    "+
;r   c                 P    t        |      |d<   |r| j                  ||d          y y )NAttemptCount)r   _add_fields_from_last_attempt)r   r   r   rF   s       r   _serialize_attemptsz!CSMSerializer._serialize_attempts  s,    %(]
>"..z8B<H r   c                 x   |j                   r@| j                  |j                         }|||d<   | j                  |j                         |d<   |j                  |j                  |d<   |j                  | j                  |j                  |d       |j                  | j                  |j                  |d       y y )NRegion	UserAgentFinalHttpStatusCodeApiCall)rL   _get_region_get_user_agentrY   r\   _serialize_parsed_errorr]   _serialize_wire_exception)r   r   last_attemptregions       r   r   z+CSMSerializer._add_fields_from_last_attempt  s    '' %%l&B&BCF!'-
8$&*&:&:,,'J{# ((40<0M0MJ,-$$0(()):y &&2**++Z 3r   c                 0    |dk(  r||d<   y |dk(  r||d<   y y )Nr   LatencyApiCallAttemptAttemptLatencyr'   )r   rX   r   r   s       r   _serialize_latencyz CSMSerializer._serialize_latency  s-    "$+Jy!+++2J'( ,r   c                     |rd|d<   y d|d<   y )Nr   r   MaxRetriesExceededr'   )r   rd   r   rF   s       r   _serialize_retries_exceededz)CSMSerializer._serialize_retries_exceeded  s     1A1
'(a
'(r   c                 4    t        |      j                  |d<   y )NFqdn)r   netloc)r   rM   r   rF   s       r   _serialize_urlzCSMSerializer._serialize_url  s    %c]11
6r   c                     | j                  |      |d<   | j                  |      r| j                  |      |d<   | j                  |      }|||d<   d|v r	|d   |d<   y y )Nr   	AccessKeyr   zX-Amz-Security-TokenSessionToken)r   
_is_signed_get_access_keyr   )r   rL   r   rF   r   s        r   _serialize_request_headersz(CSMSerializer._serialize_request_headers  sy     #'"6"6"G
;???+&*&:&:?&KJ{#!!/2#)Jx !_4)8&*J~& 5r   c                     ||d<   y )NHttpStatusCoder'   )r   rY   r   rF   s       r   _serialize_http_status_codez)CSMSerializer._serialize_http_status_code  s     (8
#$r   c                 b    | j                   j                         D ]  \  }}||v s||   ||<    y rt   )"_RESPONSE_HEADERS_TO_EVENT_ENTRIESitems)r   rZ   r   rF   headerentrys         r   _serialize_response_headersz)CSMSerializer._serialize_response_headers  s>     "DDJJL 	=MFE))$4V$<
5!	=r   c                     |dk(  rdnd}| j                  |d   | j                        ||dz   <   | j                  |d   | j                        ||dz   <   y )Nr   Final CodeAwsExceptionMessageAwsExceptionMessage)	_truncate_MAX_ERROR_CODE_LENGTH_MAX_MESSAGE_LENGTH)r   r\   r   r   rF   field_prefixs         r   r   z%CSMSerializer._serialize_parsed_error  sf     #-	"9wr48NN $"="=5

<.01 <@>>#T%=%=<

<"778r   c                     |dk(  rdnd}| j                  |j                  j                  | j                        ||dz   <   | j                  t	        |      | j
                        ||dz   <   y )Nr   r   r   SdkExceptionSdkExceptionMessage)r   r   r$   _MAX_EXCEPTION_CLASS_LENGTHstrr   )r   r]   r   r   rF   r   s         r   r   z'CSMSerializer._serialize_wire_exception  sm     #-	"9wr48NN$$--t/O/O5

<.01 <@>>!9!9<

<"778r   c                 H    t        |t              ryt        |t              ryy )Nr   r   )rn   r?   r   ru   s     r   r   zCSMSerializer._get_event_type  s"    e\*23# 4r   c                 n    | j                  |      }| j                  |      \  }}|j                  d      S )N
access_key)_get_auth_value_get_auth_matchgroup)r   rL   auth_valr5   
auth_matchs        r   r   zCSMSerializer._get_access_key  s7    ''8,,X6:--r   c                     | j                  |      sy | j                  |      }| j                  |      \  }}|dk7  ry |j                  d      S )Nr   signing_region)r   r   r   r   )r   rL   r  signature_versionr  s        r   r   zCSMSerializer._get_region  sT    /''8(,(<(<X(F%:$ 011r   c                 l    | j                  t        |j                  dd            | j                        S )Nz
User-Agentr   )r   r   r[   _MAX_USER_AGENT_LENGTHr   rL   s     r   r   zCSMSerializer._get_user_agent  s1    ~~?..|R@A''
 	
r   c                 
    d|v S NAuthorizationr'   r  s     r   r   zCSMSerializer._is_signed
  s    /11r   c                     t        |d         S r
  )r   r  s     r   r   zCSMSerializer._get_auth_value  s    oo>??r   c                 z    | j                   j                         D ]  \  }}|j                  |      }|s||fc S  y)N)NN)_AUTH_REGEXSr   match)r   r  r  regexr  s        r   r   zCSMSerializer._get_auth_match  sG    (,(9(9(?(?(A 	0$uKK)E(%//	0 r   c                 Z    t        |      |kD  rt        j                  d||       |d | S |S )Nz6Truncating following value to maximum length of %s: %s)r   r   r   )r   text
max_lengths      r   r   zCSMSerializer._truncate  s7    t9z!LLK
 $$r   N)&r$   r%   r&   r   r   r   r  r   r   recompiler  r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r'   r   r   r   r   B  s    "%  ,+*& bjj/

 bjj45L'#+K(
(&,I
*3H
28
=	
	
$.
2
2@r   r   c                       e Zd ZdZd Zd Zy)SocketPublisheri    c                 2    || _         ||f| _        || _        y)a)  Publishes monitor events to a socket

        :type socket: socket.socket
        :param socket: The socket object to use to publish events

        :type host: string
        :param host: The host to send events to

        :type port: integer
        :param port: The port on the host to send events to

        :param serializer: The serializer to use to serialize the event
            to a form that can be published to the socket. This must
            have a `serialize()` method that accepts a monitor event
            and return bytes
        N)_socket_address_serializer)r   sockethostport
serializers        r   r   zSocketPublisher.__init__%  s    " t%r   c                    | j                   j                  |      }t        |      | j                  kD  r+t        j                  dt        |      | j                         y| j                  j                  || j                         y)zPublishes a specified monitor event

        :type event: BaseMonitorEvent
        :param event: The monitor event to be sent
            over the publisher's socket to the desired address.
        z`Serialized event of size %s exceeds the maximum length allowed: %s. Not sending event to socket.N)	r  r   r   _MAX_MONITOR_EVENT_LENGTHr   r   r  sendtor  )r   rv   serialized_events      r   r   zSocketPublisher.publish:  sp      ++55e< 4#A#AALL<$%..	 ,dmm<r   N)r$   r%   r&   r!  r   r   r'   r   r   r  r  "  s     (&*=r   r  )r   loggingr  r,   botocore.compatr   r   r   botocore.retryhandlerr   rp   	getLoggerr$   r   r   r)   r{   r?   r   r   r  r'   r   r   <module>r(     s      	  B B G			8	$) )X]( ](@ 89# 9xC-* C-L] ]@(= (=r   