#!/bin/bash
#
#*****************************************************
#File Name    : create_mqcluster.sh
#Author       : guokai
#Mail         : xxx@163.com
#Create Time  : 2022-05-08 22:40:02
#Description  : The test script
#*****************************************************

#cat /etc/ssh/sshd_config.d/01-permitrootlogin.conf请修改允许root登录
MASTER_IP=`ifconfig eth0 | awk '/inet /{print $2}'`
read -p "请输入浮点ip：" VIP
read -p "请输入从节点的ip：" SLAVE_IP
read -p "请输入主节点ens19的ip：" MASTER_ens19_IP
read -p "请输入从节点ens19的ip：" SLAVE_ens19_IP
ROUTER_ID=`echo $VIP | awk -F '.' '{print $4}'`
ROOT_PASSWORD=cqt@2020
SSH_PORT=56022

color () {
	RES_COL=60
	MOVE_TO_COL="echo -en \\033[${RES_COL}G"
	SETCOLOR_SUCCESS="echo -en \\033[1;32m"
	SETCOLOR_FAILURE="echo -en \\033[1;31m"
	SETCOLOR_WARNING="echo -en \\033[1;33m"
	SETCOLOR_NORMAL="echo -en \E[0m"
	echo -n "$2" && $MOVE_TO_COL
	echo -n "["
	if [ $1 = "success" -o $1 = "0" ] ;then ${SETCOLOR_SUCCESS}
		echo -n $"  OK  "
	elif [ $1 = "failure" -o $1 = "1" ] ;then ${SETCOLOR_FAILURE}
		echo -n $"FAILED"
	else 
		${SETCOLOR_WARNING}
		echo -n $"WARNING"
	fi
	${SETCOLOR_NORMAL}
	echo -n "]"
	echo
}

virtual_ip () {
	color 0 "开始配置ens19网卡IP地址..."
    #wget -O /etc/yum.repos.d/epel.repo https://mirrors.aliyun.com/repo/epel-7.repo
	#dnf install -y ansible-core sshpass
	cat >> /etc/ansible/hosts <<EOF
[keepalived]
$MASTER_IP ansible_ssh_port=$SSH_PORT
$SLAVE_IP ansible_ssh_port=$SSH_PORT
EOF
	ssh-keygen -f /root/.ssh/id_rsa -N ""
	sshpass -p $ROOT_PASSWORD ssh-copy-id -p $SSH_PORT  -o StrictHostKeyChecking=no root@$SLAVE_IP
	cat > /etc/sysconfig/network-scripts/ifcfg-ens19 << EOF
TYPE=Ethernet
BOOTPROTO=static
NAME=ens19
DEVICE=ens19
ONBOOT=yes
IPADDR=$MASTER_ens19_IP
PREFIX=30
EOF
    nmcli connection  reload
	nmcli connection down ens19
	nmcli connection up ens19
	cat > /root/ifcfg-ens19_slave << EOF
TYPE=Ethernet
BOOTPROTO=static
NAME=ens19
DEVICE=ens19
ONBOOT=yes
IPADDR=$SLAVE_ens19_IP
PREFIX=30
EOF
	ansible $SLAVE_IP -m copy -a "src=/root/ifcfg-ens19_slave backup=yes dest=/etc/sysconfig/network-scripts/ifcfg-ens19"
    ansible $SLAVE_IP -m shell -a "nmcli connection  reload"
	ansible $SLAVE_IP -m shell -a "nmcli connection down ens19"
	ansible $SLAVE_IP -m shell -a "nmcli connection up ens19"
	sleep 3
	ping $MASTER_ens19_IP -c 3  && color 0 "MASTER节点ens19网卡配置成功" || { color 1 "MASTER节点ens19网卡配置失败,退出配置查看原因" ; exit ; }
	ping $SLAVE_ens19_IP -c 3 && color 0 "SLAVE节点ens19网卡配置成功" || { color 1 "SLAVE节点ens19网卡配置失败,退出配置查看原因" ; exit ; }
}
	
