#!/usr/bin/env python3 import requests import urllib3 from os import environ import tomlkit from mako.template import Template urllib3.disable_warnings() CONFIGFILE = environ.get('STATUSPAGE_CONFIG', 'config.toml') class StatusPage: def get_api_result(self): if self.services: return self.services headers = { 'Accept': 'application/json', 'X-HTTP-Method-Override': 'GET' } requestbody = { "attrs": [ "name", "state", "last_check_result", "host_name", "display_name" ], "joins": [ "host.name", "host.state", "host.last_check_result", "host.vars" ], "filter": self.config['filters']['services'], } r = requests.get( '{}/v1/objects/services'.format(self.config['icinga2_api']['baseurl']), headers=headers, json=requestbody, auth=(self.config['icinga2_api']['username'], self.config['icinga2_api']['password']), verify=False ) if (r.status_code == 200): self.services = r.json()['results'] else: r.raise_for_status() return self.services def prettify(self, text): for search, replace in self.config.get('prettify', {}).items(): text = text.replace(search, replace) return text def get_services_per_host(self): state_to_design_mapping = [ ('success', 'OK'), ('warning', 'WARNING'), ('danger', 'CRITICAL'), ('info', 'UNKNOWN'), ] result = {} for service in self.get_api_result(): host = service['joins']['host']['vars']['pretty_name'] if host not in result: result[host] = { 'hostname': service['attrs']['host_name'], 'services': {}, } if service['joins']['host']['state'] == 0: result[host]['host_badge'] = 'success' result[host]['host_state'] = 'UP' else: result[host]['host_badge'] = 'danger' result[host]['host_state'] = 'DOWN' self.ragecounter += 10 state = int(service['attrs']['state']) if state in (1, 2): self.ragecounter += state result[host]['services'][self.prettify(service['attrs']['display_name'])] = { 'badge': state_to_design_mapping[state][0], 'state': state_to_design_mapping[state][1], } return result def render_html(self, service_details): if self.ragecounter == 0: mood = '🆗' elif self.ragecounter < 10: mood = '🚨' else: mood = '🔥' 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, ) with open(self.config['output']['filename'], 'w') as f: f.write(output) def __init__(self): self.config = tomlkit.loads(open(CONFIGFILE).read()) self.services = {} self.ragecounter = 0 if __name__ == "__main__": page = StatusPage() service_details = page.get_services_per_host() from pprint import pprint pprint(service_details) page.render_html(service_details)