Resolved merge conflict and back to Titan 0.2.0
diff --git a/web/topology_rest.py b/web/topology_rest.py
index 3238656..392cb87 100755
--- a/web/topology_rest.py
+++ b/web/topology_rest.py
@@ -7,40 +7,51 @@
 import argparse
 import io
 import time
+import random
 
 import re
 
 from flask import Flask, json, Response, render_template, make_response, request
 
-## Global Var ##
+## Global Var for ON.Lab local REST ##
 RestIP="localhost"
 RestPort=8080
-#DBName="onos-network-map"
 
 ## Uncomment the desired block based on your testbed environment
-
 # Settings for running on production
+<<<<<<< HEAD
 core_switches=["00:00:00:00:ba:5e:ba:11", "00:00:00:00:00:00:ba:12", "00:00:20:4e:7f:51:8a:35", "00:00:00:00:ba:5e:ba:13", "00:00:00:08:a2:08:f9:01", "00:00:00:16:97:08:9a:46"]
 ONOS_GUI3_HOST="http://localhost:9000"
 ONOS_GUI3_CONTROL_HOST="http://localhost:9000"
+=======
+#controllers=["onosgui1", "onosgui2", "onosgui3", "onosgui4", "onosgui5", "onosgui6", "onosgui7", "onosgui8"]
+#core_switches=["00:00:00:00:ba:5e:ba:11", "00:00:00:00:00:00:ba:12", "00:00:20:4e:7f:51:8a:35", "00:00:00:00:ba:5e:ba:13", "00:00:00:08:a2:08:f9:01", "00:00:00:16:97:08:9a:46"]
+#ONOS_GUI3_HOST="http://gui3.onlab.us:8080"
+#ONOS_GUI3_CONTROL_HOST="http://gui3.onlab.us:8081"
+>>>>>>> ecee79b1df12c337cba14cbc9e3660741ae72441
 
 # Settings for running on dev testbed. Replace dev
 #controllers=["onosdevb1", "onosdevb2", "onosdevb3", "onosdevb4"]
-#core_switches=["00:00:00:00:00:00:01:01", "00:00:00:00:00:00:01:02", "00:00:00:00:00:00:01:03", "00:00:00:00:00:00:01:04", "00:00:00:00:00:00:01:05", "00:00:00:00:00:00:01:06"]
-#ONOS_GUI3_HOST="http://devb-gui.onlab.us:8080"
-#ONOS_GUI3_CONTROL_HOST="http://devb-gui.onlab.us:8080"
+controllers=["onosdevt1", "onosdevt2", "onosdevt3", "onosdevt4", "onosdevt5", "onosdevt6", "onosdevt7", "onosdevt8"]
+core_switches=["00:00:00:00:00:00:01:01", "00:00:00:00:00:00:01:02", "00:00:00:00:00:00:01:03", "00:00:00:00:00:00:01:04", "00:00:00:00:00:00:01:05", "00:00:00:00:00:00:01:06"]
 
+<<<<<<< HEAD
 ONOS_LOCAL_HOST="http://localhost:8080" ;# for Amazon EC2
 controllers=["Berde-MBP.local"]
 #controllers=["onosgui1", "onosgui2", "onosgui3", "onosgui4", "onosgui5", "onosgui6", "onosgui7", "onosgui8"]
 #core_switches=["00:00:00:00:ba:5e:ba:11", "00:00:00:00:00:00:ba:12", "00:00:20:4e:7f:51:8a:35", "00:00:00:00:ba:5e:ba:13", "00:00:00:08:a2:08:f9:01", "00:00:00:16:97:08:9a:46"]
 core_switches=["00:00:00:00:00:00:01:01", "00:00:00:00:00:00:01:02", "00:00:00:00:00:00:01:03", "00:00:00:00:00:00:01:04", "00:00:00:00:00:00:01:05", "00:00:00:00:00:00:01:06"]
+=======
+ONOS_GUI3_HOST="http://devt-gui.onlab.us:8080"
+ONOS_GUI3_CONTROL_HOST="http://devt-gui.onlab.us:8080"
+>>>>>>> ecee79b1df12c337cba14cbc9e3660741ae72441
 
