#!/usr/lib64/linuxfabrik-monitoring-plugins/venv/bin/python
# -*- coding: utf-8; py-indent-offset: 4 -*-
#
# Author:  Linuxfabrik GmbH, Zurich, Switzerland
# Contact: info (at) linuxfabrik (dot) ch
#          https://www.linuxfabrik.ch/
# License: The Unlicense, see LICENSE file.

# https://github.com/Linuxfabrik/monitoring-plugins/blob/main/CONTRIBUTING.md

"""See the check's README for more details."""

import argparse
import json
import re
import sys

import lib.args
import lib.base
import lib.huawei_dorado
import lib.lftest
import lib.txt
from lib.globals import STATE_CRIT, STATE_OK, STATE_UNKNOWN, STATE_WARN

__author__ = 'Linuxfabrik GmbH, Zurich/Switzerland'
__version__ = '2026081102'

DESCRIPTION = """Checks the health and running status of all controllers on a Huawei OceanStor Dorado
storage system via the REST API (/controller endpoint). Alerts when any controller
reports a non-normal health or running state, and optionally when its CPU, memory or
temperature exceeds the configured thresholds.
Supports extended reporting via --lengthy, and reporting the I/O and cache counters
via --performance."""

DEFAULT_CACHE_EXPIRE = 15  # minutes; default session timeout period is 20 minutes
DEFAULT_CRIT = ''
DEFAULT_CRIT_TEMPERATURE = ''
DEFAULT_DEVICE_ID = ''  # the appliance reports its own at login
DEFAULT_INSECURE = True
DEFAULT_NO_MATCH_SEVERITY = 'ok'
DEFAULT_NO_PROXY = False
DEFAULT_SCOPE = '0'
DEFAULT_TIMEOUT = 3
DEFAULT_WARN = ''
DEFAULT_WARN_TEMPERATURE = ''

# Highest `HEALTHSTATUS` code the REST Interface References document (offline). It
# bounds the metric so a graph scales to the whole enumeration; the thresholds stay
# out of the performance data, because whether a code is a fault depends on the
# object and is decided in `lib.huawei_dorado.get_health_status_state()`.
HEALTH_STATUS_MAX = 18

# Performance indicators this object supports, from the vendor's performance
# indicator tables. Read only when --performance is given.
#
# Cache page, chunk and page unit utilisation (1055 to 1057) are deliberately absent.
# A third-party implementation reads them, but neither REST Interface Reference lists
# them among the indicators a controller supports, and asking for a number nothing
# documents would put behaviour into this check that nobody can look up.
PERFORMANCE_INDICATORS = (
    19,
    21,
    22,
    23,
    24,
    25,
    26,
    27,
    28,
    68,
    69,
    93,
    95,
    110,
    120,
    303,
    370,
    384,
    385,
)

# Fields `--match` is applied to.
MATCH_FIELDS = ('UUID', 'LOCATION')

# RUNNINGSTATUS codes a healthy controller reports: normal (1), running (2) and
# online (27).
OK_RUNNING_STATUS = (1, 2, 27)


