forked from jpetazzo/container.training
-
Notifications
You must be signed in to change notification settings - Fork 1
/
connect-services.py
executable file
·73 lines (62 loc) · 2.56 KB
/
connect-services.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
#!/usr/bin/env python
import os
import subprocess
import sys
import yaml
stack = yaml.load(open(sys.argv[1]))
ports = yaml.load(open("ports.yml"))
project_name = os.path.basename(os.path.realpath("."))
ambassadors = []
service_instances = {}
# Generate container names for all instances
for service_name in stack:
service_instances[service_name] = []
n = 0
while True:
n += 1
try:
container_name = "{}_{}_{}".format(project_name, service_name, n)
subprocess.check_call(
[ "docker", "inspect", container_name ],
stdout=-1, stderr=-1
)
service_instances[service_name].append(container_name)
except subprocess.CalledProcessError:
break
for service_name, service in stack.items():
extra_hosts = service.get("extra_hosts", {})
for link_name, link_addr in extra_hosts.items():
if link_name not in ports:
print("# Skipping link {} in service {} "
"(no port mapping defined). "
"Your code will probably break."
.format(link, service_name))
continue
port = str(ports[link_name])
endpoints = []
for container_name in service_instances[link_name]:
endpoint = subprocess.check_output(
["docker", "port", container_name, port]
)
endpoints.append(endpoint.strip())
for container_name in service_instances[service_name]:
ambassador = {}
ambassador["image"] = "jpetazzo/hamba"
ambassador["net"] = "container:"+container_name
command = "{}:{}".format(link_addr, port)
for endpoint in endpoints:
command = command + " {} {}".format(*endpoint.split(':'))
ambassador["command"] = command
n = len(ambassadors)
ambassador["name"] = "amba{}".format(n)
ambassadors.append(ambassador)
for service_name, service in stack.items():
for container_name in service_instances[service_name]:
print("docker exec {} sh -c 'sed /^127.127/d /etc/hosts >/tmp/hosts && cat /tmp/hosts >/etc/hosts && rm /tmp/hosts'"
.format(container_name))
extra_hosts = service.get("extra_hosts", {})
for link_name, link_addr in extra_hosts.items():
print("docker exec {} sh -c 'echo {} {} >> /etc/hosts'"
.format(container_name, link_addr, link_name))
for amba in ambassadors:
print("docker run -d --name {name} --net {net} {image} {command}".format(**amba))