-nr_flow=0
+LB=True #; True or False
+ONOS_DEFAULT_HOST="localhost" ;# Has to set if LB=False
 
 DEBUG=1
-pp = pprint.PrettyPrinter(indent=4)
 
+pp = pprint.PrettyPrinter(indent=4)
 app = Flask(__name__)
 
 ## Worker Functions ##
@@ -51,7 +62,6 @@
   if DEBUG:
     print '%s' % (txt)
 
-## Rest APIs ##
 ### File Fetch ###
 @app.route('/ui/img/<filename>', methods=['GET'])
 @app.route('/img/<filename>', methods=['GET'])
@@ -75,6 +85,13 @@
   else:
     fullpath = str(request.path)[1:]
 
+  try: 
+    open(fullpath)
+  except:
+    response = make_response("Cannot find a file: %s" % (fullpath), 500)
+    response.headers["Content-type"] = "text/html"
+    return response
+
   response = make_response(open(fullpath).read())
   suffix = fullpath.split(".")[-1]
 
@@ -91,7 +108,7 @@
 
   return response
 
-
+## Proxy ##
 @app.route("/proxy/gui/link/<cmd>/<src_dpid>/<src_port>/<dst_dpid>/<dst_port>")
 def proxy_link_change(cmd, src_dpid, src_port, dst_dpid, dst_port):
   try:
@@ -105,6 +122,19 @@
   resp = Response(result, status=200, mimetype='application/json')
   return resp
 
+@app.route("/proxy/gui/switchctrl/<cmd>")
+def proxy_switch_controller_setting(cmd):
+  try:
+    command = "curl -s %s/gui/switchctrl/%s" % (ONOS_GUI3_CONTROL_HOST, cmd)
+    print command
+    result = os.popen(command).read()
+  except:
+    print "REST IF has issue"
+    exit
+
+  resp = Response(result, status=200, mimetype='application/json')
+  return resp
+
 @app.route("/proxy/gui/switch/<cmd>/<dpid>")
 def proxy_switch_status_change(cmd, dpid):
   try:
@@ -156,33 +186,11 @@
 
   resp = Response(result, status=200, mimetype='application/json')
   return resp
-@app.route("/wm/core/topology/switches/all/json")
-def switches():
-  if request.args.get('proxy') == None:
-    host = ONOS_LOCAL_HOST
-  else:
-    host = ONOS_GUI3_HOST
 
+@app.route("/proxy/gui/iperf/start/<flow_id>/<duration>/<samples>")
+def proxy_iperf_start(flow_id,duration,samples):
   try:
-    command = "curl -s %s/wm/core/topology/switches/all/json" % (host)
-#    print command
-    result = os.popen(command).read()
-  except:
-    print "REST IF has issue"
-    exit
-
-  resp = Response(result, status=200, mimetype='application/json')
-  return resp
-
-@app.route("/wm/core/topology/links/json")
-def links():
-  if request.args.get('proxy') == None:
-    host = ONOS_LOCAL_HOST
-  else:
-    host = ONOS_GUI3_HOST
-
-  try:
-    command = "curl -s %s/wm/core/topology/links/json" % (host)
+    command = "curl -s %s/gui/iperf/start/%s/%s/%s" % (ONOS_GUI3_CONTROL_HOST, flow_id, duration, samples)
     print command
     result = os.popen(command).read()
   except:
@@ -192,62 +200,117 @@
   resp = Response(result, status=200, mimetype='application/json')
   return resp
 
-@app.route("/wm/flow/getsummary/<start>/<range>/json")
-def flows(start, range):
-  if request.args.get('proxy') == None:
-    host = ONOS_LOCAL_HOST
-  else:
-    host = ONOS_GUI3_HOST
-
+@app.route("/proxy/gui/iperf/rate/<flow_id>")
+def proxy_iperf_rate(flow_id):
   try:
-    command = "curl -s %s/wm/flow/getsummary/%s/%s/json" % (host, start, range)
-#    print command
+    command = "curl -s %s/gui/iperf/rate/%s" % (ONOS_GUI3_CONTROL_HOST, flow_id)
+    print command
     result = os.popen(command).read()
   except:
     print "REST IF has issue"
     exit
 
