This repository has been archived by the owner on Nov 28, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
launch.py
325 lines (264 loc) · 9.07 KB
/
launch.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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
#!/usr/bin/env python3
"""
Utilities to initialize volumes and stand up services using docker compose
"""
import glob
import io
import logging
import os
import sys
import tarfile
from enum import Enum
import docker
import dotenv
import requests
from compose.cli.main import main as docker_compose
from fire import Fire
from mock import patch
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
env = dotenv.dotenv_values("client.env")
logging.basicConfig(
level=logging.INFO,
format="%(levelname)-8s - %(asctime)s - %(name)s :: %(message)s",
)
LOGGER = logging.getLogger(__name__)
BUILTIN_DISCOVERY_MODELS = "builtin-discovery-models"
CUSTOM_DISCOVERY_INTERPRETER = "custom-discovery-interpreter"
BUILTIN_NLPROCESSOR_MODELS = "builtin-nlprocessor-models"
def get_docker_client():
"""
Returns docker client.
Invoke this repeatedly instead of persisting an object in python
"""
return docker.client.from_env()
class RetryRequest(Retry):
"""
Custom retry class with max backoff set to TIMEOUT from client.env
"""
BACKOFF_MAX = float(env["TIMEOUT"])
retries = RetryRequest(
total=int(env["RETRIES"]), backoff_factor=1.0, status_forcelist=[500, 502, 503, 504]
)
request_session = requests.Session()
request_session.mount("http://", HTTPAdapter(max_retries=retries))
class LaunchTarget(Enum):
everything = "everything"
discovery = "discovery"
nlprocessor = "nlprocessor"
def pull_image(image):
"""
Try to pull the most up to date version of this image.
If internet connectivity is down, don't error.
"""
try:
if env.get("AUTOMATICALLY_PULL_IMAGES").title() == "True":
get_docker_client().images.pull(image)
except requests.exceptions.HTTPError:
LOGGER.warning(
"Unable to pull latest %s. Using image as found in local registry", image
)
def fix_volume_permissions(volume, folder):
busybox_tag = env["BUSYBOX_TAG"]
busybox_image = f"busybox:{busybox_tag}"
pull_image(busybox_image)
get_docker_client().containers.run(
busybox_image,
command=f"chmod -R 777 {folder}",
user="root",
remove=True,
detach=False,
volumes={volume.name: {"bind": folder, "mode": "rw"}},
)
def load_builtin_discovery_models():
"""
Create a docker volume,
attach it to a busybox container,
and load the GK interpreter models into that container
"""
# copy default models in
remove_volume(BUILTIN_DISCOVERY_MODELS)
builtin_models = get_docker_client().volumes.create(name=BUILTIN_DISCOVERY_MODELS)
folder = "/models"
fix_volume_permissions(builtin_models, folder)
initdiscovery_tag = env["INIT_DISCOVERY_TAG"]
initdiscovery_project = "docker.greenkeytech.com/greenkey-discovery-sdk-private"
initdiscovery_image = f"{initdiscovery_project}:{initdiscovery_tag}"
pull_image(initdiscovery_image)
initcontainer = get_docker_client().containers.run(
initdiscovery_image,
auto_remove=False,
detach=True,
volumes={builtin_models.name: {"bind": folder, "mode": "rw"}},
)
initcontainer.start()
initcontainer.wait()
initcontainer.remove(force=True)
def load_builtin_nlprocessor_models():
"""
Create a docker volume,
attach it to a busybox container,
and load the GK nlprocessor models into that container
"""
# copy default models in
remove_volume(BUILTIN_NLPROCESSOR_MODELS)
builtin_models = get_docker_client().volumes.create(name=BUILTIN_NLPROCESSOR_MODELS)
folder = "/models/transformers"
fix_volume_permissions(builtin_models, folder)
initnlprocessor_tag = env["INIT_NLPROCESSOR_TAG"]
initnlprocessor_project = "docker.greenkeytech.com/nlpmodelcontroller"
initnlprocessor_image = f"{initnlprocessor_project}:{initnlprocessor_tag}"
pull_image(initnlprocessor_image)
initcontainer = get_docker_client().containers.run(
initnlprocessor_image,
auto_remove=False,
detach=True,
volumes={builtin_models.name: {"bind": folder, "mode": "rw"}},
)
initcontainer.start()
initcontainer.wait()
initcontainer.remove(force=True)
def load_custom_model(interpreter_directory):
"""
Create a docker volume, attach it to a busybox container, and load our interpreter into that container
"""
if not os.path.isdir(interpreter_directory):
raise Exception(f"Interpreter directory {interpreter_directory} not found")
# copy custom model in
remove_volume(CUSTOM_DISCOVERY_INTERPRETER)
vol = get_docker_client().volumes.create(name=CUSTOM_DISCOVERY_INTERPRETER)
source = interpreter_directory
destination = "/data"
busybox_image = f"busybox:{env['BUSYBOX_TAG']}"
pull_image(busybox_image)
busybox = get_docker_client().containers.run(
busybox_image,
"sleep infinity",
auto_remove=False,
detach=True,
volumes={vol.name: {"bind": destination, "mode": "rw"}},
)
file_like_object = io.BytesIO()
with tarfile.open(fileobj=file_like_object, mode="w") as tar:
for fl in glob.glob(os.path.join(source, "*")):
tar.add(fl, arcname=fl.replace(source, ""))
file_like_object.seek(0)
data = file_like_object.read()
busybox.put_archive(destination, data)
busybox.remove(force=True)
def create_dummy_custom_model():
"""
Create a docker volume that contains nothing so docker-compose still works
"""
# copy custom model in
remove_volume(CUSTOM_DISCOVERY_INTERPRETER)
get_docker_client().volumes.create(name=CUSTOM_DISCOVERY_INTERPRETER)
def wait_on_service(address):
return request_session.get(
"/".join([address, "ping"]), timeout=float(env["TIMEOUT"])
)
def wait_for_everything(target):
"""
Wait for all services as necessary
"""
if target in [LaunchTarget.discovery, LaunchTarget.everything]:
wait_on_service(":".join([env["DISCOVERY_HOST"], env["DISCOVERY_PORT"]]))
if target in [LaunchTarget.nlprocessor, LaunchTarget.everything]:
wait_on_service(":".join([env["NLPROCESSOR_HOST"], env["NLPROCESSOR_PORT"]]))
def check_for_license():
"""
Codify license check
"""
assert (
env["LICENSE_KEY"] != ""
), "LICENSE_KEY needed. Please set in your environment or client.env"
def create_volumes(target, interpreter_directory):
"""
Create volumes as needed
"""
if interpreter_directory:
load_custom_model(interpreter_directory)
else:
create_dummy_custom_model()
if target in [LaunchTarget.discovery, LaunchTarget.everything]:
load_builtin_discovery_models()
if target in [LaunchTarget.nlprocessor, LaunchTarget.everything]:
load_builtin_nlprocessor_models()
def stand_up_compose(target):
"""
Stand up compose based on target
"""
args = ["docker-compose", "--env-file", "client.env"]
if target in [LaunchTarget.discovery, LaunchTarget.everything]:
discovery_image = f"docker.greenkeytech.com/discovery:{env['DISCOVERY_TAG']}"
pull_image(discovery_image)
args += ["-f", "discovery.yaml"]
if target in [LaunchTarget.nlprocessor, LaunchTarget.everything]:
nlprocessor_image = (
f"docker.greenkeytech.com/nlprocessor:{env['NLPROCESSOR_TAG']}"
)
pull_image(nlprocessor_image)
args += ["-f", "nlprocessor.yaml"]
args += ["up", "-d", "--force-recreate"]
with patch.object(sys, "argv", args):
docker_compose()
def prune_volumes():
"""
Prune any volumes not in use
"""
get_docker_client().volumes.prune()
def prune_containers():
"""
Prune any containers which have exited
"""
get_docker_client().containers.prune()
def launch_docker_compose(target="everything", interpreter_directory=None):
"""
Launch docker compose with either both discovery and nlprocessor or just one
"""
check_for_license()
target = LaunchTarget(target)
prune_containers()
prune_volumes()
create_volumes(target, interpreter_directory)
stand_up_compose(target)
# block until ready
wait_for_everything(target)
def remove_volume(volume_name):
"""
Try to remove a docker volume
"""
try:
vol = get_docker_client().volumes.get(volume_name)
for container in get_docker_client().containers.list():
if any(
vol.name == mount.get("Name") for mount in container.attrs["Mounts"]
):
container.remove(force=True)
vol.remove()
except docker.errors.NotFound:
pass
def teardown_docker_compose():
"""
Teardown docker compose
"""
args = [
"docker-compose",
"--env-file",
"client.env",
"-f",
"discovery.yaml",
"-f",
"nlprocessor.yaml",
"down",
]
with patch.object(sys, "argv", args):
docker_compose()
for volume_name in [
CUSTOM_DISCOVERY_INTERPRETER,
BUILTIN_DISCOVERY_MODELS,
BUILTIN_NLPROCESSOR_MODELS,
]:
remove_volume(volume_name)
if __name__ == "__main__":
Fire(launch_docker_compose)