#!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# |             ____ _               _        __  __ _  __           |
# |            / ___| |__   ___  ___| | __   |  \/  | |/ /           |
# |           | |   | '_ \ / _ \/ __| |/ /   | |\/| | ' /            |
# |           | |___| | | |  __/ (__|   <    | |  | | . \            |
# |            \____|_| |_|\___|\___|_|\_\___|_|  |_|_|\_\           |
# |                                                                  |
# | Copyright Mathias Kettner 2014             mk@mathias-kettner.de |
# +------------------------------------------------------------------+
#
# This file is part of Check_MK.
# The official homepage is at http://mathias-kettner.de/check_mk.
#
# check_mk is free software;  you can redistribute it and/or modify it
# under the  terms of the  GNU General Public License  as published by
# the Free Software Foundation in version 2.  check_mk is  distributed
# in the hope that it will be useful, but WITHOUT ANY WARRANTY;  with-
# out even the implied warranty of  MERCHANTABILITY  or  FITNESS FOR A
# PARTICULAR PURPOSE. See the  GNU General Public License for more de-
# tails. You should have  received  a copy of the  GNU  General Public
# License along with GNU Make; see the file  COPYING.  If  not,  write
# to the Free Software Foundation, Inc., 51 Franklin St,  Fifth Floor,
# Boston, MA 02110-1301 USA.


@mysql_parse_per_item
def parse_mysql_slave(info):
    data = {}
    for line in info:
        if not line[0].endswith(':'):
            continue

        key = line[0][:-1]
        val = ' '.join(line[1:])

        # Parse some values
        try:
            val = int(val)
        except ValueError:
            val = {'Yes': True, 'No': False, 'None': None}.get(val, val)
        data[key] = val

    return data


@get_parsed_item_data
def check_mysql_slave(_no_item, params, data):
    state = 0
    perfdata = []
    output = []

    if data['Slave_IO_Running']:
        output.append('Slave-IO: running')

        if data['Relay_Log_Space']:
            output.append('Relay Log: %s' % get_bytes_human_readable(data['Relay_Log_Space']))
            perfdata.append(('relay_log_space', data['Relay_Log_Space']))

    else:
        output.append('Slave-IO: not running(!!)')
        state = 2

    if data['Slave_SQL_Running']:
        output.append('Slave-SQL: running')

        # Makes only sense to monitor the age when the SQL slave is running
        if data['Seconds_Behind_Master'] == 'NULL':
            output.append('Time behind master: NULL (Lost connection?)(!!)')
            state = 2
        else:
            out = 'Time behind Master: %s' % get_age_human_readable(data['Seconds_Behind_Master'])
            warn, crit = params.get('seconds_behind_master', (None, None))
            if crit is not None and data['Seconds_Behind_Master'] > crit:
                state = 2
                out += '(!!)'
            elif warn is not None and data['Seconds_Behind_Master'] > warn:
                state = max(state, 1)
                out += '(!)'
            output.append(out)
            perfdata.append(('sync_latency', data['Seconds_Behind_Master'], warn, crit))
    else:
        output.append('Slave-SQL: not running(!!)')
        state = 2

    return state, ', '.join(output), perfdata


check_info['mysql_slave'] = {
    "parse_function": parse_mysql_slave,
    "inventory_function": discover(lambda k, v: bool(v)),
    "check_function": check_mysql_slave,
    "service_description": "MySQL DB Slave %s",
    "has_perfdata": True,
    "group": "mysql_slave",
    "includes": ["mysql.include"],
}
