脚本基于curl实现,用于检测接口或页面请求响应码和响应时长。尝试三次异常则触发告警,不会重复触发告警。告警恢复时提示。检测频率由crontab定时任务配置。
#!/bin/bash
# 默认参数 api接口
check_api=${1:-http://xxxx/api}
# 默认参数 超时时间5s
timeout=${2:-5}
#告警状态文件
shell_path=/xxx/xxx/shell/check_api_state
#告警短信接口
msg_api=http://xxx/sendSmsApi
echo "-----------------------check api start-----------------------"
echo `date "+%Y-%m-%d %H:%M:%S"`
i=1
error_times=0
#第一次正常则返回,有异常则进行三次检测
while [ $i -le 3 ];do
#调用接口计时
start_time=`date "+%Y-%m-%d %H:%M:%S"`
#curl $check_api 进行接口测试
response_code=`curl -I -s -m 10 $check_api |grep HTTP|awk '{print $2}'`
end_time=`date "+%Y-%m-%d %H:%M:%S"`
#计算响应时间
st=`date -d "$start_time" +%s`
et=`date -d "$end_time" +%s`
sumTime=$(($et-$st))
echo "接口:$check_api,第$i次接口检查"
echo "开始时间:$start_time,结束时间:$end_time。请求用时:$sumTime s,响应码:$response_code。"
((i++))
# 判断接口响应时长、响应码是否正常
if [ $sumTime -ge $timeout -o $response_code -ne '200' ];then
((error_times++))
#接口异常(可能是网络波动)等待3s 进行下一次检测
sleep 3
else
echo "检查正常!"
break
fi
done
warn_time=`echo ${start_time// /#}`
warn_msg="【xxx告警】接口$check_api异常,请求耗时$sumTime(s),响应码为$response_code,告警时间:$warn_time。"
ok_msg="【xxx告警】接口$check_api已恢复,请求耗时$sumTime(s),响应码为$response_code,恢复时间:$warn_time。"
api_md5=`echo -n $check_api|md5sum|cut -d ' ' -f1`
is_create_file=0
if [ -f "$shell_path/$api_md5.state" ]
then
echo "state file is already exists"
else
touch "$shell_path/$api_md5.state"
echo 0 > $shell_path/$api_md5.state
is_create_file=1
fi
state=`cat $shell_path/$api_md5.state`
#echo "$check_api state_code $state"
echo "异常次数 $error_times,告警状态 $state [0未告警,1已告警]"
#三次检测全部异常 进行短信告警
if [ $error_times -eq 3 ] && [ $state -eq 0 ]
then
echo 1 > $shell_path/$api_md5.state
echo "发送短信 $warn_msg"
#curl 调用接口发送告警短信
curl -H "Content-Type: application/json" -X POST -d '{"phoneNo": "131xxxxxxxx","sms": "'$warn_msg'"}' $msg_api
fi
if [ $is_create_file -eq 0 ] && [ $state -eq 1 ] && [ $sumTime -le $timeout ] && [ $response_code -eq '200' ]
then
echo 0 > $shell_path/$api_md5.state
echo "发送短信 $ok_msg"
curl -H "Content-Type: application/json" -X POST -d '{"phoneNo": "131xxxxxxxx","sms": "'$ok_msg'"}' $msg_api
fi
echo `date "+%Y-%m-%d %H:%M:%S"`
echo "-----------------------check api end-----------------------"