forked from skyportal/kowalski
-
Notifications
You must be signed in to change notification settings - Fork 1
/
kowalski.py
executable file
·575 lines (491 loc) · 17.4 KB
/
kowalski.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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
#!/usr/bin/env python
import bz2
from contextlib import contextmanager
import datetime
from deepdiff import DeepDiff
from distutils.version import LooseVersion as Version
import fire
import pathlib
from pprint import pprint
import questionary
import re
import secrets
import string
import subprocess
import sys
import time
from typing import Optional, Sequence
import yaml
dependencies = {
"python": (
# Command to get version
["python", "--version"],
# Extract *only* the version number
lambda v: v.split()[1],
# It must be >= 3.7
"3.7",
),
"docker": (
# Command to get version
["docker", "--version"],
# Extract *only* the version number
lambda v: v.split()[2][:-1],
# It must be >= 18.06
"18.06",
),
"docker-compose": (
# Command to get version
["docker-compose", "--version"],
# Extract *only* the version number
lambda v: re.search(r"\s*([\d.]+)", v).group(0).strip(),
# It must be >= 1.22.0
"1.22.0",
),
}
@contextmanager
def status(message):
"""
Borrowed from https://github.com/cesium-ml/baselayer/
:param message: message to print
:return:
"""
print(f"[·] {message}", end="")
sys.stdout.flush()
try:
yield
except Exception:
print(f"\r[✗] {message}")
raise
else:
print(f"\r[✓] {message}")
def deps_ok() -> bool:
"""
Check system dependencies
Borrowed from https://github.com/cesium-ml/baselayer/
:return:
"""
print("Checking system dependencies:")
fail = []
for dep, (cmd, get_version, min_version) in dependencies.items():
try:
query = f"{dep} >= {min_version}"
with status(query):
p = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT
)
out, err = p.communicate()
try:
version = get_version(out.decode("utf-8").strip())
print(f"[{version.rjust(8)}]".rjust(40 - len(query)), end="")
except Exception:
raise ValueError("Could not parse version")
if not (Version(version) >= Version(min_version)):
raise RuntimeError(f"Required {min_version}, found {version}")
except Exception as e:
fail.append((dep, e))
if fail:
print()
print("[!] Some system dependencies seem to be unsatisfied")
print()
print(" The failed checks were:")
print()
for (pkg, exc) in fail:
cmd, get_version, min_version = dependencies[pkg]
print(f' - {pkg}: `{" ".join(cmd)}`')
print(" ", exc)
print()
print(
" Please refer to https://github.com/dmitryduev/kowalski "
"for installation instructions."
)
print()
return False
print("-" * 20)
return True
def check_configs(
config_wildcards: Sequence = ("config.*yaml", "docker-compose.*yaml")
):
"""
- Check if config files exist
- Offer to use the config files that match the wildcards
- For config.yaml, check its contents against the defaults to make sure nothing is missing/wrong
:param config_wildcards:
:return:
"""
path = pathlib.Path(__file__).parent.absolute()
for config_wildcard in config_wildcards:
config = config_wildcard.replace("*", "")
# use config defaults if configs do not exist?
if not (path / config).exists():
answer = questionary.select(
f"{config} does not exist, do you want to use one of the following"
" (not recommended without inspection)?",
choices=[p.name for p in path.glob(config_wildcard)],
).ask()
subprocess.run(["cp", f"{path / answer}", f"{path / config}"])
# check contents of config.yaml WRT config.defaults.yaml
if config == "config.yaml":
with open(path / config.replace(".yaml", ".defaults.yaml")) as config_yaml:
config_defaults = yaml.load(config_yaml, Loader=yaml.FullLoader)
with open(path / config) as config_yaml:
config_wildcard = yaml.load(config_yaml, Loader=yaml.FullLoader)
deep_diff = DeepDiff(config_wildcard, config_defaults, ignore_order=True)
difference = {
k: v
for k, v in deep_diff.items()
if k in ("dictionary_item_added", "dictionary_item_removed")
}
if len(difference) > 0:
print("config.yaml structure differs from config.defaults.yaml")
pprint(difference)
raise KeyError("Fix config.yaml before proceeding")
def get_git_hash_date():
"""Get git date and hash
Borrowed from SkyPortal https://skyportal.io
:return:
"""
hash_date = dict()
try:
p = subprocess.Popen(
["git", "log", "-1", '--format="%h %aI"'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=pathlib.Path(__file__).parent.absolute(),
)
except FileNotFoundError:
pass
else:
out, err = p.communicate()
if p.returncode == 0:
git_hash, git_date = (
out.decode("utf-8")
.strip()
.replace('"', "")
.split("T")[0]
.replace("-", "")
.split()
)
hash_date["hash"] = git_hash
hash_date["date"] = git_date
return hash_date
class Kowalski:
def __init__(self, yes=False):
"""
:param yes: answer yes to all possible requests?
"""
self.yes = yes
@staticmethod
def check_containers_up(
containers: Sequence,
num_retries: int = 10,
sleep_for_seconds: int = 10,
):
"""Check if containers in question are up and running
:param containers: container name sequence, e.g. ("kowalski_api_1", "kowalski_mongo_1")
:param num_retries:
:param sleep_for_seconds: number of seconds to sleep for before retrying
:return:
"""
for i in range(num_retries):
if i == num_retries - 1:
raise RuntimeError(f"{containers} containers failed to spin up")
command = ["docker", "ps", "-a"]
container_list = (
subprocess.check_output(command, universal_newlines=True)
.strip()
.split("\n")
)
print(container_list)
if len(container_list) == 1:
print("No containers are running, waiting...")
time.sleep(sleep_for_seconds)
continue
containers_up = (
len(
[
container
for container in container_list
if (
(container_name in container)
and (" Up " in container)
and ("unhealthy" not in container)
and ("health: starting" not in container)
)
]
)
> 0
for container_name in containers
)
if not all(containers_up):
print(f"{containers} containers are not up, waiting...")
time.sleep(sleep_for_seconds)
continue
break
@staticmethod
def check_keyfile():
"""Check if MongoDB keyfile for replica set authorization exists; generate one if not"""
mongodb_keyfile = pathlib.Path(__file__).parent.absolute() / "mongo_key.yaml"
if not mongodb_keyfile.exists():
print("Generating MongoDB keyfile")
# generate a random key that is required to be able to use authorization with replica set
key = "".join(
secrets.choice(string.ascii_lowercase + string.digits)
for _ in range(32)
)
with open(mongodb_keyfile, "w") as f:
f.write(key)
command = ["chmod", "400", "mongo_key.yaml"]
subprocess.run(command)
@classmethod
def up(cls, build: bool = False):
"""
🐧🚀 Launch Kowalski
:param build: build the containers first?
:return:
"""
print("Spinning up Kowalski 🐧🚀")
config_wildcards = ["config.*yaml", "docker-compose.*yaml"]
# check configuration
with status("Checking configuration"):
check_configs(config_wildcards=config_wildcards)
cls.check_keyfile()
if build:
cls.build()
command = ["docker-compose", "-f", "docker-compose.yaml", "up", "-d"]
# start up Kowalski
print("Starting up")
subprocess.run(command)
@staticmethod
def down():
"""
✋ Shut down Kowalski
:return:
"""
print("Shutting down Kowalski")
command = ["docker-compose", "-f", "docker-compose.yaml", "down"]
subprocess.run(command)
@classmethod
def build(cls):
"""
Build Kowalski's containers
:return:
"""
print("Building Kowalski")
config_wildcards = ["config.*yaml", "docker-compose.*yaml"]
# always use docker-compose.yaml
command = ["docker-compose", "-f", "docker-compose.yaml", "build"]
# check configuration
with status("Checking configuration"):
check_configs(config_wildcards=config_wildcards)
# load config
with open(
pathlib.Path(__file__).parent.absolute() / "config.yaml"
) as config_yaml:
config = yaml.load(config_yaml, Loader=yaml.FullLoader)["kowalski"]
# get git version:
git_hash_date = get_git_hash_date()
version = (
f"v{config['server']['version']}"
f"+git{git_hash_date.get('date', datetime.datetime.utcnow().strftime('%Y%m%d'))}"
f".{git_hash_date.get('hash', 'unknown')}"
)
with open(
pathlib.Path(__file__).parent.absolute() / "version.txt", "w"
) as version_file:
version_file.write(f"{version}\n")
# check MongoDB keyfile
cls.check_keyfile()
subprocess.run(command)
@staticmethod
def seed(source: str = "./", drop: Optional[bool] = False):
"""
Ingest catalog dumps into Kowalski
:param source: where to look for the dumps;
can be a local path or a Google Cloud Storage bucket address, e.g. gs://kowalski-catalogs
:param drop: drop existing collections with same names before ingesting?
:return:
"""
print("Ingesting catalog dumps into a running Kowalski instance")
# check configuration
with status("Checking configuration"):
check_configs(config_wildcards=["config.*yaml"])
with open(
pathlib.Path(__file__).parent.absolute() / "config.yaml"
) as config_yaml:
config = yaml.load(config_yaml, Loader=yaml.FullLoader)["kowalski"]
command = [
"docker",
"exec",
"-i",
"kowalski_mongo_1",
"mongorestore",
f"-u={config['database']['admin_username']}",
f"-p={config['database']['admin_password']}",
"--authenticationDatabase=admin",
"--archive",
]
if drop:
command.append("--drop")
if "gs://" not in source:
# ingesting from a local path
path = pathlib.Path(source).absolute()
dumps = [p.name for p in path.glob("*.dump")]
if len(dumps) == 0:
print(f"No catalog dumps found under {path}")
return False
answer = questionary.checkbox(
"Found the following collection dumps. Which ones would you like to ingest?",
choices=dumps,
).ask()
for dump in answer:
with open(f"{path / dump}") as f:
subprocess.call(command, stdin=f)
else:
# ingesting from Google Cloud
path_tmp = pathlib.Path(__file__).parent / ".catalog_dumps"
if not path_tmp.exists():
path_tmp.mkdir(parents=True, exist_ok=True)
ls_command = ["gsutil", "ls", source]
catalog_list = (
subprocess.check_output(ls_command, universal_newlines=True)
.strip()
.split("\n")
)
dumps = [dump for dump in catalog_list if "dump" in dump]
answer = questionary.checkbox(
"Found the following collection dumps. Which ones would you like to ingest?",
choices=dumps,
).ask()
for dump in answer:
cp_command = [
"gsutil",
"-m",
"cp",
"-n",
dump,
str(path_tmp),
]
p = subprocess.run(cp_command, check=True)
if p.returncode != 0:
raise RuntimeError(f"Failed to fetch {dump}")
path_dump = f"{path_tmp / pathlib.Path(dump).name}"
if dump.endswith(".bz2"):
with bz2.BZ2File(path_dump) as f:
subprocess.call(command, stdin=f)
elif dump.endswith(".gz"):
with open(path_dump) as f:
subprocess.call(command + ["--gzip"], stdin=f)
else:
with open(path_dump) as f:
subprocess.call(command, stdin=f)
rm_fetched = questionary.confirm(f"Remove {path_dump}?").ask()
if rm_fetched:
pathlib.Path(path_dump).unlink()
@classmethod
def test(cls):
"""
Run the test suite
:return:
"""
print("Running the test suite")
# make sure the containers are up and running
cls.check_containers_up(
containers=("kowalski_ingester_1", "kowalski_api_1", "kowalski_mongo_1"),
sleep_for_seconds=10,
)
test_setups = [
{
"part": "PGIR alert broker components",
"container": "kowalski_ingester_1",
"test_script": "test_alert_broker_pgir.py",
"flaky": False,
},
{
"part": "ZTF alert broker components",
"container": "kowalski_ingester_1",
"test_script": "test_alert_broker_ztf.py",
"flaky": False,
},
{
"part": "PGIR alert ingestion",
"container": "kowalski_ingester_1",
"test_script": "test_ingester_pgir.py",
"flaky": False,
},
{
"part": "ZTF alert ingestion",
"container": "kowalski_ingester_1",
"test_script": "test_ingester.py",
"flaky": False,
},
{
"part": "API",
"container": "kowalski_api_1",
"test_script": "test_api.py",
"flaky": False,
},
{
"part": "TNS monitoring",
"container": "kowalski_ingester_1",
"test_script": "test_tns_watcher.py",
"flaky": True,
},
{
"part": "Tools",
"container": "kowalski_ingester_1",
"test_script": "test_tools.py",
"flaky": False,
},
]
failed_tests = []
for setup in test_setups:
print(f"Testing {setup['part']}")
command = [
"docker",
"exec",
"-i",
setup["container"],
"python",
"-m",
"pytest",
"-s",
setup["test_script"],
]
try:
subprocess.run(command, check=True)
except subprocess.CalledProcessError:
if not setup.get("flaky", False):
failed_tests.append(setup["part"])
else:
print(f"{setup['part']} test, marked as flaky, failed.")
continue
if failed_tests:
print(f"Failed tests: {failed_tests}")
sys.exit(1)
@staticmethod
def develop():
"""
Install developer tools
"""
subprocess.run(["pip", "install", "-U", "pre-commit"], check=True)
subprocess.run(["pre-commit", "install"], check=True)
@classmethod
def lint(cls):
"""
Lint the full code base
:return:
"""
try:
import pre_commit # noqa: F401
except ImportError:
cls.develop()
try:
subprocess.run(["pre-commit", "run", "--all-files"], check=True)
except subprocess.CalledProcessError:
sys.exit(1)
if __name__ == "__main__":
# check environment
env_ok = deps_ok()
if not env_ok:
raise RuntimeError("Halting because of unsatisfied system dependencies")
fire.Fire(Kowalski)