/
haproxy_config.py
168 lines (146 loc) · 5.02 KB
/
haproxy_config.py
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
import json
import os
PROTO_TCP = 'TCP'
PROTO_HTTP = 'HTTP'
PROTO_HTTPS = 'HTTPS'
PROTO_MAP = {
PROTO_TCP: 'tcp',
PROTO_HTTP: 'http',
PROTO_HTTPS: 'http'
}
LB_METHOD_MAP = {
'ROUND_ROBIN': 'roundrobin',
'LEAST_CONNECTIONS': 'leastconn',
'SOURCE_IP': 'source'
}
HEALTH_MONITOR_PING = 'PING'
HEALTH_MONITOR_TCP = 'TCP'
HEALTH_MONITOR_HTTP = 'HTTP'
HEALTH_MONITOR_HTTPS = 'HTTPS'
PERSISTENCE_SOURCE_IP = 'SOURCE_IP'
PERSISTENCE_HTTP_COOKIE = 'HTTP_COOKIE'
PERSISTENCE_APP_COOKIE = 'APP_COOKIE'
HTTPS_PORT = 443
def build_config(conf_file):
with open(conf_file) as data_file:
config = json.load(data_file)
conf_dir = os.path.dirname(conf_file)
conf = []
sock_path = conf_dir + '/haproxy.sock'
conf = _set_global_config(config, sock_path) + '\n\n'
conf += _set_defaults(config) + '\n\n'
conf += _set_frontend(config) + '\n\n'
conf += _set_backend(config) + '\n'
filename = conf_dir + '/haproxy.conf'
conf_file = open(filename, 'w')
conf_file.write(conf)
return filename
def _set_global_config(config, sock_path):
conf = [
'global',
'daemon',
'user nobody',
'group nogroup',
'log /dev/log local0',
'log /dev/log local1 notice',
'tune.ssl.default-dh-param 2048',
'ssl-default-bind-ciphers ECDH+AESGCM:' \
'DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:' \
'DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:' \
'RSA+3DES:!aNULL:!MD5:!DSS'
]
conf.append('stats socket %s mode 0666 level user' % sock_path)
return ("\n\t".join(conf))
def _set_defaults(config):
conf = [
'defaults',
'log global',
'retries 3',
'option redispatch',
'timeout connect 5000',
'timeout client 50000',
'timeout server 50000',
]
return ("\n\t".join(conf))
def _set_frontend(config):
port = config['vip']['port']
ssl = ''
if config['vip']['protocol'] == PROTO_HTTPS:
ssl = 'ssl crt %s no-sslv3' % config['ssl-crt']
conf = [
'frontend %s' % config['vip']['id'],
'option tcplog',
'bind %s:%d %s' % (config['vip']['address'], port, ssl),
'mode %s' % PROTO_MAP[config['vip']['protocol']],
'default_backend %s' % config['pool']['id']
]
if config['vip']['connection-limit'] >= 0:
conf.append('maxconn %s' % config['vip']['connection-limit'])
if config['vip']['protocol'] == PROTO_HTTP or \
config['vip']['protocol'] == PROTO_HTTPS:
conf.append('option forwardfor')
return ("\n\t".join(conf))
def _set_backend(config):
conf = [
'backend %s' % config['pool']['id'],
'mode %s' % PROTO_MAP[config['pool']['protocol']],
'balance %s' % LB_METHOD_MAP[config['pool']['method']]
]
if config['pool']['protocol'] == PROTO_HTTP:
conf.append('option forwardfor')
server_suffix, monitor_conf = _set_health_monitor(config)
conf.extend(monitor_conf)
session_conf = _set_session_persistence(config)
conf.extend(session_conf)
for member in config['members']:
if not member['admin-state']:
continue
server = (('server %(id)s %(address)s:%(port)s '
'weight %(weight)s') % member) + server_suffix
if (config['vip']['persistence-type'] == PERSISTENCE_HTTP_COOKIE):
server += ' cookie %d' % config['members'].index(member)
conf.append(server)
return ("\n\t".join(conf))
def _set_health_monitor(config):
for monitor in config['healthmonitors']:
if monitor['admin-state']:
break
else:
return '', []
server_suffix = ' check inter %(delay)ds fall %(max-retries)d' % monitor
conf = [
'timeout check %ds' % monitor['timeout']
]
if monitor['type'] in (HEALTH_MONITOR_HTTP, HEALTH_MONITOR_HTTPS):
conf.append('option httpchk %(http-method)s %(url)s' % monitor)
conf.append(
'http-check expect rstatus %s' %
'|'.join(_get_codes(monitor['expected-codes']))
)
if monitor['type'] == HEALTH_MONITOR_HTTPS:
conf.append('option ssl-hello-chk')
return server_suffix, conf
def _set_session_persistence(config):
conf = []
persistence = config['vip']['persistence-type']
cookie = config['vip']['persistence-cookie-name']
if persistence == PERSISTENCE_SOURCE_IP:
conf.append('stick-table type ip size 10k')
conf.append('stick on src')
elif persistence == PERSISTENCE_HTTP_COOKIE:
conf.append('cookie SRV insert indirect nocache')
elif (persistence == PERSISTENCE_APP_COOKIE and cookie):
conf.append('appsession %s len 56 timeout 3h' % cookie)
return conf
def _get_codes(codes):
response = set()
for code in codes.replace(',', ' ').split(' '):
code = code.strip()
if not code:
continue
elif '-' in code:
low, hi = code.split('-')[:2]
response.update(str(i) for i in xrange(int(low), int(hi) + 1))
else:
response.add(code)
return response