Skip to content

Commit a6c5863

Browse files
committed
add keepalived migrating vip example
1 parent b7debad commit a6c5863

File tree

3 files changed

+191
-0
lines changed

3 files changed

+191
-0
lines changed

examples/keepalived.conf

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
! Configuration File for keepalived
2+
3+
global_defs {
4+
notification_email {
5+
acassen@firewall.loc
6+
failover@firewall.loc
7+
sysadmin@firewall.loc
8+
}
9+
notification_email_from Alexandre.Cassen@firewall.loc
10+
smtp_server 192.168.200.1
11+
smtp_connect_timeout 30
12+
router_id LVS_DEVEL
13+
vrrp_skip_check_adv_addr
14+
vrrp_garp_interval 0
15+
vrrp_gna_interval 0
16+
}
17+
18+
vrrp_instance VI_1 {
19+
#注意主备参数选择
20+
state BACKUP #无常主模式初始角色,均填写 BACKUP
21+
#state BACKUP #备
22+
interface eth0 #改成本机网卡名 例如 eth0
23+
virtual_router_id 51
24+
nopreempt #非抢占模式
25+
# preempt_delay 10
26+
priority 50 #无常主模式大小相同
27+
advert_int 1
28+
authentication {
29+
auth_type PASS
30+
auth_pass 1111
31+
}
32+
unicast_src_ip 172.18.0.13 # 修改本机内网 IP
33+
unicast_peer {
34+
172.18.0.16 #修改为对端设备的 IP 地址
35+
}
36+
virtual_ipaddress {
37+
172.18.0.253 #修改为内网 VIP
38+
}
39+
notify_master "/etc/keepalived/notify_action.sh MASTER"
40+
notify_backup "/etc/keepalived/notify_action.sh BACKUP"
41+
notify_fault "/etc/keepalived/notify_action.sh FAULT"
42+
notify_stop "/etc/keepalived/notify_action.sh STOP"
43+
garp_master_delay 1
44+
garp_master_refresh 5
45+
track_interface {
46+
eth0 #改成本机网卡名 例如 eth0
47+
}
48+
track_script {
49+
checkhaproxy
50+
}
51+
}

