o
    xi0                     @  s   d Z ddlm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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.    )annotationsN)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& fd	d
Zed'd(ddZed)ddZed*ddZ	e	j
d+ddZ	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 )0AwsEnvironmentzAWS environment.regionstr
access_key
secret_keysession_tokenreturnNonec                   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__ `/home/ubuntu/.local/lib/python3.10/site-packages/wandb/sdk/launch/environment/aws_environment.pyr      s   

zAwsEnvironment.__init__N
str | Nonec              
   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_default7   s<   



zAwsEnvironment.from_defaultconfigdict[str, str]c                 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   )r   r,   r   r5   )r1   r6   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   v   s   zAwsEnvironment.regionc                 C  s
   || _ d S Nr:   )r!   r   r$   r$   r%   r   {   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   
exceptionsr0   )	r!   r2   r/   r?   identityarnmatched_partition	partitionr4   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   rB   r0   r   )r!   r2   r/   r?   r4   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   rI   r   r   r   r(   r   r   r   r   rB   r0   r   )r!   r2   r4   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   /r8   Ns3$: botocore error attempting to copy . )r   rI   r*   pathisfiler   r   r@   rA   lstripr>   r   r/   upload_filer   rB   r0   )
r!   rP   rQ   _err_prefixr@   bucketkeyr2   r/   r4   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.
        rR   rS   rT   r   rU   rV   rW   rX   r	   r   rY   r8   NrZ   \r[   r\   z&: Unexpected error attempting to copy )r   rI   r*   r]   isdirr   r   r@   rA   r_   r>   r   r/   walkjoinreplacer`   r   rB   r0   	Exception)r!   rP   rQ   ra   r@   rb   rc   r2   r/   r]   _filesfileabs_pathkey_pathr4   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: rX   r	   NrZ   )BucketErrorCode404z!Could not verify AWS storage uri z	. Bucket rV   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   rI   r   r@   r   rA   r>   r   r/   head_bucketr   rB   r0   response)r!   rp   r@   rb   r2   r/   r4   r$   r$   r%   verify_storage_uri  s4   



z!AwsEnvironment.verify_storage_uri)
r   r   r   r   r   r   r   r   r   r   r;   )r   r&   r   r   )r6   r7   r   r   )r   r   )r   r   r   r   )r   r   )r   rK   )rP   r   rQ   r   r   r   )rp   r   r   r   )__name__
__module____qualname____doc__r   classmethodr5   r9   propertyr   setterrG   rJ   r>   r`   ro   rx   __classcell__r$   r$   r"   r%   r      s"    '




(5r   )r|   
__future__r   loggingr*   wandb.sdk.launch.errorsr   
wandb.utilr   utilsr   r   r   abstractr
   r   r   	getLoggerry   r   r   r$   r$   r$   r%   <module>   s$    
