o
    d$                     @   s,  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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sIe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yu   dZY nw edfddZ edddf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)http_client)parse)_helpers)environment_vars)
exceptionszmetadata.google.internalzhttp://{}/computeMetadata/v1/z	http://{}z169.254.169.254zmetadata-flavorGoogleGCE_METADATA_TIMEOUT   c              
   C   s   d}||k rEz| t dt|d}|jt}|jtjko|tkW S  t	j
y@ } 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timeoutJCompute Engine Metadata server unavailable on attempt %s of %s. Reason: %s   NF)_METADATA_IP_ROOT_METADATA_HEADERSr   get_METADATA_FLAVOR_HEADERstatusr   OK_METADATA_FLAVOR_VALUEr   TransportError_LOGGERwarning)requestr   retry_countretriesresponsemetadata_flavore r!   K/tmp/pip-target-6c632izo/lib/python/google/auth/compute_engine/_metadata.pyping?   s2   r#   F   c              
   C   sB  t ||}|du ri n|}|rd|d< t||}d}	|	|k rOz	| |dtd}
W n- tjyJ } ztd|	d || |	d7 }	W Y d}~nd}~ww |	|k s td		||
j
tjkrt|
j}|
jd
 dkrzt|W S  ty } ztd	|}t|| W Y d}~dS 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.

    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:
{})urlparseurljoinr   update_queryr   r   r   r   r   formatr   r   r   
from_bytesdatar   jsonloads
ValueErrorsix
raise_from)r   pathrootparamsr&   r   base_urlquery_paramsr   r   r   r    content
caught_excnew_excr!   r!   r"   r   o   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   
r:   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&   r%   r4   )r*   r   )r   service_accountr2   r!   r!   r"   get_service_account_info   s   
r>   c                 C   sb   |rt |tsd|}d|i}nd}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}/tokenr<   
expires_in)secondsaccess_token)	
isinstancestrjoinr*   r   r   utcnowdatetime	timedelta)r   r=   r@   r4   r2   
token_jsontoken_expiryr!   r!   r"   get_service_account_token   s   




rL   )r;   )r;   N)%__doc__rH   r-   loggingosr0   	six.movesr   six.moves.urllibr   r'   google.authr   r   r   	getLogger__name__r   getenvGCE_METADATA_HOST_GCE_METADATA_HOSTGCE_METADATA_ROOTr*   _METADATA_ROOTGCE_METADATA_IPr   r   r   r   int_METADATA_DEFAULT_TIMEOUTr/   r#   r   r:   r>   rL   r!   r!   r!   r"   <module>   sF   

1
P
