#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (C) 2019 tribe29 GmbH - License: GNU General Public License v2
# This file is part of Checkmk (https://checkmk.com). It is subject to the terms and
# conditions defined in the file COPYING, which is part of this source code package.

# NOTE: Careful when replacing the *-import below with a more specific import. This can cause
# problems because it might remove variables from the check-context which are necessary for
# resolving legacy discovery results such as [("SUMMARY", "diskstat_default_levels")]. Furthermore,
# it might also remove variables needed for accessing discovery rulesets.
from cmk.base.check_legacy_includes.db2 import *  # pylint: disable=wildcard-import,unused-wildcard-import

# <<<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])
        elif 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
        elif line[1] in db2_counters_map:
            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

        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 is not None and rate >= crit:
            yield 2, "%s: %.1f/s" % (label, rate), perfdata
        elif warn is not 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",
    "default_levels_variable": "db2_counters_default_levels",
}
