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


winperf_cpu_default_levels = { "levels": ( 101.0, 101.0 ) }

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

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


# params: levels for warn / crit in percentage
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 = []
    for line in info[1:]:
        if line[0] in what_map:
            winperf_lines.append(line)

    if not winperf_lines:
        return

    wrapped = False
    matched = False
    for line in winperf_lines:
        if line[0] in what_map:
            matched = True
            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.
            ticks = int(line[-2])
            num_cpus = len(line) - 3
            try:
                ticks_per_sec =\
                    get_rate("winperf_util.%s" % what, this_time, ticks, onwrap = RAISE)
            except MKCounterWrapped:
                wrapped = True
                ticks_per_sec = 0
            # 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.
            #
            # 1 tick = 100ns, convert to seconds
            cpusecs_per_sec = ticks_per_sec / 10000000.0

            if what == "util":
                used_perc = 100.0 * (1 - cpusecs_per_sec)
            else:
                used_perc = 100.0 * cpusecs_per_sec

            # Due to timeing invariancies the measured level can become > 100%.
            # This makes users unhappy, so cut it off.
            if used_perc < 0:
                used_perc = 0
            elif used_perc > 100:
                used_perc = 100

            if what == "util":
                cores = []
                for i in range(num_cpus):
                    core_ticks = int(line[1 + i])
                    try:
                        core_ticks_per_sec = get_rate("winperf_util.core%d.util" % i, this_time,
                                                      core_ticks, onwrap = RAISE)
                    except MKCounterWrapped:
                        wrapped = True
                        core_ticks_per_sec = 0
                    core_cpusecs_per_sec = core_ticks_per_sec / 10000000.0
                    core_used_perc = 100.0 * (1 - core_cpusecs_per_sec)
                    # clamp percentage to the range 0-100
                    core_used_perc = min(100.0, max(0.0, core_used_perc))
                    cores.append(("core%d" % i, core_used_perc))

                if not wrapped:
                    for status, infotext, perfdata in check_cpu_util(used_perc, params,
                                                                     this_time, cores):
                        if perfdata and perfdata[0][0] == "util":
                            perfdata[0] = perfdata[0][:5] + (num_cpus,)
                        yield status, infotext, perfdata
            elif what == "user":
                yield 0, "%s perc: %.1f %%" % (what, used_perc), [(what, used_perc)]
            else: # privileged
                yield 0, "%s perc: %.1f %%" % (what, used_perc)

    if not matched:
        return

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

    yield 0, "%d CPUs" % num_cpus


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',
    'includes':                [ "cpu_util.include" ],
}
