
    	]jl)                         d Z ddlZddlZddlZddlZ	 ddlZddlZddl	m
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# e$ r dZY ;w xY w)z&Helper functions for logging handlers.    N)_get_django_requestCONTENT_LENGTHHTTP_X_CLOUD_TRACE_CONTEXTHTTP_TRACEPARENTHTTP_USER_AGENTREMOTE_ADDRHTTP_REFERERX_CLOUD_TRACE_CONTEXTTRACEPARENTSERVER_PROTOCOLc                    t        j                  | j                        \  }}|t        |      t        |dz        d| j                  | j
                  d}t        j                  dt               t        j                  |d      S )zHelper to format a LogRecord in in Stackdriver fluentd format.

    Returns:
        str: JSON str to be written to the log file.

    DEPRECATED:  use StructuredLogHandler to write formatted logs to standard out instead.
    g    eA)secondsnanos)message	timestampthreadseverityzHformat_stackdriver_json is deprecated. Use StructuredLogHandler instead.F)ensure_ascii)mathmodfcreatedintr   	levelnamewarningswarnDeprecationWarningjsondumps)recordr   	subsecondsecondpayloads        S/root/env/lib/python3.12/site-packages/google/cloud/logging_v2/handlers/_helpers.pyformat_stackdriver_jsonr$   *   ss     		&..1Iv !$Vs9s?7KL--$$	G MMR ::gE22    c                  8   t         t         j                  syt         j                  j                  t         j                  j                  t         j                  j                  j
                  t         j                  j                  j                  t              d} t         j                  j                  j                  t              }t        |      \  }}}|<t         j                  j                  j                  t              }t        |      \  }}}| |||fS )a@  Get http_request and trace data from flask request headers.

    Returns:
        Tuple[Optional[dict], Optional[str], Optional[str], bool]:
            Data related to the current http request, trace_id, span_id and trace_sampled
            for the request. All fields will be None if a Flask request isn't found.
    NNNFrequestMethod
requestUrl	userAgentprotocol)flaskrequestmethodurl
user_agentstringenvironget_PROTOCOL_HEADERheaders_FLASK_TRACEPARENT_parse_trace_parent_FLASK_XCLOUD_TRACE_HEADER_parse_xcloud_trace)http_requestheadertrace_idspan_idtrace_sampleds        r#   get_request_data_from_flaskr@   A   s     }EMM& --mm'']]--44MM))--.>?	L ]]""&&'9:F':6'B$Hg}&&**+EF+>v+F('=7M99r%   c                     t               } | y	 | j                         }| j                  || j                  j                  t              | j                  j                  t              d}| j                  j                  t              }t        |      \  }}}|.| j                  j                  t              }t        |      \  }}}||||fS # t        $ r d}Y w xY w)aC  Get http_request and trace data from django request headers.

    Returns:
        Tuple[Optional[dict], Optional[str], Optional[str], bool]:
            Data related to the current http request, trace_id, span_id, and trace_sampled
            for the request. All fields will be None if a django request isn't found.
    Nr'   r(   )r   build_absolute_uri	Exceptionr/   METAr4   _DJANGO_USERAGENT_HEADERr5   _DJANGO_TRACEPARENTr8   _DJANGO_XCLOUD_TRACE_HEADERr:   )r.   request_urlr;   r<   r=   r>   r?   s          r#   get_request_data_from_djangorI   `   s     "#G&002 !!\\%%&>?LL$$%56	L \\12F':6'B$Hg}!!"=>+>v+F('=7M99)  s   C CCc           	      8   dx}}d}| ry	 d}d}d}d}d| d| d| d| d		}t        j                  ||       }	|	j                  d
      }|	j                  d      }t        |	j                  d      d      }
t	        |
dz        }|||fS # t
        t        f$ r Y w xY w)a  Given a w3 traceparent header, extract the trace and span ids.
    For more information see https://www.w3.org/TR/trace-context/

    Args:
        header (str): the string extracted from the traceparent header
            example: 00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01
    Returns:
        Tuple[Optional[dict], Optional[str], bool]:
            The trace_id, span_id and trace_sampled extracted from the header
            Each field will be None if header can't be parsed in expected format.
    NFz(?!ff)[a-f\d]{2}z(?![0]{32})[a-f\d]{32}z(?![0]{16})[a-f\d]{16}z
