#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (C) 2019 tribe29 GmbH - License: GNU General Public License v2
# This file is part of Checkmk (https://checkmk.com). It is subject to the terms and
# conditions defined in the file COPYING, which is part of this source code package.

# NOTE: Careful when replacing the *-import below with a more specific import. This can cause
# problems because it might remove variables from the check-context which are necessary for
# resolving legacy discovery results such as [("SUMMARY", "diskstat_default_levels")]. Furthermore,
# it might also remove variables needed for accessing discovery rulesets.
from cmk.base.check_legacy_includes.cpu_load import *  # pylint: disable=wildcard-import,unused-wildcard-import
# Output is taken from /proc/loadavg plus the number of cores:
# 0.26 0.47 0.52 2/459 19531 4

#   .--Load----------------------------------------------------------------.
#   |                       _                    _                         |
#   |                      | |    ___   __ _  __| |                        |
#   |                      | |   / _ \ / _` |/ _` |                        |
#   |                      | |__| (_) | (_| | (_| |                        |
#   |                      |_____\___/ \__,_|\__,_|                        |
#   |                                                                      |
#   '----------------------------------------------------------------------'

cpuload_default_levels = (5.0, 10.0)


def inventory_cpu_load(section):
    if section:
        return [(None, "cpuload_default_levels")]


def check_cpu_load(item, params, section):
    if not section:
        return None

    return check_cpu_load_generic(params, section['load'], section['num_cpus'])


check_info["cpu.loads"] = {
    "check_function": check_cpu_load,
    "inventory_function": inventory_cpu_load,
    "service_description": "CPU load",
    "has_perfdata": True,
    "group": "cpu_load",
    "handle_real_time_checks": True,
}

#.
#   .--Threads-------------------------------------------------------------.
#   |                _____ _                        _                      |
#   |               |_   _| |__  _ __ ___  __ _  __| |___                  |
#   |                 | | | '_ \| '__/ _ \/ _` |/ _` / __|                 |
#   |                 | | | | | | | |  __/ (_| | (_| \__ \                 |
#   |                 |_| |_| |_|_|  \___|\__,_|\__,_|___/                 |
#   |                                                                      |
#   '----------------------------------------------------------------------'

threads_default_levels = {}  # legacy default levels variable

factory_settings["cpu_threads_default_levels"] = {
    "levels": ("levels", (2000, 4000)),
}


def inventory_cpu_threads(section):
    if section:
        return [(None, {})]


def _get_levels(params, level_name):
    if level_name not in params:
        return (None, None)
    levels = params[level_name]
    if levels == "no_levels":
        return (None, None)
    return levels[1]


def check_cpu_threads(item, params, section):
    if isinstance(params, tuple):
        params = {'levels': params}

    try:
        num_threads = section['num_threads']
    except Exception:
        return

    absolute_levels = _get_levels(params, "levels")
    yield check_levels(num_threads,
                       'threads',
                       absolute_levels,
                       unit="threads",
                       human_readable_func=lambda x: "%.f" % x,
                       infoname="Count")

    if 'max_threads' in section:
        thread_usage = 100.0 * num_threads / section['max_threads']
        relative_levels = _get_levels(params, "levels_percent")
        yield check_levels(thread_usage,
                           'thread_usage',
                           relative_levels,
                           human_readable_func=get_percent_human_readable,
                           infoname="Usage")


check_info["cpu.threads"] = {
    "check_function": check_cpu_threads,
    "inventory_function": inventory_cpu_threads,
    "service_description": "Number of threads",
    "has_perfdata": True,
    "group": "threads",
    "default_levels_variable": "cpu_threads_default_levels",
    "handle_real_time_checks": True,
}
