|
4 | 4 | import re |
5 | 5 | import json |
6 | 6 | import time |
7 | | -import exceptions |
8 | 7 | import urllib.error |
9 | 8 | import urllib.request |
10 | 9 | from ldap3 import Server, Connection, ALL, ALL_ATTRIBUTES, SAFE_SYNC |
|
29 | 28 |
|
30 | 29 | # Value for the base of the exponential backoff |
31 | 30 | TIMEOUT_BASE = 5 |
32 | | -MAX_RETRIES = 5 |
| 31 | +MAX_ATTEMPTS = 5 |
33 | 32 |
|
34 | 33 |
|
35 | 34 | GET = "GET" |
36 | 35 | PUT = "PUT" |
37 | 36 | POST = "POST" |
38 | 37 | DELETE = "DELETE" |
39 | 38 |
|
| 39 | +#Exceptions |
| 40 | +class Error(Exception): |
| 41 | + """Base exception class for all exceptions defined""" |
| 42 | + pass |
| 43 | + |
| 44 | + |
| 45 | +class URLRequestError(Error): |
| 46 | + """Class for exceptions due to not being able to fulfill a URLRequest""" |
| 47 | + pass |
| 48 | + |
40 | 49 |
|
41 | 50 | def getpw(user, passfd, passfile): |
42 | 51 | if ":" in user: |
@@ -81,29 +90,28 @@ def call_api2(method, target, endpoint, authstr, **kw): |
81 | 90 |
|
82 | 91 | def call_api3(method, target, data, endpoint, authstr, **kw): |
83 | 92 | req = mkrequest(method, target, data, endpoint, authstr, **kw) |
84 | | - retries = 0 |
| 93 | + req_attempts = 0 |
85 | 94 | current_timeout = TIMEOUT_BASE |
86 | 95 | total_timeout = 0 |
87 | 96 | payload = None |
88 | | - while retries <= MAX_RETRIES: |
| 97 | + while req_attempts < MAX_ATTEMPTS: |
89 | 98 | try: |
90 | 99 | resp = urllib.request.urlopen(req, timeout=current_timeout) |
91 | | - payload = resp.read() |
92 | | - break |
93 | | - # exception catching, mainly for request timeouts and "Service Temporarily Unavailable" (Rate limiting). |
94 | | - except urllib.error.HTTPError as exception: |
95 | | - if retries >= MAX_RETRIES: |
96 | | - raise exceptions.URLRequestError( |
| 100 | + # exception catching, mainly for request timeouts, "Service Temporarily Unavailable" (Rate limiting), and DNS failures. |
| 101 | + except urllib.error.URLError as exception: |
| 102 | + req_attempts += 1 |
| 103 | + if req_attempts >= MAX_ATTEMPTS: |
| 104 | + raise URLRequestError( |
97 | 105 | "Exception raised after maximum number of retries reached after total backoff of " + |
98 | | - f"{total_timeout} seconds. Retries: {retries}. " |
| 106 | + f"{total_timeout} seconds. Retries: {req_attempts}. " |
99 | 107 | + f"Exception reason: {exception}.\n Request: {req.full_url}" |
100 | 108 | ) |
101 | | - |
102 | | - print("waiting for seconds: " + str(current_timeout)) |
103 | 109 | time.sleep(current_timeout) |
104 | 110 | total_timeout += current_timeout |
105 | 111 | current_timeout *= TIMEOUT_BASE |
106 | | - retries += 1 |
| 112 | + else: |
| 113 | + payload = resp.read() |
| 114 | + break |
107 | 115 |
|
108 | 116 | return json.loads(payload) if payload else None |
109 | 117 |
|
|
0 commit comments