需求:编写脚本实现对redis cluster 主从是否发生主从切换进行监控,若发生切换,输出切换前后主从对应关系。
初始化对比文件,仅执行一次,后续不需要在执行,除非该文件不存在。
cmd="redis-cli -c -h $1 -p $2"
$cmd cluster nodes > cluster_nodes.txt
cat cluster_nodes.txt | awk -F[\ \@] '/master/{print $1,$2}' | sort -nk2 -t ':' > master.txt
cat cluster_nodes.txt | awk -F[\ \@] '/slave/{print $2,$5}' | sort -nk1 -t ':' > slave.txt
cat master.txt | while read m
do
master_ip_port=`echo $m | awk '{print $2}'`
master_tag=`echo $m | awk '{print $1}'`
cat slave.txt | while read s
do
slave_ip_port=`echo $s | awk '{print $1}'`
slave_tag=`echo $s | awk '{print $2}'`
if [[ ${master_tag} == ${slave_tag} ]];then
echo "${master_ip_port}->${slave_ip_port}" >> master_slave_map_old
fi
done
done
判断是否发生切换,如果发生,输出切换前后的对应关系
cmd="redis-cli -c -h $1 -p $2"
$cmd cluster nodes > cluster_nodes.txt
cat cluster_nodes.txt | awk -F[\ \@] '/master/{print $1,$2}' | sort -nk2 -t ':' > master.txt
cat cluster_nodes.txt | awk -F[\ \@] '/slave/{print $2,$5}' | sort -nk1 -t ':' > slave.txt
cat master.txt | while read m
do
master_ip_port=`echo $m | awk '{print $2}'`
master_tag=`echo $m | awk '{print $1}'`
cat slave.txt | while read s
do
slave_ip_port=`echo $s | awk '{print $1}'`
slave_tag=`echo $s | awk '{print $2}'`
if [[ ${master_tag} == ${slave_tag} ]];then
echo "${master_ip_port}->${slave_ip_port}" >> master_slave_map_new
fi
done
done ports=($($cmd cluster nodes | awk -F[\ \:\@] '{print $3}' | sort |uniq))
len=${#ports[@]} for ((i=;i<=$len-;i++))
do
old=$(grep ${ports[i]} master_slave_map_old | md5sum | awk '{print $1}')
new=$(grep ${ports[i]} master_slave_map_new | md5sum | awk '{print $1}')
if [[ "${old}" != "${new}" ]];then
echo -n "${ports[i]}主从实例切换前:"
grep ${ports[i]} master_slave_map_old
echo -n "${ports[i]}主从实例切换后:"
grep ${ports[i]} master_slave_map_new
fi
done cat master_slave_map_new > master_slave_map_old
rm -rf master_slave_map_new
测试过程:
5.5.5.101:> info replication
# Replication
role:slave
master_host:5.5.5.102
master_port:
master_link_status:up
master_last_io_seconds_ago:
master_sync_in_progress:
slave_repl_offset:
slave_priority:
slave_read_only:
connected_slaves:
master_replid:3c06fcc274b6fac6fe1d954f8b63687619e65cf5
master_replid2:
master_repl_offset:
second_repl_offset:-
repl_backlog_active:
repl_backlog_size:
repl_backlog_first_byte_offset:
repl_backlog_histlen:
lxd-vm1:> CLUSTER FAILOVER
OK
5.5.5.101:> info replication
# Replication
role:master
connected_slaves:
slave0:ip=5.5.5.102,port=,state=online,offset=,lag=
master_replid:a35374725759383211f8f76d6b9376d181beda17
master_replid2:3c06fcc274b6fac6fe1d954f8b63687619e65cf5
master_repl_offset:
second_repl_offset:
repl_backlog_active:
repl_backlog_size:
repl_backlog_first_byte_offset:
repl_backlog_histlen:
lxd-vm1:>
测试结果
[redis@lxd-vm3 ~]$ sh a2.sh 5.5.5.101
29001主从实例切换前:5.5.5.102:->5.5.5.101:
29001主从实例切换后:5.5.5.101:->5.5.5.102:
[redis@lxd-vm3 ~]$