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

# <<<db2_counters>>>
# TIMESTAMP 1426610723
# db2taddm:CMDBS1 deadlocks 0
# db2taddm:CMDBS1 lockwaits 99
# db2taddm:CMDBS1 sortoverflows 2387
# TIMESTAMP 1426610763
# db2taddm:CMDBS6 deadlocks 99
# db2taddm:CMDBS6 lockwaits 91
# db2taddm:CMDBS6 sortoverflows 237
#### Example for database in DPF mode
# TIMESTAMP 1439976757
# db2ifa:DDST1 node 0 iasv0091 0
# db2ifa:DDST1 node 1 iasv0091 1
# db2ifa:DDST1 node 2 iasv0091 2
# db2ifa:DDST1 node 3 iasv0091 3
# db2ifa:DDST1 node 4 iasv0091 4
# db2ifa:DDST1 node 5 iasv0091 5
# db2ifa:DDST1 deadlocks 0
# db2ifa:DDST1 deadlocks 0
# db2ifa:DDST1 deadlocks 0
# db2ifa:DDST1 deadlocks 0
# db2ifa:DDST1 deadlocks 0
# db2ifa:DDST1 deadlocks 0
# db2ifa:DDST1 lockwaits 0
# db2ifa:DDST1 lockwaits 0
# db2ifa:DDST1 lockwaits 0
# db2ifa:DDST1 lockwaits 0
# db2ifa:DDST1 lockwaits 0
# db2ifa:DDST1 lockwaits 80


factory_settings["db2_counters_default_levels"] = {}

db2_counters_map = {
    "deadlocks"     : "Deadlocks",
    "lockwaits"     : "Lockwaits",
}

def parse_db2_counters(info):
    dbs            = {}
    timestamp      = 0
    node_infos     = []
    element_offset = {}
    for line in info:
        if line[0].startswith("TIMESTAMP"):
            element_offset = {}
            node_infos     = []
            timestamp = int(line[1])
            continue
        if line[1] == "node":
            node_infos.append(" ".join(line[2:]))

        # Some databases run in DPF mode. Means that the database is split over several nodes
        # The counter information also differs for each node. We create one service per DPF node
        if line[1] in db2_counters_map.keys():
            if node_infos:
                element_offset.setdefault(line[1], 0)
                offset = element_offset[line[1]]
                key = "%s DPF %s" % (line[0], node_infos[offset])
                element_offset[line[1]] += 1
            else:
                key = line[0]
            dbs.setdefault(key, {"TIMESTAMP": timestamp})
            dbs[key][line[1]] = line[2]

    # The timestamp is still used for legacy reasons
    # The instance specific timestamp is now available in the dbs
    return timestamp, dbs

def inventory_db2_counters(parsed):
    if len(parsed) == 2:
        for db in parsed[1]:
            yield db, {}

def check_db2_counters(item, params, parsed):
    default_timestamp = parsed[0]
    db = parsed[1].get(item)
    if not db:
        raise MKCounterWrapped("Login into database failed")

    wrapped = False
    timestamp = db.get("TIMESTAMP", default_timestamp)
    for counter, label in db2_counters_map.items():
        try:
            value = float(db[counter])
        except ValueError:
            yield 2, "Invalid value: " + db[counter]
            continue

        countername = "db2_counters.%s.%s" % (item, counter)
        try:
            rate = get_rate("db2_counters.%s.%s" % (item, counter), timestamp, value, onwrap = RAISE)
        except MKCounterWrapped:
            wrapped = True
            continue

        warn, crit = params.get(counter, (None, None))
        perfdata = [(counter, rate, warn, crit)]
        if crit != None and rate >= crit:
            yield 2, "%s: %.1f/s" % (label, rate), perfdata
        elif warn != None and rate >= warn:
            yield 1, "%s: %.1f/s" % (label, rate), perfdata
        else:
            yield 0, "%s: %.1f/s" % (label, rate), perfdata

    if wrapped:
        raise MKCounterWrapped("Some counter(s) wrapped, no data this time")

check_info['db2_counters'] = {
    "parse_function"          : parse_db2_counters,
    "service_description"     : "DB2 Counters %s",
    "check_function"          : check_db2_counters,
    "inventory_function"      : inventory_db2_counters,
    "has_perfdata"            : True,
    "group"                   : "db2_counters",
    "includes"                : ["db2.include"],
    "default_levels_variable" : "db2_counters_default_levels",
}
