o
    xi1                     @  s   d 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mZ dd	lmZ e	d
ddZe	dddej_e	dddej_e	dddejj_e	dddej_e	dddej_eeZdZG dd deZd!ddZd"dd ZdS )#z7Implementation of the GCP environment for wandb launch.    )annotationsN)LaunchError)
get_module   )
GCS_URI_REevent_loop_thread_exec   )AbstractEnvironmentgoogleznGoogle Cloud Platform support requires the google package. Please install it with `pip install wandb[launch]`.)requiredzgoogle.cloud.compute_v1z|Google Cloud Platform support requires the google-cloud-compute package. Please install it with `pip install wandb[launch]`.zgoogle.auth.credentialszgGoogle Cloud Platform support requires google-auth. Please install it with `pip install wandb[launch]`.zgoogle.auth.transport.requestszgoogle.api_core.exceptionszkGoogle Cloud Platform support requires google-api-core. Please install it with `pip install wandb[launch]`.zgoogle.cloud.storagezoGoogle Cloud Platform support requires google-cloud-storage. Please install it with `pip install wandb[launch].GOOGLE_CLOUD_REGIONc                      s   e Zd ZU dZded< d fddZedd
dZed ddZe	d!ddZ
d"ddZd#ddZd$ddZd%ddZd%ddZ  ZS )&GcpEnvironmentzFGCP Environment.

    Attributes:
        region: The GCP region.
    strregionreturnNonec                   s*   t    td|  || _d| _dS )a(  Initialize the GCP environment.

        Arguments:
            region: The GCP region.
            verify: Whether to verify the credentials, region, and project.

        Raises:
            LaunchError: If verify is True and the environment is not properly
                configured.
        z&Initializing GcpEnvironment in region  N)super__init___loggerinfor   _project)selfr   	__class__ `/home/ubuntu/.local/lib/python3.10/site-packages/wandb/sdk/launch/environment/gcp_environment.pyr   =   s   

zGcpEnvironment.__init__configdictc                 C  sD   | ddkrtd| d d| d}|std| |dS )zCreate a GcpEnvironment from a config dictionary.

        Arguments:
            config: The config dictionary.

        Returns:
            GcpEnvironment: The GcpEnvironment.
        typegcpzJCould not create GcpEnvironment from config. Expected type 'gcp' but got 'z'.r   zDCould not create GcpEnvironment from config. Missing 'region' field.r   )getr   )clsr   r   r   r   r   from_configP   s   


zGcpEnvironment.from_configc                 C  s    t  }|du rtd| |dS )zCreate a GcpEnvironment from the default configuration.

        Returns:
            GcpEnvironment: The GcpEnvironment.
        Na  Could not create GcpEnvironment from user's gcloud configuration. Please set the default region with `gcloud config set compute/region` or set the environment variable {GCP_REGION_ENV_VAR}. Alternatively, you may specify the region explicitly in your wandb launch configuration at `$HOME/.config/wandb/launch-config.yaml`. See https://docs.wandb.ai/guides/launch/run-agent#environments for more information.r!   )get_default_regionr   )r#   r   r   r   r   from_defaultf   s   	
zGcpEnvironment.from_defaultc                 C  s   | j S )zGet the name of the gcp project associated with the credentials.

        Returns:
            str: The name of the gcp project.

        Raises:
            LaunchError: If the launch environment cannot be verified.
        )r   r   r   r   r   project{   s   
zGcpEnvironment.project#google.auth.credentials.Credentialsc              
     s   t d z*ttjj}| I dH \}}| js|| _t d t|jtjjj	
 I dH  W n' tjjjyD } ztd|d}~w tjjjyW } ztd|d}~ww |js_td|S )a  Get the GCP credentials.

        Uses google.auth.default() to get the credentials. If the credentials
        are invalid, this method will refresh them. If the credentials are
        still invalid after refreshing, this method will raise an error.

        Returns:
            google.auth.credentials.Credentials: The GCP credentials.

        Raises:
            LaunchError: If the GCP credentials are invalid.
        zGetting GCP credentialsNzRefreshing GCP credentialszNo Google Cloud Platform credentials found. Please run `gcloud auth application-default login` or set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the path of a valid service account key file.zCould not refresh Google Cloud Platform credentials. Please run `gcloud auth application-default login` or set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the path of a valid service account key file.zInvalid Google Cloud Platform credentials. Please run `gcloud auth application-default login` or set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the path of a valid service account key file.)r   debugr   r
   authdefaultr   refresh	transportrequestsRequest
exceptionsDefaultCredentialsErrorr   RefreshErrorvalid)r   google_auth_defaultcredsr(   er   r   r   get_credentials   s>   

zGcpEnvironment.get_credentialsc                   s   t d |  I dH  dS )a@  Verify the credentials, region, and project.

        Credentials and region are verified by calling get_credentials(). The
        region and is verified by calling the compute API.

        Raises:
            LaunchError: If the credentials, region, or project are invalid.

        Returns:
            None
        zVerifying GCP environmentN)r   r*   r8   r'   r   r   r   verify   s   
