#!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 vim: set ft=python:-*-
# +------------------------------------------------------------------+
# |             ____ _               _        __  __ _  __           |
# |            / ___| |__   ___  ___| | __   |  \/  | |/ /           |
# |           | |   | '_ \ / _ \/ __| |/ /   | |\/| | ' /            |
# |           | |___| | | |  __/ (__|   <    | |  | | . \            |
# |            \____|_| |_|\___|\___|_|\_\___|_|  |_|_|\_\           |
# |                                                                  |
# | Copyright Mathias Kettner 2015             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.

factory_settings['msexch_database_defaultlevels'] = {
    "read_attached_latency": (200., 250.),
    "read_recovery_latency": (150., 200.),
    "write_latency": (40., 50.),
    "log_latency": (5., 10.),
}

_CHECKED_COUNTERS = [  # counter, setting, name, perfvar
    ("i/o database reads (attached) average latency", "read_attached_latency",
     "db read (attached) latency", "db_read_latency"),
    ("i/o database reads (recovery) average latency", "read_recovery_latency",
     "db read (recovery) latency", "db_read_recovery_latency"),
    ("i/o database writes (attached) average latency", "write_latency",
     "db write (attached) latency", "db_write_latency"),
    ("i/o log writes average latency", "log_latency", "Log latency", "db_log_latency"),
]

_de_DE = {
    u'e/a: durchschnittliche wartezeit f\x81r datenbankleseoperationen (angef\x81gt)': "i/o database reads (attached) average latency",
    u'e/a: durchschnittliche wartezeit f\x81r datenbankleseoperationen (wiederherstellung)': "i/o database reads (recovery) average latency",
    u'e/a: durchschnittliche wartezeit f\x81r datenbankschreiboperationen (angef\x81gt)': "i/o database writes (attached) average latency",
    u'e/a: durchschnittliche wartezeit f\x81r protokollschreiboperationen': "i/o log writes average latency",
}


def _delocalize_de_DE(instance, counter, value):
    # replace localized thousands-/ decimal-separators
    value = value.replace(".", "").replace(",", ".")
    counter = _de_DE.get(counter, counter)
    return instance, counter, value


def parse_msexch_database(info):

    if not (info and info[0]):
        return {}

    delocalize_func = None
    offset = 0
    if len(info[0]) > 1 and info[0][0] == 'locale':
        locale = info[0][1].strip()
        offset = 1
        delocalize_func = {
            'de-DE': _delocalize_de_DE,
        }.get(locale)

    parsed = {}
    for row in info[offset:]:
        row = [r.strip('"') for r in row]
        if len(row) != 2 or not row[0].startswith('\\\\'):
            continue

        __, obj, counter = row[0].rsplit("\\", 2)
        instance = obj.split("(", 1)[-1].split(")", 1)[0]
        value = row[1]

        if delocalize_func is not None:
            instance, counter, value = delocalize_func(instance, counter, value)

        # The entries for log verifier contain an ID as the last part
        # which changes upon reboot of the exchange server. Therefore,
        # we just remove them here as a workaround.
        if '/log verifier' in instance:
            instance = instance.rsplit(' ', 1)[0]

        try:
            parsed.setdefault(instance, {})[counter] = float(value)
        except ValueError:
            continue
    return parsed


def inventory_msexch_database(parsed):
    for instance, data in parsed.iteritems():
        if any(entry[0] in data for entry in _CHECKED_COUNTERS):
            yield instance, None


def check_msexch_database(item, params, parsed):
    data = parsed.get(item)
    if data is None:
        return

    for counter, setting, name, perfvar in _CHECKED_COUNTERS:
        value = data.get(counter)
        if value is None:
            continue
        status = 0
        warn, crit = params.get(setting, (None, None))
        if crit is not None and value >= crit:
            status = 2
        elif warn is not None and value >= warn:
            status = 1
        yield status, "%.1fms %s" % (value, name), [(perfvar, value, warn, crit, None, None)]


check_info['msexch_database'] = {
    'inventory_function': inventory_msexch_database,
    'check_function': check_msexch_database,
    'parse_function': parse_msexch_database,
    'has_perfdata': True,
    'service_description': "Exchange Database %s",
    'group': 'msx_database',
    'default_levels_variable': 'msexch_database_defaultlevels'
}
