Monit tomcat run or not on Linux

2014年1月21日 14:28

#!/bin/bash  
#  
# Keep watch at tomcat's status,   
# automatically restart it if it dead or out of memory. 

tomcat_port=":80";
tomcat_port_pattern="/:80$/";
tomcat_base_dir="/share/tomcat80";
check_page_url=http://127.0.0.1/LotteryHome3/run.jsp;
pid_file_pattern="tomcat80";
guarder_dir="/share/monitor";
log_file="/share/monitor/tomcat_run_log.log";
d=$(date +%F" "%T);

#email config
[email protected]

#139mail can send a short message to me
#but the short message just display subject
mail_to(){
  echo "$1" | mail -s "$1" $to
}

#init log file
touch ${log_file}

do_restart_tomcat(){
  # first try to shutdown it anyway
  ${tomcat_base_dir}/bin/shutdown.sh

  # second, check if the tomcat pid still exist,if exist then kill it!
  if ps -ef | grep ${pid_file_pattern} | grep -v grep
  then
    kill -9 $(ps -ef | grep ${pid_file_pattern} | grep -v grep | awk '{print $2}')
  fi

  #run start tomcat
  ${tomcat_base_dir}/bin/startup.sh
  echo "$d success restart tomcat ,the new pid id is " >> ${log_file}
  ps -ef | grep ${pid_file_pattern} | grep -v grep | awk '{print $2}' >> ${log_file}
  echo >> ${log_file}
  mail_to "$d success restart tomcat"
}

# first, check if the tomcat si listen on the port
runingcount=$(netstat -ant | awk "\$6 == \"LISTEN\" && \$4 ~ $tomcat_port_pattern" | wc -l)
if [ "$runingcount" == "1" ];
then
  #init the check result file
  if [ -e ${guarder_dir}/checkResult.tmp ] 
  then
    cat /dev/null > ${guarder_dir}/checkResult.tmp
  else
    touch ${guarder_dir}/checkResult.tmp
  fi

  # try to get the check result
  wget -b -o wget.log -O ${guarder_dir}/checkResult.tmp ${check_page_url}
  # wait 5 second to let the get check result job done.
  sleep 5

  # check the result
  workflag=$(cat ${guarder_dir}/checkResult.tmp | grep ServerStillWorking)
  memoryflag=$(cat ${guarder_dir}/checkResult.tmp | grep LessOfMemory)

  if [ "$workflag" == "" ]; then
    echo "$d can not found [ServerStillWorking] in the check result, try to restart tomcat ......" >> ${log_file}
    do_restart_tomcat
  elif [ "$memoryflag" == "" ]; then
    echo "$d can not found [LessOfMemory] in the check result, the tomcat server may out of memory, try to restart it ......" >> ${log_file}
    do_restart_tomcat
  else
    echo "$d tomcat$port is running ......" >> ${log_file}
  fi
else
  echo "$d found the tomcat not listen on ${tomcat_port}, try to restart it ......" >> ${log_file}
  do_restart_tomcat
fi

append

'bash: mail: command not found' on centos

just install mailx : yum -y install mailx

crontab

edit crontab : crontab -e
check tomcat run or not every 2 min:

*/2 * * * * "/share/monitor/./deamon2tomcat.sh" > /dev/null 2>&1

:wq and run crontab -l to check it