
    )                        d 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
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 dd
lmZ ddlmZ ddlZdZdez  dz  Zd Zd Z G d dej2                        Z G d dej2                        Z G d dej2                        Z G d de
j:                        Z G d de      Z d Z!d Z" G d dejF                        Z$ G d de$      Z%d  Z&d! Z'd" Z(	 	 	 	 	 d$d#Z)y)%zNUtilities for working with long running operations go/long-running-operation.
    )absolute_import)division)unicode_literalsN)encoding)
exceptions)requests)waiter)log)	resources   <   c                     	  | |i |S # t         j                  $ r(}t        t        j                  |             Y d}~yd}~wt
        t        t        j                  f$ r}t        |       Y d}~yd}~ww xY w)a  Wrapper for method(...) which re-raises operation-style errors.

  Args:
    method: Original method to call.
    *args: Positional arguments to method.
    **kwargs: Keyword arguments to method.

  Raises:
    MiscOperationError: If the method call itself raises one of the exceptions
      listed below. Otherwise, the original exception is raised. Preserves
      stack trace. Re-uses the error string from original error or in the case
      of HttpError, we synthesize human-friendly string from HttpException.
      However, HttpException is neither raised nor part of the stack trace.

  Returns:
    Result of calling method(*args, **kwargs).
  N)	apitools_exceptions	HttpError_ReraiseMiscOperationErrorapi_exceptionsHttpExceptionOperationErrorOperationTimeoutErrorapp_exceptionsError)methodargskwargshttp_errerrs        1lib/googlecloudsdk/api_lib/app/operations_util.pyCallAndCollectOpErrorsr   ,   sf    $$4"6""		&	& G~;;HEFF
/1E1E	F $s##$s    
 A6A  !A6!A11A6c                 f    t        j                  t        t        j                  |                    y)z$Transform and re-raise error helper.N)r   reraiseMiscOperationErrorsix	text_type)r   s    r   r   r   G   s    'c(:;<    c                       e Zd ZdZy)r!   z;Wrapper exception for errors treated as operation failures.N)__name__
__module____qualname____doc__ r$   r   r!   r!   L   s    Cr$   r!   c                       e Zd Zy)r   Nr&   r'   r(   r*   r$   r   r   r   P       r$   r   c                       e Zd Zy)r   Nr,   r*   r$   r   r   r   T   r-   r$   r   c                       e Zd ZdZdZdZy)Status         N)r&   r'   r(   PENDING	COMPLETEDERRORr*   r$   r   r0   r0   X   s    ')
%r$   r0   c                       e Zd ZdZd Zd Zy)	OperationaR  Wrapper around Operation response objects for console output.

  Attributes:
    project: String, name of the project.
    id: String, ID of operation.
    start_time: String, time the operation started.
    status: Status enum, either PENDING, COMPLETED, or Error.
    op_resource: messages.Operation, the original Operation resource.
  c                     t         j                  j                  |j                  d      }|j                  | _        |j                         | _        t        |      | _	        t        |      | _        || _        y)z%Creates the operation wrapper object.appengine.apps.operationsN)r   REGISTRYParseRelativeNamenameappsIdprojectNameid_GetInsertTime
start_time	GetStatusstatusop_resource)selfop_responseress      r   __init__zOperation.__init__i   s\    



.
.{/?/?/JLC::DLhhjDG$[1DOK(DK"Dr$   c                 0   t        |t              xr | j                  |j                  k(  xrj | j                  |j                  k(  xrO | j                  |j                  k(  xr4 | j
                  |j
                  k(  xr | j                  |j                  k(  S N)
isinstancer8   r?   rA   rC   rE   rF   )rG   others     r   __eq__zOperation.__eq__s   s    ui( 2LLEMM)2GGuxx2 OOu///2 KK5<<'	2
  1 113r$   N)r&   r'   r(   r)   rJ   rO   r*   r$   r   r8   r8   ^   s    #3r$   r8   c                     | j                   st        j                  j                  S | j                  rt        j
                  j                  S t        j                  j                  S )zReturns string status for given operation.

  Args:
    operation: A messages.Operation instance.

  Returns:
    The status of the operation in string form.
  )doner0   r4   r=   errorr6   r5   )	operations    r   rD   rD   |   sD     
>><<   r$   c                     | j                   sy| j                   j                  }|D ])  }|j                  dk(  s|j                  j                  c S  y)zFinds the insertTime property and return its string form.

  Args:
    operation: A messages.Operation instance.

  Returns:
    The time the operation started in string form or None if N/A.
  N
insertTime)metadataadditionalPropertieskeyvaluestring_value)rS   
propertiesprops      r   rB   rB      sG     
		!!66*dxx<ZZ$$$ r$   c                   0    e Zd ZdZddZd Zd Zd Zd Zy)	AppEngineOperationPollerz"A poller for appengine operations.Nc                 >    || _         || _        t               | _        yaT  Sets up poller for appengine operations.

    Args:
      operation_service: apitools.base.py.base_api.BaseApiService, api service
        for retrieving information about ongoing operation.
      operation_metadata_type: Message class for the Operation metadata (for
        instance, OperationMetadataV1, or OperationMetadataV1Beta).
    N)operation_serviceoperation_metadata_typesetwarnings_seen)rG   ra   rb   s      r   rJ   z!AppEngineOperationPoller.__init__   s     /D#:D Dr$   c           
         | j                  |       |j                  rt        j                  dj	                  |j
                  t        j                  t        j                  |      d                   |j                  r;t        t        j                  t        j                  |j                                    yt        j                  dj	                  |j
                               y)z
