update monitor features
authorstevenvanrossem <steven.vanrossem@intec.ugent.be>
Thu, 14 Apr 2016 07:55:20 +0000 (09:55 +0200)
committerstevenvanrossem <steven.vanrossem@intec.ugent.be>
Thu, 14 Apr 2016 07:55:20 +0000 (09:55 +0200)
src/emuvim/api/zerorpc/network.py
src/emuvim/cli/monitor.py
src/emuvim/dcemulator/monitoring.py
src/emuvim/dcemulator/net.py

index a64b09e..1b7e1e0 100644 (file)
@@ -91,20 +91,30 @@ class DCNetworkApi(object):
             return ex.message
 
     # setup the rate measurement for a vnf interface
-    def monitor_setup_rate_measurement(self, vnf_name, vnf_interface, direction, metric):
+    def setup_metric(self, vnf_name, vnf_interface, metric):
+        logging.debug("RPC CALL: setup metric")
+        try:
+            c = self.net.monitor_agent.setup_metric(vnf_name, vnf_interface, metric)
+            return c
+        except Exception as ex:
+            logging.exception("RPC error.")
+            return ex.message
+
+    # setup the rate measurement for a vnf interface
+    def monitor_setup_rate_measurement(self, vnf_name, vnf_interface, metric):
         logging.debug("RPC CALL: get rate")
         try:
-            c = self.net.monitor_agent.setup_rate_measurement(vnf_name, vnf_interface, direction, metric)
+            c = self.net.monitor_agent.setup_rate_measurement(vnf_name, vnf_interface, metric)
             return c
         except Exception as ex:
             logging.exception("RPC error.")
             return ex.message
 
     # get egress(default) or ingress rate of a vnf
-    def monitor_get_rate(self, vnf_name, vnf_interface, direction, metric):
+    def monitor_get_rate(self, vnf_name, vnf_interface, metric):
         logging.debug("RPC CALL: get rate")
         try:
-            c = self.net.monitor_agent.get_rate(vnf_name, vnf_interface, direction, metric)
+            c = self.net.monitor_agent.get_rate(vnf_name, vnf_interface, metric)
             return c
         except Exception as ex:
             logging.exception("RPC error.")
index 0c3c515..1d4abfb 100755 (executable)
@@ -28,22 +28,27 @@ class ZeroRpcClient(object):
         else:\r
             print "Command not implemented."\r
 \r
-    def get_rate(self, args):\r
+    def setup_metric(self, args):\r
         vnf_name = self._parse_vnf_name(args.get("vnf_name"))\r
         vnf_interface = self._parse_vnf_interface(args.get("vnf_name"))\r
+        r = self.c.setup_metric(\r
+            vnf_name,\r
+            vnf_interface,\r
+            args.get("metric"))\r
+        pp.pprint(r)\r
+        '''\r
         self.c.monitor_setup_rate_measurement(\r
             vnf_name,\r
             vnf_interface,\r
-            args.get("direction"),\r
             args.get("metric"))\r
         while True:\r
             r = self.c.monitor_get_rate(\r
                 vnf_name,\r
                 vnf_interface,\r
-                args.get("direction"),\r
                 args.get("metric"))\r
             pp.pprint(r)\r
             time.sleep(1)\r
+        '''\r
 \r
     def _parse_vnf_name(self, vnf_name_str):\r
         vnf_name = vnf_name_str.split(':')[0]\r
@@ -64,16 +69,13 @@ parser.add_argument(
 parser.add_argument(\r
     "--vnf_name", "-vnf", dest="vnf_name",\r
     help="vnf name to be monitored")\r
-parser.add_argument(\r
-    "--direction", "-d", dest="direction",\r
-    help="rx (ingress rate) or tx (egress rate)")\r
 parser.add_argument(\r
     "--metric", "-m", dest="metric",\r
-    help="bytes (byte rate), packets (packet rate)")\r
+    help="tx_bytes, rx_bytes, tx_packets, rx_packets")\r
 \r
 def main(argv):\r
