#!/bin/bash
#################################################
#
#      Filename: monitor_netcard_in_buffer.sh
#
#        Author: scott.liu@ucloud.cn
#   Description: ---
#        Create: 2018-06-28 17:12:39
# Last Modified: 2019-11-27 13:08:23(allin.han@ucloud.cn)
#################################################

basepath=$(cd `dirname $0`; pwd)
filename=`echo $0|awk -F '/' '{print $NF}'`
tmpfile="$basepath/tmp/${filename}.tmp"
tmpdir=`dirname $tmpfile`
[ ! -d $tmpdir ] && mkdir $tmpdir
now=$(date +%s)

number=0
for netcard in `ls /sys/class/net/| egrep '^eth.$|^nic.$|^net.$'`
do
    cat /sys/class/net/$netcard/operstate |grep -q up
    if [ $? -eq 0 ];then
        active_netcard[number]=$netcard
    fi
    let number=number+1
done

addr=${active_netcard[@]}

collect() {
        ifname=$1
	bash $basepath/get_ethtool_statistics.sh
	value=$(cat $basepath/tmp/get_ethtool_statistics.sh.tmp.$ifname|grep "rx_buffer_passed_thres_phy:"|awk '{print $NF}')
        #获取不到，换一种方式重复获取
        if [ "$value" == "" ];then
                value=`ethtool -S "$ifname"|grep "rx_buffer_passed_thres_phy:"|awk '{print $NF}'`
        fi
	#查看是否有历史值
	old=`cat $tmpfile|grep "^${ifname}|"`
	if [ "$old" == "" ];then
		echo "$ifname|$value|$now" >> $tmpfile
	else
		oldvalue=`echo $old|awk -F '|' '{print $2}'`
                # oldvalue为空时，oldvalue=value
                if [ "$oldvalue" == "" ];then
                        oldvalue=$value
                fi
		oldts=`echo $old|awk -F '|' '{print $3}'`
		ratevalue=`echo "($value-$oldvalue)/($now-$oldts)"|bc`
		#删除老值插入新值
		sed -i "/${ifname}|/d" $tmpfile
		echo "$ifname|$value|$now" >> $tmpfile
		#插入结果
		sed -i "/iface=$ifname/d" $tmpfile
		if [ "$ratevalue" -ge 0 ];then
			echo "{\"value\":$ratevalue,\"tags\":\"iface=$ifname\"}" >> $tmpfile
		fi
	fi
}

for i in $addr
do	
	collect $i
done

for i in `cat $tmpfile|grep "iface="`
do
	if [ "$ret" == "" ];then
		ret=$i
	else
		ret="$ret,$i"
	fi
done
#删除结果,防止在没收集到数据时任然保留了上次的脏数据
sed -i "/iface=/d" $tmpfile
if [ "$ret" == "" ];then
	exit 1
fi
#输出结果
echo "[$ret]"
exit 0
#[{"value":0,"tags":"iface=eth1"},{"value":0,"tags":"iface=eth3"}]
