o
    -wi0                     @   s   d Z ddlZddlZddlmZmZ ddlmZ ddlm	Z	 ddl
mZmZmZ dd	lmZ e	d
ddZe	dddZeeZG dd deZdS )zImplements the AWS environment.    N)DictOptional)LaunchError)
get_module   )ARN_PARTITION_RE	S3_URI_REevent_loop_thread_exec   )AbstractEnvironmentboto3zcAWS environment requires boto3 to be installed. Please install it with `pip install wandb[launch]`.)requiredbotocorezfAWS environment requires botocore to be installed. Please install it with `pip install wandb[launch]`.c                
       s   e Zd ZdZdededededdf
 fdd	Zed"dee dd fd
dZede	eef dd fddZ
edefddZejdeddfddZdefddZd#ddZd$ddZdededdfddZdededdfddZdeddfd d!Z  ZS )%AwsEnvironmentzAWS environment.region
access_key
secret_keysession_tokenreturnNc                    sD   t    td| d || _|| _|| _|| _d| _d| _	dS )zInitialize the AWS environment.

        Arguments:
            region (str): The AWS region.

        Raises:
            LaunchError: If the AWS environment is not configured correctly.
        z'Initializing AWS environment in region .N)
super__init___loggerinfo_region_access_key_secret_key_session_token_account
_partition)selfr   r   r   r   	__class__ i/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/wandb/sdk/launch/environment/aws_environment.pyr      s   

zAwsEnvironment.__init__c              
   C   s   t d z+t }t|dr|p|j}|ptjd}|	 }|s&t
d|j}|j}|j}W n tjjyE } zt
d| d}~ww |sLt
d| ||||dS )	a-  Create an AWS environment from the default AWS environment.

        Arguments:
            region (str, optional): The AWS region.
            verify (bool, optional): Whether to verify the AWS environment. Defaults to True.

        Returns:
            AwsEnvironment: The AWS environment.
        z2Creating AWS environment from default credentials.r   
AWS_REGIONz|Could not create AWS environment from default environment. Please verify that your AWS credentials are configured correctly.z}Could not create AWS environment from default environment. Please verify that your AWS credentials are configured correctly. NzPCould not create AWS environment from default environment. Region not specified.)r   r   r   r   )r   r   r   Sessionhasattrr   osenvirongetget_credentialsr   r   r   tokenr   clientClientError)clsr   sessioncredentialsr   r   r   er#   r#   r$   from_default6   s<   



zAwsEnvironment.from_defaultconfigc                 C   s(   t |dd}|std| j|dS )a.  Create an AWS environment from the default AWS environment.

        Arguments:
            config (dict): Configuration dictionary.
            verify (bool, optional): Whether to verify the AWS environment. Defaults to True.

        Returns:
            AwsEnvironment: The AWS environment.
        r    zCCould not create AWS environment from config. Region not specified.)r   )strr*   r   r3   )r/   r4   r   r#   r#   r$   from_config^   s   zAwsEnvironment.from_configc                 C   s   | j S )zThe AWS region.r   )r    r#   r#   r$   r   u   s   zAwsEnvironment.regionc                 C   s
   || _ d S Nr8   )r    r   r#   r#   r$   r   z   s   
c           	   
      s   z>|   I dH }t|jdI dH }t|j}| I dH }|d}|s)tdt|}|s8td| d|d}|W S  t	j
jyU } ztd| |d}~ww )	z*Set the partition for the AWS environment.NstsArnz;Could not set partition for AWS environment. ARN not found.z1Could not set partition for AWS environment. ARN z is not valid.r
   z-Could not set partition for AWS environment. )get_sessionr	   r-   get_caller_identityr*   r   r   matchgroupr   
exceptionsr.   )	r    r0   r-   r=   identityarnmatched_partition	partitionr2   r#   r#   r$   get_partition~   s4   




zAwsEnvironment.get_partitionc              
      s   t d z#|  I dH }t|jdI dH }t|j}| I dH d| _W dS  tj	j
y? } ztd| |d}~ww )zVerify that the AWS environment is configured correctly.

        Raises:
            LaunchError: If the AWS environment is not configured correctly.
        zVerifying AWS environment.Nr:   AccountzdCould not verify AWS environment. Please verify that your AWS credentials are configured correctly. )r   debugr<   r	   r-   r=   r*   r   r   r@   r.   r   )r    r0   r-   r=   r2   r#   r#   r$   verify   s   

zAwsEnvironment.verifyboto3.Sessionc              
      sj   t d| j  zttj}|| j| j| j| jdI dH W S  t	j
