
                             d Z ddlZddlZddlZddlZddlZddlmZ ddlm	Z	  G d de
      Zd Z G d d	e
      Zd
 Zddej                  e e       dfdZy)aH  Retry decorators for calls raising exceptions.

This module is used mostly to decorate all integration points where the code
makes calls to remote services. Searching through the code base for @retry
should find all such places. For this reason even places where retry is not
needed right now use a @retry.no_retries decorator.
    N)_exceptions)reraisec                   $    e Zd ZdZ	 	 	 ddZd Zy)FuzzedExponentialIntervalsa<  Iterable for intervals that are exponentially spaced, with fuzzing.

  On iteration, yields retry interval lengths, in seconds. Every iteration over
  this iterable will yield differently fuzzed interval lengths, as long as fuzz
  is nonzero.

  Args:
    initial_delay_secs: The delay before the first retry, in seconds.
    num_retries: The total number of times to retry.
    factor: The exponential factor to use on subsequent retries.
      Default is 2 (doubling).
    fuzz: A value between 0 and 1, indicating the fraction of fuzz. For a
      given delay d, the fuzzed delay is randomly chosen between
      [(1 - fuzz) * d, d].
    max_delay_sec: Maximum delay (in seconds). After this limit is reached,
      further tries use max_delay_sec instead of exponentially increasing
      the time. Defaults to 5 minutes.
  c                     || _         || _        || _        d|cxk  rdk  st        d       t        d      || _        || _        y )Nr      z.Fuzz parameter expected to be in [0, 1] range.)_initial_delay_secs_num_retries_factor
ValueError_fuzz_max_delay_secs)selfinitial_delay_secsnum_retriesfactorfuzzmax_delay_secss         .lib/third_party/ml_sdk/cloud/ml/util/_retry.py__init__z#FuzzedExponentialIntervals.__init__5   sR      2D#DDL>>GHH GHHDJ)D    c              #   6  K   t        | j                  | j                        }t        | j                        D ]]  }d| j
                  z
  t        j                         | j
                  z  z   }||z   t        | j                  || j                  z        }_ y w)Nr   )minr   r	   ranger
   r   randomr   )r   current_delay_secs_fuzz_multipliers       r   __iter__z#FuzzedExponentialIntervals.__iter__C   s     T1143K3KL4$$%DJJ4::)EEo00t331DLL@B &s   BBN)         ?   )__name__
__module____qualname____doc__r   r    r   r   r   r   !   s    ,  *Br   r   c                 Z    t        | t        j                        r| j                  dk\  ryyy)z<Filter allowing retries on server errors and non-HttpErrors.i  TF)
isinstancer   _RequestExceptionstatus)	exceptions    r   retry_on_server_errors_filterr-   L   s+    	;8893 r   c                       e Zd ZdZd Zy)Clockz$A simple clock implementing sleep().c                 .    t        j                  |       y )N)timesleep)r   values     r   r2   zClock.sleep\   s    JJur   N)r#   r$   r%   r&   r2   r'   r   r   r/   r/   Y   s
    ,r   r/   c                 *     t        d d      |       S )z:A retry decorator for places where we do not want retries.c                      y)NFr'   )r   s    r   <lambda>zno_retries.<locals>.<lambda>b   s    r   N)retry_filterclock)with_exponential_backoff)funs    r   
no_retriesr;   `   s    	K	!d	KC	PPr   
   r   Tc                 &      fd}|S )a  Decorator with arguments that control the retry logic.

  Args:
    num_retries: The total number of times to retry.
    initial_delay_secs: The delay before the first retry, in seconds.
    logger: A callable used to report en exception. Must have the same signature
      as functions in the standard logging module. The default is
      logging.warning.
    retry_filter: A callable getting the exception raised and returning True
      if the retry should happen. For instance we do not want to retry on
      404 Http errors most of the time. The default value will return true
      for server errors (HTTP status code >= 500) and non Http errors.
    clock: A clock object implementing a sleep method. The default clock will
      use time.sleep().
    fuzz: True if the delay should be fuzzed (default). During testing False
      can be used so that the delays are not randomized.

  Returns:
    As per Python decorators with arguments pattern returns a decorator
    for the function which in turn will return the wrapped (decorated) function.

  The decorator is intended to be used on callables that make HTTP or RPC
  requests that can temporarily timeout or have transient errors. For instance
  the make_http_request() call below will be retried 16 times with exponential
  backoff and fuzzing of the delay interval (default settings).

  from cloudml.util import retry
  # ...
  @retry.with_exponential_backoff()
  make_http_request(args)
  c                 T     t        t        rdnd             fd}|S )zCThe real decorator whose purpose is to return the wrapped function.r!   r   )r   c                     	 	  | i |S # t         $ r5} |      s t        j                         d   }	 	 t        	      }n%# t        $ r t        t        |      ||       Y nw xY w dt        dt                    dj                  t        j                  |j                  |            dj                  t        j                  |                   j                  |       t        j                  dk  rt        j                           d }n.# t        j                  dk  rt        j                           d }w xY wY d }~nd }~ww xY wM)Nr    zRetry with exponential backoff: waiting for %s seconds before retrying %s because we caught exception: %s Traceback for above exception (most recent call last):
%sr#    )   r   )	Exceptionsysexc_infonextStopIterationr   typegetattrstrjoin	tracebackformat_exception_only	__class__	format_tbr2   version_info	exc_clear)
argskwargsexnexn_tracebacksleep_intervalr8   r:   loggerr7   retry_intervalss
        r   wrapperzAwith_exponential_backoff.<locals>.real_decorator.<locals>.wrapper   s'   	!d%f%
% 	!c" ,,.+-!5#O4n  5d3im45 M ZS2	77sKL	++M:;= KK'
 &(mmo M &(mmo MM;	! sJ    
E EADA&#D%A&&BD)*E+D>>EE)iterr   )	r:   rX   rW   r8   r   r   rV   r   r7   s	   ` @r   real_decoratorz0with_exponential_backoff.<locals>.real_decorator   s6     "#1	FGO!! !!F Nr   r'   )r   r   rV   r7   r8   r   rZ   s   `````` r   r9   r9   e   s    L* *X 
r   )r&   loggingr   rC   r1   rK   google.cloud.ml.utilr   sixr   objectr   r-   r/   r;   warningr9   r'   r   r   <module>r`      sg      
   , (B (BV
F Q
 *,01$+OO*G#(7"&Rr   