一、背景介绍
我的WordPress网站最近老是宕机无法提供服务,网站架构是经典的 Linux + OpenResty + MySQL + PHP , 宕机后大多数情况下不能立即处理,于是想写个自动检测网站健康的shell脚本,主要功能是定时检测网站运行是否正常,如果宕机,则自动初始化MySQL和PHP服务,如果初始化后还不能访问,则邮件告警通知我。
二、实现过程
1 编写脚本
脚本的内容如下,目前运行十来天左右还算正常。
#!/bin/bash
#Author:Attaboy
#Description:this script is made to check website health and roll back automattically.
# Modify history
# 20171122
# 20171130
dst_mail="[email protected]"
mail_title="Linode Website Health Report"
mail_content="\nOops,Your website is still out of service after initiating!\n\n$(iptables -vnL)\n\n\n$(netstat -nltp)\n\n"
free_mem=$(free -m | awk '/Mem/ { print $4 }')
min_mem="300"
echo "free memory is : ${free_mem} MB"
#function to check current website health.
chk_health(){
curl https://peloo.net/?p=262 2>/dev/null | grep -io "routeros"
if [ $? -eq 0 ] ; then
return 0
else
return 1
fi
}
#function to restart mysqld and php-fpm process.
init_service(){
chk_health
if [ ! $? -eq 0 ] ; then
for((i=1;i<=2;i++))
do
service php-fpm stop 2>/dev/null
service php-fpm start
echo -e "\n......php-fpm started successfully !\n"
echo -e "\n++++++++++++++++++++++++++++++++++++\n"
service mysqld stop 2>/dev/null
service mysqld start
echo -e "\n...... MySQL server started successfully !\n"
done
else
echo -e "\n......Your website is OK !\n"
fi
}
#function to do something when backup ending.
post_do(){
ping -c 30 127.1 1>/dev/null 2>&1
chk_health
if [ ! $? -eq 0 ] ; then
echo -e "\n Damn it , Your website is still out of service !!! \n"
echo -e "${mail_content}" | mailx -v -s "${mail_title}" "${dst_mail}"
fi
}
init_service
post_do
exit 0
解释:
A)函数chk_health()用来通过curl请求网页内容,如果返回的字符串检测不到,则判定网站宕机。
B)函数 init_service()先调用chk_health(),如果宕机,则重启MySQL和PHP服务。
C)post_do()函数用来做后置处理工作,主要是再次调用chk_health()函数来检测网站是否恢复正常,如果不正常,则邮件提示我自己。
2 添加Linux定时任务计划
每隔20分钟运行健康检测脚本
echo "*/20 * * * * root /bin/bash /srv/sh/init_service.sh" >>/etc/crontab