o
    ÔèFhH.  ã                   @   sT  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 e e¡Ze ejd¡ZesKe 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yw   dZY nw dZ dZ!dd„ Z"dd„ Z#edfdd„Z$edddddfdd„Z%dd„ Z&dd„ Z'd$d d!„Z(d%d"d#„Z)dS )&z‘Provides 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)Úmetricsz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                 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   ú]/var/www/html/loop/nvenv/lib/python3.10/site-packages/google/auth/compute_engine/_metadata.pyÚ	is_on_gceB   s
   

r   c                  C   sZ   zt tdƒ�} |  ¡  ¡ }W d  ƒ n1 sw   Y  W n
 ty'   Y dS w | t¡S )z Detect 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Úcontentr   r   r   r   W   s   ÿ€ÿ
r   c              
   C   s¤   d}t  ¡ }t ¡ |tj< ||k rPz| td||d�}|j t¡}|j	t
jko)|tkW S  tjyK } zt d|d ||¡ |d7 }W Y d}~nd}~ww ||k s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.
    r   ÚGET)ÚurlÚmethodÚheadersÚtimeoutúJCompute Engine Metadata server unavailable on attempt %s of %s. Reason: %sé   NF)Ú_METADATA_HEADERSÚcopyr   Úmds_pingÚAPI_CLIENT_HEADERÚ_METADATA_IP_ROOTr!   ÚgetÚ_METADATA_FLAVOR_HEADERÚstatusÚhttp_clientÚOKÚ_METADATA_FLAVOR_VALUEr   ÚTransportErrorÚ_LOGGERÚwarning)r   r"   Úretry_countÚretriesr!   ÚresponseÚmetadata_flavorÚer   r   r   r   g   s0   ÿþû€øôr   Fé   c              
   C   s\  t ||ƒ}|du ri n|}	t ¡ }
|r|
 |¡ |rd|	d< t ||	¡}d}||k rYz	| |d|
d�}W n- tjyT } zt 	d|d ||¡ |d7 }W Y d}~nd}~ww ||k s*t d	 
|¡¡‚t |j¡}|jtjkrq|rqdS |jtjkr¡t |jd
 ¡dkrŸzt |¡W S  tyž } zt d 
|¡¡}||‚d}~ww |S t d 
||j|j¡|¡‚)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 return. 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#   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   r0   r1   r2   ÚformatÚ
from_bytesÚdatar,   r-   Ú	NOT_FOUNDr.   Úparse_content_typer!   ÚjsonÚloadsÚ
ValueError)r   ÚpathÚrootÚparamsr:   r3   r!   Úreturn_none_for_not_found_errorÚbase_urlÚquery_paramsÚheaders_to_user   r4   r5   r7   r   Ú
caught_excÚnew_excr   r   r   r*   —   sj   
&
û€øûþÿþ€û
ÿû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   
rO   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)rH   zgoogleapis.comrN   )r   Úuniverse_domainr   r   r   Úget_universe_domain  s   ÿrQ   Ú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}/r:   r9   )rG   )r=   r*   )r   Úservice_accountrE   r   r   r   Úget_service_account_info$  s   
rT   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)rG   r!   Ú
expires_in)ÚsecondsÚaccess_token)Ú
isinstanceÚstrÚjoinr   r(   Útoken_request_access_token_mdsr=   r*   r   ÚutcnowÚdatetimeÚ	timedelta)r   rS   rV   rG   Úmetrics_headerrE   Ú
token_jsonÚtoken_expiryr   r   r   Úget_service_account_tokenA  s   



ÿ

ÿrd   )rR   )rR   N)*Ú__doc__r_   Úhttp.clientÚclientr-   rB   Úloggingr   Úurllib.parser   Úgoogle.authr   r   r   r   Ú	getLoggerÚ__name__r1   ÚgetenvÚGCE_METADATA_HOSTÚ_GCE_METADATA_HOSTÚGCE_METADATA_ROOTr=   Ú_METADATA_ROOTÚGCE_METADATA_IPr)   r+   r/   r%   ÚintÚ_METADATA_DEFAULT_TIMEOUTrD   r   r   r   r   r   r*   rO   rQ   rT   rd   r   r   r   r   Ú<module>   sZ   
ÿ
ÿÿ3
øe
