MON vROPs plugin patch for minor fixes found during testing 46/5746/3
authorbhangare <sbhangare@vmware.com>
Fri, 1 Dec 2017 05:18:59 +0000 (21:18 -0800)
committerbhangare <sbhangare@vmware.com>
Tue, 5 Dec 2017 17:43:30 +0000 (19:43 +0200)
Change-Id: I05f5d4e88b05e5134928cd6601e029e35bb3804b
Signed-off-by: bhangare <sbhangare@vmware.com>
osm_mon/plugins/vRealiseOps/mon_plugin_vrops.py
osm_mon/plugins/vRealiseOps/plugin_receiver.py
osm_mon/plugins/vRealiseOps/vROPs_Webservice/vrops_webservice

index 309cec9..bf1dfce 100644 (file)
@@ -131,8 +131,16 @@ class MonPlugin():
         if not metric_key_params:
             self.logger.warn("Metric not supported: {}".format(config_dict['metric_name']))
             return None
-        #2) create symptom definition
+
+        #1.2) Check if alarm definition already exists
         vrops_alarm_name = def_a_params['vrops_alarm']+ '-' + config_dict['resource_uuid']
+        alert_def_list = self.get_alarm_defination_by_name(vrops_alarm_name)
+        if alert_def_list:
+            self.logger.warn("Alarm already exists: {}. Try updating by update_alarm_request"\
+                            .format(vrops_alarm_name))
+            return None
+
+        #2) create symptom definition
         symptom_params ={'cancel_cycles': (def_a_params['cancel_period']/300)*def_a_params['cancel_cycles'],
                         'wait_cycles': (def_a_params['period']/300)*def_a_params['evaluation'],
                         'resource_kind_key': def_a_params['resource_kind'],
@@ -152,7 +160,7 @@ class MonPlugin():
         #To Do - Get type & subtypes for all 5 alarms
         alarm_params = {'name':vrops_alarm_name,
                         'description':config_dict['description']\
-                        if config_dict['description'] is not None else config_dict['alarm_name'],
+                        if config_dict.has_key('description') and config_dict['description'] is not None else config_dict['alarm_name'],
                         'adapterKindKey':def_a_params['adapter_kind'],
                         'resourceKindKey':def_a_params['resource_kind'],
                         'waitCycles':1, 'cancelCycles':1,
@@ -725,20 +733,20 @@ class MonPlugin():
             'metric_name': Normalized name of metric (string)
             'resource_uuid': Resource UUID (string)
             'tenant_id': tenent id name in which the resource is present in string format
-            'metrics_data': Dictionary containing time_series & metric_series data.
+            'metrics_data': Dictionary containing time_series & metrics_series data.
                 'time_series': List of individual time stamp values in msec
-                'metric_series': List of individual metrics data values
+                'metrics_series': List of individual metrics data values
         Raises an exception upon error or when network is not found
         """
         return_data = {}
-        return_data['schema_version'] = 1.0
+        return_data['schema_version'] = "1.0"
         return_data['schema_type'] = 'read_metric_data_response'
         return_data['metric_name'] = metric['metric_name']
         #To do - No metric_uuid in vROPs, thus returning '0'
         return_data['metric_uuid'] = '0'
         return_data['correlation_id'] = metric['correlation_id']
         return_data['resource_uuid'] = metric['resource_uuid']
-        return_data['metrics_data'] = {'time_series':[], 'metric_series':[]}
+        return_data['metrics_data'] = {'time_series':[], 'metrics_series':[]}
         #To do - Need confirmation about uuid & id
         if 'tenant_uuid' in metric and metric['tenant_uuid'] is not None:
             return_data['tenant_uuid'] = metric['tenant_uuid']
@@ -810,7 +818,7 @@ class MonPlugin():
                                 if stat_keys == 'timestamps':
                                     metrics_data['time_series'] = stat_list_v[0]['timestamps']
                                 if stat_keys == 'data':
-                                    metrics_data['metric_series'] = stat_list_v[0]['data']
+                                    metrics_data['metrics_series'] = stat_list_v[0]['data']
 
         return_data['metrics_data'] = metrics_data
 
@@ -819,6 +827,9 @@ class MonPlugin():
     def update_alarm_configuration(self, new_alarm_config):
         """Update alarm configuration (i.e. Symptom & alarm) as per request
         """
+        if new_alarm_config.get('alarm_uuid') is None:
+            self.logger.warn("alarm_uuid is required to update an Alarm")
+            return None
         #1) Get Alarm details from it's uuid & find the symptom defination
         alarm_details_json, alarm_details = self.get_alarm_defination_details(new_alarm_config['alarm_uuid'])
         if alarm_details_json is None:
@@ -879,13 +890,51 @@ class MonPlugin():
                 alarm_details['type'] = json_data['type']
                 alarm_details['sub_type'] = json_data['subType']
                 alarm_details['symptom_definition_id'] = json_data['states'][0]['base-symptom-set']['symptomDefinitionIds'][0]
-        except exception as exp:
+        except Exception as exp:
             self.logger.warn("Exception while retriving alarm defination details: {}".format(exp))
             return None, None
 
         return json_data, alarm_details
 
 
+    def get_alarm_defination_by_name(self, alarm_name):
+        """Get alarm details based on alarm name
+        """
+        status = False
+        alert_match_list = []
+
+        if alarm_name is None:
+            self.logger.warn("get_alarm_defination_by_name: Alarm name not provided")
+            return alert_match_list
+
+        json_data = {}
+        api_url = '/suite-api/api/alertdefinitions'
+        headers = {'Accept': 'application/json'}
+
+        resp = requests.get(self.vrops_site + api_url,
+                            auth=(self.vrops_user, self.vrops_password),
+                            verify = False, headers = headers)
+
+        if resp.status_code is not 200:
+            self.logger.warn("get_alarm_defination_by_name: Error in response: {}\nResponse code:{}"\
+                    "\nResponse Content: {}".format(alarm_name, resp.status_code, resp.content))
+            return alert_match_list
+
+        try:
+            json_data = json.loads(resp.content)
+            if json_data['alertDefinitions'] is not None:
+                alerts_list = json_data['alertDefinitions']
+                alert_match_list = filter(lambda alert: alert['name'] == alarm_name, alerts_list)
+                status = False if not alert_match_list else True
+                #self.logger.debug("Found alert_match_list: {}for larm_name: {},\nstatus: {}".format(alert_match_list, alarm_name,status))
+
+            return alert_match_list
+
+        except Exception as exp:
+            self.logger.warn("Exception while searching alarm defination: {}".format(exp))
+            return alert_match_list
+
+
     def update_symptom_defination(self, symptom_uuid, new_alarm_config):
         """Update symptom defination based on new alarm input configuration
         """
@@ -1130,7 +1179,8 @@ class MonPlugin():
         #TO Do - Need to add filtering of alarms based on Severity & alarm name
 
         triggered_alarms_list = []
-        if list_alarm_input['resource_uuid'] is None:
+        if list_alarm_input.get('resource_uuid') is None:
+            self.logger.warn("Resource UUID is required to get triggered alarms list")
             return triggered_alarms_list
 
         #1)Find vROPs resource ID using RO resource UUID
index 90b7480..c3a3aeb 100644 (file)
@@ -39,6 +39,7 @@ import traceback
 import os
 from xml.etree import ElementTree as XmlElementTree
 
+schema_version = "1.0"
 req_config_params = ('vrops_site', 'vrops_user', 'vrops_password',
                     'vcloud-site','admin_username','admin_password',
                     'vcenter_ip','vcenter_port','vcenter_user','vcenter_password',
@@ -165,7 +166,7 @@ class PluginReceiver():
         """
         topic = 'alarm_response'
         msg_key = 'create_alarm_response'
-        response_msg = {"schema_version":1.0,
+        response_msg = {"schema_version":schema_version,
                          "schema_type":"create_alarm_response",
                          "alarm_create_response":
                             {"correlation_id":config_alarm_info["alarm_create_request"]["correlation_id"],
@@ -190,11 +191,12 @@ class PluginReceiver():
         """
         topic = 'alarm_response'
         msg_key = 'update_alarm_response'
-        response_msg = {"schema_version":1.0,
+        response_msg = {"schema_version":schema_version,
                          "schema_type":"update_alarm_response",
                          "alarm_update_response":
                             {"correlation_id":update_alarm_info["alarm_update_request"]["correlation_id"],
-                             "alarm_uuid":alarm_uuid,
+                             "alarm_uuid":update_alarm_info["alarm_update_request"]["alarm_uuid"] \
+                             if update_alarm_info["alarm_update_request"].get('alarm_uuid') is not None else None,
                              "status": True if alarm_uuid else False
                             }
                        }
@@ -215,11 +217,11 @@ class PluginReceiver():
         """
         topic = 'alarm_response'
         msg_key = 'delete_alarm_response'
-        response_msg = {"schema_version":1.0,
+        response_msg = {"schema_version":schema_version,
                          "schema_type":"delete_alarm_response",
                          "alarm_deletion_response":
                             {"correlation_id":delete_alarm_info["alarm_delete_request"]["correlation_id"],
-                             "alarm_uuid":alarm_uuid,
+                             "alarm_uuid":delete_alarm_info["alarm_delete_request"]["alarm_uuid"],
                              "status": True if alarm_uuid else False
                             }
                        }
@@ -252,12 +254,12 @@ class PluginReceiver():
         """
         topic = 'metric_response'
         msg_key = 'create_metric_response'
-        response_msg = {"schema_version":1.0,
+        response_msg = {"schema_version":schema_version,
                          "schema_type":"create_metric_response",
                          "correlation_id":metric_info['correlation_id'],
                          "metric_create_response":
                             {
-                             "metric_uuid":0,
+                             "metric_uuid":'0',
                              "resource_uuid":metric_info['metric_create']['resource_uuid'],
                              "status":metric_status
                             }
@@ -272,12 +274,12 @@ class PluginReceiver():
         """
         topic = 'metric_response'
         msg_key = 'update_metric_response'
-        response_msg = {"schema_version":1.0,
+        response_msg = {"schema_version":schema_version,
                         "schema_type":"metric_update_response",
                         "correlation_id":metric_info['correlation_id'],
                         "metric_update_response":
                             {
-                             "metric_uuid":0,
+                             "metric_uuid":'0',
                              "resource_uuid":metric_info['metric_create']['resource_uuid'],
                              "status":metric_status
                             }
@@ -292,13 +294,18 @@ class PluginReceiver():
         """
         topic = 'metric_response'
         msg_key = 'delete_metric_response'
-        response_msg = {"schema_version":1.0,
+        if metric_info.has_key('tenant_uuid') and metric_info['tenant_uuid'] is not None:
+            tenant_uuid = metric_info['tenant_uuid']
+        else:
+            tenant_uuid = None
+
+        response_msg = {"schema_version":schema_version,
                         "schema_type":"delete_metric_response",
                         "correlation_id":metric_info['correlation_id'],
                         "metric_name":metric_info['metric_name'],
-                        "metric_uuid":0,
+                        "metric_uuid":'0',
                         "resource_uuid":metric_info['resource_uuid'],
-                        "tenant_uuid":metric_info['tenant_uuid'],
+                        "tenant_uuid":tenant_uuid,
                         "status":False
                        }
         self.logger.info("Publishing response:\nTopic={}\nKey={}\nValue={}"\
@@ -319,10 +326,9 @@ class PluginReceiver():
         """
         topic = 'alarm_response'
         msg_key = 'list_alarm_response'
-        response_msg = {"schema_version":1.0,
+        response_msg = {"schema_version":schema_version,
                         "schema_type":"list_alarm_response",
                         "correlation_id":list_alarm_input['alarm_list_request']['correlation_id'],
-                        #"resource_uuid":list_alarm_input['alarm_list_request']['resource_uuid'],
                         "list_alarm_resp":triggered_alarm_list
                        }
         self.logger.info("Publishing response:\nTopic={}\nKey={}\nValue={}"\
@@ -376,7 +382,7 @@ class PluginReceiver():
         """
         topic = 'access_credentials'
         msg_key = 'vim_access_credentials_response'
-        response_msg = {"schema_version":1.0,
+        response_msg = {"schema_version":schema_version,
                         "schema_type":"vim_access_credentials_response",
                         "correlation_id":access_info_req['access_config']['correlation_id'],
                         "status":access_update_status
index 98533f1..50b4928 100755 (executable)
@@ -193,7 +193,7 @@ def notify_alarm(alarmID):
         logger.info("Alarm details: {}".format(alarm_data))
 
         #Publish Alarm details
-        kafkaMsgProducer = KafkaProducer()
+        kafkaMsgProducer = KafkaProducer("alarm_response")
         kafkaMsgProducer.publish(topic='alarm_response', key='notify_alarm', value=alarm_data)
 
         #return 201 on Success