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

# Example output from agent:
# <<<ibm_svc_mdiskgrp:sep(58)>>>
# 0:Quorum_2:online:1:0:704.00MB:64:704.00MB:0.00MB:0.00MB:0.00MB:0:0:auto:inactive:no:0.00MB:0.00MB:0.00MB
# 1:stp5_450G_03:online:18:6:29.43TB:256:21.68TB:8.78TB:7.73TB:7.75TB:29:80:auto:inactive:no:0.00MB:0.00MB:0.00MB
# 4:stp5_450G_02:online:15:14:24.53TB:256:277.00GB:24.26TB:24.26TB:24.26TB:98:80:auto:inactive:no:0.00MB:0.00MB:0.00MB
# 9:stp6_450G_03:online:18:6:29.43TB:256:21.68TB:8.78TB:7.73TB:7.75TB:29:80:auto:inactive:no:0.00MB:0.00MB:0.00MB
# 10:stp6_450G_02:online:15:14:24.53TB:256:277.00GB:24.26TB:24.26TB:24.26TB:98:80:auto:inactive:no:0.00MB:0.00MB:0.00MB
# 15:stp6_300G_01:online:15:23:16.34TB:256:472.50GB:15.88TB:15.88TB:15.88TB:97:80:auto:inactive:no:0.00MB:0.00MB:0.00MB
# 16:stp5_300G_01:online:15:23:16.34TB:256:472.50GB:15.88TB:15.88TB:15.88TB:97:80:auto:inactive:no:0.00MB:0.00MB:0.00MB
# 17:Quorum_1:online:1:0:512.00MB:256:512.00MB:0.00MB:0.00MB:0.00MB:0:80:auto:inactive:no:0.00MB:0.00MB:0.00MB
# 18:Quorum_0:online:1:0:512.00MB:256:512.00MB:0.00MB:0.00MB:0.00MB:0:80:auto:inactive:no:0.00MB:0.00MB:0.00MB
# 21:stp5_450G_01:online:12:31:19.62TB:256:320.00GB:19.31TB:19.31TB:19.31TB:98:0:auto:inactive:no:0.00MB:0.00MB:0.00MB
# 22:stp6_450G_01:online:12:31:19.62TB:256:320.00GB:19.31TB:19.31TB:19.31TB:98:0:auto:inactive:no:0.00MB:0.00MB:0.00MB
# 23:stp5_600G_01:online:3:2:6.54TB:256:512.00MB:6.54TB:6.54TB:6.54TB:99:80:auto:inactive:no:0.00MB:0.00MB:0.00MB
# 24:stp6_600G_01:online:3:2:6.54TB:256:512.00MB:6.54TB:6.54TB:6.54TB:99:80:auto:inactive:no:0.00MB:0.00MB:0.00MB


def ibm_svc_mdiskgrp_to_mb(size):
    if size.endswith("MB"):
        size = float(size.replace("MB", ""))
    elif size.endswith("GB"):
        size = float(size.replace("GB", "")) * 1024
    elif size.endswith("TB"):
        size = float(size.replace("TB", "")) * 1024 * 1024
    elif size.endswith("PB"):
        size = float(size.replace("PB", "")) * 1024 * 1024 * 1024
    elif size.endswith("EB"):
        size = float(size.replace("EB", "")) * 1024 * 1024 * 1024 * 1024
    else:
        size = float(size)
    return size


def parse_ibm_svc_mdiskgrp(info):
    dflt_header = [
        u'id',
        u'name',
        u'status',
        u'mdisk_count',
        u'vdisk_count',
        u'capacity',
        u'extent_size',
        u'free_capacity',
        u'virtual_capacity',
        u'used_capacity',
        u'real_capacity',
        u'overallocation',
        u'warning',
        u'easy_tier',
        u'easy_tier_status',
        u'compression_active',
        u'compression_virtual_capacity',
        u'compression_compressed_capacity',
        u'compression_uncompressed_capacity',
        u'parent_mdisk_grp_id',
        u'parent_mdisk_grp_name',
        u'child_mdisk_grp_count',
        u'child_mdisk_grp_capacity',
        u'type',
        u'encrypt',
        u'owner_type',
        u'site_id',
        u'site_name',
    ]
    parsed = {}
    for rows in parse_ibm_svc_with_header(info, dflt_header).itervalues():
        try:
            data = rows[0]
        except IndexError:
            continue
        parsed.setdefault(data['name'], data)
    return parsed


def inventory_ibm_svc_mdiskgrp(parsed):
    for mdisk_name in parsed.iterkeys():
        yield mdisk_name, {}


@get_parsed_item_data
def check_ibm_svc_mdiskgrp(item, params, data):
    mgrp_status = data['status']

    if mgrp_status != "online":
        yield 2, "Status: %s" % mgrp_status
        return

    fslist = []

    # Names of the fields are a bit confusing and not what you would
    # expect.

    # 1. Physical size of the pool
    capacity = ibm_svc_mdiskgrp_to_mb(data['capacity'])

    # 2. Part of that that is physically in use
    real_capacity = ibm_svc_mdiskgrp_to_mb(data['real_capacity'])

    # 3. Provisioned space - can be more than physical size
    virtual_capacity = ibm_svc_mdiskgrp_to_mb(data['virtual_capacity'])

    # Compute available (do not use free_capacity, it's something different)
    avail_mb = capacity - real_capacity

    fslist.append((item, capacity, avail_mb, 0))
    status, message, perfdata = df_check_filesystem_list(item, params, fslist)
    yield status, message, perfdata

    mb = 1024 * 1024

    # Compute provisioning
    if not capacity:
        return  # provisioning does not make sense when capacity is 0

    provisioning = 100.0 * virtual_capacity / capacity
    infotext = "Provisioning: %s" % get_percent_human_readable(provisioning)
    state = 0
    if "provisioning_levels" in params:
        warn, crit = params["provisioning_levels"]
        if provisioning >= crit:
            state = 2
        elif provisioning >= warn:
            state = 1
        if state:
            infotext += " (warn/crit at %s/%s)" % (get_percent_human_readable(warn),
                                                   get_percent_human_readable(crit))
        warn_mb = capacity * mb * warn / 100
        crit_mb = capacity * mb * crit / 100
    else:
        warn_mb = None
        crit_mb = None

    # Note: Performance data is now (with new metric system) normed to
    # canonical units - i.e. 1 byte in this case.
    yield state, infotext, [("fs_provisioning", virtual_capacity * mb, warn_mb, crit_mb, 0,
                             capacity * mb)]


check_info["ibm_svc_mdiskgrp"] = {
    "parse_function": parse_ibm_svc_mdiskgrp,
    "check_function": check_ibm_svc_mdiskgrp,
    "inventory_function": inventory_ibm_svc_mdiskgrp,
    "service_description": "Pool Capacity %s",
    "has_perfdata": True,
    "group": "ibm_svc_mdiskgrp",
    "includes": ["ibm_svc.include", "size_trend.include", "df.include"],
    "default_levels_variable": "filesystem_default_levels",
}