jy4 } ztd| d}~ww )zGet an AWS session.

        Returns:
            boto3.Session: The AWS session.

        Raises:
            LaunchError: If the AWS session could not be created.
        zCreating AWS session in region )region_nameaws_access_key_idaws_secret_access_keyaws_session_tokenNzCould not create AWS session. )r   rG   r   r	   r   r&   r   r   r   r   r@   r.   r   )r    r0   r2   r#   r#   r$   r<      s   	
zAwsEnvironment.get_sessionsourcedestinationc           
         s   t d| d|  d| d| d}tj|s%t| d| dt|}|s6t| d| d|d	}|d
	d}|sGd}| 
 I dH }zt|jdI dH }|||| W dS  tjjy }	 zt| d| d| d|	 d}	~	ww )a  Upload a file to s3 from local storage.

        The destination is a valid s3 URI, e.g. s3://bucket/key and will
        be used as a prefix for the uploaded file.  Only the filename of the source
        is kept in the upload key.  So if the source is "foo/bar" and the
        destination is "s3://bucket/key", the file "foo/bar" will be uploaded
        to "s3://bucket/key/bar".

        Arguments:
            source (str): The path to the file or directory.
            destination (str): The uri of the storage destination. This should
                be a valid s3 URI, e.g. s3://bucket/key.

        Raises:
            LaunchError: If the copy fails, the source path does not exist, or the
                destination is not a valid s3 URI, or the upload fails.
        
Uploading  to Error attempting to copy r   	: Source  does not exist.: Destination  is not a valid s3 URI.r
   r   /r5   Ns3$: botocore error attempting to copy . )r   rG   r(   pathisfiler   r   r>   r?   lstripr<   r	   r-   upload_filer   r@   r.   )
r    rN   rO   _err_prefixr>   bucketkeyr0   r-   r2   r#   r#   r$   r^      s0   

zAwsEnvironment.upload_filec                    s  t d| d|  d| d| d}tj|s%t| d| dt|}|s6t| d| d|d	}|d
	d}|sGd}| 
 I dH }z8t|jdI dH }t|D ]%\}	}
}|D ]}tj|	|}||ddd	d}|||| qeq^W dS  tjjy } zt| d| d| d| |d}~w ty } zt| d| d| d| |d}~ww )a  Upload a directory to s3 from local storage.

        The upload will place the contents of the source directory in the destination
        with the same directory structure. So if the source is "foo/bar" and the
        destination is "s3://bucket/key", the contents of "foo/bar" will be uploaded
        to "s3://bucket/key/bar".

        Arguments:
            source (str): The path to the file or directory.
            destination (str): The URI of the storage.
            recursive (bool, optional): If True, copy the directory recursively. Defaults to False.

        Raises:
            LaunchError: If the copy fails, the source path does not exist, or the
                destination is not a valid s3 URI.
        rP   rQ   rR   r   rS   rT   rU   rV   r
   r   rW   r5   NrX   \rY   rZ   z&: Unexpected error attempting to copy )r   rG   r(   r[   isdirr   r   r>   r?   r]   r<   r	   r-   walkjoinreplacer^   r   r@   r.   	Exception)r    rN   rO   r_   r>   r`   ra   r0   r-   r[   _filesfileabs_pathkey_pathr2   r#   r#   r$   
upload_dir   sX   

zAwsEnvironment.upload_diruric              
      s   t d|  t|}|std| d|d}z|  I dH }t|jdI dH }|j	|d W dS  t
jjyv } z1|jd d	 d
krUtd| d| d|jd d	 dkrftd| dtd| d|j dd}~ww )a  Verify that s3 storage is configured correctly.

        This will check that the bucket exists and that the credentials are
        configured correctly.

        Arguments:
            uri (str): The URI of the storage.

        Raises:
            LaunchError: If the storage is not configured correctly or the URI is
                not a valid s3 URI.

        Returns:
            None
        zVerifying storage z Failed to validate storage uri: rV   r
   NrX   )BucketErrorCode404z!Could not verify AWS storage uri z	. Bucket rT   403zy. Bucket {bucket} is not accessible. Please check that this client is authenticated with permission to access the bucket.z!Failed to verify AWS storage uri z. Response: zB Please verify that your AWS credentials are configured correctly.)r   rG   r   r>   r   r?   r<   r	   r-   head_bucketr   r@   r.   response)r    rn   r>   r`   r0   r-   r2   r#   r#   r$   verify_storage_uri  s4   



z!AwsEnvironment.verify_storage_urir9   )r   N)r   rI   )__name__
__module____qualname____doc__r6   r   classmethodr   r3   r   r7   propertyr   setterrE   rH   r<   r^   rm   rv   __classcell__r#   r#   r!   r$   r      s>    '


(5r   )rz   loggingr(   typingr   r   wandb.sdk.launch.errorsr   
wandb.utilr   utilsr   r   r	   abstractr   r   r   	getLoggerrw   r   r   r#   r#   r#   r$   <module>   s$    
