#!/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.

# <<<oracle_sessions>>>
# pengt  15
# hirni  22
# newdb  47 772 65

factory_settings["oracle_sessions_default_levels"] = {
    "sessions_abs": (150, 300),
}


def parse_oracle_sessions(info):
    header = ["cursess", "maxsess", "curmax"]
    parsed = {}
    for line in info:
        for key, entry in zip(header, line[1:]):
            try:
                parsed.setdefault(line[0], {})[key] = int(entry)
            except ValueError:
                pass
    return parsed


def inventory_oracle_sessions(parsed):
    for sid in parsed:
        yield sid, {}


def check_oracle_sessions(item, params, parsed):
    if isinstance(params, tuple):
        params = {"sessions_abs": params}

    if item in parsed and 'cursess' in parsed[item]:
        data = parsed[item]
        sessions = data['cursess']
        sessions_max = data.get('maxsess')

        if sessions_max is not None:
            state = 0
            infotext = "%d of %d sessions" % (sessions, sessions_max)
            sessions_perc = 100.0 * sessions / sessions_max
            infotext_perc = "%.2f%%" % sessions_perc
            if "sessions_perc" in params:
                warn_perc, crit_perc = params["sessions_perc"]
                if sessions_perc >= crit_perc:
                    state = 2
                elif sessions_perc >= warn_perc:
                    state = 1
                if state:
                    infotext_perc += " (warn/crit at %.1f%%/%.1f%%)" % (warn_perc, crit_perc)
            yield state, infotext_perc

        else:
            infotext = "%d sessions" % sessions

        state = 0
        warn, crit = None, None
        if "sessions_abs" in params and not params["sessions_abs"] is None:
            warn, crit = params["sessions_abs"]
            if sessions >= crit:
                state = 2
            elif sessions >= warn:
                state = 1
            if state:
                infotext += " (warn/crit at %d/%d)" % (warn, crit)
        yield state, infotext, [("sessions", sessions, warn, crit, 0, sessions_max)]

        return

    # In case of missing information we assume that the login into
    # the database has failed and we simply skip this check. It won't
    # switch to UNKNOWN, but will get stale.
    raise MKCounterWrapped("Login into database failed")


check_info["oracle_sessions"] = {
    "parse_function": parse_oracle_sessions,
    'inventory_function': inventory_oracle_sessions,
    'check_function': check_oracle_sessions,
    'service_description': 'ORA %s Sessions',
    'has_perfdata': True,
    'group': 'oracle_sessions',
    'default_levels_variable': 'oracle_sessions_default_levels'
}
