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

# <<<netapp_api_volumes:sep(9)>>>
# volume vol0 size-available 556613632    state online    files-total 25876   files-used 8646 size-total 848203776    fcp_write_data 0    fcp_read_data 0cifs_write_data 0    iscsi_read_latency 0    iscsi_write_data 0  read_data 201265528798  nfs_write_latency 977623886 san_write_latency 0 san_write_data 0read_latency 1529821621 cifs_read_latency 0 fcp_write_latency 0 fcp_read_latency 0  iscsi_write_latency 0   nfs_read_latency 1491050012 iscsi_read_data 0   instance_name vol0  cifs_read_data 0    nfs_read_data 197072260981  write_latency 1528780977    san_read_data 0 san_read_latency 0  write_data 13926719804  nfs_write_data 2789744628   cifs_write_latency 0

def parse_netapp_api_volumes(info):
    volumes = {}
    for line in info:
        volume = {}
        name = line[0].split(" ", 1)[1]
        for element in line[1:]:
            tokens = element.split(" ", 1)
            volume[tokens[0]] = tokens[1]

        # Clustermode specific
        if "node" in volume:
            # There are cluster volumes and volumes which only exist on the node.
            if "msid" not in volume:
                name = "%s.%s" % (volume["node"], volume["name"])
            else:
                name = volume["name"]

        volumes[name] = volume

    return volumes

def inventory_netapp_api_volumes(parsed):
    for volume in parsed.keys():
        yield volume, {}

def check_netapp_api_volumes(item, params, parsed):
    volume = parsed.get(item)

    if not volume:
        return 3, "Volume not found in agent output"

    if volume.get("state") != "online":
        return 1, "Volume is %s" % volume.get("state")

    mega = 1024.0 * 1024.0
    size_total = int(volume.get("size-total")) / mega
    size_avail = int(volume.get("size-available")) / mega
    inodes_total = int(volume.get("files-total"))
    inodes_avail = inodes_total - int(volume.get("files-used"))
    state, info, perf = df_check_filesystem_single(g_hostname, item, size_total, size_avail, 0,
                                                   inodes_total, inodes_avail, params)

    counter_wrapped = False
    counters        = []
    now = time.time()

    perf_protocols = params.get("perfdata", [])
    for protocol in ["", "nfs_", "cifs_", "san_", "fcp_", "iscsi_"]:
        if protocol[:-1] not in perf_protocols:
            continue
        for mode in ["read_", "write_", "other_"]:
            for field, factor, format_text in [ ("data", None, None), ("latency", 10000.0, "%s: %.2f ms")]:
                key = protocol + mode + field
                value = volume.get(key)
                if value != None:
                    value = int(value)
                    try:
                        delta = get_rate("netapp_api_volumes.%s.%s" % (item, key), now, value, onwrap=RAISE)
                        perf.append( (key, delta) )

                        if protocol == "" and mode in ["read_", "write_"]:
                            if factor:
                                delta = delta / factor
                            if format_text:
                                counters.append(format_text % (key, delta))
                            else:
                                counters.append("%s: %s" % (key, get_bytes_human_readable(delta)))
                    except MKCounterWrapped:
                        counter_wrapped = True

    if not counter_wrapped:
        info += ", " +  ", ".join(counters)

    return state, info, perf

check_info["netapp_api_volumes"] = {
    'check_function'          : check_netapp_api_volumes,
    'inventory_function'      : inventory_netapp_api_volumes,
    'parse_function'          : parse_netapp_api_volumes,
    'service_description'     : 'Volume %s',
    'has_perfdata'            : True,
    'group'                   : "netapp_volumes",
    'includes'                : [ "df.include", "netapp_api.include" ],
    "default_levels_variable" : "filesystem_default_levels",
}
