blob: 58c2de93b5ee93c8eaa35a3591a92aab3fbac562 [file] [log] [blame]
Jonathan Hart0198f902014-02-21 10:45:17 -08001#!/usr/bin/env python
2
3import json
4from urllib2 import Request, urlopen, URLError, HTTPError
5from flask import Flask, json, Response, render_template, make_response, request
6
7## Global Var for ON.Lab local REST ##
Jonathan Hart2caf0292014-02-25 15:40:55 -08008# The GUI can be accessed at <this_host>:9000/onos-topology.html
Jonathan Hart0198f902014-02-21 10:45:17 -08009RestIP="localhost"
10RestPort=8080
11ONOS_DEFAULT_HOST="localhost" ;# Has to set if LB=False
12DEBUG=1
13controllers=["ubuntu1","ubuntu2","ubuntu3","ubuntu4"]
14
15app = Flask(__name__)
16
17## Worker Functions ##
18def log_error(txt):
19 print '%s' % (txt)
20
21def debug(txt):
22 if DEBUG:
23 print '%s' % (txt)
24
25def node_id(switch_array, dpid):
26 id = -1
27 for i, val in enumerate(switch_array):
28 if val['name'] == dpid:
29 id = i
30 break
31
32 return id
33
34###### ONOS REST API ##############################
35## Worker Func ###
36def get_json(url):
37 code = 200;
38 try:
39 response = urlopen(url)
40 except URLError, e:
41 print "get_json: REST IF %s has issue. Reason: %s" % (url, e.reason)
42 result = ""
43 return (500, result)
44 except HTTPError, e:
45 print "get_json: REST IF %s has issue. Code %s" % (url, e.code)
46 result = ""
47 return (e.code, result)
48
49 result = response.read()
50# parsedResult = json.loads(result)
51 return (code, result)
52
53### File Fetch ###
54@app.route('/ui/img/<filename>', methods=['GET'])
55@app.route('/img/<filename>', methods=['GET'])
56@app.route('/css/<filename>', methods=['GET'])
57@app.route('/js/models/<filename>', methods=['GET'])
58@app.route('/js/views/<filename>', methods=['GET'])
59@app.route('/js/<filename>', methods=['GET'])
60@app.route('/lib/<filename>', methods=['GET'])
61@app.route('/log/<filename>', methods=['GET'])
62@app.route('/', methods=['GET'])
63@app.route('/<filename>', methods=['GET'])
64@app.route('/tpl/<filename>', methods=['GET'])
65@app.route('/ons-demo/<filename>', methods=['GET'])
66@app.route('/ons-demo/js/<filename>', methods=['GET'])
67@app.route('/ons-demo/d3/<filename>', methods=['GET'])
68@app.route('/ons-demo/css/<filename>', methods=['GET'])
69@app.route('/ons-demo/assets/<filename>', methods=['GET'])
70@app.route('/ons-demo/data/<filename>', methods=['GET'])
71def return_file(filename="index.html"):
72 if request.path == "/":
73 fullpath = "./index.html"
74 else:
75 fullpath = str(request.path)[1:]
76
77 try:
78 open(fullpath)
79 except:
80 response = make_response("Cannot find a file: %s" % (fullpath), 500)
81 response.headers["Content-type"] = "text/html"
82 return response
83
84 response = make_response(open(fullpath).read())
85 suffix = fullpath.split(".")[-1]
86
87 if suffix == "html" or suffix == "htm":
88 response.headers["Content-type"] = "text/html"
89 elif suffix == "js":
90 response.headers["Content-type"] = "application/javascript"
91 elif suffix == "css":
92 response.headers["Content-type"] = "text/css"
93 elif suffix == "png":
94 response.headers["Content-type"] = "image/png"
95 elif suffix == "svg":
96 response.headers["Content-type"] = "image/svg+xml"
97
98 return response
99
100## API for ON.Lab local GUI ##
101@app.route('/topology', methods=['GET'])
102def topology_for_gui():
103 try:
Pavlin Radoslavov030fc442014-04-21 13:38:26 -0700104 url="http://%s:%s/wm/onos/topology/switches/json" % (RestIP, RestPort)
Jonathan Hart0198f902014-02-21 10:45:17 -0800105 (code, result) = get_json(url)
106 parsedResult = json.loads(result)
107 except:
108 log_error("REST IF has issue: %s" % url)
109 log_error("%s" % result)
110 return
111
112 topo = {}
113 switches = []
114 links = []
115 devices = []
116
117 for v in parsedResult:
118 if v.has_key('dpid'):
119# if v.has_key('dpid') and str(v['state']) == "ACTIVE":#;if you want only ACTIVE nodes
120 dpid = str(v['dpid'])
121 state = str(v['state'])
122 sw = {}
123 sw['name']=dpid
124 sw['group']= -1
125
126 if state == "INACTIVE":
127 sw['group']=0
128 switches.append(sw)
129
130 try:
131 url="http://%s:%s/wm/onos/registry/switches/json" % (RestIP, RestPort)
132 (code, result) = get_json(url)
133 parsedResult = json.loads(result)
134 except:
135 log_error("REST IF has issue: %s" % url)
136 log_error("%s" % result)
137
138 for key in parsedResult:
139 dpid = key
140 ctrl = parsedResult[dpid][0]['controllerId']
141 sw_id = node_id(switches, dpid)
142 if sw_id != -1:
143 if switches[sw_id]['group'] != 0:
144 switches[sw_id]['group'] = controllers.index(ctrl) + 1
145
146 try:
Pavlin Radoslavov030fc442014-04-21 13:38:26 -0700147 url = "http://%s:%s/wm/onos/topology/links/json" % (RestIP, RestPort)
Jonathan Hart0198f902014-02-21 10:45:17 -0800148 (code, result) = get_json(url)
149 parsedResult = json.loads(result)
150 except:
151 log_error("REST IF has issue: %s" % url)
152 log_error("%s" % result)
153 return
154# sys.exit(0)
155
156 for v in parsedResult:
157 link = {}
158 if v.has_key('dst-switch'):
159 dst_dpid = str(v['dst-switch'])
160 dst_id = node_id(switches, dst_dpid)
161 if v.has_key('src-switch'):
162 src_dpid = str(v['src-switch'])
163 src_id = node_id(switches, src_dpid)
164 link['source'] = src_id
165 link['target'] = dst_id
166
167 #onpath = 0
168 #for (s,d) in path:
169 # if s == v['src-switch'] and d == v['dst-switch']:
170 # onpath = 1
171 # break
172 #link['type'] = onpath
173
174 links.append(link)
175
176 topo['nodes'] = switches
177 topo['links'] = links
178
179 js = json.dumps(topo)
180 resp = Response(js, status=200, mimetype='application/json')
181 return resp
182
183@app.route("/controller_status")
184def controller_status():
185 url= "http://%s:%d/wm/onos/registry/controllers/json" % (RestIP, RestPort)
186 (code, result) = get_json(url)
187 parsedResult = json.loads(result)
188
189 cont_status=[]
190 for i in controllers:
191 status={}
192 if i in parsedResult:
193 onos=1
194 else:
195 onos=0
196 status["name"]=i
197 status["onos"]=onos
198 status["cassandra"]=0
199 cont_status.append(status)
200
201 js = json.dumps(cont_status)
202 resp = Response(js, status=200, mimetype='application/json')
203 return resp
204
205if __name__ == "__main__":
206 app.debug = True
207 app.run(threaded=True, host="0.0.0.0", port=9000)