-    
   resp = Response(result, status=200, mimetype='application/json')
   return resp
 
+
+###### ONOS RESET API ##############################
+## Worker Func ###
+def get_json(url):
+  code = 200
+  try:
+    command = "curl -s %s" % (url)
+    result = os.popen(command).read()
+    parsedResult = json.loads(result)    
+    if type(parsedResult) == 'dict' and parsedResult.has_key('code'):
+      print "REST %s returned code %s" % (command, parsedResult['code'])
+      code=500
+  except:
+    print "REST IF %s has issue" % command
+    result = ""
+    code = 500
+
+  return (code, result)
+
+def pick_host():
+  if LB == True:
+    nr_host=len(controllers)
+    r=random.randint(0, nr_host - 1)
+    host=controllers[r]
+  else:
+    host=ONOS_DEFAULT_HOST
+    
+  return "http://" + host + ":8080"
+
+## Switch ##
+@app.route("/wm/core/topology/switches/all/json")
+def switches():
+  if request.args.get('proxy') == None:
+    host = pick_host()
+  else:
+    host = ONOS_GUI3_HOST
+
+  url ="%s/wm/core/topology/switches/all/json" % (host)
+  (code, result) = get_json(url)
+
+  resp = Response(result, status=code, mimetype='application/json')
+  return resp
+
+## Link ##
+@app.route("/wm/core/topology/links/json")
+def links():
+  if request.args.get('proxy') == None:
+    host = pick_host()
+  else:
+    host = ONOS_GUI3_HOST
+
+  url ="%s/wm/core/topology/links/json" % (host)
+  (code, result) = get_json(url)
+
+  resp = Response(result, status=code, mimetype='application/json')
+  return resp
+
+## FlowSummary ##
+@app.route("/wm/flow/getsummary/<start>/<range>/json")
+def flows(start, range):
+  if request.args.get('proxy') == None:
+    host = pick_host()
+  else:
+    host = ONOS_GUI3_HOST
+
+  url ="%s/wm/flow/getsummary/%s/%s/json" % (host, start, range)
+  (code, result) = get_json(url)
+
+  resp = Response(result, status=code, mimetype='application/json')
+  return resp
+
 @app.route("/wm/registry/controllers/json")
 def registry_controllers():
   if request.args.get('proxy') == None:
-    host = ONOS_LOCAL_HOST
+    host = pick_host()
   else:
     host = ONOS_GUI3_HOST
 
-  try:
-    command = "curl -s %s/wm/registry/controllers/json" % (host)
-#    print command
-    result = os.popen(command).read()
-  except:
-    print "REST IF has issue"
-    exit
+  url= "%s/wm/registry/controllers/json" % (host)
+  (code, result) = get_json(url)
 
-  resp = Response(result, status=200, mimetype='application/json')
+  resp = Response(result, status=code, mimetype='application/json')
   return resp
 
+
 @app.route("/wm/registry/switches/json")
 def registry_switches():
   if request.args.get('proxy') == None:
-    host = ONOS_LOCAL_HOST
+    host = pick_host()
   else:
     host = ONOS_GUI3_HOST
 
-  try:
-    command = "curl -s %s/wm/registry/switches/json" % (host)
-#    print command
-    result = os.popen(command).read()
-  except:
-    print "REST IF has issue"
-    exit
+  url="%s/wm/registry/switches/json" % (host)
+  (code, result) = get_json(url)
 
-  resp = Response(result, status=200, mimetype='application/json')
+  resp = Response(result, status=code, mimetype='application/json')
   return resp
 
-
 def node_id(switch_array, dpid):
   id = -1
   for i, val in enumerate(switch_array):
@@ -287,39 +350,6 @@
         sw['group']=0
       switches.append(sw)
 
