slowr | db071b2 | 2017-07-07 11:10:25 -0700 | [diff] [blame] | 1 | #!/usr/bin/python3 |
| 2 | |
| 3 | async_mode = 'threading' |
| 4 | |
| 5 | import time |
| 6 | from flask import Flask, render_template, abort |
| 7 | import socketio |
| 8 | from sys import stdin, stdout, stderr |
| 9 | import json |
| 10 | import time |
| 11 | from netaddr import IPNetwork, IPAddress |
| 12 | |
| 13 | sio = socketio.Server(logger=False, async_mode=async_mode) |
| 14 | app = Flask(__name__) |
| 15 | app.wsgi_app = socketio.Middleware(sio, app.wsgi_app) |
| 16 | app.config['SECRET_KEY'] = 'secret!' |
| 17 | thread = None |
| 18 | clients = {} |
| 19 | |
| 20 | |
| 21 | def 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 | |
| 48 | def exabgp_update_event(): |
| 49 | while True: |
| 50 | line = stdin.readline().strip() |
| 51 | messages = message_parser(line) |
| 52 | |
| 53 | |
| 54 | @app.route('/') |
| 55 | def index(): |
| 56 | abort(404) |
| 57 | |
| 58 | |
| 59 | @sio.on('connect', namespace='/onos') |
| 60 | def 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') |
| 67 | def onos_disconnect(sid): |
| 68 | if sid in clients: |
| 69 | del clients[sid] |
| 70 | |
| 71 | |
| 72 | @sio.on('exa_subscribe', namespace='/onos') |
| 73 | def 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 | |
| 79 | if __name__ == '__main__': |
| 80 | app.run(host='0.0.0.0', threaded=True) |