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

import lib.args
import lib.base
import lib.lftest
import lib.redfish
import lib.time
import lib.txt
from lib.globals import STATE_CRIT, STATE_OK, STATE_UNKNOWN, STATE_WARN

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

DESCRIPTION = """Checks the event log entries exposed under the LogServices of a Redfish-compatible
server via the Redfish API. Alerts when a log entry has the severity "Warning" or "Critical".
By default it reads the System Event Log (SEL); `--log-type` selects the management controller
log (MEL) or both.
Entries can be filtered by regular expression (--match, --ignore), and entries older than --max-age
days can be aged out so a long-since resolved event does not keep the check in a non-OK state
forever."""

API_BASE = '/redfish/v1'
DEFAULT_CACHE_EXPIRE = (
    5  # minutes; also caches API responses, kept below the session timeout
)
DEFAULT_INSECURE = True
DEFAULT_LOG_TYPE = 'sel'
DEFAULT_MAX_AGE = 0  # days; 0 disables aging
DEFAULT_NO_PROXY = False
DEFAULT_RETRIES = 3  # extra attempts on a failed Redfish request
DEFAULT_TIMEOUT = 8
DEFAULT_VERBOSE = False

# Per-vendor Ids of the LogService that holds the SEL (System Event Log) and the MEL
# (management controller event log), in order of preference. The check does not build a
# path from them: it looks them up among the LogServices the managers and systems
# advertise, because vendors keep the same log in different places (HPE the IML under
# Systems, the IEL under Managers). Where no Id matches, the SEL is the log service of
# type "SEL". The SEL Ids are exercised against fixtures and mockups; the MEL Ids are
# ported 1:1 from bb-Ricardo/check_redfish and still need real-hardware verification,
# which is why --log-type defaults to "sel". An empty list means "no known log".
LOG_SERVICE_IDS = {
    'ami': {'sel': ['BIOS'], 'mel': ['EventLog']},
    # Avigilon sells relabeled Dell servers, whose iDRAC keeps Dell's logs
    'avigilon': {'sel': ['Sel'], 'mel': ['Lclog']},
    'cisco': {'sel': ['SEL'], 'mel': ['CIMC']},
    'dell': {'sel': ['Sel'], 'mel': ['Lclog']},
    # the DMTF mockups name the SEL "Log", "Log1" or "SEL"
    'generic': {'sel': ['Log', 'Log1', 'SEL'], 'mel': []},
    'hp': {'sel': ['IML'], 'mel': ['IEL']},
    'hpe': {'sel': ['IML'], 'mel': ['IEL']},
    'lenovo': {'sel': ['ActiveLog'], 'mel': ['StandardLog']},
    'supermicro': {'sel': ['Log1'], 'mel': []},
    'ts_fujitsu': {'sel': ['SystemEventLog'], 'mel': ['InternalEventLog']},
}


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='Ignore log entries whose message matches this Python regular expression. '
        'Case-sensitive by default; use `(?i)` for case-insensitive matching. '
        'Can be specified multiple times. '
        'Example: `--ignore="Log area reset/cleared"`.',
        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(
        '--log-type',
        help='Which log to read: `sel` (System Event Log, default), `mel` (management controller '
        'event log) or `both`. '
        'Default: %(default)s',
        dest='LOG_TYPE',
        choices=['sel', 'mel', 'both'],
        default=DEFAULT_LOG_TYPE,
    )

    parser.add_argument(
        '--match',
        help='Only consider log entries whose message matches this Python regular expression. '
        'Case-sensitive by default; use `(?i)` for case-insensitive matching. '
        'Can be specified multiple times. '
        + lib.args.MATCH_IGNORE_PRECEDENCE
        + ' Example: `--match="(?i)temperature"`.',
        dest='MATCH',
        action='append',
        default=None,
    )

    parser.add_argument(
        '--max-age',
        help='Age out log entries older than this many days: they are no longer alerted on, only '
        'counted in the summary. A controller keeps an entry until the log is cleared, so a '
        'long-since resolved event would otherwise keep the check in a non-OK state forever. '
        'Default: %(default)s (0 disables aging).',
        dest='MAX_AGE',
        type=int,
        default=DEFAULT_MAX_AGE,
    )

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

    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='Redfish API password.',
        dest='PASSWORD',
    )

    parser.add_argument(
        '--proxy',
        help=lib.args.help('--proxy'),
        dest='PROXY',
        default=None,
    )

    parser.add_argument(
        '--retries',
        help='Number of extra attempts if a request to the Redfish API fails, before the '
        'check gives up. Helps against an occasionally slow or flaky management controller. '
        'Default: %(default)s',
        dest='RETRIES',
        type=int,
        default=DEFAULT_RETRIES,
    )

    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(
        '--url',
        help='Redfish API URL.',
        dest='URL',
        required=True,
    )

    parser.add_argument(
        '--username',
        help='Redfish API username.',
        dest='USERNAME',
    )

    parser.add_argument(
        '--verbose',
        help=lib.args.help('--verbose') + ' ' + lib.redfish.VERBOSE_HELP,
        dest='VERBOSE',
        action='store_true',
        default=DEFAULT_VERBOSE,
    )

    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)

    # --verbose: record every Redfish response for the output, where a bug report can pick
    # them up, and trace every request to a file. A file as well, because a check slow enough
    # to need diagnosing is usually one the monitoring server terminates for exceeding its
    # timeout, and a terminated check prints nothing at all.
    if args.VERBOSE:
        success, trace_path = lib.redfish.start_trace()
        if not success:
            lib.base.cu(trace_path)
        lib.redfish.record_responses()

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

    # compile the filter regexes and work out the age cutoff once
    ignore_patterns = [
        lib.base.coe(p) for p in lib.txt.compile_regex(args.IGNORE, '--ignore')
    ]
    match_patterns = [
        lib.base.coe(p) for p in lib.txt.compile_regex(args.MATCH, '--match')
    ]
    cutoff_epoch = int(lib.time.now()) - args.MAX_AGE * 86400 if args.MAX_AGE else 0

    # fetch data
    if args.TEST is not None:
        # do not call the API, replay the responses a --verbose run recorded instead. The
        # code below then walks them exactly as it would walk the controller.
        stdout, _, _ = lib.lftest.test(args.TEST)
        lib.base.coe(lib.redfish.replay(stdout))
    if not args.URL.startswith('http'):
        lib.base.cu('--url parameter has to start with "http://" or https://".')
    header = {'Accept': 'application/json'}
    # cache_expire (seconds) enables the lib fetch layer's shared per-URL cache,
    # so sibling Redfish checks on this host share one session and each fetch.
    cache_expire = args.CACHE_EXPIRE * 60
    header.update(lib.redfish.get_auth_header(args, cache_expire=cache_expire))
    expand = lib.redfish.get_expand_suffix(
        args.URL,
        header=header,
        insecure=args.INSECURE,
        no_proxy=args.NO_PROXY,
        proxy=args.PROXY,
        timeout=args.TIMEOUT,
        retries=args.RETRIES,
        cache_expire=cache_expire,
    )
    # service root: figure out the vendor to pick the entry point, read once via
    # the lib fetch layer and cached so the sibling Redfish checks on this host
    # reuse it within the cache window instead of re-reading it.
    root_url = f'{args.URL}{API_BASE}/'
    result = lib.base.coe(
        lib.redfish.fetch_resource(
            root_url,
            header=header,
            insecure=args.INSECURE,
            no_proxy=args.NO_PROXY,
            proxy=args.PROXY,
            timeout=args.TIMEOUT,
            retries=args.RETRIES,
            cache_expire=cache_expire,
        )
    )
    vendor = lib.redfish.get_vendor(result)
    fetch_args = {
        'header': header,
        'insecure': args.INSECURE,
        'no_proxy': args.NO_PROXY,
        'proxy': args.PROXY,
        'timeout': args.TIMEOUT,
        'retries': args.RETRIES,
        'cache_expire': cache_expire,
    }

    # collect every log service the managers and systems advertise. Only advertised
    # links are followed: a controller may let a request for a resource it does not
    # have run into the timeout (#1372). The collections are read in one request each
    # via the Redfish $expand query and cached by the lib fetch layer, so the sibling
    # Redfish checks on this host reuse them within the cache window.
    log_services = []  # (member path, log service)
    collection_errors = []
    for collection in ('Managers', 'Systems'):
        success, result = lib.redfish.fetch_collection(
            f'{args.URL}{API_BASE}/{collection}', expand=expand, **fetch_args
        )
        if not success or not isinstance(result, dict):
            collection_errors.append(
                result if not success else f'Unexpected answer for {collection}.'
            )
            continue
        success, members = lib.redfish.fetch_members(
            result.get('Members', []), args.URL, **fetch_args
        )
        if not success:
            continue
        for member in members:
            link = member.get('LogServices') if isinstance(member, dict) else None
            if not isinstance(link, dict) or not link.get('@odata.id'):
                continue
            success, services_url = lib.redfish.build_url(args.URL, link['@odata.id'])
            if not success:
                continue
            success, services = lib.redfish.fetch_collection(
                services_url, expand=expand, **fetch_args
            )
            if not success or not isinstance(services, dict):
                continue
            success, services = lib.redfish.fetch_members(
                services.get('Members', []), args.URL, **fetch_args
            )
            if not success:
                continue
            log_services += [
                (member.get('@odata.id', ''), service)
                for service in services
                if isinstance(service, dict)
            ]

    # init some vars
    msg = ''
    state = STATE_OK
    perfdata = ''
    aged_out_total = 0
    members_read = set()

    # pick the log services to read for this vendor and --log-type
    service_ids = LOG_SERVICE_IDS.get(vendor, LOG_SERVICE_IDS['generic'])
    wanted = ['sel', 'mel'] if args.LOG_TYPE == 'both' else [args.LOG_TYPE]
    log_label = {'sel': 'SEL', 'mel': 'MEL', 'both': 'SEL and MEL'}[args.LOG_TYPE]
    logs = []  # (label, member path, log service)
    missing = []  # requested logs the controller does not advertise
    for label in wanted:
        found = []
        for service_id in service_ids.get(label, []):
            found = [
                (member_path, service)
                for member_path, service in log_services
                if str(service.get('Id', '')).lower() == service_id.lower()
            ]
            if found:
                break
        if not found and label == 'sel':
            found = [
                (member_path, service)
                for member_path, service in log_services
                if service.get('LogEntryType') == 'SEL'
            ]
        logs += [(label, member_path, service) for member_path, service in found]
        if not found:
            missing.append(label.upper())

    # neither collection could be read, for example because the credentials are wrong:
    # name that, instead of a controller that advertises no logs
    if len(collection_errors) == 2:
        msg = collection_errors[0]
        if args.VERBOSE:
            msg += '\n\n' + lib.redfish.format_responses()
        lib.base.oao(msg, STATE_UNKNOWN, always_ok=args.ALWAYS_OK)

    # a controller without the requested log must not pass as "no entries"
    if not logs:
        offered = sorted(
            str(service.get('@odata.id', service.get('Id', '')))
            for _, service in log_services
        )
        msg = (
            f'The controller advertises no {log_label}.'
            f' Logs it offers: {", ".join(offered) if offered else "none"}.'
        )
        if args.VERBOSE:
            msg += '\n\n' + lib.redfish.format_responses()
        lib.base.oao(msg, STATE_UNKNOWN, always_ok=args.ALWAYS_OK)

    # analyze data: read the entries of each selected log and aggregate their
    # severity into `state`
    for label, member_path, service in logs:
        service_path = service.get('@odata.id', member_path)
        entries_link = service.get('Entries')
        members_read.add(member_path)
        if not isinstance(entries_link, dict) or not entries_link.get('@odata.id'):
            # an advertised log without its entries is no more an empty one than a
            # log that cannot be read
            msg += (
                f'{service_path} ({label.upper()})\nNot readable: no Entries link.\n\n'
            )
            state = lib.base.get_worst(state, STATE_UNKNOWN)
            continue
        # fetch_collection asks the controller to inline the log entries via the
        # Redfish $expand query, so a long log is read in one request even on
        # controllers that list entries as references.
        # a link refused by build_url() makes this log unreadable, not the whole check
        success, entries = lib.redfish.build_url(args.URL, entries_link['@odata.id'])
        if success:
            success, entries = lib.redfish.fetch_collection(
                entries, expand=expand, **fetch_args
            )
        if success and isinstance(entries, dict):
            # a controller that ignores $expand lists the entries as references only,
            # whose severity would otherwise go unread
            success, entries = lib.redfish.fetch_members(
                entries.get('Members') or [], args.URL, **fetch_args
            )
        if not success or not isinstance(entries, list):
            # an advertised log that cannot be read is not an empty one
            msg += f'{service_path} ({label.upper()})\nNot readable: {entries}\n\n'
            state = lib.base.get_worst(state, STATE_UNKNOWN)
            continue
        member_msg, member_state, member_aged = (
            lib.redfish.get_manager_logservices_sel_entries(
                {'Members': entries},
                match=match_patterns,
                ignore=ignore_patterns,
                cutoff_epoch=cutoff_epoch,
            )
        )
        aged_out_total += member_aged
        if member_msg:
            msg += f'{service_path} ({label.upper()})\n{member_msg}\n\n'
            state = lib.base.get_worst(state, member_state)
    member_count = len(members_read)

    # build the message
    if missing:
        # --log-type=both on a controller that offers only one of the two logs
        msg = f'The controller advertises no {" and ".join(missing)}.\n\n' + msg
        log_label = ' and '.join(
            label.upper() for label in wanted if label.upper() not in missing
        )

    members = lib.txt.pluralize('member', member_count)
    aged = f' {aged_out_total} aged out.' if aged_out_total else ''
    if state == STATE_CRIT:
        msg = (
            f'Checked {log_label} on {member_count} {members}.'
            f' There are critical errors.{aged}\n\n'
        ) + msg
    elif state == STATE_WARN:
        msg = (
            f'Checked {log_label} on {member_count} {members}. There are warnings.{aged}\n\n'
        ) + msg
    elif state == STATE_UNKNOWN:
        msg = (
            f'Checked {log_label} on {member_count} {members}.'
            f' There are logs that cannot be read.{aged}\n\n'
        ) + msg
    else:
        msg = (
            f'Everything is ok. Checked {log_label} on {member_count} {members}.{aged}\n\n'
        ) + msg

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