
    )                        S r SSKJr  SSKJr  SSKJr  SSKrSSKrSSKJr  SSK	J
r
  SSKJr  SS	KJr  SSKrS
r " S S\
R"                  5      r " S S\
R"                  5      r " S S\
R"                  5      r " S S\R*                  " \R,                  \5      5      r " S S\5      r " S S\5      r          SS jr       SS jrS rg)z-Utilities to support long running operations.    )absolute_import)division)unicode_literalsN)encoding)
exceptions)progress_tracker)retryzThe operations may still be underway remotely and may still succeed; use gcloud list and describe commands or https://console.developers.google.com/ to check resource state.c                       \ rS rSrSrg)TimeoutError&    N__name__
__module____qualname____firstlineno____static_attributes__r       )lib/googlecloudsdk/api_lib/util/waiter.pyr   r   &       r   r   c                       \ rS rSrSrg)AbortWaitError*   r   Nr   r   r   r   r   r   *   r   r   r   c                       \ rS rSrSrg)OperationError.   r   Nr   r   r   r   r   r   .   r   r   r   c                       \ rS rSrSr\R                  S 5       r\R                  S 5       r\R                  S 5       r	Sr
g)OperationPoller2   a  Interface for defining operation which can be polled and waited on.

This construct manages operation_ref, operation and result abstract objects.
Operation_ref is an identifier for operation which is a proxy for result
object. OperationPoller has three responsibilities:
  1. Given operation object determine if it is done.
  2. Given operation_ref fetch operation object
  3. Given operation object fetch result object
c                     g)zGiven result of Poll determines if result is done.

Args:
  operation: object representing operation returned by Poll method.

Returns:

Tr   self	operations     r   IsDoneOperationPoller.IsDone=        r   c                     g)zRetrieves operation given its reference.

Args:
  operation_ref: str, some id for operation.

Returns:
  object which represents operation.
Nr   )r"   operation_refs     r   PollOperationPoller.PollI   r&   r   c                     g)zGiven operation message retrieves result it represents.

Args:
  operation: object, representing operation returned by Poll method.
Returns:
  some object created by given operation.
Nr   r!   s     r   	GetResultOperationPoller.GetResultU   s     r   r   N)r   r   r   r   __doc__abcabstractmethodr$   r)   r,   r   r   r   r   r   r   2   sU     	 	 	 	  r   r   c                   0    \ rS rSrSrS rS rS rS rSr	g)	CloudOperationPollera   zhManages a longrunning Operations.

See https://cloud.google.com/speech/reference/rpc/google.longrunning
c                     Xl         X l        g)a  Sets up poller for cloud operations.

Args:
  result_service: apitools.base.py.base_api.BaseApiService, api service for
    retrieving created result of initiated operation.
  operation_service: apitools.base.py.base_api.BaseApiService, api service
    for retrieving information about ongoing operation.

  Note that result_service and operation_service Get request must have
  single attribute called 'name'.
N)result_serviceoperation_service)r"   r5   r6   s      r   __init__CloudOperationPoller.__init__g   s     ).r   c                     UR                   (       a1  UR                  (       a  [        UR                  R                  5      eggz
Overrides.TFdoneerrorr   messager!   s     r   r$   CloudOperationPoller.IsDonev   +    ~~	Y__4455r   c                     U R                   R                  S5      nU R                   R                  U" UR                  5       S95      $ zrOverrides.

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

Returns:
  fetched operation message.
Getname)r6   GetRequestTyperC   RelativeNamer"   r(   request_types      r   r)   CloudOperationPoller.Poll~   sD     ))88?L!!%%-44679 9r   c                     U R                   R                  S5      n[        R                  " UR                  5      nU R                   R                  U" US   S95      $ )znOverrides.

Args:
  operation: api_name_messages.Operation.

Returns:
  result of result_service.Get request.
rC   rE   rD   )r5   rF   r   MessageToPyValueresponserC   )r"   r#   rI   response_dicts       r   r,   CloudOperationPoller.GetResult   sQ     &&55e<L--i.@.@AM""<]65J#KLLr   )r6   r5   N
r   r   r   r   r.   r7   r$   r)   r,   r   r   r   r   r2   r2   a   s    
/9Mr   r2   c                   4    \ rS rSrSrS	S jrS rS rS rSr	g)
CloudOperationPollerNoResources   zManages longrunning Operations for Cloud API that creates no resources.

See https://cloud.google.com/speech/reference/rpc/google.longrunning
Nc                 2    Xl         U=(       d    S U l        g)a  Sets up poller for cloud operations.

Args:
  operation_service: apitools.base.py.base_api.BaseApiService, api service
    for retrieving information about ongoing operation.

    Note that the operation_service Get request must have a
    single attribute called 'name'.
  get_name_func: the function to use to get the name from the operation_ref.
    This is to allow polling with non-traditional operation resource names.
    If the resource name is compatible with gcloud parsing, use
    `lambda x: x.RelativeName()`.
