#!/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__ = '2026081103'

DESCRIPTION = """Checks every disk of a Huawei OceanStor Pacific storage system via the REST API
(/data_service/diskpool and /cluster/diskpool/queryNodeDiskInfo endpoints). Alerts when a disk is
not healthy, and when its remaining life falls below the warning or critical threshold.
Supports extended reporting via --lengthy."""

DEFAULT_BRIEF = False
DEFAULT_CACHE_EXPIRE = 15  # minutes
DEFAULT_CRIT = '30:'
DEFAULT_INSECURE = True
DEFAULT_NO_MATCH_SEVERITY = 'ok'
DEFAULT_NO_PROXY = False
DEFAULT_SCOPE = '0'
DEFAULT_TIMEOUT = 3
DEFAULT_WARN = '180:'

# Fields `--match` is applied to. A disk has no identifier of its own that an
# operator would recognise, so the filter runs on where it sits and what it is.
MATCH_FIELDS = ('node', 'pool', 'serial', 'slot')


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(
        '--brief',
        help=lib.args.help('--brief')
        + ' Worth setting on a cluster with many disks. '
        'Default: %(default)s',
        dest='BRIEF',
        action='store_true',
        default=DEFAULT_BRIEF,
    )

    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 the remaining life of a disk, as a Nagios range in days. '
        'Default: %(default)s',
        dest='CRIT',
        default=DEFAULT_CRIT,
    )

    parser.add_argument(
        '--ignore',
        help='Skip disks. '
        + lib.args.help('--ignore-regex')
        + ' The regex is anchored at the start of the string (Python `re.match`) and is '
        'matched against the node name, the disk pool, the serial number and the slot, '
        '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 disks. '
        + lib.args.help('--match')
        + ' The regex is anchored at the start of the string (Python `re.match`) and is '
        'matched against the node name, the disk pool, the serial number and the slot, '
        '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(
        '-w',
        '--warning',
        help='WARN threshold for the remaining life of a disk, as a Nagios range in days. '
        'Default: %(default)s',
        dest='WARN',
        default=DEFAULT_WARN,
    )

    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_remaining_life_days(disk):
    """Return a disk's remaining life in days, or `None` if it does not report one."""
    # The appliance reports the remaining life in hours, and only for media that wear out.
    # A spinning disk has nothing to report and answers with zero or a negative value, which
    # must not be read as "this disk is at its end" - that would alert on every HDD forever.
    try:
        hours = int(disk.get('remainingLife'))
    except (TypeError, ValueError):
        return None
    if hours <= 0:
        return None
    return hours / 24


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
    # The disks are only reachable per disk pool, so the pools have to be enumerated
    # first. The disk listing itself lives below the appliance's older endpoint
    # generation, which is why it is queried with an explicit base path.
    if args.TEST is None:
        pools = lib.huawei_pacific.get_data('data_service/diskpool', args)
        lib.huawei_pacific.assert_ok(pools, 'the disk pools')
        disk_pools = {
            pool.get('poolId'): pool for pool in pools.get('diskPools', [])
        }
        pool_ids = list(disk_pools)
        per_pool = {}
        for pool_id in pool_ids:
            per_pool[pool_id] = lib.huawei_pacific.get_data(
                f'cluster/diskpool/queryNodeDiskInfo?diskPoolId={int(pool_id)}',
                args,
                base_path='dsware/service',
            )
    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]
        pools = lib.lftest.test_json(args.TEST, f'{test_base}-diskpools')
        lib.huawei_pacific.assert_ok(pools, 'the disk pools')
        disk_pools = {
            pool.get('poolId'): pool for pool in pools.get('diskPools', [])
        }
        pool_ids = list(disk_pools)
        per_pool = {
            pool_id: lib.lftest.test_json(args.TEST, f'{test_base}-disks-{pool_id}')
            for pool_id in pool_ids
        }

    # no valuable result?
    if not pool_ids:
        lib.base.oao('No disk pool configured, so there is no disk to check.', STATE_OK)
    for pool_id, result in per_pool.items():
        lib.huawei_pacific.assert_ok(result, f'the disks of disk pool {pool_id}')

    # 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
    # A pool that is faulty or stopped is a finding of its own: its disks may all report
    # healthy while the pool they belong to is not serving.
    pool_rows = []
    for pool_id, pool in disk_pools.items():
        pool_state = lib.huawei_pacific.get_pool_status_state(pool.get('poolStatus'))
        state = lib.base.get_worst(state, pool_state)
        pool_rows.append(
            {
                'name': pool.get('poolName', pool_id),
                'media': pool.get('mediaType', ''),
                'status': lib.huawei_pacific.get_pool_status(pool.get('poolStatus')),
                'state': lib.base.state2str(pool_state, empty_ok=False),
            }
        )

    table_data = []
    seen = set()
    for pool_id, result in per_pool.items():
        for node in result.get('nodeInfo', []):
            node_name = node.get('nodeName') or node.get('nodeMgrIp') or '--'
            for disk in node.get('mediaInfo', []):
                # An empty slot is not a disk. Reporting one would put a row without a
                # serial number, a type and a state into every table. `diskExist` is
                # 0 when a disk is present and 1 when the slot is empty.
                if lib.huawei_pacific.as_code(disk.get('diskExist')) == 1:
                    continue
                # A disk can be listed under more than one pool. Key on the node plus the
                # serial number so it is reported once, with its first pool.
                key = (node_name, disk.get('diskSn'))
                if key in seen:
                    continue
                seen.add(key)

                identity = {
                    'node': node_name,
                    'pool': pool_id,
                    'serial': disk.get('diskSn', '--'),
                    'slot': disk.get('slotDesc', '--'),
                }

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

                disk_state = lib.huawei_pacific.get_disk_status_state(
                    disk.get('diskStatus')
                )
                state = lib.base.get_worst(state, disk_state)

                days = get_remaining_life_days(disk)
                life_state = STATE_OK
                if days is not None:
                    life_state = lib.base.get_state(
                        days, args.WARN, args.CRIT, _operator='range'
                    )
                    state = lib.base.get_worst(state, life_state)

                # Keyed on the serial number, not the slot: a node numbers its SATA
                # slots and its SSD card slots from zero each, so the two disks in
                # slot 0 of the same node would otherwise share one label and only
                # one of them would reach the graph.
                label = re.sub(
                    r'\W+', '_', f'{node_name}_{disk.get("diskSn", "--")}'
                ).strip('_')
                perfdata += lib.base.get_perfdata(
                    f'{label}_status',
                    lib.huawei_pacific.as_code(disk.get('diskStatus')),
                    _min=0,
                )
                if days is not None:
                    perfdata += lib.base.get_perfdata(
                        f'{label}_remaining_life',
                        int(days * 86400),
                        uom='s',
                        _min=0,
                    )

                table_data.append(
                    {
                        'capacity': lib.human.bytes2human(
                            disk.get('mediaCapacityForByte', 0)
                        ),
                        'node': node_name,
                        'pool': pool_id,
                        'remaining_life': (
                            lib.human.seconds2human(int(days * 86400))
                            if days is not None
                            else 'not reported'
                        ),
                        'role': lib.huawei_pacific.get_disk_role(disk.get('diskRole')),
                        'serial': disk.get('diskSn', '--'),
                        'slot': disk.get('slotDesc', '--'),
                        'row_state': lib.base.get_worst(disk_state, life_state),
                        'state': lib.base.state2str(
                            lib.base.get_worst(disk_state, life_state),
                            empty_ok=False,
                        ),
                        'status': lib.huawei_pacific.get_disk_status(
                            disk.get('diskStatus')
                        ),
                        'type': lib.huawei_pacific.get_disk_type(disk.get('diskType')),
                    }
                )

    # The appliance listed disks and the filter selected none of them.
    if not table_data and args.MATCH:
        lib.base.oao(
            f'No disks 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 pool_rows:
        msg += lib.base.get_table(
            pool_rows,
            ['name', 'media', 'status', 'state'],
            header=['Pool', 'Media', 'Status', 'State'],
            missing='--',
            hide_empty=True,
        )
        msg += '\n'

    display_rows = table_data
    if args.BRIEF:
        display_rows = [row for row in table_data if row['row_state'] != STATE_OK]
    if display_rows:
        if args.LENGTHY:
            keys = [
                'node',
                'pool',
                'slot',
                'type',
                'role',
                'serial',
                'capacity',
                'remaining_life',
                'status',
                'state',
            ]
            headers = [
                'Node',
                'Pool',
                'Slot',
                'Type',
                'Role',
                'Serial',
                'Capacity',
                'Remaining Life',
                'Status',
                'State',
            ]
        else:
            keys = [
                'node',
                'pool',
                'slot',
                'capacity',
                'remaining_life',
                'status',
                'state',
            ]
            headers = [
                'Node',
                'Pool',
                'Slot',
                'Capacity',
                'Remaining Life',
                'Status',
                'State',
            ]
        msg += lib.base.get_table(
            display_rows, keys, header=headers, missing='--', hide_empty=True
        )
    elif not table_data:
        # `--brief` on a healthy cluster leaves nothing to print, and that is the point
        # of the switch. Only say something when the appliance really listed no disk.
        msg += 'Nothing checked, no disk found.'

    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()