def parse_args():
    """Parse command line arguments using argparse."""
    parser = argparse.ArgumentParser(
        description=DESCRIPTION,
        epilog=lib.args.epilog(__file__),
        formatter_class=lib.args.HelpFormatter,
    )

    parser.add_argument(
        '-V',
        '--version',
        action='version',
        version=f'%(prog)s: v{__version__} by {__author__}',
    )

    parser.add_argument(
        '--always-ok',
        help=lib.args.help('--always-ok'),
        dest='ALWAYS_OK',
        action='store_true',
        default=False,
    )

    parser.add_argument(
        '--cache-expire',
        help=lib.args.help('--cache-expire') + ' Default: %(default)s',
        dest='CACHE_EXPIRE',
        type=int,
        default=DEFAULT_CACHE_EXPIRE,
    )

    parser.add_argument(
        '-c',
        '--critical',
        help='CRIT threshold for CPU and memory usage, as a Nagios range in percent. '
        'Off by default, because a controller under load is doing its job; set it once '
        'you know what your array normally sits at. Example: `--critical=90`',
        dest='CRIT',
        default=DEFAULT_CRIT,
    )

    parser.add_argument(
        '--critical-temperature',
        help=lib.args.help('--critical-temperature')
        + ' Off by default, because a healthy operating temperature depends on the '
        'controller model and on where the array stands. Example: `--critical-temperature=55`',
        dest='CRIT_TEMPERATURE',
        default=DEFAULT_CRIT_TEMPERATURE,
    )

    parser.add_argument(
        '--device-id',
        help='Huawei OceanStor Dorado API device ID. '
        'Optional: the appliance reports its own at login, so this is only '
        'needed to override that answer.',
        dest='DEVICE_ID',
        default=DEFAULT_DEVICE_ID,
    )

    parser.add_argument(
        '--ignore',
        help='Skip controllers. '
        + lib.args.help('--ignore-regex')
        + ' The regex is anchored at the start of the string (Python `re.match`) and is '
        'matched against `UUID`, `LOCATION`, so prefix with `.*` to match anywhere.',
        dest='IGNORE',
        action='append',
        default=None,
    )

    parser.add_argument(
        '--insecure',
        help=lib.args.help('--insecure'),
        dest='INSECURE',
        action='store_true',
        default=DEFAULT_INSECURE,
    )

    parser.add_argument(
        '--lengthy',
        help=lib.args.help('--lengthy'),
        dest='LENGTHY',
        action='store_true',
        default=False,
    )

    parser.add_argument(
        '--no-insecure',
        help=lib.args.help('--no-insecure'),
        dest='INSECURE',
        action='store_false',
        default=DEFAULT_INSECURE,
    )

    parser.add_argument(
        '--match',
        help='Limit to controllers. '
        + lib.args.help('--match')
        + ' The regex is anchored at the start of the string (Python `re.match`) and is '
        'matched against `UUID`, `LOCATION`, so prefix with `.*` to match anywhere.',
        dest='MATCH',
        action='append',
        default=None,
    )

    parser.add_argument(
        '--no-match-severity',
        help=lib.args.help('--no-match-severity') + ' Default: %(default)s',
        dest='NO_MATCH_SEVERITY',
        choices=['ok', 'warn', 'crit', 'unknown'],
        default=DEFAULT_NO_MATCH_SEVERITY,
    )

    parser.add_argument(
        '--no-perfdata',
        help=lib.args.help('--no-perfdata'),
        dest='NO_PERFDATA',
        action='store_true',
        default=False,
    )

    parser.add_argument(
        '--no-proxy',
        help=lib.args.help('--no-proxy'),
        dest='NO_PROXY',
        action='store_true',
        default=DEFAULT_NO_PROXY,
    )

    parser.add_argument(
        '--performance',
        help='Additionally report the I/O counters of every controller. '
        'Costs one API request per object, so a large appliance may need a '
        'higher --timeout.',
        dest='PERFORMANCE',
        action='store_true',
        default=False,
    )

    parser.add_argument(
        '--password',
        help='Huawei OceanStor Dorado API password.',
        dest='PASSWORD',
    )

    parser.add_argument(
        '--password-file',
        help=lib.args.help('--password-file'),
        dest='PASSWORD_FILE',
    )

    parser.add_argument(
        '--scope',
        help='Huawei OceanStor Dorado API scope.',
        dest='SCOPE',
        default=DEFAULT_SCOPE,
    )

    parser.add_argument(
        '--test',
        help=lib.args.help('--test'),
        dest='TEST',
        type=lib.args.csv,
    )

    parser.add_argument(
        '--timeout',
        help=lib.args.help('--timeout') + ' Default: %(default)s (seconds)',
        dest='TIMEOUT',
        type=int,
        default=DEFAULT_TIMEOUT,
    )

    parser.add_argument(
        '-u',
        '--url',
        help='Huawei OceanStor Dorado API URL.',
        dest='URL',
        required=True,
    )

    parser.add_argument(
        '--username',
        help='Huawei OceanStor Dorado API username.',
        dest='USERNAME',
        required=True,
    )

    parser.add_argument(
        '-w',
        '--warning',
        help='WARN threshold for CPU and memory usage, as a Nagios range in percent. '
        'Off by default, because a controller under load is doing its job; set it once '
        'you know what your array normally sits at. Example: `--warning=80`',
        dest='WARN',
        default=DEFAULT_WARN,
    )

    parser.add_argument(
        '--warning-temperature',
        help=lib.args.help('--warning-temperature')
        + ' Off by default, because a healthy operating temperature depends on the '
        'controller model and on where the array stands. Example: `--warning-temperature=45`',
        dest='WARN_TEMPERATURE',
        default=DEFAULT_WARN_TEMPERATURE,
    )

    parser.add_argument(
        '-v',
        '--verbose',
        help=lib.args.help('--verbose')
        + ' Appends what every API request returned, so the appliance\'s own answers '
        'can be read while working out how it reports something. Session tokens are '
        'redacted. The output is as long as those answers are, so this is a debugging '
        'aid rather than something to leave switched on.',
        dest='VERBOSE',
        action='store_true',
        default=False,
    )

    args, _ = parser.parse_known_args()
    return args


