Merge pull request #75 from stevenvanrossem/master
start prometheus and cadvisor docker containers as monitoring tools
diff --git a/ansible/install.yml b/ansible/install.yml
index 19c1ef2..b31615e 100755
--- a/ansible/install.yml
+++ b/ansible/install.yml
@@ -53,3 +53,9 @@
- name: install docker-py
pip: name=docker-py state=latest
+
+ - name: install prometheus_client
+ pip: name=prometheus_client state=latest
+
+
+
diff --git a/setup.py b/setup.py
index 5bcad50..367c4fb 100644
--- a/setup.py
+++ b/setup.py
@@ -22,7 +22,8 @@
'Flask',
'flask_restful',
'docker-py',
- 'requests'
+ 'requests',
+ 'prometheus_client'
],
zip_safe=False,
entry_points={
diff --git a/src/emuvim/api/zerorpc/network.py b/src/emuvim/api/zerorpc/network.py
index a64b09e..ac17e25 100644
--- a/src/emuvim/api/zerorpc/network.py
+++ b/src/emuvim/api/zerorpc/network.py
@@ -91,23 +91,22 @@
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
-
diff --git a/src/emuvim/cli/monitor.py b/src/emuvim/cli/monitor.py
index 0c3c515..040fa13 100755
--- a/src/emuvim/cli/monitor.py
+++ b/src/emuvim/cli/monitor.py
@@ -28,22 +28,23 @@
else:
print "Command not implemented."
- def get_rate(self, args):
+ def setup_metric(self, args):
vnf_name = self._parse_vnf_name(args.get("vnf_name"))
vnf_interface = self._parse_vnf_interface(args.get("vnf_name"))
- self.c.monitor_setup_rate_measurement(
+ r = self.c.setup_metric(
vnf_name,
vnf_interface,
- args.get("direction"),
args.get("metric"))
- while True:
- r = self.c.monitor_get_rate(
- vnf_name,
- vnf_interface,
- args.get("direction"),
- args.get("metric"))
- pp.pprint(r)
- time.sleep(1)
+ pp.pprint(r)
+
+ def stop_metric(self, args):
+ vnf_name = self._parse_vnf_name(args.get("vnf_name"))
+ vnf_interface = self._parse_vnf_interface(args.get("vnf_name"))
+ r = self.c.remove_metric(
+ vnf_name,
+ vnf_interface,
+ args.get("metric"))
+ pp.pprint(r)
def _parse_vnf_name(self, vnf_name_str):
vnf_name = vnf_name_str.split(':')[0]
@@ -60,20 +61,17 @@
parser = argparse.ArgumentParser(description='son-emu network')
parser.add_argument(
"command",
- help="Action to be executed: get_rate")
+ help="Action to be executed")
parser.add_argument(
"--vnf_name", "-vnf", dest="vnf_name",
- help="vnf name to be monitored")
-parser.add_argument(
- "--direction", "-d", dest="direction",
- help="rx (ingress rate) or tx (egress rate)")
+ help="vnf name:interface to be monitored")
parser.add_argument(
"--metric", "-m", dest="metric",
- help="bytes (byte rate), packets (packet rate)")
+ help="tx_bytes, rx_bytes, tx_packets, rx_packets")
def main(argv):
- print "This is the son-emu monitor CLI."
- print "Arguments: %s" % str(argv)
+ #print "This is the son-emu monitor CLI."
+ #print "Arguments: %s" % str(argv)
args = vars(parser.parse_args(argv))
c = ZeroRpcClient()
c.execute_command(args)
diff --git a/src/emuvim/dcemulator/monitoring.py b/src/emuvim/dcemulator/monitoring.py
index 50393ea..82411fd 100755
--- a/src/emuvim/dcemulator/monitoring.py
+++ b/src/emuvim/dcemulator/monitoring.py
@@ -5,28 +5,70 @@
from mininet.node import OVSSwitch
import ast
import time
+from prometheus_client import start_http_server, Summary, Histogram, Gauge, Counter, REGISTRY
+import threading
+from subprocess import Popen, PIPE
+import os
+
logging.basicConfig(level=logging.INFO)
"""
-class to read openflow stats from the Ryu controller of the DCNEtwork
+class to read openflow stats from the Ryu controller of the DCNetwork
"""
class DCNetworkMonitor():
def __init__(self, net):
self.net = net
- # link to REST_API
+ # link to Ryu REST_API
self.ip = '0.0.0.0'
self.port = '8080'
self.REST_api = 'http://{0}:{1}'.format(self.ip,self.port)
- self.previous_measurement = 0
- self.previous_monitor_time = 0
- self.switch_dpid = 0
- self.metric_key = None
- self.mon_port = None
+ # helper variables to calculate the metrics
+ # Start up the server to expose the metrics to Prometheus.
+ start_http_server(8000)
+ # supported Prometheus metrics
+ self.prom_tx_packet_count = Gauge('sonemu_tx_count_packets', 'Total number of packets sent',
+ ['vnf_name', 'vnf_interface'])
+ self.prom_rx_packet_count = Gauge('sonemu_rx_count_packets', 'Total number of packets received',
+ ['vnf_name', 'vnf_interface'])
+ self.prom_tx_byte_count = Gauge('sonemu_tx_count_bytes', 'Total number of bytes sent',
+ ['vnf_name', 'vnf_interface'])
+ self.prom_rx_byte_count = Gauge('sonemu_rx_count_bytes', 'Total number of bytes received',
+ ['vnf_name', 'vnf_interface'])
+
+ self.prom_metrics={'tx_packets':self.prom_tx_packet_count, 'rx_packets':self.prom_rx_packet_count,
+ 'tx_bytes':self.prom_tx_byte_count,'rx_bytes':self.prom_rx_byte_count}
+
+ # list of installed metrics to monitor
+ # each entry can contain this data
+ '''
+ {
+ switch_dpid = 0
+ vnf_name = None
+ vnf_interface = None
+ previous_measurement = 0
+ previous_monitor_time = 0
+ metric_key = None
+ mon_port = None
+ }
+ '''
+ self.network_metrics = []
+
+ # start monitoring thread
+ self.start_monitoring = True
+ self.monitor_thread = threading.Thread(target=self.get_network_metrics)
+ self.monitor_thread.start()
+
+ # helper tools
+ self.prometheus_process = self.start_Prometheus()
+ self.cadvisor_process = self.start_cadvisor()
# first set some parameters, before measurement can start
- def setup_rate_measurement(self, vnf_name, vnf_interface=None, direction='tx', metric='packets'):
+ def setup_metric(self, vnf_name, vnf_interface=None, metric='tx_packets'):
+
+ network_metric = {}
+
# check if port is specified (vnf:port)
if vnf_interface is None:
# take first interface by default
@@ -34,6 +76,9 @@
link_dict = self.net.DCNetwork_graph[vnf_name][connected_sw]
vnf_interface = link_dict[0]['src_port_id']
+ network_metric['vnf_name'] = vnf_name
+ network_metric['vnf_interface'] = vnf_interface
+
for connected_sw in self.net.DCNetwork_graph.neighbors(vnf_name):
link_dict = self.net.DCNetwork_graph[vnf_name][connected_sw]
for link in link_dict:
@@ -41,15 +86,17 @@
if link_dict[link]['src_port_id'] == vnf_interface:
# found the right link and connected switch
# logging.info("{0},{1}".format(link_dict[link]['src_port_id'], vnf_source_interface))
- self.mon_port = link_dict[link]['dst_port']
+ network_metric['mon_port'] = link_dict[link]['dst_port']
break
+ if 'mon_port' not in network_metric:
+ logging.exception("vnf interface {0}:{1} not found!".format(vnf_name,vnf_interface))
+ return "vnf interface {0}:{1} not found!".format(vnf_name,vnf_interface)
+
try:
# default port direction to monitor
- if direction is None:
- direction = 'tx'
if metric is None:
- metric = 'packets'
+ metric = 'tx_packets'
vnf_switch = self.net.DCNetwork_graph.neighbors(str(vnf_name))
@@ -67,50 +114,171 @@
logging.info("vnf: {0} is not connected to switch".format(vnf_name))
return
- self.previous_measurement = 0
- self.previous_monitor_time = 0
+ network_metric['previous_measurement'] = 0
+ network_metric['previous_monitor_time'] = 0
- #self.switch_dpid = x = int(str(next_node.dpid), 16)
- self.switch_dpid = int(str(next_node.dpid), 16)
- self.metric_key = '{0}_{1}'.format(direction, metric)
+
+ network_metric['switch_dpid'] = int(str(next_node.dpid), 16)
+ network_metric['metric_key'] = metric
+
+ self.network_metrics.append(network_metric)
+
+ logging.info('Started monitoring: {2} on {0}:{1}'.format(vnf_name, vnf_interface, metric))
+ return 'Started monitoring: {2} on {0}:{1}'.format(vnf_name, vnf_interface, metric)
except Exception as ex:
- logging.exception("get_txrate error.")
+ logging.exception("setup_metric error.")
return ex.message
+ def stop_metric(self, vnf_name, vnf_interface, metric):
+ for metric_dict in self.network_metrics:
+ if metric_dict['vnf_name'] == vnf_name and metric_dict['vnf_interface'] == vnf_interface \
+ and metric_dict['metric_key'] == metric:
- # call this function repeatedly for streaming measurements
- def get_rate(self, vnf_name, vnf_interface=None, direction='tx', metric='packets'):
+ self.network_metrics.remove(metric_dict)
- key = self.metric_key
+ #this removes the complete metric, all labels...
+ #REGISTRY.unregister(self.prom_metrics[metric_dict['metric_key']])
- ret = self.REST_cmd('stats/port', self.switch_dpid)
- port_stat_dict = ast.literal_eval(ret)
- for port_stat in port_stat_dict[str(self.switch_dpid)]:
- if port_stat['port_no'] == self.mon_port:
- port_uptime = port_stat['duration_sec'] + port_stat['duration_nsec'] * 10 ** (-9)
- this_measurement = port_stat[key]
+ # set values to NaN, prometheus api currently does not support removal of metrics
+ self.prom_metrics[metric_dict['metric_key']].labels(vnf_name, vnf_interface).set(float('nan'))
- if self.previous_monitor_time <= 0 or self.previous_monitor_time >= port_uptime:
- self.previous_measurement = port_stat[key]
- self.previous_monitor_time = port_uptime
- # do first measurement
- time.sleep(1)
- byte_rate = self.get_rate(vnf_name, vnf_interface, direction, metric)
- return byte_rate
- else:
- time_delta = (port_uptime - self.previous_monitor_time)
- byte_rate = (this_measurement - self.previous_measurement) / float(time_delta)
- #logging.info('uptime:{2} delta:{0} rate:{1}'.format(time_delta,byte_rate,port_uptime))
+ logging.info('Stopped monitoring: {2} on {0}:{1}'.format(vnf_name, vnf_interface, metric))
+ return 'Stopped monitoring: {2} on {0}:{1}'.format(vnf_name, vnf_interface, metric)
- self.previous_measurement = this_measurement
- self.previous_monitor_time = port_uptime
+
+ # get all metrics defined in the list and export it to Prometheus
+ def get_network_metrics(self):
+ while self.start_monitoring:
+ # group metrics by dpid to optimize the rest api calls
+ dpid_list = [metric_dict['switch_dpid'] for metric_dict in self.network_metrics]
+ dpid_set = set(dpid_list)
+
+ for dpid in dpid_set:
+
+ # query Ryu
+ ret = self.REST_cmd('stats/port', dpid)
+ port_stat_dict = ast.literal_eval(ret)
+
+ metric_list = [metric_dict for metric_dict in self.network_metrics
+ if int(metric_dict['switch_dpid'])==int(dpid)]
+ #logging.info('1set prom packets:{0} '.format(self.network_metrics))
+ for metric_dict in metric_list:
+ self.set_network_metric(metric_dict, port_stat_dict)
+
+ time.sleep(1)
+
+ # add metric to the list to export to Prometheus, parse the Ryu port-stats reply
+ def set_network_metric(self, metric_dict, port_stat_dict):
+ # vnf tx is the datacenter switch rx and vice-versa
+ metric_key = self.switch_tx_rx(metric_dict['metric_key'])
+ switch_dpid = metric_dict['switch_dpid']
+ vnf_name = metric_dict['vnf_name']
+ vnf_interface = metric_dict['vnf_interface']
+ previous_measurement = metric_dict['previous_measurement']
+ previous_monitor_time = metric_dict['previous_monitor_time']
+ mon_port = metric_dict['mon_port']
+
+ for port_stat in port_stat_dict[str(switch_dpid)]:
+ if int(port_stat['port_no']) == int(mon_port):
+ port_uptime = port_stat['duration_sec'] + port_stat['duration_nsec'] * 10 ** (-9)
+ this_measurement = int(port_stat[metric_key])
+ #logging.info('set prom packets:{0} {1}:{2}'.format(this_measurement, vnf_name, vnf_interface))
+
+ # set prometheus metric
+ self.prom_metrics[metric_dict['metric_key']].labels(vnf_name, vnf_interface).set(this_measurement)
+
+ if previous_monitor_time <= 0 or previous_monitor_time >= port_uptime:
+ metric_dict['previous_measurement'] = int(port_stat[metric_key])
+ metric_dict['previous_monitor_time'] = port_uptime
+ # do first measurement
+ #logging.info('first measurement')
+ time.sleep(1)
+ byte_rate = self.get_network_metrics()
return byte_rate
+ else:
+ time_delta = (port_uptime - metric_dict['previous_monitor_time'])
+ byte_rate = (this_measurement - metric_dict['previous_measurement']) / float(time_delta)
+ # logging.info('uptime:{2} delta:{0} rate:{1}'.format(time_delta,byte_rate,port_uptime))
- return ret
+ metric_dict['previous_measurement'] = this_measurement
+ metric_dict['previous_monitor_time'] = port_uptime
+ return byte_rate
+
+ logging.exception('metric {0} not found on {1}:{2}'.format(metric_key, vnf_name, vnf_interface))
+ return 'metric {0} not found on {1}:{2}'.format(metric_key, vnf_name, vnf_interface)
+
def REST_cmd(self, prefix, dpid):
url = self.REST_api + '/' + str(prefix) + '/' + str(dpid)
req = urllib2.Request(url)
ret = urllib2.urlopen(req).read()
- return ret
\ No newline at end of file
+ return ret
+
+ def start_Prometheus(self, port=9090):
+ # prometheus.yml configuration file is located in the same directory as this file
+ cmd = ["docker",
+ "run",
+ "--rm",
+ "-p", "{0}:9090".format(port),
+ "-v", "{0}/prometheus.yml:/etc/prometheus/prometheus.yml".format(os.path.dirname(os.path.abspath(__file__))),
+ "--name", "prometheus",
+ "prom/prometheus"
+ ]
+ logging.info('Start Prometheus container {0}'.format(cmd))
+ return Popen(cmd)
+
+ def start_cadvisor(self, port=8090):
+ cmd = ["docker",
+ "run",
+ "--rm",
+ "--volume=/:/rootfs:ro",
+ "--volume=/var/run:/var/run:rw",
+ "--volume=/sys:/sys:ro",
+ "--volume=/var/lib/docker/:/var/lib/docker:ro",
+ "--publish={0}:8080".format(port),
+ "--name=cadvisor",
+ "google/cadvisor:latest"
+ ]
+ logging.info('Start cAdvisor container {0}'.format(cmd))
+ return Popen(cmd)
+
+ def stop(self):
+ # stop the monitoring thread
+ self.start_monitoring = False
+ self.monitor_thread.join()
+
+ if self.prometheus_process is not None:
+ logging.info('stopping prometheus container')
+ self.prometheus_process.terminate()
+ self.prometheus_process.kill()
+ self._stop_container('prometheus')
+
+ if self.cadvisor_process is not None:
+ logging.info('stopping cadvisor container')
+ self.cadvisor_process.terminate()
+ self.cadvisor_process.kill()
+ self._stop_container('cadvisor')
+
+ def switch_tx_rx(self,metric=''):
+ # when monitoring vnfs, the tx of the datacenter switch is actually the rx of the vnf
+ # so we need to change the metric name to be consistent with the vnf rx or tx
+ if 'tx' in metric:
+ metric = metric.replace('tx','rx')
+ elif 'rx' in metric:
+ metric = metric.replace('rx','tx')
+
+ return metric
+
+ def _stop_container(self, name):
+ cmd = ["docker",
+ "stop",
+ name]
+ Popen(cmd).wait()
+
+ cmd = ["docker",
+ "rm",
+ name]
+ Popen(cmd).wait()
+
+
diff --git a/src/emuvim/dcemulator/net.py b/src/emuvim/dcemulator/net.py
index 0bef2fa..f237cb5 100755
--- a/src/emuvim/dcemulator/net.py
+++ b/src/emuvim/dcemulator/net.py
@@ -18,7 +18,6 @@
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 @@
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 @@
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 @@
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
index 0000000..2915578
--- /dev/null
+++ b/src/emuvim/dcemulator/prometheus.yml
@@ -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']
+