#!/bin/sh

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

# ########################################################################
# 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; ;;
         -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; ;;
         --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

   # Set the exit status in case there are any problems.
   NOTE="UNK could not determine the PID file location."

   # Set up files to hold one or more PID file locations.
   local TEMP=$(mktemp -t "${0##*/}.XXXXXX") || exit $?
   local FILES=$(mktemp -t "${0##*/}.XXXXXX") || exit $?
   trap "rm -f '${TEMP}' '${FILES}' >/dev/null 2>&1" EXIT

   # If any connection option was given, then try to log in to find the PID
   # file.
   if [ "${OPT_DEFT}${OPT_HOST}${OPT_USER}${OPT_PASS}${OPT_PORT}${OPT_SOCK}" ]; then
      # If this fails (e.g. we can't log in), then there will be no line in the
      # file, and later we won't change the exit code / note away from "UNK".
      if mysql_exec "SHOW GLOBAL VARIABLES" > "${TEMP}"; then
         get_pidfile "${TEMP}" >> "${FILES}"
      fi
   else
      # Find all MySQL server instances.
      for pid in $(_pidof mysqld); do
         ps -p ${pid} -o pid,command | grep "${pid}" >> "${TEMP}"
      done
      # The ${TEMP} file may now contain lines like the following sample:
      # 13822     /usr/sbin/mysqld --defaults-file=/var/lib/mysql/my.cnf \
      #           --basedir=/usr --datadir=/var/lib/mysql/data/ \
      #           --pid-file=/var/run/mysqld/mysqld.pid \
      #           --socket=/var/run/mysqld/mysqld.sock
      # Now the task is to read find any reference to a --pid-file or --pid_file option.
      # We store these into the $FILES temp file.
      while read pid command; do
         if echo "${command}" | grep pid.file >/dev/null 2>&1; then
            # Strip off everything up to and including --pid-file=
            command="${command##*--pid?file=}"
            # Strip off any options that follow this, assuming that there's not
            # a space followed by a dash in the pidfile's path.
            echo "${command%% -*}" >> "${FILES}"
         fi
      done < "${TEMP}"
   fi

   # TODO: maybe in the future we can also check whether the PID in the file is
   # correct. TODO: maybe we should also alert on which PID is missing its
   # pidfile.
   MISSING=""
   NOTE2=""
   while read pidfile; do
      if [ ! -e "${pidfile}" ]; then
         MISSING=1
         NOTE2="${NOTE2:+${NOTE2}; }missing ${pidfile}"
      fi
      NOTE="OK all PID files exist."
   done < "${FILES}"

   if [ "${MISSING}" ]; then
      if [ "${OPT_CRIT}" ]; then
         NOTE="CRIT ${NOTE2}"
      else
         NOTE="WARN ${NOTE2}"
      fi
   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"
}

# ########################################################################
# A wrapper around pidof, which might not exist. The first argument is the
# command name to match.
# ########################################################################
_pidof() {
   if ! pidof "${1}" 2>/dev/null; then
      ps axo pid,ucomm | awk -v comm="${1}" '$2 == comm { print $1 }'
   fi
}

# ########################################################################
# Unfortunately, MySQL 5.0 doesn't have a system variable @@pid_file, so
# we have to use SHOW VARIABLES and a temp file.  In 5.1 and newer we
# could have done it in a single SQL statement:
#    SELECT IF(@@pid_file LIKE '/%', @@pid_file,
#    CONCAT(@@basedir, @@pid_file))" >> "${FILES}"
# The first argument is the file that contains SHOW VARIABLES.
# ########################################################################
get_pidfile() {
   awk '
      /^pid_file/ { pid_file = $2 }
      /^basedir/  { basedir  = $2 }
      END {
         if ( substr(pid_file, 1, 1) != "/" ) {
            pid_file = basedir pid_file;
         }
         print pid_file;
      }
      ' "$1"
}

# ########################################################################
# Determine whether this program is being executed directly, or sourced/included
# from another file.
# ########################################################################
is_not_sourced() {
   [ "${0##*/}" = "pmp-check-mysql-pidfile" ] || [ "${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-pidfile - Alert when the mysqld PID file is missing.

=head1 SYNOPSIS

  Usage: pmp-check-mysql-pidfile [OPTIONS]
  Options:
    -c CRIT         Critical threshold; makes a missing PID file critical.
    --defaults-file FILE Only read mysql options from the given file.
                    Defaults to /etc/nagios/mysql.cnf if it exists.
    -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         Warning threshold; ignored.
    --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 checks to make sure that the MySQL PID file is not missing.
The PID file contains the process ID of the MySQL server process, and is used by
init scripts to start and stop the server. If it is deleted for some reason,
then it is likely that the init script will not work correctly.  The file can be
deleted by poorly written scripts, an accident, or a mistaken attempt to restart
MySQL while it is already running, especially if mysqld is executed directly
instead of using the init script.

The plugin accepts the -w and -c options for compatibility with standard Nagios
plugin conventions, but they are not based on a threshold. Instead, the plugin
raises a warning by default, and if the -c option is given, it raises an error
instead, regardless of the option.

By default, this plugin will attempt to detect all running instances of MySQL,
and verify the PID file's existence for each one.  It does this purely by
examining the Unix process table with the C<ps> tool.  However, in some cases
the process's command line does not list the path to the PID file.  If the tool
fails to detect the MySQL server process, or if you wish to limit the check to a
single instance in the event that there are multiple instances on a single
server, then you can specify MySQL authentication options.  This will cause the
plugin to skip examining the Unix processlist, log into MySQL, and examine the
pid_file variable from SHOW VARIABLES to find the location of the PID file.

=head1 PRIVILEGES

This plugin executes the following commands against MySQL:

=over

=item *

C<SELECT> the system variables C<@@pid_file> and C<@@basedir>.

=back

This plugin executes the following UNIX commands that may need special privileges:

=over

=item *

ps

=back

The plugin should be able to either get variables from MySQL or find mysqld
PID using C<ps> command.

On BSD, if C<sysctl> option C<security.bsd.see_other_uids> is set to 0, C<ps>
will not return mysqld PID if the plugin run from non-root user.

Also an user you run the plugin from should be able to access MySQL PID file
file, so you may want to add it into mysql unix group etc.

=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-pidfile $VERSION$

=cut

DOCUMENTATION
