#!/usr/bin/env python3
# -*- 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.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__ = '2026092203'

DESCRIPTION = """Checks the health and running status of the LUNs of a Huawei OceanStor Dorado
storage system via the REST API (/lun endpoint). Alerts when a LUN reports a non-normal
state or when a HyperMetro LUN is not mapped to any host, and optionally when a thin
LUN fills up. Only LUNs mapped to a host and HyperMetro LUNs are checked by default.
Supports extended reporting via --lengthy, and reporting the I/O counters via
--performance."""

# Space allocation type of a thin LUN. A thick LUN has its whole capacity allocated by
# definition, so its usage is always 100% and says nothing about how full it is.
ALLOCTYPE_THIN = 1

# `CAPACITYALARMLEVEL`, documented in both REST Interface References as "VASA: thin LUN
# capacity alarm severity" and returned for thin LUNs only. Shown for information, not
# evaluated: the capacity thresholds of this check already cover how full a thin LUN is.
# On V700R001C10SPH128 (Dorado 6000 V6) the appliance reported 2 below 80% usage, 3 from
# 80% and 6 from 90% on all 697 LUNs.
CAPACITY_ALARM_LEVEL = {
    2: 'Normal (2)',
    3: 'Warning (3)',
    6: 'Critical (6)',
}

DEFAULT_BRIEF = False
DEFAULT_CACHE_EXPIRE = 15  # minutes; default session timeout period is 20 minutes
DEFAULT_CRIT = ''
DEFAULT_DEVICE_ID = ''  # the appliance reports its own at login
DEFAULT_DEVICE_THRESHOLD_SEVERITY = 'warn'
DEFAULT_INSECURE = True
DEFAULT_NO_MATCH_SEVERITY = 'ok'
DEFAULT_NO_PROXY = False
DEFAULT_SCOPE = '0'
DEFAULT_TIMEOUT = 30
DEFAULT_UNMAPPED_HYPERMETRO_SEVERITY = 'warn'
DEFAULT_UNMAPPED_SEVERITY = 'ok'
DEFAULT_WARN = ''

# Performance indicators this object supports, from the vendor's performance
# indicator tables. Read only when --performance is given.
PERFORMANCE_INDICATORS = (19, 21, 22, 23, 24, 25, 26, 27, 28, 370, 384, 385)

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

# An array can hold thousands of LUNs, so the walk needs a higher page cap than
# the checks that look at hardware. Both REST Interface References allow a range of
# up to 10000 results per request ("Interface for Batch Querying LUN Information",
# 3.6.2.23 in 6.1.0, 3.7.2.4.2 in V700R001C10), but a larger page does not make the
# walk faster: the appliance spends its time per LUN, not per request. Verified
# against V700R001C10SPH128 on a Dorado 6000 V6 with 697 LUNs: seven pages of 100
# took 82 s, one page of 1000 took 89 s. Small pages keep a single request short, so
# a retried page costs seconds rather than the whole run.
PAGE_SIZE = 100
MAX_PAGES = 200

