B ㊇cuPã@s´ddlZddlZddlZddlZddlmZmZmZddlm Z e  e ¡Z Gdd„dƒZGdd„dƒZGdd „d ƒZGd d „d eƒZGd d „d eƒZGdd„dƒZGdd„dƒZdS)éN)Ú ensure_bytesÚensure_unicodeÚurlparse)Ú EXCEPTION_MAPc@s2eZdZdddddgZdd„Zdd „Zd d „Zd S) ÚMonitorzbefore-parameter-buildzrequest-createdzresponse-receivedz after-callzafter-call-errorcCs||_||_dS)zåAbstraction 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ÚadapterZ publisher©r ún/private/var/folders/8c/hx9_v10d5x38qmnzt13b7b8j1k3n5b/T/pip-target-x6xd5gna/lib/python/botocore/monitoring.pyÚ__init__!szMonitor.__init__cCs"x|jD]}| ||j¡qWdS)z(Register an event emitter to the monitorN)Ú_EVENTS_TO_REGISTERZ register_lastÚcapture)r Z event_emitterZevent_to_registerr r r Úregister,s zMonitor.registerc Ks\y"|j ||¡}|r |j |¡Wn4tk rV}ztjd||dd�Wdd}~XYnXdS)zÚCaptures 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ÚpayloadZ monitor_eventÚer r r r1szMonitor.captureN)Ú__name__Ú __module__Ú __qualname__rr rrr r r r rs rc@sreZdZejfdd„Zdd„Zdd„Zdd„Zd d „Zd d „Z d d„Z dd„Z dd„Z dd„Z dd„Zdd„ZdS)ÚMonitorEventAdaptercCs ||_dS)z›Adapts event emitter events to produce monitor events :type time: callable :param time: A callable that produces the current time N)Ú_time)r Útimer r r r EszMonitorEventAdapter.__init__cCs| |¡f|Ž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 )Ú _get_handler)r Zemitter_event_nameZemitter_payloadr r r rMszMonitorEventAdapter.feedcCs t|d| d¡d dd¡ƒS)NZ_handle_Ú.rú-Ú_)ÚgetattrÚsplitÚreplace)r rr r r r ]sz MonitorEventAdapter._get_handlercKs t|jj|j| ¡d�|d<dS)N)ÚserviceÚ operationÚ timestampÚcurrent_api_call_event)Ú APICallEventZ service_modelZ service_idZ wire_nameÚ_get_current_time)r ÚmodelÚcontextÚkwargsr r r Ú_handle_before_parameter_buildbsz2MonitorEventAdapter._handle_before_parameter_buildcKs6|j}|dj| ¡d�}|j|_|j|_||d<dS)Nr*)r)Úcurrent_api_call_attempt_event)r.Únew_api_call_attemptr,ÚheadersÚrequest_headersÚurl)r Úrequestr/r.Znew_attempt_eventr r r Ú_handle_request_createdis z+MonitorEventAdapter._handle_request_createdcKsR| d¡}| |¡|_|dk rH|dd|_|dd|_| d¡|_n||_|S)Nr1ÚResponseMetadataZHTTPStatusCodeZ HTTPHeadersÚError)ÚpopÚ _get_latencyÚlatencyÚhttp_status_codeÚresponse_headersÚgetÚ parsed_errorÚwire_exception)r Zparsed_responser.Ú exceptionr/Ú attempt_eventr r r Ú_handle_response_receivedrs  z-MonitorEventAdapter._handle_response_receivedcKs |d dd¡|d_| |¡S)Nr8ZMaxAttemptsReachedFr*)r?Úretries_exceededÚ_complete_api_call)r r.Úparsedr/r r r Ú_handle_after_callƒsz&MonitorEventAdapter._handle_after_callcKs| |¡|d_| |¡S)Nr*)Ú_is_retryable_exceptionrErF)r r.rBr/r r r Ú_handle_after_call_error‰sz,MonitorEventAdapter._handle_after_call_errorcCst|ttdƒƒS)NZGENERAL_CONNECTION_ERROR)Ú isinstanceÚtupleÚRETRYABLE_EXCEPTIONS)r rBr r r rI“sz+MonitorEventAdapter._is_retryable_exceptioncCs| d¡}| |¡|_|S)Nr*)r:r;r<)r r.Z call_eventr r r rF˜s  z&MonitorEventAdapter._complete_api_callcCs| ¡|jS)N)r,r))r Úeventr r r r;�sz MonitorEventAdapter._get_latencycCst| ¡dƒS)Niè)Úintr)r r r r r, sz%MonitorEventAdapter._get_current_timeN)rrrrr rr r0r7rDrHrJrIrFr;r,r r r r rDs  rc@s$eZdZdd„Zdd„Zdd„ZdS)ÚBaseMonitorEventcCs||_||_||_dS)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 N)r'r(r))r r'r(r)r r r r ¥szBaseMonitorEvent.__init__cCs|jj›d|j›d�S)Nú(ú))Ú __class__rÚ__dict__)r r r r Ú__repr__·szBaseMonitorEvent.__repr__cCst||jƒr|j|jkSdS)NF)rKrSrT)r Úotherr r r Ú__eq__ºs  zBaseMonitorEvent.__eq__N)rrrr rUrWr r r r rP¤srPcs&eZdZd‡fdd„ Zdd„Z‡ZS)r+NFcs6tƒj|||d�||_||_|dkr,g|_||_dS)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'r(r)N)Úsuperr r<ÚattemptsrE)r r'r(r)r<rYrE)rSr r r Ás$ zAPICallEvent.__init__cCs"t|j|j|d�}|j |¡|S)zÏInstantiates APICallAttemptEvent associated to the APICallEvent :type timestamp: int :param timestamp: Epoch time in milliseconds to associate to the APICallAttemptEvent )r'r(r))ÚAPICallAttemptEventr'r(rYÚappend)r r)rCr r r r2îs z!APICallEvent.new_api_call_attempt)NNF)rrrr r2Ú __classcell__r r )rSr r+Às&r+cseZdZd‡fdd„ Z‡ZS)rZNc s@tƒj|||d�||_||_||_||_||_| |_| |_dS)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'r(r)N) rXr r<r5r=r4r>r@rA) r r'r(r)r<r5r=r4r>r@rA)rSr r r ýs9 zAPICallAttemptEvent.__init__)NNNNNNN)rrrr r\r r )rSr rZüsrZc @s&eZdZdZdZdZdZdZddddœZe   d ¡e   d ¡d œZ d d ddddddddddg Z dd„Z dd„Zdd„Zdd„Zd d!„Zd"d#„Zd$d%„Zd&d'„Zd(d)„Zd*d+„Zd,d-„Zd.d/„Zd0d1„Zd2d3„Zd4d5„Zd6d7„Zd8d9„Zd:d;„Zdd?„Z d@dA„Z!dBdC„Z"dDdE„Z#dFdG„Z$dHdI„Z%dJS)KÚ CSMSerializeréÿé€éiZXAmznRequestIdZ XAmzRequestIdZXAmzId2)zx-amzn-requestidzx-amz-request-idz x-amz-id-2zSAWS4-HMAC-SHA256 Credential=(?P\w+)/\d+/(?P[a-z0-9-]+)/zAWS (?P\w+):)Úv4Zs3r'r(r)rYr<rEr5r4r=r>r@rAcCs| |¡||_dS)zÖSerializes 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 rcr r r r ds zCSMSerializer.__init__cCs*t|ƒ|jkr&td|›d|j›d�ƒ‚dS)Nz&The value provided for csm_client_id: z exceeds the maximum length of z characters)ÚlenÚ_MAX_CLIENT_ID_LENGTHÚ ValueError)r rcr r r rbnsz!CSMSerializer._validate_client_idcCsj| |¡}| |¡}||d<x:|jD]0}t||dƒ}|dk r$t|d|ƒ|||d�q$Wttj|dd�ƒS)zàSerializes 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 ÚTypeNZ _serialize_)Ú event_type)ú,ú:)Ú separators)Ú_get_base_event_dictÚ_get_event_typeÚ_SERIALIZEABLE_EVENT_PROPERTIESr$rÚjsonÚdumps)r rNÚ event_dictrhÚattrÚvaluer r r Ú serializeus     zCSMSerializer.serializecCs d|jdœS)Né)ÚVersionZClientId)rc)r rNr r r rl‰sz"CSMSerializer._get_base_event_dictcKs ||d<dS)NZServicer )r r'rqr/r r r Ú_serialize_service�sz CSMSerializer._serialize_servicecKs ||d<dS)NZApir )r r(rqr/r r r Ú_serialize_operation’sz"CSMSerializer._serialize_operationcKs ||d<dS)NÚ Timestampr )r r)rqr/r r r Ú_serialize_timestamp•sz"CSMSerializer._serialize_timestampcKs$t|ƒ|d<|r | ||d¡dS)NZ AttemptCountéÿÿÿÿ)rdÚ_add_fields_from_last_attempt)r rYrqr/r r r Ú_serialize_attempts˜s z!CSMSerializer._serialize_attemptscCs~|jr2| |j¡}|dk r"||d<| |j¡|d<|jdk rF|j|d<|jdk r`| |j|d¡|jdk rz| |j|d¡dS)NÚRegionÚ UserAgentZFinalHttpStatusCodeÚApiCall)r4Ú _get_regionÚ_get_user_agentr=r@Ú_serialize_parsed_errorrAÚ_serialize_wire_exception)r rqÚ last_attemptÚregionr r r r|�s       z+CSMSerializer._add_fields_from_last_attemptcCs&|dkr||d<n|dkr"||d<dS)Nr€ZLatencyÚApiCallAttemptZAttemptLatencyr )r r<rqrhr r r Ú_serialize_latency²s z CSMSerializer._serialize_latencycKs|rdnd|d<dS)NrurZMaxRetriesExceededr )r rErqr/r r r Ú_serialize_retries_exceeded¸sz)CSMSerializer._serialize_retries_exceededcKst|ƒj|d<dS)NZFqdn)rÚnetloc)r r5rqr/r r r Ú_serialize_url½szCSMSerializer._serialize_urlcKsX| |¡|d<| |¡r&| |¡|d<| |¡}|dk r@||d<d|krT|d|d<dS)NrZ AccessKeyr~zX-Amz-Security-TokenZ SessionToken)r‚Ú _is_signedÚ_get_access_keyr�)r r4rqr/r†r r r Ú_serialize_request_headersÀs  z(CSMSerializer._serialize_request_headerscKs ||d<dS)NZHttpStatusCoder )r r=rqr/r r r Ú_serialize_http_status_codeÎsz)CSMSerializer._serialize_http_status_codecKs0x*|j ¡D]\}}||kr ||||<q WdS)N)Ú"_RESPONSE_HEADERS_TO_EVENT_ENTRIESÚitems)r r>rqr/ÚheaderÚentryr r r Ú_serialize_response_headersÓsz)CSMSerializer._serialize_response_headerscKsH|dkr dnd}| |d|j¡||d<| |d|j¡||d<dS)Nr€ÚFinalÚZCodeZ AwsExceptionÚMessageZAwsExceptionMessage)Ú _truncateÚ_MAX_ERROR_CODE_LENGTHÚ_MAX_MESSAGE_LENGTH)r r@rqrhr/Ú field_prefixr r r rƒÚs z%CSMSerializer._serialize_parsed_errorcKsH|dkr dnd}| |jj|j¡||d<| t|ƒ|j¡||d<dS)Nr€r•r–Z SdkExceptionZSdkExceptionMessage)r˜rSrÚ_MAX_EXCEPTION_CLASS_LENGTHÚstrrš)r rArqrhr/r›r r r r„ås z'CSMSerializer._serialize_wire_exceptioncCs t|tƒrdSt|tƒrdSdS)Nr€r‡)rKr+rZ)r rNr r r rmðs  zCSMSerializer._get_event_typecCs"| |¡}| |¡\}}| d¡S)NZ access_key)Ú_get_auth_valueÚ_get_auth_matchÚgroup)r r4Úauth_valr#Ú auth_matchr r r r�ös zCSMSerializer._get_access_keycCs<| |¡sdS| |¡}| |¡\}}|dkr2dS| d¡S)NraZsigning_region)rŒržrŸr )r r4r¡Úsignature_versionr¢r r r r�ûs  zCSMSerializer._get_regioncCs| t| dd¡ƒ|j¡S)Nz User-Agentr–)r˜rr?Ú_MAX_USER_AGENT_LENGTH)r r4r r r r‚szCSMSerializer._get_user_agentcCsd|kS)NÚ Authorizationr )r r4r r r rŒ szCSMSerializer._is_signedcCs t|dƒS)Nr¥)r)r r4r r r rž szCSMSerializer._get_auth_valuecCs2x,|j ¡D]\}}| |¡}|r ||fSq WdS)N)NN)Ú _AUTH_REGEXSr‘Úmatch)r r¡r£Úregexr§r r r rŸs   zCSMSerializer._get_auth_matchcCs*t|ƒ|kr&t d||¡|d|…S|S)Nz6Truncating following value to maximum length of %s: %s)rdrr)r ÚtextÚ max_lengthr r r r˜s  zCSMSerializer._truncateN)&rrrrerœr™r¤ršr�ÚreÚcompiler¦rnr rbrtrlrwrxrzr}r|rˆr‰r‹rŽr�r”rƒr„rmr�r�r‚rŒržrŸr˜r r r r r]Bs`    r]c@s eZdZdZdd„Zdd„ZdS)ÚSocketPublisheri cCs||_||f|_||_dS)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Ú serializerr r r r %s zSocketPublisher.__init__cCsF|j |¡}t|ƒ|jkr2t dt|ƒ|j¡dS|j ||j¡dS)zÆPublishes 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°rtrdÚ_MAX_MONITOR_EVENT_LENGTHrrr®Úsendtor¯)r rNZserialized_eventr r r r:s zSocketPublisher.publishN)rrrrµr rr r r r r­"sr­)roÚloggingr«rZbotocore.compatrrrZbotocore.retryhandlerrrMÚ getLoggerrrrrrPr+rZr]r­r r r r Ú s  ,`<Fa