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

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

DESCRIPTION = """Checks the rate of joins executed without indexes in MySQL/MariaDB. A high rate of
full joins indicates missing indexes and can severely impact query performance.
Alerts when the rate of joins without indexes 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 user, host and password from. '
        'Example: `--defaults-file=/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 '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. This is where the magic happens."""

    # logic taken from mysqltuner.pl:mysql_stats(), section # Joins, 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
    perfdata = ''

    # calculations
    mycalc = {}
    mycalc['joins_without_indexes'] = int(mystat['Select_range_check']) + int(
        mystat['Select_full_join']
    )
    # Clamp Uptime to a minimum of 1 second so the per-day rate is
    # well-defined on a freshly booted server where
    # `SHOW GLOBAL STATUS LIKE 'Uptime'` can legitimately return 0 in
    # the first second after startup.
    uptime = max(int(mystat.get('Uptime') or 0), 1)
    mycalc['joins_without_indexes_per_day'] = round(
        mycalc['joins_without_indexes'] / (uptime / 86400), 1
    )

    # Joins
    if mycalc['joins_without_indexes_per_day'] > 250:
        state = STATE_WARN
        msg = (
            f'{lib.human.number2human(mycalc["joins_without_indexes"])}'
            f' {lib.txt.pluralize("JOIN", mycalc["joins_without_indexes"])}'
            f' without indexes while MySQL/MariaDB is'
            f' {lib.human.seconds2human(int(mystat["Uptime"]))} up'
            f' (approx.'
            f' {lib.human.number2human(mycalc["joins_without_indexes_per_day"])}'
            f' joins without indexes per day)'
            f'{lib.base.state2str(state, prefix=" ")}'
        )

        # build the message
        msg += '\n\nRecommendations:\n'
        msg += '* Use JOIN with indexes\n'
        msg += (
            f'* Otherwise set join_buffer_size >'
            f' {lib.human.bytes2human(int(myvar["join_buffer_size"]))}\n'
        )
    else:
        state = STATE_OK
        msg = 'Everything is ok.'

    perfdata += lib.base.get_perfdata(
        'mysql_join_buffer_size',
        myvar['join_buffer_size'],
        uom='B',
        _min=0,
    )

    perfdata += lib.base.get_perfdata(
        'mysql_select_full_join',
        mystat['Select_full_join'],
        uom='c',
        _min=0,
    )
    perfdata += lib.base.get_perfdata(
        'mysql_select_range_check',
        mystat['Select_range_check'],
        uom='c',
        _min=0,
    )
    perfdata += lib.base.get_perfdata(
        'mysql_uptime',
        mystat['Uptime'],
        uom='s',
        _min=0,
    )

    perfdata += lib.base.get_perfdata(
        'mysql_joins_without_indexes',
        mycalc['joins_without_indexes'],
        uom='c',
        _min=0,
    )
    perfdata += lib.base.get_perfdata(
        'mysql_joins_without_indexes_per_day',
        mycalc['joins_without_indexes_per_day'],
        _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()
