forked from niwcpac/mole
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ml
executable file
·1481 lines (1243 loc) · 44.2 KB
/
ml
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
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
import argparse
import sys
import subprocess
import os
import signal
import glob
import time
try:
# Python3
from urllib.request import urlopen
except ImportError:
# Python2
from urllib import urlopen
from contextlib import closing
import json
# BACKUP_FLAG is used to handle if/where backup is called so timing and appropriate context string
# can be set.
# - pre -- Created by Django container prior to init, or by ml prior to load. db_backup service doesn't backup on load.
# - true -- Created by db_backup service on load. Django container doesn't backup on start.
# - false -- No backup created on startup / periodically. Still able to backup on demand.
# - demand -- used by ml script to indicate call is on demand. Similar behavior to 'false'
CONFIGURE_MOLE_PATH = "mole/data_collection/management/commands/"
MAP_TILES_PATH = "maps/maptiles/"
CERT_CONF_DIR = os.path.join(".", "traefik", "configuration")
CA_CONF_FILE = os.path.join(CERT_CONF_DIR, "ca.config")
CERT_EXT_FILE = os.path.join(CERT_CONF_DIR, "cert.ext")
REQ_CONF_FILE = os.path.join(CERT_CONF_DIR, "req.config")
CERT_DIR = os.path.join(".", "traefik", "certificates")
CA_KEY_FILE = os.path.join(CERT_DIR, "moleCA.key")
CA_CERT_FILE = os.path.join(CERT_DIR, "moleCA.pem")
SERVER_CSR_FILE = os.path.join(CERT_DIR, "mole.csr")
SERVER_KEY_FILE = os.path.join(CERT_DIR, "mole.key")
SERVER_CERT_FILE = os.path.join(CERT_DIR, "mole.crt")
SERVICES = {
"proxy",
"postgres",
"redis",
"django",
"docs",
"maptiles",
"report",
"portainer",
"db_backup",
"angular",
"event_generator",
"pulsar",
}
def terminate_mole(mole_subprocess, db_backup=True):
"""
CTRL-C to docker-compose allows for consecutive SIGTERMS to attempt a graceful stop
followed by killing. This function is to maintain that construct.
"""
try:
if db_backup:
print("\n\nStop requested. Backing up database.")
backup_db(name_string="shutdown&sync=true")
print("\n")
mole_subprocess.send_signal(signal.SIGTERM)
mole_subprocess.wait()
except KeyboardInterrupt:
mole_subprocess.send_signal(signal.SIGTERM)
mole_subprocess.wait()
def build_angular():
# Tell the angular container to build the angular static files and remove the container afterward
print("Building angular static files ...")
FNULL = open(os.devnull, "w")
subprocess.call(
[
"docker-compose",
"run",
"--rm",
"--entrypoint",
"ng",
"angular",
"build",
"--configuration",
"production",
"--base-href",
"static/"
]
)
print("Angular container finished building files")
def init(
configure_script,
build_only,
skip_static_build=False,
angular=False,
quiet=False,
nomaps=False,
lite=False,
profile=False,
db_backup=False,
pre_init_backup=True,
unlock_redis=False,
make_migrations=False,
deep_clean=False,
debug=False,
):
if db_backup:
BACKUP_FLAG = "pre"
else:
BACKUP_FLAG = "false"
if debug:
DEBUG_DJANGO = "true"
else:
DEBUG_DJANGO = "false"
if pre_init_backup:
print("Backing up the database...")
standalone_backup("pre-init&sync=true")
# Generate https keys/certs if they don't exist
if not os.path.isfile(CA_KEY_FILE):
keys()
yes = ("yes", "y", "ye")
if deep_clean:
prompt = """
WARNING: You have requested to delete containers and volumes.
No automatic database backup will be created prior to init.
Do you wish to proceed? [y/N]: """
sys.stdout.write(prompt)
if sys.version_info.major == 3:
choice = input().lower()
else:
choice = raw_input().lower()
if choice in yes:
print("Clearing containers and volumes...\n")
cmd = [
"docker-compose",
"down",
"--volumes",
"--remove-orphans",
]
p = subprocess.call(cmd)
print("Containers and volumes deleted...\n")
BACKUP_FLAG = "false"
else:
print("Skipping, containers and volumes not deleted")
try:
short_hash = subprocess.check_output(["git", "rev-parse", "--short", "HEAD"])
long_hash = subprocess.check_output(["git", "rev-parse", "HEAD"])
except subprocess.CalledProcessError as e:
print("Error retrieving git hash, defaulting to 'latest'")
print(e)
short_hash = "latest"
long_hash = "latest"
short_hash = short_hash.strip()
long_hash = long_hash.strip()
if build_only:
print("Building container images...\n")
cmd = [
"docker-compose",
"-f",
"docker-compose.yml",
"-f",
"docker-compose-e2e.yml",
"build",
]
env = {
"PATH": str(os.getenv("PATH")),
"NEWUSERID": str(os.getuid()),
"BUILD_TAG": short_hash,
"LONG_BUILD_TAG": long_hash,
}
p = subprocess.call(cmd, env=env)
return
# Verify configure_script exists
print("Building containers and initializing Mole...")
configure_script_file = os.path.join(
CONFIGURE_MOLE_PATH, "{}.py".format(configure_script)
)
if not os.path.isfile(configure_script_file):
available_scripts = glob.glob(CONFIGURE_MOLE_PATH + "[!_]*.py")
available_scripts = [os.path.splitext(x)[0] for x in available_scripts]
available_scripts = [os.path.basename(x) for x in available_scripts]
print('ERROR: configuration script "{}" not found.\n'.format(configure_script))
print(
"The available scripts are:\n {}".format("\n ".join(available_scripts))
)
return
prompt = """
WARNING: You have requested to initialize Mole.
This will permanently overwrite your current database. Do you wish to proceed?
Do you wish to continue? [y/N]: """
sys.stdout.write(prompt)
if sys.version_info.major == 3:
choice = input().lower()
else:
choice = raw_input().lower()
if choice in yes:
cmd = [
"docker-compose",
"up",
"--build",
"--force-recreate",
"--always-recreate-deps",
]
if os.environ.get("UNLOCK_REDIS") or unlock_redis:
cmd = [
"docker-compose",
"-f",
"docker-compose.yml",
"-f",
"docker-compose-unlocked-redis.yml",
"up",
"--build",
"--force-recreate",
"--always-recreate-deps",
]
# Don't run portainer if "lite" flag is set
if lite:
SERVICES.discard("portainer")
SERVICES.discard("docs")
# Should reverse-proxy always be included even under lite mode?
SERVICES.discard("proxy")
SERVICES.discard("event_generator")
SERVICES.discard("pulsar")
if not db_backup:
SERVICES.discard("db_backup")
if not angular or skip_static_build:
SERVICES.discard("angular")
if make_migrations:
MAKE_MIGRATIONS_FLAG = "true"
else:
MAKE_MIGRATIONS_FLAG = "false"
# Don't run map tile server if there are no tile sets available
available_mbtiles = glob.glob(MAP_TILES_PATH + "*.mbtiles")
if not available_mbtiles:
print(
"No .mbtiles tile sets available. Not starting maptiles service. See Mole docs for more information."
)
nomaps = True
if nomaps:
SERVICES.discard("maptiles")
env = {
"PROFILE": str(profile).lower(),
"BACKUP_FLAG": BACKUP_FLAG,
"MAKE_MIGRATIONS": MAKE_MIGRATIONS_FLAG,
"POPULATE_DB": configure_script,
"NEWUSERID": str(os.getuid()),
"DEBUG_DJANGO": DEBUG_DJANGO,
"PATH": str(os.getenv("PATH")),
"BUILD_TAG": short_hash,
"LONG_BUILD_TAG": long_hash,
}
if not skip_static_build:
build_angular()
else:
print("Skipping static build...")
clear_images_cmd = ["find", "mole/media/images/", "-type", "f", "-not", "-name", "README", "-delete"]
subprocess.call(clear_images_cmd)
cmd.extend(SERVICES)
p = subprocess.Popen(cmd, preexec_fn=os.setpgrp, env=env)
try:
return p.wait()
except KeyboardInterrupt:
terminate_mole(p, db_backup)
else:
print("\n Exiting...")
return
def run(
quiet=False,
nomaps=False,
lite=False,
profile=False,
db_backup=False,
unlock_redis=False,
angular=False,
debug=False,
):
# Need recreate on so new environment variable get set. (BACKUP_FLAG, etc.)
cmd = ["docker-compose", "up"]
if os.environ.get("UNLOCK_REDIS") or unlock_redis:
cmd = ["docker-compose", "-f", "docker-compose.yml", "-f", "docker-compose-unlocked-redis.yml", "up"]
if quiet:
cmd.append("-d")
# Don't run non-essential services if "lite" flag is set
if lite:
SERVICES.discard("portainer")
SERVICES.discard("docs")
# Should reverse-proxy always be included even under lite mode?
SERVICES.discard("proxy")
SERVICES.discard("event_generator")
SERVICES.discard("pulsar")
if not db_backup:
SERVICES.discard("db_backup")
if not angular:
SERVICES.discard("angular")
# Don't run map tile server if there are no tile sets available
available_mbtiles = glob.glob(MAP_TILES_PATH + "*.mbtiles")
if not available_mbtiles:
print(
"No .mbtiles tile sets available. Not starting maptiles service. See Mole docs for more information."
)
nomaps = True
if nomaps:
SERVICES.discard("maptiles")
cmd.extend(SERVICES)
if db_backup:
BACKUP_FLAG = "true"
else:
BACKUP_FLAG = "false"
if debug:
DEBUG_DJANGO = "true"
else:
DEBUG_DJANGO = "false"
env = {
"PROFILE": str(profile).lower(),
"BACKUP_FLAG": BACKUP_FLAG,
"POPULATE_DB": "false",
"DEBUG_DJANGO": DEBUG_DJANGO,
"PATH": str(os.getenv("PATH")),
}
p = subprocess.Popen(cmd, preexec_fn=os.setpgrp, env=env)
try:
return p.wait()
except KeyboardInterrupt:
terminate_mole(p, db_backup)
def stop():
print("Stop requested. Backing up database.")
backup_db(name_string="ml_stop")
cmd = ["docker-compose", "stop"]
subprocess.call(cmd)
def test(dropdb=False, integration=False):
if dropdb:
cmd = ["docker-compose", "-f", "compose_init_db.yml", "up", "-d", "postgres"]
subprocess.call(cmd)
cmd = [
"docker-compose",
"exec",
"postgres",
"dropdb",
"--username=mole_user",
"test_mole",
]
subprocess.call(cmd)
return
if integration:
standalone_backup()
cmd = [
"docker-compose",
"-f",
"docker-compose-e2e.yml",
"-f",
"docker-compose.yml",
"up",
"--force-recreate",
"--renew-anon-volumes",
"--abort-on-container-exit",
"--exit-code-from",
"django",
]
env = {
"PROFILE": "false",
"BACKUP_FLAG": "false",
"MAKE_MIGRATIONS": "false",
"POPULATE_DB": "integration_test",
"NEWUSERID": str(os.getuid()),
"DEBUG_DJANGO": "false",
"PATH": str(os.getenv("PATH")),
}
p = subprocess.Popen(cmd, preexec_fn=os.setpgrp, env=env)
try:
return p.wait()
except KeyboardInterrupt:
terminate_mole(p, False)
cmd = [
"docker-compose",
"-f",
"docker-compose-tests.yml",
"up",
]
p = subprocess.Popen(cmd, preexec_fn=os.setpgrp)
try:
return p.wait()
except KeyboardInterrupt:
terminate_mole(p, False)
def shell():
print("Building container for shell. Mole is not running in this mode.")
cmd = ["cp", "docker-compose.yml", "compose_init_db.yml"]
subprocess.call(cmd)
cmd = ["sed", "-i", "-e", "s/init/init_shell/g", "compose_init_db.yml"]
subprocess.call(cmd)
cmd = ["docker-compose", "-f", "compose_init_db.yml", "up", "-d"]
subprocess.call(cmd)
try:
cmd = ["docker-compose", "exec", "django", "/bin/bash"]
subprocess.call(cmd)
stop()
except KeyboardInterrupt:
stop()
def service_is_running(service_name, id=False):
running = False
cmd = ["docker-compose", "ps", "-q", service_name]
container_id = subprocess.check_output(cmd)
if container_id:
# Returns empty string if not running
cmd = ["docker", "ps", "-q", "--no-trunc"]
docker_ps = subprocess.check_output(cmd)
running = container_id in docker_ps
if id:
return bool(running), container_id.rstrip().decode()
return bool(running)
def standalone_backup(name_string="on_demand&sync=true"):
"""
docker-compose up -d postgres
"""
postgres_running = service_is_running("postgres")
db_backup_running = service_is_running("db_backup")
if not (postgres_running and db_backup_running):
# BACKUP_FLAG == "demand" so db_backup container skips backup on startup if not running.
env = {
"BACKUP_FLAG": "demand",
"POPULATE_DB": "false",
"NEWUSERID": str(os.getuid()),
"PATH": str(os.getenv("PATH")),
}
print("Starting necessary services...")
cmd = ["docker-compose", "up", "-d", "postgres", "db_backup"]
subprocess.call(cmd, env=env)
else:
print("Necessary services already running.")
response = backup_db(name_string=name_string)
if response["status"] == 200:
filename = json.loads(response["body"])["backup_filename"]
print("Backup file created: {}".format(filename))
elif response["status"] == 429:
print("Backup request throttled. Try again later.")
else:
print("Error creating backup.")
print("Stopping previously stopped services...")
# Stop postgres if it wasn't running already
if not postgres_running:
cmd = ["docker-compose", "stop", "postgres"]
subprocess.call(cmd, env=env)
# Stop db_backup if it wasn't running already
if not db_backup_running:
cmd = ["docker-compose", "stop", "db_backup"]
subprocess.call(cmd, env=env)
def backup_db(name_string=""):
"""
Backup the postgres db.
"""
url = "http://localhost:8003/backup_db/"
if name_string:
url += "?context={}".format(name_string)
# retry 3 times in case db_backup service isn't ready yet
for i in range(3):
try:
# Use closing since Python 2 urlopen doesn't have context handler necessary for with...as statement
with closing(urlopen(url)) as response:
status = response.getcode()
body = response.read()
return {"status": status, "body": body}
except IOError:
print("Backup service unavailable. Retrying...")
time.sleep(1.0)
return {
"status": None,
"body": "Failed to connect to backup service. No backup created.",
}
def get_project_config():
project_info = []
docker_compose = ["docker-compose", "images"]
awk = ["awk", "NR>2"]
project_images = subprocess.Popen(
docker_compose,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
cleaned_project_images = subprocess.Popen(
awk, stdin=project_images.stdout, stdout=subprocess.PIPE
)
if sys.version_info.major == 3:
output, err = cleaned_project_images.communicate(
"Grabbing the project images".encode()
)
output = output.decode()
else:
output, err = cleaned_project_images.communicate(b"Grabbing the project images")
print("\ncontents of project:")
print(output)
img_data = output.split("\n")
for img_info in img_data:
if img_info:
container = {}
container_info = img_info.split()
container["name"] = container_info[0]
container["repository"] = container_info[1]
container["tag"] = container_info[2]
container["img_id"] = container_info[3]
project_info.append(container)
return project_info
def export_project_containers():
project_info = get_project_config()
containers_file = open("project_containers.txt", "w")
for instance in project_info:
print("Exporting container %s" % (instance["name"]))
containers_file.write(instance["name"] + "\n")
cmd = [
"docker",
"export",
"--output=%s.tar" % (instance["name"]),
instance["name"],
]
subprocess.call(cmd)
containers_file.close()
def import_project_containers():
project_containers = open("project_containers.txt", "r").readlines()
for container in project_containers:
print("importing %s" % (container))
cmd = ["docker", "import", container + ".tar"]
subprocess.call(cmd)
def delete_project_config():
project_info = get_project_config()
for instance in project_info:
print("Deleting container: %s" % (instance["name"]))
cmd = ["docker", "rm", instance["name"]]
print("Deleting image: %s" % (instance["repository"]))
subprocess.call(cmd)
cmd = ["docker", "image", "rm", instance["img_id"]]
subprocess.call(cmd)
print("DELETING Volumes")
cmd = ["docker", "volume", "prune"]
subprocess.call(cmd)
def save_project_images(target, repos):
project_config = get_project_config()
img_save_cmd = ["docker", "save", "-o", "%s.tar" % (target)]
for instance in project_config:
repository = instance["repository"]
tag = instance["tag"]
if len(repos) > 0:
if repository in repos:
print("Adding %s to repository." % (repository))
command_txt = repository + ":" + tag
img_save_cmd.append(command_txt)
repos.remove(repository)
else:
print("Adding %s:%s to archive" % (repository, tag))
command_txt = repository + ":" + tag
img_save_cmd.append(command_txt)
if len(repos) > 0:
for name in repos:
print("Error!!! Image %s NOT FOUND! Could not add to archive" % (name))
print("Creating Project Repository Tarball")
subprocess.call(img_save_cmd)
print("Compressing Tarball")
compress_tarball_cmd = ["gzip", "%s.tar" % (target)]
subprocess.call(compress_tarball_cmd)
def manage(
target,
load="mole_project",
build=False,
save=False,
imp=False,
exp=False,
all=False,
):
if load:
yes = ("yes", "y", "ye")
prompt = """
WARNING: You have requested to load images for Mole.
This will permanently delete all current docker images for the project.
Would you like to backup the current images? [y/N]: """
sys.stdout.write(prompt)
if sys.version_info.major == 3:
choice = input().lower()
else:
choice = raw_input().lower()
if choice in yes:
save_project_images("mole_project_backup", [])
delete_project_config()
load_cmd = ["docker", "load", "-i", load]
print("Loading images from: %s" % load)
subprocess.call(load_cmd)
if build:
run()
if save != None:
save_project_images(target[0], save)
if imp != None:
import_project_containers()
if exp != None:
export_project_containers()
def db(backup=False, load=False):
if backup:
standalone_backup()
if load:
postgres_running, pg_container_id = service_is_running("postgres", id=True)
db_backup_running = service_is_running("db_backup")
if not postgres_running:
cmd = ["docker-compose", "up", "-d", "postgres"]
subprocess.call(cmd)
_, pg_container_id = service_is_running("postgres", id=True)
# BACKUP_FLAG="pre" so db_backup service doesn't backup on start. Backup called below.
env = {
"BACKUP_FLAG": "pre",
"PATH": str(os.getenv("PATH")),
}
if not db_backup_running:
cmd = ["docker-compose", "up", "-d", "db_backup"]
subprocess.call(cmd, env=env)
backup_db(name_string="pre_load&sync=true")
perform_backup = True
is_archive = False
file_path = load[0]
# parse file name
file_path_split = file_path.split("/")
if file_path.endswith(".tar.gz"):
file_name = file_path_split[-1][:-7]
is_archive = True
elif file_path.endswith(".sql"):
file_name = file_path_split[-1][:-4]
else:
file_name = file_path_split[-1]
# check if valid backup file & update file paths
if file_path[0] == "/": # check if the file path is explicit
# if not a valid file path, don't try to load it
if not os.path.isfile(file_path):
print("Not a valid file path.")
perform_backup = False
else: # file path is verified
# if not an archive, only need to copy sql to postgres
# (archives are extracted by default later, no need to copy here)
if not is_archive:
# copy sql to backups directory
cmd = [ "cp", file_path, "db_backup/backups/%s.sql" % (file_name) ]
subprocess.call(cmd, env=env)
else: # only database name was provided, construct file path and validate
file_path = "db_backup/backups/%s.tar.gz" % (file_name)
is_archive = True
if not os.path.isfile(file_path): # test if it's an archive
file_path = "db_backup/backups/%s.sql" % (file_name)
is_archive = False
if not os.path.isfile(file_path): # test if it's sql
print("Not a valid file path.")
perform_backup = False
# Drop old DB & perform backup
if perform_backup:
if is_archive:
# make directory to extract zip archive into
backup_dir_path = "db_backup/backups/%s" % (file_name)
cmd = [ "mkdir", "-p", backup_dir_path ]
subprocess.call(cmd, env=env)
# unzip the archive
cmd = [ "tar", "-zxvf", "%s" % file_path, "-C", backup_dir_path ]
subprocess.call(cmd, env=env)
# Copy images over
cmd = ["rsync", "-a", "--delete", "%s/mole_media/images/" % (backup_dir_path), "mole/media/images"]
subprocess.call(cmd, env=env)
# it's assumed the sql has the same name as the archive name
postgres_sql_path = "/backups/%s/%s.sql" % (file_name, file_name)
# handle case where the sql in archive doesn't match the name of the archive
if not os.path.isfile("db_backup/backups/%s/%s.sql" % (file_name, file_name)):
sql_glob = glob.glob("db_backup/backups/%s/*.sql" % (file_name))
if len(sql_glob) >= 1:
sql_path = sql_glob[0] # take first sql file found
sql_path_split = sql_path.split("/")
sql_name = sql_path_split[len(sql_path_split)-1][:-4]
postgres_sql_path = "/backups/%s/%s.sql" % (file_name, sql_name)
else: # uh oh..
print("No sql backup found in archive!")
postgres_sql_path = None
else: # no archive, sql should be directly under backups
postgres_sql_path = "/backups/%s.sql" % (file_name)
if postgres_sql_path:
# Force disconnect of active connections
cmd = [
"docker-compose",
"exec",
"postgres",
"psql",
"-U",
"mole_user",
"-d",
"postgres",
"-c",
"SELECT pg_terminate_backend(pg_stat_activity.pid) \
FROM pg_stat_activity \
WHERE pg_stat_activity.datname = 'mole';",
]
subprocess.call(cmd, env=env)
print("Dropping db: mole")
cmd = (
'docker exec -it %s psql -U mole_user -d postgres -c "DROP DATABASE mole;"'
% (pg_container_id)
)
subprocess.call(cmd, shell=True)
print("Loading backup from %s" % (postgres_sql_path))
cmd = [ "docker-compose", "exec", "postgres", "psql", "--quiet", "-U", "mole_user", "-d", "postgres", "-f", postgres_sql_path ]
subprocess.call(cmd, env=env)
# Stop services that were not previously running.
if not postgres_running:
cmd = ["docker-compose", "stop", "postgres"]
subprocess.call(cmd, env=env)
if not db_backup_running:
cmd = ["docker-compose", "stop", "db_backup"]
subprocess.call(cmd, env=env)
def django(make_migrations=False):
if make_migrations:
django_running, dj_container_id = service_is_running("django", id=True)
if django_running:
print("Django running, attempting to make migrations.")
cmd = "docker exec -it %s ./manage.py makemigrations" % (dj_container_id)
subprocess.call(cmd, shell=True)
def docs(serve=True, schema=False, graph_models=False):
db_backup = False
cmd = []
if schema or graph_models:
if schema and graph_models:
msg = "Generating OpenAPI schema and graphing models. Waiting for Django service..."
elif schema:
msg = "Generating OpenAPI schema. Waiting for Django service..."
elif graph_models:
msg = "Graphing models. Waiting for Django servoce..."
print(msg)
url = "http://mole.localhost:8000/api/"
cmd = [
"docker-compose",
"-f",
"docker-compose.yml",
"-f",
"docker-compose-docs-livereload-override.yml",
"up",
"django",
]
subprocess.Popen(cmd, preexec_fn=os.setpgrp)
num_tries = 15
# retry num_tries for Django service to be ready
for i in range(num_tries + 1):
try:
# Use closing since Python 2 urlopen doesn't have context handler necessary for with...as statement
with closing(urlopen(url)) as response:
status = response.getcode()
body = response.read()
if schema:
cmd = [
"docker-compose",
"exec",
"django",
"python",
"manage.py",
"generateschema",
"--file",
"openapi_schema.yml",
]
p1 = subprocess.call(cmd)
print("\nOpenAPI Schema generated: mole/openapi_schema.yml\n")
if graph_models:
cmd = [
"docker-compose",
"exec",
"django",
"python",
"manage.py",
"graph_models",
"-a",
"-g",
"-o",
"mole_models_graph.png",
]
p1 = subprocess.call(cmd)
print("\nModels graphed: mole/mole_models_graph.png\n")
print("Stopping Django service...")
cmd = ["docker-compose", "stop", "django"]
subprocess.call(cmd)
break
except IOError:
time.sleep(1.0)
if i == num_tries:
print(
"Schema Generation Error: Django service failed to start. Unable to generate OpenAPI schema."
)
if serve:
print("Serving documentation at http://localhost:8001.")
print("Note: Only limited Mole services are running in this mode.\n")
cmd = [
"docker-compose",
"-f",
"docker-compose.yml",
"-f",
"docker-compose-docs-livereload-override.yml",
"up",
"docs",
"proxy",
]
p = subprocess.Popen(cmd, preexec_fn=os.setpgrp)
try:
return p.wait()
except KeyboardInterrupt:
terminate_mole(p, db_backup)
else:
print(
"Building documentation. Other Mole services are not running in this mode."
)
# override default "mkdocs serve" entrypoint
cmd = ["docker-compose", "run", "--entrypoint", '""', "docs", "mkdocs", "build"]
try:
subprocess.call(cmd)
except KeyboardInterrupt:
stop()
def maps():
cmd = ["docker-compose", "up", "maptiles"]
try:
subprocess.call(cmd)
except KeyboardInterrupt:
stop()
def ang(build=False):
try:
if build:
# check if django service running, start before angular build to ensure it
# is up before attempting to collect static
django_running = service_is_running("django")
if not django_running:
print("Django service not running, starting Django...")
subprocess.call(["docker-compose", "up", "-d", "django"])
# build angular files
build_angular()
# collect static
print("Collecting front-end static files...")
subprocess.call([
"docker-compose",
"exec",
"django",
"./manage.py",
"collectstatic",
"--no-input"
])
# if django wasn't originally running, stop django
if not django_running:
subprocess.call(
["docker-compose", "stop", "django", "postgres", "redis"]
)
else:
print("Spinning up angular development container ...")
subprocess.call(["docker-compose", "up", "angular"])
except KeyboardInterrupt: