#!/bin/bash
#################################################
#
#      Filename: monitor_netcard_rdma_oos.sh
#
#        Author: allin.han@ucloud.cn
#   Description: The number of out of sequence packets received.
#        Create: 2019-10-24 18:21:39
# Last Modified: 2020-02-17 21:51:39(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)

addr="mlx5_bond_0"

collect() {
        ifname=$1
        value=`cat /sys/class/infiniband/$ifname/ports/1/hw_counters/out_of_sequence`
	#获取不到填充oldvalue
	if [ "$value" == "" ];then
		value=$oldvalue
	fi
	#查看是否有历史值
	old=`cat $tmpfile|grep "^${ifname}|"`
	if [ "$old" == "" ];then
		echo "$ifname|$value|$now" >> $tmpfile
	else
		oldvalue=`echo $old|awk -F '|' '{print $2}'`
		oldts=`echo $old|awk -F '|' '{print $3}'`
		ratevalue=$(($value-$oldvalue))
   		# 有些情况下，oldvalue为空，导致差值=value造成误报，暂时用这种方式过滤错误值
		if [[ $ratevalue -eq $value ]];then
			ratevalue=0
		fi
		#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"}]
