#!/bin/sh
# 2019-07-29
# f@pear.hk
# https://www.ibm.com/developerworks/cn/linux/1412_xiehy_tc/

## variables
##
net_cls_dir=/sys/fs/cgroup/net_cls
net_cls_pear_dir=${net_cls_dir}/pear

debug=0
rate_mbit=10
nic=none
env=emb
app=none
pid=none

## parameters
##
while getopts 'dr:n:e:P:p:h?' OPT
do
    case ${OPT} in
        d)
		debug=1
        ;;
        r)
        rate_mbit=${OPTARG} 
        ;;
        n)
        nic=${OPTARG}
        ;;
        e)
        env=${OPTARG}
        ;;
		P)
        app=${OPTARG}
		;;
		p)
		pid=${OPTARG}
		;;
        h|?|*)
        echo "Usage: -d -r rate_mbit -n nic [-e pc -P app] [-p pid]"
        echo ""
        echo "Options:"
        echo " 	-d                such as: -d"
        echo " 	-r rate_mbit      such as: -r 1"
        echo " 	-n nic            such as: -n eht0"
        echo " 	-e env            such as: -e [pc,emb]"
        echo " 	-P app            such as: -P nginx"
        echo " 	-p pid            such as: -p pid"
        exit 0  
        ;;
    esac
done

## debug
##
if test ${debug} -eq 1;then
	echo "rate_mbit=${rate_mbit}, nic=${nic}, env=${env}, app=${app}, pid=${pid}"
	exit 0
fi

## set queue displine
##
if test "x${nic}" != "xnone";then
	## set HTB
	##
	tc qdisc del dev ${nic} root
	tc qdisc add dev ${nic} root handle 1: htb default 2

	tc class add dev ${nic} parent 1: classid 1:1 htb rate 200mbit burst 30k
	tc class add dev ${nic} parent 1:1 classid 1:2 htb rate ${rate_mbit}mbit burst 30k
	tc class add dev ${nic} parent 1:1 classid 1:200 htb rate 200mbit burst 30k

	## set rules
	##
	tc qdisc add dev ${nic} parent 1:2 handle 2: fq_codel
	tc qdisc add dev ${nic} parent 1:200 handle 200: fq_codel

	## active
	##
	test ! -d ${net_cls_pear_dir} && mkdir ${net_cls_pear_dir}
	echo 0x00010200 > ${net_cls_dir}/net_cls.classid
	echo 0x00010002 > ${net_cls_pear_dir}/net_cls.classid
	tc filter add dev ${nic} parent 1: protocol ip prio 1 handle 1: cgroup
fi

## limit bandwidth of process via app name
##
if test "x${app}" != "xnone";then
	if test "x${env}" != "xpc";then
		for i in `ps aux|grep ${app}|grep -v "grep"|grep -v "$0"|awk '{print $2}'`;
		do 
			echo $i > ${net_cls_pear_dir}/tasks
		done
	else
		for i in `ps|grep ${app}|grep -v "grep"|grep -v "$0"|awk '{print $1}'`;
		do 
			echo $i > ${net_cls_pear_dir}/tasks
		done
	fi
fi

## limit bandwidth of process via pid
##
if test "x${pid}" != "xnone";then
	echo ${pid} > ${net_cls_pear_dir}/tasks
fi





