U
    #FZh<2                     @   sr  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 dd	lmZ eeZeejdZeseejd
ZdeZdeejdZdZdZeeiZze eddZ!W n e"k
r
   dZ!Y nX dZ#dZ$dd Z%dd Z&e!dfddZ'eddddde!fddZ(dd Z)dd  Z*d&d"d#Z+d'd$d%Z,dS )(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)	transport)ExponentialBackoffzmetadata.google.internalzhttp://{}/computeMetadata/v1/z	http://{}z169.254.169.254zmetadata-flavorZGoogleZGCE_METADATA_TIMEOUT   z/sys/class/dmi/id/product_namec                 C   s    t | rdS tjdkrdS 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request r   k/home/aprabhat/apps/x.techxrdev.in/venv/lib/python3.8/site-packages/google/auth/compute_engine/_metadata.py	is_on_gceD   s
    

r   c               	   C   sH   z&t td} |   }W 5 Q R X W n tk
r<   Y dS X |tS )zDetect Google Compute Engine residency by smbios check on Linux

    Returns:
        bool: True if the GCE product name file is detected, False otherwise.
    rF)open_GCE_PRODUCT_NAME_FILEreadstrip	Exception
startswith_GOOGLE)Zfile_objcontentr   r   r   r   Y   s    r   c           	      C   s   t  }t |tj< t|d}|D ]p}z6| td||d}|jt	}|j
tjkoX|tkW   S  tjk
r } ztd||| W 5 d}~X Y q$X q$dS )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.
    Ztotal_attemptsGETurlmethodheaderstimeoutJCompute Engine Metadata server unavailable on attempt %s of %s. Reason: %sNF)_METADATA_HEADERScopyr   Z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responseZmetadata_flavorer   r   r   r   i   s.    
   r   F   c	                 C   s  t ||}	|dkri n|}
t }|r0|| |r<d|
d< t|	|
}t|d}d}|D ]}z^| |d||d}|jtj	krt
d|||j t|jdr|jd	n|j}W qZnW  q
W qZ tjk
r } zt
d
||| |}W 5 d}~X Y qZX qZtd||t|j}|jtjkr.|r.dS |jtjkrt|jd dkrzt|W S  tk
r } ztd|}||W 5 d}~X Y nX n|S td||j|j|dS )aH  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.
        timeout (int): How long to wait, in seconds for the metadata server to respond.

    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   zSCompute Engine Metadata server unavailable on attempt %s of %s. Response status: %sdecodezutf-8r$   z{Failed to retrieve {} from the Google Compute Engine metadata service. Compute Engine Metadata server unavailable due to {}z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   Zupdate_queryr   r+   r   ZDEFAULT_RETRYABLE_STATUS_CODESr0   r1   hasattrdatar:   r   r/   format
from_bytesr,   	NOT_FOUNDr-   Zparse_content_typer"   jsonloads
ValueError)r   pathrootparamsr9   r2   r"   return_none_for_not_found_errorr#   base_urlZquery_paramsZheaders_to_user    r3   Zfailure_reasonr4   r5   r6   r   Z
caught_excnew_excr   r   r   r)      s    (


   	
   r)   c                 C   s
   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r)   r   r   r   r   get_project_id  s    rK   c                 C   s   t | ddd}|sdS |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)rG   zgoogleapis.comrJ   )r   Zuniverse_domainr   r   r   get_universe_domain%  s      rL   defaultc                 C   s   d |}t| |ddid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}/r9   r8   )rF   )r>   r)   )r   service_accountrD   r   r   r   get_service_account_info<  s    
rO   c                 C   sr   |r"t |tsd|}d|i}nd}tjt i}d|}t| |||d}t	 t
j|d d }|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)rF   r"   Z
expires_in)secondsZaccess_token)
isinstancestrjoinr   r'   Ztoken_request_access_token_mdsr>   r)   r   utcnowdatetime	timedelta)r   rN   rQ   rF   Zmetrics_headerrD   Z
token_jsonZtoken_expiryr   r   r   get_service_account_tokenY  s    


 

rY   )rM   )rM   N)-__doc__rW   http.clientclientr,   rA   loggingr   urllib.parser   Zgoogle.authr   r   r   r   r   Z google.auth._exponential_backoffr   	getLogger__name__r0   getenvZGCE_METADATA_HOSTZ_GCE_METADATA_HOSTZGCE_METADATA_ROOTr>   Z_METADATA_ROOTZGCE_METADATA_IPr(   r*   r.   r%   intZ_METADATA_DEFAULT_TIMEOUTrC   r   r   r   r   r   r)   rK   rL   rO   rY   r   r   r   r   <module>   s^   
 

3
{
