#!/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 the ratio of on-disk versus in-memory temporary tables in MySQL/MariaDB. A
high rate of disk-based temporary tables indicates that tmp_table_size or
max_heap_table_size may need to be increased.
Alerts when the disk-based temporary table rate is too high."""

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 parameters like 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 'max_heap_table_size'
            or variable_name like 'tmp_table_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 'Created_tmp_disk_tables'
            or variable_name like 'Created_tmp_tables'
            ;
          """
    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:mysql_stats(), section # Temporary tables, v1.9.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))
    mystat = lib.db_mysql.lod2dict(get_status(conn))
    lib.db_mysql.close(conn)

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

    # calculations
    mycalc = {}
    if int(mystat['Created_tmp_tables']) > 0:
        if int(mystat['Created_tmp_disk_tables']) > 0:
            mycalc['pct_temp_disk'] = round(
                int(mystat['Created_tmp_disk_tables'])
                / int(mystat['Created_tmp_tables'])
                * 100,
                1,
            )
        else:
            mycalc['pct_temp_disk'] = 0
    mycalc['max_tmp_table_size'] = max(
        int(myvar['max_heap_table_size']), int(myvar['tmp_table_size'])
    )

    # Temporary tables
    if int(mystat['Created_tmp_tables']) > 0:

        # build the message
        msg += (
            f'{mycalc["pct_temp_disk"]}% temporary tables'
            f' created on disk'
            f' ({lib.human.number2human(mystat["Created_tmp_disk_tables"])}'
            f' on disk /'
            f' {lib.human.number2human(mystat["Created_tmp_tables"])}'
            f' total)'
        )
        if (
            mycalc['pct_temp_disk'] > 25
            and mycalc['max_tmp_table_size'] < 256 * 1024 * 1024
        ):
            state = STATE_WARN
            msg += lib.base.state2str(state, prefix=' ')
            msg += '\n\nRecommendations:\n'
            msg += (
                f'* Set tmp_table_size >'
                f' {lib.human.bytes2human(int(myvar["tmp_table_size"]))}'
                f' and max_heap_table_size >'
                f' {lib.human.bytes2human(int(myvar["max_heap_table_size"]))}'
                f'\n'
            )
            msg += '* When making adjustments, make tmp_table_size/max_heap_table_size equal\n'
            msg += '* Reduce your SELECT DISTINCT queries which have no LIMIT clause\n'
        elif (
            mycalc['pct_temp_disk'] > 25
            and mycalc['max_tmp_table_size'] >= 256 * 1024 * 1024
        ):
            state = STATE_WARN
            msg += lib.base.state2str(state, prefix=' ')
            msg += '\n\nRecommendations:\n'
            msg += '* Temporary table size is already large - reduce result set size\n'
            msg += '* Reduce your SELECT DISTINCT queries which have no LIMIT clause\n'
        else:
            msg += '.'
    else:
        msg = 'Everything is ok.'

    perfdata += lib.base.get_perfdata(
        'mysql_max_heap_table_size',
        myvar['max_heap_table_size'],
        uom='B',
        _min=0,
    )
    perfdata += lib.base.get_perfdata(
        'mysql_tmp_table_size',
        myvar['tmp_table_size'],
        uom='B',
        _min=0,
    )

    perfdata += lib.base.get_perfdata(
        'mysql_created_tmp_disk_tables',
        mystat['Created_tmp_disk_tables'],
        uom='c',
        _min=0,
    )
    perfdata += lib.base.get_perfdata(
        'mysql_created_tmp_tables',
        mystat['Created_tmp_tables'],
        uom='c',
        _min=0,
    )

    perfdata += lib.base.get_perfdata(
        'mysql_max_tmp_table_size',
        mycalc['max_tmp_table_size'],
        uom='B',
        _min=0,
    )
    perfdata += lib.base.get_perfdata(
        'mysql_pct_temp_disk',
        mycalc['pct_temp_disk'],
        uom='%',
        _min=0,
        _max=100,
    )

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


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