#!/usr/bin/env python

# Nagios monitoring script, used for check 5XX error of all applications,
# written by Ma Libo @ 2018.5.7
import requests
import sys

# Nagios Return Code
OK=0
WARN=1
CRITICAL=2
UNKNOWN=3

def get_data(url):
    if url:
        rst = requests.get(url)
    if rst.ok:
        return rst.json()['data']['result']
    else:
        return None
    return


def calculate_data(data, threshold=200):
    """ if threshold > 200 , return error message
    """
    alert_message = {
            'message_body': "",
            'value': OK,
            'error_data': [],
            'normal_data': []
            }

    if data is not None:
        for app in data:
            if float(app['value'][1]) > float(threshold):
                _app = app['metric']['host']
                _5xx_err = float(app['value'][1])
                alert_message['error_data'].append((_app, _5xx_err, 1))
            else:
                alert_message['normal_data'].append((app['metric']['host'], float(app['value'][1]), 0))

        if alert_message['error_data']:
            alert_message['message_body'] = "CRITICAL: 5XX ERROR | {0} are TOO high!".format(" | ".join(["{0} ==> {1:.0f}".format(d[0],d[1]) for d in alert_message['error_data']]))
            alert_message['value'] = CRITICAL
            return alert_message
        else:
            alert_message['message_body'] = "OK: All applications {0} 5XX Errors under normal status".format(" | ".join(["{0} ==> {1:.0f}".format(d[0],d[1]) for d in alert_message['normal_data']]))
            return alert_message
    else:
        alert_message['message_body'] = "ERROR: No Data found"
        alert_message['value'] = UNKNOWN
        return alert_message


if __name__ == '__main__':
    import time
    import sys
    nowtime = time.time()

    url = "http://prometheus.garenanow.com/api/v1/query?query=sum(job%3Anginx_requests_total%3Aincrease_by_endpoint%7Bstatus_code%3D~%225..%22%7D)+by+(host)"
    data = get_data(url)

    if len(sys.argv) != 2:
        script = sys.argv[0]
        print "Usage: python {0} threshold".format(script)
        sys.exit(UNKNOWN)

    script, threshold = sys.argv
    alert_message = calculate_data(data, threshold)

    if alert_message['value'] != 0:
        print alert_message['message_body']
        sys.exit(alert_message['value'])
    else:
        print "OK: All applications under normal status."
        sys.exit(alert_message['value'])