# RUNNINGSTATUS code a healthy LUN reports: online (27). Both REST Interface
# References list offline (28), initializing (53) and deleting (106) as the other
# values for this object, next to HEALTHSTATUS normal (1), faulty (2) and write
# protected (15).
OK_RUNNING_STATUS = (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(
        '--brief',
        help=lib.args.help('--brief') + ' Worth setting on an array with many LUNs.',
        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 used capacity of a thin LUN, as a Nagios range in '
        'percent. Off by default, because a thin LUN that is full is doing what it was '
        'created for; what runs out is the pool behind it. Example: `--critical=95`',
        dest='CRIT',
        default=DEFAULT_CRIT,
    )

    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(
        '--device-threshold-severity',
        help='State to report for a thin LUN that reached the capacity alarm threshold '
        'the appliance keeps for it. The vendor documents that threshold as the capacity '
        'alarm for thin LUNs mounted to Windows Server 2012 hosts (50 to 99 percent, 90 '
        'by default), with a separate switch that turns it on. A LUN whose switch is off '
        'is not affected. '
        'Default: %(default)s',
        dest='DEVICE_THRESHOLD_SEVERITY',
        choices=['ok', 'warn', 'crit', 'unknown'],
        default=DEFAULT_DEVICE_THRESHOLD_SEVERITY,
    )

    parser.add_argument(
        '--ignore',
        help='Skip LUNs. '
        + lib.args.help('--ignore-regex')
        + ' The regex is anchored at the start of the string (Python `re.match`) and '
        'is matched against the LUN identifier, the LUN name and the name of its '
        'storage pool, so prefix with `.*` to match anywhere. Default: %(default)s',
        dest='IGNORE',
        action='append',
        default=None,
    )

    parser.add_argument(
        '--include-unmapped',
        help='Also check LUNs that are not mapped to any host. Those are not serving '
        'anything, so they are left out by default. HyperMetro LUNs are always '
        'checked, see `--unmapped-hypermetro-severity`.',
        dest='INCLUDE_UNMAPPED',
        action='store_true',
        default=False,
    )

    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 LUNs. '
        + lib.args.help('--match')
        + ' The regex is anchored at the start of the string (Python `re.match`) and '
        'is matched against the LUN identifier, the LUN name and the name of its '
        'storage pool, 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(
        '--performance',
        help='Additionally report the I/O counters of every LUN. '
        '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(
        '--proxy',
        help=lib.args.help('--proxy'),
        dest='PROXY',
        default=None,
    )

    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(
        '--unmapped-hypermetro-severity',
        help='State to report for a HyperMetro LUN that is not mapped to any host on '
        'this array. Hosts then reach the LUN only through the remote array, so losing '
        'that array or the link to it cuts them off, and the appliance raises an alarm '
        'for it as well. Such LUNs are checked even without `--include-unmapped`. '
        'Default: %(default)s',
        dest='UNMAPPED_HYPERMETRO_SEVERITY',
        choices=['ok', 'warn', 'crit', 'unknown'],
        default=DEFAULT_UNMAPPED_HYPERMETRO_SEVERITY,
    )

    parser.add_argument(
        '--unmapped-severity',
        help='State to report for a LUN that is not mapped to any host. Only takes '
        'effect together with `--include-unmapped`, which is what brings those LUNs into '
        'the check in the first place. Worth raising on an array where every LUN is meant '
        'to be in use, so a LUN that dropped out of its mapping view is noticed. '
        'Does not apply to HyperMetro LUNs, see `--unmapped-hypermetro-severity`. '
        'Default: %(default)s',
        dest='UNMAPPED_SEVERITY',
        choices=['ok', 'warn', 'crit', 'unknown'],
        default=DEFAULT_UNMAPPED_SEVERITY,
    )

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

    parser.add_argument(
        '-w',
        '--warning',
        help='WARN threshold for the used capacity of a thin LUN, as a Nagios range in '
        'percent. Off by default, because a thin LUN that is full is doing what it was '
        'created for; what runs out is the pool behind it. Example: `--warning=85`',
        dest='WARN',
        default=DEFAULT_WARN,
    )

    args, _ = parser.parse_known_args()
    return args


def is_true(value):
    """Return whether the appliance reported a boolean field as true."""
    # The API sends its booleans as the strings 'true' and 'false', but a firmware that
    # sends a real boolean must not be read as false.
    return str(value).strip().lower() == 'true'


def is_hypermetro(lun):
    """
    Return whether a LUN is a member of a HyperMetro pair.

    Parameters
    ----------
    lun : dict
        One LUN as the API returned it.

    Returns
    -------
    bool
        `True` if the LUN's list of value-added services marks HyperMetro as in use.
        `False` if it does not, and if the list is missing or unreadable.

    Examples
    --------
    >>> is_hypermetro({'HASRSSOBJECT': '{"SnapShot":"FALSE","HyperMetro":"TRUE"}'})
    True
    """
    # The REST Interface Reference types `HASRSSOBJECT` as `string(json)`: a JSON object
    # serialised into a string, one key per value-added service with "TRUE" or "FALSE".
    # Verified against V700R001C10SPH128 on a Dorado 6000 V6. A firmware that sends the
    # object itself is accepted as well, and anything else reads as "no HyperMetro"
    # rather than crashing the check.
    services = lun.get('HASRSSOBJECT')
    if isinstance(services, str):
        try:
            services = json.loads(services)
        except ValueError:
            return False
    if not isinstance(services, dict):
        return False
    return is_true(services.get('HyperMetro'))


