o .&ajP@sddlZddlZddlZddlZddlmZmZmZddlm Z e e Z GdddeZGdddeZGdd d eZGd d d eZGd d d eZGdddeZGdddeZdS)N)ensure_unicode ensure_bytesurlparse) EXCEPTION_MAPc@s,eZdZgdZddZddZddZdS) Monitor)zbefore-parameter-buildzrequest-createdzresponse-receivedz after-callzafter-call-errorcCs||_||_dS)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)selfadapter publisherr 5/usr/lib/python3/dist-packages/botocore/monitoring.py__init__"s zMonitor.__init__cCs|jD] }|||jqdS)z(Register an event emitter to the monitorN)_EVENTS_TO_REGISTER register_lastcapture)r event_emitterevent_to_registerr r r register-s zMonitor.registerc Ksdz|j||}|r|j|WdSWdSty1}ztjd||ddWYd}~dSd}~ww)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)rfeedrpublish Exceptionloggerdebug)r event_namepayload monitor_eventer r r r2szMonitor.captureN)__name__ __module__ __qualname__rrrrr r r r rs  rc@sreZdZejfddZddZddZddZd d Zd d Z d dZ ddZ ddZ ddZ ddZddZdS)MonitorEventAdaptercCs ||_dS)zAdapts 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 rCs zMonitorEventAdapter.__init__cCs||di|S)aFeed 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 Nr ) _get_handler)r emitter_event_nameemitter_payloadr r r rKszMonitorEventAdapter.feedcCs t|d|ddddS)N_handle_.r-_)getattrsplitreplace)r rr r r r%[sz MonitorEventAdapter._get_handlercKs t|jj|j|d|d<dS)Nservice operation timestampcurrent_api_call_event) APICallEvent service_model service_id wire_name_get_current_time)r modelcontextkwargsr r r _handle_before_parameter_build`s z2MonitorEventAdapter._handle_before_parameter_buildcKs6|j}|dj|d}|j|_|j|_||d<dS)Nr3)r2current_api_call_attempt_event)r:new_api_call_attemptr8headersrequest_headersurl)r requestr;r:new_attempt_eventr r r _handle_request_createdgs z+MonitorEventAdapter._handle_request_createdcKsT|d}|||_|dur%|dd|_|dd|_|d|_|S||_|S)Nr=ResponseMetadataHTTPStatusCode HTTPHeadersError)pop _get_latencylatencyhttp_status_coderesponse_headersget parsed_errorwire_exception)r parsed_responser: exceptionr; attempt_eventr r r _handle_response_receivedps"   z-MonitorEventAdapter._handle_response_receivedcKs |ddd|d_||S)NrEMaxAttemptsReachedFr3)rNretries_exceeded_complete_api_call)r r:parsedr;r r r _handle_after_call~s  z&MonitorEventAdapter._handle_after_callcKs|||d_||SNr3)_is_retryable_exceptionrVrW)r r:rRr;r r r _handle_after_call_errors z,MonitorEventAdapter._handle_after_call_errorcCst|ttdS)NGENERAL_CONNECTION_ERROR) isinstancetupleRETRYABLE_EXCEPTIONS)r rRr r r r[s z+MonitorEventAdapter._is_retryable_exceptioncCs|d}|||_|SrZ)rIrJrK)r r: call_eventr r r rWs  z&MonitorEventAdapter._complete_api_callcCs||jSN)r8r2r eventr r r rJsz MonitorEventAdapter._get_latencycCst|dS)Ni)intr#r r r r r8sz%MonitorEventAdapter._get_current_timeN)rr r!r$rrr%r<rDrTrYr\r[rWrJr8r r r r r"Bs   r"c@s$eZdZddZddZddZdS)BaseMonitorEventcCs||_||_||_dS)aBase 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 r0r1r2r r r rs zBaseMonitorEvent.__init__cCsd|jj|jfS)Nz%s(%r)) __class__r__dict__rfr r r __repr__zBaseMonitorEvent.__repr__cCst||jr |j|jkSdS)NF)r^rhri)r otherr r r __eq__s  zBaseMonitorEvent.__eq__N)rr r!rrjrmr r r r rgs rgcs*eZdZ  dfdd ZddZZS)r4NFcs:tt|j|||d||_||_|durg|_||_dS)aMonitor 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)superr4rrKattemptsrV)r r0r1r2rKrorVrhr r rs  zAPICallEvent.__init__cCs"t|j|j|d}|j||S)zInstantiates APICallAttemptEvent associated to the APICallEvent :type timestamp: int :param timestamp: Epoch time in milliseconds to associate to the APICallAttemptEvent r/)APICallAttemptEventr0r1roappend)r r2rSr r r r>s z!APICallEvent.new_api_call_attempt)NNF)rr r!rr> __classcell__r r rpr r4s %r4cs$eZdZ   dfdd ZZS)rqNc sDtt|j|||d||_||_||_||_||_| |_| |_ dS)aMonitor 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) rnrqrrKrArLr@rMrOrP) r r0r1r2rKrArLr@rMrOrPrpr r rs 0 zAPICallAttemptEvent.__init__)NNNNNNN)rr r!rrsr r rpr rqs rqc@seZdZdZdZdZdZdZddddZe d e d d Z gd Z d dZ ddZddZddZddZddZddZddZddZdd Zd!d"Zd#d$Zd%d&Zd'd(Zd)d*Zd+d,Zd-d.Zd/d0Zd1d2Zd3d4Z d5d6Z!d7d8Z"d9d:Z#d;d<Z$d=d>Z%d?S)@ CSMSerializeriXAmznRequestId XAmzRequestIdXAmzId2)zx-amzn-requestidzx-amz-request-idz x-amz-id-2zSAWS4-HMAC-SHA256 Credential=(?P\w+)/\d+/(?P[a-z0-9-]+)/zAWS (?P\w+):)v4s3) r0r1r2rorKrVrAr@rLrMrOrPcCs||||_dS)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_idr r~r r r rOs  zCSMSerializer.__init__cCs$t||jkrtd||jfdS)NzTThe value provided for csm_client_id: %s exceeds the maximum length of %s characters)len_MAX_CLIENT_ID_LENGTH ValueErrorrr r r r}Ysz!CSMSerializer._validate_client_idcCsf||}||}||d<|jD]}t||d}|dur)t|d||||dqttj|ddS)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_PROPERTIESr,rjsondumps)r rd event_dictrattrvaluer r r serializeas     zCSMSerializer.serializecCs d|jdS)N)VersionClientId)r~rcr r r rusz"CSMSerializer._get_base_event_dictcK ||d<dS)NServicer )r r0rr;r r r _serialize_service{ z CSMSerializer._serialize_servicecKr)NApir )r r1rr;r r r _serialize_operation~rz"CSMSerializer._serialize_operationcKr)N Timestampr )r r2rr;r r r _serialize_timestamprz"CSMSerializer._serialize_timestampcKs(t||d<|r|||ddSdS)N AttemptCount)r_add_fields_from_last_attempt)r rorr;r r r _serialize_attemptss z!CSMSerializer._serialize_attemptscCs|jr||j}|dur||d<||j|d<|jdur#|j|d<|jdur0||j|d|jdur?||j|ddSdS)NRegion UserAgentFinalHttpStatusCodeApiCall)r@ _get_region_get_user_agentrLrO_serialize_parsed_errorrP_serialize_wire_exception)r r last_attemptregionr r r rs$     z+CSMSerializer._add_fields_from_last_attemptcCs,|dkr ||d<dS|dkr||d<dSdS)NrLatencyApiCallAttemptAttemptLatencyr )r rKrrr r r _serialize_latencys   z CSMSerializer._serialize_latencycKs|rdnd|d<dS)NrrMaxRetriesExceededr )r rVrr;r r r _serialize_retries_exceededsz)CSMSerializer._serialize_retries_exceededcKst|j|d<dS)NFqdn)rnetloc)r rArr;r r r _serialize_urlrkzCSMSerializer._serialize_urlcKs\|||d<||r|||d<||}|dur ||d<d|vr,|d|d<dSdS)Nr AccessKeyrzX-Amz-Security-Token SessionToken)r _is_signed_get_access_keyr)r r@rr;rr r r _serialize_request_headerss   z(CSMSerializer._serialize_request_headerscKr)NHttpStatusCoder )r rLrr;r r r _serialize_http_status_codes z)CSMSerializer._serialize_http_status_codecKs,|jD]\}}||vr||||<qdSrb)"_RESPONSE_HEADERS_TO_EVENT_ENTRIESitems)r rMrr;headerentryr r r _serialize_response_headerss  z)CSMSerializer._serialize_response_headerscKsH|dkrdnd}||d|j||d<||d|j||d<dS)NrFinalCode AwsExceptionMessageAwsExceptionMessage) _truncate_MAX_ERROR_CODE_LENGTH_MAX_MESSAGE_LENGTH)r rOrrr; field_prefixr r r rs   z%CSMSerializer._serialize_parsed_errorcKsH|dkrdnd}||jj|j||d<|t||j||d<dS)Nrrr SdkExceptionSdkExceptionMessage)rrhr_MAX_EXCEPTION_CLASS_LENGTHstrr)r rPrrr;rr r r rs  z'CSMSerializer._serialize_wire_exceptioncCs t|trdSt|trdSdS)Nrr)r^r4rqrcr r r rs  zCSMSerializer._get_event_typecCs"||}||\}}|dS)N access_key)_get_auth_value_get_auth_matchgroup)r r@auth_valr+ auth_matchr r r rs  zCSMSerializer._get_access_keycCs<||sdS||}||\}}|dkrdS|dS)Nr{signing_region)rrrr)r r@rsignature_versionrr r r rs   zCSMSerializer._get_regioncCs|t|dd|jS)Nz User-Agentr)rrrN_MAX_USER_AGENT_LENGTHr r@r r r rszCSMSerializer._get_user_agentcCsd|vSN Authorizationr rr r r rszCSMSerializer._is_signedcCs t|dSr)rrr r r rrzCSMSerializer._get_auth_valuecCs2|jD]\}}||}|r||fSqdS)N)NN) _AUTH_REGEXSrmatch)r rrregexrr r r rs   zCSMSerializer._get_auth_matchcCs*t||krtd|||d|S|S)Nz6Truncating following value to maximum length of %s: %s)rrr)r text max_lengthr r r rs  zCSMSerializer._truncateN)&rr r!rrrrrrrecompilerrrr}rrrrrrrrrrrrrrrrrrrrrrrr r r r rt+sV      rtc@s eZdZdZddZddZdS)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 sockethostport serializerr r r rs  zSocketPublisher.__init__cCsF|j|}t||jkrtdt||jdS|j||jdS)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) rrr_MAX_MONITOR_EVENT_LENGTHrrrsendtor)r rdserialized_eventr r r rs  zSocketPublisher.publishN)rr r!rrrr r r r rs r)rloggingrr$botocore.compatrrrbotocore.retryhandlerrr` getLoggerrrobjectrr"rgr4rqrtrr r r r s   )Z6=U