#!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# |          _           _           _       _   __   _______        |
# |       __| |_  ___ __| |__  _ __ | |__   / | /  \ |__ / _ \       |
# |      / _| ' \/ -_) _| / / | '  \| / /   | || () | |_ \_, /       |
# |      \__|_||_\___\__|_\_\_|_|_|_|_\_\   |_(_)__(_)___//_/        |
# |                                            check_mk 1.0.39       |
# |                                                                  |
# | Copyright Mathias Kettner 2009                mk@mathias-kettner |
# +------------------------------------------------------------------+
# 
# This file is part of check_mk 1.0.39.
# 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-
# ails.  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 check_statgrab_util(item, params, info):
    global g_counters
    user = 0
    try:
        for var, value in info:
            if var == 'iowait':
                wait = int(value)
            elif var == 'kernel':
                system = int(value)
            elif var == 'nice' or var == 'user':
                user += int(value)
            elif var == 'total':
                total = int(value)
    except:
        return (3, "UNKNOWN - invalid output from plugin")

    values = [ user, system, wait, total ]
    this_time = int(time.time())
    diff_values = [ ]
    n = 0
    for v in values:
        n += 1
        countername = "cpu.util.%d" % n
        last_time, last_val = g_counters.get(countername, (0, 0))
        diff_values.append(v - last_val)
        g_counters[countername] = (this_time, v)
        
    diff_total = diff_values[3]
    if diff_total == 0:
        return (0, "OK - too short interval")
    user_perc   = 100.0 * float(diff_values[0]) / float(diff_total)
    system_perc = 100.0 * float(diff_values[1]) / float(diff_total)
    wait_perc   = 100.0 * float(diff_values[2]) / float(diff_total)
    perfdata = [ 
          ( "user",   "%.3f" % user_perc ), 
          ( "system", "%.3f" % system_perc ), 
          ( "wait",   "%.3f" % wait_perc ) ]
    return (0, "OK - user: %2.0f%%, system: %2.0f%%, wait: %2.0f%%" % (user_perc, system_perc, wait_perc), perfdata)

check_info['statgrab_cpu'] = (check_statgrab_util, "CPU utilization", 1, no_inventory_possible)
