#!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# |             ____ _               _        __  __ _  __           |
# |            / ___| |__   ___  ___| | __   |  \/  | |/ /           |
# |           | |   | '_ \ / _ \/ __| |/ /   | |\/| | ' /            |
# |           | |___| | | |  __/ (__|   <    | |  | | . \            |
# |            \____|_| |_|\___|\___|_|\_\___|_|  |_|_|\_\           |
# |                                                                  |
# | Copyright Mathias Kettner 2018             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 parse_frac_prefix(value):
    # type: (str) -> float
    if value.endswith('m'):
        return 0.001 * float(value[:-1])
    return float(value)


def parse_mul_prefix(value):
    # type: (str) -> int
    if value.endswith('k'):
        return 1000 * int(value[:-1])
    return int(value)


@get_parsed_item_data
def check_k8s_pods_memory(item, params, metrics):

    metric_names = [('rss', 'RSS'), ('swap', 'Swap'), ('usage_bytes', 'Bytes used'),
                    ('max_usage_bytes', 'Max. bytes used')]
    for what, title in metric_names:
        try:
            value = sum(
                map(parse_mul_prefix,
                    [pod_data['metrics']['memory_%s' % what] for pod_data in metrics]))
            yield check_levels(value,
                               what,
                               params.get(what),
                               human_readable_func=get_bytes_human_readable,
                               infoname=title)
        except KeyError:
            yield 0, "Memory %s currently unavailable" % what


check_info['k8s_pods_memory'] = {
    'parse_function': parse_k8s,
    'inventory_function': discover(),
    'check_function': check_k8s_pods_memory,
    'service_description': 'Memory usage for Pods in %s namespace',
    'group': 'k8s_pods_memory',
    'has_perfdata': True,
    'includes': ['k8s.include'],
}


@get_parsed_item_data
def check_k8s_pods_cpu(item, params, metrics):
    metric_names = [('system', 'System'), ('user', 'User'), ('usage', 'Usage')]
    for what, title in metric_names:
        try:
            value = sum(
                map(parse_frac_prefix,
                    [pod_data['metrics']['cpu_%s' % what] for pod_data in metrics]))
            yield check_levels(value, what, params.get(what), infoname=title)
        except KeyError:
            yield 0, "CPU %s currently unavailable" % what.title()


check_info['k8s_pods_cpu'] = {
    'parse_function': parse_k8s,
    'inventory_function': discover(),
    'check_function': check_k8s_pods_cpu,
    'service_description': 'CPU usage for Pods in %s namespace',
    'group': 'k8s_pods_cpu',
    'has_perfdata': True,
    'includes': ['k8s.include'],
}


@get_parsed_item_data
def check_k8s_pods_fs(item, params, metrics):
    metric_names = [('inodes', 'INodes'), ('reads', 'Reads'), ('writes', 'Writes'),
                    ('limit_bytes', 'Limit bytes'), ('usage_bytes', 'Bytes used')]
    for what, title in metric_names:
        try:
            parser = parse_mul_prefix if 'bytes' in what else parse_frac_prefix
            value = sum(map(parser, [pod_data['metrics']['fs_%s' % what] for pod_data in metrics]))
            hrf = get_bytes_human_readable if 'bytes' in what else None
            yield check_levels(value,
                               what,
                               params.get(what),
                               human_readable_func=hrf,
                               infoname=title)
        except KeyError:
            yield 0, "FS %s currently unavailable" % what.title()


check_info['k8s_pods_fs'] = {
    'parse_function': parse_k8s,
    'inventory_function': discover(),
    'check_function': check_k8s_pods_fs,
    'service_description': 'FS usage for Pods in %s namespace',
    'group': 'k8s_pods_fs',
    'has_perfdata': True,
    'includes': ['k8s.include'],
}