zGcpEnvironment.verifyuric              
     s   t |}|std| |d}ttjjj}z| 	 I dH }||dI dH }t|j
|I dH }W dS  tjjjyR } ztd| d| d|d}~w tjjjyl } ztd| d| d|d}~ww )	zVerify that a storage URI is valid.

        Arguments:
            uri: The storage URI.

        Raises:
            LaunchError: If the storage URI is invalid.
        zInvalid GCS URI: r   NcredentialszFailed verifying storage uri z	: bucket  does not exist.z@ is not accessible. Please check your permissions and try again.)r   matchr   groupr   r
   cloudstorageClientr8   
get_bucketapi_corer1   GoogleAPICallError	Forbidden)r   r:   r>   bucketcloud_storage_clientr<   storage_clientr7   r   r   r   verify_storage_uri   s2   
	
z!GcpEnvironment.verify_storage_urisourcedestinationc                   sf  t d| d|  d| d| }tj|s$t| d| dt|}|s4t| d| |d}|d		d
}t
tjjj}|  I dH }z)||dI dH }	t
|	j|I dH }t
|j|I dH }
t
|
j|I dH  W dS  tjjjy } z+|j}|dusJ z
| d d }W n ty   t|}Y nw t| d| |d}~ww )zUpload a file to GCS.

        Arguments:
            source: The path to the local file.
            destination: The path to the GCS file.

        Raises:
            LaunchError: If the file cannot be uploaded.
        zUploading file  to zCould not upload file  to GCS destination z: File r=   : Invalid GCS URI: r   r   /Nr;   errormessage: )r   r*   ospathisfiler   r   r>   r?   lstripr   r
   r@   rA   rB   r8   rG   blobupload_from_filenamerD   r1   rE   responsejson	Exceptionr   )r   rK   rL   _err_prefixr>   rG   keygoogle_storage_clientr<   rI   rX   r7   resprR   r   r   r   upload_file   s8   


zGcpEnvironment.upload_filec                   s  t d| d|  d| d| }tj|s$t| d| dt|}|s4t| d| |d}|d		d
}t
tjjj}|  I dH }zP||dI dH }	t
|	j|I dH }t|D ]5\}
}}|D ]-}tj|
|}tj|tj||dd
}t
|j|I dH }t
|j|I dH  qnqgW dS  tjjjy } z+|j}|dusJ z
| d d }W n ty   t|}Y nw t| d| |d}~w ty } z
t| d| |d}~ww )zUpload a directory to GCS.

        Arguments:
            source: The path to the local directory.
            destination: The path to the GCS directory.

        Raises:
            LaunchError: If the directory cannot be uploaded.
        zUploading directory rM   zCould not upload directory rN   z: Directory r=   rO   r   r   rP   Nr;   \rQ   rR   rS   z: GCS upload failed: )r   r*   rT   rU   isdirr   r   r>   r?   rW   r   r
   r@   rA   rB   r8   rG   walkjoinrelpathreplacerX   rY   rD   r1   rE   rZ   r[   r\   r   )r   rK   rL   r]   r>   rG   r^   r_   r<   rI   root_filesfile
local_pathgcs_pathrX   r7   r`   rR   r   r   r   
upload_dir  sT   


zGcpEnvironment.upload_dir)r   r   r   r   )r   r   r   r   )r   r   )r   r   )r   r)   )r   r   )r:   r   r   r   )rK   r   rL   r   r   r   )__name__
__module____qualname____doc____annotations__r   classmethodr$   r&   propertyr(   r8   r9   rJ   ra   rn   __classcell__r   r   r   r   r   4   s   
 

/

#r   config_namer   r   
str | Nonec                 C  sZ   z!t jddd| gt jd}t|d }|rd|vr|W S W dS  t jy,   Y dS w )zGet a value from gcloud config.

    Arguments:
        config_name: The name of the config value.

    Returns:
        str: The config value, or None if the value is not set.
    gcloudr   z	get-value)stderrzutf-8unsetN)
subprocesscheck_outputSTDOUTr   decodestripCalledProcessError)rw   outputvaluer   r   r   get_gcloud_config_value1  s   	r   c                  C  s   t d} | stjt} | S )zGet the default region from gcloud config or environment variables.

    Returns:
        str: The default region, or None if it cannot be determined.
    zcompute/region)r   rT   environr"   GCP_REGION_ENV_VARr!   r   r   r   r%   F  s   r%   )rw   r   r   rx   )r   rx   ) rr   
__future__r   loggingrT   r|   wandb.sdk.launch.errorsr   
wandb.utilr   utilsr   r   abstractr	   r
   r@   
compute_v1r+   r<   r.   r/   rD   r1   rA   	getLoggerro   r   r   r   r   r%   r   r   r   r   <module>   sN    




 
~