#!/bin/sh

# ########################################################################
# This program is part of $PROJECT_NAME$
# License: GPL License (see COPYING)
# Authors:
#  Baron Schwartz, Roman Vynar
# ########################################################################

# ########################################################################
# Redirect STDERR to STDOUT; Nagios doesn't handle STDERR.
# ########################################################################
exec 2>&1

# ########################################################################
# Set up constants, etc.
# ########################################################################
STATE_OK=0
STATE_WARNING=1
STATE_CRITICAL=2
STATE_UNKNOWN=3
STATE_DEPENDENT=4

# ########################################################################
# Run the program.
# ########################################################################
main() {
   # Get options
   for o; do
      case "${o}" in
         -c)              shift; OPT_CRIT="${1}"; shift; ;;
         --defaults-file) shift; OPT_DEFT="${1}"; shift; ;;
         -d)              shift; OPT_DELD=1; shift; ;;
         -H)              shift; OPT_HOST="${1}"; shift; ;;
         -l)              shift; OPT_USER="${1}"; shift; ;;
         -L)              shift; OPT_LOPA="${1}"; shift; ;;
         -p)              shift; OPT_PASS="${1}"; shift; ;;
         -P)              shift; OPT_PORT="${1}"; shift; ;;
         -S)              shift; OPT_SOCK="${1}"; shift; ;;
         -w)              shift; OPT_WARN="${1}"; shift; ;;
         --master-conn)   shift; OPT_MASTERCONN="${1}"; shift; ;;
         --version)       grep -A2 '^=head1 VERSION' "$0" | tail -n1; exit 0 ;;
         --help)          perl -00 -ne 'm/^  Usage:/ && print' "$0"; exit 0 ;;
         -*)              echo "Unknown option ${o}.  Try --help."; exit 1; ;;
      esac
   done
   if [ -e '/etc/nagios/mysql.cnf' ]; then
      OPT_DEFT="${OPT_DEFT:-/etc/nagios/mysql.cnf}"
   fi
   if is_not_sourced; then
      if [ -n "$1" ]; then
         echo "WARN spurious command-line options: $@"
         exit 1
      fi
   fi

   # Get replication status into a temp file. TODO: move this into a subroutine
   # and test it.  But, if there is a commandline argument left over after
   # parsing options, then use that as the file instead.
   local TEMP=$(mktemp -t "${0##*/}.XXXXXX") || exit $?
   trap "rm -f '${TEMP}' >/dev/null 2>&1" EXIT
   if [ -z "$1" ]; then
      if [ "${OPT_MASTERCONN}" ]; then
         # MariaDB multi-source replication
         mysql_exec "SHOW SLAVE '${OPT_MASTERCONN}' STATUS\G" > "${TEMP}"
      else
         # Leverage lock-free SHOW SLAVE STATUS if available
         mysql_exec "SHOW SLAVE STATUS NONBLOCKING\G" > "${TEMP}" 2>/dev/null ||
         mysql_exec "SHOW SLAVE STATUS NOLOCK\G" > "${TEMP}" 2>/dev/null ||
         mysql_exec "SHOW SLAVE STATUS\G" > "${TEMP}"
      fi
   else
      # This is just for testing.  /dev/null it.
      cat "$1" > "${TEMP}" 2>/dev/null
   fi

   if [ $? = 0 ]; then
      # SHOW SLAVE STATUS isn't an error if the server isn't a replica. The file
      # will be empty if that happens.
      if [ -s "${TEMP}" ]; then
         NOTE=$(awk '$1 ~ /_Running:|Last_Error:/{print substr($0, 1, 100)}' "${TEMP}")
         if grep 'Last_Error: .' "${TEMP}" >/dev/null 2>&1; then
            NOTE="CRIT $NOTE"
         # pt-slave-delayed slave
         elif [ -n "${OPT_DELD}" ] &&
              grep 'Slave_IO_Running: Yes' "${TEMP}" >/dev/null 2>&1 &&
              grep 'Slave_SQL_Running: No' "${TEMP}" >/dev/null 2>&1; then
            NOTE="OK (delayed slave) $NOTE"
         elif egrep "_Running: (No|Connecting)" "${TEMP}" >/dev/null 2>&1; then
            if [ "${OPT_CRIT}" ]; then
               NOTE="CRIT $NOTE"
            else
               NOTE="WARN $NOTE"
            fi
         else
            NOTE="OK $NOTE"
         fi
      elif [ "${OPT_WARN}" ]; then
         # Empty file; not a replica, but that's not supposed to happen.
         NOTE="WARN This server is not configured as a replica."
      else
         # Empty file; not a replica.
         NOTE="OK This server is not configured as a replica."
      fi
   else
      NOTE="UNK could not determine replication status"
   fi

   echo $NOTE
}

