diff --git a/inventory_provider/db/ims.py b/inventory_provider/db/ims.py index c85c2d3c6f784615a93a540d58587b7643d1c125..5a9f1d4120e46513a37edbfa4bbfed0bbf1d08ad 100644 --- a/inventory_provider/db/ims.py +++ b/inventory_provider/db/ims.py @@ -1,3 +1,5 @@ +import json + import requests import time @@ -55,13 +57,14 @@ class IMS(object): cache = {} base_url = None bearer_token = None - bearer_token_init_time = None + bearer_token_init_time = 0 reconnect_attempts = 0 - def __init__(self, base_url, username, password): + def __init__(self, base_url, username, password, bearer_token=None): IMS.base_url = base_url self.username = username self.password = password + IMS.bearer_token = bearer_token @classmethod def _init_bearer_token(cls, username, password): @@ -69,14 +72,14 @@ class IMS(object): if not cls.bearer_token or \ re_init_time - cls.bearer_token_init_time \ > cls.TIMEOUT_THRESHOLD: - IMS.reconnect_attempts = 0 + cls.reconnect_attempts = 0 else: cls.reconnect_attempts += 1 if cls.reconnect_attempts > cls.PERMITTED_RECONNECT_ATTEMPTS: raise IMSError('Too many reconnection attempts made') response = requests.post( - IMS.base_url + IMS.LOGIN_PATH, + cls.base_url + cls.LOGIN_PATH, auth=(username, password)) response.raise_for_status() cls.bearer_token_init_time = re_init_time @@ -109,23 +112,33 @@ class IMS(object): if not IMS.bearer_token: self._init_bearer_token(self.username, self.password) - make_request = True - while make_request: + def _is_invalid_login_state(response_): + if response_.status_code == requests.codes.unauthorized: + return True + + if response_.status_code == requests.codes.ok: + j = response_.json() + if j and isinstance(j, dict) and \ + j.get('HasErrors', False) and 'guid expired' in \ + j['Errors'][0]['ErrorMessage'].lower(): + return True + + return False + + while True: response = requests.get( url, headers={'Authorization': self.bearer_token}, params=params) - if response.status_code == requests.codes.unauthorized: + if _is_invalid_login_state(response): IMS._init_bearer_token(self.username, self.password) else: - make_request = False + response.raise_for_status() + return_value = response.json() - response.raise_for_status() - return_value = response.json() - - if use_cache: - IMS.cache[cache_key] = return_value - return return_value + if use_cache: + IMS.cache[cache_key] = return_value + return return_value def get_entity_by_id( self, @@ -168,7 +181,8 @@ class IMS(object): use_cache) more_to_come = False if entities: - more_to_come = len(entities) >= IMS.NO_OF_ELEMENTS_PER_ITERATION + more_to_come = \ + len(entities) >= IMS.NO_OF_ELEMENTS_PER_ITERATION start_entity += IMS.NO_OF_ELEMENTS_PER_ITERATION yield from entities