#!/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  # pylint: disable=C0413
import sys  # pylint: disable=C0413

import lib.base  # pylint: disable=C0413
import lib.db_mysql  # pylint: disable=C0413
import lib.human  # pylint: disable=C0413
import lib.txt  # pylint: disable=C0413
from lib.globals import (STATE_OK, STATE_UNKNOWN,  # pylint: disable=C0413
                          STATE_WARN)

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

DESCRIPTION = """Checks if many joins per day without indexes were executed on MySQL/MariaDB."""

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='{0}: v{1} by {2}'.format('%(prog)s', __version__, __author__)
    )

    parser.add_argument(
        '--always-ok',
        help='Always returns OK.',
        dest='ALWAYS_OK',
        action='store_true',
        default=False,
    )

    parser.add_argument(
        '--defaults-file',
        help='Specifies a cnf file to read parameters like user, host and password from '
             '(instead of specifying them on the command line), '
             'for example `/var/spool/icinga2/.my.cnf`. Default: %(default)s',
        dest='DEFAULTS_FILE',
        default=DEFAULT_DEFAULTS_FILE,
    )

    parser.add_argument(
        '--defaults-group',
        help='Group/section to read from in the cnf file. Default: %(default)s',
        dest='DEFAULTS_GROUP',
        default=DEFAULT_DEFAULTS_GROUP,
    )

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

    return parser.parse_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 'join_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 'Select_full_join'
            or variable_name like 'Select_range_check'
            or variable_name like 'Uptime'
            ;
          """
    return lib.base.coe(lib.db_mysql.select(conn, sql))


def main():
    """The main function. Hier spielt die Musik.
    """

    # logic taken from mysqltuner.pl:mysql_stats(), section # Joins, v1.9.8
    # including variable names

    # parse the command line, exit with UNKNOWN if it fails
    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
    perfdata = ''

    # calculations
    mycalc = {}
    mycalc['joins_without_indexes'] = int(mystat['Select_range_check']) + int(mystat['Select_full_join'])
    mycalc['joins_without_indexes_per_day'] = round(mycalc['joins_without_indexes'] / (int(mystat['Uptime']) / 86400), 1)

    # Joins
    if mycalc['joins_without_indexes_per_day'] > 250:
        state = STATE_WARN
        msg = '{} {} without indexes while MySQL/MariaDB is {} up (approx. {} joins without indexes per day){}'.format(
            lib.human.number2human(mycalc['joins_without_indexes']),
            lib.txt.pluralize('JOIN', mycalc['joins_without_indexes']),
            lib.human.seconds2human(int(mystat['Uptime'])),
            lib.human.number2human(mycalc['joins_without_indexes_per_day']),
            lib.base.state2str(state, prefix=' '),
        )
        msg += '\n\nRecommendations:\n'
        msg += '* Use JOIN with indexes\n'
        msg += '* Otherwise set join_buffer_size > {}\n'.format(
            lib.human.bytes2human(int(myvar['join_buffer_size'])),
        )
    else:
        state = STATE_OK
        msg = 'Everything is ok.'

    perfdata += lib.base.get_perfdata('mysql_join_buffer_size', myvar['join_buffer_size'], 'B', None, None, 0, None)
    
    perfdata += lib.base.get_perfdata('mysql_select_full_join', mystat['Select_full_join'], 'c', None, None, 0, None)
    perfdata += lib.base.get_perfdata('mysql_select_range_check', mystat['Select_range_check'], 'c', None, None, 0, None)
    perfdata += lib.base.get_perfdata('mysql_uptime', mystat['Uptime'], 's', None, None, 0, None)

    perfdata += lib.base.get_perfdata('mysql_joins_without_indexes', mycalc['joins_without_indexes'], 'c', None, None, 0, None)
    perfdata += lib.base.get_perfdata('mysql_joins_without_indexes_per_day', mycalc['joins_without_indexes_per_day'], None, None, None, 0, None)

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


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