keepalived () {
	MASTER_HOSTNAME=`hostname` 
	SLAVE_HOSTNAME=`ansible $SLAVE_IP -m shell -a "hostname" | tail -1`
	color 0 "开始修改配置文件..."
	cat > /home/keepuser/keepalived/keepalived.conf  << EOF
! Configuration File for keepalived
#配置默认
global_defs {
   notification_email {
     acassen@firewall.loc
     failover@firewall.loc
     sysadmin@firewall.loc
   }
   notification_email_from Alexandre.Cassen@firewall.loc
   smtp_server 192.168.200.1
   smtp_connect_timeout 30
   router_id $MASTER_HOSTNAME
   vrrp_skip_check_adv_addr
   vrrp_garp_interval 0
   vrrp_gna_interval 0
}
#设置检测脚本
vrrp_script checktest{
        script "/home/keepuser/keepalived/check.sh"
        interval 1
        weight -2 #需要结合主从priority的差值,非0时减去数值，使优先级降低
        fall 3
        rise 2
}
#设置vrrp的端口（实际端口）， 角色（MASTER），id（主备相同），优先级(主节点大)，认证信息(主备相同)
vrrp_instance NO011 {
    state MASTER
    interface ens19
    virtual_router_id $ROUTER_ID
    priority 100
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 111111
    }
    unicast_src_ip $MASTER_ens19_IP
    unicast_peer {
        $SLAVE_ens19_IP
    }

#设置虚拟IP
    virtual_ipaddress {
       $VIP/24 dev eth0 label eth0:0
    }
#调用检测脚本
   track_script {
        checktest
   }
}
EOF

cat > /root/keepalived_slave.conf << EOF
! Configuration File for keepalived
global_defs {
   notification_email {
     acassen@firewall.loc
     failover@firewall.loc
     sysadmin@firewall.loc
   }
   notification_email_from Alexandre.Cassen@firewall.loc
   smtp_server 192.168.200.1
   smtp_connect_timeout 30
   router_id $SLAVE_HOSTNAME
   vrrp_skip_check_adv_addr
   vrrp_garp_interval 0
   vrrp_gna_interval 0
}
vrrp_script checktest{
        script "/home/keepuser/keepalived/check.sh"
        interval 1
        weight -2 
        fall 3
        rise 2
}

vrrp_instance NO011 {
    state BACKUP #不同点
    interface ens19
    virtual_router_id $ROUTER_ID
    priority 99 #不同点
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 111111
    }
    unicast_src_ip $SLAVE_ens19_IP
    unicast_peer {
        $MASTER_ens19_IP
    }

    virtual_ipaddress {
       $VIP/24 dev eth0 label eth0:0
    }
   track_script {
        checktest
   }
 }
EOF

cat > /home/keepuser/keepalived/check.sh << EOF
#!/bin/bash
. /etc/profile
. ~/.bash_profile
ha_pid=\`ps aux | grep -v grep |grep haproxy | grep -v check.sh | wc -l\`
if [ \${ha_pid} -eq 0 ]; then
        exit 1
else
        exit 0
fi
EOF

chmod 755 	/home/keepuser/keepalived/check.sh
chown keepuser:keepuser /home/keepuser/keepalived/check.sh
	ansible $SLAVE_IP -m copy -a "src=/root/keepalived_slave.conf backup=yes dest=/home/keepuser/keepalived/keepalived.conf"
	ansible $SLAVE_IP -m copy -a "src=/home/keepuser/keepalived/check.sh dest=/home/keepuser/keepalived/check.sh"
	ansible $SLAVE_IP -m shell -a "chmod 755 	/home/keepuser/keepalived/check.sh"
    ansible $SLAVE_IP -m shell -a "chown keepuser:keepuser /home/keepuser/keepalived/check.sh"
	systemctl restart keepalived-nonroot.service
	systemctl is-active keepalived-nonroot.service && color 0 "主节点 keepalived 重启成功"
	ansible $SLAVE_IP -m shell -a "systemctl restart keepalived-nonroot.service"
	ansible $SLAVE_IP -m shell -a "systemctl is-active keepalived-nonroot.service" && color 0 "从节点 keepalived 重启成功"

	VIP1=`ifconfig eth0:0 | awk '/inet/ {print $2}'`
	VIP2=`ansible $SLAVE_IP -m shell -a "ifconfig eth0:0" | awk '/inet/ {print $2}'`
if 
	[ "$VIP1" = "$VIP" -a "$VIP2" != "$VIP" ] ; then 
	color 0 "VIP 在主节点上且不存在脑裂现象，配置正常！"
	else 
	color 1 "异常！！！请检查VIP的配置情况！"
fi
}	

virtual_ip
keepalived
