#!/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 asmcmd lsdg:
# State    Type    Rebal  Sector  Block       AU  Total_MB  Free_MB  Req_mir_free_MB  Usable_file_MB  Offline_disks  Voting_files  Name
# MOUNTED  NORMAL  N         512   4096  1048576    512000    92888                0           46444              0             N  DATA/
# MOUNTED  NORMAL  N         512   4096  1048576      3072     2146              309             918              0             Y  OCR_VOTE/
# DISMOUNTED  N 0 0 0 0 0 0 0 0 N DB_DG1/
# DISMOUNTED  N 0 4096 0 0 0 0 0 0 N ABC/
# MOUNTED EXTERN N 512 4096 1048576 2047984 163379 0 163379 0 N XYZ/
# MOUNTED EXTERN N 512 4096 1048576 307092 291710 0 291710 0 N HUHU/
# DISMOUNTED  N 0 4096 0 0 0 0 0 0 N FOO/
# DISMOUNTED  N 0 4096 0 0 0 0 0 0 N BAR/

# The agent section <<<oracle_asm_diskgroup>>> does not output the header line


factory_settings["asm_diskgroup_default_levels"] = {
    "levels"          : (80.0, 90.0), # warn/crit in percent
    "magic_normsize"  : 20,       # Standard size if 20 GB
    "levels_low"      : (50.0, 60.0), # Never move warn level below 50% due to magic factor
    "trend_range"     : 24,
    "trend_perfdata"  : True,    # do send performance data for trends
    "req_mir_free"    : False,   # Ignore Requirre mirror free space in DG
}


def parse_oracle_asm_diskgroup(info):
    parsed = {}
    for line in info:
        diskstate = line[0]
        if diskstate == "DISMOUNTED":
            disktype     = None
            index        = 1

        elif diskstate == "MOUNTED":
            disktype     = line[1]
            index        = 2

        else:
            continue

        stripped_line = line[index:]

        if len(stripped_line) == 10:
            rebal, sector, block, au, total_mb, free_mb, req_mir_free_mb, \
                usable_file_mb, offline_disks, diskname = stripped_line
            voting_files = "N"

        elif len(stripped_line) == 11:
            rebal, sector, block, au, total_mb, free_mb, req_mir_free_mb, \
                usable_file_mb, offline_disks, voting_files, diskname = stripped_line

        else:
            continue

        parsed.setdefault(diskname.rstrip("/"), {
            "diskstate"       : diskstate,
            "disktype"        : disktype,
            "rebal"           : rebal,
            "sector"          : sector,
            "block"           : block,
            "au"              : au,
            "total_mb"        : total_mb,
            "free_mb"         : free_mb,
            "req_mir_free_mb" : req_mir_free_mb,
            "usable_file_mb"  : usable_file_mb,
            "offline_disks"   : offline_disks,
            "voting_files"    : voting_files,
        })

    return parsed


def inventory_oracle_asm_diskgroup(parsed):
    for asm_diskgroup_name, attrs in parsed.items():
        if attrs["diskstate"] in [ "MOUNTED", "DISMOUNTED" ]:
            yield asm_diskgroup_name, {}


def check_oracle_asm_diskgroup(item, params, parsed):
    if item in parsed:
        data = parsed[item]
        diskstate       = data["diskstate"]
        disktype        = data["disktype"]
        block           = data["block"]
        total_mb        = data["total_mb"]
        free_mb         = data["free_mb"]
        req_mir_free_mb = data["req_mir_free_mb"]
        offline_disks   = data["offline_disks"]
        voting_files    = data["voting_files"]

        if diskstate == "DISMOUNTED" and block == "0":
            return 2, "Disk dismounted"

        add_text = ""
        if disktype in ('NORMAL', 'HIGH'):
            if disktype == 'NORMAL':
                if voting_files == 'Y':
                    # NORMAL Redundancy Disk-Groups with Voting requires 3 Failgroups
                    dg_factor = 3
                else:
                    dg_factor = 2

            elif disktype == 'HIGH':
                if voting_files == 'Y':
                    # HIGH Redundancy Disk-Groups with Voting requires 5 Failgroups
                    dg_factor = 5
                else:
                    dg_factor = 3

            total_mb = int(total_mb)/dg_factor
            free_space_mb = int(free_mb)/dg_factor

            if params.get('req_mir_free'):
                req_mir_free_mb = int(req_mir_free_mb)
                if req_mir_free_mb < 0:
                    # requirred mirror free space could be negative!
                    req_mir_free_mb = 0

                free_space_mb = int(req_mir_free_mb)
                add_text = ', required mirror free space used'

        else:
            # EXTERNAL Redundancy
            free_space_mb = int(free_mb)

        status, infotext, perfdata = df_check_filesystem(g_hostname, item, int(total_mb),
                                                         free_space_mb, 0, params)
        if disktype is not None:
            infotext += ', %s redundancy' % disktype.lower()
        infotext += add_text

        offline_disks = int(offline_disks)
        if offline_disks > 0:
            status = max(2, status)
            infotext += ', %d Offline disks found(!!)' % offline_disks

        return status, infotext, perfdata

    # In case of missing information we assume that the ASM-Instance is
    # checked at a later time.
    # This reduce false notifications for not running ASM-Instances
    raise MKCounterWrapped("Diskgroup %s not found" % item)


check_info["oracle_asm_diskgroup"] = {
    'parse_function'          : parse_oracle_asm_diskgroup,
    'inventory_function'      : inventory_oracle_asm_diskgroup,
    'check_function'          : check_oracle_asm_diskgroup,
    'service_description'     : 'ASM Diskgroup %s',
    'has_perfdata'            : True,
    'group'                   : 'asm_diskgroup',
    'default_levels_variable' : 'asm_diskgroup_default_levels',
    "includes"                : [ "df.include" ],
}
