#!/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.db_sqlite
import lib.wildfly
from lib.globals import STATE_OK, STATE_UNKNOWN

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

DESCRIPTION = """Reports garbage collector activity from a WildFly/JBoss AS server via its HTTP
management API, reporting the collection rate and the share of wall-clock time spent in garbage
collection (GC overhead) for each collector."""

DEFAULT_INSECURE = False
DEFAULT_NO_PROXY = False
DEFAULT_TIMEOUT = 3
DEFAULT_URL = 'http://localhost:9990'
DEFAULT_USERNAME = 'wildfly-monitoring'


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(
        '--insecure',
        help=lib.args.help('--insecure'),
        dest='INSECURE',
        action='store_true',
        default=DEFAULT_INSECURE,
    )

    parser.add_argument(
        '--instance',
        help='WildFly instance (server-config) to check when running in domain mode.',
        dest='INSTANCE',
    )

    parser.add_argument(
        '--mode',
        help='WildFly server mode. Default: %(default)s',
        dest='MODE',
        choices=['standalone', 'domain'],
        default='standalone',
    )

    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(
        '--node',
        help='WildFly node (host) when running in domain mode.',
        dest='NODE',
    )

    parser.add_argument(
        '-p',
        '--password',
        help='WildFly management API password.',
        dest='PASSWORD',
        required=True,
    )

    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='WildFly management API URL. Default: %(default)s',
        dest='URL',
        default=DEFAULT_URL,
    )

    parser.add_argument(
        '--username',
        help='WildFly management API username. Default: %(default)s',
        dest='USERNAME',
        default=DEFAULT_USERNAME,
        required=True,
    )

    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)

    # fetch data
    # https://docs.wildfly.org/23/Admin_Guide.html
    data = {
        'operation': 'read-resource',
        'include-runtime': 'true',
        'recursive': 'true',
        # /core-service/platform-mbean/type/garbage-collector
        'address': [{'core-service': 'platform-mbean'}, {'type': 'garbage-collector'}],
        'json': 1,
    }
    res = lib.wildfly.get_data(args, data)

    # collection-count and collection-time from the JVM GarbageCollectorMXBean
    # are cumulative since JVM start. Convert them to a per-second collection
    # rate and a GC overhead percentage (share of wall-clock time spent in GC)
    # against the previous run, stored in this plugin's own SQLite cache,
    # instead of emitting continuous counters (issue #320). All collectors are
    # kept in a single cache row (one column per collector) so a two-collector
    # JVM (young + old) still gets a valid delta.
    collectors = []
    counters = {}
    for name, value in res['name'].items():
        key = re.sub(r'\W+', '_', name).strip('_').lower()
        collectors.append((name, key))
        counters[f'{key}_count'] = int(value['collection-count'])
        counters[f'{key}_time'] = int(value['collection-time'])

    rates = lib.db_sqlite.per_second_deltas(
        'linuxfabrik-monitoring-plugins-wildfly-gc-status.db',
        'wildfly-gc-status',
        counters,
    )
    if rates is None:
        # first run or counter reset (JVM restart): no delta yet
        lib.base.oao('Waiting for more data.', STATE_OK)

    # init some vars
    msg = ''
    perfdata = ''
    state = STATE_OK

    for name, key in collectors:
        gc_count_rate = round(rates[f'{key}_count'], 2)
        # ms of GC per wall-second / 1000 * 100 = percent of time spent in GC
        gc_overhead = round(rates[f'{key}_time'] / 10, 2)
        perfdata += lib.base.get_perfdata(
            f'garbage-collector-{name}-collection-count-per-second',
            gc_count_rate,
            uom=None,
            _min=0,
        )
        perfdata += lib.base.get_perfdata(
            f'garbage-collector-{name}-collection-time-percent',
            gc_overhead,
            uom='%',
            _min=0,
        )

        # build the message
        msg += f'{name}: {gc_count_rate}/s collections, {gc_overhead}% GC time; '

    # over and out
    lib.base.oao(
        msg[:-2],
        state,
        perfdata,
        always_ok=args.ALWAYS_OK,
        no_perfdata=args.NO_PERFDATA,
    )


if __name__ == '__main__':
    try:
        main()
    except Exception:
        lib.base.cu()
