-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgenerate_keepalived
executable file
·105 lines (82 loc) · 2.76 KB
/
generate_keepalived
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#!/usr/bin/python
# This script scans the haproxy configuration and generates the keepalived config to match.
# Used in HA deployments where we need fail-over capability.
# First developed: Hereward Cooper - Apr 2011
import subprocess
import re
import datetime
import imp
import sys
from subprocess import Popen, PIPE, STDOUT
__author__ = "Hereward Cooper <coops@fawk.eu>"
__version__ = "v0.1"
__website__ = "http://github.com/hcooper/haproxy-tools/"
def get_ips(configfile):
"""
Extract the IPs which HAProxy will listen on (i.e. VIPs) from the config file
"""
# This could be ported to pure python, however I can't figure the regex out.
getips = subprocess.Popen(["egrep '(listen|frontend)' " + configfile + "\
| grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}' \
| grep -v 127.0.0.1 \
| sort \
| uniq"], shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
# Return the list of VIPs
return getips.stdout.read()
def main(vips):
"""
Generate the keepalived config using the list of VIPs we're provided
"""
# Get current time
time = datetime.datetime.now()
## Import the sysconfig configuration file
config = imp.load_source('haproxy', '/etc/sysconfig/haproxy')
## Check the haproxy slave config
try:
config.HAPROXYSLAVE
except:
ROLE="slave"
PRIORITY="100"
else:
ROLE="master"
PRIORITY="101"
## Check the interface where the VIPs live is defined
try:
config.VIPINT
except:
print "ERROR: No interface defined in /etc/sysconfig/haproxy"
sys.exit(1)
else:
VIPINT = config.VIPINT
OUTPUT = """
## /etc/keepalived/keepalived.conf
## THIS CONFIGURATION IS AUTOMATICALLY GENERATED.
## MANUAL CHANGES WILL BE OVERWRITTEN.
##
## Configuration at """ + str(time.ctime()) + """
## ROLE = """ + ROLE + """
## VIPINT = """ + VIPINT + """
vrrp_script chk_haproxy { # Requires keepalived-1.1.13
script "killall -0 haproxy" # cheaper than pidof
interval 2 # check every 2 seconds
weight 2 # add 2 points of prio if OK
}
vrrp_instance VI_1 {
interface """ + VIPINT + """
state MASTER
virtual_router_id 51
priority """ + PRIORITY + """ # 101=master, 100=standby
virtual_ipaddress {
""" + vips + """
}
track_script {
chk_haproxy
}
}
"""
return OUTPUT
if __name__ == "__main__":
haproxy_config="/etc/haproxy/haproxy.cfg"
# Fire up the engines
vips = get_ips(haproxy_config)
print main(vips)