自動監控url是否可用,如不可用則重啟應用,并做相應的報警策略
#!/bin/bashauthor: QingFeng
qq: 530035210
blog: http://my.oschina.net/pwd/blog
自動監控url是否可用,如不可用則重啟應用,并做相應的報警策略。
缺省的配置如下
logdir=/data/log/check #日志路徑 log=$logdir/log.log #日志文件 is_font=1 #終端是否打印日志: 1打印 0不打印 is_log=0 #是否記錄日志: 1記錄 0不記錄 key="data-camp" #進程關鍵字 exec_stop="/etc/init.d/data-camp stop" #停應用命令 exec_start="/etc/init.d/data-camp start" #啟動應用命令
datef(){ date "+%Y-%m-%d %H:%M:%S" }
print_log(){ if [[ $is_log -eq 1 ]];then [[ -d $logdir ]] || mkdir -p $logdir echo "[ $(datef) ] $1" >> $log fi if [[ $is_font -eq 1 ]];then echo -e "[ $(datef) ] $1" fi }
定義重啟
derestart(){
if [[ $1 == "" ]];then print_log "$FUNCNAME():應用關鍵字不能為空" exit fi
if [[ $2 == "" ]];then print_log "$FUNCNAME():啟動文件不能為空" exit fi
if [[ $2 == "" ]];then print_log "$FUNCNAME():啟動參數口不能為空" exit fi
ppid=0 ppid=$(ps axu |grep "$1" |grep -v grep |grep -v "$0" |wc -l) $2 $3 ppid=$(ps axu |grep "$1" |grep -v grep |grep -v "$0" |wc -l) echo $ppid > /tmp/restart.num print_log "$FUNCNAME(): $1的進程數為:$ppid"
}
場景一: 當網站返回碼不為200,則重啟應用.
check_code(){ if [[ $1 == "" ]];then print_log "$FUNCNAME():服務器地址不能為空" exit fi
if [[ $2 == "" ]];then print_log "$FUNCNAME():服務器端口不能為空" exit fi
print_log "$FUNCNAME():開始檢測-[$1:$2]服務器的網站狀態返回碼." code=$(curl -m 8 -o /dev/null -s -w %{http_code} http://$1:$2/verdict/session/LSGJA52U7CH055974/latest/result)
if [[ $code -ne 200 ]];then print_log "$FUNCNAME():[$1:$2]服務器的網站狀態返回碼不正常,開始重啟應用--$code." print_log "$FUNCNAME():執行命令: $exec_stop" derestart "$key" "$exec_stop" num2=$(cat /tmp/restart.num) if [[ $num2 -ne 0 ]];then print_log "$FUNCNAME():停應用失敗." fi print_log "$FUNCNAME():執行命令: $exec_start" sleep 3 derestart "$key" "$exec_start" num2=$(cat /tmp/restart.num) if [[ $num2 -eq 0 ]];then print_log "$FUNCNAME():啟動應用失敗." fi
print_log "$FUNCNAME():重啟應用成功." else print_log "$FUNCNAME():[$1:$2]服務器的網站狀態返回碼正常--$code." fi }
場景二: 檢測網站http返回的時間
check_timeout(){ if [[ $1 == "" ]];then print_log "$FUNCNAME():服務器地址不能為空" exit fi
if [[ $2 == "" ]];then print_log "$FUNCNAME():服務器端口不能為空" exit fi
print_log "$FUNCNAME():開始檢測-[$1:$2]服務器的網站超時時間." httptime=
curl -o /dev/null -s -w "time_connect: %{time_connect}\ntime_starttransfer:%{time_starttransfer}\ntime_total: %{time_total}\n" "http://$1:$2/verdict/session/LSGJA52U7CH055974/latest/result" |grep time_total|awk -F ":" '{print $2*1000}'
taketime=$(expr $httptime / 1000)
if [[ $httptime -gt 60000 ]];then print_log "$FUNCNAME():[$1:$2]服務器的網站響應時間不正常,開始重啟應用--$httptime ms." print_log "$FUNCNAME():執行命令: $exec_stop" derestart "$key" "$exec_stop" num2=$(cat /tmp/restart.num) if [[ $num2 -ne 0 ]];then print_log "$FUNCNAME():停應用失敗." fi print_log "$FUNCNAME():執行命令: $exec_start" sleep 3 derestart "$key" "$exec_start" num2=$(cat /tmp/restart.num) if [[ $num2 -eq 0 ]];then print_log "$FUNCNAME():啟動應用失敗." fi
print_log "$FUNCNAME():重啟應用成功." else print_log "$FUNCNAME():[$1:$2]服務器的網站響應時間正常--$httptime ms/$taketime s." fi }
check_code "localhost" "6500" check_timeout "localhost" "6500"</pre>