#!/bin/bash

## PPS Limit
LIMIT=$1

## Path Set
IF_CUR_PATH="/tmp/vm_interface.cur"
IF_AFTER_PATH="/tmp/vm_interface.after"

LOG_PATH="/tmp/vm_interface.result"
IGNORE_DIR="/etc/zabbix/scripts/data"
IGNORE_PATH="${IGNORE_DIR}/pps_ignore.txt"
TMP_PATH="/tmp/vm_pps.count"

if [ ! -d $IGNORE_DIR ]
then
   mkdir -p $IGNORE_DIR
fi

if [ ! -f $IGNORE_PATH ]
then
   touch $IGNORE_PATH
fi

STATUS=0

if [ ! -f $IGNORE_PATH ] 
then
    mkdir -p /etc/zabbix/scripts/data;
    touch $IGNORE_PATH
fi
if [ ! -f $TMP_PATH ]
then
    echo "0" > $TMP_PATH
fi

if [ -f $LOG_PATH ]
then
    cat /dev/null > $LOG_PATH
fi

PPS_COUNT=`cat $TMP_PATH`

## Get packet
ifconfig -s | grep "tap" | egrep -v -f $IGNORE_PATH > $IF_CUR_PATH
sleep 1
ifconfig -s | grep "tap" | egrep -v -f $IGNORE_PATH > $IF_AFTER_PATH

## tap device count
IF_COUNT=`cat $IF_CUR_PATH | wc -l`

## current packet 
for ((i=1;i<=$IF_COUNT;i++))
do
    IF[$i]=`cat $IF_CUR_PATH | awk '{print $1}' | sed -n "$i p"`
    RX1[$i]=`cat $IF_CUR_PATH | grep "${IF[$i]}" | awk '{print $4}'`
    TX1[$i]=`cat $IF_CUR_PATH | grep "${IF[$i]}" | awk '{print $8}'`
done

## After packet
for ((i=1;i<=$IF_COUNT;i++))
do
    IF[$i]=`cat $IF_AFTER_PATH | awk '{print $1}' | sed -n "$i p"`
    RX2[$i]=`cat $IF_AFTER_PATH | grep "${IF[$i]}" | awk '{print $4}'`
    TX2[$i]=`cat $IF_AFTER_PATH | grep "${IF[$i]}" | awk '{print $8}'`
done

## pps calculation  
for ((i=1;i<=$IF_COUNT;i++))
do
    RX_DIFF[$i]=`expr ${RX2[$i]} - ${RX1[$i]}`
    TX_DIFF[$i]=`expr ${TX2[$i]} - ${TX1[$i]}`
done

## check to instance over the limit 
for ((i=1;i<=$IF_COUNT;i++))
do
    if [ ${RX_DIFF[$i]} -gt $LIMIT ] || [ ${TX_DIFF[$i]} -gt $LIMIT ]
    then
            INSTANCE_ID[$i]=`grep -r "${IF[$i]}" /var/lib/nova/instances/*/libvirt.xml | awk -F"/" '{print $6}'`
            if [ -z "${INSTANCE_ID[$i]}" ]
            then
                 INSTANCE_ID[$i]="Unknown                            "
            fi

            ## tap device rx/tx reverse
            echo -e "${INSTANCE_ID[$i]}\t${RX_DIFF[$i]} pps/tx, ${TX_DIFF[$i]} pps/rx" >> $LOG_PATH
            STATUS=1
    fi
done

rm -f $IF_CUR_PATH
rm -f $IF_AFTER_PATH

## alert (0: OK, 1: Problem)
if [ $STATUS -eq 1 ]
then
    if [ $PPS_COUNT -eq 1 ]
    then
        echo "`cat $LOG_PATH`"
    elif [ $PPS_COUNT -eq 0 ]
    then
        echo "1" > $TMP_PATH
        echo "OK"
    fi
else
    echo "0" > $TMP_PATH
    echo "OK"
fi
