我們在線上跑的服務,不知道為什么最近有幾回運行的進程莫名其妙的就沒有了,就特意寫了這個監控腳本,讓其自動掃描服務,把訪問不正常的服務,自動啟動或重啟服務,并且導出當時的線程使用情況,方便定位問題。
步驟:
1.修改web服務名稱和端口
monitorTcp.sh
2.修改掃描時間
monitorServer.sh
3.啟動守候進程
/usr/bin/nohup /bin/sh /home/Gzh/shell/monitorServer.sh 2>&1 > /dev/null &
monitorServer.sh
Shell代碼#!/bin/sh
###########################################################
#desc:后臺守候檢查服務是否正常
#author:gaozhonghui
#mail:toptreegzh@163.com
#date:20121210
###########################################################
while true
do
/bin/sh /home/Gzh/shell/monitorTcp.sh > /dev/null 2>&1
sleep 10
done
#!/bin/sh
###########################################################
#desc:后臺守候檢查服務是否正常
#author:gaozhonghui
#mail:toptreegzh@163.com
#date:20121210
###########################################################
while true
do
/bin/sh /home/Gzh/shell/monitorTcp.sh > /dev/null 2>&1
sleep 10
done
monitorTcp.sh
Shell代碼#!/bin/sh
#####################################################
#desc:掃描后臺服務器的應用服務器,若不能正常訪問則重啟
#author:gaozhonghui
#mail:toptreegzh@163.com
#date:20121127
#######################################################
year=`date -d "today" +"%Y"`
monthday=`date -d "today" +"%m"`
date=$(date -d "today" +"%Y%m%d")
#被監控服務器、端口列表
#str = web服務文件夾:端口號
server_all_list=(
'www.test2.com:9090'
'www.test.com:8090'
)
#應用服務器基路徑
serverBasePath="/web/webserver/jboss/"
#日志路徑
logBasePath="/web/webserver/logs/$year/$monthday/"
#獲得監控服務PID
function_getPID(){
local PID=`ps -ef|grep $1|grep java |awk '{print $2}'`
echo $PID
}
#dump 線程詳細信息方便定位問題
function_jstackinfo(){
PID=`function_getPID $1`
if [ x$PID != x"" ] ;then
if [ ! -d ${logBasePath} ];then
mkdir -p ${logBasePath}
fi
jstack -l ${PID} >> ${logBasePath}"jstack_$1_${date}.log"
fi
}
#關閉應用服務
function_shutdown(){
local shutdownSh=${serverBasePath}$1"/bin/shutdown.sh"
if [ -f $shutdownSh ];then
local PID=`function_getPID $1`
if [ x$PID != x"" ] ;then
sh $shutdownSh > /dev/null 2>&1
sleep 2
fi
local PID2=`function_getPID $1`
if [ x$PID2 != x"" ];then
kill -9 $PID2
fi
fi
}
#啟動應用服務
function_startup(){
local startupSh=${serverBasePath}$1"/bin/startup.sh"
if [ -f $shutdownSh ];then
sh $startupSh > /dev/null 2>&1
fi
}
#重啟應用服務
function_restart(){
function_shutdown $1
sleep 5
function_startup $1
}
#掃描監控服務
for server in ${server_all_list[@]}; do
server_ip=127.0.0.1
server_name=$( echo ${server} | awk -F ':' '{print $1}')
server_port=$( echo ${server} | awk -F ':' '{print $2}')