start cadvisor and prometheus docker container at startup
authorstevenvanrossem <steven.vanrossem@intec.ugent.be>
Fri, 15 Apr 2016 11:28:23 +0000 (13:28 +0200)
committerstevenvanrossem <steven.vanrossem@intec.ugent.be>
Fri, 15 Apr 2016 13:15:51 +0000 (15:15 +0200)
src/emuvim/api/zerorpc/network.py
src/emuvim/cli/monitor.py
src/emuvim/dcemulator/monitoring.py

index 1b7e1e0..f21ce99 100644 (file)
@@ -100,6 +100,16 @@ class DCNetworkApi(object):
             logging.exception("RPC error.")
             return ex.message
 
+    # remove the rate measurement for a vnf interface
+    def remove_metric(self, vnf_name, vnf_interface, metric):
+        logging.debug("RPC CALL: setup metric")
+        try:
+            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
+
     # 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")
index 1d4abfb..bae0c07 100755 (executable)
@@ -36,19 +36,15 @@ class ZeroRpcClient(object):
             vnf_interface,\r
             args.get("metric"))\r
         pp.pprint(r)\r
-        '''\r
-        self.c.monitor_setup_rate_measurement(\r
+\r
+    def remove_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
-        while True:\r
-            r = self.c.monitor_get_rate(\r
-                vnf_name,\r
-                vnf_interface,\r
-                args.get("metric"))\r
-            pp.pprint(r)\r
-            time.sleep(1)\r
-        '''\r
+        pp.pprint(r)\r
 \r
     def _parse_vnf_name(self, vnf_name_str):\r
         vnf_name = vnf_name_str.split(':')[0]\r
index d745069..7fa5e18 100755 (executable)
@@ -7,8 +7,8 @@ import ast
 import time\r
 from prometheus_client import start_http_server, Summary, Histogram, Gauge, Counter\r
 import threading\r
-from subprocess import Popen\r
-from os import getcwd\r
+from subprocess import Popen, PIPE\r
+import os\r
 \r
 logging.basicConfig(level=logging.INFO)\r
 \r
@@ -25,16 +25,6 @@ class DCNetworkMonitor():
         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.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
@@ -66,13 +56,13 @@ class DCNetworkMonitor():
         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 = None\r
-        self.cAdvisor_process = None\r
-\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_metric(self, vnf_name, vnf_interface=None, metric='tx_packets'):\r
@@ -88,8 +78,6 @@ class DCNetworkMonitor():
 \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
@@ -99,7 +87,6 @@ class DCNetworkMonitor():
                     # found the right link and connected switch\r
                     # logging.info("{0},{1}".format(link_dict[link]['src_port_id'], vnf_source_interface))\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
@@ -129,13 +116,11 @@ class DCNetworkMonitor():
 \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
 \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
 \r
             self.network_metrics.append(network_metric)\r
 \r
@@ -146,10 +131,18 @@ class DCNetworkMonitor():
             logging.exception("get_rate error.")\r
             return ex.message\r
 \r
+    def remove_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'] == metric:\r
+                self.network_metrics.remove(metric_dict)\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
-    # get all metrics defined in the list\r
+\r
+    # get all metrics defined in the list and export it to Prometheus\r
     def get_network_metrics(self):\r
-        while True:\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
@@ -168,10 +161,10 @@ class DCNetworkMonitor():
 \r
             time.sleep(1)\r
 \r
-    # call this function repeatedly for streaming measurements\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
-\r
-        metric_key = metric_dict['metric_key']\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
@@ -209,43 +202,6 @@ class DCNetworkMonitor():
         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
-            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 = 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 = int(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
-                    return byte_rate\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
@@ -253,18 +209,19 @@ class DCNetworkMonitor():
         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(getcwd()),\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
-        self.prometheus_process = Popen(cmd)\r
-\r
-    def start_cAdvisor(self, port=8090):\r
+    def start_cadvisor(self, port=8090):\r
         cmd = ["docker",\r
                "run",\r
                "--rm",\r
@@ -276,13 +233,45 @@ class DCNetworkMonitor():
                "--name=cadvisor",\r
                "google/cadvisor:latest"\r
                ]\r
-        self.cAdvisor_process = Popen(cmd)\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
-        if self.cAdvisor_process is not None:\r
-            self.cAdvisor_process.terminate()\r
-            self.cAdvisor_process.kill()\r