Refactors codebase
[osm/MON.git] / osm_mon / plugins / CloudWatch / metrics.py
index 5c6c976..1812002 100644 (file)
 # contact with: wajeeha.hamid@xflowresearch.com
 ##
 
 # contact with: wajeeha.hamid@xflowresearch.com
 ##
 
-'''
+"""
 AWS-Plugin implements all the methods of MON to interact with AWS using the BOTO client
 AWS-Plugin implements all the methods of MON to interact with AWS using the BOTO client
-'''
+"""
 
 __author__ = "Wajeeha Hamid"
 
 __author__ = "Wajeeha Hamid"
-__date__   = "18-Sept-2017"
+__date__ = "18-Sept-2017"
 
 
-import sys
 import datetime
 import datetime
-import json
 import logging
 
 try:
 import logging
 
 try:
@@ -42,36 +40,36 @@ except:
 
 log = logging.getLogger(__name__)
 
 
 log = logging.getLogger(__name__)
 
-class Metrics():
 
 
-    def createMetrics(self,cloudwatch_conn,metric_info):
+class Metrics:
+
+    def createMetrics(self, cloudwatch_conn, metric_info):
         try:
         try:
-            
-            '''createMetrics will be returning the metric_uuid=0 and
-             status=True when the metric is supported by AWS'''
 
 
-            supported=self.check_metric(metric_info['metric_name'])
+            """createMetrics will be returning the metric_uuid=0 and
+             status=True when the metric is supported by AWS"""
+
+            supported = self.check_metric(metric_info['metric_name'])
             metric_resp = dict()
             metric_resp['resource_uuid'] = metric_info['resource_uuid']
             metric_resp = dict()
             metric_resp['resource_uuid'] = metric_info['resource_uuid']
-            
-            if supported['status'] == True:
+
+            if supported['status']:
                 metric_resp['status'] = True
                 metric_resp['metric_uuid'] = 0
                 metric_resp['status'] = True
                 metric_resp['metric_uuid'] = 0
-                log.debug("Metrics Configured Succesfully : %s" , metric_resp)
+                log.debug("Metrics Configured Successfully : %s", metric_resp)
             else:
                 metric_resp['status'] = False
                 metric_resp['metric_uuid'] = None
             else:
                 metric_resp['status'] = False
                 metric_resp['metric_uuid'] = None
-                log.error("Metric name is not supported") 
-            
-            return metric_resp         
+                log.error("Metric name is not supported")
+
+            return metric_resp
 
         except Exception as e:
             log.error("Metric Configuration Failed: " + str(e))
 
         except Exception as e:
             log.error("Metric Configuration Failed: " + str(e))
-#-----------------------------------------------------------------------------------------------------------------------------
-    
-    def metricsData(self,cloudwatch_conn,data_info):
 
 
-       """Getting Metrics Stats for an Hour.The datapoints are
+    def metricsData(self, cloudwatch_conn, data_info):
+
+        """Getting Metrics Stats for an Hour.The datapoints are
         received after every one minute.
         Time interval can be modified using Timedelta value"""
 
         received after every one minute.
         Time interval can be modified using Timedelta value"""
 
@@ -81,43 +79,48 @@ class Metrics():
             timestamp_arr = {}
             value_arr = {}
 
             timestamp_arr = {}
             value_arr = {}
 
-            supported=self.check_metric(data_info['metric_name'])
+            supported = self.check_metric(data_info['metric_name'])
 
 
-            if supported['status'] == True:
+            if supported['status']:
                 if int(data_info['collection_period']) % 60 == 0:
                 if int(data_info['collection_period']) % 60 == 0:
-                    metric_stats=cloudwatch_conn.get_metric_statistics(60, datetime.datetime.utcnow() - datetime.timedelta(seconds=int(data_info['collection_period'])),
-                                        datetime.datetime.utcnow(),supported['metric_name'],'AWS/EC2', 'Maximum',
-                                        dimensions={'InstanceId':data_info['resource_uuid']}, unit='Percent')  
+                    metric_stats = cloudwatch_conn.get_metric_statistics(60,
+                                                                         datetime.datetime.utcnow() - datetime.timedelta(
+                                                                             seconds=int(
+                                                                                 data_info['collection_period'])),
+                                                                         datetime.datetime.utcnow(),
+                                                                         supported['metric_name'], 'AWS/EC2', 'Maximum',
+                                                                         dimensions={
+                                                                             'InstanceId': data_info['resource_uuid']},
+                                                                         unit='Percent')
                     index = 0
                     index = 0
-                    for itr in range (len(metric_stats)):
+                    for itr in range(len(metric_stats)):
                         timestamp_arr[index] = str(metric_stats[itr]['Timestamp'])
                         value_arr[index] = metric_stats[itr]['Maximum']
                         timestamp_arr[index] = str(metric_stats[itr]['Timestamp'])
                         value_arr[index] = metric_stats[itr]['Maximum']
-                        index +=1
+                        index += 1
                     metric_info_dict['time_series'] = timestamp_arr
                     metric_info_dict['metrics_series'] = value_arr
                     log.debug("Metrics Data : %s", metric_info_dict)
                     return metric_info_dict
                     metric_info_dict['time_series'] = timestamp_arr
                     metric_info_dict['metrics_series'] = value_arr
                     log.debug("Metrics Data : %s", metric_info_dict)
                     return metric_info_dict
-                else: 
+                else:
                     log.error("Collection Period should be a multiple of 60")
                     return False
 
             else:
                 log.error("Metric name is not supported")
                 return False
                     log.error("Collection Period should be a multiple of 60")
                     return False
 
             else:
                 log.error("Metric name is not supported")
                 return False
-        
+
         except Exception as e:
             log.error("Error returning Metrics Data" + str(e))
 
         except Exception as e:
             log.error("Error returning Metrics Data" + str(e))
 
-#-----------------------------------------------------------------------------------------------------------------------------
-    def updateMetrics(self,cloudwatch_conn,metric_info):
-        
-        '''updateMetrics will be returning the metric_uuid=0 and
-         status=True when the metric is supported by AWS'''
+    def updateMetrics(self, cloudwatch_conn, metric_info):
+
+        """updateMetrics will be returning the metric_uuid=0 and
+         status=True when the metric is supported by AWS"""
         try:
         try:
-            supported=self.check_metric(metric_info['metric_name'])
+            supported = self.check_metric(metric_info['metric_name'])
             update_resp = dict()
             update_resp['resource_uuid'] = metric_info['resource_uuid']
             update_resp = dict()
             update_resp['resource_uuid'] = metric_info['resource_uuid']
-            if supported['status'] == True:
+            if supported['status']:
                 update_resp['status'] = True
                 update_resp['metric_uuid'] = 0
                 log.debug("Metric Updated : %s", update_resp)
                 update_resp['status'] = True
                 update_resp['metric_uuid'] = 0
                 log.debug("Metric Updated : %s", update_resp)
@@ -125,21 +128,21 @@ class Metrics():
                 update_resp['status'] = False
                 update_resp['metric_uuid'] = None
                 log.error("Metric name is not supported")
                 update_resp['status'] = False
                 update_resp['metric_uuid'] = None
                 log.error("Metric name is not supported")
-             
-            return update_resp  
-        
+
+            return update_resp
+
         except Exception as e:
             log.error("Error in Update Metrics" + str(e))
         except Exception as e:
             log.error("Error in Update Metrics" + str(e))
-#-----------------------------------------------------------------------------------------------------------------------------
-    def deleteMetrics(self,cloudwatch_conn,del_info):
-        
-        ''' " Not supported in AWS"
-        Returning the required parameters with status = False'''
+
+    def deleteMetrics(self, cloudwatch_conn, del_info):
+
+        """ " Not supported in AWS"
+        Returning the required parameters with status = False"""
         try:
         try:
-            supported=self.check_metric(del_info['metric_name'])
+            supported = self.check_metric(del_info['metric_name'])
             metric_resp = dict()
             del_resp = dict()
             metric_resp = dict()
             del_resp = dict()
-            if supported['status'] == True:      
+            if supported['status']:
                 del_resp['schema_version'] = del_info['schema_version']
                 del_resp['schema_type'] = "delete_metric_response"
                 del_resp['metric_name'] = del_info['metric_name']
                 del_resp['schema_version'] = del_info['schema_version']
                 del_resp['schema_type'] = "delete_metric_response"
                 del_resp['metric_name'] = del_info['metric_name']
@@ -149,54 +152,52 @@ class Metrics():
                 del_resp['tenant_uuid'] = del_info['tenant_uuid']
                 del_resp['correlation_id'] = del_info['correlation_uuid']
                 del_resp['status'] = False
                 del_resp['tenant_uuid'] = del_info['tenant_uuid']
                 del_resp['correlation_id'] = del_info['correlation_uuid']
                 del_resp['status'] = False
-                log.info("Metric Deletion Not supported in AWS : %s",del_resp)
+                log.info("Metric Deletion Not supported in AWS : %s", del_resp)
                 return del_resp
             else:
                 log.error("Metric name is not supported")
                 return False
 
         except Exception as e:
                 return del_resp
             else:
                 log.error("Metric name is not supported")
                 return False
 
         except Exception as e:
-                log.error(" Metric Deletion Not supported in AWS : " + str(e))
-#------------------------------------------------------------------------------------------------------------------------------------
-    
-    def listMetrics(self,cloudwatch_conn ,list_info):
+            log.error(" Metric Deletion Not supported in AWS : " + str(e))
+
+    def listMetrics(self, cloudwatch_conn, list_info):
 
 
-        '''Returns the list of available AWS/EC2 metrics on which
-        alarms have been configured and the metrics are being monitored'''
+        """Returns the list of available AWS/EC2 metrics on which
+        alarms have been configured and the metrics are being monitored"""
         try:
             supported = self.check_metric(list_info['metric_name'])
         try:
             supported = self.check_metric(list_info['metric_name'])
-            if supported['status'] == True: 
+            if supported['status']:
                 metrics_list = []
                 metrics_list = []
-                metrics_data = dict()    
+                metrics_data = dict()
 
 
-                #To get the list of associated metrics with the alarms
+                # To get the list of associated metrics with the alarms
                 alarms = cloudwatch_conn.describe_alarms()
                 itr = 0
                 if list_info['metric_name'] == "":
                     for alarm in alarms:
                         metrics_info = dict()
                 alarms = cloudwatch_conn.describe_alarms()
                 itr = 0
                 if list_info['metric_name'] == "":
                     for alarm in alarms:
                         metrics_info = dict()
-                        instance_id = str(alarm.dimensions['InstanceId']).split("'")[1] 
-                        metrics_info['metric_name'] = str(alarm.metric) 
-                        metrics_info['metric_uuid'] = 0     
-                        metrics_info['metric_unit'] = str(alarm.unit)    
-                        metrics_info['resource_uuid'] = instance_id 
-                        metrics_list.insert(itr,metrics_info)
+                        instance_id = str(alarm.dimensions['InstanceId']).split("'")[1]
+                        metrics_info['metric_name'] = str(alarm.metric)
+                        metrics_info['metric_uuid'] = 0
+                        metrics_info['metric_unit'] = str(alarm.unit)
+                        metrics_info['resource_uuid'] = instance_id
+                        metrics_list.insert(itr, metrics_info)
                         itr += 1
                         itr += 1
-                    print metrics_list
+                    log.info(metrics_list)
                     return metrics_list
                     return metrics_list
-                else: 
+                else:
                     for alarm in alarms:
                         metrics_info = dict()
                         if alarm.metric == supported['metric_name']:
                     for alarm in alarms:
                         metrics_info = dict()
                         if alarm.metric == supported['metric_name']:
-                            instance_id = str(alarm.dimensions['InstanceId']).split("'")[1] 
+                            instance_id = str(alarm.dimensions['InstanceId']).split("'")[1]
                             metrics_info['metric_name'] = str(alarm.metric)
                             metrics_info['metric_name'] = str(alarm.metric)
-                            metrics_info['metric_uuid'] = 0     
-                            metrics_info['metric_unit'] = str(alarm.unit)    
+                            metrics_info['metric_uuid'] = 0
+                            metrics_info['metric_unit'] = str(alarm.unit)
                             metrics_info['resource_uuid'] = instance_id
                             metrics_info['resource_uuid'] = instance_id
-                            metrics_list.insert(itr,metrics_info)
+                            metrics_list.insert(itr, metrics_info)
                             itr += 1
                             itr += 1
-                    return metrics_list               
-                log.debug("Metrics List : %s",metrics_list)
+                    return metrics_list
             else:
                 log.error("Metric name is not supported")
                 return False
             else:
                 log.error("Metric name is not supported")
                 return False
@@ -204,11 +205,9 @@ class Metrics():
         except Exception as e:
             log.error("Error in Getting Metric List " + str(e))
 
         except Exception as e:
             log.error("Error in Getting Metric List " + str(e))
 
-#------------------------------------------------------------------------------------------------------------------------------------
+    def check_metric(self, metric_name):
 
 
-    def check_metric(self,metric_name):
-    
-        ''' Checking whether the metric is supported by AWS '''
+        """ Checking whether the metric is supported by AWS """
         try:
             check_resp = dict()
             # metric_name
         try:
             check_resp = dict()
             # metric_name
@@ -242,22 +241,13 @@ class Metrics():
                 metric_status = False
                 log.info("Metric Not Supported by AWS plugin ")
             check_resp['metric_name'] = metric_name
                 metric_status = False
                 log.info("Metric Not Supported by AWS plugin ")
             check_resp['metric_name'] = metric_name
-            #status
-            if metric_status == True:
+            # status
+            if metric_status:
                 check_resp['status'] = True
             else:
                 check_resp['status'] = True
             else:
-               check_resp['status'] = False
+                check_resp['status'] = False
 
             return check_resp
 
 
             return check_resp
 
-        except Exception as e: 
-            log.error("Error in Plugin Inputs %s",str(e))     
-#--------------------------------------------------------------------------------------------------------------------------------------
-
-      
-
-
-
-
-
-
+        except Exception as e:
+            log.error("Error in Plugin Inputs %s", str(e))