| 1 |
# -*- coding: utf-8 -*- |
| 2 |
# coding=utf-8 |
| 3 |
# -------------------------------------------------------------------------- |
| 4 |
# Copyright (c) Microsoft Corporation. All rights reserved. |
| 5 |
# Licensed under the MIT License. See License.txt in the project root for |
| 6 |
# license information. |
| 7 |
# -------------------------------------------------------------------------- |
| 8 |
|
| 9 |
""" |
| 10 |
Provides implementation of different Retry Policies |
| 11 |
""" |
| 12 |
|
| 13 |
# standard imports |
| 14 |
import logging |
| 15 |
import sys |
| 16 |
import time |
| 17 |
from functools import wraps |
| 18 |
# local imports |
| 19 |
|
| 20 |
logger = logging.getLogger(__name__) |
| 21 |
|
| 22 |
|
| 23 |
class RetryPolicy: |
| 24 |
def should_retry(self, *args): |
| 25 |
pass |
| 26 |
|
| 27 |
|
| 28 |
class NoRetryPolicy(RetryPolicy): |
| 29 |
def should_retry(self, *args): |
| 30 |
return False |
| 31 |
|
| 32 |
|
| 33 |
class ExponentialRetryPolicy(RetryPolicy): |
| 34 |
|
| 35 |
def __init__(self, max_retries=None, exponential_retry_interval=None, exponential_factor=None): |
| 36 |
self.exponential_factor = 4 if exponential_factor is None else exponential_factor |
| 37 |
self.max_retries = 4 if max_retries is None else max_retries |
| 38 |
self.exponential_retry_interval = 1 if exponential_retry_interval is None else exponential_retry_interval |
| 39 |
|
| 40 |
def should_retry(self, response, last_exception, retry_count): |
| 41 |
if retry_count >= self.max_retries: |
| 42 |
return False |
| 43 |
|
| 44 |
if last_exception is not None: |
| 45 |
self.__backoff() |
| 46 |
return True |
| 47 |
|
| 48 |
if response is None: |
| 49 |
return False |
| 50 |
|
| 51 |
status_code = response.status_code |
| 52 |
|
| 53 |
if(status_code == 501 |
| 54 |
or status_code == 505 |
| 55 |
or (300 <= status_code < 500 |
| 56 |
and status_code != 401 |
| 57 |
and status_code != 408 |
| 58 |
and status_code != 429)): |
| 59 |
return False |
| 60 |
|
| 61 |
if(status_code >= 500 |
| 62 |
or status_code == 401 |
| 63 |
or status_code == 408 |
| 64 |
or status_code == 429 |
| 65 |
or status_code == 104): |
| 66 |
self.__backoff() |
| 67 |
return True |
| 68 |
|
| 69 |
if 100 <= status_code < 300: |
| 70 |
return False |
| 71 |
|
| 72 |
return False |
| 73 |
|
| 74 |
def __backoff(self): |
| 75 |
time.sleep(self.exponential_retry_interval) |
| 76 |
self.exponential_retry_interval *= self.exponential_factor |