misp-dashboard/server.py

113 lines
3.4 KiB
Python
Raw Normal View History

2017-08-24 07:25:13 +02:00
#!/usr/bin/env python3.5
2017-08-24 11:43:23 +02:00
from flask import Flask, render_template, Response
import json
import redis
2017-10-11 10:47:11 +02:00
import random
import configparser
2017-08-24 11:47:54 +02:00
from time import gmtime as now
from time import sleep, strftime
import os
configfile = os.path.join(os.environ['VIRTUAL_ENV'], '../config.cfg')
cfg = configparser.ConfigParser()
cfg.read(configfile)
2017-08-24 11:43:23 +02:00
2017-08-24 07:25:13 +02:00
app = Flask(__name__)
2017-10-11 10:47:11 +02:00
redis_server_log = redis.StrictRedis(
host=cfg.get('RedisLog', 'host'),
port=cfg.getint('RedisLog', 'port'),
db=cfg.getint('RedisLog', 'db'))
redis_server_map = redis.StrictRedis(
host=cfg.get('RedisMap', 'host'),
port=cfg.getint('RedisMap', 'port'),
db=cfg.getint('RedisMap', 'db'))
subscriber_log = redis_server_log.pubsub(ignore_subscribe_messages=True)
subscriber_log.psubscribe(cfg.get('RedisLog', 'channel'))
subscriber_map = redis_server_map.pubsub(ignore_subscribe_messages=True)
subscriber_map.psubscribe(cfg.get('RedisMap', 'channelDisp'))
eventNumber = 0
class LogItem():
2017-08-24 11:43:23 +02:00
2017-09-12 12:27:35 +02:00
FIELDNAME_ORDER = []
for item in json.loads(cfg.get('Log', 'fieldname_order')):
FIELDNAME_ORDER.append(item)
2017-08-24 11:43:23 +02:00
#def __init__(self, feed='', time='', level='level', src='source', name='name', message='wonderful meesage'):
def __init__(self, feed):
self.time = strftime("%H:%M:%S", now())
2017-09-12 12:34:15 +02:00
#FIXME Parse feed message?
2017-09-12 12:27:35 +02:00
self.fields = []
2017-09-12 12:34:15 +02:00
self.fields.append(self.time)
2017-09-12 12:27:35 +02:00
for f in feed:
self.fields.append(f)
2017-08-24 11:43:23 +02:00
def get_head_row(self):
to_ret = []
for fn in LogItem.FIELDNAME_ORDER:
to_ret.append(fn[0].upper()+fn[1:])
2017-08-24 11:43:23 +02:00
return to_ret
def get_row(self):
to_ret = {}
#Number to keep them sorted (jsonify sort keys)
2017-09-12 12:27:35 +02:00
for i in range(len(LogItem.FIELDNAME_ORDER)):
try:
2017-09-12 12:34:15 +02:00
to_ret[i] = self.fields[i]
2017-09-12 12:27:35 +02:00
except IndexError: # not enough field in rcv item
2017-09-12 12:34:15 +02:00
to_ret[i] = ''
2017-08-24 11:43:23 +02:00
return to_ret
class EventMessage():
# Suppose the event message is a json with the format {name: 'feedName', log:'logData'}
2017-08-24 11:43:23 +02:00
def __init__(self, msg):
msg = msg.decode('utf8')
try:
jsonMsg = json.loads(msg)
except json.JSONDecodeError:
2017-09-12 12:27:35 +02:00
print('json decode error')
jsonMsg = { 'name': "undefined" ,'log': json.loads(msg) }
2017-08-24 11:43:23 +02:00
self.feedName = jsonMsg['name']
2017-09-12 12:27:35 +02:00
self.feed = json.loads(jsonMsg['log'])
self.feed = LogItem(self.feed).get_row()
2017-08-24 11:43:23 +02:00
def to_json(self):
to_ret = { 'log': self.feed, 'feedName': self.feedName }
2017-08-24 11:43:23 +02:00
return 'data: {}\n\n'.format(json.dumps(to_ret))
2017-08-24 07:25:13 +02:00
@app.route("/")
def index():
return render_template('index.html',
graph_log_refresh_rate=cfg.getint('Dashboard' ,'graph_log_refresh_rate')
)
2017-08-24 07:25:13 +02:00
2017-08-24 11:43:23 +02:00
@app.route("/_logs")
def logs():
2017-10-11 10:47:11 +02:00
return Response(event_stream_log(), mimetype="text/event-stream")
@app.route("/_maps")
def maps():
return Response(event_stream_maps(), mimetype="text/event-stream")
2017-08-24 11:43:23 +02:00
@app.route("/_get_log_head")
def getLogHead():
return json.dumps(LogItem('').get_head_row())
2017-08-24 11:43:23 +02:00
2017-10-11 10:47:11 +02:00
def event_stream_log():
for msg in subscriber_log.listen():
content = msg['data']
yield EventMessage(content).to_json()
2017-08-24 07:25:13 +02:00
2017-10-11 10:47:11 +02:00
def event_stream_maps():
for msg in subscriber_map.listen():
content = msg['data'].decode('utf8')
2017-10-13 15:03:09 +02:00
print('sending map', content)
yield 'data: {}\n\n'.format(content)
2017-10-11 10:47:11 +02:00
2017-08-24 07:25:13 +02:00
if __name__ == '__main__':
2017-10-11 10:47:11 +02:00
app.run(host='localhost', port=8000, threaded=True)