blueprints.api: add calc_uptime, uptime field on api

This commit is contained in:
Luna Mendes 2018-08-08 17:30:51 -03:00
parent 93de3dfda0
commit 86c99c8fee

View file

@ -1,3 +1,4 @@
from decimal import Decimal
from sanic import Blueprint, response from sanic import Blueprint, response
bp = Blueprint(__name__) bp = Blueprint(__name__)
@ -42,10 +43,51 @@ def get_graphs(manager):
return res return res
def calc_uptime(manager):
res = {}
for name, worker in manager.workers.items():
cur = manager.conn.cursor()
# get total period we've been polling the service
cur.execute(f"""
SELECT min(timestamp), max(timestamp) from {name}
""")
row = cur.fetchone()
min_tstamp, max_tstamp = row[0], row[1]
t_period = max_tstamp - min_tstamp
# get all polls that failed
cur.execute(f"""
SELECT COUNT(*) FROM {name}
WHERE status = false
""")
row = cur.fetchone()
down_hits = row[0]
# total downtime in seconds
downtime = down_hits * worker.service['poll']
# calculate total downtime in percentage
percent = Decimal(downtime) / Decimal(t_period)
# uptime - downtime = real uptime
res[name] = str(Decimal(100) - percent)
return res
@bp.get('/api/current_status') @bp.get('/api/current_status')
async def get_cur_status(request): async def get_cur_status(request):
manager = request.app.manager manager = request.app.manager
return response.json(get_status(manager)) return response.json({
**get_status(manager),
**{
'uptime': calc_uptime(manager)
}
})
@bp.get('/api/status') @bp.get('/api/status')
@ -55,4 +97,5 @@ async def get_full_status(request):
return response.json({ return response.json({
'status': get_status(manager), 'status': get_status(manager),
'graph': get_graphs(manager), 'graph': get_graphs(manager),
'uptime': calc_uptime(manager)
}) })