blob: 001faa65e7c574e4be606b905793674bfefd70a0 [file] [log] [blame]
Pankaj Berde7b0122b2013-01-23 14:22:37 -08001#! /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 ##
14RestIP="127.0.0.1"
15RestPort=8182
Ubuntu25072e52013-01-31 22:11:00 +000016DBName="onos-network-map"
Pankaj Berde7b0122b2013-01-23 14:22:37 -080017
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
31def portV_to_dpid(vertex):
32 try:
33 command = "curl -s http://%s:%s/graphs/%s/vertices/%d/in" % (RestIP, RestPort, DBName, vertex)
34 result = os.popen(command).read()
35 parsedResult = json.loads(result)['results']
36 except:
Ubuntu25072e52013-01-31 22:11:00 +000037 log_error("REST IF has issue: %s" % command)
38 log_error("%s" % result)
39 sys.exit(0)
Pankaj Berde7b0122b2013-01-23 14:22:37 -080040
41 debug("portV_to_dpid %s" % command)
42 debug("parsed %s" % parsedResult)
Ubuntu25072e52013-01-31 22:11:00 +000043
44 found = 0
Pankaj Berde7b0122b2013-01-23 14:22:37 -080045 for v in parsedResult:
46 if v.has_key('type') and v['type'] == "switch":
Ubuntu25072e52013-01-31 22:11:00 +000047 found = 1
Pankaj Berde7b0122b2013-01-23 14:22:37 -080048 sw_dpid = v['dpid']
49 break
50
Ubuntu25072e52013-01-31 22:11:00 +000051 if not found:
52 log_error("No switch attached to port vertex %d" % vertex)
53 sys.exit(0)
54 else:
55 return sw_dpid
56
Pankaj Berde7b0122b2013-01-23 14:22:37 -080057
58def switchV_to_dpid(vertex):
59 try:
60 command = "curl -s http://%s:%s/graphs/%s/vertices/%d" % (RestIP, RestPort, DBName, vertex)
61 result = os.popen(command).read()
62 parsedResult = json.loads(result)['results']
63 except:
Ubuntu25072e52013-01-31 22:11:00 +000064 log_error("REST IF has issue: %s" % command)
65 log_error("%s" % result)
66 sys.exit(0)
Pankaj Berde7b0122b2013-01-23 14:22:37 -080067
68 debug("switchV_to_dpid %s" % command)
69 if not parsedResult.has_key("type") or parsedResult['type'] != "switch":
70 print "not a switch vertex"
Ubuntu25072e52013-01-31 22:11:00 +000071 sys.exit(0)
Pankaj Berde7b0122b2013-01-23 14:22:37 -080072 else:
73 sw_dpid = parsedResult['dpid']
74
75 return sw_dpid
76
77def portV_to_port_dpid(vertex):
78 try:
79 command = "curl -s http://%s:%s/graphs/%s/vertices/%d" % (RestIP, RestPort, DBName, vertex)
80 result = os.popen(command).read()
81 parsedResult = json.loads(result)['results']
82 except:
Ubuntu25072e52013-01-31 22:11:00 +000083 log_error("REST IF has issue: %s" % command)
84 log_error("%s" % result)
85 sys.exit(0)
Pankaj Berde7b0122b2013-01-23 14:22:37 -080086
87 debug("portV_to_port_dpid %s" % command)
88 port_number = parsedResult['number']
89 switch_dpid = portV_to_dpid(vertex)
90
91 return (port_number, switch_dpid)
92
93def deviceV_to_attachpoint(vertex):
94 try:
95 command = "curl -s http://%s:%s/graphs/%s/vertices/%d/in" % (RestIP, RestPort, DBName, vertex)
96 result = os.popen(command).read()
97 parsedResult = json.loads(result)['results']
98 except:
Ubuntu25072e52013-01-31 22:11:00 +000099 log_error("REST IF has issue: %s" % command)
100 log_error("%s" % result)
101 sys.exit(0)
Pankaj Berde7b0122b2013-01-23 14:22:37 -0800102
103 port = parsedResult[0]['number']
104 vertex = parsedResult[0]['_id']
105 dpid = portV_to_dpid(vertex)
106 return port, dpid
107
108## Rest APIs ##
109### File Fetch ###
110@app.route('/ui/img/<filename>', methods=['GET'])
111@app.route('/img/<filename>', methods=['GET'])
112@app.route('/css/<filename>', methods=['GET'])
113@app.route('/js/models/<filename>', methods=['GET'])
114@app.route('/js/views/<filename>', methods=['GET'])
115@app.route('/js/<filename>', methods=['GET'])
116@app.route('/lib/<filename>', methods=['GET'])
117@app.route('/', methods=['GET'])
118@app.route('/<filename>', methods=['GET'])
119@app.route('/tpl/<filename>', methods=['GET'])
120def return_file(filename="index.html"):
121 if request.path == "/":
122 fullpath = "./index.html"
123 else:
124 fullpath = str(request.path)[1:]
125
126 response = make_response(open(fullpath).read())
127 suffix = fullpath.split(".")[-1]
128
129 if suffix == "html" or suffix == "htm":
130 response.headers["Content-type"] = "text/html"
131 elif suffix == "js":
132 response.headers["Content-type"] = "application/javascript"
133 elif suffix == "css":
134 response.headers["Content-type"] = "text/css"
135 elif suffix == "png":
136 response.headers["Content-type"] = "image/png"
137
138 return response
139
140@app.route("/wm/device/")
141def devices():
142 try:
143 command = "curl -s http://%s:%s/graphs/%s/vertices\?key=type\&value=device" % (RestIP, RestPort, DBName)
144 result = os.popen(command).read()
145 parsedResult = json.loads(result)['results']
146 except:
Ubuntu25072e52013-01-31 22:11:00 +0000147 log_error("REST IF has issue: %s" % command)
148 log_error("%s" % result)
149 sys.exit(0)
Pankaj Berde7b0122b2013-01-23 14:22:37 -0800150
151 devices = []
152 for v in parsedResult:
153 dl_addr = v['dl_addr']
154 nw_addr = v['nw_addr']
155 vertex = v['_id']
156 mac = []
157 mac.append(dl_addr)
158 ip = []
159 ip.append(nw_addr)
160 device = {}
161 device['entryClass']="DefaultEntryClass"
162 device['mac']=mac
163 device['ipv4']=ip
164 device['vlan']=[]
165 device['lastSeen']=0
166 attachpoints =[]
167
168 port, dpid = deviceV_to_attachpoint(vertex)
169 attachpoint = {}
170 attachpoint['port']=port
171 attachpoint['switchDPID']=dpid
172 attachpoints.append(attachpoint)
173 device['attachmentPoint']=attachpoints
174 devices.append(device)
175
176 print devices
177 js = json.dumps(devices)
178 resp = Response(js, status=200, mimetype='application/json')
179 return resp
180
181#{"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}
182
183
184## return fake stat for now
185@app.route("/wm/core/switch/<switchId>/<statType>/json")
186def switch_stat(switchId, statType):
187 if statType == "desc":
188 desc=[{"length":1056,"serialNumber":"None","manufacturerDescription":"Nicira Networks, Inc.","hardwareDescription":"Open vSwitch","softwareDescription":"1.4.0+build0","datapathDescription":"None"}]
189 ret = {}
190 ret[switchId]=desc
191 elif statType == "aggregate":
192 aggr = {"packetCount":0,"byteCount":0,"flowCount":0}
193 ret = {}
194 ret[switchId]=aggr
195 else:
196 ret = {}
197
198 js = json.dumps(ret)
199 resp = Response(js, status=200, mimetype='application/json')
200 return resp
201
202@app.route("/wm/core/controller/switches/json")
203def query_switch():
204 try:
205 command = "curl -s \'http://%s:%s/graphs/%s/vertices?key=type&value=switch\'" % (RestIP, RestPort, DBName)
206 result = os.popen(command).read()
207 parsedResult = json.loads(result)['results']
208 except:
Ubuntu25072e52013-01-31 22:11:00 +0000209 log_error("REST IF has issue: %s" % command)
210 log_error("%s" % result)
211 sys.exit(0)
Pankaj Berde7b0122b2013-01-23 14:22:37 -0800212
213 switches_ = []
214 for v in parsedResult:
Pankaj Berdeff421802013-01-29 20:28:52 -0800215# if v.has_key('dpid'):
216 if v.has_key('dpid') and str(v['state']) == "ACTIVE":#;if you want only ACTIVE nodes
Pankaj Berde7b0122b2013-01-23 14:22:37 -0800217 dpid = str(v['dpid'])
218 state = str(v['state'])
219 sw = {}
220 sw['dpid']=dpid
221 sw['active']=state
222 switches_.append(sw)
223
224 pp.pprint(switches_)
225 js = json.dumps(switches_)
226 resp = Response(js, status=200, mimetype='application/json')
227 return resp
228
229@app.route("/wm/topology/links/json")
230def query_links():
231 try:
232 command = 'curl -s http://%s:%s/graphs/%s/vertices?key=type\&value=port' % (RestIP, RestPort, DBName)
233 result = os.popen(command).read()
234 parsedResult = json.loads(result)['results']
235 except:
Ubuntu25072e52013-01-31 22:11:00 +0000236 log_error("REST IF has issue: %s" % command)
237 log_error("%s" % result)
238 sys.exit(0)
Pankaj Berde7b0122b2013-01-23 14:22:37 -0800239
240 debug("query_links %s" % command)
241 pp.pprint(parsedResult)
242 sport = []
243 links = []
244 for v in parsedResult:
245 srcport = v['_id']
246 try:
247 command = "curl -s http://%s:%s/graphs/%s/vertices/%d/out?_label=link" % (RestIP, RestPort, DBName, srcport)
248 print command
249 result = os.popen(command).read()
250 linkResults = json.loads(result)['results']
251 except:
Ubuntu25072e52013-01-31 22:11:00 +0000252 log_error("REST IF has issue: %s" % command)
253 log_error("%s" % result)
254 sys.exit(0)
Pankaj Berde7b0122b2013-01-23 14:22:37 -0800255
Pankaj Berde7b0122b2013-01-23 14:22:37 -0800256 for p in linkResults:
257 if p.has_key('type') and p['type'] == "port":
258 dstport = p['_id']
259 (sport, sdpid) = portV_to_port_dpid(srcport)
260 (dport, ddpid) = portV_to_port_dpid(dstport)
261 link = {}
262 link["src-switch"]=sdpid
263 link["src-port"]=sport
264 link["src-port-state"]=0
265 link["dst-switch"]=ddpid
266 link["dst-port"]=dport
267 link["dst-port-state"]=0
268 link["type"]="internal"
269 links.append(link)
270
271 pp.pprint(links)
272 js = json.dumps(links)
273 resp = Response(js, status=200, mimetype='application/json')
274 return resp
275
276if __name__ == "__main__":
277 if len(sys.argv) > 1 and sys.argv[1] == "-d":
278 print "-- query all switches --"
279 query_switch()
280 print "-- query all links --"
281 query_links()
282 print "-- query all devices --"
283 devices()
284 else:
285 app.debug = True
286 app.run(host="0.0.0.0", port=9000)