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


def inventory_winperf_util(info):
    if len(info) <= 1:
        return None

    for line in info[1:]:
        try:
            if line[0] == '-232':
                return [(None, {})]
        except IndexError:
            pass


def _clamp_percentage(value):
    '''clamp percentage to the range 0-100

    Due to timing invariancies the measured level can become > 100%.
    This makes users unhappy, so cut it off.
    '''
    return min(100.0, max(0.0, value))


def _get_secs_per_sec(raw_value, key, this_time, wrapped):
    ticks = int(raw_value)
    try:
        ticks_per_sec =\
            get_rate("winperf_util.%s" % key, this_time, ticks, onwrap=RAISE)
    except MKCounterWrapped:
        return True, 0.0
    # 1 tick = 100ns, convert to seconds
    return wrapped, ticks_per_sec / 10000000.0


def check_winperf_util(_no_item, params, info):
    if not info:
        return

    this_time = int(float(info[0][0]))

    what_map = {"-232": "util", "-96": "user", "-94": "privileged"}

    winperf_lines = [l for l in info[1:] if l[0] in what_map]
    if not winperf_lines:
        return

    wrapped = False
    for line in winperf_lines:

        what = what_map[line[0]]
        # Windows sends one counter for each CPU plus one counter that
        # sums up to total (called _Total). We only need that last value.
        wrapped, cpusecs_per_sec = _get_secs_per_sec(line[-2], what, this_time, wrapped)

        # We get the value of the PERF_100NSEC_TIMER_INV here.
        # This counter type shows the average percentage of active time observed
        # during the sample interval. This is an inverse counter. Counters of this
        # type calculate active time by measuring the time that the service was
        # inactive and then subtracting the percentage of active time from 100 percent.
        if what == "util":
            used_perc = _clamp_percentage(100.0 * (1 - cpusecs_per_sec))
            cores = []
            for i, raw_core_ticks in enumerate(line[1:-2]):
                wrapped, core_cpusecs_per_sec = _get_secs_per_sec(raw_core_ticks, "core%d.util" % i,
                                                                  this_time, wrapped)
                core_used_perc = _clamp_percentage(100.0 * (1 - core_cpusecs_per_sec))
                cores.append(("core%d" % i, core_used_perc))

            if not wrapped:
                for subresult in check_cpu_util(used_perc, params, this_time, cores):
                    if len(subresult) == 3 and subresult[2]:
                        perf = subresult[2]
                        if perf[0][0] == "util":
                            perf[0] = perf[0][:5] + (len(cores),)
                    yield subresult

        elif what == "user":
            used_perc = _clamp_percentage(100.0 * cpusecs_per_sec)
            yield 0, "%s perc: %.1f %%" % (what, used_perc), [(what, used_perc)]
        else:  # privileged
            used_perc = _clamp_percentage(100.0 * cpusecs_per_sec)
            yield 0, "%s perc: %.1f %%" % (what, used_perc)

    if wrapped:
        # all counters initialized, NOW we can raise the exception
        raise MKCounterWrapped("Counter wrap, skipping checks this time")

    try:
        yield 0, "%d CPUs" % len(cores)
    except NameError:
        pass


check_info["winperf_processor.util"] = {
    'check_function': check_winperf_util,
    'inventory_function': inventory_winperf_util,
    'service_description': 'CPU utilization',
    'has_perfdata': True,
    'handle_real_time_checks': True,
    'group': 'cpu_utilization_os',
    'default_levels_variable': 'winperf_cpu_default_levels',
    'includes': ["cpu_util.include", "winperf.include"],
}
