add some logging and error handling

This commit is contained in:
Franzi 2023-05-20 20:08:08 +02:00
parent fee4b8dac0
commit 0a0ee1bbfc
Signed by untrusted user: kunsi
GPG key ID: 12E3D2136B818350
2 changed files with 71 additions and 4 deletions

36
error.html Normal file
View file

@ -0,0 +1,36 @@
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>${title}</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="bootstrap.min.css">
<link rel="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>🔥</text></svg>">
</head>
<body>
<div class="container">
<div class="page-header my-5" id="banner">
<div class="row">
<div class="col-lg-8">
<h1>Status: 🔥</h1>
</div>
</div>
</div>
<div class="row">
<div class="col">
<div class="card text-white border-primary mb-3">
<div class="card-header d-flex justify-content-between align-items-center">
<h4>Something went wrong</h4>
</div>
<div class="card-body">
<p>
There was an error rendering the status page.
Admins have been notified.
</p>
</div>
</div>
</div>
</div>
</div>
</body>
</html>

View file

@ -3,10 +3,13 @@
import requests
import urllib3
from os import environ
import sys
import logging
import tomlkit
from mako.template import Template
import shutil
from datetime import datetime
urllib3.disable_warnings()
CONFIGFILE = environ.get('STATUSPAGE_CONFIG', 'config.toml')
@ -14,6 +17,8 @@ CONFIGFILE = environ.get('STATUSPAGE_CONFIG', 'config.toml')
class StatusPage:
def get_api_result(self):
if self.services:
log.debug('services already exist, returning early')
return self.services
headers = {
@ -23,7 +28,7 @@ class StatusPage:
requestbody = {
"attrs": [ "name", "state", "last_check_result", "host_name", "display_name" ],
"joins": [ "host.name", "host.state", "host.last_check_result", "host.vars" ],
"joins": [ "host", "host.state", "host.last_check_result", "host.vars" ],
"filter": self.config['filters']['services'],
}
@ -35,11 +40,16 @@ class StatusPage:
verify=False
)
self.logger.info(f'got http status code {r.status_code}')
self.logger.debug(r.text)
if (r.status_code == 200):
self.services = r.json()['results']
else:
r.raise_for_status()
self.logger.info(f'got {len(self.services)} services from api')
return self.services
@ -60,6 +70,9 @@ class StatusPage:
result = {}
for service in self.get_api_result():
self.logger.info(f'now processing {service["attrs"]["host_name"]} "{service["attrs"]["display_name"]}"')
self.logger.debug(service)
host = service['joins']['host']['vars']['pretty_name']
if host not in result:
@ -84,6 +97,7 @@ class StatusPage:
'badge': state_to_design_mapping[state][0],
'state': state_to_design_mapping[state][1],
}
self.logger.info(f'ragecounter is now {self.ragecounter}')
return result
@ -96,12 +110,18 @@ class StatusPage:
else:
mood = '🔥'
self.logger.info('rendering output html')
start = datetime.now()
template = Template(filename=self.config['output'].get('template', 'template.html'))
output = template.render(
title=self.config['output'].get('page_title', 'Status Page'),
mood=mood,
hosts=service_details,
)
end = datetime.now()
self.logger.info(f'rendered in {(end-start).total_seconds():.09f}s')
with open(self.config['output']['filename'], 'w') as f:
f.write(output)
@ -112,8 +132,19 @@ class StatusPage:
self.services = {}
self.ragecounter = 0
self.logger = logging.getLogger('StatusPage')
handler = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter('%(levelname)s {%(filename)s:%(lineno)d} %(message)s')
handler.setFormatter(formatter)
self.logger.addHandler(handler)
self.logger.setLevel(self.config.get('loglevel', 'INFO'))
if __name__ == "__main__":
page = StatusPage()
try:
service_details = page.get_services_per_host()
page.render_html(service_details)
except Exception as e:
shutil.copyfile('error.html', page.config['output']['filename'])
raise e