#!/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 re
import sys

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

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

DESCRIPTION = """Checks the namespaces of a Huawei OceanStor Pacific storage system via the REST API
(/converged_service/namespaces endpoint). Alerts when a namespace cannot be reached, when it turned
read-only, and when it reports a running status other than normal. Reports the space and the number
of files every namespace uses. Supports extended reporting via --lengthy."""

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

# Fields `--match` and `--ignore` are applied to.
MATCH_FIELDS = ('id', 'name')

# The only running status both REST Interface References document is the normal one, so
# every other code is reported as the appliance sent it rather than translated into an
# invented name.
RUNNING_STATUS_NORMAL = 0

# How the namespace can be used, fully documented in both references. `inaccessible` is
# the one that means an outage; a read-only namespace still serves reads and is a
# legitimate configuration for an archive, which is why its severity is a parameter.
READ_WRITE_MODE_READABLE_WRITABLE = 0
READ_WRITE_MODE_READ_ONLY = 1
READ_WRITE_MODE_INACCESSIBLE = 2
READ_WRITE_MODES = {
    READ_WRITE_MODE_READABLE_WRITABLE: 'readable and writable (0)',
    READ_WRITE_MODE_READ_ONLY: 'read-only (1)',
    READ_WRITE_MODE_INACCESSIBLE: 'inaccessible (2)',
}

