#!/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_pacific
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 cluster nodes on a Huawei OceanStor
Pacific storage system via the REST API (/cluster/servers endpoint). Alerts when any node is not
online or its OAM agent is not healthy.
Supports extended reporting via --lengthy."""

DEFAULT_CACHE_EXPIRE = 15  # minutes
DEFAULT_INSECURE = True
DEFAULT_NO_MATCH_SEVERITY = 'ok'
DEFAULT_NO_PROXY = False
DEFAULT_SCOPE = '0'
DEFAULT_TIMEOUT = 3
DEFAULT_WARRANTY_SEVERITY = 'ok'

# Fields `--match` is applied to.
MATCH_FIELDS = ('name', 'management_ip')

# `warranty_status` codes worth reporting on: about to expire (2) and expired (3).
# `0` is a node that is not a storage node, `1` a warranty with more than six months to
# run, and `4` a node whose lifecycle information the cluster does not have.
WARRANTY_ENDING = (2, 3)

# `oam_agent_status` codes. `-1` is the appliance's "not monitored" marker, which is the
# lower bound of the metric rather than a state worth alerting on.
OAM_AGENT_NOT_MONITORED = -1
OAM_AGENT_FAULTY = 1


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(
        '--ignore',
        help='Skip cluster nodes. '
        + lib.args.help('--ignore-regex')
        + ' The regex is anchored at the start of the string (Python `re.match`) and is '
        'matched against `name`, `management_ip`, 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 cluster nodes. '
        + lib.args.help('--match')
        + ' The regex is anchored at the start of the string (Python `re.match`) and is '
        'matched against `name`, `management_ip`, 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(
        '--password',
        help='Huawei OceanStor Pacific 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 Pacific 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 Pacific API URL.',
        dest='URL',
        required=True,
    )

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

    parser.add_argument(
        '--warranty-severity',
        help='State to report for a node whose warranty has expired or is about to. '
        'This is a commercial fact rather than a fault, so it does not alert by default: '
        'a node out of warranty runs exactly as well as one in warranty, right up to the '
        'point where a part has to be replaced. '
        'Default: %(default)s',
        dest='WARRANTY_SEVERITY',
        choices=['ok', 'warn', 'crit', 'unknown'],
        default=DEFAULT_WARRANTY_SEVERITY,
    )

    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_pacific.get_data('cluster/servers', 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_pacific.assert_ok(result, 'the cluster nodes')

    # A cluster always has cluster nodes, 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 cluster nodes.'
            ' 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')
    ]
    warranty_state = lib.base.str2state(args.WARRANTY_SEVERITY)

    # analyze data
    table_data = []
    for node in result.get('data') or []:
        # `in_cluster` has three documented values: True (added), False (not added) and
        # null (about to be added). A node that is not part of the cluster holds none of
        # its storage, so judging it would report a fault the cluster does not have. A
        # firmware that omits the field must not narrow the result, so absent means keep.
        if 'in_cluster' in node and node['in_cluster'] is not True:
            continue

        if args.MATCH and not any(
            lib.base.coe(lib.txt.match_regex(pattern, str(node.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(node.get(field, ''))))
            for pattern in compiled_ignore_regex
            for field in MATCH_FIELDS
        ):
            continue

        running_state = lib.huawei_pacific.get_node_running_status_state(
            node.get('running_status')
        )
        state = lib.base.get_worst(state, running_state)

        # `-1` is the appliance's "not monitored" marker, not a fault: a node whose OAM
        # agent is not being watched has nothing to report, and alerting on it would
        # warn forever on every cluster that does not run the agent.
        oam_agent_status = lib.huawei_pacific.as_code(node.get('oam_agent_status'))
        oam_state = STATE_OK
        if oam_agent_status is not None and oam_agent_status > 0:
            oam_state = STATE_WARN
            state = lib.base.get_worst(state, oam_state)

        # An error code the node reports is a fault it has already diagnosed itself.
        error_code = node.get('error_code')
        error_state = STATE_OK
        if error_code not in (None, '', '0', 0):
            error_state = STATE_CRIT
            state = lib.base.get_worst(state, error_state)

        # A warranty running out is not a fault, so it stays quiet unless the operator
        # asks. It is what an administrator plans a hardware refresh from.
        warranty = lib.huawei_pacific.as_code(node.get('warranty_status'))
        node_warranty_state = STATE_OK
        if warranty in WARRANTY_ENDING:
            node_warranty_state = warranty_state
            state = lib.base.get_worst(state, node_warranty_state)

        label = re.sub(r'\W+', '_', str(node.get('name', node.get('id'))))
        perfdata += lib.base.get_perfdata(
            f'{label}_oam_agent_status',
            oam_agent_status,
            uom=None,
            _min=OAM_AGENT_NOT_MONITORED,
            _max=OAM_AGENT_FAULTY,
        )

        node['base_board'] = lib.huawei_pacific.get_base_board(
            node.get('base_board'),
        )
        node['oam_agent_status'] = lib.huawei_pacific.get_oam_agent_status(
            node.get('oam_agent_status'),
        )
        node['error_code'] = '--' if error_code in (None, '') else str(error_code)
        node['warranty'] = lib.huawei_pacific.get_warranty_status(warranty)
        # One state per node, 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. Which aspect is at fault stays readable in the columns in front of it.
        node['state'] = lib.base.state2str(
            lib.base.get_worst(
                running_state, oam_state, error_state, node_warranty_state
            ),
            empty_ok=False,
        )

        table_data.append(node)

    # The appliance listed cluster nodes and the filter selected none of them.
    if not table_data and args.MATCH:
        lib.base.oao(
            f'No cluster nodes 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 = [
                'name',
                'management_ip',
                'model',
                'base_board',
                'software_version',
                'running_status',
                'oam_agent_status',
                'error_code',
                'warranty',
                'state',
            ]
            headers = [
                'Name',
                'Management IP',
                'Model',
                'Base Board',
                'Software Version',
                'Running',
                'OAM Agent',
                'Error Code',
                'Warranty',
                'State',
            ]
        else:
            keys = [
                'name',
                'running_status',
                'oam_agent_status',
                'error_code',
                'warranty',
                'state',
            ]
            headers = [
                'Name',
                'Running',
                'OAM Agent',
                'Error Code',
                'Warranty',
                'State',
            ]

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

    if args.VERBOSE:
        msg += '\n\n' + lib.huawei_pacific.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()