-    print "This is the son-emu monitor CLI."\r
-    print "Arguments: %s" % str(argv)\r
+    #print "This is the son-emu monitor CLI."\r
+    #print "Arguments: %s" % str(argv)\r
     args = vars(parser.parse_args(argv))\r
     c = ZeroRpcClient()\r
     c.execute_command(args)\r
index 50393ea..1f7ff2e 100755 (executable)
@@ -5,28 +5,74 @@ import logging
 from mininet.node import  OVSSwitch\r
 import ast\r
 import time\r
+from prometheus_client import start_http_server, Summary, Histogram, Gauge, Counter\r
+import threading\r
+\r
 logging.basicConfig(level=logging.INFO)\r
 \r
 """\r
-class to read openflow stats from the Ryu controller of the DCNEtwork\r
+class to read openflow stats from the Ryu controller of the DCNetwork\r
 """\r
 \r
 class DCNetworkMonitor():\r
     def __init__(self, net):\r
         self.net = net\r
-        # link to REST_API\r
+        # link to Ryu REST_API\r
         self.ip = '0.0.0.0'\r
         self.port = '8080'\r
         self.REST_api = 'http://{0}:{1}'.format(self.ip,self.port)\r
 \r
+        # helper variables to calculate the metrics\r
+        # TODO put these in a list to support multiple metrics simultaneously\r
+        self.switch_dpid = 0\r
+        self.vnf_name = None\r
+        self.vnf_interface = None\r
         self.previous_measurement = 0\r
         self.previous_monitor_time = 0\r
-        self.switch_dpid = 0\r
         self.metric_key = None\r
         self.mon_port = None\r
 \r
+\r
+        # Start up the server to expose the metrics to Prometheus.\r
+        start_http_server(8000)\r
+        # supported Prometheus metrics\r
+        self.prom_tx_packet_count = Gauge('sonemu_tx_count_packets', 'Total number of packets sent',\r
+                                          ['vnf_name', 'vnf_interface'])\r
+        self.prom_rx_packet_count = Gauge('sonemu_rx_count_packets', 'Total number of packets received',\r
+                                          ['vnf_name', 'vnf_interface'])\r
+        self.prom_tx_byte_count = Gauge('sonemu_tx_count_bytes', 'Total number of bytes sent',\r
+                                        ['vnf_name', 'vnf_interface'])\r
+        self.prom_rx_byte_count = Gauge('sonemu_rx_count_bytes', 'Total number of bytes received',\r
+                                        ['vnf_name', 'vnf_interface'])\r
+\r
+        self.prom_metrics={'tx_packets':self.prom_tx_packet_count, 'rx_packets':self.prom_rx_packet_count,\r
+                           'tx_bytes':self.prom_tx_byte_count,'rx_bytes':self.prom_rx_byte_count}\r
+\r
+        # list of installed metrics to monitor\r
+        # each entry can contain this data\r
+        '''\r
+        {\r
+        switch_dpid = 0\r
+        vnf_name = None\r
+        vnf_interface = None\r
+        previous_measurement = 0\r
+        previous_monitor_time = 0\r
+        metric_key = None\r
+        mon_port = None\r
+        }\r
+        '''\r
+        self.network_metrics=[]\r
+\r
+        # start monitoring thread\r
+        self.monitor_thread = threading.Thread(target=self.get_network_metrics)\r
+        self.monitor_thread.start()\r
+\r
+\r
     # first set some parameters, before measurement can start\r
-    def setup_rate_measurement(self, vnf_name, vnf_interface=None, direction='tx', metric='packets'):\r
+    def setup_metric(self, vnf_name, vnf_interface=None, metric='tx_packets'):\r
+\r
+        network_metric = {}\r
+\r
         # check if port is specified (vnf:port)\r
         if vnf_interface is None:\r
             # take first interface by default\r
@@ -34,6 +80,11 @@ class DCNetworkMonitor():
             link_dict = self.net.DCNetwork_graph[vnf_name][connected_sw]\r
             vnf_interface = link_dict[0]['src_port_id']\r
 \r
