又拍云之 Keepalived 高可用部署( 二 )

配置中用到了“check_vip.sh”和“change_state.sh”的两个脚本,我们也来简单看下 。
check_vip.sh上面配置中只是举例说明,当 ping 丢包严重超过 80% 时,就认为要切换主备关系了 。大家也可以根据具体的业务场景做一些逻辑判断,来实现主备切换,以达到高可用的目的 。
#!/bin/shTMP="/tmp/bad"GATEWAY=$(ip ro|awk '/default/{print $3}')LOSS=$(ping -fc10 -s1 $GATEWAY | sed -r -n '/loss/s@.* (.*)%.*@\1@p')if [ $LOSS -ge 80 ];thenecho "${LOSS}% lost#`date`" >> $TMPfiif [ -e $TMP ] ;thenexit 1fichange_state.sh当检测到服务器的角色转换时,这个脚本就会调用钉钉报警,并且调整业务上的一些操作 。如 sysctl.conf 配置或者 iptables 上的规则,甚至可以配合 LVS 做一些负载均衡的部署 。
#!/bin/bashHOME="/etc/keepalived/"LIP=`/sbin/ip addr | awk '/192.168./{gsub("/.*","");if($2!=""){print $2}}'|sort -u|head -n1`VIP=$(awk '/virtual_ipaddress/{getline; print $1}' $HOME/keepalived.conf)URL="https://oapi.dingtalk.com/robot/send?access_token=07xxxxxxxxxxxxx"[ -z $LIP ] && LIP=$VIP############################################################################dingding(){curl $URL --connect-timeout 10 -H 'Content-Type: application/json' \-d '{"msgtype": "markdown","markdown": {"title": "数据中心报警","text": "* 报警类别: '"$1"'\n* 报警机器: '"$2"'\n* 报警服务: '"$3"'\n* 报警内容: '"$4"'\n* 报警时间: '"$(date "+%Y-%m-%d %T")"'\n"}}'}ENDSTATE=$3NAME=$2TYPE=$1dingding Keepalived $LIP Change_state "$ENDSTATE"case $ENDSTATE in"BACKUP") # Perform action for transition to BACKUP stateecho "--- I am$ENDSTATE #`date`" >> /tmp/keepalived.logsed -r -i '/state/s#MASTER#BACKUP#g' $HOME/keepalived.confsysctl -w \net.ipv4.conf.all.arp_accept=1 \net.ipv4.conf.all.arp_ignore=0 \net.ipv4.conf.all.arp_announce=0\net.ipv4.ip_nonlocal_bind=1#$HOME/tunl startexit 0;;"FAULT")# Perform action for transition to FAULT stateexit 0;;"MASTER") # Perform action for transition to MASTER stateecho "+++ I am$ENDSTATE #`date`" >> /tmp/keepalived.logsed -r -i '/state/s#BACKUP#MASTER#g' $HOME/keepalived.confsysctl -w \net.ipv4.conf.all.arp_ignore=1 \net.ipv4.conf.all.arp_accept=1 \net.ipv4.conf.all.arp_announce=1\net.ipv4.ip_nonlocal_bind=1iptables -L -vn | grep -iqE "vrrp|112"[ $? = 0 ] || iptables -I INPUT -p vrrp -j ACCEPTiptables -L -vn | grep -iq "accept .*$VIP"[ $? = 0 ] || iptables -I INPUT -d $VIP -j ACCEPTexit 0;;*)echo "Unknown state ${ENDSTATE} for VRRP ${TYPE} ${NAME}"exit 1;;esac今天的分享就到这了,大家可以扫描下方二维码加又小拍好友,期望与你有更多交流 。
推荐阅读详解 SSL(三):SSL 证书该如何选择?
红利风口下,企业出海如何强势突围?
【又拍云之 Keepalived 高可用部署】

经验总结扩展阅读