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

factory_settings['jolokia_jvm_threading.pool'] = {
    'currentThreadsBusy': (80, 90),
}


def parse_jolokia_json_output(info):
    for line in info:
        try:
            instance, mbean, raw_json_data = line
            yield instance, mbean, json.loads(raw_json_data)
        except ValueError:
            continue


def parse_jolokia_jvm_threading(info):
    parsed = {}
    for instance, mbean, data in parse_jolokia_json_output(info):

        type_ = mbean.split("type=", 1)[-1].split(",", 1)[0].split("/", 1)[0]
        parsed_data = parsed.setdefault(instance, {}).setdefault(type_, {})

        if type_ == "ThreadPool":
            for key in data:
                name = key.split('name="', 1)[-1].split('"', 1)[0]
                parsed_data[name] = data[key]
        else:
            parsed_data.update(data)

    return parsed


@discover
def discover_jolokia_jvm_threading(_instance, data):
    return bool(data.get("Threading"))


@get_parsed_item_data
def check_jolokia_jvm_threading(item, params, instance_data):
    data = instance_data.get("Threading", {})
    count = data.get('ThreadCount')
    if count is not None:
        levels = params.get('threadcount_levels')
        yield check_levels(count,
                           'ThreadCount',
                           levels,
                           infoname="Count",
                           human_readable_func=lambda i: "%.f" % i)

        counter = "jolokia_jvm_threading.count.%s" % item
        thread_rate = get_rate(counter, time.time(), count, allow_negative=True)
        levels = params.get('threadrate_levels')
        yield check_levels(thread_rate, 'ThreadRate', levels, infoname="Rate")

    for key, name in (
        ('DaemonThreadCount', 'Daemon threads'),
        ('PeakThreadCount', 'Peak count'),
        ('TotalStartedThreadCount', 'Total started'),
    ):
        value = data.get(key)
        if value is None:
            continue
        levels = params.get('%s_levels' % key.lower())
        yield check_levels(value,
                           key,
                           levels,
                           infoname=name,
                           human_readable_func=lambda i: "%.f" % i)


check_info["jolokia_jvm_threading"] = {
    "parse_function": parse_jolokia_jvm_threading,
    "inventory_function": discover_jolokia_jvm_threading,
    "check_function": check_jolokia_jvm_threading,
    "service_description": "JVM %s Threading",
    "group": "jvm_threading",
    "has_perfdata": True,
}


def discover_jolokia_jvm_threading_pool(parsed):
    for instance in parsed:
        threadpool_data = parsed[instance].get("ThreadPool", {})
        for name in threadpool_data:
            yield "%s ThreadPool %s" % (instance, name), {}


def check_jolokia_jvm_threading_pool(item, params, parsed):
    instance, pool_name = item.split(" ThreadPool ", 1)
    thread_pools = parsed.get(instance, {}).get("ThreadPool", {})
    threadpool_info = thread_pools.get(pool_name, {})
    max_threads = threadpool_info.get("maxThreads")
    if max_threads is None:
        return

    yield 0, "Maximum threads: %d" % max_threads

    for key, name in (
        ('currentThreadsBusy', 'Busy'),
        ('currentThreadCount', 'Total'),
    ):
        value = threadpool_info.get(key)
        if value is None:
            continue
        result = check_levels(value,
                              key,
                              params.get(key),
                              infoname=name,
                              factor=max_threads / 100.,
                              human_readable_func=lambda f: "%.f" % f)
        result[2][0] = result[2][0][:4] + (None, max_threads)
        yield result


check_info["jolokia_jvm_threading.pool"] = {
    "inventory_function": discover_jolokia_jvm_threading_pool,
    "check_function": check_jolokia_jvm_threading_pool,
    "default_levels_variable": "jolokia_jvm_threading.pool",
    "service_description": "JVM %s",
    "group": "jvm_tp",
    "has_perfdata": True,
}
