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

brocade_mlx_states = {
    0:  (1, "Slot is empty"),
    2:  (1, "Module is going down"),
    3:  (2, "Rejected due to wrong configuration"),
    4:  (2, "Hardware is bad"),
    8:  (1, "Configured / Stacking"),
    9:  (1, "In power-up cycle"),
    10: (0, "Running"),
    11: (0, "Blocked for full height card"),
}

brocade_mlx_info = [
    ('.1.3.6.1.4.1.1991.1.1.2.2.1.1', [ 1, 2, 12, 24, 25 ]),
    # id, descr, overall status, MemoryTotal, MemoryAvailable
    ('.1.3.6.1.4.1.1991.1.1.2.11.1.1.5', [ OID_END, "" ]),
    # Rest of OId starting with module ID, CpuUtilPercent
]

def brocade_mlx_get_state(state):
    return brocade_mlx_states.get(state, (3, 'Unhandled state - %d' % state))

def brocade_mlx_scan(oid):
    return oid(".1.3.6.1.2.1.1.2.0").startswith(".1.3.6.1.4.1.1991.1.")

def brocade_mlx_combine_item(id, descr):
    if descr == "":
        return id
    else:
        descr = re.sub(" *Module", "", descr)
        return "%s %s" % (id, descr)

#   .--Overall Status------------------------------------------------------.
#   |     ___                      _ _   ____  _        _                  |
#   |    / _ \__   _____ _ __ __ _| | | / ___|| |_ __ _| |_ _   _ ___      |
#   |   | | | \ \ / / _ \ '__/ _` | | | \___ \| __/ _` | __| | | / __|     |
#   |   | |_| |\ V /  __/ | | (_| | | |  ___) | || (_| | |_| |_| \__ \     |
#   |    \___/  \_/ \___|_|  \__,_|_|_| |____/ \__\__,_|\__|\__,_|___/     |
#   |                                                                      |
#   +----------------------------------------------------------------------+

def inventory_brocade_mlx_module(info):
    inventory = []
    for module_id, module_descr, module_state, mem_total, mem_avail in info[0]:
        # do not inventorize modules reported as empty
        if module_state != "0":
            inventory.append( (brocade_mlx_combine_item(module_id, module_descr), None) )
    return inventory

def check_brocade_mlx_module(item, _no_params, info):
    for module_id, module_descr, module_state, mem_total, mem_avail in info[0]:
        if brocade_mlx_combine_item(module_id, module_descr) == item:
            return brocade_mlx_get_state(int(module_state))
    return 3, "Module not found"

check_info["brocade_mlx.module_status"] = {
    "check_function"        : check_brocade_mlx_module,
    "inventory_function"    : inventory_brocade_mlx_module,
    "service_description"   : "Status Module %s",
    "snmp_info"             : brocade_mlx_info,
    "snmp_scan_function"    : brocade_mlx_scan,
    "has_perfdata"          : False,
}

#.
#   .--Memory--------------------------------------------------------------.
#   |               __  __                                                 |
#   |              |  \/  | ___ _ __ ___   ___  _ __ _   _                 |
#   |              | |\/| |/ _ \ '_ ` _ \ / _ \| '__| | | |                |
#   |              | |  | |  __/ | | | | | (_) | |  | |_| |                |
#   |              |_|  |_|\___|_| |_| |_|\___/|_|   \__, |                |
#   |                                                |___/                 |
#   +----------------------------------------------------------------------+

brocade_mlx_mem_default_levels = { "levels": (80.0, 90.0) }

def inventory_brocade_mlx_module_mem(info):
    inventory = []
    for module_id, module_descr, module_state, mem_total, mem_avail in info[0]:
        # do not inventorize modules reported as empty or "Blocked for full height card"
        # and: monitor cpu only on NI-MLX and BR-MLX modules
        if module_state != "0" and module_state != "11" and ( module_descr.startswith("NI-MLX") or module_descr.startswith("BR-MLX") ):
            inventory.append( (brocade_mlx_combine_item(module_id, module_descr), "brocade_mlx_mem_default_levels") )
    return inventory

