"""
import requests
-import logging as log
+import logging
from pyvcloud.vcloudair import VCA
from xml.etree import ElementTree as XmlElementTree
import traceback
from OpenSSL.crypto import load_certificate, FILETYPE_PEM
import os
import datetime
+from socket import gethostname
+
+from requests.packages.urllib3.exceptions import InsecureRequestWarning
+requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
OPERATION_MAPPING = {'GE':'GT_EQ', 'LE':'LT_EQ', 'GT':'GT', 'LT':'LT', 'EQ':'EQ'}
severity_mano2vrops = {'WARNING':'WARNING', 'MINOR':'WARNING', 'MAJOR':"IMMEDIATE",\
#To Do - Add actual webhook url & certificate
#SSL_CERTIFICATE_FILE_NAME = 'vROPs_Webservice/SSL_certificate/www.vrops_webservice.com.cert'
-webhook_url = "https://mano-dev-1:8080/notify/" #for testing
-SSL_CERTIFICATE_FILE_NAME = 'vROPs_Webservice/SSL_certificate/10.172.137.214.cert' #for testing
+#webhook_url = "https://mano-dev-1:8080/notify/" #for testing
+webhook_url = "https://" + gethostname() + ":8080/notify/"
+SSL_CERTIFICATE_FILE_NAME = ('vROPs_Webservice/SSL_certificate/' + gethostname() + ".cert")
+#SSL_CERTIFICATE_FILE_NAME = 'vROPs_Webservice/SSL_certificate/10.172.137.214.cert' #for testing
MODULE_DIR = os.path.dirname(__file__)
CONFIG_FILE_NAME = 'vrops_config.xml'
Returns: Raise an exception if some needed parameter is missing, but it must not do any connectivity
check against the VIM
"""
+ self.logger = logging.getLogger('PluginReceiver.MonPlugin')
+ self.logger.setLevel(logging.DEBUG)
+
access_config = self.get_default_Params('Access_Config')
self.access_config = access_config
if not bool(access_config):
- log.error("Access configuration not provided in vROPs Config file")
+ self.logger.error("Access configuration not provided in vROPs Config file")
raise KeyError("Access configuration not provided in vROPs Config file")
try:
self.admin_password = access_config['admin_password']
self.tenant_id = access_config['tenant_id']
except KeyError as exp:
- log.error("Check Access configuration in vROPs Config file: {}".format(exp))
+ self.logger.error("Check Access configuration in vROPs Config file: {}".format(exp))
raise KeyError("Check Access configuration in vROPs Config file: {}".format(exp))
#1) get alarm & metrics parameters from plugin specific file
def_a_params = self.get_default_Params(config_dict['alarm_name'])
if not def_a_params:
- log.warn("Alarm not supported: {}".format(config_dict['alarm_name']))
+ self.logger.warn("Alarm not supported: {}".format(config_dict['alarm_name']))
return None
metric_key_params = self.get_default_Params(config_dict['metric_name'])
if not metric_key_params:
- log.warn("Metric not supported: {}".format(config_dict['metric_name']))
+ self.logger.warn("Metric not supported: {}".format(config_dict['metric_name']))
return None
#2) create symptom definition
vrops_alarm_name = def_a_params['vrops_alarm']+ '-' + config_dict['resource_uuid']
'threshold_value':config_dict['threshold_value']}
symptom_uuid = self.create_symptom(symptom_params)
if symptom_uuid is not None:
- log.info("Symptom defined: {} with ID: {}".format(symptom_params['symptom_name'],symptom_uuid))
+ self.logger.info("Symptom defined: {} with ID: {}".format(symptom_params['symptom_name'],symptom_uuid))
else:
- log.warn("Failed to create Symptom: {}".format(symptom_params['symptom_name']))
+ self.logger.warn("Failed to create Symptom: {}".format(symptom_params['symptom_name']))
return None
#3) create alert definition
#To Do - Get type & subtypes for all 5 alarms
alarm_def = self.create_alarm_definition(alarm_params)
if alarm_def is None:
- log.warn("Failed to create Alert: {}".format(alarm_params['name']))
+ self.logger.warn("Failed to create Alert: {}".format(alarm_params['name']))
return None
- log.info("Alarm defined: {} with ID: {}".format(alarm_params['name'],alarm_def))
+ self.logger.info("Alarm defined: {} with ID: {}".format(alarm_params['name'],alarm_def))
#4) Find vm_moref_id from vApp uuid in vCD
vm_moref_id = self.get_vm_moref_id(config_dict['resource_uuid'])
if vm_moref_id is None:
- log.warn("Failed to find vm morefid for vApp in vCD: {}".format(config_dict['resource_uuid']))
+ self.logger.warn("Failed to find vm morefid for vApp in vCD: {}".format(config_dict['resource_uuid']))
return None
#5) Based on vm_moref_id, find VM's corresponding resource_id in vROPs to set notification
resource_id = self.get_vm_resource_id(vm_moref_id)
if resource_id is None:
- log.warn("Failed to find resource in vROPs: {}".format(config_dict['resource_uuid']))
+ self.logger.warn("Failed to find resource in vROPs: {}".format(config_dict['resource_uuid']))
return None
#6) Configure alarm notification for a particular VM using it's resource_id
return None
else:
alarm_def_uuid = alarm_def.split('-', 1)[1]
- log.info("Alarm defination created with notification: {} with ID: {}"\
+ self.logger.info("Alarm defination created with notification: {} with ID: {}"\
.format(alarm_params['name'],alarm_def_uuid))
#Return alarm defination UUID by removing 'AlertDefinition' from UUID
return (alarm_def_uuid)
except IOError as exp:
msg = ("Could not read Config file: {}, \nException: {}"\
.format(CONFIG_FILE_PATH, exp))
- log.error(msg)
+ self.logger.error(msg)
raise IOError(msg)
tree = XmlElementTree.parse(source)
data=data)
if resp.status_code != 201:
- log.warn("Failed to create Symptom definition: {}, response {}"\
+ self.logger.warn("Failed to create Symptom definition: {}, response {}"\
.format(symptom_params['symptom_name'], resp.content))
return None
return symptom_id
except Exception as exp:
- log.warn("Error creating symptom definition : {}\n{}"\
+ self.logger.warn("Error creating symptom definition : {}\n{}"\
.format(exp, traceback.format_exc()))
data=data)
if resp.status_code != 201:
- log.warn("Failed to create Alarm definition: {}, response {}"\
+ self.logger.warn("Failed to create Alarm definition: {}, response {}"\
.format(alarm_params['name'], resp.content))
return None
return alarm_uuid
except Exception as exp:
- log.warn("Error creating alarm definition : {}\n{}".format(exp, traceback.format_exc()))
+ self.logger.warn("Error creating alarm definition : {}\n{}".format(exp, traceback.format_exc()))
def configure_rest_plugin(self):
cert_file_string = open(SSL_CERTIFICATE_FILE_PATH, "rb").read()
except IOError as exp:
msg = ("Could not read SSL certificate file: {}".format(SSL_CERTIFICATE_FILE_PATH))
- log.error(msg)
+ self.logger.error(msg)
raise IOError(msg)
cert = load_certificate(FILETYPE_PEM, cert_file_string)
certificate = cert.digest("sha1")
<ops:name>{0:s}</ops:name>
<ops:configValues>
<ops:configValue name="Url">{1:s}</ops:configValue>
- <ops:configValue name="Content-type">application/xml</ops:configValue>
+ <ops:configValue name="Content-type">application/json</ops:configValue>
<ops:configValue name="Certificate">{2:s}</ops:configValue>
<ops:configValue name="ConnectionCount">20</ops:configValue>
</ops:configValues>
data=data)
if resp.status_code is not 201:
- log.warn("Failed to create REST Plugin: {} for url: {}, \nresponse code: {},"\
+ self.logger.warn("Failed to create REST Plugin: {} for url: {}, \nresponse code: {},"\
"\nresponse content: {}".format(plugin_name, webhook_url,\
resp.status_code, resp.content))
return None
plugin_id = plugin_xmlroot.find('{http://webservice.vmware.com/vRealizeOpsMgr/1.0/}pluginId').text
if plugin_id is None:
- log.warn("Failed to get REST Plugin ID for {}, url: {}".format(plugin_name, webhook_url))
+ self.logger.warn("Failed to get REST Plugin ID for {}, url: {}".format(plugin_name, webhook_url))
return None
else:
- log.info("Created REST Plugin: {} with ID : {} for url: {}".format(plugin_name, plugin_id, webhook_url))
+ self.logger.info("Created REST Plugin: {} with ID : {} for url: {}".format(plugin_name, plugin_id, webhook_url))
status = self.enable_rest_plugin(plugin_id, plugin_name)
if status is False:
- log.warn("Failed to enable created REST Plugin: {} for url: {}".format(plugin_name, webhook_url))
+ self.logger.warn("Failed to enable created REST Plugin: {} for url: {}".format(plugin_name, webhook_url))
return None
else:
- log.info("Enabled REST Plugin: {} for url: {}".format(plugin_name, webhook_url))
+ self.logger.info("Enabled REST Plugin: {} for url: {}".format(plugin_name, webhook_url))
return plugin_id
def check_if_plugin_configured(self, plugin_name):
verify = False, headers = headers)
if resp.status_code is not 200:
- log.warn("Failed to REST GET Alarm plugin details \nResponse code: {}\nResponse content: {}"\
+ self.logger.warn("Failed to REST GET Alarm plugin details \nResponse code: {}\nResponse content: {}"\
.format(resp.status_code, resp.content))
return None
plugin_id = notify_plugin.find('params:pluginId',namespace).text
if plugin_id is None:
- log.warn("REST plugin {} not found".format('MON_module_REST_Plugin'))
+ self.logger.warn("REST plugin {} not found".format('MON_module_REST_Plugin'))
return None
else:
- log.info("Found REST Plugin: {}".format(plugin_name))
+ self.logger.info("Found REST Plugin: {}".format(plugin_name))
return plugin_id
"""
if plugin_id is None or plugin_name is None:
- log.debug("enable_rest_plugin() : Plugin ID or plugin_name not provided for {} plugin"\
+ self.logger.debug("enable_rest_plugin() : Plugin ID or plugin_name not provided for {} plugin"\
.format(plugin_name))
return False
verify = False)
if resp.status_code is not 204:
- log.warn("Failed to enable REST plugin {}. \nResponse code {}\nResponse Content: {}"\
+ self.logger.warn("Failed to enable REST plugin {}. \nResponse code {}\nResponse Content: {}"\
.format(plugin_name, resp.status_code, resp.content))
return False
- log.info("Enabled REST plugin {}.".format(plugin_name))
+ self.logger.info("Enabled REST plugin {}.".format(plugin_name))
return True
except Exception as exp:
- log.warn("Error enabling REST plugin for {} plugin: Exception: {}\n{}"\
+ self.logger.warn("Error enabling REST plugin for {} plugin: Exception: {}\n{}"\
.format(plugin_name, exp, traceback.format_exc()))
def create_alarm_notification_rule(self, alarm_name, alarm_id, resource_id):
#1) Find the REST Plugin id details for - MON_module_REST_Plugin
plugin_id = self.check_if_plugin_configured(plugin_name)
if plugin_id is None:
- log.warn("Failed to get REST plugin_id for : {}".format('MON_module_REST_Plugin'))
+ self.logger.warn("Failed to get REST plugin_id for : {}".format('MON_module_REST_Plugin'))
return None
#2) Create Alarm notification rule
data=data)
if resp.status_code is not 201:
- log.warn("Failed to create Alarm notification rule {} for {} alarm."\
+ self.logger.warn("Failed to create Alarm notification rule {} for {} alarm."\
"\nResponse code: {}\nResponse content: {}"\
.format(notification_name, alarm_name, resp.status_code, resp.content))
return None
if xmlroot_resp is not None and 'id' in xmlroot_resp.attrib:
notification_id = xmlroot_resp.attrib.get('id')
- log.info("Created Alarm notification rule {} for {} alarm.".format(notification_name, alarm_name))
+ self.logger.info("Created Alarm notification rule {} for {} alarm.".format(notification_name, alarm_name))
return notification_id
def get_vm_moref_id(self, vapp_uuid):
if vm_details and "vm_vcenter_info" in vm_details:
vm_moref_id = vm_details["vm_vcenter_info"].get("vm_moref_id", None)
- log.info("Found vm_moref_id: {} for vApp UUID: {}".format(vm_moref_id, vapp_uuid))
+ self.logger.info("Found vm_moref_id: {} for vApp UUID: {}".format(vm_moref_id, vapp_uuid))
return vm_moref_id
except Exception as exp:
- log.warn("Error occurred while getting VM moref ID for VM : {}\n{}"\
+ self.logger.warn("Error occurred while getting VM moref ID for VM : {}\n{}"\
.format(exp, traceback.format_exc()))
vca = self.connect_as_admin()
if not vca:
- log.warn("connect() to vCD is failed")
+ self.logger.warn("connect() to vCD is failed")
if vapp_uuid is None:
return None
verify=vca.verify)
if response.status_code != 200:
- log.warn("REST API call {} failed. Return status code {}"\
+ self.logger.warn("REST API call {} failed. Return status code {}"\
.format(get_vapp_restcall, response.content))
return parsed_respond
parsed_respond["vm_vcenter_info"]= vm_vcenter_info
except Exception as exp :
- log.warn("Error occurred calling rest api for getting vApp details: {}\n{}"\
+ self.logger.warn("Error occurred calling rest api for getting vApp details: {}\n{}"\
.format(exp, traceback.format_exc()))
return parsed_respond
The return vca object that letter can be used to connect to vcloud direct as admin for provider vdc
"""
- log.info("Logging in to a VCD org as admin.")
+ self.logger.info("Logging in to a VCD org as admin.")
vca_admin = VCA(host=self.vcloud_site,
username=self.admin_username,
log=False)
result = vca_admin.login(password=self.admin_password, org='System')
if not result:
- log.warn("Can't connect to a vCloud director as: {}".format(self.admin_username))
+ self.logger.warn("Can't connect to a vCloud director as: {}".format(self.admin_username))
result = vca_admin.login(token=vca_admin.token, org='System', org_url=vca_admin.vcloud_session.org_url)
if result is True:
- log.info("Successfully logged to a vcloud direct org: {} as user: {}"\
+ self.logger.info("Successfully logged to a vcloud direct org: {} as user: {}"\
.format('System', self.admin_username))
return vca_admin
verify = False, headers = headers)
if resp.status_code is not 200:
- log.warn("Failed to get resource details from vROPs for {}\nResponse code:{}\nResponse Content: {}"\
+ self.logger.warn("Failed to get resource details from vROPs for {}\nResponse code:{}\nResponse Content: {}"\
.format(vm_moref_id, resp.status_code, resp.content))
return None
resourceIdentifiers = child
for r_id in resourceIdentifiers:
if r_id.find('params:value',namespace).text == vm_moref_id:
- log.info("Found Resource ID : {} in vROPs for {}"\
+ self.logger.info("Found Resource ID : {} in vROPs for {}"\
.format(resource.attrib['identifier'], vm_moref_id))
return resource.attrib['identifier']
except Exception as exp:
- log.warn("Error in parsing {}\n{}".format(exp, traceback.format_exc()))
+ self.logger.warn("Error in parsing {}\n{}".format(exp, traceback.format_exc()))
def get_metrics_data(self, metric={}):
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 metric_name
- return_data['metric_uuid'] = 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':[]}
#To do - Need confirmation about uuid & id
- return_data['tenant_uuid'] = metric['tenant_uuid']
+ if 'tenant_uuid' in metric and metric['tenant_uuid'] is not None:
+ return_data['tenant_uuid'] = metric['tenant_uuid']
+ else:
+ return_data['tenant_uuid'] = None
return_data['unit'] = None
#return_data['tenant_id'] = self.tenant_id
- #log.warn("return_data: {}".format(return_data))
+ #self.logger.warn("return_data: {}".format(return_data))
#1) Get metric details from plugin specific file & format it into vROPs metrics
metric_key_params = self.get_default_Params(metric['metric_name'])
if not metric_key_params:
- log.warn("Metric not supported: {}".format(metric['metric_name']))
+ self.logger.warn("Metric not supported: {}".format(metric['metric_name']))
#To Do: Return message
return return_data
#2.a) Find vm_moref_id from vApp uuid in vCD
vm_moref_id = self.get_vm_moref_id(metric['resource_uuid'])
if vm_moref_id is None:
- log.warn("Failed to find vm morefid for vApp in vCD: {}".format(config_dict['resource_uuid']))
+ self.logger.warn("Failed to find vm morefid for vApp in vCD: {}".format(config_dict['resource_uuid']))
return return_data
#2.b) Based on vm_moref_id, find VM's corresponding resource_id in vROPs to set notification
resource_id = self.get_vm_resource_id(vm_moref_id)
if resource_id is None:
- log.warn("Failed to find resource in vROPs: {}".format(config_dict['resource_uuid']))
+ self.logger.warn("Failed to find resource in vROPs: {}".format(config_dict['resource_uuid']))
return return_data
#3) Calculate begin & end time for period & period unit
begin_time = end_time - time_diff
#4) Get the metrics data
- log.info("metric_key_params['metric_key'] = {}".format(metric_key_params['metric_key']))
- log.info("end_time: {}, begin_time: {}".format(end_time, begin_time))
+ self.logger.info("metric_key_params['metric_key'] = {}".format(metric_key_params['metric_key']))
+ self.logger.info("end_time: {}, begin_time: {}".format(end_time, begin_time))
url_list = ['/suite-api/api/resources/', resource_id, '/stats?statKey=',\
metric_key_params['metric_key'], '&begin=', str(begin_time),'&end=',str(end_time)]
verify = False, headers = headers)
if resp.status_code is not 200:
- log.warn("Failed to retrive Metric data from vROPs for {}\nResponse code:{}\nResponse Content: {}"\
+ self.logger.warn("Failed to retrive Metric data from vROPs for {}\nResponse code:{}\nResponse Content: {}"\
.format(metric['metric_name'], resp.status_code, resp.content))
return return_data
if alarm_details['alarm_id'] is not None and alarm_details['symptom_definition_id'] is not None:
symptom_defination_id = alarm_details['symptom_definition_id']
else:
- log.info("Symptom Defination ID not found for {}".format(new_alarm_config['alarm_uuid']))
+ self.logger.info("Symptom Defination ID not found for {}".format(new_alarm_config['alarm_uuid']))
return None
symptom_uuid = self.update_symptom_defination(symptom_defination_id, new_alarm_config)
#3) Update the alarm defination & Return UUID if successful update
if symptom_uuid is None:
+ self.logger.info("Symptom Defination details not found for {}"\
+ .format(new_alarm_config['alarm_uuid']))
return None
else:
alarm_uuid = self.reconfigure_alarm(alarm_details_json, new_alarm_config)
else:
return alarm_uuid
except:
- log.error("Exception while updating alarm: {}".format(traceback.format_exc()))
+ self.logger.error("Exception while updating alarm: {}".format(traceback.format_exc()))
def get_alarm_defination_details(self, alarm_uuid):
"""Get alarm details based on alarm UUID
"""
if alarm_uuid is None:
- log.warn("get_alarm_defination_details: Alarm UUID not provided")
- return None
+ self.logger.warn("get_alarm_defination_details: Alarm UUID not provided")
+ return None, None
alarm_details = {}
json_data = {}
verify = False, headers = headers)
if resp.status_code is not 200:
- log.warn("Failed to get alarm details from vROPs for {}\nResponse code:{}\nResponse Content: {}"\
+ self.logger.warn("Alarm to be updated not found: {}\nResponse code:{}\nResponse Content: {}"\
.format(alarm_uuid, resp.status_code, resp.content))
- return None
+ return None, None
try:
json_data = json.loads(resp.content)
alarm_details['alarm_name'] = json_data['name']
alarm_details['adapter_kind'] = json_data['adapterKindKey']
alarm_details['resource_kind'] = json_data['resourceKindKey']
- alarm_details['type'] = ['type']
+ 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:
- log.warn("Exception while retriving alarm defination details: {}".format(exp))
+ self.logger.warn("Exception while retriving alarm defination details: {}".format(exp))
+ return None, None
return json_data, alarm_details
if new_alarm_config.has_key('metric_name') and new_alarm_config['metric_name'] is not None:
metric_key_params = self.get_default_Params(new_alarm_config['metric_name'])
if not metric_key_params:
- log.warn("Metric not supported: {}".format(config_dict['metric_name']))
+ self.logger.warn("Metric not supported: {}".format(config_dict['metric_name']))
return None
symptom_details['state']['condition']['key'] = metric_key_params['metric_key']
"""
- log.info("Fetched Symptom details : {}".format(symptom_details))
+ self.logger.info("Fetched Symptom details : {}".format(symptom_details))
api_url = '/suite-api/api/symptomdefinitions'
headers = {'Content-Type': 'application/json', 'Accept':'application/json'}
data=data)
if resp.status_code != 200:
- log.warn("Failed to update Symptom definition: {}, response {}"\
+ self.logger.warn("Failed to update Symptom definition: {}, response {}"\
.format(symptom_uuid, resp.content))
return None
if symptom_uuid is not None:
- log.info("Symptom defination updated {} for alarm: {}"\
+ self.logger.info("Symptom defination updated {} for alarm: {}"\
.format(symptom_uuid, new_alarm_config['alarm_uuid']))
return symptom_uuid
else:
- log.warn("Failed to update Symptom Defination {} for : {}"\
+ self.logger.warn("Failed to update Symptom Defination {} for : {}"\
.format(symptom_uuid, new_alarm_config['alarm_uuid']))
return None
"""
symptom_details = {}
if symptom_uuid is None:
- log.warn("get_symptom_defination_details: Symptom UUID not provided")
+ self.logger.warn("get_symptom_defination_details: Symptom UUID not provided")
return None
api_url = '/suite-api/api/symptomdefinitions/'
verify = False, headers = headers)
if resp.status_code is not 200:
- log.warn("Failed to get symptom details for {} \nResponse code:{}\nResponse Content: {}"\
+ self.logger.warn("Symptom defination not found {} \nResponse code:{}\nResponse Content: {}"\
.format(symptom_uuid, resp.status_code, resp.content))
return None
"""
if new_alarm_config.has_key('severity') and new_alarm_config['severity'] is not None:
alarm_details_json['states'][0]['severity'] = new_alarm_config['severity']
+ if new_alarm_config.has_key('description') and new_alarm_config['description'] is not None:
+ alarm_details_json['description'] = new_alarm_config['description']
api_url = '/suite-api/api/alertdefinitions'
headers = {'Content-Type': 'application/json', 'Accept':'application/json'}
data=data)
if resp.status_code != 200:
- log.warn("Failed to create Symptom definition: {}, response code {}, response content: {}"\
+ self.logger.warn("Failed to create Symptom definition: {}, response code {}, response content: {}"\
.format(symptom_uuid, resp.status_code, resp.content))
return None
else:
parsed_alarm_details = json.loads(resp.content)
alarm_def_uuid = parsed_alarm_details['id'].split('-', 1)[1]
- log.info("Successfully updated Alarm defination: {}".format(alarm_def_uuid))
+ self.logger.info("Successfully updated Alarm defination: {}".format(alarm_def_uuid))
return alarm_def_uuid
def delete_alarm_configuration(self, delete_alarm_req_dict):
"""Delete complete alarm configuration
"""
if delete_alarm_req_dict['alarm_uuid'] is None:
- log.info("delete_alarm_configuration: Alarm UUID not provided")
+ self.logger.info("delete_alarm_configuration: Alarm UUID not provided")
return None
#1)Get alarm & symptom defination details
alarm_details_json, alarm_details = self.get_alarm_defination_details(delete_alarm_req_dict['alarm_uuid'])
if symptom_id is None:
return None
else:
- log.info("Completed deleting alarm configuration: {}"\
+ self.logger.info("Completed deleting alarm configuration: {}"\
.format(delete_alarm_req_dict['alarm_uuid']))
return delete_alarm_req_dict['alarm_uuid']
auth=(self.vrops_user, self.vrops_password),
verify = False, headers = headers)
if resp.status_code is not 204:
- log.warn("Failed to delete notification rules for {}".format(alarm_name))
+ self.logger.warn("Failed to delete notification rules for {}".format(alarm_name))
return None
else:
- log.info("Deleted notification rules for {}".format(alarm_name))
+ self.logger.info("Deleted notification rules for {}".format(alarm_name))
return rule_id
def get_notification_rule_id_by_alarm_name(self, alarm_name):
verify = False, headers = headers)
if resp.status_code is not 200:
- log.warn("Failed to get notification rules details for {}"\
+ self.logger.warn("Failed to get notification rules details for {}"\
.format(delete_alarm_req_dict['alarm_name']))
return None
for dict in notifications_list:
if dict['name'] is not None and dict['name'] == alarm_notify_id:
notification_id = dict['id']
- log.info("Found Notification id to be deleted: {} for {}"\
+ self.logger.info("Found Notification id to be deleted: {} for {}"\
.format(notification_id, alarm_name))
return notification_id
- log.warn("Notification id to be deleted not found for {}"\
+ self.logger.warn("Notification id to be deleted not found for {}"\
.format(notification_id, alarm_name))
return None
auth=(self.vrops_user, self.vrops_password),
verify = False, headers = headers)
if resp.status_code is not 204:
- log.warn("Failed to delete alarm definition {}".format(alarm_id))
+ self.logger.warn("Failed to delete alarm definition {}".format(alarm_id))
return None
else:
- log.info("Deleted alarm definition {}".format(alarm_id))
+ self.logger.info("Deleted alarm definition {}".format(alarm_id))
return alarm_id
def delete_symptom_definition(self, symptom_id):
auth=(self.vrops_user, self.vrops_password),
verify = False, headers = headers)
if resp.status_code is not 204:
- log.warn("Failed to delete symptom definition {}".format(symptom_id))
+ self.logger.warn("Failed to delete symptom definition {}".format(symptom_id))
return None
else:
- log.info("Deleted symptom definition {}".format(symptom_id))
+ self.logger.info("Deleted symptom definition {}".format(symptom_id))
return symptom_id
status: True if supported, False if not supported
"""
status = False
+ if 'metric_name' not in metric_info:
+ self.logger.debug("Metric name not provided: {}".format(metric_info))
+ return status
metric_key_params = self.get_default_Params(metric_info['metric_name'])
if not metric_key_params:
- log.warn("Metric not supported: {}".format(metric_info['metric_name']))
+ self.logger.warn("Metric not supported: {}".format(metric_info['metric_name']))
return status
else:
- #If Metric is supported, verify metric unit & return status
- if metric_key_params['unit'] == metric_info['metric_unit']:
- log.info("Metric is supported: {}".format(metric_info['metric_name']))
- status = True
- else:
- log.warn("Metric not supported: {}".format(metric_info['metric_name']))
- status = False
- return status
+ #If Metric is supported, verify optional metric unit & return status
+ if 'metric_unit' in metric_info:
+ if metric_key_params.get('unit') == metric_info['metric_unit']:
+ self.logger.info("Metric is supported with unit: {}".format(metric_info['metric_name']))
+ status = True
+ else:
+ self.logger.debug("Metric supported but there is unit mismatch for: {}."\
+ "Supported unit: {}"\
+ .format(metric_info['metric_name'],metric_key_params['unit']))
+ status = True
+ return status
def get_triggered_alarms_list(self, list_alarm_input):
"""Get list of triggered alarms on a resource based on alarm input request.
#1) Find vm_moref_id from vApp uuid in vCD
vm_moref_id = self.get_vm_moref_id(ro_resource_uuid)
if vm_moref_id is None:
- log.warn("Failed to find vm morefid for vApp in vCD: {}".format(ro_resource_uuid))
+ self.logger.warn("Failed to find vm morefid for vApp in vCD: {}".format(ro_resource_uuid))
return None
#2) Based on vm_moref_id, find VM's corresponding resource_id in vROPs to set notification
vrops_resource_id = self.get_vm_resource_id(vm_moref_id)
if vrops_resource_id is None:
- log.warn("Failed to find resource in vROPs: {}".format(ro_resource_uuid))
+ self.logger.warn("Failed to find resource in vROPs: {}".format(ro_resource_uuid))
return None
return vrops_resource_id
verify = False, headers = headers)
if resp.status_code is not 200:
- log.warn("Failed to get notification rules details for {}"\
+ self.logger.warn("Failed to get notification rules details for {}"\
.format(delete_alarm_req_dict['alarm_name']))
return None
all_alerts = json.loads(resp.content)
if all_alerts.has_key('alerts'):
if not all_alerts['alerts']:
- log.info("No alarms present on resource {}".format(ro_resource_uuid))
+ self.logger.info("No alarms present on resource {}".format(ro_resource_uuid))
return resource_alarms
all_alerts_list = all_alerts['alerts']
for alarm in all_alerts_list:
- #log.info("Triggered Alarm {}".format(alarm))
+ #self.logger.info("Triggered Alarm {}".format(alarm))
if alarm['alertDefinitionName'] is not None and\
len(alarm['alertDefinitionName'].split('-', 1)) == 2:
if alarm['alertDefinitionName'].split('-', 1)[1] == ro_resource_uuid:
alarm_instance['start_date'] = self.convert_date_time(alarm['startTimeUTC'])
alarm_instance['update_date'] = self.convert_date_time(alarm['updateTimeUTC'])
alarm_instance['cancel_date'] = self.convert_date_time(alarm['cancelTimeUTC'])
- log.info("Triggered Alarm on resource {}".format(alarm_instance))
+ self.logger.info("Triggered Alarm on resource {}".format(alarm_instance))
resource_alarms.append(alarm_instance)
if not resource_alarms:
- log.info("No alarms present on resource {}".format(ro_resource_uuid))
+ self.logger.info("No alarms present on resource {}".format(ro_resource_uuid))
return resource_alarms
def convert_date_time(self, date_time):
date_time_formatted = complete_datetime.split('.',1)[0]
return date_time_formatted
+
responds using producer for vROPs
"""
+import sys
from mon_plugin_vrops import MonPlugin
from kafka_consumer_vrops import vROP_KafkaConsumer
#Core producer
-from core.message_bus.producer import KafkaProducer
+sys.path.append("../../core/message_bus")
+from producer import KafkaProducer
+#from core.message_bus.producer import KafkaProducer
import json
-import logging as log
+import logging
import traceback
+import os
+from xml.etree import ElementTree as XmlElementTree
+
+req_config_params = ('vrops_site', 'vrops_user', 'vrops_password',
+ 'vcloud-site','admin_username','admin_password',
+ 'vcenter_ip','vcenter_port','vcenter_user','vcenter_password',
+ 'vim_tenant_name','orgname','tenant_id')
+MODULE_DIR = os.path.dirname(__file__)
+CONFIG_FILE_NAME = 'vrops_config.xml'
+CONFIG_FILE_PATH = os.path.join(MODULE_DIR, CONFIG_FILE_NAME)
+
+def set_logger():
+ """Set Logger
+ """
+ BASE_DIR = os.path.dirname(os.path.dirname(__file__))
+ logger = logging.getLogger()
+ formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
+ handler = logging.FileHandler(os.path.join(BASE_DIR,"mon_vrops_log.log"))
+ handler.setFormatter(formatter)
+ logger.addHandler(handler)
+
class PluginReceiver():
"""MON Plugin receiver receiving request messages & responding using producer for vROPs
"""Constructor of PluginReceiver
"""
- topics = ['alarm_request', 'metric_request', 'Access_Credentials', 'alarm_response']
+ topics = ['alarm_request', 'metric_request', 'access_credentials']
+
+ self.logger = logging.getLogger('PluginReceiver')
+ self.logger.setLevel(logging.DEBUG)
+
#To Do - Add broker uri
broker_uri = None
- self.mon_plugin = MonPlugin()
+ #self.mon_plugin = MonPlugin()
self.consumer = vROP_KafkaConsumer(topics, broker_uri)
#Core producer
- self.producer = KafkaProducer()
+ self.producer_alarms = KafkaProducer('alarm_response')
+ self.producer_metrics = KafkaProducer('metric_response')
+ self.producer_access_credentials = KafkaProducer('vim_access_credentials_response')
+
def consume(self):
"""Consume the message, act on it & respond
if message_values.has_key('vim_type'):
vim_type = message_values['vim_type'].lower()
if vim_type == 'vmware':
- log.info("Action required for: {}".format(message.topic))
+ self.logger.info("Action required for: {}".format(message.topic))
if message.topic == 'alarm_request':
if message.key == "create_alarm_request":
config_alarm_info = json.loads(message.value)
- alarm_uuid = self.create_alarm(config_alarm_info['alarm_creation_request'])
- log.info("Alarm created with alarm uuid: {}".format(alarm_uuid))
+ alarm_uuid = self.create_alarm(config_alarm_info['alarm_create_request'])
+ self.logger.info("Alarm created with alarm uuid: {}".format(alarm_uuid))
#Publish message using producer
self.publish_create_alarm_status(alarm_uuid, config_alarm_info)
elif message.key == "update_alarm_request":
update_alarm_info = json.loads(message.value)
alarm_uuid = self.update_alarm(update_alarm_info['alarm_update_request'])
- log.info("In plugin_receiver: Alarm defination updated : alarm uuid: {}".format(alarm_uuid))
+ self.logger.info("Alarm defination updated : alarm uuid: {}".format(alarm_uuid))
#Publish message using producer
self.publish_update_alarm_status(alarm_uuid, update_alarm_info)
elif message.key == "delete_alarm_request":
delete_alarm_info = json.loads(message.value)
- alarm_uuid = self.delete_alarm(delete_alarm_info['alarm_deletion_request'])
- log.info("In plugin_receiver: Alarm defination deleted : alarm uuid: {}".format(alarm_uuid))
+ alarm_uuid = self.delete_alarm(delete_alarm_info['alarm_delete_request'])
+ self.logger.info("Alarm defination deleted : alarm uuid: {}".format(alarm_uuid))
#Publish message using producer
self.publish_delete_alarm_status(alarm_uuid, delete_alarm_info)
elif message.key == "list_alarm_request":
elif message.topic == 'metric_request':
if message.key == "read_metric_data_request":
metric_request_info = json.loads(message.value)
- metrics_data = self.mon_plugin.get_metrics_data(metric_request_info)
- log.info("Collected Metrics Data: {}".format(metrics_data))
+ mon_plugin_obj = MonPlugin()
+ metrics_data = mon_plugin_obj.get_metrics_data(metric_request_info)
+ self.logger.info("Collected Metrics Data: {}".format(metrics_data))
#Publish message using producer
self.publish_metrics_data_status(metrics_data)
elif message.key == "create_metric_request":
elif message.key == "delete_metric_request":
metric_info = json.loads(message.value)
#Deleting Metric Data is not allowed. Publish status as False
- log.warn("Deleting Metric is not allowed: {}".format(metric_info['metric_name']))
+ self.logger.warn("Deleting Metric is not allowed: {}".format(metric_info['metric_name']))
#Publish message using producer
self.publish_delete_metric_response(metric_info)
+ elif message.topic == 'access_credentials':
+ if message.key == "vim_access_credentials":
+ access_info = json.loads(message.value)
+ access_update_status = self.update_access_credentials(access_info['access_config'])
+ self.publish_access_update_response(access_update_status, access_info)
+
+ except:
+ self.logger.error("Exception in receiver: {}".format(traceback.format_exc()))
- except Exception as exp:
- log.error("Exception in receiver: {} {}".format(exp, traceback.format_exc()))
def create_alarm(self, config_alarm_info):
"""Create alarm using vROPs plugin
"""
- plugin_uuid = self.mon_plugin.configure_rest_plugin()
- alarm_uuid = self.mon_plugin.configure_alarm(config_alarm_info)
+ mon_plugin = MonPlugin()
+ plugin_uuid = mon_plugin.configure_rest_plugin()
+ alarm_uuid = mon_plugin.configure_alarm(config_alarm_info)
return alarm_uuid
def publish_create_alarm_status(self, alarm_uuid, config_alarm_info):
msg_key = 'create_alarm_response'
response_msg = {"schema_version":1.0,
"schema_type":"create_alarm_response",
- "alarm_creation_response":
- {"correlation_id":config_alarm_info["alarm_creation_request"]["correlation_id"],
+ "alarm_create_response":
+ {"correlation_id":config_alarm_info["alarm_create_request"]["correlation_id"],
"alarm_uuid":alarm_uuid,
"status": True if alarm_uuid else False
}
}
#Core producer
- self.producer.publish(key=msg_key, value=json.dumps(response_msg), topic=topic)
+ self.producer_alarms.publish(key=msg_key, value=json.dumps(response_msg), topic=topic)
def update_alarm(self, update_alarm_info):
"""Updare already created alarm
"""
- alarm_uuid = self.mon_plugin.update_alarm_configuration(update_alarm_info)
+ mon_plugin = MonPlugin()
+ alarm_uuid = mon_plugin.update_alarm_configuration(update_alarm_info)
return alarm_uuid
def publish_update_alarm_status(self, alarm_uuid, update_alarm_info):
}
}
#Core producer
- self.producer.publish(key=msg_key, value=json.dumps(response_msg), topic=topic)
+ self.producer_alarms.publish(key=msg_key, value=json.dumps(response_msg), topic=topic)
def delete_alarm(self, delete_alarm_info):
"""Delete alarm configuration
"""
- alarm_uuid = self.mon_plugin.delete_alarm_configuration(delete_alarm_info)
+ mon_plugin = MonPlugin()
+ alarm_uuid = mon_plugin.delete_alarm_configuration(delete_alarm_info)
return alarm_uuid
def publish_delete_alarm_status(self, alarm_uuid, delete_alarm_info):
response_msg = {"schema_version":1.0,
"schema_type":"delete_alarm_response",
"alarm_deletion_response":
- {"correlation_id":delete_alarm_info["alarm_deletion_request"]["correlation_id"],
+ {"correlation_id":delete_alarm_info["alarm_delete_request"]["correlation_id"],
"alarm_uuid":alarm_uuid,
"status": True if alarm_uuid else False
}
}
#Core producer
- self.producer.publish(key=msg_key, value=json.dumps(response_msg), topic=topic)
+ self.producer_alarms.publish(key=msg_key, value=json.dumps(response_msg), topic=topic)
def publish_metrics_data_status(self, metrics_data):
topic = 'metric_response'
msg_key = 'read_metric_data_response'
#Core producer
- self.producer.publish(key=msg_key, value=json.dumps(metrics_data), topic=topic)
+ self.producer_metrics.publish(key=msg_key, value=json.dumps(metrics_data), topic=topic)
def verify_metric(self, metric_info):
"""Verify if metric is supported or not
"""
- metric_key_status = self.mon_plugin.verify_metric_support(metric_info)
+ mon_plugin = MonPlugin()
+ metric_key_status = mon_plugin.verify_metric_support(metric_info)
return metric_key_status
def publish_create_metric_response(self, metric_info, metric_status):
}
}
#Core producer
- self.producer.publish(key=msg_key, value=json.dumps(response_msg), topic=topic)
+ self.producer_metrics.publish(key=msg_key, value=json.dumps(response_msg), topic=topic)
def publish_update_metric_response(self, metric_info, metric_status):
"""Publish update metric response
}
}
#Core producer
- self.producer.publish(key=msg_key, value=json.dumps(response_msg), topic=topic)
+ self.producer_metrics.publish(key=msg_key, value=json.dumps(response_msg), topic=topic)
def publish_delete_metric_response(self, metric_info):
"""
"status":False
}
#Core producer
- self.producer.publish(key=msg_key, value=json.dumps(response_msg), topic=topic)
+ self.producer_metrics.publish(key=msg_key, value=json.dumps(response_msg), topic=topic)
def list_alarms(self, list_alarm_input):
+ """Collect list of triggered alarms based on input
"""
- """
- triggered_alarms = self.mon_plugin.get_triggered_alarms_list(list_alarm_input)
+ mon_plugin = MonPlugin()
+ triggered_alarms = mon_plugin.get_triggered_alarms_list(list_alarm_input)
return triggered_alarms
def publish_list_alarm_response(self, triggered_alarm_list, list_alarm_input):
- """
+ """Publish list of triggered alarms
"""
topic = 'alarm_response'
msg_key = 'list_alarm_response'
response_msg = {"schema_version":1.0,
"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'],
+ #"resource_uuid":list_alarm_input['alarm_list_request']['resource_uuid'],
"list_alarm_resp":triggered_alarm_list
}
#Core producer
- self.producer.publish(key=msg_key, value=json.dumps(response_msg), topic=topic)
+ self.producer_alarms.publish(key=msg_key, value=json.dumps(response_msg), topic=topic)
+
+
+ def update_access_credentials(self, access_info):
+ """Verify if all the required access config params are provided and
+ updates access config in default vrops config file
+ """
+ update_status = False
+ wr_status = False
+ #Check if all the required config params are passed in request
+ if not all (keys in access_info for keys in req_config_params):
+ self.logger.debug("All required Access Config Parameters not provided")
+ self.logger.debug("List of required Access Config Parameters: {}".format(req_config_params))
+ self.logger.debug("List of given Access Config Parameters: {}".format(access_info))
+ return update_status
+
+ wr_status = self.write_access_config(access_info)
+ return wr_status #True/False
+
+ def write_access_config(self, access_info):
+ """Write access configuration to vROPs config file.
+ """
+ wr_status = False
+ try:
+ tree = XmlElementTree.parse(CONFIG_FILE_PATH)
+ root = tree.getroot()
+ alarmParams = {}
+ for config in root:
+ if config.tag == 'Access_Config':
+ for param in config:
+ for key,val in access_info.iteritems():
+ if param.tag == key:
+ #print param.tag, val
+ param.text = val
+
+ tree.write(CONFIG_FILE_PATH)
+ wr_status = True
+ except Exception as exp:
+ self.logger.warn("Failed to update Access Config Parameters: {}".format(exp))
+ return wr_status
+
+
+ def publish_access_update_response(self, access_update_status, access_info_req):
+ """Publish access update response
+ """
+ topic = 'access_credentials'
+ msg_key = 'vim_access_credentials_response'
+ response_msg = {"schema_version":1.0,
+ "schema_type":"vim_access_credentials_response",
+ "correlation_id":access_info_req['access_config']['correlation_id'],
+ "status":access_update_status
+ }
+ #To Do - Add producer
+ #self.producer.publish(key=msg_key, value=json.dumps(response_msg), topic=topic)
+ self.producer.publish(topic=topic, messages=json.dumps(response_msg), msg_key=msg_key)
def main():
- log.basicConfig(filename='mon_vrops_log.log',level=log.DEBUG)
+ #log.basicConfig(filename='mon_vrops_log.log',level=log.DEBUG)
+ set_logger()
plugin_rcvr = PluginReceiver()
plugin_rcvr.consume()
if __name__ == "__main__":
main()
+