-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathsetup
executable file
·2781 lines (2480 loc) · 105 KB
/
setup
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 python3
from enum import Enum
from getpass import getpass
import os
import json
import argparse
import stat as st
import ipaddress
from secrets import token_bytes
from base64 import b64encode
from os import stat
import re
import socket
import shutil
import subprocess
import platform
import urllib.request
import urllib.parse
import urllib.error
import time
import multiprocessing
import sys
import random
import string
import readline
from urllib.parse import urlparse
SECRET_FILE_NAME = ".env.keys"
DEFAULT_INPUTS = {
"CORE_TAG": {
"default": "crestsystems/netskope:core-latest",
"skip": True,
"help": "",
},
"UI_TAG": {
"default": "crestsystems/netskope:ui-latest",
"skip": True,
"help": "",
},
"UI_PORT": {
"default": 80,
"skip": False,
"help": "",
"user_input": "Enter the port on which you want to access the Netskope CE UI",
},
"JWT_SECRET": {
"default": "",
"skip": False,
"help": "",
"mandatory": True,
"user_input": "Enter a JWT Secret which will be used for signing the authentication tokens",
},
"MAINTENANCE_PASSWORD": {
"default": "",
"skip": False,
# "help": "Enter maintenance password that will be used for docker services. This password can be set only once. ",
"help": "",
"mandatory": True,
"user_input": "Enter maintenance password that will be used for RabbitMQ and MongoDB services (This password can be set only once)",
},
"MAINTENANCE_PASSWORD_ESCAPED": {
"default": "",
"skip": True,
"help": "Enter maintenance password that will be used for docker services. This password can be set only once.",
},
"WATCHTOWER_TOKEN": {"default": "token", "skip": True, "help": ""},
"DOCKER_USERNAME": {"default": "", "skip": True, "help": ""},
"DOCKER_PASSWORD": {"default": "", "skip": True, "help": ""},
"MAX_MAINTENANCE_WINDOW_MINUTES": {
"default": 15,
"skip": True,
"help": "",
},
"PULL_THREADS": {"default": 4, "skip": True, "help": ""},
"MAX_WAIT_ON_LOCK_IN_MINUTES": {"default": 240, "skip": True, "help": ""},
"ENABLE_TLS_V_1_2": {
"default": "No",
"skip": False,
"help": "",
"user_input": "Do you want to enable TLSv1.2 along with TLSv1.3 for CE UI",
},
"UI_PROTOCOL": {"default": "https", "skip": True, "help": ""},
"REQUESTS_TIMEOUT": {"default": 300, "skip": True, "help": ""},
"POPEN_TIMEOUT": {"default": 1800, "skip": True, "help": ""},
"IS_MPASS_CONFIGURED": {"default": True, "skip": True, "help": ""},
"MONGO_COMPATIBILITY": {"default": False, "skip": True, "help": ""},
"RABBITMQ_COOKIE": {"default": "", "skip": True, "help": ""},
"LOCATION": {"default": "", "skip": True, "help": ""},
"COMPOSE_HTTP_TIMEOUT": {"default": 600, "skip": True, "help": ""},
"CE_AS_VM": {"default": "False", "skip": True, "help": ""},
"HA_ENABLED": {"default": "False", "skip": True, "help": ""},
"CONTAINERIZATION_PLATFORM": {"default": "", "skip": True, "help": ""},
"COMPOSE_VERSION": {"default": "", "skip": True, "help": ""},
"HOST_OS": {"default": "", "skip": True, "help": ""},
"PLATFORM_PROVIDER": {"default": "unknown", "skip": True, "help": ""},
"PROMOTION_BANNERS_FILE_LOCATION": {
"default": "https://raw.githubusercontent.com/netskopeoss/ta_cloud_exchange/main/ce_promotions.json",
"skip": True,
"help": ""
},
}
AVAILABLE_INPUTS = {}
CHECKS = {}
MIN_CPU = 8
MIN_MEM_KB = 0.90 * 16 * 1024**2 # 90% of 16 GB
MEDIUM_PROFILE_REQUIREMENTS = [8, 16, 80, 20] # CPU, Memory (in GB), Disk (in GB), Free Disk (in GB)
LARGE_PROFILE_REQUIREMENTS = [16, 32, 120, 20] # CPU, Memory (in GB), Disk (in GB), Free Disk (in GB)
CE_PROFILING = {
MEDIUM_PROFILE_REQUIREMENTS[0] : {
"name": "Medium",
"memory": MEDIUM_PROFILE_REQUIREMENTS[1], # in GB
"min_memory": MEDIUM_PROFILE_REQUIREMENTS[1] * 0.90 * 1024**2, # 90% of 16 GB
"min_disk_bytes": MEDIUM_PROFILE_REQUIREMENTS[2] * 0.90 * 1024**3 # 90% of 80 GB
},
LARGE_PROFILE_REQUIREMENTS[0] : {
"name": "Large",
"memory": LARGE_PROFILE_REQUIREMENTS[1], # in GB
"min_memory": LARGE_PROFILE_REQUIREMENTS[1] * 0.90 * 1024**2, # 90% of 32 GB
"min_disk_bytes": LARGE_PROFILE_REQUIREMENTS[2] * 0.90 * 1024**3 # 90% of 120 GB
}
}
MIN_DISK_BYTES = 0.90 * 80 * 1024**3 # 90% of 80 GB
MIN_FREE_DISK_BYTES = 20*1024**3
MIN_DOCKER_VERSION = "19.0.0"
MIN_DOCKER_COMPOSE_VERSION = "2.16.0"
MIN_PODMAN_VERSION = "3.4.2"
MIN_PODMAN_COMPOSE_VERSION = "1.0.3"
N = 5
MIN_HA_SUPPORTED_VERSION = "5.0.0"
CURRENT_VERSION = "5.1.0"
PREVIOUS_VERSION = "5.0.1"
CURRENT_BETA_VERSION = "5.1.0-beta"
CE_VERSION_1 = f"CE v{N}-{CURRENT_VERSION}"
CE_VERSION_2 = f"CE v{N}-{PREVIOUS_VERSION}"
CE_VERSION_3 = f"CE {CURRENT_BETA_VERSION}"
CORE_VERSION_1_TAG = (
f"netskopetechnicalalliances/cloudexchange:core{N}-{CURRENT_VERSION}"
)
UI_VERSION_1_TAG = f"netskopetechnicalalliances/cloudexchange:ui{N}-{CURRENT_VERSION}"
CORE_VERSION_2_TAG = (
f"netskopetechnicalalliances/cloudexchange:core{N}-{PREVIOUS_VERSION}"
)
UI_VERSION_2_TAG = (
f"netskopetechnicalalliances/cloudexchange:ui{N}-{PREVIOUS_VERSION}"
)
CORE_VERSION_BETA_TAG = (
f"netskopetechnicalalliances/cloudexchange:core-{CURRENT_BETA_VERSION}"
)
UI_VERSION_BETA_TAG = (
f"netskopetechnicalalliances/cloudexchange:ui-{CURRENT_BETA_VERSION}"
)
CORE_VERSION_1_LATEST_TAG = f"netskopetechnicalalliances/cloudexchange:core{N}-latest"
UI_VERSION_1_LATEST_TAG = f"netskopetechnicalalliances/cloudexchange:ui{N}-latest"
CORE_VERSION_2_LATEST_TAG = f"netskopetechnicalalliances/cloudexchange:core{N}-latest"
UI_VERSION_2_LATEST_TAG = f"netskopetechnicalalliances/cloudexchange:ui{N}-latest"
RECOMMENDED_DOCKER_VERSION = "25.0.3"
RECOMMENDED_DOCKER_COMPOSE_VERSION = "2.27.0"
RECOMMENDED_PODMAN_VERSION = "4.6.1"
RECOMMENDED_PODMAN_COMPOSE_VERSION = "1.0.6"
RECOMMENDED_HOST_OS = ["Ubuntu 20", "Ubuntu 22", "RHEL 8", "RHEL 9"]
GIT_PLUGIN_REPO = "https://github.com/netskopeoss/ta_cloud_exchange_plugins.git"
MONGO_USER_ID = 999
MONGO_MIGRATION_TIMEOUT = 60
is_ui_running = False
is_rabbitmq_running = False
is_mongodb_running = False
is_ha = False
CONTAINERIZATION_PLATFORM = None
COMPOSE_VERSION = None
HOST_OS = None
should_ignore = False
CE_VERSIONS_INPUT_DICT = {
CE_VERSION_1: {
"CORE_TAG": CORE_VERSION_1_TAG,
"UI_TAG": UI_VERSION_1_TAG,
"BETA_OPT_IN": "No",
"CORE_LATEST_VERSION_TAG": CORE_VERSION_1_LATEST_TAG,
"UI_LATEST_VERSION_TAG": UI_VERSION_1_LATEST_TAG,
"INSTALL_VERSION": CURRENT_VERSION,
},
CE_VERSION_2: {
"CORE_TAG": CORE_VERSION_2_TAG,
"UI_TAG": UI_VERSION_2_TAG,
"BETA_OPT_IN": "No",
"CORE_LATEST_VERSION_TAG": CORE_VERSION_2_LATEST_TAG,
"UI_LATEST_VERSION_TAG": UI_VERSION_2_LATEST_TAG,
"INSTALL_VERSION": PREVIOUS_VERSION,
},
CE_VERSION_3: {
"CORE_TAG": CORE_VERSION_BETA_TAG,
"UI_TAG": UI_VERSION_BETA_TAG,
"BETA_OPT_IN": "yes",
"CORE_LATEST_VERSION_TAG": CORE_VERSION_BETA_TAG,
"UI_LATEST_VERSION_TAG": UI_VERSION_BETA_TAG,
"INSTALL_VERSION": CURRENT_BETA_VERSION,
},
}
class Status(Enum):
PASS = ("PASS",)
NOT_VERIFIED = ("COULDN'T VERIFY",)
FAIL = "FAIL"
def print_banner():
print(
"""
_ _ _ _ ____ _____
| \ | | ___ | |_ ___ | | __ ___ _ __ ___ / ___|| ____|
| \| | / _ \| __|/ __|| |/ // _ \ | '_ \ / _ \ | | | _|
| |\ || __/| |_ \__ \| <| (_) || |_) || __/ | |___ | |___
|_| \_| \___| \__||___/|_|\_\\\___/ | .__/ \___| \____||_____|
___ _ _ _ |_| _ _
|_ _| _ __ ___ | |_ __ _ | || | __ _ | |_ (_) ___ _ __
| | | '_ \ / __|| __|/ _` || || | / _` || __|| | / _ \ | '_ \
| | | | | |\__ \| |_| (_| || || || (_| || |_ | || (_) || | | |
|___||_| |_||___/ \__|\__,_||_||_| \__,_| \__||_| \___/ |_| |_|
"""
)
def print_warning(message):
print(f"\033[1;93m[!] \033[0;37m{message}")
def print_fail(message):
print(f"\033[1;31m[F] \033[1;37m{message}\033[0;37m")
def print_pass(message):
print(f"\033[0;32m[P] \033[0;37m{message}")
def compare_versions(version1, version2):
versions1 = [int(v) for v in version1.split(".")]
versions2 = [int(v) for v in version2.split(".")]
for i in range(max(len(versions1), len(versions2))):
v1 = versions1[i] if i < len(versions1) else 0
v2 = versions2[i] if i < len(versions2) else 0
if v1 > v2:
return True
elif v1 < v2:
return False
return True
def compare_ce_versions(v1, v2):
"""
Compare two CE version strings.
The version string is in the format "A.B.C" or "A.B.C-beta.D.E". The function
first splits the string into main version and beta version. Then it compares
the main version first, and the beta version second. If the beta version is
not present, it is considered to be (0,).
Returns:
0 if the versions are equal
-1 if v1 is less than v2
1 if v1 is greater than v2
"""
if not v1:
return -1
if not v2:
return 1
def version_to_tuple(version):
parts = version.split('-')
main_version = parts[0].split('.')
main_version = tuple(int(part) for part in main_version)
if len(parts) > 1:
beta_version = parts[1].split('.')
beta_version = tuple(int(part) for part in beta_version if part.isdigit())
return main_version + (0,) + beta_version
else:
return main_version + (1,)
v1_tuple = version_to_tuple(v1)
v2_tuple = version_to_tuple(v2)
if v1_tuple == v2_tuple:
return 0
elif v1_tuple < v2_tuple:
return -1
else:
return 1
def _get_container_name(container_info):
container_name = container_info.get("Names", "")
if isinstance(container_name, list):
container_name = container_name[0]
return container_name
def strtobool(val):
val = val.lower()
if val in ("y", "yes", "t", "true", "on", "1"):
return 1
elif val in ("n", "no", "f", "false", "off", "0"):
return 0
else:
raise ValueError("invalid truth value %r" % (val,))
def ce_as_vm_check():
return os.path.exists("/.cloud_exchange_vm.marker")
def fetch_container_info():
global is_ui_running, is_rabbitmq_running, is_mongodb_running
try:
if isRedHat():
p = subprocess.Popen(
["podman", "ps", "--format", "json"],
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
)
out, err = p.communicate()
containers = json.loads(out.decode("utf-8"))
if err:
raise Exception("Unable to fetch container information.")
else:
p = subprocess.Popen(
["docker", "ps", "--format", "json"],
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
)
out, err = p.communicate()
if err:
raise Exception("Unable to fetch container information.")
containers = [json.loads(line) for line in out.decode("utf-8").splitlines()]
for container_info in containers:
if "_mongodb-primary" in _get_container_name(container_info):
is_mongodb_running = True
elif "_rabbitmq-stats" in _get_container_name(container_info):
is_rabbitmq_running = True
elif "_ui" in _get_container_name(container_info):
is_ui_running = True
except Exception:
print_warning("Unable to fetch container information.")
def put_proxy_in_env(location=".env"):
try:
with open(location, "w") as f:
for key, value in AVAILABLE_INPUTS.items():
f.write(f"{key}={value}\n")
except Exception as e:
raise Exception(f"Error occurred while putting proxy variables: {e}")
def update_connection_string(hosts_list, location):
host_list = []
for hostname in hosts_list:
host_list.append(f"{hostname}:27017")
with open(location, "r") as file:
lines = file.readlines()
new_lines = []
mpass_escaped = None
for line in lines:
if line.startswith("MAINTENANCE_PASSWORD_ESCAPED="):
mpass_escaped = line.split("=")[1].strip()
if line.startswith("MONGO_CONNECTION_STRING=") and mpass_escaped:
mongo_host_list = ",".join(host_list)
mongo_connection_string = f"mongodb://cteadmin:{mpass_escaped}@{mongo_host_list}/cte?replicaSet=mongo_replica_set"
new_line = "MONGO_CONNECTION_STRING=" + mongo_connection_string + "\n"
elif line.startswith("RABBITMQ_CONNECTION_STRING=") and mpass_escaped:
rabbitmq_connection_string = ";".join(
[f"amqp://user:{mpass_escaped}@{host}" for host in hosts_list]
)
new_line = "RABBITMQ_CONNECTION_STRING=" + rabbitmq_connection_string + "\n"
else:
new_line = line
new_lines.append(new_line)
# Write the updated content back to the file
with open(location, "w") as file:
file.writelines(new_lines)
def create_secret_file(passwords, location):
mpass = passwords["MAINTENANCE_PASSWORD"][1:-1]
mpass_escaped = passwords["MAINTENANCE_PASSWORD_ESCAPED"]
passwords[
"MONGO_CONNECTION_STRING"
] = f"mongodb://cteadmin:{mpass_escaped}@mongodb-primary:27017/cte"
passwords[
"RABBITMQ_CONNECTION_STRING"
] = f"amqp://user:{mpass_escaped}@rabbitmq-stats"
passwords["RABBITMQ_DEFAULT_PASS"] = mpass
passwords["MONGO_INITDB_ROOT_PASSWORD"] = mpass
passwords["MONGODB_PASSWORD"] = mpass
with open(location, "w") as f:
for key, value in passwords.items():
f.write(f"{key}={value}\n")
command = f"sudo chmod 400 {location}"
set_directory_permission(location, command)
def get_secret_location(inputs):
secret_location = SECRET_FILE_NAME
if ce_as_vm_check():
secret_location = f"/etc/{SECRET_FILE_NAME}"
if "HA_IP_LIST" in inputs.keys():
secret_location = (
inputs.get("HA_NFS_DATA_DIRECTORY", None) + f"/{SECRET_FILE_NAME}"
if inputs.get("HA_NFS_DATA_DIRECTORY", None)
else None
)
return secret_location
def put_env_variable(inputs, location=".env"):
inputs = dict(inputs)
# Remove keys that are not in .env
inputs.pop("CURRENT_DATABASE_VERSION", None)
if location != ".env":
inputs.pop("HA_CURRENT_NODE", None)
inputs.pop("HA_NFS_DATA_DIRECTORY", None)
try:
if (
"MAINTENANCE_PASSWORD" in inputs
and "MAINTENANCE_PASSWORD_ESCAPED" in inputs
):
inputs["IS_MPASS_CONFIGURED"] = True
passwords = {}
passwords["MAINTENANCE_PASSWORD"] = inputs.pop("MAINTENANCE_PASSWORD", None)
passwords["MAINTENANCE_PASSWORD_ESCAPED"] = inputs.pop(
"MAINTENANCE_PASSWORD_ESCAPED", None
)
if (
passwords["MAINTENANCE_PASSWORD"]
and passwords["MAINTENANCE_PASSWORD_ESCAPED"]
):
secret_location = get_secret_location(inputs)
if secret_location:
create_secret_file(passwords, secret_location)
inputs["LOCATION"] = secret_location
AVAILABLE_INPUTS["LOCATION"] = secret_location
if "HA_IP_LIST" in inputs.keys():
update_connection_string(
inputs.get("HA_IP_LIST", []).split(","), inputs.get("LOCATION", "")
)
with open(location, "w") as f:
for key, value in inputs.items():
f.write(f"{key}={value}\n")
except Exception as e:
raise Exception(f"Error occurred while putting env variables: {e}")
def create_env_if_not_exist(location=".env"):
try:
with open(location, "a") as f:
pass
except Exception as e:
raise Exception(f"Error occurred while creating file: {e}")
def execute_shell_command(command, **kwargs):
"""Function to exectute shell command using python script."""
p = None
try:
p = subprocess.check_output(command, shell=True, **kwargs)
return p
except Exception as e:
if p:
p.kill()
raise Exception(f"Error occurred while executing command. Error: {e}")
def create_mongo_container(deployment, maintenance_password, http_proxy, https_proxy, temp_container_name, image_name):
"""Create MongoDB container."""
create_container = f"{deployment} run -d -t -e MONGODB_ADVERTISED_HOSTNAME=mongodb-primary \
-e MONGO_INITDB_ROOT_USERNAME=root \
-e MONGO_INITDB_ROOT_PASSWORD={maintenance_password} \
-e MONGO_INITDB_DATABASE=cte \
-e MONGODB_USERNAME=cteadmin \
-e MONGODB_PASSWORD={maintenance_password} \
-e HTTP_PROXY=${http_proxy} \
-e HTTPS_PROXY=${https_proxy} \
-v ./data/mongo-data/data/db:/data/db:z \
--name {temp_container_name} \
index.docker.io/{image_name} >/dev/null 2>&1"
execute_shell_command(create_container)
def remove_mongo_contianer(deployment, temp_mongo_container_name):
"""Remove mongodb contianer."""
remove_container = f"{deployment} rm -f {temp_mongo_container_name} >/dev/null 2>&1"
execute_shell_command(remove_container)
time.sleep(5)
def execute_mongodb_command(deployment, temp_mongo_container_name, shell, maintenance_password, eval_command, **kwargs):
"""Execute command inside mongodb contianer."""
compatibility_command = f"{deployment} exec {temp_mongo_container_name} {shell} -u root --password {maintenance_password} admin --eval {eval_command}"
execute_shell_command(compatibility_command, **kwargs)
def run_temp_mongo_container_for_migration(
maintenance_password, http_proxy, https_proxy
):
"""Migrate mongo data by running temp mongo container and update featurecompatibilityversion variable from mongo."""
deployment = None
MONGO_MIGRATE_IMAGE = "mongo:5.0.21"
MONGO_CURRENT_IMAGE = "mongo:6.0.12"
temp_mongo_container_name = "mongo-migration"
if isRedHat():
deployment = "podman"
else:
deployment = "docker"
# If from previous temp container is still running then kill that container and start again.
remove_mongo_contianer(deployment, temp_mongo_container_name)
# create mongo contianer
create_mongo_container(
deployment,
maintenance_password,
http_proxy,
https_proxy,
temp_mongo_container_name,
MONGO_MIGRATE_IMAGE
)
try:
time.sleep(MONGO_MIGRATION_TIMEOUT // 2)
eval_command = """'db.adminCommand({setFeatureCompatibilityVersion: "5.0"})'"""
execute_mongodb_command(deployment, temp_mongo_container_name, "mongo", maintenance_password, eval_command, stderr=subprocess.PIPE)
except Exception:
# remove above container
time.sleep(MONGO_MIGRATION_TIMEOUT // 2)
remove_mongo_contianer(deployment, temp_mongo_container_name)
# spin latest mongo version to check compatibility
create_mongo_container(
deployment,
maintenance_password,
http_proxy,
https_proxy,
temp_mongo_container_name,
MONGO_CURRENT_IMAGE
)
time.sleep(MONGO_MIGRATION_TIMEOUT // 2)
eval_command = """'db.adminCommand({getParameter: 1, featureCompatibilityVersion: 1})'"""
execute_mongodb_command(deployment, temp_mongo_container_name, "mongosh", maintenance_password, eval_command)
time.sleep(MONGO_MIGRATION_TIMEOUT // 2)
remove_mongo_contianer(deployment, temp_mongo_container_name)
print_pass("The migration of database has been successfully completed.")
def get_all_existed_env_variable(location=".env", override=True):
try:
if not os.path.exists(location):
return
with open(location, "r") as f:
if os.stat(location).st_size > 0:
with open(f"{location}.{int(time.time())}", "w+") as backup:
for line in f.readlines():
backup.write(line)
key, value = line.split("=", 1)
if override or key not in AVAILABLE_INPUTS:
AVAILABLE_INPUTS[key] = value.strip()
if AVAILABLE_INPUTS.get("HTTPS_PROXY"):
AVAILABLE_INPUTS["CORE_HTTP_PROXY"] = AVAILABLE_INPUTS["HTTPS_PROXY"]
AVAILABLE_INPUTS["CORE_HTTPS_PROXY"] = AVAILABLE_INPUTS["HTTPS_PROXY"]
AVAILABLE_INPUTS.pop("HTTP_PROXY", None)
AVAILABLE_INPUTS.pop("HTTPS_PROXY", None)
if AVAILABLE_INPUTS.get("RABBITMQ_CUSTOM_CONF_PATH"):
AVAILABLE_INPUTS.pop("RABBITMQ_CUSTOM_CONF_PATH", None)
except Exception as e:
raise Exception(f"Error occurred while getting env variables: {e}")
def set_directory_permission(directory, command):
p = None
try:
p = subprocess.Popen(
command.split(),
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
)
out, err = p.communicate()
if len(err) <= 0:
return
else:
raise Exception(err.decode("utf-8"))
except Exception as e:
if p:
p.kill()
raise Exception(
f"Error occurred while setting file permissions for {directory}. Error: {e}"
)
def _get_cert_location():
cert_file = "data/ssl_certs/cte_cert.crt"
key_file = "data/ssl_certs/cte_cert_key.key"
if AVAILABLE_INPUTS.get("HA_NFS_DATA_DIRECTORY"):
cert_file = (
f"{AVAILABLE_INPUTS['HA_NFS_DATA_DIRECTORY']}/config/ssl_certs/cte_cert.crt"
)
key_file = f"{AVAILABLE_INPUTS['HA_NFS_DATA_DIRECTORY']}/config/ssl_certs/cte_cert_key.key"
return cert_file, key_file
def check_for_certs():
try:
cert_file, key_file = _get_cert_location()
if os.path.isfile(cert_file) and os.path.isfile(key_file):
return True
return False
except Exception as e:
raise Exception(f"Error occurred while checking for SSL certs. Error: {e}")
def create_self_signed_ssl_certs():
try:
cert_file, key_file = _get_cert_location()
print(f"Generating self signed certificate with validity of one year...")
command = f"openssl req -x509 -newkey rsa:4096 -keyout {key_file} -out {cert_file} -sha256 -days 365 -nodes -subj /CN=localhost -extensions extendedkeyusage -config data/ssl_certs/extendedkeyusage.txt"
p = subprocess.Popen(
command.split(),
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
)
out, err = p.communicate()
if p.returncode == 0:
print(f"{err.decode('utf-8')}\n")
command = f"sudo chmod 666 {cert_file}"
set_directory_permission(cert_file, command)
command_key = f"sudo chmod 666 {key_file}"
set_directory_permission(key_file, command_key)
else:
raise Exception(f"{err.decode('utf-8')}\n")
except Exception as e:
p.kill()
raise Exception(
f"Error occurred while generating self-signed ssl certificates. Error: {e}"
)
def check_port_for_ha(ip, port, timeout=3):
"""
Check if a specific port on a given IP is reachable.
Args:
ip (str): The IP address to check.
port (int): The port number to check.
timeout (int): Timeout for the connection attempt in seconds.
Returns:
tuple: A tuple containing the following elements:
- is_port_open (bool): True if the port is open, False otherwise.
- is_service_running (bool): True if the service is running, False otherwise.
"""
# Create a socket object
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout)
is_port_open = False
is_service_running = False
try:
# Try to connect to the given IP and port
sock.connect((ip, port))
try:
# Try to send some data to see if the service responds
sock.sendall(b'Hello')
data = sock.recv(1024)
if data:
is_port_open = True
is_service_running = True
else:
is_port_open = True
is_service_running = False
except socket.error:
is_port_open = True
is_service_running = False
except socket.timeout:
is_port_open = False
is_service_running = False
except socket.error as e:
if e.errno == 111: # Connection refused
is_port_open = True
is_service_running = False
else:
is_port_open = False
is_service_running = False
finally:
sock.close()
return is_port_open, is_service_running
def check_for_ha_ports():
try:
port_flag = True
for port in [4369, 5672, 15672, 25672, 35672]:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex(("127.0.0.1", port))
if result == 0:
if is_rabbitmq_running:
print_warning("RabbitMQ container is already running.")
break
else:
print_fail(f"Port {port} is already in use.")
port_flag = False
else:
print_pass(f"Port {port} is available.")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex(("127.0.0.1", 27017))
if result == 0:
if is_mongodb_running:
print_warning("MongoDB container is already running.")
else:
print_fail(f"Port 27017 is already in use.")
port_flag = False
else:
print_pass(f"Port 27017 is available.")
CHECKS["Port Check"] = Status.PASS if port_flag else Status.FAIL
except Exception as e:
# print(e)
print_warning(f"Could not verify Port information of the machine")
CHECKS["Port Check"] = Status.NOT_VERIFIED
port_error_msg = False
for host in AVAILABLE_INPUTS.get("HA_IP_LIST", "").split(","):
if host != AVAILABLE_INPUTS.get("HA_CURRENT_NODE"):
for port in [4369, 5672, 15672, 25672, 35672, 27017]:
is_port_open, _ = check_port_for_ha(host, port)
if not is_port_open:
print_fail(f"Port {port} of {host} is not reachable from {AVAILABLE_INPUTS.get('HA_CURRENT_NODE')}")
port_error_msg = True
else:
print_pass(f"Port {port} of {host} is reachable from {AVAILABLE_INPUTS.get('HA_CURRENT_NODE')}")
if port_error_msg:
print(
"\033[1;31mPlease ensure all HA nodes are reachable from each other.\033[0;37m"
)
CHECKS["Port Check"] = Status.FAIL
def print_sizing_table(actual):
"""Print the sizing table."""
metrics = ["Cores", "RAM (GB)", "Disk Space (GB)", "Free Space (GB)"]
print("+-----------------+---------------+-----------------+-----------------+")
print(f"| {'Metric':<15} | {'Current':<13} | {'Medium Profile':<15} | {'Large Profile':<15} |")
print("+-----------------+---------------+-----------------+-----------------+")
# Print the data rows
for i in range(len(metrics)):
print(f"| {metrics[i]:<15} | {str(actual[i]):<13} | {str(MEDIUM_PROFILE_REQUIREMENTS[i]):<15} | {str(LARGE_PROFILE_REQUIREMENTS[i]):<15} |")
print("+-----------------+---------------+-----------------+-----------------+")
def check_machine_specs():
print("\nVerifying minimum system requirements...")
print(
'\033[1;37mNOTE: The actual system requirements depend on several criteria including data volume, # of plugins among others.\nIt is highly recommended to refer to the System Requirements section of the "User Guide".\n'+
'CE sizing profile is decided based on number of CPU(s) on the machine. 8 CPUs are required for the medium profile and 16 CPUs are required for the large profile.\033[0;37m'
)
# Check CPUs
try:
profile_name = None
cpu_cores = multiprocessing.cpu_count()
if cpu_cores not in CE_PROFILING:
CHECKS["CPU Check"] = Status.FAIL
else:
profile_name = CE_PROFILING[cpu_cores]["name"]
CHECKS["CPU Check"] = Status.PASS
except Exception as e:
print_warning(f"Could not verify CPU information of the machine...")
CHECKS["CPU Check"] = Status.NOT_VERIFIED
# Check Memory
try:
total_memory = None
with open("/proc/meminfo", "r") as f:
lines = f.readlines()
for line in lines:
if line.startswith("MemTotal"):
memory = int(line.split()[1])
total_memory = round(memory/1024**2, 1)
memory_pass = False
if cpu_cores in CE_PROFILING:
if memory < CE_PROFILING[cpu_cores]["min_memory"]:
CHECKS["Memory Check"] = Status.FAIL
else:
memory_pass = True
else:
CHECKS["Memory Check"] = Status.FAIL
if memory_pass:
CHECKS["Memory Check"] = Status.PASS
break
except Exception as e:
# print(e)
print_warning(f"Could not verify Memory information of the machine")
CHECKS["Memory Check"] = Status.NOT_VERIFIED
# Check Disk Space
try:
# Get the path of the current file
current_file_path = __file__
# Get the directory of the current file
current_dir = os.path.dirname(current_file_path) or os.getcwd()
disk_stats = shutil.disk_usage(current_dir)
free_space = disk_stats.free
total_space = disk_stats.total
disk_space_check_pass = False
if cpu_cores in CE_PROFILING:
min_disk_bytes = CE_PROFILING[cpu_cores]["min_disk_bytes"]
if total_space < min_disk_bytes:
CHECKS["Disk Space Check"] = Status.FAIL
else:
disk_space_check_pass = True
else:
CHECKS["Disk Space Check"] = Status.FAIL
if disk_space_check_pass:
CHECKS["Disk Space Check"] = Status.PASS
try:
if free_space < MIN_FREE_DISK_BYTES:
CHECKS["Free Disk Space Check"] = Status.FAIL
else:
CHECKS["Free Disk Space Check"] = Status.PASS
except Exception as e:
print_warning(f"Could not verify Disk information of the machine")
CHECKS["Free Disk Space Check"] = Status.NOT_VERIFIED
except Exception as e:
# print(e)
print_warning(f"Could not verify Disk information of the machine")
CHECKS["Disk Space Check"] = Status.NOT_VERIFIED
matched = not ( Status.FAIL in [
CHECKS.get("CPU Check"),
CHECKS.get("Memory Check"),
CHECKS.get("Disk Space Check"),
CHECKS.get("Free Disk Space Check")
]
)
sizing_result = None
if not profile_name and cpu_cores < MEDIUM_PROFILE_REQUIREMENTS[0]:
profile_name = CE_PROFILING[MEDIUM_PROFILE_REQUIREMENTS[0]]["name"]
elif not profile_name:
profile_name = CE_PROFILING[LARGE_PROFILE_REQUIREMENTS[0]]["name"]
if matched:
sizing_result = f"\033[0;32mMatched with {profile_name} profile\033[0;37m"
else:
sizing_result = f"\033[1;31mFailed for {profile_name} profile\033[0;37m"
print("\nCE Sizing Profile Check:", sizing_result, end="\n\n")
if not matched:
machine_specs = [cpu_cores, total_memory, round(total_space/1024**3, 1), round(free_space/1024**3, 1)]
print_sizing_table(machine_specs)
# Check port availability
if is_ha or (AVAILABLE_INPUTS.get("HA_IP_LIST") and AVAILABLE_INPUTS.get("HA_CURRENT_NODE")):
check_for_ha_ports()
if Status.FAIL in [
CHECKS.get("Memory Check"),
CHECKS.get("Disk Space Check"),
CHECKS.get("Free Disk Space Check"),
CHECKS.get("CPU Check"),
CHECKS.get("Port Check"),
]:
print(
"\033[1;31mOne or more system requirement checks have failed. Please ensure the minimum system requirements are met to proceed further. \033[0;37m"
)
global should_ignore
if not should_ignore and Status.FAIL in [
CHECKS.get("Memory Check"),
CHECKS.get("Disk Space Check"),
CHECKS.get("Free Disk Space Check"),
CHECKS.get("CPU Check"),
CHECKS.get("Port Check"),
]:
exit(1)
def check_docker_versions():
try:
global CONTAINERIZATION_PLATFORM, COMPOSE_VERSION
regex = r"(\d+(\.\d+){2,3})"
command = "docker --version"
p = subprocess.check_output(command, shell=True)
docker_version = re.search(regex, p.decode("utf-8")).groups()[0]
CONTAINERIZATION_PLATFORM = "Docker " + docker_version
if compare_versions(docker_version, MIN_DOCKER_VERSION):
print_pass(f"Docker Version {docker_version}")
CHECKS["Docker"] = Status.PASS
else:
print_fail(
f"Docker Version {docker_version} (Minimum {MIN_DOCKER_VERSION} is required)"
)
CHECKS["Docker"] = Status.FAIL
if docker_version != RECOMMENDED_DOCKER_VERSION:
print_warning(f"The recommended docker version is {RECOMMENDED_DOCKER_VERSION}")
command = "docker compose version"
p = subprocess.check_output(command, shell=True)
docker_compose_version = re.search(regex, p.decode("utf-8")).groups()[0]
COMPOSE_VERSION = "docker compose " + docker_compose_version
if compare_versions(docker_compose_version, MIN_DOCKER_COMPOSE_VERSION):
print_pass(f"Docker Compose Version {docker_compose_version}")
CHECKS["Docker-Compose"] = Status.PASS
else:
print_fail(
f"Docker Compose Version {docker_compose_version} (Minimum {MIN_DOCKER_COMPOSE_VERSION} is required)"
)
CHECKS["Docker-Compose"] = Status.FAIL
if docker_compose_version != RECOMMENDED_DOCKER_COMPOSE_VERSION:
print_warning(f"The recommended docker compose version is {RECOMMENDED_DOCKER_COMPOSE_VERSION}")
except Exception as e:
CHECKS["Docker-Compose"] = Status.NOT_VERIFIED
CHECKS["Docker"] = Status.NOT_VERIFIED
raise Exception("Docker not found")
def check_podman_versions():
try:
global CONTAINERIZATION_PLATFORM, COMPOSE_VERSION
regex = r"(\d+(\.\d+){2,3})"
command = "podman-compose --version"
p = subprocess.check_output(command, shell=True)
lines = p.decode("utf-8").splitlines()
podman_version = ""
for line in lines:
if "podman version" in line:
podman_version = re.search(regex, line).groups()[0]
break
if podman_version == "":
raise
CONTAINERIZATION_PLATFORM = "Podman " + podman_version
if compare_versions(podman_version, MIN_PODMAN_VERSION):
print_pass(f"Podman Version {podman_version}")
CHECKS["Podman"] = Status.PASS
else:
print_fail(
f"Podman Version {podman_version} (Minimum {MIN_PODMAN_VERSION} is required)"
)
CHECKS["Podman"] = Status.FAIL
if podman_version != RECOMMENDED_PODMAN_VERSION:
print_warning(f"The recommended podman version is {RECOMMENDED_PODMAN_VERSION}")
podman_compose_version = ""
for line in lines:
if "podman-compose" in line:
podman_compose_version = re.search(regex, line).groups()[0]
break
if podman_compose_version == "":
raise
COMPOSE_VERSION = "podman-compose " + podman_compose_version
if compare_versions(podman_compose_version, MIN_PODMAN_COMPOSE_VERSION):
print_pass(f"Podman Compose Version {podman_compose_version}")
CHECKS["Podman-Compose"] = Status.PASS
else:
print_fail(
f"Podman Compose Version {podman_compose_version} (Minimum {MIN_PODMAN_COMPOSE_VERSION} is required)"
)
CHECKS["Podman-Compose"] = Status.FAIL
if podman_compose_version != RECOMMENDED_PODMAN_COMPOSE_VERSION:
print_warning(f"The recommended podman-compose version is {RECOMMENDED_PODMAN_COMPOSE_VERSION}")
command = "rpm -qa"
p = subprocess.check_output(command, shell=True)
lines = p.decode("utf-8").splitlines()
is_plugin_present = False
for line in lines:
if line.startswith("podman-plugins"):
is_plugin_present = True
break
if is_plugin_present:
print_pass(f"Verified podman plugins are installed")
CHECKS["Podman-Plugin"] = Status.PASS
else:
print_fail(
f"Required podman plugins are not installed. (Run `yum install podman-plugins` and Re-run the script)"
)
CHECKS["Podman-Plugin"] = Status.FAIL