postgresql 高可用 etcd + patroni 之六 callback bind vip

时间:2022-03-25 20:17:06

os: centos 7.4
postgresql: 9.6.9
etcd: 3.2.18
patroni: 1.4.4

本篇blog介绍下 etcd + patroni 发生切换时使用 callback 来重新设定 master 的 vip。
主要是方便自有机房或托管的,云环境貌似不能绑定固定的vip。

patroni 的一些参数

官方文档描述在callback时又这几个状态:

on_reload: run this script when configuration reload is triggered.
on_restart: run this script when the cluster restarts.
on_role_change: run this script when the cluster is being promoted or demoted.
on_start: run this script when the cluster starts.
on_stop: run this script when the cluster stops.



# su - postgres
$ vi /usr/patroni/conf/patroni_postgresql.yml

postgresql:
  callbacks:
    on_start: /usr/patroni/conf/patroni_callback.sh
    on_stop: /usr/patroni/conf/patroni_callback.sh
    on_role_change: /usr/patroni/conf/patroni_callback.sh

patroni_callback.sh

这个脚本的作用就是,当本地postgresql变为 master 时,就绑定vip,变为slave时,就删除vip。

# cd /usr/patroni/conf/
# vi patroni_callback.sh

#!/bin/bash

readonly cb_name=$1
readonly role=$2
readonly scope=$3

function usage() {
    echo "Usage: $0 <on_start|on_stop|on_role_change> <role> <scope>";
    exit 1;
}

echo "this is patroni callback $cb_name $role $scope"

case $cb_name in
    on_stop)
        sudo ip addr del 192.168.56.100/24 dev enp0s8 label enp0s8:1   
        #sudo arping -q -A -c 1 -I enp0s8 192.168.56.100
        sudo iptables -F
        ;;
    on_start)
        ;;
    on_role_change)
        if [[ $role == 'master' ]]; then
            sudo ip addr add 192.168.56.100/24 brd 192.168.56.255 dev enp0s8 label enp0s8:1
            sudo arping -q -A -c 1 -I enp0s8 192.168.56.100
            sudo iptables -F
        elif [[ $role == 'slave' ]]||[[ $role == 'replica' ]]||[[ $role == 'logical' ]]; then
            sudo ip addr del 192.168.56.100/24 dev enp0s8 label enp0s8:1   
            #sudo arping -q -A -c 1 -I enp0s8 192.168.56.100
            sudo iptables -F
        fi
        ;; 
    *)
        usage
        ;;
esac


修改ip后,一定要使用 arping

配置 sudo

# visudo 
postgres ALL=(ALL) NOPASSWD:ALL


更改权限

# chown -R postgres:postgres /usr/patroni/conf/*
# ls -l
total 8
-rwxr--r-x 1 postgres postgres  768 Aug  8 18:59 patroni_callback.sh
-rw-r--r-- 1 postgres postgres 1616 Aug  8 18:44 patroni_postgresql.yml

参考:
https://postgresconf.org/system/events/document/000/000/228/Patroni_tutorial_4x3-2.pdf