blob: a5947b9abdf1962ae28a83434f74fb12b535719f [file] [log] [blame]
slowrdb071b22017-07-07 11:10:25 -07001#!/usr/bin/python3
2
3async_mode = 'threading'
4
5import time
6from flask import Flask, render_template, abort
7import socketio
8from sys import stdin, stdout, stderr
9import json
10import time
11from netaddr import IPNetwork, IPAddress
12
13sio = socketio.Server(logger=False, async_mode=async_mode)
14app = Flask(__name__)
15app.wsgi_app = socketio.Middleware(sio, app.wsgi_app)
16app.config['SECRET_KEY'] = 'secret!'
17thread = None
18clients = {}
19
20
21def message_parser(line):
22 try:
23 temp_message = json.loads(line)
24 if temp_message['type'] == 'update':
25 for origin in temp_message['neighbor']['message']['update']['announce']['ipv4 unicast']:
26 message = {
27 'type': 'A',
28 'timestamp': temp_message['time'],
29 'peer': temp_message['neighbor']['ip'],
30 'host': 'exabgp',
31 'path': temp_message['neighbor']['message']['update']['attribute']['as-path'],
32 }
33 for prefix in temp_message['neighbor']['message']['update']['announce']['ipv4 unicast'][origin]:
34 message['prefix'] = prefix
35 for sid in clients.keys():
36 try:
37 if IPAddress(str(prefix).split('/')[0]) in clients[sid][0]:
38 print('Sending exa_message to ' +
39 str(clients[sid][0]), file=stderr)
40 sio.emit(
41 'exa_message', message, room=sid, namespace='/onos')
42 except:
43 print('Invalid format received from %s'.format(str(sid)))
44 except Exception as e:
45 print(str(e), file=stderr)
46
47
48def exabgp_update_event():
49 while True:
50 line = stdin.readline().strip()
51 messages = message_parser(line)
52
53
54@app.route('/')
55def index():
56 abort(404)
57
58
59@sio.on('connect', namespace='/onos')
60def onos_connect(sid, environ):
61 global thread
62 if thread is None:
63 thread = sio.start_background_task(exabgp_update_event)
64
65
66@sio.on('disconnect', namespace='/onos')
67def onos_disconnect(sid):
68 if sid in clients:
69 del clients[sid]
70
71
72@sio.on('exa_subscribe', namespace='/onos')
73def onos_exa_subscribe(sid, message):
74 try:
75 clients[sid] = [IPNetwork(message['prefix']), True]
76 except:
77 print('Invalid format received from %s'.format(str(sid)))
78
79if __name__ == '__main__':
80 app.run(host='0.0.0.0', threaded=True)