#!/bin/bash
# Copyright 2011, Dell
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#  http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

#
# check to see that nova services are running within options
#

# get arguments

int_warn=1
int_crit=2
int_compute=0
int_volume=0
int_network=0
int_scheduler=0

while getopts 'hS:N:C:V:w:c:' OPT; do
  case $OPT in
    w)  int_warn=$OPTARG;;
    c)  int_crit=$OPTARG;;
    C)  int_compute=$OPTARG;;
    V)  int_volume=$OPTARG;;
    N)  int_network=$OPTARG;;
    S)  int_scheduler=$OPTARG;;
    h)  hlp="yes";;
    *)  unknown="yes";;
  esac
done

# usage
HELP="
Usage: $0 [ -w value ] [ -c value ] [ -C value ] [ -N value ] [ -S value ] [ -V value ]
Options:
   -w --> Warning threshold of missing components (default: 1)
   -c --> Critical threshold of missing components (default: 2)
   -C --> Expected Compute service entries (default: 0)
   -N --> Expected Network service entries (default: 0)
   -S --> Expected Scheduler service entries (default: 0)
   -V --> Expected Volume service entries (default: 0)
   -h --> print this help screen
"

if [ "$hlp" = "yes" ]; then
  echo "$HELP"
  exit 0
fi

# Get nova status
nova-manage service list > /tmp/nova.out.$$
N_N=`grep nova-network /tmp/nova.out.$$ | grep -v XXX | wc -l`
N_C=`grep nova-compute /tmp/nova.out.$$ | grep -v XXX | wc -l`
N_V=`grep nova-volume /tmp/nova.out.$$ | grep -v XXX | wc -l`
N_S=`grep nova-scheduler /tmp/nova.out.$$ | grep -v XXX | wc -l`

D_C=`expr $int_compute - $N_C`
if [ $D_C -lt 0 ]; then
  D_C=0
fi
D_N=`expr $int_network - $N_N`
if [ $D_N -lt 0 ]; then
  D_N=0
fi
D_V=`expr $int_volume - $N_V`
if [ $D_V -lt 0 ]; then
  D_V=0
fi
D_S=`expr $int_scheduler - $N_S`
if [ $D_S -lt 0 ]; then
  D_S=0
fi

D_Total=`expr $D_N + $D_S + $D_C + $D_V`

err=0
if (( $D_Total >= $int_crit )); then
  err=2
elif (( $D_Total >= $int_warn )); then
  err=1
fi

OUTPUTP="scheduler: $N_S ($int_scheduler), network: $N_N ($int_network), compute: $N_C ($int_compute), volume: $N_V ($int_volume)"

if (( $err == 0 )); then
  echo "Nova OK - $OUTPUTP"
  exit "$err"
elif (( $err == 1 )); then
  echo "Nova WARNING ($D_Total) - $OUTPUTP"
  exit "$err"
elif (( $err == 2 )); then
  echo "Nova CRITICAL ($D_Total) - $OUTPUTP"
  exit "$err"
fi
  
echo "Nova UNKNOWN - Bad Code Path"
exit -1

