#!/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/
# 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 inventory_oracle_asm_diskgroup(info):
    return [ (line[-1].rstrip("/"), {}) for line in info
             if len(line) in [ 12, 13 ] and line[0] in [ "MOUNTED", "DISMOUNTED" ] ]

def check_oracle_asm_diskgroup(item, params, info):
    for line in info:
        voting_files = 'N'

        if len(line) == 13:
            state, typ, rebal, sector, block, au, total_mb,  \
                free_mb, req_mir_free_mb, usable_file_mb, offline_disks, \
                voting_files, name = line
        elif len(line) == 12:
            state, typ, rebal, sector, block, au, total_mb,  \
                free_mb, req_mir_free_mb, usable_file_mb, offline_disks, \
                name = line
        else:
            continue # Invalid data, skip this line

        if state not in [ "MOUNTED", "DISMOUNTED" ]:
            continue # Invalid data, skip this line

        dg_name = name.rstrip('/')

        if dg_name == item:

            # Indices are wrong: TYPE missing, only critical if block==0 (T.Bruhns)
            if state == "DISMOUNTED" and line[3] == "0":
                return 2, "Disk dismounted"

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

                elif typ == '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)

            infotext += ', %s redundancy' % typ.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"] = {
    'check_function'          : check_oracle_asm_diskgroup,
    'inventory_function'      : inventory_oracle_asm_diskgroup,
    'service_description'     : 'ASM Diskgroup %s',
    'has_perfdata'            : True,
    'group'                   : 'asm_diskgroup',
    'default_levels_variable' : 'asm_diskgroup_default_levels',
    "includes"                : [ "df.include" ],
}
