#!/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_win_cpuusage(info):
    for line in info:
        try:
            if line[0] == '238:6':
                return [(None, None, "winperf_cpu_default_levels")]
        except:
            pass

winperf_cpu_default_levels = ( 101, 101 )

# params: levels for warn / crit in percentage
def check_win_cpuusage(item, params, info):
    # get parameters. Be nice to older installations that still use 'None'
    # as parameters
    if params == None:
        params = winperf_cpu_default_levels # for legacy reasons
    elif type(params) == tuple:
        warn, crit = params
    else:
        warn, crit = params['levels']

    for line in info:
        if line[0] == '238:6':
            this_time = int(float(line[1]))
            # Windows sends one counter for each CPU plus one counter that
            # I've forgotton what's it for (idle?)
            num_cpus = len(line) - 4
            overall_perc = 0
            for cpu in range(0, num_cpus):
                ticks = int(line[2 + cpu])
                ticks_per_sec = get_rate("cpuusage.%d" % cpu, this_time, ticks)
                secs_per_sec = ticks_per_sec / 10000000.0;
                used_perc = 100 * (1 - secs_per_sec)
                overall_perc += used_perc

            used_perc = overall_perc / num_cpus

            if used_perc < 0:
                used_perc = 0
            elif used_perc > 100:
                used_perc = 100
            perfdata = [ ("cpuusage", "%.2f" % used_perc, '', '', 0, 100) ]
            if num_cpus == 1:
                num_txt = ""
            else:
                num_txt = " / %d CPUs" % num_cpus

            infotext = "%d%% used%s" % (int(used_perc), num_txt)

            if used_perc >= crit:
                return (2, infotext, perfdata)
            elif used_perc >= warn:
                return (1, infotext, perfdata)
            else:
                return (0, infotext, perfdata)

    return (3, "counter for cpu (238:6) not found")

def inventory_win_diskstat(info):
    for line in info:
        try:
            if line[0] == '2:16' or line[0] == '2:18':
                return [(None, None, None)]
        except:
            pass
    return []


def check_win_diskstat(item, params, info):
    read_bytes_ctr = 0
    write_bytes_ctr = 0
    for line in info:
        if line[0] == '2:16':
            read_bytes_ctr = int(line[2])
        elif line[0] == '2:18':
            write_bytes_ctr = int(line[2])
            break
    this_time = int(float(line[1]))

    try:
        read_per_sec  = get_rate("diskstat.read",  this_time, read_bytes_ctr)
        write_per_sec = get_rate("diskstat.write", this_time, write_bytes_ctr)
    except MKCounterWrapped, e:
        # make sure that inital check does not need three cycles for all counters
        # to be initialized
        get_rate("diskstat.write", this_time, write_bytes_ctr)
        raise e

    perfdata = [ ("read", "%dc" % read_bytes_ctr),
                 ("write", "%dc" % write_bytes_ctr) ]
    return (0, "reading %.1f MB/s, writing %.1f MB/s" %
            (read_per_sec / 1048576, write_per_sec / 1048576), perfdata)


check_config_variables.append("winperf_cpu_default_levels")

check_info["winperf.cpuusage"] = {
    'check_function':          check_win_cpuusage,
    'inventory_function':      inventory_win_cpuusage,
    'service_description':     'CPU Usage',
    'has_perfdata':            True,
}

check_info["winperf.diskstat"] = {
    'check_function':          check_win_diskstat,
    'inventory_function':      inventory_win_diskstat,
    'service_description':     'Disk IO',
    'has_perfdata':            True,
}
