#!/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.diskstat import *  # pylint: disable=wildcard-import,unused-wildcard-import


def parse_emc_vplex_volumes(info):
    volumes = {}
    now = time.time()

    # Each volume is listed twice, because they are connected to both directors
    instance_count = {}
    for line in info:
        # Note: Since the volume name can appear multiple times we need an instance
        # counter for each volume. Let's hope they always appear in the same order...
        name = line[0]
        instance_count.setdefault(name, 0)
        instance_count[name] += 1
        read_delta = get_rate("readbytes.%s.%s" % (name, instance_count[name]), now, int(line[3]))
        write_delta = get_rate("writebytes.%s.%s" % (name, instance_count[name]), now, int(line[4]))
        ios = get_rate("ios.%s.%s" % (name, instance_count[name]), now, int(line[2]))
        read_wait = float(line[5]) / 1000000
        write_wait = float(line[6]) / 1000000

        if name in volumes:
            volumes[name]["read_throughput"] += read_delta
            volumes[name]["write_throughput"] += write_delta
            volumes[name]["ios"] += ios
            volumes[name]["average_read_wait"] = max(volumes[name]["average_read_wait"], read_wait)
            volumes[name]["average_write_wait"] = max(volumes[name]["average_write_wait"],
                                                      write_wait)
        else:
            volumes[name] = {
                "average_read_wait": read_wait,
                "average_write_wait": write_wait,
                "read_throughput": read_delta,
                "write_throughput": write_delta,
                "ios": ios
            }

    return volumes


def inventory_emc_vplex_volumes(parsed):
    return inventory_diskstat_generic([(None, x) for x in parsed])


def check_emc_vplex_volumes(item, params, parsed):
    # The check_diskstat_dict function may compute average values
    # We won't allow this if some of the counters have wrapped
    if last_counter_wrap():
        raise MKCounterWrapped("Value overflow")
    return check_diskstat_dict(item, params, parsed)

check_info["emc_vplex_volumes"] = {
    "parse_function"        : parse_emc_vplex_volumes,
    "check_function"        : check_emc_vplex_volumes,
    "inventory_function"    : inventory_emc_vplex_volumes,
    "service_description"   : "Disk IO Volume %s",
    "snmp_scan_function"    : lambda oid: oid(".1.3.6.1.2.1.1.1.0") == "" and\
                                          oid(".1.3.6.1.4.1.1139.21.2.2.8.1.*"),
    "snmp_info"             :
                                (".1.3.6.1.4.1.1139.21.2.2.8.1", [
                                    1, # vplexDirectorVirtualVolumeName
                                    2, # vplexDirectorVirtualVolumeUuid
                                    3, # vplexDirectorVirtualVolumeOps
                                    4, # vplexDirectorVirtualVolumeRead
                                    5, # vplexDirectorVirtualVolumeWrite
                                    6, # vplexDirectorVirtualVolumeReadAvgLatency
                                    7, # vplexDirectorVirtualVolumeWriteAvgLatency
                                ]),
    "has_perfdata"          : True,
    "group"                 : "diskstat",
}
