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

# +------------------------------------------------------------------+
# | This file has been contributed and is copyrighted by:            |
# |                                                                  |
# | Joerg Linge 2009 <joerg.linge@pnp4nagios.org>     Copyright 2010 |
# +------------------------------------------------------------------+

# Legacy default params for services discovered before 1.6
lparstat_default_levels = {}
kernel_util_default_levels = {}


def parse_lparstat_aix(info):
    if not info:
        return {}
    if len(info) < 4:
        return {'update_required': True}

    # get system config:
    kv_pairs = (word for word in info[0] if '=' in word)
    parsed = {'system_config': dict(kv.split('=', 1) for kv in kv_pairs)}
    # from ibm.com: 'If there are two SMT threads, the row is displayed as "on."'
    if parsed['system_config'].get('smt', '').lower() == 'on':
        parsed['system_config']['smt'] = '2'

    for index, key in enumerate(info[1]):
        name = key.lstrip('%')
        uom = '%' if '%' in key else ''
        try:
            value = float(info[3][index])
        except (IndexError, ValueError):
            continue

        if name in ('user', 'sys', 'idle', 'wait'):
            parsed.setdefault('cpu', {})[name] = value
        else:
            parsed.setdefault('util', []).append((name, value, uom))

    return parsed


def inventory_lparstat(parsed):
    if parsed and parsed.get('util'):
        yield None, {}


def check_lparstat(_no_item, _no_params, parsed):
    if not parsed:
        return
    if parsed.get('update_required'):
        yield 3, "Please upgrade your AIX agent."
        return

    utilization = parsed.get('util', [])
    for name, value, uom in utilization:
        yield 0, "%s: %s%s" % (name.title(), value, uom), [(name, value)]


check_info["lparstat_aix"] = {
    'parse_function': parse_lparstat_aix,
    'check_function': check_lparstat,
    'inventory_function': inventory_lparstat,
    'service_description': 'lparstat',
    'has_perfdata': True,
}


def inventory_lparstat_aix_cpu(parsed):
    if parsed.get('update_required'):
        return [(None, {})]
    if all(k in parsed.get('cpu', {}) for k in ('user', 'sys', 'wait', 'idle')):
        return [(None, {})]


def check_lparstat_aix_cpu(_no_item, params, parsed):
    if parsed.get('update_required'):
        yield 3, "Please upgrade your AIX agent."
        return

    cpu = parsed.get('cpu', {})
    user, system, wait = cpu.get('user'), cpu.get('sys'), cpu.get('wait')
    if None in (user, system, wait):
        return

    util = user + system + wait
    # ancient legacy rule
    # and legacy None defaults before 1.6
    params = transform_cpu_iowait(params)

    values = cpu_info(['', user, 0, system, cpu.get('idle', 0), wait], caster=None)

    for util_result in check_cpu_util_unix(values, params, values_counter=False):
        yield util_result

    config = parsed.get('system_config', {})
    partition_type = config.get('type', '').lower()
    try:
        kwargs = {
            'shared': {
                'infoname': "100% corresponding to entitled processing capacity",
                'unit': "CPUs"
            },
            'dedicated': {
                'infoname': "100% corresponding to",
                'unit': "physical processors"
            },
        }[partition_type]
        cpu_entitlement = float(config['ent'])
    except (KeyError, ValueError):
        return
    yield check_levels(cpu_entitlement, 'cpu_entitlement', None, **kwargs)
    yield 0, "", [('cpu_entitlement_util', util / 100. * cpu_entitlement)]


check_info['lparstat_aix.cpu_util'] = {
    "check_function": check_lparstat_aix_cpu,
    "inventory_function": inventory_lparstat_aix_cpu,
    "service_description": "CPU utilization",
    "has_perfdata": True,
    "group": "cpu_iowait",
    "includes": ["transforms.include", "cpu_util.include"],
}