-## Comment in if we need devies
-#      sw_index = len(switches) - 1
-#      for p in v['ports']:
-#        for d in p['devices']:
-#          device = {}
-#          device['attached_switch']=dpid
-#          device['name']=d['mac']
-#          if d['state'] == "ACTIVE":
-#            device['group']=1000
-#          else:
-#            device['group']=1001
-#
-#          switches.append(device)
-#          device_index = len (switches) -1
-#          link = {}
-#          link['source'] = device_index
-#          link['target'] = sw_index
-#          link['type'] = -1
-#          links.append(link)
-#          link = {}
-#          link['source'] = sw_index
-#          link['target'] = device_index
-#          link['type'] = -1
-#          links.append(link)
-
-#  try:
-#    command = "curl -s \'http://%s:%s/wm/registry/controllers/json\'" % (RestIP, RestPort)
-#    result = os.popen(command).read()
-#    controllers = json.loads(result)
-#  except:
-#    log_error("xx REST IF has issue: %s" % command)
-#    log_error("%s" % result)
-
   try:
     command = "curl -s \'http://%s:%s/wm/registry/switches/json\'" % (RestIP, RestPort)
     result = os.popen(command).read()
@@ -391,7 +421,6 @@
   topo['nodes'] = switches
   topo['links'] = links
 
-  pp.pprint(topo)
   js = json.dumps(topo)
   resp = Response(js, status=200, mimetype='application/json')
   return resp
@@ -478,7 +507,6 @@
   topo['nodes'] = switches
   topo['links'] = links
 
-#  pp.pprint(topo)
   js = json.dumps(topo)
   resp = Response(js, status=200, mimetype='application/json')
   return resp
@@ -550,7 +578,6 @@
     device['attachmentPoint']=attachpoints
     devices.append(device)
 
-  print devices
   js = json.dumps(devices)
   resp = Response(js, status=200, mimetype='application/json')
   return resp
@@ -624,82 +651,6 @@
   resp = Response(js, status=200, mimetype='application/json')
   return resp
 
-topo_less = {
-  "nodes" : [
-    {"name" : "00:a0", "group" : 1},
-    {"name" : "00:a1", "group" : 1},
-    {"name" : "00:a2", "group" : 1},
-    ],
-  "links" : [
-    {"source" :0, "target": 1},
-    {"source" :1, "target": 0},
-    {"source" :0, "target": 2},
-    {"source" :2, "target": 0},
-    {"source" :1, "target": 2},
-    {"source" :2, "target": 1},
-    ]
-}
-
-topo_more = {
-  "nodes" : [
-    {"name" : "00:a3", "group" : 2},
-    {"name" : "00:a0", "group" : 1},
-    {"name" : "00:a1", "group" : 1},
-    {"name" : "00:a2", "group" : 1},
-    ],
-  "links" : [
-    {"source" :1, "target": 2},
-    {"source" :2, "target": 1},
-    {"source" :1, "target": 3},
-    {"source" :3, "target": 1},
-    {"source" :2, "target": 3},
-    {"source" :3, "target": 2},
-    {"source" :0, "target": 2},
-    ]
-}
-
-@app.route("/topology_more")
-def topology_more():
-  topo = topo_more
-  js = json.dumps(topo)
-  resp = Response(js, status=200, mimetype='application/json')
-  return resp
-
-@app.route("/topology_less")
-def topology_less():
-  topo = topo_less
-  js = json.dumps(topo)
-  resp = Response(js, status=200, mimetype='application/json')
-  return resp
-
-cont_status1 = [
-           {"name":"onos9vpc",  "onos": 1, "cassandra": 1},
-            {"name":"onos10vpc",  "onos": 0, "cassandra": 1},
-            {"name":"onos11vpc",  "onos": 1, "cassandra": 0},
-            {"name":"onos12vpc",  "onos": 1, "cassandra": 0}]
-
-cont_status2 = [
-            {"name":"onos9vpc",  "onos": 0, "cassandra": 1},
-            {"name":"onos10vpc",  "onos": 0, "cassandra": 1},
-            {"name":"onos11vpc",  "onos": 0, "cassandra": 1},
-            {"name":"onos12vpc",  "onos": 0, "cassandra": 1}]
-
-@app.route("/controller_status1")
-def controller_status1():
-  status = cont_status1
-  js = json.dumps(status)
-  resp = Response(js, status=200, mimetype='application/json')
-  pp.pprint(resp)
-  return resp
-
-@app.route("/controller_status2")
-def controller_status2():
-  status = cont_status2
-  js = json.dumps(status)
-  resp = Response(js, status=200, mimetype='application/json')
-  pp.pprint(resp)
-  return resp
-
 @app.route("/controller_status")
 def controller_status():
   onos_check="sh ~/src/ONOS/start-onos.sh status | awk '{print $1}'"
