#!/bin/bash

cd `dirname $0`

if [ -f 'ip.txt' ]
then
  ip=`head -1 ip.txt`
else
  ip=`curl ip.sb`
  echo ${ip} >ip.txt
fi
port="9100"
instance_name=$ip:$port
function show_elapsed_time()
{
        user_hz=$(getconf CLK_TCK) #mostly it's 100 on x86/x86_64
        pid=$1
        if [ -z $pid ]; then
                echo "0"
        else
                jiffies=$(cat /proc/$pid/stat | cut -d" " -f22)
                sys_uptime=$(cat /proc/uptime | cut -d" " -f1)
                last_time=$(( ${sys_uptime%.*} - $jiffies/$user_hz ))
                echo "${last_time}"
        fi
}

while true
do
  cat  process_monitor.list|while read line
  do
    pname=`echo $line|awk -F\| '{print $1}' `
    pkeyword=`echo $line|awk -F\| '{$1="";print $0}' |sed "s/ //"`
    pid=$(ps -ef| grep "${pkeyword}" |grep -v "$0"| grep -v grep|awk '{print $2}')
    runtime=`show_elapsed_time $pid`
    echo "${pname}_count ${runtime}" |curl --data-binary @- http://43.153.222.205:9091/metrics/job/BI/instance/$instance_name/hostname/`hostname`

    cpu=`top -bn1 -p $pid|head -8|tail -1|awk '{print $9}'`
    logname=`ls -t  /usr/local/kafka_2.11-0.11.0.3/logs/kafkaServer-gc.log.*.current |head -1|awk '{print $1}'`
    mem=`tail  $logname|grep 'Eden:'|grep 'Survivors:'|awk -F'->' '{print $NF}'|awk -F 'M' '{print $1}'`
    echo "${pname}_process_cpu $cpu"|curl --data-binary @- http://43.153.222.205:9091/metrics/job/BI/instance/$instance_name/hostname/`hostname`
    echo "${pname}_process_memory $mem"|curl --data-binary @- http://43.153.222.205:9091/metrics/job/BI/instance/$instance_name/hostname/`hostname`
    echo "plogname:$logname,mem:$mem"  >real.log1
  done
  sleep 30
done

