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

DESCRIPTION = """Checks the health, link status and optical power of the optical modules (SFP) of a
Huawei OceanStor Dorado storage system via the REST API (/sfp endpoint). Alerts when a module
reports a non-normal health status, when its receive or transmit power leaves the range the module
itself reports as its operating range, and optionally when its link is down. A degrading transceiver
or a dirty connector shows up as falling receive power long before the link drops.
Supports extended reporting via --lengthy."""

DEFAULT_BRIEF = False
DEFAULT_CACHE_EXPIRE = 15  # minutes; default session timeout period is 20 minutes
DEFAULT_DEVICE_ID = ''  # the appliance reports its own at login
DEFAULT_INSECURE = True
DEFAULT_LINK_DOWN_SEVERITY = 'ok'
DEFAULT_NO_MATCH_SEVERITY = 'ok'
DEFAULT_NO_PROXY = False
DEFAULT_RX_POWER_CRIT = ''
DEFAULT_RX_POWER_WARN = ''
DEFAULT_SCOPE = '0'
DEFAULT_TIMEOUT = 3
DEFAULT_TX_POWER_CRIT = ''
DEFAULT_TX_POWER_WARN = ''

# The optical power fields are counted in units of 0.1 microwatt, and the appliance
# reports this value for a reading it does not have. It is the largest 32-bit unsigned
# integer, not a measurement.
INVALID_VALUE32 = 4294967295

# 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

# RUNNINGSTATUS code of a port whose link is down. These endpoints use their own
# enumeration: 0 unknown, 10 link up, 11 link down, and 33 to be recovered on
# Ethernet ports.
LINK_DOWN = 11

# Fields `--match` is applied to. Unlike every other object on this appliance, an SFP
# reports its fields in camelCase and has no `TYPE`, so `lib.huawei_dorado.get_uuid()`
# does not apply here and the module is identified by its location.
MATCH_FIELDS = ('id', 'location', 'vendor', 'model', 'sn')

# RUNNINGSTATUS code a healthy port reports: link up (10).
OK_RUNNING_STATUS = (10,)

# What the `parentType` of a module names, so the output says what the module sits in
# rather than repeating a number.
PARENT_TYPES = {
    207: 'controller',
    208: 'expansion module',
    209: 'interface module',
}

# The field names of the optical power readings and of the operating range the module
# reports for them. The REST Interface Reference documents these in camelCase in its
# parameter table and in upper case in the response example on the same page, so both
# spellings are tried.
POWER_FIELDS = {
    'rx': (
        ('rxPowerReal', 'RXPOWER'),
        ('rxPowerMin', 'RXPOWERMIN'),
        ('rxPowerMax', 'RXPOWERMAX'),
    ),
    'tx': (
        ('txPowerReal', 'TXPOWER'),
        ('txPowerMin', 'TXPOWERMIN'),
        ('txPowerMax', 'TXPOWERMAX'),
    ),
}

