我编写了一个小(希望)简单的脚本的一部分,用于检查使用wget返回的URL是否存在错误。然后,它将错误输出到日志文件,以便发出警报。然后我想做的是让服务自动重新启动。
我将通过cronjob每分钟运行一次检查,所以如果在服务重新启动后仍然有错误,我不希望脚本再次重新启动服务。
是否有一种优雅的方式来实现这一点?
这是我到目前为止所做的,一个wget检查,如果错误代码5,输出到health.log文件并重启nginx,但是,我不希望在运行cronjob时每60秒重启一次nginx。
#!bin/bash
URL='http://some-url-here/'
LOG='/var/log/nginx/health.log'
wget -q $URL
if [ $? = 5 ] ; then
echo "$(date). SSL Error." > $LOG
sudo service nginx restart
exit
fi
假设:
- 如果我们创建一个新文件(
restart.log
)是可以的,否则我们可以在$LOG
添加一个新行 - 我们将只执行
restart
尝试每10分钟(aka 600秒) - OP想要附加到当前的
$LOG
(当前代码每次脚本运行时会覆盖/替换整个文件) 提出方法:
- 使用一个新文件来存储最后一次尝试
restart
的纪元时间 - 在尝试
restart
之前,我们将当前纪元与保存的纪元进行比较,只有当纪元差大于600秒时才继续(使用restart
)
修改OP当前脚本:
#!/bin/bash # add "/" at start of shebang path
URL='http://some-url-here/'
LOG='/var/log/nginx/health.log'
RLOG='/var/log/nginx/restart.log'
touch "$RLOG"
wget -q $URL
if [ $? = 5 ] ; then
echo "$(date). SSL Error." >> "$LOG" # replace ">" with ">>" so that we append to $LOG
read -r prev_epoch < <(tail -1 "$RLOG") # retrieve epoch of last restart attempt
prev_epoch="${prev_epoch:-0}" # default to 0 if there is nothing in the file
printf -v curr_epoch '%(%s)T' # use printf builtin to grab current epoch and save in variable 'curr_epoch'
# curr_epoch=$((date '+%s')) # uncomment if 'printf -v' is not available in your system
delta=$((curr_epoch - prev_epoch))
if [[ "${delta}" -gt 600 ]] ; then
sudo service nginx restart
echo "${curr_epoch}" > "$RLOG" # replace ">" with ">>" if you want to maintain a history of restart epochs; the "tail -1" should insure we only grab the 'last' entry
exit
else
echo "it has only been ${delta} seconds since last restart attempt; skipping restart" >> "$LOG"
fi
fi