monit-dashboard/bin/monit-dashboard.py

117 lines
2.8 KiB
Python
Raw Normal View History

#!/usr/bin/python
import web
import requests
import xmltodict
import json
import os
import sys
import datetime
2019-08-14 11:01:29 +00:00
from collections import OrderedDict
from operator import itemgetter
import utils
urls = ('/', 'index',
'/help', 'help',
'/download', 'download'
)
app = web.application(urls, globals())
render = web.template.render('templates/', base="layout")
# Uncomment to turn debug off
web.config.debug = False
# Variables
output = []
# Functions
2020-01-26 23:21:03 +00:00
2019-10-25 15:48:24 +00:00
def calculate_count(data):
count = {}
2020-08-22 19:45:32 +00:00
ls = list(data.values())
2020-01-26 23:21:03 +00:00
z, nz = 0, 0
2019-08-16 17:07:50 +00:00
for v in ls:
if v == 0:
z += 1
else:
nz += 1
2019-10-25 15:48:24 +00:00
count['green'] = z
count['red'] = nz
return count
2019-08-16 17:07:50 +00:00
def getMonit():
output = []
xmlQuery = "/_status?format=xml"
with open('{0}/conf/servers.json'.format(os.path.expanduser('.'))) as f:
cf = json.loads(f.read())
for site in cf:
s = cf[site]
r = requests.get(s['url'] + xmlQuery,
auth=(s['user'], s['passwd']),
timeout=5)
allstat = json.loads(json.dumps(xmltodict.parse(r.text)['monit']))
services = allstat['service']
status = {}
2019-08-14 11:10:54 +00:00
server = {}
2019-08-14 11:01:29 +00:00
checks = OrderedDict()
for service in services:
name = service['name']
status[name] = int(service['status'])
2019-08-14 11:10:54 +00:00
checks[name] = status[name]
2019-08-14 11:01:29 +00:00
sorted_checks = OrderedDict()
2020-08-22 19:45:32 +00:00
sorted_checks = OrderedDict(sorted(iter(checks.items()),
2020-01-26 23:21:03 +00:00
key=itemgetter(1), reverse=True))
2019-10-25 15:48:24 +00:00
count = calculate_count(sorted_checks)
2019-11-24 13:25:21 +00:00
server = dict(name=site, url=s['url'],
2020-01-26 23:21:03 +00:00
result=sorted_checks, s_rate=count)
output.append(server)
2020-08-22 19:45:32 +00:00
print((datetime.datetime.now()))
return(output)
# Classes
2020-01-26 23:21:03 +00:00
class monitDashboard(web.application):
def run(self, port=8080, *middleware):
func = self.wsgifunc(*middleware)
return web.httpserver.runsimple(func, ('0.0.0.0', port))
class index(object):
def GET(self):
return render.index(output=getMonit(),
2020-01-26 23:21:03 +00:00
now=datetime.datetime.now())
class help(object):
def GET(self):
return render.help()
2020-01-26 23:21:03 +00:00
2019-11-24 13:25:21 +00:00
class download(object):
def GET(self):
filename = 'health_report.xlsx'
output = getMonit()
utils.generate_report_excel(output, filename)
web.header('Content-Disposition',
2020-01-26 23:21:03 +00:00
'attachment; filename="health_report.xlsx"')
web.header('Content-type', 'application/octet-stream')
web.header('Cache-Control', 'no-cache')
2019-11-24 13:25:21 +00:00
return open(filename, 'rb').read()
2020-01-26 23:21:03 +00:00
# Main
if __name__ == "__main__":
app = monitDashboard(urls, globals())
app.run(port=8080)