#!/bin/bash
#################################################
#
#      Filename: monitor_net_link.sh
#
#        Author: scott.liu@ucloud.cn
#   Description: ---
#        Create: 2019-03-07 17:53:56
# Last Modified: 2019-06-17 13:37:50(allin.han@ucloud.cn)
#################################################

if [ `df -h|grep -c /dev/vda` -ne 0 ];then
    echo "not support vm"
    exit 1
fi

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

for netcard in ${active_netcard[@]}
do
    base_num=`ethtool $netcard | grep "Supported link modes:" -A 2|grep -c base`
    if [ -z $base_num ];then
        continue
    # 支持的速率不识别，经验证属于网线问题, 但实测无影响。取不到eth_info无法进一步监控，暂且认为正常。
    elif [ $base_num -eq 0 ];then
        ret[`echo ${#ret[*]}`]={\"value\":0,\"tags\":\"iface=$netcard\"}
        continue
    elif [ $base_num -eq 3 ];then
	eth_info=`ethtool $netcard | grep "Supported link modes:" -A 2 | grep -v "auto-negotiation:" | grep -v "Advertised link modes:" | awk 'END {print}' | cut -d"b" -f 1|sed 's/^[ \t]*//g'`
    elif [ $base_num -eq 1 ];then
	eth_info=`ethtool $netcard | grep "baseT/Full" | grep -v "baseT/Half" | grep "Supported link modes:" | awk '{print $4}' | cut -d"b" -f 1|sed 's/^[ \t]*//g'`
    fi
    eth_speed=`ethtool $netcard | grep "Speed:" | awk '{print $2}' | cut -d"M" -f 1`
    if [ -z $eth_speed ];then
        ret[`echo ${#ret[*]}`]={\"value\":3,\"tags\":\"iface=$netcard\"}
    # 物理网卡最大支持25000，交换机上联10G口，自适应到10000属于正常。怎么兼容目前没有好的办法，先判断正常绕过。
    elif [ $eth_speed -eq 10000 ]  && [ $eth_info -eq 25000 ];then
	ret[`echo ${#ret[*]}`]={\"value\":0,\"tags\":\"iface=$netcard\"}
    elif [ $eth_speed == "Unknown!" ];then
        ret[`echo ${#ret[*]}`]={\"value\":2,\"tags\":\"iface=$netcard\"}
    elif [ $eth_speed -lt $eth_info ];then
        ret[`echo ${#ret[*]}`]={\"value\":1,\"tags\":\"iface=$netcard\"}
    elif [ $eth_speed -eq $eth_info ];then
	ret[`echo ${#ret[*]}`]={\"value\":0,\"tags\":\"iface=$netcard\"}
    fi
done

if [ ${#ret[@]} -eq 0 ];then
    exit 1
fi
flag=0
for re in ${ret[@]}
do
    if [ $flag -eq 0 ];then
         rets=$re
	 flag=1
    else
         rets=$rets,$re
    fi
done
echo "[$rets]"
exit 0
