
    	2                       d Z ddlmZ ddlmZ ddlmZ ddlm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  ej                  d
      Z ej                  d      Z G d dej$                        Z G d dej$                        Z G d dej$                        Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      Z G d dee	j6                        Z G d dee      Z G d  d!ee      Z G d" d#ee      Z G d$ d%e	j@                        Z! G d& d'ee	j6                        Z"	 d*d(Z#	 d*d)Z$y)+z;API interface for interacting with cloud storage providers.    )absolute_import)annotations)division)unicode_literalsN)
exceptions)resource)urllibz(b/(?P<bucket>.*)/o/(?P<object>.*?)(\?|$)z`^b/(?P<bucket>[a-z0-9\-_\.]+)(/)?(iam|channels|lockRetentionPolicy|iam/testPermissions|o)?(\?|$)c                      e Zd Zy)CloudApiErrorN__name__
__module____qualname__     ,lib/googlecloudsdk/api_lib/storage/errors.pyr   r   /       r   r   c                      e Zd Zy)InsightApiErrorNr   r   r   r   r   r   3   r   r   r   c                      e Zd Zy)StorageBatchOperationsApiErrorNr   r   r   r   r   r   7   r   r   r   c                      e Zd ZdZy)RetryableApiErrorz3Error raised to indicate a transient network error.Nr   r   r   __doc__r   r   r   r   r   ;   s    ;r   r   c                      e Zd ZdZy)NotFoundErrorzError raised when the requested resource does not exist.

  Both GCS and S3 APIs should raise this error if a resource
  does not exist so that the caller can handle the error in an API agnostic
  manner.
  Nr   r   r   r   r   r   @   s     r   r   c                      e Zd ZdZy)PreconditionFailedError,Raised when a precondition is not satisfied.Nr   r   r   r   r   r   J       4r   r   c                      e Zd ZdZy)ConflictErrorDRaised when a resource cannot be created because one already exists.Nr   r   r   r   r#   r#   N       Lr   r#   c                      e Zd ZdZy)ResumableUploadAbortErrorz5Raised when a resumable upload needs to be restarted.Nr   r   r   r   r'   r'   R   s    =r   r'   c                  "    e Zd ZdZedd       Zy)GcsApiErrorzBase class for GCS API errors.c                    t        | d      r%| j                  r	 t        | j                  dd      S yy# t        $ r Y yw xY w)zEReturns the status code of the error, or None if it is not available.errorstatus_codeN)hasattrr+   getattrKeyError)selfs    r   r,   zGcsApiError.status_codeZ   sH     tW$**tzz=$77	 #-
  s   3 	??N)returnz
int | None)r   r   r   r   propertyr,   r   r   r   r)   r)   W   s    & r   r)   c                  .     e Zd ZdZ fdZd Zd Z xZS )GcsNotFoundErrorzwError raised when the requested GCS resource does not exist.

  Implements custom formatting to avoid messy default.
  c                @   ~~t         t        |   |d       |j                  sy d}t	        j
                  |j                        \  }}}t        j                  |      }|r| j                  ||       y t        j                  |      }|r| j                  ||       y y )Nz)HTTPError {status_code}: {status_message})error_formatz.gs://{instance_name} not found: {status_code}.)superr4   __init__urlr   SplitEndpointUrlOBJECT_RESOURCE_PATH_PATTERNsearch_custom_format_object_errorBUCKET_RESOURCE_PATH_PATTERN_custom_format_bucket_error)
r0   r+   argskwargs+custom_error_format_for_buckets_and_objects_resource_pathmatch_object_resource_pathmatch_bucket_resource_path	__class__s
            r   r8   zGcsNotFoundError.__init__l   s    f	
D* A + 	B 99 	9 0 #33EII>Aq-!=!D!D"!
&&
$
57 !=!D!D"!
&&
$
57 "r   c                R    || _         |j                  d      | j                  _        y)a*  Sets custom error formatting for buckets resource paths.

    Args:
      match_bucket_resource_path (re.Match): Match object that contains the
        result of searching regex BUCKET_RESOURCE_PATH_PATTERN in a resource
        path.
      error_format (str): Custom error format for buckets.
    bucketN)r6   grouppayloadinstance_name)r0   rF   r6   s      r   r?   z,GcsNotFoundError._custom_format_bucket_error   s#     %D!;!A!A(!KDLLr   c                   |j                   }t        j                  j                  |      }d|v rd|d   d   z   }nd}|| _        dj                  |j                  d      |j                  d      |      | j                  _        y)	a)  Sets custom error formatting for object resource paths.

    Args:
      match_object_resource_path (re.Match): Match object
        that contains the result of searching regex OBJECT_RESOURCE_PATH_PATTERN
        in a resource path.
      error_format (str): Custom error format for objects.
    
generation#r    z{}/{}{}rI   objectN)	stringr	   parseparse_qsr6   formatrJ   rK   rL   )r0   rE   r6   rD   paramsgeneration_strings         r   r=   z,GcsNotFoundError._custom_format_object_error   s     /55M\\""=1Fv| 4Q 77 $D!*!1!1"((2"((24E"GDLLr   )r   r   r   r   r8   r?   r=   __classcell__rG   s   @r   r4   r4   f   s    
"7HLGr   r4   c                      e Zd ZdZy)GcsPreconditionFailedErrorr    Nr   r   r   r   r[   r[      r!   r   r[   c                      e Zd ZdZy)GcsConflictErrorr$   Nr   r   r   r   r]   r]      r%   r   r]   c                  "     e Zd ZdZ fdZ xZS )S3ErrorPayloada^  Allows using format strings to create strings from botocore ClientErrors.

  Format strings of the form '{field_name}' will be populated from class
  attributes. Strings of the form '{.field_name}' will be populated from the
  self.content JSON dump. See api_lib.util.HttpErrorPayload for more detail and
  sample usage.

  Attributes:
    content (dict): The dumped JSON content.
    message (str): The human readable error message.
    status_code (int): The HTTP status code number.
    status_description (str): The status_code description.
    status_message (str): Context specific status message.
  c                   t         t        |   |       t        |      | _        t        |d      r|j                  | _        d|j                  v r$|j                  d   j                  dd      | _	        d|j                  v r=|j                  d   }|j                  dd      | _
        |j                  dd      | _        | j                         | _        y	y	)
zInitializes an S3ErrorPayload instance.

    Args:
      client_error (Union[botocore.exceptions.ClientError, str]): The error
        thrown by botocore, or a string that will be displayed as the error
        message.
    responseResponseMetadataHttpStatusCoder   ErrorCoderP   MessageN)r7   r_   r8   strbotocore_error_stringr-   ra   contentgetr,   status_descriptionstatus_message_MakeGenericMessagemessage)r0   client_errorr+   rG   s      r   r8   zS3ErrorPayload.__init__   s     
.$(6 "%\!2D|Z(!**dl	|44	4'001CDHHa!	L))	)%%g."'))FB"7#ii	26--/dl )r   r   r   r   r   r8   rX   rY   s   @r   r_   r_      s    0 0r   r_   c                  $     e Zd ZdZd fd	Z xZS )XmlApiErrorzTranslates a botocore ClientError and allows formatting.

  Attributes:
    error: The original ClientError.
    error_format: An S3ErrorPayload format string.
    payload: The S3ErrorPayload object.
  c                :    t         t        |   ||t               y )N)r6   payload_class)r7   rr   r8   r_   )r0   r+   r6   rG   s      r   r8   zXmlApiError.__init__   s    	+t%L & Hr   )z{botocore_error_string}rp   rY   s   @r   rr   rr      s    H Hr   rr   c                t    |d }|D ]-  \  }}}t        | |      s|| ||       |k(  s$ || |      c S  | S )a  Translates error or returns original error if no matches.

  Note, an error will be translated if it is a child class of a value in
  translation_list. Also, translations earlier in the list take priority.

  Args:
    error (Exception): Error to translate.
    translation_list (list): List of (Exception, int|None, Exception) tuples.
      Translates errors that are instances of first error type to second if the
      status code of the first exception matches the integer value. If the
      status code argument is None, the entry will translate errors of any
      status code.
    format_str (str|None): An api_lib.util.exceptions.FormattableErrorPayload
      format string. Note that any properties that are accessed here are on the
      FormattableErrorPayload object, not the object returned from the server.
    status_code_getter (Exception -> int|None): Function that gets a status code
      from the exception type raised by the underlying client, e.g.
      apitools_exceptions.HttpError. If None, only entries with a null status
      code in `translation_list` will translate errors.

  Returns:
    Error (Exception). Translated if match. Else, original error.
  c                     y )Nr   )rC   s    r   <lambda>z!translate_error.<locals>.<lambda>  s    4r   )
isinstance)r+   translation_list
format_strstatus_code_getteruntranslated_erroruntranslated_status_codetranslated_errors          r   translate_errorr      sa    4 ' 	%+, (%e$(@@eZ00  
,r   c                      fd}|S )a  Decorator catches an error and raises CloudApiError with a custom message.

  Args:
    translation_list (list): List of (Exception, int|None, Exception) tuples.
      Translates errors that are instances of first error type to second if the
      status code of the first exception matches the integer value. If the
      status code argument is None, the entry will translate errors of any
      status code.
    format_str (str|None): An api_lib.util.exceptions.FormattableErrorPayload
      format string. Note that any properties that are accessed here are on the
      FormattableErrorPayload object, not the object returned from the server.
    status_code_getter (Exception -> int|None): Function that gets a status code
      from the exception type raised by the underlying client, e.g.
      apitools_exceptions.HttpError. If None, only entries with a null status
      code in `translation_list` will translate errors.

  Returns:
    A decorator that catches errors and raises a CloudApiError with a
      customizable error message.

  Example:
    @catch_error_raise_cloud_api_error(
        [(apitools_exceptions.HttpError, GcsApiError)],
        'Error [{status_code}]')
    def some_func_that_might_throw_an_error():
  c                      fd}|S )Nc            	         	  | i |S # t         $ r,}t        j                  t        |             Y d }~y d }~ww xY w)N)rz   r{   )	Exceptioncore_exceptionsreraiser   )r@   rA   erz   functionr{   ry   s      r   wrapperzYcatch_error_raise_cloud_api_error.<locals>.translate_api_error_decorator.<locals>.wrapperE  sO    
((( 	
 %#5		
 	
	
s    	A ";A r   )r   r   rz   r{   ry   s   ` r   translate_api_error_decoratorzHcatch_error_raise_cloud_api_error.<locals>.translate_api_error_decoratorB  s    
 Nr   r   )ry   rz   r{   r   s   ``` r   !catch_error_raise_cloud_api_errorr   %  s    :( 
'&r   )NN)%r   
__future__r   r   r   r   regooglecloudsdk.api_lib.utilr   api_exceptionsr   googlecloudsdk.corer   	six.movesr	   compiler;   r>   rd   r   r   r   r   r   r   r#   r'   HttpExceptionr)   r4   r[   r]   FormattableErrorPayloadr_   rr   r   r   r   r   r   <module>r      sN   B & "  ' 	 D 0 = 
  *rzz/ 1   *rzz% & 
O)) o++ _%:%:  
M 5m 5MM M 
-!=!= NG{M NGb5.E 5M{M M%0^;; %0PH-!=!= H( BF(X ;?1'r   