Merge pull request #75 from stevenvanrossem/master
authorstevenvanrossem <steven.vanrossem@intec.ugent.be>
Fri, 15 Apr 2016 14:32:35 +0000 (16:32 +0200)
committerstevenvanrossem <steven.vanrossem@intec.ugent.be>
Fri, 15 Apr 2016 14:32:35 +0000 (16:32 +0200)
start prometheus and cadvisor docker containers as monitoring tools

ansible/install.yml
setup.py
src/emuvim/api/zerorpc/network.py
src/emuvim/cli/monitor.py
src/emuvim/dcemulator/monitoring.py
src/emuvim/dcemulator/net.py
src/emuvim/dcemulator/prometheus.yml [new file with mode: 0644]

index 19c1ef2..b31615e 100755 (executable)
@@ -53,3 +53,9 @@
 
    - name: install docker-py
      pip: name=docker-py state=latest
+
+   - name: install prometheus_client
+     pip: name=prometheus_client state=latest
+
+
+
index 5bcad50..367c4fb 100644 (file)
--- a/setup.py
+++ b/setup.py
@@ -22,7 +22,8 @@ setup(name='emuvim',
           'Flask',
           'flask_restful',
           'docker-py',
-          'requests'
+          'requests',
+         'prometheus_client'
       ],
       zip_safe=False,
       entry_points={
index a64b09e..ac17e25 100644 (file)
@@ -91,23 +91,22 @@ 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):
-        logging.debug("RPC CALL: get rate")
+    def setup_metric(self, vnf_name, vnf_interface, metric):
+        logging.debug("RPC CALL: setup metric")
         try:
-            c = self.net.monitor_agent.setup_rate_measurement(vnf_name, vnf_interface, direction, metric)
+            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
 
-    # get egress(default) or ingress rate of a vnf
-    def monitor_get_rate(self, vnf_name, vnf_interface, direction, metric):
-        logging.debug("RPC CALL: get rate")
+    # remove the rate measurement for a vnf interface
+    def stop_metric(self, vnf_name, vnf_interface, metric):
+        logging.debug("RPC CALL: setup metric")
         try:
-            c = self.net.monitor_agent.get_rate(vnf_name, vnf_interface, direction, metric)
+            c = self.net.monitor_agent.remove_metric(vnf_name, vnf_interface, metric)
             return c
         except Exception as ex:
             logging.exception("RPC error.")
             return ex.message
 
-
index 0c3c515..040fa13 100755 (executable)
@@ -28,22 +28,23 @@ 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
-        self.c.monitor_setup_rate_measurement(\r
+        r = self.c.setup_metric(\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
+        pp.pprint(r)\r
+\r
+    def stop_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.remove_metric(\r
+            vnf_name,\r
+            vnf_interface,\r
+            args.get("metric"))\r
+        pp.pprint(r)\r
 \r
     def _parse_vnf_name(self, vnf_name_str):\r
         vnf_name = vnf_name_str.split(':')[0]\r
@@ -60,20 +61,17 @@ class ZeroRpcClient(object):
 parser = argparse.ArgumentParser(description='son-emu network')\r
 parser.add_argument(\r
     "command",\r
-    help="Action to be executed: get_rate")\r
+    help="Action to be executed")\r
 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
+    help="vnf name:interface to be monitored")\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..82411fd 100755 (executable)
@@ -5,28 +5,70 @@ 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, REGISTRY\r
+import threading\r
+from subprocess import Popen, PIPE\r
+import os\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
-        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
+        # helper variables to calculate the metrics\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.start_monitoring = True\r
+        self.monitor_thread = threading.Thread(target=self.get_network_metrics)\r
+        self.monitor_thread.start()\r
+\r
+        # helper tools\r
+        self.prometheus_process = self.start_Prometheus()\r
+        self.cadvisor_process = self.start_cadvisor()\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 +76,9 @@ 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
+\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 +86,17 @@ 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
                     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,50 +114,171 @@ 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
+\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
+            network_metric['switch_dpid'] = int(str(next_node.dpid), 16)\r
+            network_metric['metric_key'] = metric\r
+\r
+            self.network_metrics.append(network_metric)\r
+\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("setup_metric error.")\r
             return ex.message\r
 \r
