import json from pathlib import Path from flask import Flask, Response, request from icinga2api.client import Client client = Client('https://localhost:8080', 'icingaweb2', 'password1234') OK = 0 WARNING = 1 CRITICAL = 2 UNKNOWN = 3 app = Flask(__name__) def return_json(json_dict, start_response, status_code=200): headers = [('Content-Type', 'application/json')] start_response(str(status_code), headers) return iter([json.dumps(json_dict).encode('utf-8')]) @app.route('/host') @app.route('/host/') @app.route("/host/") def get_host_state(hostid=None): path = Path(request.base_url) args_service = request.args.getlist('service') kuma_mode = True if request.args.get('kuma') == 'true' else False if not hostid: return Response(json.dumps({'error': 'must specify host'}), status=406, mimetype='application/json') result = { 'host': {}, 'services': {}, 'failed_services': [] } host_status = client.objects.list('Host', filters='match(hpattern, host.name)', filter_vars={'hpattern': hostid}) if not len(host_status): return Response(json.dumps({'error': 'could not find host'}), status=404, mimetype='application/json') else: host_status = host_status[0] result['host'] = { 'name': host_status['name'], 'state': 0 if (host_status['attrs']['acknowledgement'] or host_status['attrs']['acknowledgement_expiry']) else host_status['attrs']['state'], 'actual_state': host_status['attrs']['state'], 'attrs': { **host_status['attrs'] } } services_status = client.objects.list('Service', filters='match(hpattern, host.name)', filter_vars={'hpattern': hostid}) for attrs in services_status: name = attrs['name'].split('!')[1] result['services'][name] = { 'state': 0 if (attrs['attrs']['acknowledgement'] or attrs['attrs']['acknowledgement_expiry']) else attrs['attrs']['state'], 'actual_state': attrs['attrs']['state'], 'attrs': { **attrs } } if len(args_service): services = {} for service in args_service: if service in result['services'].keys(): services[service] = result['services'][service] else: return Response(json.dumps({'error': 'service not found', 'service': service}), status=400, mimetype='application/json') result['services'] = services if kuma_mode: for name, service in result['services'].items(): if service['state'] != OK: result['failed_services'].append({'name': name, 'state': service['state']}) if result['host']['state'] != OK: result['failed_services'].append({'name': hostid, 'state': result['host']['state']}) if len(result['failed_services']): return Response(json.dumps(result), status=410, mimetype='application/json') else: return result