Skip to content
This repository has been archived by the owner on Sep 18, 2024. It is now read-only.

Commit

Permalink
Improved error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
xannz committed Dec 5, 2019
1 parent fc2d749 commit 83865b8
Showing 1 changed file with 72 additions and 58 deletions.
130 changes: 72 additions & 58 deletions obelisk/obeliskclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
logger = logging.getLogger(__name__)


class ObeliskError(requests.exceptions.HTTPError):
class ObeliskError(Exception):
pass


Expand All @@ -31,10 +31,8 @@ class ObeliskPrecisions(Enum):
wait_gen=backoff.expo,
exception=(
ObeliskError,
requests.exceptions.Timeout,
requests.exceptions.ConnectionError
),
max_tries=5,
max_tries=3,
)


Expand All @@ -52,67 +50,83 @@ def __init__(self, base_url, client_id, client_secret, scope_id, version='v2', p

@retry_timeout
def __request_access_token(self):
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
body = 'grant_type=client_credentials'
r = requests.post("{}/auth/realms/idlab-iot/protocol/openid-connect/token".format(self._base_url), data=body,
auth=HTTPBasicAuth(self._client_id, self._client_secret), headers=headers, timeout=10)
r.raise_for_status()
message = r.json()
return message['access_token']
try:
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
body = 'grant_type=client_credentials'
r = requests.post("{}/auth/realms/idlab-iot/protocol/openid-connect/token".format(self._base_url), data=body,
auth=HTTPBasicAuth(self._client_id, self._client_secret), headers=headers, timeout=10)
r.raise_for_status()
message = r.json()
return message['access_token']
except requests.exceptions.HTTPError as e:
logger.error(e)
raise ObeliskError("Could not request access token.")

@retry_timeout
def __request_rpt_token(self):
access_token = self.__request_access_token()
headers = {
'Authorization': 'Bearer {}'.format(access_token),
'Content-Type': 'application/x-www-form-urlencoded'

}
payload = {
'grant_type': 'urn:ietf:params:oauth:grant-type:uma-ticket',
'audience': 'policy-enforcer',
}
r = requests.post("{}/auth/realms/idlab-iot/protocol/openid-connect/token".format(self._base_url), data=payload,
headers=headers, timeout=10)
r.raise_for_status()
message = r.json()
self._rpt_token = message['access_token']
self._rpt_refresh_token = message['refresh_token']
self._rpt_refresh_token_expire_date = datetime.utcnow(
) + timedelta(seconds=message['refresh_expires_in'])
try:
access_token = self.__request_access_token()
headers = {
'Authorization': 'Bearer {}'.format(access_token),
'Content-Type': 'application/x-www-form-urlencoded'

}
payload = {
'grant_type': 'urn:ietf:params:oauth:grant-type:uma-ticket',
'audience': 'policy-enforcer',
}
r = requests.post("{}/auth/realms/idlab-iot/protocol/openid-connect/token".format(self._base_url), data=payload,
headers=headers, timeout=10)
r.raise_for_status()
message = r.json()
self._rpt_token = message['access_token']
self._rpt_refresh_token = message['refresh_token']
self._rpt_refresh_token_expire_date = datetime.utcnow(
) + timedelta(seconds=message['refresh_expires_in'])
except requests.exceptions.HTTPError as e:
logger.error(e)
raise ObeliskError("Could not request RPT token.")

@retry_timeout
def __refresh_rpt_token(self):
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
payload = {
'grant_type': 'refresh_token',
'refresh_token': self._rpt_refresh_token,
'client_id': self._client_id,
'client_secret': self._client_secret,
}
r = requests.post("{}/auth/realms/idlab-iot/protocol/openid-connect/token".format(
self._base_url), headers=headers, data=payload, timeout=10)
r.raise_for_status()
message = r.json()
self._rpt_token = message['access_token']
self._rpt_refresh_token = message['refresh_token']
self._rpt_refresh_token_expire_date = datetime.utcnow(
) + timedelta(seconds=message['refresh_expires_in'])
try:
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
payload = {
'grant_type': 'refresh_token',
'refresh_token': self._rpt_refresh_token,
'client_id': self._client_id,
'client_secret': self._client_secret,
}
r = requests.post("{}/auth/realms/idlab-iot/protocol/openid-connect/token".format(
self._base_url), headers=headers, data=payload, timeout=10)
r.raise_for_status()
message = r.json()
self._rpt_token = message['access_token']
self._rpt_refresh_token = message['refresh_token']
self._rpt_refresh_token_expire_date = datetime.utcnow(
) + timedelta(seconds=message['refresh_expires_in'])
except requests.exceptions.HTTPError as e:
logger.error(e)
raise ObeliskError("Could not refresh RPT token.")

@retry_timeout
def send_to_obelisk(self, data, refresh_rpt=False):
if refresh_rpt:
if not self._rpt_refresh_token_expire_date or self._rpt_refresh_token_expire_date < datetime.utcnow():
self.__request_rpt_token()
try:
if refresh_rpt:
if not self._rpt_refresh_token_expire_date or self._rpt_refresh_token_expire_date < datetime.utcnow():
self.__request_rpt_token()
else:
self.__refresh_rpt_token()
headers = {'Content-Type': 'application/json',
'Authorization': 'Bearer {}'.format(self._rpt_token)}
url = "{}/api/{}/scopes/{}/ingest?precision={}".format(
self._base_url, self._version, self._scope_id, obelisk_precisions[self._precision])
resp = requests.post(url, json=data, headers=headers, timeout=10)
if resp.status_code == 403 or resp.status_code == 401:
logger.debug("Requesting/renewing RPT token")
self.send_to_obelisk(data, refresh_rpt=True)
else:
self.__refresh_rpt_token()
headers = {'Content-Type': 'application/json',
'Authorization': 'Bearer {}'.format(self._rpt_token)}
url = "{}/api/{}/scopes/{}/ingest?precision={}".format(
self._base_url, self._version, self._scope_id, obelisk_precisions[self._precision])
resp = requests.post(url, json=data, headers=headers, timeout=10)
if resp.status_code == 403 or resp.status_code == 401:
logger.debug("Requesting/renewing RPT token")
self.send_to_obelisk(data, refresh_rpt=True)
else:
resp.raise_for_status()
resp.raise_for_status()
except requests.exceptions.HTTPError as e:
logger.error(e)
raise ObeliskError("Could not send data to Obelisk.")

0 comments on commit 83865b8

Please sign in to comment.