# What the namespace speaks, for the extended table.
PROTOCOL_TYPES = {
    0: 'NAS',
    2: 'HDFS',
    3: 'protocol interworking',
}


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 namespaces. '
        + lib.args.help('--ignore-regex')
        + ' The regex is anchored at the start of the string (Python `re.match`) and is '
        'matched against the namespace identifier and its name, so prefix with `.*` to '
        'match anywhere. Default: %(default)s',
        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(
        '--match',
        help='Limit to namespaces. '
        + lib.args.help('--match')
        + ' The regex is anchored at the start of the string (Python `re.match`) and is '
        'matched against the namespace identifier and its name, so prefix with `.*` to '
        'match anywhere. Default: %(default)s',
        dest='MATCH',
        action='append',
        default=None,
    )

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

    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(
        '--read-only-severity',
        help='State to report for a namespace that is read-only. A namespace can be set '
        'read-only on purpose, which is what an archive that must not change any more '
        'looks like, so this is not a fault by itself. '
        'Default: %(default)s',
        dest='READ_ONLY_SEVERITY',
        choices=['ok', 'warn', 'crit', 'unknown'],
        default=DEFAULT_READ_ONLY_SEVERITY,
    )

    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(
        '-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 get_read_write_mode_state(mode, read_only_state):
    """
    Convert a namespace's read/write mode into the state a check reports.

    ### Parameters
    - **mode** (`int` or `str`): The `read_write_mode` of a namespace.
    - **read_only_state** (`int`): What a read-only namespace should report, which is a
      parameter because being read-only can be the point of an archive.

    ### Returns
    - **int**:
      `STATE_OK` for a namespace that is readable and writable, `STATE_CRIT` for one that
      cannot be reached at all, `read_only_state` for a read-only one, and `STATE_WARN`
      for a code the enumeration does not know and for a missing value.

    ### Example
    >>> get_read_write_mode_state(0, STATE_WARN) == STATE_OK
    True

    >>> get_read_write_mode_state(2, STATE_WARN) == STATE_CRIT
    True
    """
    code = lib.huawei_pacific.as_code(mode)
    if code == READ_WRITE_MODE_READABLE_WRITABLE:
        return STATE_OK
    if code == READ_WRITE_MODE_INACCESSIBLE:
        return STATE_CRIT
    if code == READ_WRITE_MODE_READ_ONLY:
        return read_only_state
    return STATE_WARN


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.')

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

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

    # fetch data
    # Asked in one request. The endpoint takes `offset` and `limit` rather than the
    # `range` object its siblings use, and the two REST Interface References disagree on
    # what `range` even means here, so paging it would be guesswork. The count endpoint
    # next to it settles the only question paging would have answered, namely whether
    # every namespace was listed.
    expected = None
    if args.TEST is None:
        result = lib.huawei_pacific.get_data('converged_service/namespaces', args)
        count = lib.huawei_pacific.get_data('converged_service/namespaces_count', args)
        # A failing count query is not fatal. It is a cross-check, not the data itself,
        # and a firmware that does not offer the endpoint must not take the check down.
        if lib.huawei_pacific.get_result_code(count) in (0, '0'):
            expected = lib.huawei_pacific.as_code(
                (count.get('data') or {}).get('count')
            )
    else:
        # do not call the API, put in test data. Each API call has its own fixture
        # suffix, so the fixture file names describe what they contain.
        test_base = args.TEST[0]
        result = lib.lftest.test_json(args.TEST, f'{test_base}-namespaces')
        expected = lib.huawei_pacific.as_code(
            (
                lib.lftest.test_json(args.TEST, f'{test_base}-count').get('data') or {}
            ).get('count')
        )

    # no valuable result?
    lib.huawei_pacific.assert_ok(result, 'the namespaces')

    # A cluster that serves storage has at least one namespace, 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.
    namespaces = result.get('data') or []
    if not namespaces:
        lib.base.oao(
            f'{args.URL} reported no namespaces.'
            ' Verify that the API user is allowed to query them.',
            STATE_UNKNOWN,
        )

    # The cluster counts its own namespaces, so a listing that is short of that count was
    # capped somewhere on the way. Reporting only what arrived would present a partial
    # inventory as a complete one, which is the one failure a check must not have.
    truncated = expected is not None and expected > len(namespaces)

    # init some vars
    msg = ''
    state = STATE_OK
    perfdata = ''
    table_data = []

    # compile user-supplied regex patterns
    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')
    ]
    read_only_state = lib.base.str2state(args.READ_ONLY_SEVERITY)

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

        # Only the normal code is documented, so anything else warns and is passed
        # through rather than being called a failure the vendor never named.
        running_status = lib.huawei_pacific.as_code(namespace.get('running_status'))
        running_state = (
            STATE_OK if running_status == RUNNING_STATUS_NORMAL else STATE_WARN
        )
        state = lib.base.get_worst(state, running_state)

        mode = lib.huawei_pacific.as_code(namespace.get('read_write_mode'))
        mode_state = get_read_write_mode_state(mode, read_only_state)
        state = lib.base.get_worst(state, mode_state)

        # The appliance counts the used space in the unit it names next to it, the same
        # way it reports a quota, and sends the placeholder of the field's data type
        # where it has nothing to report.
        space_used = lib.huawei_pacific.get_quota_bytes(
            namespace.get('space_used'), namespace.get('space_unit_type')
        )
        file_used = lib.huawei_pacific.as_code(namespace.get('file_used'))
        if file_used == lib.huawei_pacific.QUOTA_INVALID_VALUE64:
            file_used = None

        # Perfdata labels carry the namespace name, the way every sibling Pacific check
        # labels its objects.
        label = re.sub(
            r'\W+', '_', str(namespace.get('name') or namespace.get('id'))
        ).strip('_')
        perfdata += lib.base.get_perfdata(
            f'{label}_running_status',
            running_status,
            uom=None,
            _min=0,
        )
        perfdata += lib.base.get_perfdata(
            f'{label}_read_write_mode',
            mode,
            uom=None,
            _min=0,
            _max=READ_WRITE_MODE_INACCESSIBLE,
        )
        if space_used is not None:
            perfdata += lib.base.get_perfdata(
                f'{label}_space_used',
                space_used,
                uom='B',
                _min=0,
            )
        if file_used is not None:
            # A count of files, so it carries no unit of its own.
            perfdata += lib.base.get_perfdata(
                f'{label}_file_used',
                file_used,
                uom=None,
                _min=0,
            )

        row_state = lib.base.get_worst(running_state, mode_state)
        table_data.append(
            {
                'access': (
                    f'{READ_WRITE_MODES.get(mode, "Unknown")}'
                    f'{lib.base.state2str(mode_state, prefix=" ")}'
                ),
                'files': (
                    '--' if file_used is None else lib.human.number2human(file_used)
                ),
                'id': namespace.get('id'),
                'name': namespace.get('name'),
                'pool': namespace.get('storage_pool_id'),
                'protocol': PROTOCOL_TYPES.get(
                    lib.huawei_pacific.as_code(namespace.get('protocol_type')),
                    'Unknown',
                ),
                'row_state': row_state,
                # 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. The access column in front of it says
                # whether it was the mode rather than the namespace itself.
                'state': lib.base.state2str(row_state, empty_ok=False),
                'status': (
                    'normal (0)'
                    if running_status == RUNNING_STATUS_NORMAL
                    else f'not normal ({namespace.get("running_status")})'
                ),
                'used': (
                    '--' if space_used is None else lib.human.bytes2human(space_used)
                ),
            }
        )

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

    # The truncated walk raises the state before the summary is written, so a partially
    # read appliance does not open with "Everything is ok." and then exit WARNING.
    if truncated:
        state = lib.base.get_worst(state, STATE_WARN)

    # build the message
    # The count covers two independent findings, an access mode and a running status, so
    # it says "healthy" rather than naming one of them: a namespace with an unknown
    # status is not necessarily unreachable. Said the positive way round where there is
    # nothing wrong, because "0 not healthy" makes the reader resolve a double negative
    # on every glance.
    unhealthy = [row for row in table_data if row['row_state'] != STATE_OK]
    if state == STATE_CRIT:
        msg += 'There are critical errors.'
    elif state == STATE_WARN:
        msg += 'There are warnings.'
    else:
        msg += 'Everything is ok.'
    msg += (
        f' Checked {len(table_data)}'
        f' {lib.txt.pluralize("namespace", len(table_data))},'
        f'{f" {len(unhealthy)} not healthy." if unhealthy else " all healthy."}'
    )
    if truncated:
        msg += (
            f'\n\nThe cluster counts {expected} namespaces and listed'
            f' {len(namespaces)}; the list below is incomplete.'
        )

    # build table output
    if args.LENGTHY:
        keys = [
            'id',
            'name',
            'pool',
            'protocol',
            'used',
            'files',
            'access',
            'status',
            'state',
        ]
        headers = [
            'ID',
            'Name',
            'Pool',
            'Protocol',
            'Used',
            'Files',
            'Access',
            'Status',
            'State',
        ]
    else:
        keys = ['name', 'used', 'files', 'access', 'status', 'state']
        headers = ['Name', 'Used', 'Files', 'Access', 'Status', 'State']
    msg += '\n\n' + 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()