+    def stop_metric(self, vnf_name, vnf_interface, metric):\r
+        for metric_dict in self.network_metrics:\r
+            if metric_dict['vnf_name'] == vnf_name and metric_dict['vnf_interface'] == vnf_interface \\r
+                    and metric_dict['metric_key'] == metric:\r
+\r
+                self.network_metrics.remove(metric_dict)\r
+\r
+                #this removes the complete metric, all labels...\r
+                #REGISTRY.unregister(self.prom_metrics[metric_dict['metric_key']])\r
+\r
+                # set values to NaN, prometheus api currently does not support removal of metrics\r
+                self.prom_metrics[metric_dict['metric_key']].labels(vnf_name, vnf_interface).set(float('nan'))\r
+\r
+                logging.info('Stopped monitoring: {2} on {0}:{1}'.format(vnf_name, vnf_interface, metric))\r
+                return 'Stopped monitoring: {2} on {0}:{1}'.format(vnf_name, vnf_interface, metric)\r
+\r
+\r
+    # get all metrics defined in the list and export it to Prometheus\r
+    def get_network_metrics(self):\r
+        while self.start_monitoring:\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
-    # call this function repeatedly for streaming measurements\r
-    def get_rate(self, vnf_name, vnf_interface=None, direction='tx', metric='packets'):\r
-\r
-            key = self.metric_key\r
-\r
-            ret = self.REST_cmd('stats/port', self.switch_dpid)\r
-            port_stat_dict = ast.literal_eval(ret)\r
-            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
-\r
-                    if self.previous_monitor_time <= 0 or self.previous_monitor_time >= port_uptime:\r
-                        self.previous_measurement = port_stat[key]\r
-                        self.previous_monitor_time = port_uptime\r
-                        # do first measurement\r
-                        time.sleep(1)\r
-                        byte_rate = self.get_rate(vnf_name, vnf_interface, direction, metric)\r
-                        return byte_rate\r
-                    else:\r
-                        time_delta = (port_uptime - self.previous_monitor_time)\r
-                        byte_rate = (this_measurement - self.previous_measurement) / float(time_delta)\r
-                        #logging.info('uptime:{2} delta:{0} rate:{1}'.format(time_delta,byte_rate,port_uptime))\r
-\r
-                    self.previous_measurement = this_measurement\r
-                    self.previous_monitor_time = port_uptime\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
+    # add metric to the list to export to Prometheus, parse the Ryu port-stats reply\r
+    def set_network_metric(self, metric_dict, port_stat_dict):\r
+        # vnf tx is the datacenter switch rx and vice-versa\r
+        metric_key = self.switch_tx_rx(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_dict['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
-            return ret\r
 \r
     def REST_cmd(self, prefix, dpid):\r
         url = self.REST_api + '/' + str(prefix) + '/' + str(dpid)\r
         req = urllib2.Request(url)\r
         ret = urllib2.urlopen(req).read()\r
-        return ret
\ No newline at end of file
+        return ret\r
+\r
+    def start_Prometheus(self, port=9090):\r
+        # prometheus.yml configuration file is located in the same directory as this file\r
+        cmd = ["docker",\r
+               "run",\r
+               "--rm",\r
+               "-p", "{0}:9090".format(port),\r
+               "-v", "{0}/prometheus.yml:/etc/prometheus/prometheus.yml".format(os.path.dirname(os.path.abspath(__file__))),\r
+               "--name", "prometheus",\r
+               "prom/prometheus"\r
+               ]\r
+        logging.info('Start Prometheus container {0}'.format(cmd))\r
+        return Popen(cmd)\r
+\r
+    def start_cadvisor(self, port=8090):\r
+        cmd = ["docker",\r
+               "run",\r
+               "--rm",\r
+               "--volume=/:/rootfs:ro",\r
+               "--volume=/var/run:/var/run:rw",\r
+               "--volume=/sys:/sys:ro",\r
+               "--volume=/var/lib/docker/:/var/lib/docker:ro",\r
+               "--publish={0}:8080".format(port),\r
+               "--name=cadvisor",\r
+               "google/cadvisor:latest"\r
+               ]\r
+        logging.info('Start cAdvisor container {0}'.format(cmd))\r
+        return Popen(cmd)\r
+\r
+    def stop(self):\r
+        # stop the monitoring thread\r
+        self.start_monitoring = False\r
+        self.monitor_thread.join()\r
+\r
+        if self.prometheus_process is not None:\r
+            logging.info('stopping prometheus container')\r
+            self.prometheus_process.terminate()\r
+            self.prometheus_process.kill()\r
+            self._stop_container('prometheus')\r
+\r
+        if self.cadvisor_process is not None:\r
+            logging.info('stopping cadvisor container')\r
+            self.cadvisor_process.terminate()\r
+            self.cadvisor_process.kill()\r
+            self._stop_container('cadvisor')\r
+\r
+    def switch_tx_rx(self,metric=''):\r
+        # when monitoring vnfs, the tx of the datacenter switch is actually the rx of the vnf\r
+        # so we need to change the metric name to be consistent with the vnf rx or tx\r
+        if 'tx' in metric:\r
+            metric = metric.replace('tx','rx')\r
+        elif 'rx' in metric:\r
+            metric = metric.replace('rx','tx')\r
+\r
+        return metric\r
+\r
+    def _stop_container(self, name):\r
+        cmd = ["docker",\r
+               "stop",\r
+               name]\r
+        Popen(cmd).wait()\r
+\r
+        cmd = ["docker",\r
+               "rm",\r
+               name]\r
+        Popen(cmd).wait()\r
+\r
+\r
index 0bef2fa..f237cb5 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
@@ -27,7 +26,7 @@ class DCNetwork(Dockernet):
     This class is used by topology definition scripts.
     """
 
-    def __init__(self, controller=RemoteController,
+    def __init__(self, controller=RemoteController, monitor=True,
                  dc_emulation_max_cpu=1.0,  # fraction of overall CPU time for emulation
                  dc_emulation_max_mem=512,  # emulation max mem in MB
                  **kwargs):
@@ -56,7 +55,10 @@ class DCNetwork(Dockernet):
         self.DCNetwork_graph = nx.MultiDiGraph()
 
         # monitoring agent
-        self.monitor_agent = DCNetworkMonitor(self)
+        if monitor:
+            self.monitor_agent = DCNetworkMonitor(self)
+        else:
+            self.monitor_agent = None
 
         # initialize resource model registrar
         self.rm_registrar = ResourceModelRegistrar(
@@ -176,10 +178,18 @@ class DCNetwork(Dockernet):
         Dockernet.start(self)
 
     def stop(self):
-        # stop Ryu controller
+
+        # stop the monitor agent
+        if self.monitor_agent is not None:
+            self.monitor_agent.stop()
+
+        # stop emulator net
         Dockernet.stop(self)
+
+        # stop Ryu controller
         self.stopRyu()
 
+
     def CLI(self):
         CLI(self)
 
diff --git a/src/emuvim/dcemulator/prometheus.yml b/src/emuvim/dcemulator/prometheus.yml
new file mode 100644 (file)
index 0000000..2915578
--- /dev/null
@@ -0,0 +1,36 @@
+global:
+  scrape_interval:     15s # By default, scrape targets every 15 seconds.
+
+  # Attach these labels to any time series or alerts when communicating with
+  # external systems (federation, remote storage, Alertmanager).
+  external_labels:
+    monitor: 'codelab-monitor'
+
+# A scrape configuration containing exactly one endpoint to scrape:
+# Here it's Prometheus itself.
+scrape_configs:
+  # The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
+  - job_name: 'prometheus'
+
+    # Override the global default and scrape targets from this job every 5 seconds.
+    scrape_interval: 5s
+
+    target_groups:
+      #- targets: ['localhost:9090']
+
+  - job_name: 'son-emu'
+
+    # Override the global default and scrape targets from this job every 5 seconds.
+    scrape_interval: 5s
+
+    target_groups:
+      - targets: ['172.17.0.1:8000']
+
+  - job_name: 'cAdvisor'
+
+    # Override the global default and scrape targets from this job every 5 seconds.
+    scrape_interval: 5s
+
+    target_groups:
+      - targets: ['172.17.0.1:8090']
+