1、介绍
nginx运维脚本,包含启动,停止,重启,重新加载配置,平滑升级,服务状态检查 使用方法:
- 在脚本同级目录下新建nginxPath.txt文件,输入nginx运行目录,如:/home/jiang/resty/bin/nginx
- 执行sh control.sh start启动nginx
2、源代码
脚本名control.sh
#!/bin/bash
ACTION=$1
curr_dir=$(cd "$(dirname "$0")" || exit; pwd)
nginx_path=$(cat "${curr_dir}"/nginxPath.txt)
pid_file="${nginx_path}/logs/nginx.pid"
function check()
{
local ok=0
master_count=$(ps -ef | grep -v grep | grep -c "master process" )
if (( master_count > 1 )); then
echo "[check] Error, master count is more than one!"
ok=1
elif (( master_count > 1 )); then
echo "[check] Error, master count is more than one!"
ok=1
else
echo "[check] OK, The process is running normally!"
fi
if [ -f "$pid_file" ]; then
pid=$(cat "${pid_file}")
master_pid=$(ps -ef | grep -v grep | grep "master process" | awk '{print $2}')
if [ "y${pid}" == "y${master_pid}" ]; then
echo "[check] OK, Pid file no problem!"
else
echo "[check] Error, Pid file not correct!"
ok=1
fi
else
echo "[check] Error, Pid file does not exist!"
ok=1
fi
echo "[check] OK, Timer task ok!"
return "${ok}"
}
function start()
{
master_count=$(ps -ef | grep -v grep | grep -c "master process" )
if (( master_count >= 1 )); then
echo "[start] OK, nginx is alredy running, nothing to do!"
return 1
fi
"${nginx_path}"/sbin/nginx -t
if [ $? != 0 ]; then
echo "[start] Error, Nginx conf file test error!!!!!!"
return 1
fi
"${nginx_path}"/sbin/nginx
sleep 0.5
master_count=$(ps -ef | grep -v grep | grep -c "master process" )
if (( master_count != 1 )); then
echo "[start] Error, Conf ok but master process start failed!!!!!!"
return 1
fi
ps -ef | grep nginx
echo "[start] OK"
return 0
}
function stop()
{
nginx_count=$(ps -ef | grep -v grep | grep -c "nginx:" )
if (( nginx_count == 0 )); then
echo "[stop] OK, nginx has stopped, nothing to do!"
return 1
fi
"${nginx_path}"/sbin/nginx -s stop
sleep 0.5
nginx_count=$(ps -ef | grep -v grep | grep -c "nginx:" )
if (( nginx_count != 0 )); then
echo "[stop] Error, stop failed!"
return 1
fi
echo "[stop] OK"
return 0
}
function update()
{
if [ ! -f "$pid_file" ]; then
echo "[update] Error, Pid file does not exist!!!!!!"
return 1
fi
master_count=$(ps -ef | grep -v grep | grep -c "master process" )
if (( master_count != 1 )); then
echo "[update] Error, Master count does not equal 1 !!!!!!"
return 1
fi
pid=$(cat "${pid_file}")
kill -USR2 "${pid}"
sleep 0.5
kill -WINCH "${pid}"
kill -QUIT "${pid}"
echo "[update] OK"
check
return $?
}
function usage()
{
echo ""
echo "=============control 脚本使用方法============="
echo " 1、启动服务 sh control.sh start"
echo " 2、停止服务 sh control.sh stop"
echo " 3、重启服务 sh control.sh restart"
echo " 4、重新加载配置文件 sh control.sh reload"
echo " 5、服务平滑升级 sh control.sh update"
echo " 6、服务状态检测 sh control.sh check"
echo " 7、脚本使用方法 sh control.sh usage"
echo "============================================="
echo ""
}
function main()
{
case "${ACTION}" in
start)
start
;;
stop)
stop
;;
restart)
stop
start
;;
reload)
start
stop
;;
update)
update
;;
check)
check
;;
*)
usage
;;
esac
exit $?
}
main "$@"
|