Merge pull request #218 from stevenvanrossem/master
authorstevenvanrossem <steven.vanrossem@intec.ugent.be>
Tue, 9 May 2017 12:53:56 +0000 (14:53 +0200)
committerpeusterm <manuel.peuster@uni-paderborn.de>
Tue, 9 May 2017 12:53:56 +0000 (14:53 +0200)
some updates, mainly demo features

src/emuvim/api/rest/compute.py
src/emuvim/api/rest/monitor.py
src/emuvim/api/rest/rest_api_endpoint.py
src/emuvim/dashboard/css/main.css
src/emuvim/dashboard/index.html
src/emuvim/dashboard/js/graph.js
src/emuvim/dashboard/js/main.js
src/emuvim/dcemulator/monitoring.py

index 07d059f..b657660 100755 (executable)
@@ -35,6 +35,7 @@ logging.basicConfig(level=logging.INFO)
 
 CORS_HEADER = {'Access-Control-Allow-Origin': '*'}
 
+# the dcs dict is set in the rest_api_endpoint.py upon datacenter init
 dcs = {}
 
 
@@ -49,6 +50,7 @@ class Compute(Resource):
     example networks list({"id":"input","ip": "10.0.0.254/8"}, {"id":"output","ip": "11.0.0.254/24"})
     :return: docker inspect dict of deployed docker
     """
+
     global dcs
 
     def put(self, dc_label, compute_name, resource=None, value=None):
index 74f7acf..eac10ef 100755 (executable)
@@ -277,10 +277,10 @@ class MonitorSkewAction(Resource):
             c = net.monitor_agent.update_skewmon(vnf_name, resource_name, action='start')
 
             # return monitor message response
-            return  str(c), 200
+            return  str(c), 200, CORS_HEADER
         except Exception as ex:
             logging.exception("API error.")
-            return ex.message, 500
+            return ex.message, 500, CORS_HEADER
 
     def delete(self):
         logging.debug("REST CALL: stop monitor skewness")
@@ -300,3 +300,27 @@ class MonitorSkewAction(Resource):
             logging.exception("API error.")
             return ex.message, 500, CORS_HEADER
 
+class MonitorTerminal(Resource):
+    """
+    start a terminal for the selected VNFs
+    :param vnf_list: list of names of the VNFs to start a terminal from (all VNFs if None)
+    :return: message string indicating if the monitor action is succesful or not
+    """
+    global net
+
+    def get(self):
+        # get URL parameters
+        data = request.args
+        if data is None:
+            data = {}
+        vnf_list = data.get("vnf_list")
+        logging.debug("REST CALL: start terminal for: {}".format(vnf_list))
+        try:
+            # start terminals
+            c = net.monitor_agent.term(vnf_list)
+
+            # return monitor message response
+            return  str(c), 200, CORS_HEADER
+        except Exception as ex:
+            logging.exception("API error.")
+            return ex.message, 500, CORS_HEADER
\ No newline at end of file
index 0c9e1bc..891f95d 100755 (executable)
@@ -41,7 +41,7 @@ import network
 from network import NetworkAction, DrawD3jsgraph
 
 import monitor
-from monitor import MonitorInterfaceAction, MonitorFlowAction, MonitorLinkAction, MonitorSkewAction
+from monitor import MonitorInterfaceAction, MonitorFlowAction, MonitorLinkAction, MonitorSkewAction, MonitorTerminal
 
 import pkg_resources
 from os import path
@@ -103,6 +103,9 @@ class RestApiEndpoint(object):
         # the skewness metric is exported
         self.api.add_resource(MonitorSkewAction,
                               "/restapi/monitor/skewness")
+        # start a terminal window for the specified vnfs
+        self.api.add_resource(MonitorTerminal,
+                              "/restapi/monitor/term")
 
 
         logging.debug("Created API endpoint %s(%s:%d)" % (self.__class__.__name__, self.ip, self.port))
index 5e9162c..6289439 100755 (executable)
@@ -36,7 +36,7 @@ body {
 }
 
 .interface_table {
-    width: 420px;
+    width: 570px;
 }
 
 
@@ -50,4 +50,8 @@ body {
 
 .interface_ip {
    width: 100px;
+}
+
+.interface_mac {
+   width: 150px;
 }
\ No newline at end of file
index abdc2c6..bd57753 100755 (executable)
@@ -25,6 +25,8 @@
     <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
     <![endif]-->
 
+
+
     <script src="js/main.js" type="text/javascript"></script>
 
 
index 5858833..b158bf0 100755 (executable)
@@ -30,6 +30,7 @@ d3.json("http://127.0.0.1:5001/restapi/network/d3jsgraph", function(error, json)
       .enter().append("g")
       .attr("class", "node")
       .call(force.drag)
+      .on("dblclick", dblclick)
 
   node.append("circle")
     .attr("r", 10)
@@ -49,5 +50,17 @@ d3.json("http://127.0.0.1:5001/restapi/network/d3jsgraph", function(error, json)
     node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
   });
 
+  // action to take on double mouse click, call rest api to start xterm
+  function dblclick() {
+      var vnf_name = d3.select(this).text()
+      console.debug(vnf_name)
+      var rest_url = "http://127.0.0.1:5001/restapi/monitor/term?vnf_list=" + vnf_name
+
+      d3.json(rest_url, function(error, json) {
+        if (error) throw error;
+        console.debug(json)
+      });
+  }
+
 
 });
\ No newline at end of file
index c8d65ea..3fdd488 100755 (executable)
@@ -83,7 +83,7 @@ function update_table_container(data)
            build_network_table(item[1].network, item[0]);
     });
     $("#lbl_container_count").text(data.length);
-    $("#table_network").append('<table class="interface_table"><tr class="interface_row"><td class="interface_port">datacenter port</td><td class="interface name">interface</td><td class="interface_ip">ip</td></tr></table>')
+    $("#table_network").append('<table class="interface_table"><tr class="interface_row"><td class="interface_port">datacenter port</td><td class="interface_name">interface</td><td class="interface_ip">ip</td><td class="interface_mac">mac</td></tr></table>')
     // update lateness counter
     LAST_UPDATE_TIMESTAMP_CONTAINER = Date.now();
 }
@@ -96,8 +96,9 @@ function build_network_table(network_list, id)
     network_list.forEach(function(interface) {
         row_str += '<tr class="interface_row">';
         row_str += '<td class="interface_port">' + interface.dc_portname + '</td>';
-        row_str += '<td class="interface name">' + interface.intf_name + '</td>';
+        row_str += '<td class="interface_name">' + interface.intf_name + '</td>';
         row_str += '<td class="interface_ip">' + interface.ip + '</td>';
+        row_str += '<td class="interface_mac">' + interface.mac + '</td>';
         row_str += '</tr>';
     });
     $("#network_list_" + id).append(row_str)
index 78b8007..0d40531 100755 (executable)
@@ -34,10 +34,11 @@ import time
 from prometheus_client import start_http_server, Summary, Histogram, Gauge, Counter, REGISTRY, CollectorRegistry, \\r
     pushadd_to_gateway, push_to_gateway, delete_from_gateway\r
 import threading\r
-from subprocess import Popen, check_call\r
+from subprocess import Popen\r
 import os\r
 import docker\r
 import json\r
+from copy import deepcopy\r
 \r
 logging.basicConfig(level=logging.INFO)\r
 \r
@@ -272,7 +273,7 @@ class DCNetworkMonitor():
             link_dict = self.net.DCNetwork_graph[vnf_name][connected_sw]\r
             vnf_interface = link_dict[0]['src_port_id']\r
 \r
-        for metric_dict in self.network_metrics:\r
+        for metric_dict in deepcopy(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
@@ -302,20 +303,17 @@ class DCNetworkMonitor():
             elif metric_dict['vnf_name'] == vnf_name and vnf_interface is None and metric is None:\r
                 self.monitor_lock.acquire()\r
                 self.network_metrics.remove(metric_dict)\r
-                for collector in self.registry._collectors:\r
-                    collector_dict = collector._metrics.copy()\r
-                    for name, interface, id in collector_dict:\r
-                        if name == vnf_name:\r
-                            logging.info('3 name:{0} labels:{1} metrics:{2}'.format(collector._name, collector._labelnames,\r
-                                                                           collector._metrics))\r
-                            collector.remove(name, interface, 'None')\r
+                logging.info('remove metric from monitor: vnf_name:{0} vnf_interface:{1} mon_port:{2}'.format(metric_dict['vnf_name'], metric_dict['vnf_interface'], metric_dict['mon_port']))\r
 \r
                 delete_from_gateway(self.pushgateway, job='sonemu-SDNcontroller')\r
                 self.monitor_lock.release()\r
-                logging.info('Stopped monitoring vnf: {0}'.format(vnf_name))\r
-                return 'Stopped monitoring: {0}'.format(vnf_name)\r
+                continue\r
 \r
-        return 'Error stopping monitoring metric: {0} on {1}:{2}'.format(metric, vnf_name, vnf_interface)\r
+        if vnf_interface is None and metric is None:\r
+            logging.info('Stopped monitoring vnf: {0}'.format(vnf_name))\r
+            return 'Stopped monitoring: {0}'.format(vnf_name)\r
+        else:\r
+            return 'Error stopping monitoring metric: {0} on {1}:{2}'.format(metric, vnf_name, vnf_interface)\r
 \r
 \r
 # get all metrics defined in the list and export it to Prometheus\r
@@ -430,7 +428,7 @@ class DCNetworkMonitor():
 \r
                 else:\r
                     time_delta = (port_uptime - metric_dict['previous_monitor_time'])\r
-                    metric_rate = (this_measurement - metric_dict['previous_measurement']) / float(time_delta)\r
+                    #metric_rate = (this_measurement - metric_dict['previous_measurement']) / float(time_delta)\r
 \r
                 metric_dict['previous_measurement'] = this_measurement\r
                 metric_dict['previous_monitor_time'] = port_uptime\r
@@ -438,6 +436,7 @@ class DCNetworkMonitor():
 \r
         logging.exception('metric {0} not found on {1}:{2}'.format(metric_key, vnf_name, vnf_interface))\r
         logging.exception('monport:{0}, dpid:{1}'.format(mon_port, switch_dpid))\r
+        logging.exception('monitored network_metrics:{0}'.format(self.network_metrics))\r
         logging.exception('port dict:{0}'.format(port_stat_dict))\r
         return 'metric {0} not found on {1}:{2}'.format(metric_key, vnf_name, vnf_interface)\r
 \r
@@ -627,6 +626,46 @@ class DCNetworkMonitor():
                 wait_time += 1\r
         return ret\r
 \r
+    def term(self, vnf_list=[]):\r
+        """\r
+        Start a terminal window for the specified VNFs\r
+        (start a terminal for all VNFs if vnf_list is empty)\r
+        :param vnf_list:\r
+        :return:\r
+        """\r
+\r
+\r
+        if vnf_list is None:\r
+            vnf_list = []\r
+        if not isinstance(vnf_list, list):\r
+            vnf_list = str(vnf_list).split(',')\r
+            vnf_list = map(str.strip, vnf_list)\r
+        logging.info('vnf_list: {}'.format(vnf_list))\r
+\r
+        return self.start_xterm(vnf_list)\r
+\r
+\r
+    # start an xterm for the specfified vnfs\r
+    def start_xterm(self, vnf_names):\r
+        # start xterm for all vnfs\r
+        for vnf_name in vnf_names:\r
+            terminal_cmd = "docker exec -it mn.{0} /bin/bash".format(vnf_name)\r
+\r
+            cmd = ['xterm', '-xrm', 'XTerm*selectToClipboard: true', '-xrm', 'XTerm.vt100.allowTitleOps: false',\r
+                   '-T', vnf_name,\r
+                   '-e', terminal_cmd]\r
+            Popen(cmd)\r
+\r
+        ret = 'xterms started for {0}'.format(vnf_names)\r
+        if len(vnf_names) == 0:\r
+            ret = 'vnf list is empty, no xterms started'\r
+        return ret\r
+\r
+\r
+\r
+\r
+\r
+\r
 \r
 \r
 \r