self.password: str = kw['password']
# move the following line (class attribute?)
self.client: RedFishClient = RedFishClient(host=self.host, port=self.port, username=self.username, password=self.password)
- self.log.logger.info(f"redfish system initialization, host: {self.host}, user: {self.username}")
+ self.log.logger.info(f'redfish system initialization, host: {self.host}, user: {self.username}')
self.run: bool = False
self.thread: Thread
# this loop can have:
# - caching logic
while self.run:
- self.log.logger.debug("waiting for a lock.")
+ self.log.logger.debug('waiting for a lock.')
self.lock.acquire()
- self.log.logger.debug("lock acquired.")
+ self.log.logger.debug('lock acquired.')
try:
self._update_system()
self._update_sn()
sleep(5)
except RuntimeError as e:
self.run = False
- self.log.logger.error(f"Error detected, trying to gracefully log out from redfish api.\n{e}")
+ self.log.logger.error(f'Error detected, trying to gracefully log out from redfish api.\n{e}')
self.client.logout()
finally:
self.lock.release()
- self.log.logger.debug("lock released.")
+ self.log.logger.debug('lock released.')
def flush(self) -> None:
- self.log.logger.info("Acquiring lock to flush data.")
+ self.log.logger.info('Acquiring lock to flush data.')
self.lock.acquire()
- self.log.logger.info("Lock acquired, flushing data.")
+ self.log.logger.info('Lock acquired, flushing data.')
self._system = {}
self.previous_data = {}
- self.log.logger.info("Data flushed.")
+ self.log.logger.info('Data flushed.')
self.data_ready = False
- self.log.logger.info("Data marked as not ready.")
+ self.log.logger.info('Data marked as not ready.')
self.lock.release()
- self.log.logger.info("Lock released.")
+ self.log.logger.info('Lock released.')
@retry(retries=10, delay=2)
def _get_path(self, path: str) -> Dict:
except RuntimeError:
raise
if result is None:
- self.log.logger.error(f"The client reported an error when getting path: {path}")
- raise RuntimeError(f"Could not get path: {path}")
+ self.log.logger.error(f'The client reported an error when getting path: {path}')
+ raise RuntimeError(f'Could not get path: {path}')
return result
def get_members(self, data: Dict[str, Any], path: str) -> List:
def check_status(self) -> bool:
if self.__dict__.get('system') and not self.system.run:
- raise RuntimeError("node-proxy encountered an error.")
+ raise RuntimeError('node-proxy encountered an error.')
if self.exc:
traceback.print_tb(self.exc.__traceback__)
- self.log.logger.error(f"{self.exc.__class__.__name__}: {self.exc}")
+ self.log.logger.error(f'{self.exc.__class__.__name__}: {self.exc}')
raise self.exc
return True
self.log = Logger(__name__, level=self.config.__dict__['logging']['level'])
# create the redfish system and the obsever
- self.log.logger.info(f"Server initialization...")
+ self.log.logger.info('Server initialization...')
try:
self.system = RedfishDellSystem(host=self.__dict__['host'],
port=self.__dict__.get('port', 443),
PREFIX = '/redfish/v1/'
def __init__(self,
- host: str = "",
+ host: str = '',
port: int = 443,
- username: str = "",
- password: str = ""):
+ username: str = '',
+ password: str = ''):
super().__init__(host, username, password)
self.log: Logger = Logger(__name__)
- self.log.logger.info(f"Initializing redfish client {__name__}")
+ self.log.logger.info(f'Initializing redfish client {__name__}')
self.host: str = host
self.port: int = port
- self.url: str = f"https://{self.host}:{self.port}"
+ self.url: str = f'https://{self.host}:{self.port}'
self.token: str = ''
self.location: str = ''
def login(self) -> None:
if not self.is_logged_in():
- self.log.logger.info("Logging in to "
+ self.log.logger.info('Logging in to '
f"{self.url} as '{self.username}'")
- oob_credentials = json.dumps({"UserName": self.username,
- "Password": self.password})
- headers = {"Content-Type": "application/json"}
+ oob_credentials = json.dumps({'UserName': self.username,
+ 'Password': self.password})
+ headers = {'Content-Type': 'application/json'}
try:
_headers, _data, _status_code = self.query(data=oob_credentials,
self.location = _headers['Location']
def is_logged_in(self) -> bool:
- self.log.logger.debug(f"Checking token validity for {self.url}")
+ self.log.logger.debug(f'Checking token validity for {self.url}')
if not self.location or not self.token:
- self.log.logger.debug(f"No token found for {self.url}.")
+ self.log.logger.debug(f'No token found for {self.url}.')
return False
- headers = {"X-Auth-Token": self.token}
+ headers = {'X-Auth-Token': self.token}
try:
_headers, _data, _status_code = self.query(headers=headers,
endpoint=self.location)
except URLError as e:
self.log.logger.error("Can't check token "
- f"validity for {self.url}: {e}")
+ f'validity for {self.url}: {e}')
raise RuntimeError
return _status_code == 200
def logout(self) -> Dict[str, Any]:
try:
_, _data, _status_code = self.query(method='DELETE',
- headers={"X-Auth-Token": self.token},
+ headers={'X-Auth-Token': self.token},
endpoint=self.location)
except URLError:
self.log.logger.error(f"Can't log out from {self.url}")
def get_path(self, path: str) -> Dict[str, Any]:
if self.PREFIX not in path:
- path = f"{self.PREFIX}{path}"
+ path = f'{self.PREFIX}{path}'
try:
_, result, _status_code = self.query(endpoint=path)
result_json = json.loads(result)
return response_headers, response_str, response_status
except (HTTPError, URLError) as e:
- self.log.logger.debug(f"{e}")
+ self.log.logger.debug(f'{e}')
raise
try:
result[member_id][to_snake_case(field)] = member_info[field]
except KeyError:
- self.log.logger.warning(f"Could not find field: {field} in member_info: {member_info}")
+ self.log.logger.warning(f'Could not find field: {field} in member_info: {member_info}')
return normalize_dict(result)
fields: Dict[str, List[str]],
path: str) -> Dict[str, Dict[str, Dict]]:
result: Dict[str, Dict[str, Dict]] = dict()
- data = self._get_path(f"{self.chassis_endpoint}/{path}")
+ data = self._get_path(f'{self.chassis_endpoint}/{path}')
for elt, _fields in fields.items():
for member_elt in data[elt]:
try:
result[_id][to_snake_case(field)] = member_elt[field]
except KeyError:
- self.log.logger.warning(f"Could not find field: {field} in data: {data[elt]}")
+ self.log.logger.warning(f'Could not find field: {field} in data: {data[elt]}')
return normalize_dict(result)
def get_sn(self) -> str:
self.reporter_port: int = reporter_port
self.reporter_endpoint: str = reporter_endpoint
self.log = Logger(__name__)
- self.reporter_url: str = (f"{reporter_scheme}:{reporter_hostname}:"
- f"{reporter_port}{reporter_endpoint}")
+ self.reporter_url: str = (f'{reporter_scheme}:{reporter_hostname}:'
+ f'{reporter_port}{reporter_endpoint}')
self.log.logger.info(f'Reporter url set to {self.reporter_url}')
def stop(self) -> None:
# scenario probably we should just send the sub-parts
# that have changed to minimize the traffic in
# dense clusters
- self.log.logger.debug("waiting for a lock.")
+ self.log.logger.debug('waiting for a lock.')
self.system.lock.acquire()
- self.log.logger.debug("lock acquired.")
+ self.log.logger.debug('lock acquired.')
if self.system.data_ready:
self.log.logger.info('data ready to be sent to the mgr.')
if not self.system.get_system() == self.system.previous_data:
self.data['patch'] = self.system.get_system()
try:
# TODO: add a timeout parameter to the reporter in the config file
- self.log.logger.info(f"sending data to {self.reporter_url}")
+ self.log.logger.info(f'sending data to {self.reporter_url}')
http_req(hostname=self.reporter_hostname,
port=self.reporter_port,
method='POST',
else:
self.log.logger.info('no diff, not sending data to the mgr.')
self.system.lock.release()
- self.log.logger.debug("lock released.")
+ self.log.logger.debug('lock released.')
time.sleep(5)
_tries = retries
while _tries > 1:
try:
- log.logger.debug("{} {} attempt(s) left.".format(f, _tries - 1))
+ log.logger.debug('{} {} attempt(s) left.'.format(f, _tries - 1))
return f(*args, **kwargs)
except exceptions:
time.sleep(delay)
_tries -= 1
- log.logger.warn("{} has failed after {} tries".format(f, retries))
+ log.logger.warn('{} has failed after {} tries'.format(f, retries))
return f(*args, **kwargs)
return _retry
return decorator