#!/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" : (50, 100),
}


def parse_oracle_sessions(info):
    parsed = {}
    for line in info:
        if len(line) == 4:
            # new format with max values
            sid, cursess, maxsess, curmax = line
            parsed.setdefault(sid, {
                 "cursess" : int(cursess),
                 "maxsess" : int(maxsess),
                 "curmax"  : int(curmax),
            })

        elif len(line) == 7:
            # detailed session information for PDBs
            sid, pdb_name, sstate, smode, stype, bmode, cnt = line

            if pdb_name <> '' and pdb_name <> 'CDB$ROOT':
                sid = '%s.%s' % (sid, pdb_name)

            if sstate == '':
                # found a line with only number of sessions
                # typically found in PDB without any connected session
                parsed.setdefault(sid, {
                    "count" : cnt,
                })

            else:
                parsed.setdefault(sid, {
                    "count"     : cnt,
                    "sessstate" : sstate,
                    "sessmode"  : smode,
                    "sesstype"  : stype,
                    "blockmode" : bmode,
                })

        elif len(line) == 2:
            # old agent format!
            sid, cursess = line
            parsed.setdefault(sid, {
                 "cursess" : int(cursess),
            })

    return parsed


def inventory_oracle_sessions(parsed):
    for sid in parsed:
        if sid.find(".") < 0:
            yield sid, {}


def check_oracle_sessions(item, params, parsed):
    if type(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"] == 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'
}
