In the actual work of small and medium-sized to encounter a problem that is when I go to operate the deployment script, another person can also operate, this how can do, and then the small part of the thought to re-optimize the code, add a process lock
The usual, first comb the idea:
At the same time, the script can only allow one person to operate, that is to say
As long as the script executes to create a file, as long as the file exists, then let the script exit, and prompt "script is really running", the script is completed, delete the created file
The code is as follows
#!/bin/bash
# 功能:打包代码
# 名称:deploy.sh
# 灰度
# 版本:0.4
# 联系方式:xxxxx
# 日志功能
write_log(){
LOG_DATE=`date +%F`
LOG_TIME=`date +%T`
buzhou="$1"
echo " ${LOG_DATE} ${LOG_TIME}$0${buzhou}" >> /data/logs/deploy.log
}
# 增加锁文件
add_lock(){
echo "增加锁文件"
touch /tmp/deploy.pid
write_log "增加锁文件"
}
# 删除锁文件
del_lock(){
echo "删除锁文件"
rm -f /tmp/deploy.pid
write_log "删除锁文件"
}
# 打包代码
tar_code(){
echo "打包代码"
ssh [email protected].168.56.12 "/bin/bash /data/scripts/code_tar.sh"
write_log "打包代码"
}
# 传输代码
scp_code(){
echo "传输代码"
cd /data/codes/
[ -f django.tar.gz ] && rm -f django.tar.gz
[ -d django ] && rm -rf django
scp [email protected].168.56.12:/data/code/django.tar.gz ./
write_log "传输代码"
}
# 关闭应用
serv_stop(){
echo "关闭nginx应用"
/data/server/nginx/sbin/nginx -s stop
write_log "关闭nginx应用"
echo "关闭django应用"
django_pid=$(lsof -Pti :8000)
kill "${django_pid}"
write_log "关闭django应用"
}
# 解压代码
untar_code(){
echo "解压代码"
cd /data/codes/
tar xf django.tar.gz
write_log "解压代码"
}
# 放置代码
fangzhi_code(){
echo "备份原文件"
B_TIME=$(date +%Y%m%d%H%M%S)
mv /data/server/itcast/test1/views.py /data/backup/views.py-"${B_TIME}"
write_log "备份原文件"
echo "放置新文件"
mv /data/codes/django/views.py /data/server/itcast/test1/
write_log "放置新文件"
}
# 开启应用
serv_star(){
echo "开启django应用"
source /data/virtual/venv/bin/activate
cd /data/server/itcast/
python manage.py runserver >>/dev/null 2>&1 &
deactivate
write_log "开启django应用"
echo "开启nginx应用"
/data/server/nginx/sbin/nginx
write_log "开启nginx应用"
}
# 检查
check(){
echo "检查部署效果"
netstat -tnulp | grep ‘:80‘
write_log "检查部署效果"
}
main(){
if [ -f /tmp/deploy.pid ]
then
echo "$0 脚本正在执行中..."
exit
else
add_lock
tar_code
scp_code
serv_stop
untar_code
fangzhi_code
serv_star
check
del_lock
fi
}
main
Shell Programming-project Deployment (optimization)