c                 "    U R                  5       $ N)rG   )xs    r   <lambda>:CloudOperationPollerNoResources.__init__.<locals>.<lambda>   s    0@r   N)r6   get_name)r"   r6   get_name_funcs      r   r7   (CloudOperationPollerNoResources.__init__   s     /!A&@DMr   c                     UR                   (       a1  UR                  (       a  [        UR                  R                  5      eggr:   r;   r!   s     r   r$   &CloudOperationPollerNoResources.IsDone   r@   r   c                     U R                   R                  S5      nU R                   R                  U" U R                  U5      S95      $ rB   )r6   rF   rC   rZ   rH   s      r   r)   $CloudOperationPollerNoResources.Poll   sD     ))88?L!!%%$--679 9r   c                     UR                   $ )zOverrides to get the response from the completed operation.

Args:
  operation: api_name_messages.Operation.

Returns:
  the 'response' field of the Operation.
)rM   r!   s     r   r,   )CloudOperationPollerNoResources.GetResult   s     r   )rZ   r6   rV   rP   r   r   r   rR   rR      s    B"9	r   rR   c                 D  ^^ SR                  U5      n U(       d  [        R                  " X,S9OU mU(       a  [        U5        UU4S jn[	        XXgXU
X5	      nSSS5        U R                  W5      $ ! , (       d  f       N= f! [
        R                   a#    [        SR                  XS-  [        5      5      e[
        R                   aQ  n[        SR                  UUR                  R                  S-  UR                  R                  [        5      5      eSnAff = f)a  Waits for poller.Poll and displays pending operation spinner.

Args:
  poller: OperationPoller, poller to use during retrials.
  operation_ref: object, passed to operation poller poll method.
  message: str, string to display for default progress_tracker.
  custom_tracker: ProgressTracker, progress_tracker to use for display.
  tracker_update_func: func(tracker, result, status), tracker update function.
  pre_start_sleep_ms: int, Time to wait before making first poll request.
  max_retrials: int, max number of retrials before raising RetryException.
  max_wait_ms: int, number of ms to wait before raising WaitException.
  exponential_sleep_multiplier: float, factor to use on subsequent retries.
  jitter_ms: int, random (up to the value) additional sleep between retries.
  wait_ceiling_ms: int, Maximum wait between retries.
  sleep_ms: int or iterable: for how long to wait between trials.

Returns:
  poller.GetResult(operation).

Raises:
  AbortWaitError: if ctrl-c was pressed.
  TimeoutError: if retryer has finished without being done.
z!Aborting wait for operation {0}.
)aborted_messagec                 H   > T(       a
  T" TX5        g TR                  5         g rV   )Tick)resultstatustrackertracker_update_funcs     r   _StatusUpdateWaitFor.<locals>._StatusUpdate   s    
gv
6
,,.r   Nz2Operation {0} has not finished in {1} seconds. {2}  zIOperation {0} has not finished in {1} seconds after max {2} retrials. {3})formatr   ProgressTracker_SleepMsPollUntilDoner	   WaitExceptionr   _TIMEOUT_MESSAGEMaxRetrialsExceptionstatetime_passed_msretrialr,   )pollerr(   r>   custom_trackerrj   pre_start_sleep_msmax_retrialsmax_wait_msexponential_sleep_multiplier	jitter_mswait_ceiling_mssleep_msrd   rk   r#   eri   s       `           @r   WaitForr      s   F 9??N/#  
	)	)
!/
03:	#$  

&?
#i
0> 
		)	$$?
0 
0$ 
		 G
<	d24D	EG G 
	#	# #
	&	&&$. 
"# ##s6   B )A4B 4
B>B B A	DADDc	           	         ^  [         R                  " UUUUUUS9n	U 4S jn
U	R                  T R                  U4U
US9nU$ )ae  Waits for poller.Poll to complete.

Note that this *does not* print nice messages to stderr for the user; most
callers should use WaitFor instead for the best UX unless there's a good
reason not to print.

Args:
  poller: OperationPoller, poller to use during retrials.
  operation_ref: object, passed to operation poller poll method.
  max_retrials: int, max number of retrials before raising RetryException.
  max_wait_ms: int, number of ms to wait before raising WaitException.
  exponential_sleep_multiplier: float, factor to use on subsequent retries.
  jitter_ms: int, random (up to the value) additional sleep between retries.
  wait_ceiling_ms: int, Maximum wait between retries.
  sleep_ms: int or iterable: for how long to wait between trials.
  status_update: func(result, state) called right after each trial.

Returns:
  The return value from poller.Poll.
)r{   r|   r}   r~   r   status_update_funcc                 0   > TR                  U 5      (       + $ rV   )r$   )r#   unused_staterx   s     r   
_IsNotDone!PollUntilDone.<locals>._IsNotDone?  s    }}Y'''r   )funcargsshould_retry_ifr   )r	   RetryerRetryOnResultr)   )rx   r(   r{   r|   r}   r~   r   r   status_updateretryerr   r#   s   `           r   rq   rq     s\    : MM#?%&('( ##;; 	 $ ) 
r   c                 6    [         R                  " U S-  5        g )Nrm   )timesleep)milisecondss    r   rp   rp   K  s    **[4 r   )
NNNrm   N@w ffffff?rm       )Nr   r   rm   r   r   N)r.   
__future__r   r   r   r/   r   apitools.base.pyr   googlecloudsdk.corer   googlecloudsdk.core.consoler   googlecloudsdk.core.utilr	   sixrs   Errorr   r   r   with_metaclassABCMetaobjectr   r2   rR   r   rq   rp   r   r   r   <module>r      s     4 &  ' 
  % * 8 * 
F :## Z%% Z%% ,c((f= ,^5M? 5Mp7o 7x  $#),"D%P  $%/2 "( $.b!r   