[a-f\d]{2}z^\s?(z)-(z)(-.*)?\s?$               )rematchgroupr   bool
IndexErrorAttributeError)r<   r=   r>   r?   VERSION_PARTTRACE_ID_PARTPARENT_ID_PART
FLAGS_PARTregexrQ   int_flags              r#   r8   r8      s     HwM	.L5M6N&J\N#m_C?OsS]R^^jkEHHUF+E{{1~Hkk!nG5;;q>2.H A.M Wm++ N+ 		s   A8B BBc                 @   dx}}d}| rl	 d}t        j                  ||       }|j                  d      }|j                  d      }|j                  d      dk(  }	 t        |      }|dkD  r
|d	k  r|d
}nd}|||fS # t        t
        f$ r d}Y w xY w# t        $ r Y 'w xY w)aW  Given an X_CLOUD_TRACE header, extract the trace and span ids.

    Args:
        header (str): the string extracted from the X_CLOUD_TRACE header
    Returns:
        Tuple[Optional[str], Optional[str], bool]:
            The trace_id, span_id and trace_sampled extracted from the header
            Each field will be None if not found.
    NFz"([\w-]+)?(\/?([\w-]+))?(;?o=(\d))?rO   rL      1r   l            016x)rP   rQ   rR   r   
ValueError	TypeErrorrT   )r<   r=   r>   r?   rZ   rQ   span_id_ints          r#   r:   r:      s     HwM 	9EHHUF+E{{1~Hkk!nG!KKNc1M!'l?{U':!,T 2G"G Wm++ 	*   		s0   AB A: :BB BB 	BBc                     t         j                  j                         } | t         j                  j                  j                  k7  r}| j                         }t         j                  j                  |j                        }t         j                  j                  |j                        }|j                  j                  }|||fS y)ar  Helper to retrieve trace, span ID, and trace sampled information from the current
    OpenTelemetry span.

    Returns:
        Tuple[Optional[str], Optional[str], bool]:
            Data related to the current trace_id, span_id, and trace_sampled for the
            current OpenTelemetry span. If a span is not found, return None/False for all
            fields.
    NNF)opentelemetrytraceget_current_spanspanINVALID_SPANget_span_contextformat_trace_idr=   format_span_idr>   trace_flagssampled)rh   contextr=   r>   r?   s        r#   %_retrieve_current_open_telemetry_spanrp      s     //1D}""''444'') &&66w7G7GH%%44W__E++33-//r%   c                      t               \  } }}t        t        f}d\  }}}}|D ]  } |       \  }}}}|d\  }}} n | r|| ||fS ||||fS )a[  Helper to get http_request and trace data from supported web
    frameworks (currently supported: Flask and Django), as well as OpenTelemetry. Attempts
    to retrieve trace/spanID from OpenTelemetry first, before going to Traceparent then XCTC.
    HTTP request data is taken from a supporting web framework (currently Flask or Django).
    Because HTTP request data is decoupled from OpenTelemetry, it is possible to get as a
    return value the HTTP request from the web framework of choice, and trace/span data from
    OpenTelemetry, even if trace data is present in the HTTP request headers.

    Returns:
        Tuple[Optional[dict], Optional[str], Optional[str], bool]:
            Data related to the current http request, trace_id, span_id, and trace_sampled
            for the request. All fields will be None if a http request isn't found.
    r'   rd   )rp   rI   r@   )	otel_trace_idotel_span_idotel_trace_sampledcheckersr;   http_trace_idhttp_span_idhttp_trace_sampledcheckers	            r#   get_request_datarz      s    & 	./	
 	%#H
EAL-/A  HO	Em\3E>O;M<); ]L:LLL]L:LLLr%   )__doc__r   r   rP   r   r-   ImportErroropentelemetry.tracere   3google.cloud.logging_v2.handlers.middleware.requestr   _DJANGO_CONTENT_LENGTHrG   rF   rE   _DJANGO_REMOTE_ADDR_HEADER_DJANGO_REFERER_HEADERr9   r7   r5   r$   r@   rI   r8   r:   rp   rz    r%   r#   <module>r      s    -   	   S) : ( , * ' 4 " $ 3.:>%:P ,F*,Z,-Mm  Es   A
 
AA