今日,一个用户反馈老的系统应用服务不稳定,有自己停掉的风险,需要开发一个自动重启定时服务的脚本。基于这个需求,我开发了一个sh脚本进行服务的检测和重启,以下操作仍有许多不足之处,请斟酌后使用。
服务状态检测
基于现有服务采取ps aux|grep {command}|grep -v grep|wc -l` -gt 0
或者systemctl status {service_name}
进行判断,根据$?
(上一次命令退出状态)判断服务是否正常运行。
服务重启
根据服务状态检测结果决定是否执行服务重启命令
脚本内容(仅供参考)
#!/bin/bash
# sudo
if [ `id -u` -ne 0 ]
then
echo "please use sudo privilege!"
exit
fi
# 检测
detect() {
if [ "${1:0:8}" = "command:" ]
then
${1:8} > /dev/null 2>&1
[ $? -eq 0 ]
else
[ `ps aux|grep $1|grep -v grep|wc -l` -gt 0 ]
fi
return $?
}
# 检测和重启($1:服务名;$2:检测命令;$3:启动命令)
detect_and_retry() {
# 消息定义
successMessage="\033[32m success\033[0m"
failedMessage="\033[31m failed\033[0m"
# 检测服务(command:使用命令退出状态来判断;否则用ps查看进程数判断)
echo -ne " > $1:"
detect "$2"
if [ $? -eq 0 ]
then
echo -e $successMessage
else
echo -e $failedMessage
# 未传入命令视为手动处理
if [ -z "$3" ]
then
echo -e " >> please restart manually!"
return
fi
# 尝试重启
echo -ne " >> try restart:"
$3 >/dev/null 2>&1 &
# 重新检测服务运行状态
sleep 1
detect "$2"
if [ $? -eq 0 ]
then
echo -e $successMessage "pid:$!"
else
echo -e $failedMessage
fi
fi
}
# 检测mongod服务
echo "detect services..."
detect_and_retry "mongo" "mongo" "nohup /usr/bin/mongod --config /etc/mongod.conf"
# 检测mysql服务
detect_and_retry "mysql" "command:systemctl status mysqld.service" "systemctl start mysqld.service"
# 检测nginx服务
detect_and_retry "nginx" "nginx" "nohup /usr/local/nginx/sbin/nginx"
# 检测php-fpm服务
detect_and_retry "php-fpm" "command:systemctl status php-fpm" "systemctl start php-fpm.service"
思考
- 服务可以改写成systemd服务来保证服务异常重启和开机重启
- 服务可以改写成docker容器启动并通过docker保证容器的可用