-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathupdater.py
84 lines (68 loc) · 2.48 KB
/
updater.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
import dns.resolver
import dockercloud
import os
import requests
import sys
import time
if not os.environ.get("DOCKERCLOUD_SUBDOMAINS_DOMAIN"):
print 'Please set the DOCKERCLOUD_SUBDOMAINS_DOMAIN environment variable to specify the domain that subdomains are on.'
sys.exit(1)
DOMAIN = os.environ['DOCKERCLOUD_SUBDOMAINS_DOMAIN']
SUBDOMAIN_LABEL = os.environ['DOCKERCLOUD_SUBDOMAINS_SUBDOMAIN_LABEL']
PORT_LABEL = os.environ['DOCKERCLOUD_SUBDOMAINS_PORT_LABEL']
def generate_provider(containers):
provider = {
"frontends": {},
"backends": {},
}
for container in containers:
container.refresh()
if not hasattr(container, "labels"):
continue
if not container.state == "Running":
continue
subdomain = container.labels.get(SUBDOMAIN_LABEL)
if not subdomain:
continue
domain = '.'.join([subdomain, DOMAIN])
if domain not in provider["frontends"]:
provider["frontends"][domain] = {
"backend": domain,
"routes": {
"default": {
"rule": "Host: %s" % domain,
}
},
"passHostHeader": True,
}
if domain not in provider["backends"]:
provider["backends"][domain] = {
"servers": {},
}
port = container.labels.get(PORT_LABEL, '80')
provider["backends"][domain]["servers"][container.uuid] = {
"url": "http://{}:{}".format(container.private_ip, port),
}
return provider
def get_traefik_ip_addresses():
return [unicode(r) for r in dns.resolver.query('traefik', 'A')]
def main():
if not os.environ.get("DOCKERCLOUD_USER") or not os.environ.get("DOCKERCLOUD_APIKEY"):
print "Please set DOCKERCLOUD_USER and DOCKERCLOUD_APIKEY environment variables."
return 1
previous_provider = None
while True:
containers = dockercloud.Container.list()
provider = generate_provider(containers)
addresses = get_traefik_ip_addresses()
print "Updating {} to {}".format(addresses, provider)
for address in addresses:
resp = requests.put(
"http://{}:8080/api/providers/web".format(address),
json=provider
)
resp.raise_for_status()
time.sleep(int(os.environ.get("UPDATE_INTERVAL", 30)))
return 0
if __name__ == "__main__":
sys.exit(main())