Overrides.z%Operation [{0}] complete. Result: {1}   )indentTz/Operation [{0}] not complete. Waiting to retry.F)_LogNewWarningsrQ   r
   debugformatr=   jsondumpsr   MessageToDictrR   r   r   ExtractErrorMessageMessageToPyValuerG   rS   s     r   IsDonezAppEngineOperationPoller.IsDone   s    #~~	ii7>>
..
**X++I6q
AC D 
X99%%ioo68 9 	9II?FF r$   c                     | j                   j                  d      } ||j                               }| j                   j                  |      }| j	                  |       |S )zOverrides.

    Args:
      operation_ref: googlecloudsdk.core.resources.Resource.

    Returns:
      fetched operation message.
    Get)r=   )ra   GetRequestTypeRelativeNamers   rh   )rG   operation_refrequest_typerequestrS   s        r   PollzAppEngineOperationPoller.Poll   sW     ))88?L : : <=G&&**73I#r$   c                     | j                   r^t        || j                         | j                  z
  }|D ]5  }t        j                  |dz          | j                  j                  |       7 y y )N
)rb   GetWarningsFromOperationrd   r
   warningadd)rG   rS   new_warningsr}   s       r   rh   z(AppEngineOperationPoller._LogNewWarnings   sb    ##-
T113595G5GHl!'GdN#w' "	 $r$   c                     |S )zSimply returns the operation.

    Args:
      operation: api_name_messages.Operation.

    Returns:
      the 'response' field of the Operation.
    r*   rp   s     r   	GetResultz"AppEngineOperationPoller.GetResult   s
     r$   rL   )	r&   r'   r(   r)   rJ   rq   ry   rh   r   r*   r$   r   r^   r^      s    *(	r$   r^   c                   ,     e Zd ZdZ fdZ fdZ xZS )AppEngineOperationBuildPollerz@Waits for a build to be present, or for the operation to finish.c                 .    t         t        |   ||       yr`   )superr   rJ   )rG   ra   rb   	__class__s      r   rJ   z&AppEngineOperationBuildPoller.__init__   s     

'78I8OQr$   c                 X    t        || j                        ryt        t        |   |      S )NT)GetBuildFromOperationrb   r   r   rq   )rG   rS   r   s     r   rq   z$AppEngineOperationBuildPoller.IsDone   s)    Y(D(DE.<YGGr$   )r&   r'   r(   r)   rJ   rq   __classcell__)r   s   @r   r   r      s    H
QH Hr$   r   c                     | j                   sy t        j                  |t        j                  | j                               S rL   )rV   r   JsonToMessageMessageToJson)rS   rb   s     r   GetMetadataFromOperationr      s8    						Y//0
2 2r$   c                 d    t        | |      }|r|j                  sy |j                  j                  S rL   )r   createVersionMetadatacloudBuildIdrS   rb   rV   s      r   r   r      s/    %i1HI(	77		'	'	4	44r$   c                 j    t        | |      }|s
t               S t        d |j                  D              S )Nc              3       K   | ]  }|  y wrL   r*   ).0r}   s     r   	<genexpr>z+GetWarningsFromOperation.<locals>.<genexpr>	  s     5$4W$4s   )r   rc   r}   r   s      r   r|   r|     s0    %i1HI(	5L	5H$4$45	55r$   c           	         |xs t        |       }|j                  |      r|j                  |      S t        j                  j                  |j                  |      }|	t        dz
  }|t        }|dj                  |j                               }|dz  }	 t        j                  |||d|d|      }|S # t        j                  $ r% t        dj                  |j                              w xY w)a  Wait until the operation is complete or times out.

  Args:
    operation_service: The apitools service type for operations
    operation: The operation resource to wait on
    max_retries: Maximum number of times to poll the operation
    retry_interval: Frequency of polling in seconds
    operation_collection: The resource collection of the operation.
    message: str, the message to display while progress tracker displays.
    poller: AppEngineOperationPoller to poll with, defaulting to done.
  Returns:
    The operation resource when it has completed
  Raises:
    OperationError: if the operation contains an error.
    OperationTimeoutError: when the operation polling times out

  r1   z&Waiting for operation [{}] to completei  g      ?)pre_start_sleep_msmax_retrialsexponential_sleep_multipliersleep_msz@Operation [{0}] timed out. This operation may still be underway.)r^   rq   r   r   r;   r<   r=   DEFAULT_OPERATION_MAX_TRIES DEFAULT_OPERATION_RETRY_INTERVALrj   ru   r	   WaitForTimeoutErrorr   )	ra   rS   max_retriesretry_intervaloperation_collectionmessagepollerrv   completed_operations	            r   WaitForOperationr     s   . @-.?@&]]9I&&$$66nn- -1K5N_6==""$&G D.6 .. %(! 
	 
		 6
 ":;A6%.^^<56 66s   B4 48C,)NNr:   NN)*r)   
__future__r   r   r   rk   apitools.base.pyr   r   r   enumgooglecloudsdk.api_lib.appr   googlecloudsdk.api_lib.utilr   r   r	   googlecloudsdk.corer
   r   r"   r   r   r   r   r   r!   r   r   Enumr0   objectr8   rD   rB   OperationPollerr^   r   r   r   r|   r   r*   r$   r   <module>r      s    '  '  % >  C D 0 . * # ) 
 $%  !%EEK $6=
D)) DZ%% J,, TYY 3 3<!"%"@v55 @FH$< H*256 "&$(*E! 3r$   