#!/bin/bash
# function:自动监控tomcat进程,挂了就执行重启操作
# author:evanxue
# DEFINE
format_time=`date +"%Y-%m-%d_%H:%M:%S"`
# 获取tomcat PPID
TomcatID=$(ps -ef |grep tomcat |grep -w 'jdk1.8.0_171'|grep -v 'grep'|awk '{print $2}')
# tomcat_startup
StartTomcat=/home/apache-tomcat-8.0.53/bin/startup.sh
#TomcatCache=/home/apache-tomcat-8.0.53/work
# 定义要监控的页面地址
WebUrl_1=http://127.0.0.1:8081/ihug/info/interactive.do
#WebUrl_2=http://127.0.0.1:8081/ihug/kc/cSubmit.do
WebUrl_2=http://127.0.0.1:8081/ihug/info/interactive.do
# 日志输出
GetPageInfo=/home/apache-tomcat-8.0.53/logs/TomcatMonitor/GetPageInfo.log
TomcatMonitorLog=/home/apache-tomcat-8.0.53/logs/TomcatMonitor/TomcatMonitor.log
Monitor()
{
echo "[info]开始监控tomcat...[$(date +'%F %H:%M:%S')]"
if [[ $TomcatID ]];then
echo "[info]tomcat进程ID为:$TomcatID."
# 获取返回状态码
TomcatServiceCode_1=$(curl -s -o $GetPageInfo -m 10 --connect-timeout 10 $WebUrl_1 -w %{http_code})
sleep 2
TomcatServiceCode_2=$(curl -s -o $GetPageInfo -m 10 --connect-timeout 10 $WebUrl_2 -w %{http_code})
if [ $TomcatServiceCode_1 -eq 200 ] || [ $TomcatServiceCode_2 -eq 200 ];then
echo "[info]返回码为$TomcatServiceCode_1,$TomcatServiceCode_2,tomcat启动成功,页面正常."
else
echo "[error]访问出错,状态码为$TomcatServiceCode_1,$TomcatServiceCode_2,错误日志已输出到$GetPageInfo"
#当前查看数据库连接数
echo "---当前查看数据库连接数----"
netstat -anp | grep 3306 >> /home/apache-tomcat-8.0.53/logs/TomcatMonitor/status.log
#查看tomcat连接数
echo "----查看tomcat连接数---------"
netstat -anp | grep 8081 >> /home/apache-tomcat-8.0.53/logs/TomcatMonitor/status.log
#查看tomcat状态
echo "---查看tomcat状态----"
echo "---查看tomcat状态jmap heap----" >> /home/apache-tomcat-8.0.53/logs/TomcatMonitor/status.log
jmap -heap $TomcatID >> /home/apache-tomcat-8.0.53/logs/TomcatMonitor/status.log
echo "---查看tomcat状态jstat gc----" >> /home/apache-tomcat-8.0.53/logs/TomcatMonitor/status.log
jstat -gc $TomcatID 500 20 >> /home/apache-tomcat-8.0.53/logs/TomcatMonitor/status.log
echo "---查看tomcat状态jstack----" >> /home/apache-tomcat-8.0.53/logs/TomcatMonitor/status.log
jstack $TomcatID >> /home/apache-tomcat-8.0.53/logs/TomcatMonitor/status.log
#将java堆输出为hprof二进制 格式文件
jmap -dump:file=/home/apache-tomcat-8.0.53/logs/TomcatMonitor/dump_log_$format_time.hprof $TomcatID
echo "[error]开始重启tomcat"
kill -9 $TomcatID # 杀掉原tomcat进程
sleep 3
#rm -rf $TomcatCache # 清理tomcat缓存
JAVA_HOME=/home/jdk1.8.0_171
PATH=$JAVA_HOME/bin:$PATH
CLASSPATH=.:$JAVA_HOME/jre/lib/rt.jar:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
export JAVA_HOME
export PATH
export CLASSPATH
$StartTomcat
fi
else
echo "[error]进程不存在!tomcat自动重启..."
echo "[info]$StartTomcat,请稍候......"
#rm -rf $TomcatCache
JAVA_HOME=/home/jdk1.8.0_171
PATH=$JAVA_HOME/bin:$PATH
CLASSPATH=.:$JAVA_HOME/jre/lib/rt.jar:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
export JAVA_HOME
export PATH
export CLASSPATH
$StartTomcat
fi
echo "------------------------------"
}
Monitor>>$TomcatMonitorLog