|
5 | 5 | import sys
|
6 | 6 | import json
|
7 | 7 | import time
|
| 8 | +import exceptions |
8 | 9 | import urllib.error
|
9 | 10 | import urllib.request
|
10 | 11 | from ldap3 import Server, Connection, ALL, ALL_ATTRIBUTES, SAFE_SYNC
|
|
27 | 28 | TEST_UNIX_CLUSTER_ID = 10
|
28 | 29 | TEST_LDAP_TARGET_ID = 9
|
29 | 30 |
|
30 |
| - |
31 |
| -TIMEOUT_MIN = 5 |
32 |
| -TIMEOUT_MULTIPLE = 5 |
33 |
| -MAX_RETRIES = 5 |
| 31 | +# Value for the base of the exponential backoff |
| 32 | +TIMEOUT_BASE = 5 |
| 33 | +MAX_RETRIES = 2 |
34 | 34 |
|
35 | 35 |
|
36 | 36 | GET = "GET"
|
@@ -83,28 +83,29 @@ def call_api2(method, target, endpoint, authstr, **kw):
|
83 | 83 | def call_api3(method, target, data, endpoint, authstr, **kw):
|
84 | 84 | req = mkrequest(method, target, data, endpoint, authstr, **kw)
|
85 | 85 | retries = 0
|
86 |
| - currentTimeout = TIMEOUT_MIN |
87 |
| - requestingStart = time.time() |
| 86 | + current_timeout = TIMEOUT_BASE |
| 87 | + total_timeout = 0 |
88 | 88 | payload = None
|
89 |
| - while payload == None: |
| 89 | + while retries <= MAX_RETRIES: |
90 | 90 | try:
|
91 |
| - resp = urllib.request.urlopen(req, timeout=currentTimeout) |
92 |
| - if retries > 0: |
93 |
| - print(f"Succeeded for request {req.full_url} after {retries} retries.") |
| 91 | + resp = urllib.request.urlopen(req, timeout=current_timeout) |
94 | 92 | payload = resp.read()
|
95 |
| - except urllib.error.URLError as exception: |
96 |
| - if retries < MAX_RETRIES: |
97 |
| - print(f"Error: {exception} for request {req.full_url}, sleeping for {currentTimeout} seconds and retrying.") |
98 |
| - time.sleep(currentTimeout) |
99 |
| - currentTimeout *= TIMEOUT_MULTIPLE |
100 |
| - retries += 1 |
101 |
| - else: |
102 |
| - requestingStop = time.time() |
103 |
| - sys.exit( |
104 |
| - f"Exception raised after maximum number of retries reached after {requestingStop - requestingStart} seconds. Retries: {retries}. " |
| 93 | + break |
| 94 | + # exception catching, mainly for request timeouts and "Service Temporarily Unavailable" (Rate limiting). |
| 95 | + except urllib.error.HTTPError as exception: |
| 96 | + if retries >= MAX_RETRIES: |
| 97 | + raise exceptions.URLRequestError( |
| 98 | + "Exception raised after maximum number of retries reached after total backoff of " + |
| 99 | + f"{total_timeout} seconds. Retries: {retries}. " |
105 | 100 | + f"Exception reason: {exception}.\n Request: {req.full_url}"
|
106 | 101 | )
|
107 | 102 |
|
| 103 | + print("waiting for seconds: " + str(current_timeout)) |
| 104 | + time.sleep(current_timeout) |
| 105 | + total_timeout += current_timeout |
| 106 | + current_timeout *= TIMEOUT_BASE |
| 107 | + retries += 1 |
| 108 | + |
108 | 109 | return json.loads(payload) if payload else None
|
109 | 110 |
|
110 | 111 |
|
|
0 commit comments