如何监视代码更新并自动重启?

Bash

1 前言

一个问题,一篇文章,一出故事。
众多的服务器频繁代码更新会占用运维大量的时间,于是笔者想到监视代码的更新并自动重启服务。于是整理此文。

2 最佳实践

2.1 创建脚本目录

mkdir ~/scripts

2.2 创建脚本

vim ~/scripts/autoRestart.sh

加入如下配置,

#!/bin/bash

monitorFiles="/usr/api/api.jar /etc/api/application-prod.properties"
monitorLog="/var/log/autoRestart.log"
monitorDate=`date +"%Y-%m-%d %H:%M:%S"`
serviceList="api.service nginx.service"

if [ ! -f "$monitorLog" ]; then
	touch "$monitorLog"
fi
if [ ! -f "$monitorLog" ]; then
	echo "$monitorDate"' Failed to create log file!'
	exit 1
fi

for i in $serviceList; do
	if [ "$i" == "" ]; then
		echo "$monitorDate"' Service name cannot be empty!' | tee -a "$monitorLog"
		continue
	fi
	checkServer="0"
	checkServer=`/usr/bin/systemctl status "$i" | grep "Active:" | grep "running" | wc -l`
	if [ "$checkServer" != "1" ]; then
		echo "$monitorDate"' Service non-running, this script restarts service!' | tee -a "$monitorLog"
		echo "$monitorDate"' Restarting Service '"$i" | tee -a "$monitorLog"
		/usr/bin/systemctl restart "$i"	
	fi
done

oldFileMd5=""
newFileMd5=""
restartMark="0"
for i in $monitorFiles; do
	if [ "`grep "$i" "$monitorLog" | wc -l`" != "0" ]; then
		oldFileMd5=`grep "$i" "$monitorLog" | cut -d" " -f3 | tail -n 1`
	else
		echo "$monitorDate"' '`md5sum "$i"` >> $monitorLog
	fi
	newFileMd5=`md5sum "$i" | cut -d" " -f1`

	if [ "$oldFileMd5" == "" -o "$newFileMd5" == "" ]; then
		echo "$monitorDate"' Get md5 exception!' | tee -a "$monitorLog"
		exit 1
	fi
	if [ "$oldFileMd5" != "$newFileMd5" ]; then
		echo "$monitorDate"' '`md5sum "$i"` >> $monitorLog
		restartMark="1"
	fi
done

if [ "$restartMark" == "1" ]; then
	echo "$monitorDate"' Program update, this script restarts service!' | tee -a "$monitorLog"
	for i in $serviceList; do
		if [ "$i" == "" ]; then
			echo "$monitorDate"' Service name cannot be empty!' | tee -a "$monitorLog"
			continue
		fi
		echo "$monitorDate"' Restarting Service '"$i" | tee -a "$monitorLog"
		/usr/bin/systemctl restart "$i"	
	done
fi

需要注意的是,
– 参数“monitorFiles”声明需要监视可能更新的代码文件(多个文件请使用空格分隔)
– 参数“monitorLog”声明脚本运行日志路径
– 参数“serviceList”声明需要重启的服务列表(多个服务请使用空格分隔)

2.3 设置脚本触发

crontab -e

加入如下设置,

*/5 * * * * sh ~/scripts/autoRestart.sh
没有评论

发表回复

Bash
如何实现文件夹路径转纯数字符串?

1 前言 一个问题,一篇文章,一出故事。 由于由于需要设置某目录的配额,配额要求为每个目录指定一个项 …

Bash
如何统计Linux打开文件前10进程?

1 前言 一个问题,一篇文章,一出故事。 笔者生产环境有台服务最近压力比较大,打开的文件数量不断地往 …

Bash
如何获取VSFTP昨天活跃和有效用户?

1 前言 一个问题,一篇文章,一出故事。 笔者生产环境有台老旧的FTP服务器,用户众多。笔者希望每天 …