blob: a91bd7c9c68a8f8e10c95f6d43e0587c94d74392 [file] [log] [blame]
Ubuntu82b8a832013-02-06 22:00:11 +00001#! /usr/bin/env python
2import pprint
3import os
4import sys
5import subprocess
6import json
7import argparse
8import io
9import time
10
11from flask import Flask, json, Response, render_template, make_response, request
12
13## Global Var ##
Ubuntuf6ce96c2013-02-07 01:45:07 +000014RestIP="localhost"
Ubuntu82b8a832013-02-06 22:00:11 +000015RestPort=8080
16#DBName="onos-network-map"
17
18DEBUG=1
19pp = pprint.PrettyPrinter(indent=4)
20
21app = Flask(__name__)
22
23## Worker Functions ##
24def log_error(txt):
25 print '%s' % (txt)
26
27def debug(txt):
28 if DEBUG:
29 print '%s' % (txt)
30
31## Rest APIs ##
32### File Fetch ###
33@app.route('/ui/img/<filename>', methods=['GET'])
34@app.route('/img/<filename>', methods=['GET'])
35@app.route('/css/<filename>', methods=['GET'])
36@app.route('/js/models/<filename>', methods=['GET'])
37@app.route('/js/views/<filename>', methods=['GET'])
38@app.route('/js/<filename>', methods=['GET'])
39@app.route('/lib/<filename>', methods=['GET'])
40@app.route('/', methods=['GET'])
41@app.route('/<filename>', methods=['GET'])
42@app.route('/tpl/<filename>', methods=['GET'])
43def return_file(filename="index.html"):
44 if request.path == "/":
45 fullpath = "./index.html"
46 else:
47 fullpath = str(request.path)[1:]
48
49 response = make_response(open(fullpath).read())
50 suffix = fullpath.split(".")[-1]
51
52 if suffix == "html" or suffix == "htm":
53 response.headers["Content-type"] = "text/html"
54 elif suffix == "js":
55 response.headers["Content-type"] = "application/javascript"
56 elif suffix == "css":
57 response.headers["Content-type"] = "text/css"
58 elif suffix == "png":
59 response.headers["Content-type"] = "image/png"
60
61 return response
62
63init_topo1 = {
64 "nodes" : [
65 {"name" : "sw0", "group" : 0},
66 {"name" : "sw1", "group" : 0},
67 {"name" : "sw2", "group" : 0},
68 {"name" : "sw3", "group" : 0},
69 {"name" : "sw4", "group" : 0},
70 {"name" : "sw5", "group" : 0},
71 {"name" : "host0", "group" : 1}
72 ],
73 "links" : [
74 {"source" :0, "target": 1},
75 {"source" :1, "target": 0},
76 {"source" :0, "target": 2},
77 {"source" :2, "target": 0},
78 {"source" :1, "target": 3},
79 {"source" :3, "target": 1},
80 {"source" :2, "target": 3},
81 {"source" :3, "target": 2},
82 {"source" :2, "target": 4},
83 {"source" :4, "target": 2},
84 {"source" :3, "target": 5},
85 {"source" :5, "target": 3},
86 {"source" :4, "target": 5},
87 {"source" :5, "target": 4},
88 {"source" :6, "target": 0},
89 {"source" :0, "target": 6}
90 ]
91}
92
93def node_id(switch_array, dpid):
94 id = -1
95 for i, val in enumerate(switch_array):
96 if val['name'] == dpid:
97 id = i
98 break
99
100 return id
101
102@app.route("/topology")
103def topology_for_gui():
104 try:
105 command = "curl -s \'http://%s:%s/wm/core/topology/switches/all/json\'" % (RestIP, RestPort)
106 result = os.popen(command).read()
107 parsedResult = json.loads(result)
108 except:
109 log_error("REST IF has issue: %s" % command)
110 log_error("%s" % result)
111 sys.exit(0)
112
113 topo = {}
114 switches = []
115 links = []
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 if str(v['state']) == "ACTIVE":
Masayoshi Kobayashi274c07d2013-02-20 21:38:16 +0000125 if dpid[-2:-1] == "a":
Ubuntu82b8a832013-02-06 22:00:11 +0000126 sw['group']=1
Masayoshi Kobayashi274c07d2013-02-20 21:38:16 +0000127 if dpid[-2:-1] == "b":
128 sw['group']=2
129 if dpid[-2:-1] == "c":
130 sw['group']=3
131 if str(v['state']) == "INACTIVE":
132 sw['group']=0
133
Ubuntu82b8a832013-02-06 22:00:11 +0000134
135 switches.append(sw)
136
137 try:
138 command = "curl -s \'http://%s:%s/wm/core/topology/links/json\'" % (RestIP, RestPort)
139 result = os.popen(command).read()
140 parsedResult = json.loads(result)
141 except:
142 log_error("REST IF has issue: %s" % command)
143 log_error("%s" % result)
144 sys.exit(0)
145
146 for v in parsedResult:
147 link = {}
148 if v.has_key('dst-switch'):
149 dst_dpid = str(v['dst-switch'])
150 dst_id = node_id(switches, dst_dpid)
151 if v.has_key('src-switch'):
152 src_dpid = str(v['src-switch'])
153 src_id = node_id(switches, src_dpid)
154 link['source'] = src_id
155 link['target'] = dst_id
156 links.append(link)
157
158 topo['nodes'] = switches
159 topo['links'] = links
160
161 pp.pprint(topo)
162 js = json.dumps(topo)
163 resp = Response(js, status=200, mimetype='application/json')
164 return resp
165
166
Ubuntuaea2a682013-02-08 08:30:10 +0000167#@app.route("/wm/topology/toporoute/00:00:00:00:00:a1/2/00:00:00:00:00:c1/3/json")
168#@app.route("/wm/topology/toporoute/<srcdpid>/<srcport>/<destdpid>/<destport>/json")
169@app.route("/wm/topology/toporoute/<v1>/<p1>/<v2>/<p2>/json")
170def shortest_path(v1, p1, v2, p2):
171 try:
172 command = "curl -s \'http://%s:%s/wm/core/topology/switches/all/json\'" % (RestIP, RestPort)
173 result = os.popen(command).read()
174 parsedResult = json.loads(result)
175 except:
176 log_error("REST IF has issue: %s" % command)
177 log_error("%s" % result)
178 sys.exit(0)
179
180 topo = {}
181 switches = []
182 links = []
183
184 for v in parsedResult:
185 if v.has_key('dpid'):
186 dpid = str(v['dpid'])
187 state = str(v['state'])
188 sw = {}
189 sw['name']=dpid
190 if str(v['state']) == "ACTIVE":
191 if dpid[-2:-1] == "a":
192 sw['group']=1
193 if dpid[-2:-1] == "b":
194 sw['group']=2
195 if dpid[-2:-1] == "c":
196 sw['group']=3
197 if str(v['state']) == "INACTIVE":
198 sw['group']=0
199
200 switches.append(sw)
201
202 try:
203 command = "curl -s http://%s:%s/wm/topology/route/%s/%s/%s/%s/json" % (RestIP, RestPort, v1, p1, v2, p2)
204 result = os.popen(command).read()
205 parsedResult = json.loads(result)
206 except:
207 log_error("No route")
208 parsedResult = []
209# exit(1)
210
211 path = [];
212 for i, v in enumerate(parsedResult):
213 if i < len(parsedResult) - 1:
214 sdpid= parsedResult[i]['switch']
215 ddpid = parsedResult[i+1]['switch']
216 path.append( (sdpid, ddpid))
217
218 try:
219 command = "curl -s \'http://%s:%s/wm/core/topology/links/json\'" % (RestIP, RestPort)
220 result = os.popen(command).read()
221 parsedResult = json.loads(result)
222 except:
223 log_error("REST IF has issue: %s" % command)
224 log_error("%s" % result)
225 sys.exit(0)
226
227 for v in parsedResult:
228 link = {}
229 if v.has_key('dst-switch'):
230 dst_dpid = str(v['dst-switch'])
231 dst_id = node_id(switches, dst_dpid)
232 if v.has_key('src-switch'):
233 src_dpid = str(v['src-switch'])
234 src_id = node_id(switches, src_dpid)
235 link['source'] = src_id
236 link['target'] = dst_id
237 onpath = 0
238 for (s,d) in path:
239 if s == v['src-switch'] and d == v['dst-switch']:
240 onpath = 1
241 break
242
243 link['type'] = onpath
244 links.append(link)
245
246 topo['nodes'] = switches
247 topo['links'] = links
248
249 pp.pprint(topo)
250 js = json.dumps(topo)
251 resp = Response(js, status=200, mimetype='application/json')
252 return resp
253
254
255
256
257
Ubuntu82b8a832013-02-06 22:00:11 +0000258@app.route("/wm/core/controller/switches/json")
259def query_switch():
260 try:
261 command = "curl -s \'http://%s:%s/wm/core/topology/switches/all/json\'" % (RestIP, RestPort)
262# http://localhost:8080/wm/core/topology/switches/active/json
263 result = os.popen(command).read()
264 parsedResult = json.loads(result)
265 except:
266 log_error("REST IF has issue: %s" % command)
267 log_error("%s" % result)
268 sys.exit(0)
269
270# print command
271# print result
272 switches_ = []
273 for v in parsedResult:
274 if v.has_key('dpid'):
275 if v.has_key('dpid') and str(v['state']) == "ACTIVE":#;if you want only ACTIVE nodes
276 dpid = str(v['dpid'])
277 state = str(v['state'])
278 sw = {}
279 sw['dpid']=dpid
280 sw['active']=state
281 switches_.append(sw)
282
283 pp.pprint(switches_)
284 js = json.dumps(switches_)
285 resp = Response(js, status=200, mimetype='application/json')
286 return resp
287
288@app.route("/wm/device/")
289def devices():
290 try:
291 command = "curl -s http://%s:%s/graphs/%s/vertices\?key=type\&value=device" % (RestIP, RestPort, DBName)
292 result = os.popen(command).read()
293 parsedResult = json.loads(result)['results']
294 except:
295 log_error("REST IF has issue: %s" % command)
296 log_error("%s" % result)
297 sys.exit(0)
298
299 devices = []
300 for v in parsedResult:
301 dl_addr = v['dl_addr']
302 nw_addr = v['nw_addr']
303 vertex = v['_id']
304 mac = []
305 mac.append(dl_addr)
306 ip = []
307 ip.append(nw_addr)
308 device = {}
309 device['entryClass']="DefaultEntryClass"
310 device['mac']=mac
311 device['ipv4']=ip
312 device['vlan']=[]
313 device['lastSeen']=0
314 attachpoints =[]
315
316 port, dpid = deviceV_to_attachpoint(vertex)
317 attachpoint = {}
318 attachpoint['port']=port
319 attachpoint['switchDPID']=dpid
320 attachpoints.append(attachpoint)
321 device['attachmentPoint']=attachpoints
322 devices.append(device)
323
324 print devices
325 js = json.dumps(devices)
326 resp = Response(js, status=200, mimetype='application/json')
327 return resp
328
329#{"entityClass":"DefaultEntityClass","mac":["7c:d1:c3:e0:8c:a3"],"ipv4":["192.168.2.102","10.1.10.35"],"vlan":[],"attachmentPoint":[{"port":13,"switchDPID":"00:01:00:12:e2:78:32:44","errorStatus":null}],"lastSeen":1357333593496}
330
331
332## return fake stat for now
333@app.route("/wm/core/switch/<switchId>/<statType>/json")
334def switch_stat(switchId, statType):
335 if statType == "desc":
336 desc=[{"length":1056,"serialNumber":"None","manufacturerDescription":"Nicira Networks, Inc.","hardwareDescription":"Open vSwitch","softwareDescription":"1.4.0+build0","datapathDescription":"None"}]
337 ret = {}
338 ret[switchId]=desc
339 elif statType == "aggregate":
340 aggr = {"packetCount":0,"byteCount":0,"flowCount":0}
341 ret = {}
342 ret[switchId]=aggr
343 else:
344 ret = {}
345
346 js = json.dumps(ret)
347 resp = Response(js, status=200, mimetype='application/json')
348 return resp
349
350
351@app.route("/wm/topology/links/json")
352def query_links():
353 try:
354 command = 'curl -s http://%s:%s/graphs/%s/vertices?key=type\&value=port' % (RestIP, RestPort, DBName)
355 result = os.popen(command).read()
356 parsedResult = json.loads(result)['results']
357 except:
358 log_error("REST IF has issue: %s" % command)
359 log_error("%s" % result)
360 sys.exit(0)
361
362 debug("query_links %s" % command)
363 pp.pprint(parsedResult)
364 sport = []
365 links = []
366 for v in parsedResult:
367 srcport = v['_id']
368 try:
369 command = "curl -s http://%s:%s/graphs/%s/vertices/%d/out?_label=link" % (RestIP, RestPort, DBName, srcport)
370 print command
371 result = os.popen(command).read()
372 linkResults = json.loads(result)['results']
373 except:
374 log_error("REST IF has issue: %s" % command)
375 log_error("%s" % result)
376 sys.exit(0)
377
378 for p in linkResults:
379 if p.has_key('type') and p['type'] == "port":
380 dstport = p['_id']
381 (sport, sdpid) = portV_to_port_dpid(srcport)
382 (dport, ddpid) = portV_to_port_dpid(dstport)
383 link = {}
384 link["src-switch"]=sdpid
385 link["src-port"]=sport
386 link["src-port-state"]=0
387 link["dst-switch"]=ddpid
388 link["dst-port"]=dport
389 link["dst-port-state"]=0
390 link["type"]="internal"
391 links.append(link)
392
393 pp.pprint(links)
394 js = json.dumps(links)
395 resp = Response(js, status=200, mimetype='application/json')
396 return resp
397
398if __name__ == "__main__":
399 if len(sys.argv) > 1 and sys.argv[1] == "-d":
400 print "-- query all switches --"
401 query_switch()
402 print "-- query topo --"
403 topology_for_gui()
404# print "-- query all links --"
405# query_links()
406# print "-- query all devices --"
407# devices()
408 else:
409 app.debug = True
Ubuntuf6ce96c2013-02-07 01:45:07 +0000410# app.run(host="10.0.1.29", port=9000)
Ubuntu82b8a832013-02-06 22:00:11 +0000411 app.run(host="0.0.0.0", port=9000)