#!/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.
#
# session_id, wait_duration_ms, wait_type, blocking_session_id
# <<<mssql_blocked_sessions>>>
# Blocked _Sessions
# 119 232292187 LCK_M_U 75
# 76 221526672 LCK_M_U 115

# <<<mssql_blocked_sessions:sep(124)>>>
# Blocked _Sessions
# 119|232292187|LCK_M_U|75
# 76|221526672|LCK_M_U|115

# <<<mssql_blocked_sessions:sep(124)>>>
# Blocked _Sessions
# INST_ID1|119|232292187|LCK_M_U|75
# INST_ID2|76|221526672|LCK_M_U|115

# <<<mssql_blocked_sessions:sept(124)>>>
# INST_ID1|No blocking sessions

factory_settings['mssql_blocked_sessions_default_levels'] = {
    'state': 2,
}

NO_BLOCKING_SESSIONS_MSG = 'No blocking sessions'


def parse_mssql_blocked_sessions(info):
    db_instance = collections.namedtuple(
        "DBInstance", ["session_id", "wait_type", "blocking_session_id", "wait_duration"])
    parsed = {}
    for line in info:
        if line[-1].startswith("ERROR:"):
            continue

        if len(line) == 2 and line[1] == NO_BLOCKING_SESSIONS_MSG:
            parsed.setdefault(line[0], NO_BLOCKING_SESSIONS_MSG)
            continue

        elif len(line) == 1 and line[-1] == NO_BLOCKING_SESSIONS_MSG:
            parsed.setdefault("", NO_BLOCKING_SESSIONS_MSG)
            continue

        elif len(line) == 4:
            session_id, wait_duration_ms, wait_type, blocking_session_id = line
            inst = ""

        elif len(line) == 5:
            inst, session_id, wait_duration_ms, wait_type, blocking_session_id = line

        else:
            continue

        parsed.setdefault(inst, []).append(
            db_instance(
                session_id,
                wait_type,
                blocking_session_id,
                float(wait_duration_ms) / 1000,
            ))

    return parsed


def check_mssql_blocked_sessions(item, params, parsed):
    if item is None:
        item = ""

    data = parsed.get(item)
    if data is None:
        # Assume general connection problem to the database, which is reported
        # by the "X Instance" service and skip this check.
        raise MKCounterWrapped("Failed to retrieve data from database")

    if data == NO_BLOCKING_SESSIONS_MSG:
        yield 0, NO_BLOCKING_SESSIONS_MSG
        return

    summary = {}
    details = []
    warn, crit = params.get('waittime', (None, None))
    ignored_waittypes = set()
    waittypes_to_be_ignored = params.get("ignore_waittypes", [])

    for db_inst in data:
        if db_inst.wait_type in waittypes_to_be_ignored:
            ignored_waittypes.add(db_inst.wait_type)
            continue

        if crit is not None and db_inst.wait_duration >= crit:
            state = 2
        elif warn is not None and db_inst.wait_duration >= warn:
            state = 1
        else:
            state = 0

        summary.setdefault(db_inst.session_id, 0)
        summary[db_inst.session_id] += 1
        details.append((state, "Session %s blocked by %s (Type: %s, Wait: %s)" % \
                       (db_inst.session_id, db_inst.blocking_session_id, db_inst.wait_type,
                        get_age_human_readable(db_inst.wait_duration))))

    if summary:
        yield params['state'], "Summary: %s" % (", ".join(
            ["%s blocked by %s ID(s)" % (k, v) for k, v in sorted(summary.iteritems())]))

        max_state = max([state for state, _infotext in details])
        if max_state:
            yield max_state, 'At least one session above thresholds (warn/crit at %s/%s)' % (
                get_age_human_readable(warn), get_age_human_readable(crit))
        for state, infotext in details:
            yield state, "\n%s" % infotext

    else:
        yield 0, "No blocked sessions"

    if ignored_waittypes:
        yield 0, "\nIgnored wait types: %s" % ", ".join(ignored_waittypes)


check_info['mssql_blocked_sessions'] = {
    'parse_function': parse_mssql_blocked_sessions,
    'inventory_function': discover(),
    'check_function': check_mssql_blocked_sessions,
    'service_description': 'MSSQL %s Blocked Sessions',
    'group': 'mssql_instance_blocked_sessions',
    'default_levels_variable': 'mssql_blocked_sessions_default_levels',
}