+        network_metric['vnf_name'] = vnf_name\r
+        network_metric['vnf_interface'] = vnf_interface\r
+        #self.vnf_name = vnf_name\r
+        #self.vnf_interface = vnf_interface\r
+\r
         for connected_sw in self.net.DCNetwork_graph.neighbors(vnf_name):\r
             link_dict = self.net.DCNetwork_graph[vnf_name][connected_sw]\r
             for link in link_dict:\r
@@ -41,15 +92,18 @@ class DCNetworkMonitor():
                 if link_dict[link]['src_port_id'] == vnf_interface:\r
                     # found the right link and connected switch\r
                     # logging.info("{0},{1}".format(link_dict[link]['src_port_id'], vnf_source_interface))\r
-                    self.mon_port = link_dict[link]['dst_port']\r
+                    network_metric['mon_port'] = link_dict[link]['dst_port']\r
+                    # self.mon_port = link_dict[link]['dst_port']\r
                     break\r
 \r
+        if 'mon_port' not in network_metric:\r
+            logging.exception("vnf interface {0}:{1} not found!".format(vnf_name,vnf_interface))\r
+            return "vnf interface {0}:{1} not found!".format(vnf_name,vnf_interface)\r
+\r
         try:\r
             # default port direction to monitor\r
-            if direction is None:\r
-                direction = 'tx'\r
             if metric is None:\r
-                metric = 'packets'\r
+                metric = 'tx_packets'\r
 \r
             vnf_switch = self.net.DCNetwork_graph.neighbors(str(vnf_name))\r
 \r
@@ -67,18 +121,88 @@ class DCNetworkMonitor():
                 logging.info("vnf: {0} is not connected to switch".format(vnf_name))\r
                 return\r
 \r
-            self.previous_measurement = 0\r
-            self.previous_monitor_time = 0\r
+            network_metric['previous_measurement'] = 0\r
+            network_metric['previous_monitor_time'] = 0\r
+            #self.previous_measurement = 0\r
+            #self.previous_monitor_time = 0\r
+\r
+            network_metric['switch_dpid'] = int(str(next_node.dpid), 16)\r
+            network_metric['metric_key'] = metric\r
+            #self.switch_dpid = int(str(next_node.dpid), 16)\r
+            #self.metric_key = '{0}_{1}'.format(direction, metric)\r
+\r
+            self.network_metrics.append(network_metric)\r
 \r
-            #self.switch_dpid = x = int(str(next_node.dpid), 16)\r
-            self.switch_dpid = int(str(next_node.dpid), 16)\r
-            self.metric_key = '{0}_{1}'.format(direction, metric)\r
+            logging.info('Started monitoring: {2} on {0}:{1}'.format(vnf_name, vnf_interface, metric))\r
+            return 'Started monitoring: {2} on {0}:{1}'.format(vnf_name, vnf_interface, metric)\r
 \r
         except Exception as ex:\r
-            logging.exception("get_txrate error.")\r
+            logging.exception("get_rate error.")\r
             return ex.message\r
 \r
 \r