# ########################################################################
# Execute a MySQL command.
# ########################################################################
mysql_exec() {
   mysql ${OPT_DEFT:+--defaults-file="${OPT_DEFT}"} \
      ${OPT_LOPA:+--login-path="${OPT_LOPA}"} \
      ${OPT_HOST:+-h"${OPT_HOST}"} ${OPT_PORT:+-P"${OPT_PORT}"} \
      ${OPT_USER:+-u"${OPT_USER}"} ${OPT_PASS:+-p"${OPT_PASS}"} \
      ${OPT_SOCK:+-S"${OPT_SOCK}"} -ss -e "$1"
}

# ########################################################################
# Determine whether this program is being executed directly, or sourced/included
# from another file.
# ########################################################################
is_not_sourced() {
   [ "${0##*/}" = "pmp-check-mysql-replication-running" ] || [ "${0##*/}" = "bash" -a "$_" = "$0" ]
}

# ########################################################################
# Execute the program if it was not included from another file.
# This makes it possible to include without executing, and thus test.
# ########################################################################
if is_not_sourced; then
   OUTPUT=$(main "$@")
   EXITSTATUS=$STATE_UNKNOWN
   case "${OUTPUT}" in
      UNK*)  EXITSTATUS=$STATE_UNKNOWN;  ;;
      OK*)   EXITSTATUS=$STATE_OK;       ;;
      WARN*) EXITSTATUS=$STATE_WARNING;  ;;
      CRIT*) EXITSTATUS=$STATE_CRITICAL; ;;
   esac
   echo "${OUTPUT}"
   exit $EXITSTATUS
fi

# ############################################################################
# Documentation
# ############################################################################
: <<'DOCUMENTATION'
=pod

=head1 NAME

pmp-check-mysql-replication-running - Alert when MySQL replication stops.

=head1 SYNOPSIS

  Usage: pmp-check-mysql-replication-running [OPTIONS]
  Options:
    -c CRIT         Report CRITICAL when replication is stopped with or w/o errors.
    --defaults-file FILE Only read mysql options from the given file.
                    Defaults to /etc/nagios/mysql.cnf if it exists.
    -d              Useful for slaves delayed by pt-slave-delay. It will not alert
                    when IO thread is running, SQL one is not and no errors.
    -H HOST         MySQL hostname.
    -l USER         MySQL username.
    -L LOGIN-PATH   Use login-path to access MySQL (with MySQL client 5.6).
    -p PASS         MySQL password.
    -P PORT         MySQL port.
    -S SOCKET       MySQL socket file.
    -w WARN         Report WARNING when SHOW SLAVE STATUS output is empty.
    --master-conn NAME  Master connection name for MariaDB multi-source replication.
    --help          Print help and exit.
    --version       Print version and exit.
  Options must be given as --option value, not --option=value or -Ovalue.
  Use perldoc to read embedded documentation with more details.

=head1 DESCRIPTION

This Nagios plugin examines whether replication is running. It is separate from
the check for delay because it is confusing or impossible to handle all of the
combinations of replication errors and delays correctly, and provide an
appropriate type of alert, in a single program.

By default, this plugin treats it as critical when the either thread stops with
an error, and a warning when threads are stopped with no error.  You can provide
critical and warning thresholds with the -c and -w options, for compatibility
with Nagios plugin conventions, but they don't work as thresholds.  Instead, if
you specify a critical threshold, this plugin will treat it as critical if
either thread is stopped, with or without an error.

The warning threshold makes the plugin report a warning when SHOW SLAVE STATUS
produces no output, which means it is not configured as a replica.  By default,
this plugin will report that replication is healthy when a server isn't
configured as a replica.

If you want to run this check against the delayed slaves, e.g. those running
with pt-slave-delay tool, you may want to specify -d option. It will not alert
when Slave_IO_Running is Yes, Slave_SQL_Running is No and there are no errors.

=head1 PRIVILEGES

This plugin executes the following commands against MySQL:

=over

=item *

C<SHOW SLAVE STATUS [NONBLOCKING|NOLOCK]>

=back

This plugin executes no UNIX commands that may need special privileges.

=head1 COPYRIGHT, LICENSE, AND WARRANTY

This program is copyright 2012-$CURRENT_YEAR$ Baron Schwartz, 2012-$CURRENT_YEAR$ Percona Inc.
Feedback and improvements are welcome.

THIS PROGRAM IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.

This program 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, version 2.  You should have received a copy of the GNU General
Public License along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA.

=head1 VERSION

$PROJECT_NAME$ pmp-check-mysql-replication-running $VERSION$

=cut

DOCUMENTATION