examples/nexthop.py

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
#!/usr/bin/python
2+
# -*- coding: utf-8 -*-
3+
#/etc/keepalived/nexthop.py
4+
5+
import os
6+
import time
7+
import json
8+
import sys
9+
from kscore.session import get_session
10+
11+
##################需修改部分Begin####################
12+
region='cn-beijing-6' #region code
13+
vpcId = '1858a08a-6cc9-4278-8d0c-d536f441fe8e' #vpcId
14+
ks_access_key_id = '您的ak'
15+
ks_secret_access_key = '您的sk'
16+
vip = "172.18.0.253" #改成您的本机内网 VIP
17+
DestinationCidrBlock = '172.18.0.253/32' #修改为VIP
18+
thisInstanceId = '1cf963ff-7847-4859-8462-5405f0facc1d' #当前主机的Id
19+
thatInstanceId = 'b141da5f-8e3e-44c0-ac0f-a0feccba78c7' #迁移前所在主机Id
20+
interface = {"eth0":"172.18.0.13"} #当前机器主网卡和主IP
21+
##################需修改部分End######################
22+
23+
log = open('/var/log/keepalived.log', 'a+')
24+
state_file = open('/var/keepalived/state', 'r')
25+
26+
def get_now_time():
27+
return time.strftime('[%Y-%m-%d %H:%M:%S]',time.localtime(time.time())) + '[pid' + str(os.getpid()) + ']'
28+
29+
def log_write(message=''):
30+
log.write(get_now_time() + " " + str(message) + "\n")
31+
32+
def get_ip():
33+
f = os.popen('ip addr show dev %s | grep %s | awk \'{print $2}\' | awk -F/ \'{print $1}\'' % (interface.keys()[0] , interface.values()[0]))
34+
return f.read().strip()
35+
36+
def findRoute():
37+
for route in vpcClient.describe_routes()['RouteSet']:
38+
if route['DestinationCidrBlock'] == DestinationCidrBlock:
39+
print 'current route found'
40+
return route['RouteId']
41+
42+
print 'route not found'
43+
def migrateVip():
44+
params = {
45+
'vpcId': vpcId,
46+
'privateIpAddress': vip,
47+
'thatInstanceId': thatInstanceId,
48+
'thisInstanceId': thisInstanceId
49+
}
50+
51+
log_write(" try set vip.")
52+
retry_times_when_mgr_ip_got = 4
53+
exceptimes = 0
54+
get_ip_times = 0
55+
time.sleep(0.5)
56+
r = findRoute()
57+
if r:
58+
vpcClient.delete_route(**{'RouteId':r})
59+
log_write(" now change the nexthop of vip to this host." + get_ip())
60+
vpcClient.create_route(**{'VpcId':vpcId,'DestinationCidrBlock':DestinationCidrBlock,'RouteType':'Host','InstanceId':thisInstanceId})
61+
while get_ip_times < 5:
62+
log_write(" get_ip=" + get_ip())
63+
if get_ip()==interface.values()[0]:
64+
try:
65+
i = 0
66+
while i < retry_times_when_mgr_ip_got:
67+
state_file.seek(0)
68+
state = state_file.readline()
69+
if state == 'MASTER':
70+
break
71+
i = i + 1
72+
time.sleep(2)
73+
if i >= retry_times_when_mgr_ip_got:
74+
log_write(" set vip failed")
75+
break
76+
except Exception, e:
77+
log_write(' exception:' + str(e))
78+
exceptimes = exceptimes + 1
79+
if exceptimes > 3:
80+
break
81+
time.sleep(0.5)
82+
get_ip_times = get_ip_times + 1
83+
84+
def print_help():
85+
log_write(
86+
'''
87+
./nexthop.py migrate
88+
migrate your vip
89+
''')
90+
91+
if __name__ == '__main__':
92+
s = get_session()
93+
s.set_credentials(ks_access_key_id,ks_secret_access_key)
94+
vpcClient = s.create_client("vpc", region, use_ssl=True)
95+
if len(sys.argv) == 1:
96+
log_write("nexthop.py: parameter num is 0")
97+
print_help()
98+
elif sys.argv[1] == 'migrate':
99+
migrateVip()
100+
log_write()
101+
else:
102+
log_write("nexthop.py: misMatched parameter")
103+
print_help()
104+

examples/notify_action.sh

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
#!/bin/bash
2+
#/etc/keepalived/notify_action.sh
3+
log_file=/var/log/keepalived.log
4+
log_write()
5+
{
6+
echo "[`date '+%Y-%m-%d %T'`] $1" >> $log_file
7+
}
8+
9+
[ ! -d /var/keepalived/ ] && mkdir -p /var/keepalived/
10+
11+
case "$1" in
12+
"MASTER" )
13+
echo -n "$1" > /var/keepalived/state
14+
log_write " notify_master"
15+
echo -n "0" > /var/keepalived/vip_check_failed_count
16+
python /etc/keepalived/nexthop.py migrate >> $log_file 2>&1 &
17+
;;
18+
19+
"BACKUP" )
20+
echo -n "$1" > /var/keepalived/state
21+
log_write " notify_backup"
22+
;;
23+
24+
"FAULT" )
25+
echo -n "$1" > /var/keepalived/state
26+
log_write " notify_fault"
27+
;;
28+
29+
"STOP" )
30+
echo -n "$1" > /var/keepalived/state
31+
log_write " notify_stop"
32+
;;
33+
*)
34+
log_write "notify_action.sh: STATE ERROR!!!"
35+
;;
36+
esac

0 commit comments

Comments
 (0)