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

import json


def parse_cadvisor_cpu(info):
    cpu_info = json.loads(info[0][0])
    parsed = {}
    for cpu_name, cpu_entries in cpu_info.items():
        if len(cpu_entries) != 1:
            continue
        try:
            parsed[cpu_name] = float(cpu_entries[0]["value"])
        except KeyError:
            continue
    return parsed


def check_cadvisor_cpu(_item, params, parsed):
    # No suitable function in cpu_util.include
    cpu_user = parsed["cpu_user"]
    cpu_system = parsed["cpu_system"]
    cpu_total = cpu_user + cpu_system

    yield check_levels(
        cpu_user, "user", None, human_readable_func=get_percent_human_readable, infoname="User"
    )
    yield check_levels(
        cpu_system,
        "system",
        None,
        human_readable_func=get_percent_human_readable,
        infoname="System",
    )
    yield check_levels(
        cpu_total,
        "util",
        params.get("util"),
        human_readable_func=get_percent_human_readable,
        infoname="Total CPU",
    )


check_info["cadvisor_cpu"] = {
    "parse_function": parse_cadvisor_cpu,
    "inventory_function": discover_single,
    "check_function": check_cadvisor_cpu,
    "service_description": "CPU utilization",
    "has_perfdata": True,
    "group": "cpu_utilization",
}