+    # get all metrics defined in the list\r
+    def get_network_metrics(self):\r
+        while True:\r
+            # group metrics by dpid to optimize the rest api calls\r
+            dpid_list = [metric_dict['switch_dpid'] for metric_dict in self.network_metrics]\r
+            dpid_set = set(dpid_list)\r
+\r
+            for dpid in dpid_set:\r
+\r
+                # query Ryu\r
+                ret = self.REST_cmd('stats/port', dpid)\r
+                port_stat_dict = ast.literal_eval(ret)\r
+\r
+                metric_list = [metric_dict for metric_dict in self.network_metrics\r
+                               if int(metric_dict['switch_dpid'])==int(dpid)]\r
+                #logging.info('1set prom packets:{0} '.format(self.network_metrics))\r
+                for metric_dict in metric_list:\r
+                    self.set_network_metric(metric_dict, port_stat_dict)\r
+\r
+            time.sleep(1)\r
+\r
+    # call this function repeatedly for streaming measurements\r
+    def set_network_metric(self, metric_dict, port_stat_dict):\r
+\r
+        metric_key = metric_dict['metric_key']\r
+        switch_dpid = metric_dict['switch_dpid']\r
+        vnf_name = metric_dict['vnf_name']\r
+        vnf_interface = metric_dict['vnf_interface']\r
+        previous_measurement = metric_dict['previous_measurement']\r
+        previous_monitor_time = metric_dict['previous_monitor_time']\r
+        mon_port = metric_dict['mon_port']\r
+\r
+        for port_stat in port_stat_dict[str(switch_dpid)]:\r
+            if int(port_stat['port_no']) == int(mon_port):\r
+                port_uptime = port_stat['duration_sec'] + port_stat['duration_nsec'] * 10 ** (-9)\r
+                this_measurement = int(port_stat[metric_key])\r
+                #logging.info('set prom packets:{0} {1}:{2}'.format(this_measurement, vnf_name, vnf_interface))\r
+\r
+                # set prometheus metric\r
+                self.prom_metrics[metric_key].labels(vnf_name, vnf_interface).set(this_measurement)\r
+\r
+                if previous_monitor_time <= 0 or previous_monitor_time >= port_uptime:\r
+                    metric_dict['previous_measurement'] = int(port_stat[metric_key])\r
+                    metric_dict['previous_monitor_time'] = port_uptime\r
+                    # do first measurement\r
+                    #logging.info('first measurement')\r
+                    time.sleep(1)\r
+                    byte_rate = self.get_network_metrics()\r
+                    return byte_rate\r
+                else:\r
+                    time_delta = (port_uptime - metric_dict['previous_monitor_time'])\r
+                    byte_rate = (this_measurement - metric_dict['previous_measurement']) / float(time_delta)\r
+                    # logging.info('uptime:{2} delta:{0} rate:{1}'.format(time_delta,byte_rate,port_uptime))\r
+\r
+                metric_dict['previous_measurement'] = this_measurement\r
+                metric_dict['previous_monitor_time'] = port_uptime\r
+                return byte_rate\r
+\r
+        logging.exception('metric {0} not found on {1}:{2}'.format(metric_key, vnf_name, vnf_interface))\r
+        return 'metric {0} not found on {1}:{2}'.format(metric_key, vnf_name, vnf_interface)\r
+\r
+\r
     # call this function repeatedly for streaming measurements\r
     def get_rate(self, vnf_name, vnf_interface=None, direction='tx', metric='packets'):\r
 \r
@@ -89,10 +213,17 @@ class DCNetworkMonitor():
             for port_stat in port_stat_dict[str(self.switch_dpid)]:\r
                 if port_stat['port_no'] == self.mon_port:\r
                     port_uptime = port_stat['duration_sec'] + port_stat['duration_nsec'] * 10 ** (-9)\r
-                    this_measurement = port_stat[key]\r
+                    this_measurement = int(port_stat[key])\r
+                    #logging.info('packets:{0}'.format(this_measurement))\r
+\r
+                    # set prometheus metrics\r
+                    if metric == 'packets':\r
+                        self.prom_tx_packet_count.labels(self.vnf_name, self.vnf_interface).set(this_measurement)\r
+                    elif metric == 'bytes':\r
+                        self.prom_tx_byte_count.labels(self.vnf_name, self.vnf_interface).set(this_measurement)\r
 \r
                     if self.previous_monitor_time <= 0 or self.previous_monitor_time >= port_uptime:\r
-                        self.previous_measurement = port_stat[key]\r
+                        self.previous_measurement = int(port_stat[key])\r
                         self.previous_monitor_time = port_uptime\r
                         # do first measurement\r
                         time.sleep(1)\r
index 0bef2fa..8130f84 100755 (executable)
@@ -18,7 +18,6 @@ from emuvim.dcemulator.monitoring import DCNetworkMonitor
 from emuvim.dcemulator.node import Datacenter, EmulatorCompute
 from emuvim.dcemulator.resourcemodel import ResourceModelRegistrar
 
-
 class DCNetwork(Dockernet):
     """
     Wraps the original Mininet/Dockernet class and provides