# `sfpModeType` values.
SFP_MODE_TYPES = {
    0: 'single-mode',
    1: 'multi-mode',
}


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 an array with many optical modules. '
        '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(
        '--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 optical modules. '
        + lib.args.help('--ignore-regex')
        + ' The regex is anchored at the start of the string (Python `re.match`) and '
        'is matched against the module identifier, its location, vendor, model and '
        'serial number, 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(
        '--link-down-severity',
        help=lib.args.help('--link-down-severity') + ' Default: %(default)s',
        dest='LINK_DOWN_SEVERITY',
        choices=['ok', 'warn', 'crit', 'unknown'],
        default=DEFAULT_LINK_DOWN_SEVERITY,
    )

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

    parser.add_argument(
        '--match',
        help='Limit to optical modules. '
        + lib.args.help('--match')
        + ' The regex is anchored at the start of the string (Python `re.match`) and '
        'is matched against the module identifier, its location, vendor, model and '
        'serial number, 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 Dorado API password.',
        dest='PASSWORD',
    )

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

    parser.add_argument(
        '--rx-power-critical',
        help='CRIT threshold for the receive power of a module, as a Nagios range in '
        'dBm. '
        'Defaults to the operating range the module itself reports, so a transceiver is '
        'judged against its own data sheet rather than against one number for the whole '
        'appliance. '
        'Example: `--rx-power-critical=-14:0`',
        dest='RX_POWER_CRIT',
        default=DEFAULT_RX_POWER_CRIT,
    )

    parser.add_argument(
        '--rx-power-warning',
        help='WARN threshold for the receive power of a module, as a Nagios range in '
        'dBm. '
        'Example: `--rx-power-warning=-12:-1`',
        dest='RX_POWER_WARN',
        default=DEFAULT_RX_POWER_WARN,
    )

    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(
        '--tx-power-critical',
        help='CRIT threshold for the transmit power of a module, as a Nagios range in '
        'dBm. '
        'Defaults to the operating range the module itself reports. '
        'Example: `--tx-power-critical=-9:3`',
        dest='TX_POWER_CRIT',
        default=DEFAULT_TX_POWER_CRIT,
    )

    parser.add_argument(
        '--tx-power-warning',
        help='WARN threshold for the transmit power of a module, as a Nagios range in '
        'dBm. '
        'Example: `--tx-power-warning=-8:2`',
        dest='TX_POWER_WARN',
        default=DEFAULT_TX_POWER_WARN,
    )

    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(
        '-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 as_dbm(tenth_microwatts):
    """
    Convert an optical power reading into dBm.

    The appliance reports optical power in units of 0.1 microwatt. Transceiver data
    sheets, and every other tool an engineer compares a reading against, state it in dBm.

    ### Parameters
    - **tenth_microwatts** (`int`, `str` or `None`): The reading as the API reported it.

    ### Returns
    - **float** or **None**: The power in dBm, rounded to two decimals, or `None` for a
      value that cannot be used.

    ### Notes
    - Zero is not a reading but the absence of light, and dBm is undefined for it. So is
      the appliance's `4294967295` marker for a value it does not have. Both yield `None`,
      which keeps them out of the performance data instead of graphing minus infinity.

    ### Example
    >>> as_dbm('10000')
    0.0

    >>> as_dbm('1000')
    -10.0

    >>> as_dbm('4294967295') is None
    True
    """
    value = lib.huawei_dorado.as_code(tenth_microwatts)
    if value is None or value <= 0 or value >= INVALID_VALUE32:
        return None
    # 0.1 uW -> mW, then the usual decibel-milliwatt definition.
    return round(10 * math.log10(value / 10000), 2)


def get_power(module, fields):
    """
    Read one optical power reading and the operating range the module reports for it.

    ### Parameters
    - **module** (`dict`): One optical module as the API returned it.
    - **fields** (`tuple`): The reading, minimum and maximum field names to try, each as
      a tuple of the spellings the vendor documents.

    ### Returns
    - **tuple** (`float` or `None`, `float` or `None`, `float` or `None`):
      The reading and its lower and upper bound, all in dBm.

    ### Notes
    - The reading is documented as an array, because a module with several lanes reports
      one value per lane. The first usable lane is taken: a check reports whether the
      module has light, and a per-lane breakdown belongs in a diagnosis, not in a
      threshold.
    - A module that does not report its operating range yields `None` for the bounds, and
      the caller then has nothing to compare against unless the operator supplied a range.

    ### Example
    >>> get_power({'RXPOWER': '[10000]', 'RXPOWERMIN': '1000'}, POWER_FIELDS['rx'])
    (0.0, -10.0, None)
    """
    reading_names, min_names, max_names = fields

    raw = lib.huawei_dorado.field(module, *reading_names)
    lanes = raw if isinstance(raw, list) else str(raw or '').strip('[]').split(',')
    reading = next(
        (dbm for dbm in (as_dbm(lane) for lane in lanes) if dbm is not None), None
    )

    lower = as_dbm(lib.huawei_dorado.field(module, *min_names))
    upper = as_dbm(lib.huawei_dorado.field(module, *max_names))
    return reading, lower, upper


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('sfp', 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 optical modules')

    modules = result.get('data') or []

    # An array with no optical module at all is a plausible array: a purely SAS-attached
    # one has none, and the endpoint itself only exists from V700R001C10 on. Reporting
    # the harmless reading beats alerting on every such array forever.
    if not modules:
        lib.base.oao(
            'No optical modules found. An array with no optical connectivity has none,'
            ' and firmware older than V700R001C10 does not serve this endpoint.',
            STATE_OK,
        )

    # 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')
    ]
    link_down_state = lib.base.str2state(args.LINK_DOWN_SEVERITY)

    # analyze data
    table_data = []
    for module in modules:
        # An SFP carries no TYPE, so there is no TYPE:ID to build a label from. Its
        # location is the only stable identifier it has, and it is also what an
        # engineer reads off the chassis.
        label = re.sub(r'\W+', '_', str(module.get('location', module.get('id', ''))))

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

        health_state = lib.huawei_dorado.get_health_status_state(
            module.get('healthStatus')
        )
        state = lib.base.get_worst(state, health_state)

        # A module whose link is down looks exactly like one nobody cabled, so how
        # loud that should be is the operator's call rather than this check's.
        if lib.huawei_dorado.as_code(module.get('runningStatus')) == LINK_DOWN:
            running_state = link_down_state
        else:
            running_state = lib.huawei_dorado.get_running_status_state(
                module.get('runningStatus'), OK_RUNNING_STATUS
            )
        state = lib.base.get_worst(state, running_state)

        perfdata += lib.base.get_perfdata(
            f'{label}_health_status',
            module.get('healthStatus'),
            uom=None,
            _min=0,
            _max=HEALTH_STATUS_MAX,
        )
        perfdata += lib.base.get_perfdata(
            f'{label}_running_status',
            module.get('runningStatus'),
            uom=None,
            _min=0,
        )

        perfdata += lib.base.get_perfdata(
            f'{label}_speed',
            lib.huawei_dorado.as_code(module.get('speed')),
            uom=None,
            _min=0,
        )

        module_state = lib.base.get_worst(health_state, running_state)

        # A degrading transceiver or a dirty connector shows up as falling receive
        # power long before the link drops, so this is the reading worth watching.
        for direction, thresholds in (
            ('rx', (args.RX_POWER_WARN, args.RX_POWER_CRIT)),
            ('tx', (args.TX_POWER_WARN, args.TX_POWER_CRIT)),
        ):
            reading, lower, upper = get_power(module, POWER_FIELDS[direction])
            warn, crit = thresholds
            # Without an operator-supplied range, the module's own operating range is
            # what it is judged against: a data sheet per transceiver beats one number
            # for the whole appliance. A module that reports its bounds the wrong way
            # round is skipped rather than turned into an invalid Nagios range, which
            # would end the whole check in UNKNOWN without naming the module.
            if not crit and lower is not None and upper is not None and lower < upper:
                crit = f'{lower}:{upper}'

            power_state = STATE_OK
            if reading is not None and (warn or crit):
                power_state = lib.base.get_state(
                    reading, warn or None, crit or None, _operator='range'
                )
                state = lib.base.get_worst(state, power_state)
                module_state = lib.base.get_worst(module_state, power_state)

            perfdata += lib.base.get_perfdata(
                f'{label}_{direction}_power',
                reading,
                uom=None,
                warn=warn or None,
                crit=crit or None,
            )
            module[f'{direction}_power'] = (
                '--'
                if reading is None
                else f'{reading}{lib.base.state2str(power_state, prefix=" ")}'
            )

        module['row_state'] = module_state
        module['health'] = lib.huawei_dorado.get_health_status(
            module.get('healthStatus')
        )
        module['link'] = lib.huawei_dorado.get_running_status(
            module.get('runningStatus')
        )
        module['mode'] = SFP_MODE_TYPES.get(
            lib.huawei_dorado.as_code(module.get('sfpModeType')), 'unknown'
        )
        # 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.
        module['state'] = lib.base.state2str(module['row_state'], empty_ok=False)
        module['sits_in'] = PARENT_TYPES.get(
            lib.huawei_dorado.as_code(module.get('parentType')), 'unknown'
        )

        table_data.append(module)

    # The appliance listed modules and the filter selected none of them.
    if not table_data:
        lib.base.oao(
            f'No optical modules 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
    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 = [
                'location',
                'sits_in',
                'vendor',
                'model',
                'mode',
                'speed',
                'rx_power',
                'tx_power',
                'link',
                'health',
                'state',
            ]
            headers = [
                'Location',
                'Sits In',
                'Vendor',
                'Model',
                'Mode',
                'Mbit/s',
                'Rx (dBm)',
                'Tx (dBm)',
                'Link',
                'Health',
                'State',
            ]
        else:
            keys = [
                'location',
                'sits_in',
                'speed',
                'rx_power',
                'tx_power',
                'link',
                'health',
                'state',
            ]
            headers = [
                'Location',
                'Sits In',
                'Mbit/s',
                'Rx (dBm)',
                'Tx (dBm)',
                'Link',
                'Health',
                'State',
            ]

        msg += lib.base.get_table(
            display_rows, 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()
