#!/bin/bash

# 下载程序&端口映射文件
mkdir -p /opt/release_port/
if [ ! -f /opt/release_port/release_ports ];then
      wget -O /opt/release_port/release_ports "http://tw06d0006.onething.net/iaas_tools/ksvod_release_ports" 2>/dev/null
fi

# 遍历端口列表，获取端口对应pid及processName，如果当前processName与期待processName一致则跳过，否则kill对应进程
function release_port() {

   while read line
   do
     port=`echo $line | awk '{print $2}'`
     expect_process=`echo $line | awk '{print $1}'`
     PIDS=$(lsof -t -i:$port)
     for PID in $PIDS
     do
       status=`ps -ef | grep $PID | grep -v grep | grep $expect_process`
       if [ ! -n $status ];then
         kill -9 $PID
       fi
     done
   done </opt/release_port/release_ports
}

# 内核参数配置预留端口不用作随机端口
function reserved_ports() {
    cur_ports=$(sysctl -a 2> /dev/null | grep net.ipv4.ip_local_reserved_ports |awk  '{print $3}')
    if [ -n "$cur_ports" ];then
        sysctl -w net.ipv4.ip_local_reserved_ports=${cur_ports},50490,50499,60490,60499 &> /dev/null
    else
        sysctl -w net.ipv4.ip_local_reserved_ports=50490,50499,60490,60499 &> /dev/null
    fi
}

function main() {
    release_port
    reserved_ports
    echo -n 'ok'
}

main
