#!/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_docker_node_info(info):
    try:
        import json
        return json.loads("".join(info[0]))
    except ValueError:
        return " ".join(info[0])


def inventory_docker_node_info(parsed):
    if parsed and isinstance(parsed, dict):
        return [(None, {})]


def check_docker_node_info(item, params, parsed):
    if isinstance(parsed, dict):
        # TODO use other infos from this section?
        return 0, 'Daemon running on host %s' % parsed["Name"]

    return 2, parsed


check_info['docker_node_info'] = {
    'parse_function'        : parse_docker_node_info,
    'inventory_function'    : inventory_docker_node_info,
    'check_function'        : check_docker_node_info,
    'service_description'   : 'Docker node info',
}


def inventory_docker_node_containers(parsed):
    if parsed and isinstance(parsed, dict):
        return [(None, {})]


def check_docker_node_containers(item, params, parsed):
    if not isinstance(parsed, dict):
        # String with error message in case the daemon is not running
        return

    def check_node_levels(count, warn, crit, warn_lower, crit_lower):
        if crit is not None and count >= crit:
            return 2, " (warn/crit at %s/%s)" % (warn, crit)
        if crit_lower is not None and count < crit_lower:
            return 2, " (warn/crit below %s/%s)" % (warn_lower, crit_lower)
        if warn is not None and count >= warn:
            return 1, " (warn/crit at %s/%s)" % (warn, crit)
        if warn_lower is not None and count < warn_lower:
            return 1, " (warn/crit below %s/%s)" % (warn_lower, crit_lower)
        return 0, ""

    for title, key, upper_name, lower_name in (
        ("containers", "Containers", 'upper_levels', 'lower_levels'),
        ("running", "ContainersRunning", 'running_upper_levels', 'running_lower_levels'),
        ("paused", "ContainersPaused", 'paused_upper_levels', 'paused_lower_levels'),
        ("stopped", "ContainersStopped", 'stopped_upper_levels', 'stopped_lower_levels'),
    ):
        raw_count = parsed.get(key)
        if raw_count is None:
            yield 3, "%s: count not present in agent output" % title
        count = int(raw_count)

        warn, crit = params.get(upper_name, (None, None))
        lower_warn, lower_crit = params.get(lower_name, (None, None))

        status, level_text = check_node_levels(count, warn, crit, lower_warn, lower_crit)
        infotext = "%s: %d" % (title, count)
        if level_text:
            infotext += level_text
        perfdata = [(title.lower(), count, warn, crit, lower_warn, lower_crit)]

        yield status, infotext, perfdata


check_info["docker_node_info.containers"] = {
    "inventory_function": inventory_docker_node_containers,
    "check_function": check_docker_node_containers,
    "service_description": "Docker containers",
    "has_perfdata": True,
    "group": "docker_node_containers",
}
