#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (C) 2019 tribe29 GmbH - License: GNU General Public License v2
# This file is part of Checkmk (https://checkmk.com). It is subject to the terms and
# conditions defined in the file COPYING, which is part of this source code package.

# <<<haproxy:sep(44)>>>
# # pxname,svname,qcur,qmax,scur,smax,slim,stot,bin,bout,dreq,dresp,ereq,econ,eresp,wretr,wredis,status,weight,act,bck,chkfail,chkdown,lastchg,downtime,qlimit,pid,iid,sid,throttle,lbtot,tracked,type,rate,rate_lim,rate_max,check_status,check_code,check_duration,hrsp_1xx,hrsp_2xx,hrsp_3xx,hrsp_4xx,hrsp_5xx,hrsp_other,hanafail,req_rate,req_rate_max,req_tot,cli_abrt,srv_abrt,comp_in,comp_out,comp_byp,comp_rsp,lastsess,last_chk,last_agt,qtime,ctime,rtime,ttime,
# https_t3test.tgic.de,FRONTEND,,,0,0,2000,0,0,0,0,0,0,,,,,OPEN,,,,,,,,,1,2,0,,,,0,0,0,0,,,,0,0,0,0,0,0,,0,0,0,,,0,0,0,0,,,,,,,,
# https_t3test.tgic.de,BACKEND,0,0,0,0,200,0,0,0,0,0,,0,0,0,0,UP,0,0,0,,0,363417,0,,1,2,0,,0,,1,0,,0,,,,0,0,0,0,0,0,,,,,0,0,0,0,0,0,-1,,,0,0,0,0,
# t3test,t3test,0,0,0,0,,0,0,0,,0,,0,0,0,0,UP,1,1,0,0,0,363417,0,,1,3,1,,0,,2,0,,0,L4OK,,0,0,0,0,0,0,0,0,,,,0,0,,,,,-1,,,0,0,0,0,

# <<<haproxy:sep(44)>>>
# BLABLABFO,ELEADC05,0,0,0,5,,841,483793,1386127,,0,,0,751,0,0,UP,1,1,0,0,0,38624,0,,1,5,2,,841,,2,0,,4,L4OK,,0,,,,,,,0,,,,90,751,,,,,169,,,0,0,0,3073,
# BLABLABLABLA,FRONTEND,,,0,0,2000,0,0,0,0,0,0,,,,,OPEN,,,,,,,,,1,2,0,,,,0,0,0,0,,,,0,0,0,0,0,0,,0,0,0,,,0,0,0,0,,,,,,,,
# LDAP,IP.IP.IP.IP,,,0,32,250,5892,3365040,9470591,0,0,0,,,,,OPEN,,,,,,,,,1,3,1,,,,3,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,

# from http://www.haproxy.org/download/1.7/doc/management.txt
# 0=frontend, 1=backend, 2=server, 3=socket/listener


def parse_haproxy(info):
    parsed = {}
    for line in info:
        if len(line) <= 32 or line[32] not in ('0', '2'):
            continue

        data = {"status": line[17]}

        if line[32] == "0":
            data["type"] = "frontend"
            item = line[0]
            try:
                data["stot"] = int(line[7])
            except ValueError:
                continue

        elif line[32] == "2":
            data["type"] = "server"
            item = "%s/%s" % (line[0], line[1])
            data["layer_check"] = line[36]
            for key, idx in (("uptime", 23), ("active", 19), ("backup", 20)):
                try:
                    data[key] = int(line[idx])
                except ValueError:
                    continue

        parsed[item] = data

    return parsed


check_info["haproxy"] = {
    'parse_function': parse_haproxy,
}


@get_parsed_item_data
def check_haproxy_frontend(item, _no_params, data):
    status = data.get("status")
    yield 0 if status == "OPEN" else 2, "Status: %s" % status

    stot = data.get("stot")
    if stot is not None:
        session_rate = get_rate("sessions.%s" % item, time.time(), stot)
        yield check_levels(session_rate, 'session_rate', None, infoname="Session Rate")


check_info["haproxy.frontend"] = {
    'check_function': check_haproxy_frontend,
    'inventory_function': discover(lambda _k, v: v.get("type") == "frontend"),
    'service_description': 'HAProxy Frontend %s',
    'has_perfdata': True,
}


@get_parsed_item_data
def check_haproxy_server(_item, _no_params, data):
    status = data.get("status")
    yield 0 if status == "UP" else 2, "Status: %s" % status

    if data.get("active"):
        yield 0, "Active"
    elif data.get("backup"):
        yield 0, "Backup"
    else:
        yield 2, "Neither active nor backup"

    yield 0, "Layer Check: %s" % data['layer_check']

    uptime = data.get("uptime")
    if uptime is not None:
        yield 0, "Up since %s" % get_age_human_readable(uptime)


check_info["haproxy.server"] = {
    'check_function': check_haproxy_server,
    'inventory_function': discover(lambda _k, v: v.get("type") == "server"),
    'service_description': 'HAProxy Server %s',
}
