
    Th.                     @   d Z ddlZddlm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  ej"                  e      Z ej(                  ej*                  d      Zes ej(                  ej.                  d	      Zd
j1                  e      Zdj1                   ej(                  ej4                  d            ZdZdZeeiZ	  e ej(                  dd            Z dZ"dZ#d Z$d Z%e dfdZ&edddddfdZ'd Z(d Z)ddZ*ddZ+y# e!$ r dZ Y 2w xY w)zProvides helper methods for talking to the Compute Engine metadata server.

See https://cloud.google.com/compute/docs/metadata for more details.
    N)urljoin)_helpers)environment_vars)
exceptions)metrics)ExponentialBackoffzmetadata.google.internalzhttp://{}/computeMetadata/v1/z	http://{}z169.254.169.254zmetadata-flavorGoogleGCE_METADATA_TIMEOUT   z/sys/class/dmi/id/product_namec                 V    t        |       ryt        j                  dk(  ryt               S )a  Checks to see if the code runs on Google Compute Engine

    Args:
        request (google.auth.transport.Request): A callable used to make
            HTTP requests.

    Returns:
        bool: True if the code runs on Google Compute Engine, False otherwise.
    TntF)pingosnamedetect_gce_residency_linuxrequests    d/opt/server/standalone/crm/venv/lib/python3.12/site-packages/google/auth/compute_engine/_metadata.py	is_on_gcer   C   s'     G}	ww$ &''    c                      	 t        t        d      5 } | j                         j                         }ddd       j                  t              S # 1 sw Y   xY w# t        $ r Y yw xY w)zDetect Google Compute Engine residency by smbios check on Linux

    Returns:
        bool: True if the GCE product name file is detected, False otherwise.
    rNF)open_GCE_PRODUCT_NAME_FILEreadstrip	Exception
startswith_GOOGLE)file_objcontents     r   r   r   X   sc    (#. 	.(mmo++-G	. g&&	. 	.  s'   A AA AA 	A&%A&c                    t         j                         }t        j                         |t        j                  <   t        |      }|D ][  }	  | t        d||      }|j                  j                  t              }|j                  t        j                  k(  xr	 |t        k(  c S  y# t        j                  $ r"}t         j#                  d|||       Y d}~d}~ww xY w)a  Checks to see if the metadata server is available.

    Args:
        request (google.auth.transport.Request): A callable used to make
            HTTP requests.
        timeout (int): How long to wait for the metadata server to respond.
        retry_count (int): How many times to attempt connecting to metadata
            server using above timeout.

    Returns:
        bool: True if the metadata server is reachable, False otherwise.
    total_attemptsGET)urlmethodheaderstimeoutJCompute Engine Metadata server unavailable on attempt %s of %s. Reason: %sNF)_METADATA_HEADERScopyr   mds_pingAPI_CLIENT_HEADERr   _METADATA_IP_ROOTr(   get_METADATA_FLAVOR_HEADERstatushttp_clientOK_METADATA_FLAVOR_VALUEr   TransportError_LOGGERwarning)	r   r)   retry_countr(   backoffattemptresponsemetadata_flavores	            r   r   r   h   s    &  $$&G)0)9)9);GG%%& <G 	%eWgH '..223JKO;>>1 >#'==*  (( 	OO/ 	s   AB''C:CCF   c                    t        ||      }|i n|}	t        j                         }