def get_usage_percent(lun):
    """
    Return a thin LUN's used capacity in percent, or `None` if it has none to report.

    Parameters
    ----------
    lun : dict
        One LUN as the API returned it.

    Returns
    -------
    float or None
        The used capacity in percent. `None` for a thick LUN, whose
        capacity is fully allocated by definition, and for a LUN that is still being
        created, which the appliance answers for without the usage field.

    Examples
    --------
    >>> get_usage_percent({'ALLOCTYPE': '1', 'THINCAPACITYUSAGE': '42'})
    42.0
    """
    if lib.huawei_dorado.as_code(lun.get('ALLOCTYPE')) != ALLOCTYPE_THIN:
        return None
    # The appliance computes the ratio itself and leaves the field out while a LUN is
    # being created, which is why it is read before falling back to the raw capacities.
    reported = lib.huawei_dorado.as_code(lun.get('THINCAPACITYUSAGE'))
    if reported is not None:
        return float(reported)
    capacity = lib.huawei_dorado.as_code(lun.get('CAPACITY'))
    allocated = lib.huawei_dorado.as_code(lun.get('ALLOCCAPACITY'))
    if not capacity or allocated is None:
        return None
    return round(allocated / capacity * 100, 1)


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
    truncated = False
    if args.TEST is None:
        result, truncated = lib.huawei_dorado.get_all_data(
            'lun', args, page_size=PAGE_SIZE, max_pages=MAX_PAGES
        )
    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 LUNs')

    # init some vars
    msg = ''
    state = STATE_OK
    allocated_sum = None
    capacity_sum = None
    luns_not_ok = 0
    perfdata = ''
    performance_perfdata = ''
    usage_percent_max = None
    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')
    ]
    device_threshold_state = lib.base.str2state(args.DEVICE_THRESHOLD_SEVERITY)
    unmapped_hypermetro_count = 0
    unmapped_hypermetro_state = lib.base.str2state(args.UNMAPPED_HYPERMETRO_SEVERITY)
    unmapped_state = lib.base.str2state(args.UNMAPPED_SEVERITY)

    # analyze data
    table_data = []
    for lun in result.get('data') or []:
        lun['UUID'] = lib.huawei_dorado.get_uuid(lun)

        # An unmapped HyperMetro LUN is checked regardless: it is typically the local
        # side of a pair whose hosts only have a path to the remote array, which the
        # appliance itself alarms on ("The Local Array Has HyperMetro LUNs That Are Not
        # Mapped To The Host"). Any other unmapped LUN, a leftover or a snapshot for
        # example, is not serving anything.
        mapped = is_true(lun.get('EXPOSEDTOINITIATOR'))
        hypermetro = is_hypermetro(lun)
        if not mapped and not hypermetro and not args.INCLUDE_UNMAPPED:
            continue

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

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

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

        usage_percent = get_usage_percent(lun)
        usage_state = STATE_OK
        if usage_percent is not None and (args.WARN or args.CRIT):
            usage_state = lib.base.get_state(
                usage_percent, args.WARN or None, args.CRIT or None, _operator='range'
            )
            state = lib.base.get_worst(state, usage_state)

        # The appliance carries a capacity alarm threshold per LUN, which the REST
        # Interface References describe as the one for thin LUNs mounted to Windows
        # Server 2012 hosts (50 to 99, default 90), and a switch saying whether it is
        # in use at all. Verified against V700R001C10SPH128 on a Dorado 6000 V6: all
        # 697 LUNs report the default 90 with the switch off.
        device_state = STATE_OK
        device_threshold = lib.huawei_dorado.as_code(lun.get('ISCSITHINLUNTHRESHOLD'))
        if (
            usage_percent is not None
            and is_true(lun.get('ENABLEISCSITHINLUNTHRESHOLD'))
            and device_threshold
            and 0 < device_threshold <= 100
            and usage_percent >= device_threshold
        ):
            device_state = device_threshold_state
            state = lib.base.get_worst(state, device_state)

        # A plain unmapped LUN is only reached at all with --include-unmapped, which is
        # why each kind of unmapped LUN has a severity knob of its own.
        unmapped_lun_state = STATE_OK
        if not mapped:
            if hypermetro:
                unmapped_hypermetro_count += 1
                unmapped_lun_state = unmapped_hypermetro_state
            else:
                unmapped_lun_state = unmapped_state
            state = lib.base.get_worst(state, unmapped_lun_state)

        capacity = lib.huawei_dorado.sectors2bytes(lun.get('CAPACITY'))
        allocated = lib.huawei_dorado.sectors2bytes(lun.get('ALLOCCAPACITY'))

        # The performance data summarizes the LUNs instead of graphing each one: an
        # array can hold thousands of them, and their status codes are judged above
        # already. Per-LUN detail is in the table.
        if capacity is not None:
            capacity_sum = (capacity_sum or 0) + capacity
        if allocated is not None:
            allocated_sum = (allocated_sum or 0) + allocated
        if usage_percent is not None:
            usage_percent_max = (
                usage_percent
                if usage_percent_max is None
                else max(usage_percent_max, usage_percent)
            )

        row_state = lib.base.get_worst(
            lib.base.get_worst(health_state, running_state),
            lib.base.get_worst(
                usage_state, lib.base.get_worst(device_state, unmapped_lun_state)
            ),
        )
        if row_state != STATE_OK:
            luns_not_ok += 1
        lun['allocated'] = (
            lib.human.bytes2human(allocated)
            if allocated is not None
            else 'not reported'
        )
        lun['capacity'] = (
            lib.human.bytes2human(capacity) if capacity is not None else 'not reported'
        )
        # The counters come from a second endpoint, which a fixture cannot stand
        # in for. `lib.huawei_dorado.get_performance()` covers that path. They are
        # reported per LUN, which is why they are opt-in. Their labels carry the
        # object's own TYPE:ID, which stays the same when a LUN is renamed, unlike its
        # name.
        if args.PERFORMANCE and args.TEST is None:
            samples = lib.huawei_dorado.get_performance(
                lun['UUID'], PERFORMANCE_INDICATORS, args
            )
            performance_perfdata += lib.huawei_dorado.get_performance_perfdata(
                re.sub(r'\W+', '_', lun['UUID']), samples
            )

        capacity_alarm_level = lib.huawei_dorado.as_code(lun.get('CAPACITYALARMLEVEL'))
        if capacity_alarm_level is not None:
            lun['capacity_alarm'] = CAPACITY_ALARM_LEVEL.get(
                capacity_alarm_level, 'Unknown'
            )
        lun['health'] = lib.huawei_dorado.get_health_status(lun.get('HEALTHSTATUS'))
        lun['row_state'] = row_state
        lun['is_mapped'] = mapped
        if mapped:
            lun['mapped'] = 'yes'
        else:
            lun['mapped'] = (
                f'no{" (HyperMetro)" if hypermetro else ""}'
                f'{lib.base.state2str(unmapped_lun_state, prefix=" ")}'
            )
        # The row's State column is the worst of everything evaluated for the LUN. A
        # threshold that fired is also marked on the value that caused it (Usage,
        # Mapped), the way Health and Running name the code that decided them.
        lun['running'] = lib.huawei_dorado.get_running_status(lun.get('RUNNINGSTATUS'))
        lun['state'] = lib.base.state2str(lun['row_state'], empty_ok=False)
        lun['thin'] = (
            'thin'
            if lib.huawei_dorado.as_code(lun.get('ALLOCTYPE')) == ALLOCTYPE_THIN
            else 'thick'
        )
        # Both the operator's thresholds and the appliance's own limit judge this
        # number, so the cell carries the worse of the two. Marking it with only one of
        # them left a `--warning` breach invisible in the row that caused it.
        fill_state = lib.base.get_worst(usage_state, device_state)
        lun['usage'] = (
            f'{usage_percent:.0f}%{lib.base.state2str(fill_state, prefix=" ")}'
            if usage_percent is not None
            else 'n/a'
        )

        table_data.append(lun)

    if not table_data:
        # Either the filter selected nothing, or the array has no mapped LUN at all. The
        # second is unusual but legitimate, for example on an array being set up.
        lib.base.oao(
            f'No LUNs matched `{", ".join(args.MATCH)}`.'
            if args.MATCH
            else 'No mapped LUNs found.',
            lib.base.str2state(args.NO_MATCH_SEVERITY) if args.MATCH else STATE_OK,
            always_ok=args.ALWAYS_OK,
            no_perfdata=args.NO_PERFDATA,
        )

    # build the message
    # 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)

    count = len(table_data)
    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 {count} {lib.txt.pluralize("LUN", count)}.'
    if unmapped_hypermetro_count and unmapped_hypermetro_state != STATE_OK:
        msg += (
            f' {unmapped_hypermetro_count} HyperMetro'
            f' {lib.txt.pluralize("LUN", unmapped_hypermetro_count)}'
            f' {"is" if unmapped_hypermetro_count == 1 else "are"} not mapped to any'
            ' host on this array.'
        )
    msg += '\n'
    perfdata += lib.base.get_perfdata(
        'luns',
        count,
        uom=None,
        _min=0,
    )
    perfdata += lib.base.get_perfdata(
        'luns_not_ok',
        luns_not_ok,
        uom=None,
        _min=0,
    )
    if capacity_sum is not None:
        perfdata += lib.base.get_perfdata(
            'capacity',
            capacity_sum,
            uom='B',
            _min=0,
        )
    if allocated_sum is not None:
        perfdata += lib.base.get_perfdata(
            'allocated_capacity',
            allocated_sum,
            uom='B',
            _min=0,
            _max=capacity_sum,
        )
    if usage_percent_max is not None:
        perfdata += lib.base.get_perfdata(
            'usage_percent_max',
            usage_percent_max,
            uom='%',
            warn=args.WARN or None,
            crit=args.CRIT or None,
            _min=0,
            _max=100,
        )
    perfdata += performance_perfdata
    if truncated:
        # The walk hit its page cap, so LUNs beyond it were never looked at.
        msg += (
            'The appliance reports more LUNs than this check reads in one run;'
            ' the list below is incomplete.\n'
        )
    msg += '\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 = [
                'UUID',
                'NAME',
                'PARENTNAME',
                'thin',
                'mapped',
                'allocated',
                'capacity',
                'usage',
                'capacity_alarm',
                'WWN',
                'OWNINGCONTROLLER',
                'health',
                'running',
                'state',
            ]
            headers = [
                'UUID',
                'Name',
                'Pool',
                'Type',
                'Mapped',
                'Allocated',
                'Capacity',
                'Usage',
                'Capacity Alarm',
                'WWN',
                'Controller',
                'Health',
                'Running',
                'State',
            ]
        else:
            keys = [
                'UUID',
                'NAME',
                'PARENTNAME',
                'allocated',
                'capacity',
                'usage',
                'health',
                'running',
                'state',
            ]
            headers = [
                'UUID',
                'Name',
                'Pool',
                'Allocated',
                'Capacity',
                'Usage',
                'Health',
                'Running',
                'State',
            ]
            # An unmapped row can be raised by its severity knob alone, so the column
            # that says why has to be there; without such rows it would read "yes" on
            # every row.
            if any(not row['is_mapped'] for row in display_rows):
                keys.insert(3, 'mapped')
                headers.insert(3, 'Mapped')
        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()