def check_brocade_mlx_module_mem(item, params, info):
    warn, crit = params["levels"]
    for module_id, module_descr, module_state, mem_total, mem_avail in info[0]:
        module_state = int(module_state)
        if brocade_mlx_combine_item(module_id, module_descr) == item:
            if module_state != 10:
                return 3, "Module is not running (Current State: %s)" % brocade_mlx_get_state(module_state)[1]

            mem_avail = saveint(mem_avail)
            mem_total = saveint(mem_total)
            mem_used  = mem_total - mem_avail
            mem_used_percent = savefloat(mem_used) / savefloat(mem_total) * 100

            if type(warn) is int:
                warn_absolut = warn
            else:
                warn_absolut = int(mem_total * warn / 100)

            if type(crit) is int:
                crit_absolut = crit
            else:
                crit_absolut = int(mem_total * crit / 100)

            perfdata = [ ('memused', str(mem_used) + 'Bytes', warn_absolut, crit_absolut, 0, mem_total) ]

            status = 0
            if mem_used > warn_absolut:
                status = 1
            if mem_used > crit_absolut:
                status = 2

            return status, "%s used (%0.1f%%) of total %s" % \
                (get_bytes_human_readable(mem_used), mem_used_percent, \
                get_bytes_human_readable(mem_total)), perfdata

    return 3, "Module not found"

check_info["brocade_mlx.module_mem"] = {
    "check_function"        : check_brocade_mlx_module_mem,
    "inventory_function"    : inventory_brocade_mlx_module_mem,
    "service_description"   : "Memory Module %s",
    "snmp_info"             : brocade_mlx_info,
    "snmp_scan_function"    : brocade_mlx_scan,
    "has_perfdata"          : True,
    "group"                 : "memory_multiitem",
}

#.
#   .--CPU-----------------------------------------------------------------.
#   |                           ____ ____  _   _                           |
#   |                          / ___|  _ \| | | |                          |
#   |                         | |   | |_) | | | |                          |
#   |                         | |___|  __/| |_| |                          |
#   |                          \____|_|    \___/                           |
#   |                                                                      |
#   +----------------------------------------------------------------------+

brocade_mlx_cpu_default_levels = { "levels" : (80.0, 90.0) }

def inventory_brocade_mlx_module_cpu(info):
    inventory = []
    for module_id, module_descr, module_state, mem_total, mem_avail in info[0]:
        # do not inventorize modules reported as empty or "Blocked for full height card"
        # and: monitor cpu only on NI-MLX and BR-MLX modules
        if module_state != "0" and module_state != "11" and ( module_descr.startswith("NI-MLX") or module_descr.startswith("BR-MLX") ):
            inventory.append( (brocade_mlx_combine_item(module_id, module_descr), "brocade_mlx_cpu_default_levels") )
    return inventory

def check_brocade_mlx_module_cpu(item, params, info):
    warn, crit = params["levels"]
    for module_id, module_descr, module_state, mem_total, mem_avail in info[0]:
        if brocade_mlx_combine_item(module_id, module_descr) == item:
            if module_state != "10":
                return 3, "Module is not in state running"

            cpu_util1 = ""
            cpu_util5 = ""
            cpu_util60 = ""
            cpu_util300 = ""
            for oid_end, cpu_util in info[1]:
                if oid_end == "%s.1.1" % module_id:
                    cpu_util1 = saveint(cpu_util)
                if oid_end == "%s.1.5" % module_id:
                    cpu_util5 = saveint(cpu_util)
                if oid_end == "%s.1.60" % module_id:
                    cpu_util60 = saveint(cpu_util)
                if oid_end == "%s.1.300" % module_id:
                    cpu_util300 = saveint(cpu_util)

            if cpu_util1 == "" or cpu_util5 == "" or cpu_util60 == "" or cpu_util300 == "":
                return 3, "did not find all cpu utilization values in snmp output"

            perfdata = [ ('cpu_util1',   str(cpu_util1)   + '%', '',   '',   0, 100),
                         ('cpu_util5',   str(cpu_util5)   + '%', '',   '',   0, 100),
                         ('cpu_util60',  str(cpu_util60)  + '%', warn, crit, 0, 100),
                         ('cpu_util300', str(cpu_util300) + '%', '',   '',   0, 100),
                       ]

            status = 0
            errorstring = ""
            if cpu_util60 > warn:
                status = 1
                errorstring = "(!)"
            if cpu_util60 > crit:
                status = 2
                errorstring = "(!!)"

            return status, "CPU utilization was %s/%s/%s%s/%s%% for the last 1/5/60/300 sec" % \
                (cpu_util1, cpu_util5, cpu_util60, errorstring, cpu_util300), perfdata

    return 3, "Module not found"

check_info["brocade_mlx.module_cpu"] = {
    "check_function"        : check_brocade_mlx_module_cpu,
    "inventory_function"    : inventory_brocade_mlx_module_cpu,
    "service_description"   : "CPU utilization Module %s",
    "snmp_info"             : brocade_mlx_info,
    "snmp_scan_function"    : brocade_mlx_scan,
    "has_perfdata"          : True,
    "group"                 : "cpu_utilization_multiitem",
}

