#!/bin/bash
#
# check_varnish_health
#
# A nagios plugin to check the health status of a varnish web cache using varnishadm.
# by rudi kramer
# Copyright 2010 rudi Kramer <rudi(dot)kramer(at)gmail(dot)com>, BSD-style copyright and disclaimer.
#
# version 1.1 - Fixed bug where backend server is not called default 
# 
# Command Line Usage: ./check_varnish_health -i <ip> -p <port>
#
# Example: ./check_varnish_health -i 127.0.0.1 -p 6082
#
#################################################################################

PATH=/sbin:/bin:/usr/sbin:/usr/bin

E_SUCCESS="0"
E_WARNING="1"
E_CRITICAL="2"
E_UNKNOWN="3"

PROGNAME=`basename $0`
CHECK_VARNISHD=`ps ax| grep varnishd| grep -v grep`

print_help() {
        echo ""
        echo "This plugin checks the health status of a varnish web cache using varnishadm"
        echo ""
        echo "Usage: $PROGNAME -i <ip address>  -p <port> -s <secret file> -w <maximum number of sick backends before raise a warning state> -c <same as previous but for critical state>"
        echo ""
}

if [ $# -lt 10 ]; then
        print_help
        exit $E_UNKNOWN
fi

if [ -z "$CHECK_VARNISHD" ]; then
    echo "CRITICAL: varnishd is not running, unable to check health status"
    exit $E_CRITICAL
fi

while test -n "$1"; do
    case "$1" in
        --help | -h)
            print_help
            exit $E_UNKNOWN
            ;;
        -i)
            IP=$2
            shift
            ;;
        -p)
            PORT=$2
            shift
            ;;
        -s)
            SECRET=$2
            shift
            ;;
        -w)
            WARNING=$2
            shift
            ;;
        -c)
            CRITICAL=$2
            shift
            ;;
    esac
    shift
done

COMMAND=`varnishadm -S $SECRET -T $IP\:$PORT debug.health  2>&1 | grep "^Backend " | grep -v "Healthy" |wc -l`
OUTPUT=`varnishadm -S $SECRET -T $IP\:$PORT debug.health  2>&1 | grep "^Backend " |tr '\n' ','`

if [ $COMMAND -lt $WARNING ]; then
    echo "OK: $OUTPUT"
    exit ${E_SUCCESS}

elif [ $COMMAND -lt $CRITICAL ]; then
    echo "WARNING: $OUTPUT"
    exit ${E_WARNING}

else
    echo "CRITICAL: $OUTPUT"
    exit ${E_CRITICAL}
fi
