#!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# |             ____ _               _        __  __ _  __           |
# |            / ___| |__   ___  ___| | __   |  \/  | |/ /           |
# |           | |   | '_ \ / _ \/ __| |/ /   | |\/| | ' /            |
# |           | |___| | | |  __/ (__|   <    | |  | | . \            |
# |            \____|_| |_|\___|\___|_|\_\___|_|  |_|_|\_\           |
# |                                                                  |
# | Copyright Mathias Kettner 2014             mk@mathias-kettner.de |
# +------------------------------------------------------------------+
#
# This file is part of Check_MK.
# The official homepage is at http://mathias-kettner.de/check_mk.
#
# check_mk is free software;  you can redistribute it and/or modify it
# under the  terms of the  GNU General Public License  as published by
# the Free Software Foundation in version 2.  check_mk is  distributed
# in the hope that it will be useful, but WITHOUT ANY WARRANTY;  with-
# out even the implied warranty of  MERCHANTABILITY  or  FITNESS FOR A
# PARTICULAR PURPOSE. See the  GNU General Public License for more de-
# tails. You should have  received  a copy of the  GNU  General Public
# License along with GNU Make; see the file  COPYING.  If  not,  write
# to the Free Software Foundation, Inc., 51 Franklin St,  Fifth Floor,
# Boston, MA 02110-1301 USA.

# <<<postgres_bloat>>>
# [databases_start]
# postgres
# testdb
# datenbank
# [databases_end]
# db;schemaname;tablename;tups;pages;otta;tbloat;wastedpages;wastedbytes;wastedsize;iname;itups;ipages;iotta;ibloat;wastedipages;wastedibytes;wastedisize;totalwastedbytes
# postgres;pg_catalog;pg_amop;403;4;3;1.3;1;8192;8192;pg_amop_oid_index;403;4;2;2.0;2;16384;16384;24576
# postgres;pg_catalog;pg_amproc;291;3;2;1.5;1;8192;8192;pg_amproc_fam_proc_index;291;4;2;2.0;2;16384;16384;24576
# postgres;pg_catalog;pg_amop;403;4;3;1.3;1;8192;8192;pg_amop_opr_fam_index;403;4;2;2.0;2;16384;16384;24576

factory_settings["postgres_bloat_default_levels"] = {
    'table_bloat_perc': (180.0, 200.0), # WARN at 180%, CRIT at 200%
    'index_bloat_perc': (180.0, 200.0)
}

def inventory_postgres_bloat(parsed):
    for entry in parsed.keys():
        yield entry, {}

def check_postgres_bloat(item, params, parsed):
    database = parsed.get(item)
    if not database:
        return

    table_perc_max = None
    table_abs_max  = None
    index_perc_max = None
    index_abs_max  = None

    table_abs_total  = 0
    index_abs_total  = 0

    show_levels = False
    for line in database:
        tbloat  = float(line["tbloat"])
        twasted = int(line["wastedbytes"])
        ibloat  = float(line["ibloat"])
        iwasted = int(line["wastedibytes"])

        table_abs_total += twasted
        index_abs_total += iwasted

        # Calculate highest loss
        if not table_perc_max or tbloat > float(table_perc_max["tbloat"]):
            table_perc_max = line
        if not table_abs_max or twasted > int(table_abs_max["wastedbytes"]):
            table_abs_max  = line
        if not index_perc_max or ibloat > float(index_perc_max["ibloat"]):
            index_perc_max = line
        if not index_abs_max or iwasted > int(index_abs_max["wastedibytes"]):
            index_abs_max  = line

        for what, bloat, wasted in [ ("table", tbloat, twasted),
                                     ("index", ibloat, iwasted) ]:
            if "%s_bloat_perc" % what in params:
                warn, crit = params["%s_bloat_perc" % what]
                if bloat >= crit:
                    yield 2, "%s %s bloat: %s%% (too high)" % (line["tablename"], what, bloat)
                    show_levels = True
                elif bloat >= warn:
                    yield 1, "%s %s bloat: %s%% (too high)" % (line["tablename"], what, bloat)
                    show_levels = True

            if "%s_bloat_abs" % what in params:
                warn, crit = params["%s_bloat_abs" % what]
                if wasted >= crit:
                    yield 2, "%s wasted %s bytes: %s (too high)" % (line["tablename"], what,
                                get_bytes_human_readable(wasted))
                    show_levels = True
                elif wasted >= warn:
                    yield 1, "%s wasted %s bytes: %s (too high)" % (line["tablename"], what,
                                get_bytes_human_readable(wasted))
                    show_levels = True

    if show_levels:
        levels_info = ["Levels:"]
        for what in ["table", "index"]:
            if "%s_bloat_perc" % what in params:
                levels_info.append("%s Perc (%.0f%%/%.0f%%)" % ((what.title(),) + params["%s_bloat_perc" % what]))
            if "%s_bloat_abs" % what in params:
                levels_info.append("%s Abs (%s/%s)" % ((what.title(),) + \
                    tuple(map(lambda x: get_bytes_human_readable(int(x)), params["%s_bloat_abs" % what]))))
        yield 0, " ".join(levels_info)
    else:
        # No errors. Show some general information
        for what, perc_max, abs_max in [ ("table", table_perc_max, table_abs_max),
                             ("index", index_perc_max, index_abs_max) ]:
            yield 0, "Maximum %s bloat at %s: %d%%" % (what, perc_max["tablename"],
                                                       float(perc_max["%sbloat" % what[0]]) * 100)
            yield 0, "Maximum wasted %sspace at %s: %s" % (what, abs_max["tablename"],
                         get_bytes_human_readable(int(abs_max["wasted%sbytes" % (what == "index" and "i" or "")])))

    # Summary information
    for what, total_value in [ ("table", table_abs_total),
                               ("index", index_abs_total) ]:
        yield 0, "Summary of top %d wasted %sspace: %s" % (len(database), what,
            get_bytes_human_readable(total_value)), [("%sspace_wasted" % what, total_value)]

check_info['postgres_bloat'] = {
    "parse_function"          : parse_postgres_dbs,
    "check_function"          : check_postgres_bloat,
    "inventory_function"      : inventory_postgres_bloat,
    "service_description"     : "PostgreSQL Bloat %s",
    "group"                   : "db_bloat",
    "default_levels_variable" : "postgres_bloat_default_levels",
    "has_perfdata"            : True,
    "includes"                : [ "postgres.include" ]
}

