X-Git-Url: https://osm.etsi.org/gitweb/?p=osm%2Fvim-emu.git;a=blobdiff_plain;f=src%2Femuvim%2Fdcemulator%2Fmonitoring.py;h=ce24a4000867508f92e0cce7c7b326b3c325218a;hp=8db10da6f2192fff4a46d1db295f3f0b1263b4ac;hb=c911ca6a6560d062fed5d294bc5a80c26da69672;hpb=5e040bf29bd5cda68f1416b48227a7419cb6fee0 diff --git a/src/emuvim/dcemulator/monitoring.py b/src/emuvim/dcemulator/monitoring.py index 8db10da..ce24a40 100755 --- a/src/emuvim/dcemulator/monitoring.py +++ b/src/emuvim/dcemulator/monitoring.py @@ -1,18 +1,43 @@ -__author__ = 'Administrator' +""" +Copyright (c) 2015 SONATA-NFV +ALL RIGHTS RESERVED. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Neither the name of the SONATA-NFV [, ANY ADDITIONAL AFFILIATION] +nor the names of its contributors may be used to endorse or promote +products derived from this software without specific prior written +permission. + +This work has been performed in the framework of the SONATA project, +funded by the European Commission under Grant number 671517 through +the Horizon 2020 and 5G-PPP programmes. The authors would like to +acknowledge the contributions of their colleagues of the SONATA +partner consortium (www.sonata-nfv.eu). +""" -import urllib2 import logging +import sys from mininet.node import OVSSwitch import ast import time from prometheus_client import start_http_server, Summary, Histogram, Gauge, Counter, REGISTRY, CollectorRegistry, \ pushadd_to_gateway, push_to_gateway, delete_from_gateway import threading -from subprocess import Popen, PIPE +from subprocess import Popen, check_call import os - -import paramiko -import gevent +import docker +import json logging.basicConfig(level=logging.INFO) @@ -20,20 +45,20 @@ logging.basicConfig(level=logging.INFO) class to read openflow stats from the Ryu controller of the DCNetwork """ +PUSHGATEWAY_PORT = 9091 +# we cannot use port 8080 because ryu-ofrest api is already using that one +CADVISOR_PORT = 8081 + +COOKIE_MASK = 0xffffffff + class DCNetworkMonitor(): def __init__(self, net): self.net = net + self.dockercli = docker.from_env() - prometheus_ip = '0.0.0.0' - prometheus_port = '9090' - self.prometheus_REST_api = 'http://{0}:{1}'.format(prometheus_ip, prometheus_port) - + # pushgateway address + self.pushgateway = 'localhost:{0}'.format(PUSHGATEWAY_PORT) - - # helper variables to calculate the metrics - self.pushgateway = 'localhost:9091' - # Start up the server to expose the metrics to Prometheus. - #start_http_server(8000) # supported Prometheus metrics self.registry = CollectorRegistry() self.prom_tx_packet_count = Gauge('sonemu_tx_count_packets', 'Total number of packets sent', @@ -65,6 +90,7 @@ class DCNetworkMonitor(): self.monitor_flow_lock = threading.Lock() self.network_metrics = [] self.flow_metrics = [] + self.skewmon_metrics = {} # start monitoring thread self.start_monitoring = True @@ -75,9 +101,10 @@ class DCNetworkMonitor(): self.monitor_flow_thread.start() # helper tools - #self.pushgateway_process = self.start_PushGateway() - #self.prometheus_process = self.start_Prometheus() - self.cadvisor_process = self.start_cadvisor() + # cAdvisor, Prometheus pushgateway are started as external container, to gather monitoring metric in son-emu + self.pushgateway_process = self.start_PushGateway() + self.cadvisor_process = self.start_cAdvisor() + # first set some parameters, before measurement can start def setup_flow(self, vnf_name, vnf_interface=None, metric='tx_packets', cookie=0): @@ -98,10 +125,8 @@ class DCNetworkMonitor(): 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: - # logging.info("{0},{1}".format(link_dict[link],vnf_interface)) 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)) vnf_switch = connected_sw flow_metric['mon_port'] = link_dict[link]['dst_port_nr'] break @@ -139,7 +164,15 @@ class DCNetworkMonitor(): logging.exception("setup_metric error.") return ex.message - def stop_flow(self, vnf_name, vnf_interface=None, metric=None, cookie=0): + def stop_flow(self, vnf_name, vnf_interface=None, metric=None, cookie=0,): + + # check if port is specified (vnf:port) + if vnf_interface is None and metric is not None: + # take first interface by default + connected_sw = self.net.DCNetwork_graph.neighbors(vnf_name)[0] + link_dict = self.net.DCNetwork_graph[vnf_name][connected_sw] + vnf_interface = link_dict[0]['src_port_id'] + for flow_dict in self.flow_metrics: if flow_dict['vnf_name'] == vnf_name and flow_dict['vnf_interface'] == vnf_interface \ and flow_dict['metric_key'] == metric and flow_dict['cookie'] == cookie: @@ -148,11 +181,10 @@ class DCNetworkMonitor(): self.flow_metrics.remove(flow_dict) - for collector in self.registry._collectors: - if (vnf_name, vnf_interface, cookie) in collector._metrics: - #logging.info('2 name:{0} labels:{1} metrics:{2}'.format(collector._name, collector._labelnames, - # collector._metrics)) - collector.remove(vnf_name, vnf_interface, cookie) + # set metric to NaN + self.prom_metrics[flow_dict['metric_key']]. \ + labels(vnf_name=vnf_name, vnf_interface=vnf_interface, flow_id=cookie). \ + set(float('nan')) delete_from_gateway(self.pushgateway, job='sonemu-SDNcontroller') @@ -161,6 +193,8 @@ class DCNetworkMonitor(): logging.info('Stopped monitoring flow {3}: {2} on {0}:{1}'.format(vnf_name, vnf_interface, metric, cookie)) return 'Stopped monitoring flow {3}: {2} on {0}:{1}'.format(vnf_name, vnf_interface, metric, cookie) + return 'Error stopping monitoring flow: {0} on {1}:{2}'.format(metric, vnf_name, vnf_interface) + # first set some parameters, before measurement can start def setup_metric(self, vnf_name, vnf_interface=None, metric='tx_packets'): @@ -180,10 +214,8 @@ class DCNetworkMonitor(): 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: - # logging.info("{0},{1}".format(link_dict[link],vnf_interface)) 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)) network_metric['mon_port'] = link_dict[link]['dst_port_nr'] break @@ -220,7 +252,6 @@ class DCNetworkMonitor(): network_metric['metric_key'] = metric self.monitor_lock.acquire() - self.network_metrics.append(network_metric) self.monitor_lock.release() @@ -234,8 +265,14 @@ class DCNetworkMonitor(): def stop_metric(self, vnf_name, vnf_interface=None, metric=None): + # check if port is specified (vnf:port) + if vnf_interface is None and metric is not None: + # take first interface by default + connected_sw = self.net.DCNetwork_graph.neighbors(vnf_name)[0] + link_dict = self.net.DCNetwork_graph[vnf_name][connected_sw] + vnf_interface = link_dict[0]['src_port_id'] + for metric_dict in self.network_metrics: - #logging.info('start Stopped monitoring: {2} on {0}:{1}'.format(vnf_name, vnf_interface, metric_dict)) if metric_dict['vnf_name'] == vnf_name and metric_dict['vnf_interface'] == vnf_interface \ and metric_dict['metric_key'] == metric: @@ -243,30 +280,11 @@ class DCNetworkMonitor(): self.network_metrics.remove(metric_dict) - #this removes the complete metric, all labels... - #REGISTRY.unregister(self.prom_metrics[metric_dict['metric_key']]) - #self.registry.unregister(self.prom_metrics[metric_dict['metric_key']]) - - for collector in self.registry._collectors : - #logging.info('name:{0} labels:{1} metrics:{2}'.format(collector._name, collector._labelnames, collector._metrics)) - """ - INFO:root:name:sonemu_rx_count_packets - labels:('vnf_name', 'vnf_interface') - metrics:{(u'tsrc', u'output'): < prometheus_client.core.Gauge - object - at - 0x7f353447fd10 >} - """ - logging.info('{0}'.format(collector._metrics.values())) - #if self.prom_metrics[metric_dict['metric_key']] - if (vnf_name, vnf_interface, 'None') in collector._metrics: - logging.info('2 name:{0} labels:{1} metrics:{2}'.format(collector._name, collector._labelnames, - collector._metrics)) - #collector._metrics = {} - collector.remove(vnf_name, vnf_interface, 'None') - # 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')) + self.prom_metrics[metric_dict['metric_key']]. \ + labels(vnf_name=vnf_name, vnf_interface=vnf_interface, flow_id=None). \ + set(float('nan')) # this removes the complete metric, all labels... # 1 single monitor job for all metrics of the SDN controller @@ -297,8 +315,10 @@ class DCNetworkMonitor(): logging.info('Stopped monitoring vnf: {0}'.format(vnf_name)) return 'Stopped monitoring: {0}'.format(vnf_name) + return 'Error stopping monitoring metric: {0} on {1}:{2}'.format(metric, vnf_name, vnf_interface) + - # get all metrics defined in the list and export it to Prometheus +# get all metrics defined in the list and export it to Prometheus def get_flow_metrics(self): while self.start_monitoring: @@ -308,6 +328,7 @@ class DCNetworkMonitor(): data = {} data['cookie'] = flow_dict['cookie'] + data['cookie_mask'] = COOKIE_MASK if 'tx' in flow_dict['metric_key']: data['match'] = {'in_port':flow_dict['mon_port']} @@ -317,11 +338,24 @@ class DCNetworkMonitor(): # query Ryu ret = self.net.ryu_REST('stats/flow', dpid=flow_dict['switch_dpid'], data=data) - flow_stat_dict = ast.literal_eval(ret) + if isinstance(ret, dict): + flow_stat_dict = ret + elif isinstance(ret, basestring): + flow_stat_dict = ast.literal_eval(ret.rstrip()) + else: + flow_stat_dict = None + + logging.debug('received flow stat:{0} '.format(flow_stat_dict)) - #logging.info('received flow stat:{0} '.format(flow_stat_dict)) self.set_flow_metric(flow_dict, flow_stat_dict) + + try: + if len(self.flow_metrics) > 0: + pushadd_to_gateway(self.pushgateway, job='sonemu-SDNcontroller', registry=self.registry) + except Exception, e: + logging.warning("Pushgateway not reachable: {0} {1}".format(Exception, e)) + self.monitor_flow_lock.release() time.sleep(1) @@ -338,14 +372,25 @@ class DCNetworkMonitor(): # query Ryu ret = self.net.ryu_REST('stats/port', dpid=dpid) - port_stat_dict = ast.literal_eval(ret) + if isinstance(ret, dict): + port_stat_dict = ret + elif isinstance(ret, basestring): + port_stat_dict = ast.literal_eval(ret.rstrip()) + else: + port_stat_dict = None 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) + try: + if len(self.network_metrics) > 0: + pushadd_to_gateway(self.pushgateway, job='sonemu-SDNcontroller', registry=self.registry) + except Exception, e: + logging.warning("Pushgateway not reachable: {0} {1}".format(Exception, e)) + self.monitor_lock.release() time.sleep(1) @@ -364,44 +409,38 @@ class DCNetworkMonitor(): 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_name, 'vnf_interface': vnf_interface, 'flow_id': None}).\ + labels(vnf_name=vnf_name, vnf_interface=vnf_interface, flow_id=None).\ set(this_measurement) - #push_to_gateway(self.pushgateway, job='SDNcontroller', - # grouping_key={'metric':metric_dict['metric_key']}, registry=self.registry) - - # 1 single monitor job for all metrics of the SDN controller - pushadd_to_gateway(self.pushgateway, job='sonemu-SDNcontroller', registry=self.registry) + # also the rate is calculated here, but not used for now + # (rate can be easily queried from prometheus also) 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) - self.monitor_lock.release() - - metric_rate = self.get_network_metrics() - return metric_rate + #time.sleep(1) + #self.monitor_lock.release() + # rate cannot be calculated yet (need a first measurement) + metric_rate = None else: time_delta = (port_uptime - metric_dict['previous_monitor_time']) metric_rate = (this_measurement - metric_dict['previous_measurement']) / float(time_delta) - #logging.info('metric: {0} rate:{1}'.format(metric_dict['metric_key'], metric_rate)) metric_dict['previous_measurement'] = this_measurement metric_dict['previous_monitor_time'] = port_uptime - return metric_rate + return logging.exception('metric {0} not found on {1}:{2}'.format(metric_key, vnf_name, vnf_interface)) + logging.exception('monport:{0}, dpid:{1}'.format(mon_port, switch_dpid)) + logging.exception('port dict:{0}'.format(port_stat_dict)) return 'metric {0} not found on {1}:{2}'.format(metric_key, vnf_name, vnf_interface) def set_flow_metric(self, metric_dict, flow_stat_dict): # vnf tx is the datacenter switch rx and vice-versa - #metric_key = self.switch_tx_rx(metric_dict['metric_key']) metric_key = metric_dict['metric_key'] switch_dpid = metric_dict['switch_dpid'] vnf_name = metric_dict['vnf_name'] @@ -410,44 +449,20 @@ class DCNetworkMonitor(): previous_monitor_time = metric_dict['previous_monitor_time'] cookie = metric_dict['cookie'] - # TODO aggregate all found flow stats - flow_stat = flow_stat_dict[str(switch_dpid)][0] - if 'bytes' in metric_key: - counter = flow_stat['byte_count'] - elif 'packet' in metric_key: - counter = flow_stat['packet_count'] + counter = 0 + for flow_stat in flow_stat_dict[str(switch_dpid)]: + if 'bytes' in metric_key: + counter += flow_stat['byte_count'] + elif 'packet' in metric_key: + counter += flow_stat['packet_count'] - flow_uptime = flow_stat['duration_sec'] + flow_stat['duration_nsec'] * 10 ** (-9) + # flow_uptime disabled for now (can give error) + #flow_stat = flow_stat_dict[str(switch_dpid)][0] + #flow_uptime = flow_stat['duration_sec'] + flow_stat['duration_nsec'] * 10 ** (-9) self.prom_metrics[metric_dict['metric_key']]. \ - labels({'vnf_name': vnf_name, 'vnf_interface': vnf_interface, 'flow_id': cookie}). \ + labels(vnf_name=vnf_name, vnf_interface=vnf_interface, flow_id=cookie). \ set(counter) - pushadd_to_gateway(self.pushgateway, job='sonemu-SDNcontroller', registry=self.registry) - - #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 query_Prometheus(self, query): - ''' - escaped_chars='{}[]' - for old in escaped_chars: - new = '\{0}'.format(old) - query = query.replace(old, new) - ''' - url = self.prometheus_REST_api + '/' + 'api/v1/query?query=' + query - #logging.info('query:{0}'.format(url)) - req = urllib2.Request(url) - ret = urllib2.urlopen(req).read() - ret = ast.literal_eval(ret) - if ret['status'] == 'success': - #logging.info('return:{0}'.format(ret)) - try: - ret = ret['data']['result'][0]['value'] - except: - ret = None - else: - ret = None - return ret def start_Prometheus(self, port=9090): # prometheus.yml configuration file is located in the same directory as this file @@ -463,19 +478,20 @@ class DCNetworkMonitor(): logging.info('Start Prometheus container {0}'.format(cmd)) return Popen(cmd) - def start_PushGateway(self, port=9091): + def start_PushGateway(self, port=PUSHGATEWAY_PORT): cmd = ["docker", "run", "-d", "-p", "{0}:9091".format(port), "--name", "pushgateway", + "--label", 'com.containernet=""', "prom/pushgateway" ] logging.info('Start Prometheus Push Gateway container {0}'.format(cmd)) return Popen(cmd) - def start_cadvisor(self, port=8090): + def start_cAdvisor(self, port=CADVISOR_PORT): cmd = ["docker", "run", "--rm", @@ -485,6 +501,7 @@ class DCNetworkMonitor(): "--volume=/var/lib/docker/:/var/lib/docker:ro", "--publish={0}:8080".format(port), "--name=cadvisor", + "--label",'com.containernet=""', "google/cadvisor:latest" ] logging.info('Start cAdvisor container {0}'.format(cmd)) @@ -496,24 +513,14 @@ class DCNetworkMonitor(): self.monitor_thread.join() self.monitor_flow_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') + # these containers are used for monitoring but are started now outside of son-emu if self.pushgateway_process is not None: logging.info('stopping pushgateway container') - self.pushgateway_process.terminate() - self.pushgateway_process.kill() self._stop_container('pushgateway') - ''' 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=''): @@ -527,43 +534,94 @@ class DCNetworkMonitor(): return metric def _stop_container(self, name): - cmd = ["docker", - "stop", - name] - Popen(cmd).wait() - cmd = ["docker", - "rm", - name] - Popen(cmd).wait() - - def profile(self, mgmt_ip, rate, input_ip, vnf_uuid ): - - ssh = paramiko.SSHClient() - ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) - #ssh.connect(mgmt_ip, username='steven', password='test') - ssh.connect(mgmt_ip, username='root', password='root') - - iperf_cmd = 'iperf -c {0} -u -l18 -b{1}M -t1000 &'.format(input_ip, rate) - if rate > 0: - stdin, stdout, stderr = ssh.exec_command(iperf_cmd) - - start_time = time.time() - query_cpu = '(sum(rate(container_cpu_usage_seconds_total{{id="/docker/{0}"}}[{1}s])))'.format(vnf_uuid, 1) - while (time.time() - start_time) < 15: - data = self.query_Prometheus(query_cpu) - # logging.info('rate: {1} data:{0}'.format(data, rate)) - gevent.sleep(0) - time.sleep(1) + #container = self.dockercli.containers.get(name) + #container.stop() + #container.remove(force=True) + + # the only robust way to stop these containers is via Popen, it seems + time.sleep(1) + cmd = ['docker', 'rm', '-f', name] + Popen(cmd) + + + def update_skewmon(self, vnf_name, resource_name, action): + + ret = '' + + config_file_path = '/tmp/skewmon.cfg' + configfile = open(config_file_path, 'a+') + try: + config = json.load(configfile) + except: + #not a valid json file or empty + config = {} + + #initialize config file + if len(self.skewmon_metrics) == 0: + config = {} + json.dump(config, configfile) + configfile.close() + + docker_name = 'mn.' + vnf_name + vnf_container = self.dockercli.containers.get(docker_name) + key = resource_name + '_' + vnf_container.short_id + vnf_id = vnf_container.id + + if action == 'start': + # add a new vnf to monitor + config[key] = dict(VNF_NAME=vnf_name, + VNF_ID=vnf_id, + VNF_METRIC=resource_name) + ret = 'adding to skewness monitor: {0} {1} '.format(vnf_name, resource_name) + logging.info(ret) + elif action == 'stop': + # remove vnf to monitor + config.pop(key) + ret = 'removing from skewness monitor: {0} {1} '.format(vnf_name, resource_name) + logging.info(ret) + + self.skewmon_metrics = config + configfile = open(config_file_path, 'w') + json.dump(config, configfile) + configfile.close() + + try: + skewmon_container = self.dockercli.containers.get('skewmon') + + # remove container if config is empty + if len(config) == 0: + ret += 'stopping skewness monitor' + logging.info('stopping skewness monitor') + skewmon_container.remove(force=True) + + except docker.errors.NotFound: + # start container if not running + ret += 'starting skewness monitor' + logging.info('starting skewness monitor') + volumes = {'/sys/fs/cgroup':{'bind':'/sys/fs/cgroup', 'mode':'ro'}, + '/tmp/skewmon.cfg':{'bind':'/config.txt', 'mode':'ro'}} + self.dockercli.containers.run('skewmon', + detach=True, + volumes=volumes, + labels=['com.containernet'], + name='skewmon' + ) + # Wait a while for containers to be completely started + started = False + wait_time = 0 + while not started: + list1 = self.dockercli.containers.list(filters={'status': 'running', 'name': 'prometheus'}) + if len(list1) >= 1: + time.sleep(1) + started = True + if wait_time > 5: + return 'skewmon not started' + time.sleep(1) + wait_time += 1 + return ret + - query_cpu2 = '(sum(rate(container_cpu_usage_seconds_total{{id="/docker/{0}"}}[{1}s])))'.format(vnf_uuid, 8) - cpu_load = float(self.query_Prometheus(query_cpu2)[1]) - output = 'rate: {1}Mbps; cpu_load: {0}%'.format(round(cpu_load * 100, 2), rate) - output_line = output - logging.info(output_line) - stop_iperf = 'pkill -9 iperf' - stdin, stdout, stderr = ssh.exec_command(stop_iperf) - return output_line