@@ -716,25 +667,42 @@
 
   js = json.dumps(cont_status)
   resp = Response(js, status=200, mimetype='application/json')
-  pp.pprint(js)
   return resp
 
+### Command ###
 @app.route("/gui/controller/<cmd>/<controller_name>")
 def controller_status_change(cmd, controller_name):
   start_onos="~/src/ONOS/start-onos.sh start" % (controller_name)
   stop_onos="~/src/ONOS/start-onos.sh stop" % (controller_name)
 
   if cmd == "up":
-    print start_onos
     result=os.popen(start_onos).read()
     ret = "controller %s is up" % (controller_name)
   elif cmd == "down":
-    print stop_onos
     result=os.popen(stop_onos).read()
     ret = "controller %s is down" % (controller_name)
 
   return ret
 
+@app.route("/gui/switchctrl/<cmd>")
+def switch_controller_setting(cmd):
+  if cmd =="local":
+    print "All aggr switches connects to local controller only"
+    result=""
+    for i in range(0, len(controllers)): 
+      cmd_string="ssh -i ~/.ssh/onlabkey.pem %s 'cd ONOS/scripts; ./ctrl-local.sh'" % (controllers[i])
+      result += os.popen(cmd_string).read()
+  elif cmd =="all":
+    print "All aggr switches connects to all controllers except for core controller"
+    result=""
+    for i in range(0, len(controllers)): 
+      cmd_string="ssh -i ~/.ssh/onlabkey.pem %s 'cd ONOS/scripts; ./ctrl-add-ext.sh'" % (controllers[i])
+      result += os.popen(cmd_string).read()
+
+  return result
+
+
+
 @app.route("/gui/switch/<cmd>/<dpid>")
 def switch_status_change(cmd, dpid):
   r = re.compile(':')
@@ -845,6 +813,7 @@
 
   parsedResult = json.loads(result)
 
+#  flowId = int(parsedResult['flowId']['value'], 16)
   flowId = int(parsedResult['flowId']['value'], 16)
   src_dpid = parsedResult['dataPath']['srcPort']['dpid']['value']
   src_port = parsedResult['dataPath']['srcPort']['port']['value']
@@ -874,8 +843,8 @@
     print command
     result = os.popen(command).read()
     if len(result) == 0:
-      print "No Flow found"
-      return;
+      resp = Response(result, status=400, mimetype='text/html')
+      return "no such iperf flow (flowid %s)" % flow_id;
   except:
     print "REST IF has issue"
     exit
@@ -899,14 +868,18 @@
     print command
     result = os.popen(command).read()
   except:
-    print "REST IF has issue"
     exit
 
-  resp = Response(result, status=200, mimetype='application/json')
-  return resp
+  if len(result) == 0:
+    resp = Response(result, status=400, mimetype='text/html')
+    return "no iperf file found (flowid %s)" % flow_id;
+  else:
+    resp = Response(result, status=200, mimetype='application/json')
+    return resp
 
 
 if __name__ == "__main__":
+  random.seed()
   if len(sys.argv) > 1 and sys.argv[1] == "-d":
 #      add_flow("00:00:00:00:00:00:02:02", 1, "00:00:00:00:00:00:03:02", 1, "00:00:00:00:02:02", "00:00:00:00:03:0c")
 #     link_change("up", "00:00:00:00:ba:5e:ba:11", 1, "00:00:00:00:00:00:00:00", 1)
@@ -922,8 +895,9 @@
 #    query_links()
 #    print "-- query all devices --"
 #    devices()
-    iperf_start(1,10,15)
-    iperf_rate(1)
+#    iperf_start(1,10,15)
+#    iperf_rate(1)
+    switches()
   else:
     app.debug = True
     app.run(threaded=True, host="0.0.0.0", port=9000)