#!/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

# ########################################################################
# Print the name and fullness of every LVM snapshot that is open and
# nearly full.  The input is the file with 'lvs', and the allowable fullness.
# In many cases lvs will report "File descriptor %d (...) leaked" and we ignore
# this, as it's only a warning that usually happens from a shell.
# ########################################################################
check_lvm_snapshot_fullness() {
   local FILE="$1"
   local FULL="$2"
   awk -v full="$FULL" '
      $1 != "LV" && $1 != "File" && $6 !~ /[^0-9.]/ && $6 > full {
         print $2 "/" $1 "[" $5 "]=" $6 "%"
      }' "${FILE}"
}

# ########################################################################
# Run the program.
# ########################################################################
main() {

   # Get options
   for o; do
      case "${o}" in
         -w)        shift; OPT_WARN="${1}"; shift; ;;
         -c)        shift; OPT_CRIT="${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
   OPT_WARN=${OPT_WARN:-90}
   OPT_CRIT=${OPT_CRIT:-95}
   if is_not_sourced; then
      if [ -n "$1" ]; then
         echo "WARN spurious command-line options: $@"
         exit 1
      fi
   fi

   local NOTE="OK no full LVM snapshot volumes"
   local TEMP=$(mktemp -t "${0##*/}.XXXXXX") || exit $?
   trap "rm -f '${TEMP}' >/dev/null 2>&1" EXIT

   # The lvs command is usually in /usr/sbin.  But if it's run as a non-root
   # user, it will print out "WARNING: Running as a non-root user. Functionality
   # may be unavailable." and exit with success anyway.  So we have to detect
   # this and make the plugin exit UNKNOWN in that case.  If there is a $1 it's
   # the output of lvs.
   PATH="$PATH:/usr/sbin:/sbin"
   if [ -z "$1" ]; then
      lvs > "${TEMP}" 2>&1
   else
      cat "$1" > "${TEMP}" 2>/dev/null # For testing only
   fi

   if grep 'command not found' "${TEMP}" > /dev/null 2>&1; then
      NOTE="OK $(cat "${TEMP}")"
   elif grep 'WARNING: Running as a non-root user' "${TEMP}" >/dev/null 2>&1; then
      NOTE="UNK You must execute lvs with root privileges"
   else
      local VOLS=$(check_lvm_snapshot_fullness "${TEMP}" "${OPT_CRIT}")
      if [ "${VOLS}" ]; then
         NOTE="CRIT LVM snapshot volumes over ${OPT_CRIT}% full: ${VOLS}"
      else
         VOLS=$(check_lvm_snapshot_fullness "${TEMP}" "${OPT_WARN}")
         if [ "${VOLS}" ]; then
            NOTE="WARN LVM snapshot volumes over ${OPT_WARN}% full: ${VOLS}"
         fi
      fi
   fi

   echo $NOTE
}

# ########################################################################
# Determine whether this program is being executed directly, or sourced/included
# from another file.
# ########################################################################
is_not_sourced() {
   [ "${0##*/}" = "pmp-check-lvm-snapshots" ] || [ "${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-lvm-snapshots - Alert when LVM snapshots are running out of copy-on-write space.

=head1 SYNOPSIS

  Usage: pmp-check-lvm-snapshots [OPTIONS]
  Options:
    -c CRIT     Critical threshold; default 95%.
    -w WARN     Warning threshold; default 90%.
    --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 looks at the output of the 'lvs' command to find LVM snapshot volumes
that are beginning to run out of copy-on-write space. If a snapshot fills up its
copy-on-write space, it will fail.  This is also a useful way to detect whether
some process, such as a backup, failed to release a snapshot volume after
finishing with it.

=head1 PRIVILEGES

This plugin does not access MySQL.

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

=over

=item *

lvs

=back

=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-lvm-snapshots $VERSION$

=cut

DOCUMENTATION