def main():
    """The main function. This is where the magic happens."""

    # parse the command line
    try:
        args = parse_args()
    except SystemExit:
        sys.exit(STATE_UNKNOWN)

    if args.PASSWORD_FILE:
        args.PASSWORD = lib.args.load_secret(args.PASSWORD_FILE)
    if not args.PASSWORD:
        lib.base.cu('Provide the API password via --password or --password-file.')

    # set default values for append parameters that were not specified
    if args.IGNORE is None:
        args.IGNORE = []
    if args.MATCH is None:
        args.MATCH = []

    if not args.URL.startswith('http'):
        lib.base.cu('--url parameter has to start with "http://" or https://".')

    # fetch data
    if args.TEST is None:
        result = lib.huawei_dorado.get_data('controller', args)
    else:
        # do not call the command, put in test data
        stdout, _stderr, _retc = lib.lftest.test(args.TEST)
        result = json.loads(stdout)

    # no valuable result?
    lib.huawei_dorado.assert_ok(result, 'the controllers')

    # An appliance always has controllers, so an empty list is a query that
    # never reached them rather than an inventory that is genuinely empty.
    # Reporting OK here would hide the fault behind a green check.
    if not result.get('data'):
        lib.base.oao(
            f'{args.URL} reported no controllers.'
            ' Verify that the API user is allowed to query them.',
            STATE_UNKNOWN,
        )

    # init some vars
    msg = ''
    state = STATE_OK
    perfdata = ''
    compiled_match_regex = [
        lib.base.coe(item) for item in lib.txt.compile_regex(args.MATCH, '--match')
    ]
    compiled_ignore_regex = [
        lib.base.coe(item)
        for item in lib.txt.compile_regex(args.IGNORE, '--ignore')
    ]

    # analyze data
    table_data = []
    for controller in result.get('data') or []:
        controller['UUID'] = lib.huawei_dorado.get_uuid(controller)
        # Perfdata labels carry the object's own TYPE:ID, which stays the same
        # when hardware is moved between slots, unlike its location.
        label = re.sub(r'\W+', '_', controller['UUID'])

        if args.MATCH and not any(
            lib.base.coe(lib.txt.match_regex(pattern, str(controller.get(field, ''))))
            for pattern in compiled_match_regex
            for field in MATCH_FIELDS
        ):
            continue

        if args.IGNORE and any(
            lib.base.coe(lib.txt.match_regex(pattern, str(controller.get(field, ''))))
            for pattern in compiled_ignore_regex
            for field in MATCH_FIELDS
        ):
            continue

        health_state = lib.huawei_dorado.get_health_status_state(
            controller.get('HEALTHSTATUS')
        )
        state = lib.base.get_worst(state, health_state)

        running_state = lib.huawei_dorado.get_running_status_state(
            controller.get('RUNNINGSTATUS'), OK_RUNNING_STATUS
        )
        state = lib.base.get_worst(state, running_state)

        # A controller board without a temperature sensor reports -1, which is not a
        # reading: it is neither compared against a threshold nor graphed.
        controller['TEMPERATURE'] = lib.huawei_dorado.as_temperature(
            controller.get('TEMPERATURE')
        )

        # The REST Interface References give no unit for the board voltage, but their own
        # response examples show 120 and 160 next to a backup power module reading 161,
        # which they do document as tenths of a volt. A controller board runs on 12 V, so
        # the raw value is read the same way rather than as 120 volts.
        voltage = lib.huawei_dorado.as_code(controller.get('VOLTAGE'))
        controller['VOLTAGE'] = None if voltage is None else round(voltage / 10, 1)

        # All three thresholds are off unless the operator sets them. A controller under
        # load is doing its job, and what counts as hot depends on the model and on where
        # the array stands, so there is no default that would be right everywhere.
        if args.WARN or args.CRIT:
            for field in ('CPUUSAGE', 'MEMORYUSAGE'):
                usage = lib.huawei_dorado.as_code(controller.get(field))
                if usage is None:
                    # A firmware that does not report this reading has nothing to
                    # compare, and comparing the missing value would alert on it.
                    continue
                state = lib.base.get_worst(
                    state,
                    lib.base.get_state(
                        usage,
                        args.WARN or None,
                        args.CRIT or None,
                        _operator='range',
                    ),
                )
        if controller['TEMPERATURE'] and (
            args.WARN_TEMPERATURE or args.CRIT_TEMPERATURE
        ):
            state = lib.base.get_worst(
                state,
                lib.base.get_state(
                    controller['TEMPERATURE'],
                    args.WARN_TEMPERATURE or None,
                    args.CRIT_TEMPERATURE or None,
                    _operator='range',
                ),
            )

        perfdata += lib.base.get_perfdata(
            f'{label}_health_status',
            controller.get('HEALTHSTATUS'),
            uom=None,
            _min=0,
            _max=HEALTH_STATUS_MAX,
        )
        perfdata += lib.base.get_perfdata(
            f'{label}_running_status',
            controller.get('RUNNINGSTATUS'),
            _min=0,
        )
        perfdata += lib.base.get_perfdata(
            f'{label}_cpu_usage',
            controller.get('CPUUSAGE'),
            uom='%',
            warn=args.WARN or None,
            crit=args.CRIT or None,
            _min=0,
            _max=100,
        )
        perfdata += lib.base.get_perfdata(
            f'{label}_dirty_data_rate',
            controller.get('DIRTYDATARATE'),
            uom='%',
            _min=0,
            _max=100,
        )
        # The bare code, not a label. The vendor documents this field both ways round in
        # the same document (the batch query as `1: off, 2: on`, the single-object query
        # as `1: on, 2: off`), and appliances additionally send a 0 that neither table
        # lists, so a readable state cannot be derived from it. See
        # `lib.huawei_dorado.get_led_status()`, which covers the other spelling.
        perfdata += lib.base.get_perfdata(
            f'{label}_light_status',
            controller.get('LIGHT_STATUS'),
            _min=0,
            _max=2,
        )
        perfdata += lib.base.get_perfdata(
            f'{label}_memory_usage',
            controller.get('MEMORYUSAGE'),
            uom='%',
            warn=args.WARN or None,
            crit=args.CRIT or None,
            _min=0,
            _max=100,
        )
        perfdata += lib.base.get_perfdata(
            f'{label}_temperature',
            controller['TEMPERATURE'],
            uom=None,
            warn=args.WARN_TEMPERATURE or None,
            crit=args.CRIT_TEMPERATURE or None,
            _min=0,
        )
        perfdata += lib.base.get_perfdata(
            f'{label}_voltage',
            controller.get('VOLTAGE'),
            _min=0,
        )

        # The counters come from a second endpoint, which a fixture cannot stand
        # in for. `lib.huawei_dorado.get_performance()` covers that path.
        if args.PERFORMANCE and args.TEST is None:
            samples = lib.huawei_dorado.get_performance(
                controller['UUID'], PERFORMANCE_INDICATORS, args
            )
            perfdata += lib.huawei_dorado.get_performance_perfdata(label, samples)

        controller['health'] = lib.huawei_dorado.get_health_status(
            controller.get('HEALTHSTATUS')
        )
        controller['running'] = lib.huawei_dorado.get_running_status(
            controller.get('RUNNINGSTATUS')
        )
        # One state per row, in the last column. IcingaWeb replaces a state with an
        # icon, which shifts everything to the right of it, so a second one mid-row
        # would break the table. What decided it stays readable in the two columns
        # in front of it.
        controller['state'] = lib.base.state2str(
            lib.base.get_worst(health_state, running_state), empty_ok=False
        )
        controller['ISMASTER'] = (
            'x' if str(controller.get('ISMASTER')).strip().lower() == 'true' else '-'
        )
        controller['MODEL'] = lib.huawei_dorado.get_controller_model(
            controller.get('MODEL')
        )
        controller['ROLE'] = lib.huawei_dorado.get_controller_role(
            controller.get('ROLE')
        )
        # The performance data is written above, so what is left here is the display
        # value. A board that reports neither reading prints the appliance's own
        # placeholder rather than a literal "None".
        if controller['TEMPERATURE'] is None:
            controller['TEMPERATURE'] = '--'
        if controller['VOLTAGE'] is None:
            controller['VOLTAGE'] = '--'

        table_data.append(controller)

    # The appliance listed controllers and the filter selected none of them.
    if not table_data:
        lib.base.oao(
            f'No controllers matched `{", ".join(args.MATCH)}`.',
            lib.base.str2state(args.NO_MATCH_SEVERITY),
            always_ok=args.ALWAYS_OK,
            no_perfdata=args.NO_PERFDATA,
        )

    # build the message
    if state == STATE_CRIT:
        msg += 'There are critical errors.'
    elif state == STATE_WARN:
        msg += 'There are warnings.'
    else:
        msg += 'Everything is ok.'
    msg += '\n\n'

    # build table output
    if table_data:
        if args.LENGTHY:
            keys = [
                'UUID',
                'LOCATION',
                'MODEL',
                'ROLE',
                'ISMASTER',
                'CPUUSAGE',
                'MEMORYUSAGE',
                'VOLTAGE',
                'TEMPERATURE',
                'health',
                'running',
                'state',
            ]
            headers = [
                'UUID',
                'Location',
                'Model',
                'Role',
                'Master',
                'CPU (%)',
                'Mem (%)',
                'Volt',
                'Temp',
                'Health',
                'Running',
                'State',
            ]
        else:
            keys = [
                'UUID',
                'LOCATION',
                'ISMASTER',
                'CPUUSAGE',
                'MEMORYUSAGE',
                'TEMPERATURE',
                'health',
                'running',
                'state',
            ]
            headers = [
                'UUID',
                'Location',
                'Master',
                'CPU (%)',
                'Mem (%)',
                'Temp',
                'Health',
                'Running',
                'State',
            ]

        msg += lib.base.get_table(
            table_data, keys, header=headers, missing='--', hide_empty=True
        )

    if args.VERBOSE:
        msg += '\n\n' + lib.huawei_dorado.format_responses()

    # over and out
    lib.base.oao(
        msg, state, perfdata, always_ok=args.ALWAYS_OK, no_perfdata=args.NO_PERFDATA
    )


if __name__ == '__main__':
    try:
        main()
    except Exception:
        lib.base.cu()
