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

import lib.args
import lib.base
import lib.db_mysql
import lib.human
from lib.globals import STATE_OK, STATE_UNKNOWN, STATE_WARN

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

DESCRIPTION = """Checks metrics of the Aria storage engine in MySQL/MariaDB, including page cache read
and write hit rates. Alerts when cache efficiency drops below optimal levels."""

DEFAULT_DEFAULTS_FILE = '/var/spool/icinga2/.my.cnf'
DEFAULT_DEFAULTS_GROUP = 'client'
DEFAULT_TIMEOUT = 3


def parse_args():
    """Parse command line arguments using argparse."""
    parser = argparse.ArgumentParser(description=DESCRIPTION)

    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(
        '--defaults-file',
        help='MySQL/MariaDB cnf file to read user, host and password from (instead of specifying them on the command line). '
        'Example: `/var/spool/icinga2/.my.cnf`. '
        'Default: %(default)s',
        dest='DEFAULTS_FILE',
        default=DEFAULT_DEFAULTS_FILE,
    )

    parser.add_argument(
        '--defaults-group',
        help=lib.args.help('--defaults-group') + ' Default: %(default)s',
        dest='DEFAULTS_GROUP',
        default=DEFAULT_DEFAULTS_GROUP,
    )

    parser.add_argument(
        '--timeout',
        help=lib.args.help('--timeout') + ' Default: %(default)s (seconds)',
        dest='TIMEOUT',
        type=int,
        default=DEFAULT_TIMEOUT,
    )

    args, _ = parser.parse_known_args()
    return args


def get_vars(conn):
    # Do not implement `get_all_vars()`, just fetch the ones we need for this check.
    # Without the GLOBAL modifier, SHOW VARIABLES displays the values that are used for
    # the current connection to MariaDB.
    sql = """
        show global variables
        where variable_name like 'aria_pagecache_buffer_size';
          """
    return lib.base.coe(lib.db_mysql.select(conn, sql))


def get_status(conn):
    # Do not implement `get_all_vars()`, just fetch the ones we need for this check.
    # Without the GLOBAL modifier, SHOW STATUS displays the values that are used for
    # the current connection to MariaDB.
    sql = """
        show global status
        where variable_name like 'Aria_pagecache_reads'
            or variable_name like 'Aria_pagecache_read_requests';
          """
    return lib.base.coe(lib.db_mysql.select(conn, sql))


def main():
    """The main function. This is where the magic happens."""

    # logic taken from mysqltuner.pl:mariadb_aria(), v2.2.8
    # including variable names

    # parse the command line
    try:
        args = parse_args()
    except SystemExit:
        sys.exit(STATE_UNKNOWN)

    mysql_connection = {
        'defaults_file': args.DEFAULTS_FILE,
        'defaults_group': args.DEFAULTS_GROUP,
        'timeout': args.TIMEOUT,
    }
    conn = lib.base.coe(lib.db_mysql.connect(mysql_connection))
    lib.base.coe(lib.db_mysql.check_select_privileges(conn))
    myvar = lib.db_mysql.lod2dict(get_vars(conn))
    engines = lib.db_mysql.get_engines(conn)

    if not engines.get('have_aria', ''):
        lib.base.cu('Aria Storage Engine not available.')
    if engines['have_aria'] != 'YES':
        lib.base.cu('Aria Storage Engine is disabled.')

    # Aria pagecache
    sql = """
        select ifnull(sum(index_length), 0) as total_aria_indexes
        from information_schema.tables
        where table_schema not in ('information_schema')
            and engine = 'aria';
          """
    result = lib.base.coe(lib.db_mysql.select(conn, sql))
    total_aria_indexes = result[0].get('total_aria_indexes', None)
    if total_aria_indexes is None:
        lib.base.oao(
            'Unable to calculate Aria index size on MySQL/MariaDB server.', STATE_OK
        )

    mystat = lib.db_mysql.lod2dict(get_status(conn))
    lib.db_mysql.close(conn)

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

    # calculations
    if (
        mystat.get('Aria_pagecache_read_requests', 0)
        and int(mystat['Aria_pagecache_read_requests']) > 0
    ):
        pct_aria_keys_from_mem = 100 - round(
            int(mystat['Aria_pagecache_reads'])
            / int(mystat['Aria_pagecache_read_requests'])
            * 100,
            1,
        )
    else:
        pct_aria_keys_from_mem = 0

    # total_aria_indexes == 0 if there are no aria tables or user has no SELECT privileges on them
    if (
        int(myvar['aria_pagecache_buffer_size']) < total_aria_indexes
        and pct_aria_keys_from_mem < 95
    ):
        aria_pagecache_buffer_size_state = STATE_WARN
        state = lib.base.get_worst(state, aria_pagecache_buffer_size_state)
        aria_state_str = lib.base.state2str(
            aria_pagecache_buffer_size_state,
            prefix=' ',
        )

        # build the message
        msg += (
            f' (adjust aria_pagecache_buffer_size'
            f' > {total_aria_indexes}){aria_state_str}'
        )
    else:
        aria_pagecache_buffer_size_state = STATE_OK
    aria_idx = lib.human.bytes2human(int(total_aria_indexes))
    aria_cache = lib.human.bytes2human(
        int(myvar['aria_pagecache_buffer_size']),
    )
    msg = f'Total Aria indexes: {aria_idx}, Aria pagecache size: {aria_cache}{msg}; '
    perfdata += lib.base.get_perfdata(
        'mysql_aria_pagecache_buffer_size',
        myvar['aria_pagecache_buffer_size'],
        uom='B',
        _min=0,
    )
    perfdata += lib.base.get_perfdata(
        'mysql_total_aria_indexes',
        total_aria_indexes,
        _min=0,
    )

    if int(mystat['Aria_pagecache_read_requests']) > 0:
        cached = lib.human.number2human(
            mystat['Aria_pagecache_read_requests'],
        )
        reads = lib.human.number2human(
            mystat['Aria_pagecache_reads'],
        )
        msg += (
            f'{pct_aria_keys_from_mem}%'
            f' Aria pagecache hit rate'
            f' ({cached} cached / {reads} reads)'
        )
        # Remove WARN if `aria_pagecache_read_requests` > 0 and `pct_aria_keys_from_mem` < 95%
        # Because there's nothing we can do about it:
        # if pct_aria_keys_from_mem < 95:
        #     pct_aria_keys_from_mem_state = STATE_WARN
        #     state = lib.base.get_worst(state, pct_aria_keys_from_mem_state)
        #     msg += f'{lib.base.state2str(pct_aria_keys_from_mem_state, prefix=" ")}'
        perfdata += lib.base.get_perfdata(
            'mysql_pct_aria_keys_from_mem',
            pct_aria_keys_from_mem,
            uom='%',
            warn=95,
            _min=0,
            _max=100,
        )
        perfdata += lib.base.get_perfdata(
            'mysql_aria_pagecache_read_requests',
            mystat['Aria_pagecache_read_requests'],
            uom='c',
            _min=0,
        )
        perfdata += lib.base.get_perfdata(
            'mysql_aria_pagecache_reads',
            mystat['Aria_pagecache_reads'],
            uom='c',
            _min=0,
        )

    # over and out
    lib.base.oao(msg, state, perfdata, always_ok=args.ALWAYS_OK)


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