|r|
j                  |       |rd|	d<   t	        j
                  ||	      }t        |      }|D ]  }	  | |d|
      } n% t        j                  dj                  |            t	        j                  |j                        }|j                  t        j                   k(  r|ry|j                  t        j"                  k(  r=t	        j$                  |j&                  d	         d
k(  r	 t)        j*                  |      S |S t        j                  dj                  ||j                  |j                        |      # t        j                  $ r#}t        j                  d|||       Y d}~;d}~ww xY w# t,        $ r,}t        j                  dj                  |            }||d}~ww xY w)a  Fetch a resource from the metadata server.

    Args:
        request (google.auth.transport.Request): A callable used to make
            HTTP requests.
        path (str): The resource to retrieve. For example,
            ``'instance/service-accounts/default'``.
        root (str): The full path to the metadata server root.
        params (Optional[Mapping[str, str]]): A mapping of query parameter
            keys to values.
        recursive (bool): Whether to do a recursive query of metadata. See
            https://cloud.google.com/compute/docs/metadata#aggcontents for more
            details.
        retry_count (int): How many times to attempt connecting to metadata
            server using above timeout.
        headers (Optional[Mapping[str, str]]): Headers for the request.
        return_none_for_not_found_error (Optional[bool]): If True, returns None
            for 404 error instead of throwing an exception.

    Returns:
        Union[Mapping, str]: If the metadata server returns JSON, a mapping of
            the decoded JSON is returned. Otherwise, the response content is
            returned as a string.

    Raises:
        google.auth.exceptions.TransportError: if an error occurred while
            retrieving metadata.
    Ntrue	recursiver#   r%   )r&   r'   r(   r*   zqFailed to retrieve {} from the Google Compute Engine metadata service. Compute Engine Metadata server unavailablezcontent-typezapplication/jsonzMReceived invalid JSON from the Google Compute Engine metadata service: {:.20}z^Failed to retrieve {} from the Google Compute Engine metadata service. Status: {} Response:
{})r   r+   r,   updater   update_queryr   r   r6   r7   r8   format
from_bytesdatar2   r3   	NOT_FOUNDr4   parse_content_typer(   jsonloads
ValueError)r   pathrootparamsrB   r9   r(   return_none_for_not_found_errorbase_urlquery_paramsheaders_to_user&   r:   r;   r<   r>   r!   
caught_excnew_excs                      r   r0   r0      s   L tT"H2VL&++-Ng&$*[!


,
7C <G 
	3unMH
 ''KKQ6RU;
 	

 !!(--0G+///4S+..(''(8(8(HI!".zz'** N

#
#	55;V(--6
 	 G (( 	OO/ 	4  .$33//5vg :-.s0   )E/F( /F%F  F%(	G1'GGc                     t        | d      S )aO  Get the Google Cloud Project ID from the metadata server.

    Args:
        request (google.auth.transport.Request): A callable used to make
            HTTP requests.

    Returns:
        str: The project ID

    Raises:
        google.auth.exceptions.TransportError: if an error occurred while
            retrieving metadata.
    zproject/project-idr0   r   s    r   get_project_idrX      s     w,--r   c                 (    t        | dd      }|sy|S )a  Get the universe domain value from the metadata server.

    Args:
        request (google.auth.transport.Request): A callable used to make
            HTTP requests.

    Returns:
        str: The universe domain value. If the universe domain endpoint is not
        not found, return the default value, which is googleapis.com

    Raises:
        google.auth.exceptions.TransportError: if an error other than
            404 occurs while retrieving metadata.
    zuniverse/universe_domainT)rP   zgoogleapis.comrW   )r   universe_domains     r   get_universe_domainr[     s$     +TO r   c                 D    dj                  |      }t        | |ddi      S )a  Get information about a service account from the metadata server.

    Args:
        request (google.auth.transport.Request): A callable used to make
            HTTP requests.
        service_account (str): The string 'default' or a service account email
            address. The determines which service account for which to acquire
            information.

    Returns:
        Mapping: The service account's information, for example::

            {
                'email': '...',
                'scopes': ['scope', ...],
                'aliases': ['default', '...']
            }

    Raises:
        google.auth.exceptions.TransportError: if an error occurred while
            retrieving metadata.
    zinstance/service-accounts/{0}/rB   rA   )rO   )rE   r0   )r   service_accountrM   s      r   get_service_account_infor^   %  s*    . ,22?CD wk6%:;;r   c                 H   |r&t        |t              sdj                  |      }d|i}nd}t        j                  t        j
                         i}dj                  |      }t        | |||      }t        j                         t        j                  |d         z   }|d   |fS )	a  Get the OAuth 2.0 access token for a service account.

    Args:
        request (google.auth.transport.Request): A callable used to make
            HTTP requests.
        service_account (str): The string 'default' or a service account email
            address. The determines which service account for which to acquire
            an access token.
        scopes (Optional[Union[str, List[str]]]): Optional string or list of
            strings with auth scopes.
    Returns:
        Tuple[str, datetime]: The access token and its expiration.

    Raises:
        google.auth.exceptions.TransportError: if an error occurred while
            retrieving metadata.
    ,scopesNz#instance/service-accounts/{0}/token)rO   r(   
expires_in)secondsaccess_token)
isinstancestrjoinr   r.   token_request_access_token_mdsrE   r0   r   utcnowdatetime	timedelta)r   r]   ra   rO   metrics_headerrM   
token_jsontoken_expirys           r   get_service_account_tokenro   B  s    $ &#&XXf%FF# 	!!7#I#I#KN 177HDWd6>JJ??$x'9'9<(( L n%|33r   )default)rp   N),__doc__rj   http.clientclientr3   rJ   loggingr   urllib.parser   google.authr   r   r   r    google.auth._exponential_backoffr   	getLogger__name__r7   getenvGCE_METADATA_HOST_GCE_METADATA_HOSTGCE_METADATA_ROOTrE   _METADATA_ROOTGCE_METADATA_IPr/   r1   r5   r+   int_METADATA_DEFAULT_TIMEOUTrL   r   r   r   r   r   r0   rX   r[   r^   ro    r   r   <module>r      s\  
  !   	     ( "  ?
'

H
% RYY/AA4H "**,F 1778JK  &&BII..0AB  , ! ,.DE " #IBII.Da$H I
 9 (*'  4 -f 
$)bJ.".<:"4O  " !"s   D DD