-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
executable file
·85 lines (66 loc) · 2.15 KB
/
main.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
#!/usr/bin/python
import etcd
from jinja2 import Environment, PackageLoader
import os
from subprocess import call
import signal
import sys
import time
import json
env = Environment(loader=PackageLoader('haproxy', 'templates'))
POLL_TIMEOUT=5
signal.signal(signal.SIGCHLD, signal.SIG_IGN)
def get_etcd_addr():
if "ETCD_HOST" not in os.environ:
print "ETCD_HOST not set"
sys.exit(1)
etcd_host = os.environ["ETCD_HOST"]
if not etcd_host:
print "ETCD_HOST not set"
sys.exit(1)
port = 4001
host = etcd_host
if ":" in etcd_host:
host, port = etcd_host.split(":")
return host, port
def get_services():
host, port = get_etcd_addr()
client = etcd.Client(host=host, port=int(port))
backends = client.read('/backends', recursive = True)
services = {}
for i in backends.children:
if i.key[1:].count("/") != 2:
continue
ignore, service, container = i.key[1:].split("/")
endpoints = services.setdefault(service, dict(port="", backends=[]))
if container == "port":
endpoints["port"] = i.value
continue
if container == "dns":
endpoints["dns"] = i.value.split(",")
continue
endpoints["backends"].append(dict(name=container, addr=i.value))
return services
def generate_config(services):
template = env.get_template('haproxy.cfg.tmpl')
with open("/etc/haproxy.cfg", "w") as f:
f.write(template.render(services=services))
if __name__ == "__main__":
current_services = {}
while True:
try:
services = get_services()
if not services or services == current_services:
time.sleep(POLL_TIMEOUT)
continue
print "config changed. reload haproxy"
generate_config(services)
ret = call(["./reload-haproxy.sh"])
if ret != 0:
print "reloading haproxy returned: ", ret
time.sleep(POLL_TIMEOUT)
continue
current_services = services
except Exception, e:
print "Error:", e
time.sleep(POLL_TIMEOUT)