!/bin/bash ################################ ## Author: xgmin ## Version: 1.0 ## Date: 20191121 ################################ yum clean all && yum repolist yum install vim tree -y #安装keepalived##################### mkdir -p /etc/keepalived/script mkdir -p /var/log/keepalived #增加keepalived主从切换脚本######### tee > /etc/keepalived/script/pgsql_check.sh <<'EOF'

#!/bin/bash VIP=ip a | grep 10.10.10.247 | wc -l #判断是否是从库处于等待的状态 Standby_Wait=ps -ef | grep postgres | grep 'startup process' | wc -l #判断从库链接主库是否正常 Standby_Primary=ps -ef | grep postgres | grep 'receiver' | wc -l #判断主库连接从库是否正常 Primary_Standby=ps -ef | grep postgres | grep 'sender' | wc -l #如果pgstgresql端口号不存在,将消息写入日志并且关闭keepalived if [ $(netstat -lntup | grep 5432 | wc -l) -eq 0 ]; then echo "[$(date +"%F %T")] postgresql stop so vip stop" >> /var/log/keepalived/check_pg.log systemctl stop keepalived

else #判断出主挂了,vip浮到了从,提升从的地位让他可读写 if [ $VIP -eq 1 ] && [ $Standby_Wait -eq 1 ] && [ $Standby_Primary -eq 0 ]; then su - postgres -c "pg_ctl promote -D /var/lib/pgsql/9.6/data/"     echo "[$(date +"%F %T")] standby promote" >> /var/log/keepalived/check_pg.log fi #判断出自己是主并且和从失去联系 if [ $VIP -eq 1 ] && [ $Standby_Wait -eq 0 ] && [ $Standby_Primary -eq 0 ] && [ $Primary_Standby -eq 0 ]; then sleep 5 && echo "[$(date +"%F %T")] can not find standby" >> /var/log/keepalived/check_pg.log fi fi EOF sleep 3 chmod +x /etc/keepalived/script/pgsql_check.sh yum install keepalived -y #修改keepalived配置文件############# tee > /etc/keepalived/keepalived.conf <<'EOF' ! Configuration File for keepalived

global_defs { router_id PRO_PGSQL }

vrrp_script chk_pgsql_proxy { script "/etc/keepalived/script/pgsql_check.sh" interval 2 weight -20 }

vrrp_instance VI_1 { state BACKUP interface eth0 virtual_router_id 90 priority 200 advert_int 1 nopreempt authentication { auth_type PASS auth_pass 363747 } virtual_ipaddress { 10.10.10..247/24 dev eth0 label eth0:vip } track_script { chk_pgsql_proxy } } EOF #修改keepalived日志################# sed -i '14 s#KEEPALIVED_OPTIONS="-D"#KEEPALIVED_OPTIONS="-D -d -S 0"#g' /etc/sysconfig/keepalived sed -i '1 i/var/log/keepalived/keepalived.log' /etc/logrotate.d/syslog sed -i '42 i# keepalived' /etc/rsyslog.conf sed -i '43 ilocal0.* /var/log/keepalived/keepalived.log' /etc/rsyslog.conf sed -i '44 i*.err;kern.debug;daemon.notice;local0.none /var/log/messages' /etc/rsyslog.conf sed -i '45 i\ ' /etc/rsyslog.conf systemctl restart rsyslog