async def receive(request): Log.debug(f"Received GET request for component " \ f"{request.rel_url.query['component']}") try: component = request.rel_url.query['component'] EventMessage.subscribe(component=component) alert = EventMessage.receive() except EventMessageError as e: status_code = e.rc error_message = e.desc Log.error(f"Unable to receive event message for component: " \ f"{component}, status code: {status_code}," \ f" error: {error_message}") response_obj = {'error_code': status_code, 'exception': \ ['EventMessageError', {'message': error_message}]} except Exception as e: exception_key = type(e).__name__ exception = RestServerError(exception_key).http_error() status_code = exception[0] error_message = exception[1] Log.error(f"Internal error while receiving event messages for " \ f"component: {component}, status code: " \ f"{status_code}, error: {error_message}") response_obj = {'error_code': status_code, 'exception': \ [exception_key, {'message': error_message}]} raise EventMessageError(status_code, error_message) from e else: status_code = 200 # No exception, Success response_obj = {'alert': alert} Log.debug(f"GET method finished with status code: {status_code}" \ f"for component {component} and received event message " \ f"alert info. - {alert['iem']['info']}.") finally: return web.Response(text=json.dumps(response_obj), \ status=status_code)
def test_alert_send(self): """ Test send alerts """ EventMessage.init(component='cmp', source='H', \ cluster_id=TestMessage._cluster_id, \ message_server_endpoints=TestMessage._message_server_endpoints) EventMessage.send(module='mod', event_id='500', severity='B', \ message_blob='This is message')
def test_json_alert_send(self): """ Test send json as message description """ EventMessage.init(component='cmp', source='H', \ cluster_id=TestMessage._cluster_id, \ message_server_endpoints=TestMessage._message_server_endpoints) EventMessage.send(module='mod', event_id='500', severity='B', \ message_blob={'input': 'This is message'})
def test_bulk_alert_send(self): """ Test bulk send alerts """ EventMessage.init(component='cmp', source='H', \ cluster_id=TestMessage._cluster_id, \ message_server_endpoints=TestMessage._message_server_endpoints) for alert_count in range(0, 1000): EventMessage.send(module='mod', event_id='500', severity='B', \ message_blob='test_bulk_message' + str(alert_count))
def init(args): EventMessage.init(component='sspl', source='S') # Check existing iem alert present in MessageBus EventMessage.subscribe(component='sspl') while True: msg = EventMessage.receive() if msg is None: break
def test_init_validation(self): """ Validate init attributes """ with self.assertRaises(EventMessageError): EventMessage.init(component=None, source='H', \ cluster_id=TestMessage._cluster_id, \ message_server_endpoints=TestMessage._message_server_endpoints) EventMessage.init(component=None, source='I', \ cluster_id=TestMessage._cluster_id, \ message_server_endpoints=TestMessage._message_server_endpoints)
def test_bulk_verify_receive(self): """ Test bulk receive alerts """ EventMessage.init(component='cmp', source='H', receiver=True) count = 0 while True: alert = EventMessage.receive() if alert is None: break self.assertIs(type(alert), dict) count += 1 self.assertEqual(count, 1000)
def receive(self, component): """Receive the incoming message.""" EventMessage.subscribe(component) try: alert = EventMessage.receive() self._logger.DEBUG("Received message --> ", alert) except Exception as exception: self._logger.ERROR("Exception : ", exception) return False return True
def test_validate_without_optional_params(self): """ Validate without optional params of send attributes """ EventMessage.send(module='mod', event_id='500', severity='B', \ message_blob={'input': 'This is message'}) alert = EventMessage.receive() self.assertEqual(alert['iem']['location']['site_id'], \ alert['iem']['source']['site_id']) self.assertEqual(alert['iem']['location']['node_id'], \ alert['iem']['source']['node_id']) self.assertEqual(alert['iem']['location']['rack_id'], \ alert['iem']['source']['rack_id'])
def generate_iem(module, event_code, severity, description): """Generate iem and send it to a MessgaeBroker.""" try: logger.info(f"Sending IEM alert for module:{module}" f" and event_code:{event_code}") EventMessage.send(module=module, event_id=event_code, severity=severity, message_blob=description) except EventMessageError as e: logger.error("Failed to send IEM alert." f"Error:{e}")
def send(self, module, event_id, severity, message_blob): """Send the message.""" try: EventMessage.send(module='S3 BG delete', event_id=event_id, severity=severity, message_blob=message_blob) except Exception as exception: self._logger.ERROR("Exception : ", exception) return False return True
def test_bulk_verify_receive(self): """ Test bulk receive alerts """ EventMessage.subscribe(component='cmp', \ message_server_endpoints=TestMessage._message_server_endpoints) count = 0 while True: alert = EventMessage.receive() if alert is None: break self.assertIs(type(alert), dict) if 'test_bulk_message' in alert['iem']['contents']['message']: count += 1 self.assertEqual(count, 1000)
def __init__(self, logger, loglevel, eventcode, eventstring): """Init.""" self.eventCode = eventcode self.loglevel = loglevel self.eventString = eventstring self._logger = logger EventMessage.init(self.component, self.source) if (loglevel == "INFO"): self.severity = "I" if (loglevel == "WARN"): self.severity = "W" if (loglevel == "ERROR"): self.severity = "E" self.log_iem()
def raise_iem_event(module, event_code, severity, description): """Send IEM message.""" # check if IEM Framework initialized, # if not, retry initializing the IEM Framework if os.path.exists(IEM_INIT_FAILED): with open(IEM_INIT_FAILED, 'r') as f: sspl_pid = f.read() if sspl_pid and psutil.pid_exists(int(sspl_pid)): EventMessage.init(component='sspl', source='S') logger.info("IEM framework initialization completed!!") os.remove(IEM_INIT_FAILED) EventMessage.send(module=module, event_id=event_code, severity=severity, message_blob=description)
def test_iem_alerts(self): """Test iem 'ipmitool' fault alert receive.""" check_sspl_ll_is_running() Iem().iem_fault("IPMITOOL_ERROR") time.sleep(10) EventMessage.subscribe(component='sspl') fault_alert = EventMessage.receive() print(f"IEM Received:{fault_alert}") assert (fault_alert is not None) assert (fault_alert["iem"]["info"]["severity"] is not None) assert (fault_alert["iem"]["info"]["type"] is not None) assert (fault_alert["iem"]["info"]["event_time"] is not None) assert (fault_alert["iem"]["source"]["module"] is not None) assert (fault_alert["iem"]["contents"]["event"] is not None)
def test_send_validation(self): """ Validate send attributes """ with self.assertRaises(EventMessageError): EventMessage.send(module=None, event_id='500', severity='B', \ message_blob='This is message') EventMessage.send(module='mod', event_id=None, severity='B', \ message_blob='This is message') EventMessage.send(module='mod', event_id='500', severity='Z', \ message_blob='This is message') EventMessage.send(module='mod', event_id='500', severity='Z', \ message_blob=None)
def generate_iem(module, event_code, severity, description): """Generate iem and send it to a MessgaeBroker.""" try: logger.info(f"Sending IEM alert for module:{module}" f" and event_code:{event_code}") # check if IEM Framework initialized, # if not, retry initializing the IEM Frameowork if os.path.exists(IEM_INIT_FAILED): with open(IEM_INIT_FAILED, 'r') as f: sspl_pid = f.read() if sspl_pid and psutil.pid_exists(int(sspl_pid)): EventMessage.init(component='sspl', source='S') logger.info("IEM framework initialization completed!!") os.remove(IEM_INIT_FAILED) EventMessage.send(module=module, event_id=event_code, severity=severity, message_blob=description) except EventMessageError as e: logger.error("Failed to send IEM alert." f"Error:{e}")
async def send(request): try: payload = await request.json() component = payload['component'] source = payload['source'] EventMessage.init(component=component, source=source,\ cluster_id=IemRequestHandler.cluster_id,\ message_server_endpoints=IemRequestHandler.message_server_endpoints) del payload['component'] del payload['source'] EventMessage.send(**payload) except EventMessageError as e: status_code = e.rc error_message = e.desc Log.error(f"Unable to send event message for component: " \ f"{component}, status code: {status_code}," \ f" error: {error_message}") response_obj = {'error_code': status_code, 'exception': \ ['EventMessageError', {'message': error_message}]} except Exception as e: exception_key = type(e).__name__ exception = RestServerError(exception_key).http_error() status_code = exception[0] error_message = exception[1] Log.error(f"Internal error while sending event messages for " \ f"component: {component}, status code: " \ f"{status_code}, error: {error_message}") response_obj = {'error_code': status_code, 'exception': \ [exception_key, {'message': error_message}]} raise EventMessageError(status_code, error_message) from e else: status_code = 200 # No exception, Success response_obj = {'status_code': status_code, 'status': 'success'} Log.debug(f"POST method finished for component: {component} " f"and source: {source}, with status code: {status_code}") finally: return web.Response(text=json.dumps(response_obj), \ status=status_code)
def test_init_validation(self): """ Validate init attributes """ with self.assertRaises(EventMessageError): EventMessage.init(component=None, source='H') EventMessage.init(component='cmp', source='I')
def test_receive_without_send(self): """ Receive message without send """ EventMessage.subscribe(component='cmp', \ message_server_endpoints=TestMessage._message_server_endpoints) alert = EventMessage.receive() self.assertIsNone(alert)
def test_alert_fail_send(self): """ Send message without initialising """ with self.assertRaises(EventMessageError): EventMessage.send(module='mod', event_id='500', severity='B', \ message_blob='This is message')
def test_alert_fail_receive(self): """ Receive message without subscribing """ with self.assertRaises(EventMessageError): EventMessage.receive()
def test_alert_verify_receive(self): """ Test receive alerts """ EventMessage.subscribe(component='cmp', \ message_server_endpoints=TestMessage._message_server_endpoints) alert = EventMessage.receive() self.assertIs(type(alert), dict)
def test_receive_fail(self): """ Receive message with receiver as False """ EventMessage.init(component='cmp', source='H') with self.assertRaises(KeyError): EventMessage.receive()
def test_bulk_alert_send(self): """ Test bulk send alerts """ EventMessage.init(component='cmp', source='H') for alert_count in range(0, 1000): EventMessage.send(module='mod', event_id='500', severity='B', \ message='This is message' + str(alert_count))
def test_send_fail(self): """ Send message with receiver as True """ EventMessage.init(component='cmp', source='H', receiver=True) with self.assertRaises(NameError): EventMessage.send(module='mod', event_id='500', severity='B', \ message='This is message')
def test_subscribe_validation(self): with self.assertRaises(EventMessageError): EventMessage.subscribe(component=None, \ message_server_endpoints=TestMessage._message_server_endpoints)
def test_receive_without_send(self): """ Receive message without send """ EventMessage.init(component='cmp', source='H', receiver=True) alert = EventMessage.receive() self.assertIsNone(alert)
def test_json_verify_receive(self): """ Test receive json as message description """ EventMessage.init(component='cmp', source='H', receiver=True) alert = EventMessage.receive() self.assertIs(type(alert), dict)
def test_json_alert_send(self): """ Test send json as message description """ EventMessage.init(component='cmp', source='H') EventMessage.send(module='mod', event_id='500', severity='B', \ message={'input': 'This is message'})