导语:生产环境发布没有健康检查,需要手动一半一半发布。经常会忘记发另一部分,而且需要去查看是否发布成功。打算优化一下 发布流程。找了如下2个ansible的模块。
wait_for
test.yml 用作检测端口状态
# /tmp/test.yml
- hosts: test
gather_facts: no
tasks:
- name: Wait for
wait_for:
port: "{{ port }}"
delay: 10
timeout: 300
担心端口起来了 可能服务还没有就绪。比如tomcat服务已经就绪,端口健康。 但是服务还没有startup
查了下资料,貌似这个wait_for没办法使用shell 为了保证发布的安全,本来打算用一个shell的task,去检查状态并写入文件,再通过search_regex的方法去判断服务是否正常,后面使用了async
async
先测试一下
health_test2.yml
# health_test2.yml
- hosts: health-prod2
environment:
LC_ALL: zh_CN.UTF-8
LANG : zh_CN.UTF-8
tasks:
- name: wair for
shell: sleep 16 // 这里可以设置健康检查的命令
async: 10
poll: 2
进行修改,改成自己想要的效果。
原shell 健康检查脚本
second=2
while true; do
result=$( (
sleep 1
echo 'status'
sleep 1
) | telnet localhost 20916)
echo "------"
if [[ "$result" =~ OK ]]; then
echo 通了
break
elif [ ${second} -ge 150 ]; then
echo "部署等待时间过长 判断为部署失败 请自行检查服务状态" && exit 1
else
second=$((second + 7)) && sleep 5
fi
done
echo "++++"
把上面的脚本锁成一行
second=2;while true; do result=$((sleep 1 ;echo 'status';sleep 1) | telnet localhost 20902);echo "------";if [[ "$result" =~ OK ]]; then echo 通了;break;elif [ ${second} -ge 300 ]; then echo "部署等待时间过长 判断为部署失败 请自行检查服务状态" && exit 1;else second=$((second + 7)) && sleep 5;fi;done;echo "++++"
需要修改添加ansible的host 如下
# 添加一个health的组,里面包含health-gray,health-prod,health-prod1,health-prod2 这几个组,这几个组共享health的参数,dubbo_port=20909,tomcat_port=8809
[health:children]
health-gray
health-prod
health-prod1
health-prod2
[health:vars]
dubbo_port=20909
tomcat_port=8809
最后生成的健康检查文件如下,将dubbo_port 通过/etc/ansible/hosts-prod里的参数传入。
- hosts: health-prod1
gather_facts: no
tasks:
- name: health_check "{{ dubbo_port }}" ,timeout for 300 seconds
shell: second=2;while true; do result=$((sleep 1 ;echo 'status';sleep 1) | telnet localhost "{{ dubbo_port }}");echo "------";if [[ "$result" =~ OK ]]; then echo 通了;break;elif [ ${second} -ge 300 ]; then echo "部署等待时间过长 判断为部署失败 请自行检查服务状态" && date && exit 1;else second=$((second + 7)) && echo second $second && sleep 5;fi;done;echo "++++"
async: 0
poll: 2
- name: Wait for port "{{ tomcat_port }}" to become open on the host, don't start checking for 2 seconds ,timeout for 10 seconds
wait_for:
port: "{{ tomcat_port }}"
delay: 2
timeout: 10
为了确保服务没问题,我检查完dubbo_port的状态之后 仍旧检查了一下tomcat端口的状态,双保险。并且有些服务telnet dubbo端口没有ok的返回,就只能通过tomcat端口或者dubbo_port端口来判断健康状况。后续可以更换成url检查
dubbo_port检查失败如下
tomcat_port检查失败如下(正常情况不会出现dubbo_port健康,tomcat有问题情况,这里是改成错的toncat_port)