-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
compose.py
250 lines (204 loc) · 8.28 KB
/
compose.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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
import io
import logging
import os
import sys
import tarfile
import time
from contextlib import contextmanager
INTEGRATION_TESTS = os.environ.get('INTEGRATION_TESTS', False)
if INTEGRATION_TESTS:
from compose.cli.command import get_project
from compose.config.environment import Environment
from compose.service import BuildAction
from compose.service import ConvergenceStrategy
class ComposeMixin(object):
"""
Manage docker-compose to ensure that needed services are running during tests
"""
# List of required services to run INTEGRATION_TESTS
COMPOSE_SERVICES = []
# Additional environment variables for docker compose
COMPOSE_ENV = {}
# timeout waiting for health (seconds)
COMPOSE_TIMEOUT = 300
# add advertised host environment file
COMPOSE_ADVERTISED_HOST = False
# port to advertise when COMPOSE_ADVERTISED_HOST is set to true
COMPOSE_ADVERTISED_PORT = None
@classmethod
def compose_up(cls):
"""
Ensure *only* the services defined under `COMPOSE_SERVICES` are running and healthy
"""
if not INTEGRATION_TESTS or not cls.COMPOSE_SERVICES:
return
if os.environ.get('NO_COMPOSE'):
return
def print_logs(container):
print("---- " + container.name_without_project)
print(container.logs())
print("----")
def is_healthy(container):
return container.inspect()['State']['Health']['Status'] == 'healthy'
project = cls.compose_project()
with disabled_logger('compose.service'):
project.pull(
ignore_pull_failures=True,
service_names=cls.COMPOSE_SERVICES)
project.up(
strategy=ConvergenceStrategy.always,
service_names=cls.COMPOSE_SERVICES,
timeout=30)
# Wait for them to be healthy
start = time.time()
while True:
containers = project.containers(
service_names=cls.COMPOSE_SERVICES,
stopped=True)
healthy = True
for container in containers:
if not container.is_running:
print_logs(container)
raise Exception(
"Container %s unexpectedly finished on startup" %
container.name_without_project)
if not is_healthy(container):
healthy = False
break
if healthy:
break
if cls.COMPOSE_ADVERTISED_HOST:
for service in cls.COMPOSE_SERVICES:
cls._setup_advertised_host(project, service)
time.sleep(1)
timeout = time.time() - start > cls.COMPOSE_TIMEOUT
if timeout:
for container in containers:
if not is_healthy(container):
print_logs(container)
raise Exception(
"Timeout while waiting for healthy "
"docker-compose services: %s" %
','.join(cls.COMPOSE_SERVICES))
@classmethod
def _setup_advertised_host(cls, project, service):
"""
There are services like kafka that announce an advertised address
to clients, who should reconnect to this address. This method
sends the proper address to use to the container by adding a
environment file with the SERVICE_HOST variable set to this value.
"""
host = cls.compose_host(service=service, port=cls.COMPOSE_ADVERTISED_PORT)
content = "SERVICE_HOST=%s" % host
info = tarfile.TarInfo(name="/run/compose_env")
info.mode = 0o100644
info.size = len(content)
data = io.BytesIO()
tar = tarfile.TarFile(fileobj=data, mode='w')
tar.addfile(info, fileobj=io.BytesIO(content.encode("utf-8")))
tar.close()
containers = project.containers(service_names=[service])
for container in containers:
container.client.put_archive(container=container.id, path="/", data=data.getvalue())
@classmethod
def compose_down(cls):
"""
Stop all running containers
"""
if os.environ.get('NO_COMPOSE'):
return
if INTEGRATION_TESTS and cls.COMPOSE_SERVICES:
# Use down on per-module scenarios to release network pools too
if os.path.basename(os.path.dirname(cls.find_compose_path())) == "module":
cls.compose_project().down(remove_image_type=None, include_volumes=True)
else:
cls.compose_project().kill(service_names=cls.COMPOSE_SERVICES)
@classmethod
def get_hosts(cls):
return [cls.compose_host()]
@classmethod
def _private_host(cls, info, port):
"""
Return the address of the container, it should be reachable from the
host if docker is being run natively. To be used when the tests are
run from another container in the same network. It also works when
running from the host network if the docker daemon runs natively.
"""
networks = list(info['NetworkSettings']['Networks'].values())
port = port.split("/")[0]
for network in networks:
ip = network['IPAddress']
if ip:
return "%s:%s" % (ip, port)
@classmethod
def _exposed_host(cls, info, port):
"""
Return the exposed address in the host, can be used when the test is
run from the host network. Recommended when using docker machines.
"""
hostPort = info['NetworkSettings']['Ports'][port][0]['HostPort']
return "localhost:%s" % hostPort
@classmethod
def compose_host(cls, service=None, port=None):
if not INTEGRATION_TESTS or not cls.COMPOSE_SERVICES:
return []
if service is None:
service = cls.COMPOSE_SERVICES[0]
host_env = os.environ.get(service.upper() + "_HOST")
if host_env:
return host_env
container = cls.compose_project().containers(service_names=[service])[0]
info = container.inspect()
portsConfig = info['HostConfig']['PortBindings']
if len(portsConfig) == 0:
raise Exception("No exposed ports for service %s" % service)
if port is None:
port = list(portsConfig.keys())[0]
# We can use _exposed_host for all platforms when we can use host network
# in the metricbeat container
if sys.platform.startswith('linux'):
return cls._private_host(info, port)
return cls._exposed_host(info, port)
@classmethod
def compose_project_name(cls):
basename = os.path.basename(cls.find_compose_path())
def positivehash(x):
return hash(x) % ((sys.maxsize + 1) * 2)
return "%s_%X" % (basename, positivehash(frozenset(cls.COMPOSE_ENV.items())))
@classmethod
def compose_project(cls):
env = Environment(os.environ.copy())
env.update(cls.COMPOSE_ENV)
return get_project(cls.find_compose_path(),
project_name=cls.compose_project_name(),
environment=env)
@classmethod
def find_compose_path(cls):
class_dir = os.path.abspath(os.path.dirname(sys.modules[cls.__module__].__file__))
while True:
if os.path.exists(os.path.join(class_dir, "docker-compose.yml")):
return class_dir
class_dir, current = os.path.split(class_dir)
if current == '': # We have reached root
raise Exception("failed to find a docker-compose.yml file")
@classmethod
def get_service_log(cls, service):
container = cls.compose_project().containers(service_names=[service])[0]
return container.logs()
@classmethod
def service_log_contains(cls, service, msg):
log = cls.get_service_log(service)
counter = 0
for line in log.splitlines():
if line.find(msg.encode("utf-8")) >= 0:
counter += 1
return counter > 0
@contextmanager
def disabled_logger(name):
logger = logging.getLogger(name)
old_level = logger.getEffectiveLevel()
logger.setLevel(logging.CRITICAL)
try:
yield logger
finally:
logger.setLevel(old_level)