#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (C) 2019 Checkmk 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.oracle import *  # pylint: disable=wildcard-import,unused-wildcard-import

# In cooperation with Thorsten Bruhns from OPITZ Consulting

# <<<oracle_processes>>>
# TUX2 51 300
# FOOBAR 11 4780

# Columns: SID PROCESSES_COUNT PROCESSES_LIMIT

factory_settings["oracle_processes_defaults"] = {
    "levels": (70.0, 90.0),
}


def inventory_oracle_processes(info):

    return [(line[0], {}) for line in info]


def check_oracle_processes(item, params, info):
    for line in info:
        if len(line) < 3:
            continue
        if line[0] == item:
            err = oracle_handle_ora_errors(line)
            if err is False:
                continue
            elif isinstance(err, tuple):
                return err

            processes_num = int(line[1])
            processes_max = int(line[2])
            processes_pct = float(processes_num) / float(processes_max) * 100

            warn, crit = params["levels"]
            processes_warn = processes_max * warn / 100
            processes_crit = processes_max * crit / 100

            if processes_pct >= crit:
                state = 2
            elif processes_pct >= warn:
                state = 1
            else:
                state = 0

            return (
                state,
                "%d of %d processes are used (%d%%, warn/crit at %d%%/%d%%)"
                % (processes_num, processes_max, processes_pct, warn, crit),
                [("processes", processes_num, processes_warn, processes_crit)],
            )

    # In case of missing information we assume that the login into
    # the database has failed and we simply skip this check. It won't
    # switch to UNKNOWN, but will get stale.
    raise MKCounterWrapped("Login into database failed")


check_info["oracle_processes"] = {
    "check_function": check_oracle_processes,
    "inventory_function": inventory_oracle_processes,
    "service_description": "ORA %s Processes",
    "has_perfdata": True,
    "default_levels_variable": "oracle_processes_defaults",
    "group": "oracle_processes",
}
