Skip to content

Commit 2e9bd59

Browse files
Update COmanage API request timeouts
Fix exponential backoff to also apply to wait times between making requests, and not just timeouts on the requests themselves. Also improve error messages to include more information about how the request went / why it failed.
1 parent 80a0cd3 commit 2e9bd59

File tree

1 file changed

+19
-11
lines changed

1 file changed

+19
-11
lines changed

comanage_utils.py

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import re
55
import sys
66
import json
7+
import time
78
import urllib.error
89
import urllib.request
910
from ldap3 import Server, Connection, ALL, ALL_ATTRIBUTES, SAFE_SYNC
@@ -27,9 +28,9 @@
2728
TEST_LDAP_TARGET_ID = 9
2829

2930

30-
MIN_TIMEOUT = 5
31-
MAX_TIMEOUT = 625
32-
TIMEOUTMULTIPLE = 5
31+
TIMEOUT_MIN = 5
32+
TIMEOUT_MULTIPLE = 5
33+
MAX_RETRIES = 5
3334

3435

3536
GET = "GET"
@@ -81,20 +82,27 @@ def call_api2(method, target, endpoint, authstr, **kw):
8182

8283
def call_api3(method, target, data, endpoint, authstr, **kw):
8384
req = mkrequest(method, target, data, endpoint, authstr, **kw)
84-
trying = True
85-
currentTimeout = MIN_TIMEOUT
86-
while trying:
85+
retries = 0
86+
currentTimeout = TIMEOUT_MIN
87+
requestingStart = time.time()
88+
payload = None
89+
while payload == None:
8790
try:
8891
resp = urllib.request.urlopen(req, timeout=currentTimeout)
92+
if retries > 0:
93+
print(f"Succeeded for request {req.full_url} after {retries} retries.")
8994
payload = resp.read()
90-
trying = False
9195
except urllib.error.URLError as exception:
92-
if currentTimeout < MAX_TIMEOUT:
93-
currentTimeout *= TIMEOUTMULTIPLE
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
94101
else:
102+
requestingStop = time.time()
95103
sys.exit(
96-
f"Exception raised after maximum number of retries and/or timeout {MAX_TIMEOUT} seconds reached. "
97-
+ f"Exception reason: {exception.reason}.\n Request: {req.full_url}"
104+
f"Exception raised after maximum number of retries reached after {requestingStop - requestingStart} seconds. Retries: {retries}. "
105+
+ f"Exception reason: {exception}.\n Request: {req.full_url}"
98106
)
99107

100108
return json.loads(payload) if payload else None

0 commit comments

Comments
 (0)