应用服务可用监控-1

场景:应用服务域名对应多台负载机,当某台出现CPU或RAM资源阻塞时,如果服务器并未死机,根据负载策略(类似 ping或telnet),服务器可能仍然是可用的,新的访问仍然有分配到这台机器处理的可能,但实际又不可用,体验不好,且不能及时发送故障通知。新的负载策略是访问指定页面(类似curl命令),检查返回结果中是否有关键字,来判断服务是否正常,如果不正常,则从应用集群中踢掉这台机器,待恢复正常后再加入。但当时踢掉后没有邮件通知功能,就做了个脚本来监控。

 

一、通知脚本notice.sh

 1 #!/bin/bash
 2 
 3 # 定义需要检查的 URL 和关键字
 4 hostname=`awk 'NR==3 {print $1}' /etc/hosts`
 5 url="http://$hostname:login.html"
 6 keyword="记住密码"
 7 users=("1@qq.com;2@qq.com")
 8 # 如果一台服务器触发了就修改状态以免多次触发邮件:y-可以触发
 9 sendFlag=`cat /root/home/send.flag`
10 
11 # 发送邮件的函数
12 send_email() {
13 to=$users
14 subject="$hostname service unreachable"
15 body="URL: $url\n服务异常\n断言关键字: $keyword\n"
16 echo -e "$body" | mail -s "$subject" "$to"
17 }
18 
19 # 使用 curl 请求 URL 并检查返回结果是否包含关键字
20 response=$(curl -s "$url")
21 if [[ $sendFlag = y ]];then
22 if [[ $response =~ $keyword ]]; then
23 echo "`date`: 找到关键字"
24 else
25 echo "`date`: 未找到关键字"
26 echo "n" > /root/home/send.flag
27 for i in "$users"
28 do
29 send_email
30 done
31 #systemctl tomcat start
32 fi
33 else
34 echo "`date`:发送标志是$sendFlag,不再重复发送"
35 fi

 

二、在crontab中配置定时任务

1 */5 3-23,0-1 * * * sh /root/home/notice.sh >> /root/home/notice.log 2>&1
2 0 7 * * * echo "y" > /root/home/send.flag

 

posted @ 2023-12-13 11:38  stuka  阅读(12)  评论(0编辑  收藏  举报