-
Notifications
You must be signed in to change notification settings - Fork 14
/
setup
executable file
·2321 lines (2057 loc) · 87.5 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
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": ""},
}
AVAILABLE_INPUTS = {}
CHECKS = {}
MIN_CPU = 2
MIN_MEM_KB = 3500000
MIN_DISK_BYTES = 20000000000
MIN_DOCKER_VERSION = "19.0.0"
MIN_DOCKER_COMPOSE_VERSION = "1.29.0"
MIN_PODMAN_VERSION = "3.4.2"
MIN_PODMAN_COMPOSE_VERSION = "1.0.3"
N = 5
CURRENT_VERSION = "5.0.1"
PREVIOUS_VERSION = "4.2.0"
CURRENT_BETA_VERSION = "5.0.1"
CE_VERSION_1 = f"CE v{N}-{CURRENT_VERSION}"
CE_VERSION_2 = f"CE v{N-1}-{PREVIOUS_VERSION}"
CE_VERSION_3 = f"CE {CURRENT_BETA_VERSION}-beta"
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-1}-{PREVIOUS_VERSION}"
)
UI_VERSION_2_TAG = (
f"netskopetechnicalalliances/cloudexchange:ui{N-1}-{PREVIOUS_VERSION}"
)
CORE_VERSION_BETA_TAG = (
f"netskopetechnicalalliances/cloudexchange:core-{CURRENT_BETA_VERSION}-beta"
)
UI_VERSION_BETA_TAG = (
f"netskopetechnicalalliances/cloudexchange:ui-{CURRENT_BETA_VERSION}-beta"
)
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-1}-latest"
UI_VERSION_2_LATEST_TAG = f"netskopetechnicalalliances/cloudexchange:ui{N-1}-latest"
RECOMMENDED_DOCKER_VERSION = "25.0.3"
RECOMMENDED_DOCKER_COMPOSE_VERSION = "2.24.6"
RECOMMENDED_PODMAN_VERSION = "4.6.1"
RECOMMENDED_PODMAN_COMPOSE_VERSION = "1.0.6"
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
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 _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)
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):
"""Function to exectute shell command using python script."""
p = None
try:
p = subprocess.check_output(command, shell=True)
except Exception as e:
if p:
p.kill()
raise Exception(f"Error occurred while executing command. Error: {e}")
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"
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_container = f"{deployment} rm -f {temp_mongo_container_name} >/dev/null 2>&1"
execute_shell_command(remove_container)
time.sleep(5)
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_mongo_container_name} \
index.docker.io/{MONGO_MIGRATE_IMAGE} >/dev/null 2>&1"
execute_shell_command(create_container)
time.sleep(MONGO_MIGRATION_TIMEOUT // 2)
eval_command = """'db.adminCommand({setFeatureCompatibilityVersion: "5.0"})'"""
compatibility_command = f"{deployment} exec {temp_mongo_container_name} mongo -u root --password {maintenance_password} admin --eval {eval_command}"
execute_shell_command(compatibility_command)
time.sleep(MONGO_MIGRATION_TIMEOUT // 2)
remove_container = f"{deployment} rm -f {temp_mongo_container_name} >/dev/null 2>&1"
execute_shell_command(remove_container)
print_pass("The migration of database has been successfully completed.")
def get_all_existed_env_variable(location=".env", override=True):
try:
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_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".\033[0;37m'
)
# Check Memory
try:
with open("/proc/meminfo", "r") as f:
lines = f.readlines()
for line in lines:
if line.startswith("MemTotal"):
memory = int(line.split()[1])
if memory < MIN_MEM_KB:
print_fail(
f"{round(memory/1000000, 1)}GB Memory (Minimum {round(MIN_MEM_KB/1000000)}GB required)"
)
CHECKS["Memory Check"] = Status.FAIL
else:
print_pass(f"{round(memory/1000000, 1)}GB Memory")
CHECKS["Memory Check"] = Status.PASS
except Exception as e:
# print(e)
print_warning(f"Could not verify Memory information of the machine")
CHECKS["Memory Check"] = Status.NOT_VERIFIED
# Check CPUs
try:
cpu_cores = multiprocessing.cpu_count()
if cpu_cores < MIN_CPU:
print_fail(f"{cpu_cores} CPU(s) (Minimum {MIN_CPU} CPU(s) required)")
CHECKS["CPU Check"] = Status.FAIL
else:
print_pass(f"{cpu_cores} CPU(s)")
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 Disk Space
try:
path = "/var/lib/docker"
if isRedHat() and not isRedHat79():
path = "/var/lib/containers"
disk_stats = shutil.disk_usage(path)
free_space = disk_stats.free
if free_space < MIN_DISK_BYTES:
print_fail(
f"{round(free_space/1000000000, 1)}GB free disk space (Minimum {round(MIN_DISK_BYTES/1000000000, 1)}GB free disk space is required)"
)
CHECKS["Disk Space Check"] = Status.FAIL
else:
print_pass(f"{round(free_space/1000000000, 1)}GB free disk space")
CHECKS["Disk Space Check"] = Status.PASS
except Exception as e:
# print(e)
print_warning(f"Could not verify Disk information of the machine")
CHECKS["Disk Space Check"] = Status.NOT_VERIFIED
# Check 15672 and 27017 Port availability
if is_ha:
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
if Status.FAIL in [
CHECKS.get("Memory Check"),
CHECKS.get("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"
)
def check_docker_versions():
try:
regex = "(\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]
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]
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:
regex = "(\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
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
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
except Exception as e:
# print(e)
CHECKS["Podman-Compose"] = Status.NOT_VERIFIED
CHECKS["Podman-Plugin"] = Status.NOT_VERIFIED
CHECKS["Podman"] = Status.NOT_VERIFIED
raise Exception("Podman not found")
def validate_proxy(proxy, cur_proxy=None):
if proxy == "" and cur_proxy is not None and len(cur_proxy) > 0:
return True
regex = "^(?:(.*))://(?:(.*))$"
result = re.search(regex, proxy)
if result is None:
print("Invalid Proxy Provided...")
return False
parts = result.groups()
if len(parts) < 2:
print("Invalid Proxy Provided...")
return False
if parts[0] not in ["http", "https"]:
print("Invalid Protocol Provided... Valid Protocols are http/https...")
return False
if parts[1] == " ":
print("Invalid Hostname Provided... It should be valid IP/FQDN...")
return False
return True
def prepare_proxy(url, username=None, password=None):
if username is None or len(username) == 0 or password is None or len(password) == 0:
return url
prefix = "https://" if url.startswith("https://") else "http://"
url = url.replace(prefix, "")
username = urllib.parse.quote_plus(username)
password = urllib.parse.quote_plus(password)
return f"{prefix}{username}:{password}@{url}"
def parse_proxy(url):
if url is None or len(url) == 0:
return None
url = urllib.parse.urlparse(url)
if url.scheme is None:
return f"{url.hostname}"
if url.port is None:
return f"{url.scheme}://{url.hostname}"
return f"{url.scheme}://{url.hostname}:{url.port}"
def set_ce_version_for_vm():
try:
from ce_as_vm_tags import BETA_OPT_IN, CORE_TAG, UI_TAG
AVAILABLE_INPUTS["CORE_TAG"] = CORE_TAG
AVAILABLE_INPUTS["UI_TAG"] = UI_TAG
if BETA_OPT_IN.lower() == "yes":
AVAILABLE_INPUTS["BETA_OPT_IN"] = "yes"
else:
AVAILABLE_INPUTS["BETA_OPT_IN"] = "No"
AVAILABLE_INPUTS["CORE_LATEST_VERSION_TAG"] = CORE_VERSION_1_LATEST_TAG
AVAILABLE_INPUTS["UI_LATEST_VERSION_TAG"] = UI_VERSION_1_LATEST_TAG
AVAILABLE_INPUTS["INSTALL_VERSION"] = CURRENT_VERSION
except Exception:
ask_for_ce_version()
def ask_for_ce_version():
while True:
current_version = ""
if AVAILABLE_INPUTS.get("BETA_OPT_IN", "No").lower() in ["yes", "y"]:
current_version = CE_VERSION_3
elif CORE_VERSION_1_TAG == AVAILABLE_INPUTS.get("CORE_TAG", "").strip():
current_version = CE_VERSION_1
elif CORE_VERSION_2_TAG == AVAILABLE_INPUTS.get("CORE_TAG", "").strip():
current_version = CE_VERSION_2
if current_version == "":
print(
f"\nAvailable Netskope CE Versions\n\t 1. {CE_VERSION_1} \n\t 2. {CE_VERSION_2} \n\t 3. {CE_VERSION_3}\n"
)
else:
print(
f"\nAvailable Netskope CE Versions (Current Version: {current_version})\n\t 1. {CE_VERSION_1} \n\t 2. {CE_VERSION_2} \n\t 3. {CE_VERSION_3}\n"
)
n = input("Select the version you want to install (1/2/3): ")
try:
n = int(n)
if n not in [1, 2, 3]:
print(f"{n} is not a valid selection.")
continue
break
except Exception as err:
print(err)
print(f"{n} is not a valid selection.")
continue
if n == 1:
AVAILABLE_INPUTS["CORE_TAG"] = CORE_VERSION_1_TAG
AVAILABLE_INPUTS["UI_TAG"] = UI_VERSION_1_TAG
AVAILABLE_INPUTS["BETA_OPT_IN"] = "No"
AVAILABLE_INPUTS["CORE_LATEST_VERSION_TAG"] = CORE_VERSION_1_LATEST_TAG
AVAILABLE_INPUTS["UI_LATEST_VERSION_TAG"] = UI_VERSION_1_LATEST_TAG
AVAILABLE_INPUTS["INSTALL_VERSION"] = CURRENT_VERSION
elif n == 2:
AVAILABLE_INPUTS["CORE_TAG"] = CORE_VERSION_2_TAG
AVAILABLE_INPUTS["UI_TAG"] = UI_VERSION_2_TAG
AVAILABLE_INPUTS["BETA_OPT_IN"] = "No"
AVAILABLE_INPUTS["CORE_LATEST_VERSION_TAG"] = CORE_VERSION_2_LATEST_TAG
AVAILABLE_INPUTS["UI_LATEST_VERSION_TAG"] = UI_VERSION_2_LATEST_TAG
AVAILABLE_INPUTS["INSTALL_VERSION"] = PREVIOUS_VERSION
elif n == 3:
AVAILABLE_INPUTS["CORE_TAG"] = CORE_VERSION_BETA_TAG
AVAILABLE_INPUTS["UI_TAG"] = UI_VERSION_BETA_TAG
AVAILABLE_INPUTS["BETA_OPT_IN"] = "yes"
AVAILABLE_INPUTS["CORE_LATEST_VERSION_TAG"] = CORE_VERSION_BETA_TAG
AVAILABLE_INPUTS["UI_LATEST_VERSION_TAG"] = UI_VERSION_BETA_TAG
AVAILABLE_INPUTS["INSTALL_VERSION"] = CURRENT_VERSION
def ask_for_initial_inputs():
isProxy = (
input("\n\nAre you using HTTP(s) proxy for outbound traffic? [y/n]\n> ")
.strip()
.lower()
)
if isProxy == "y" or isProxy == "yes":
# HTTPS_PROXY
cur_https_proxy = parse_proxy(AVAILABLE_INPUTS.get("CORE_HTTPS_PROXY", None))
print(
f"\nEnter Proxy URL (e.g. http(s)://10.0.0.0:3128) {('(Current: ' + cur_https_proxy + ')') if cur_https_proxy is not None else ''}"
)
https_proxy = input("> ").strip()
https_proxy_password = None
while not validate_proxy(https_proxy, cur_https_proxy):
print(
f"\nEnter Proxy URL (e.g. http(s)://10.0.0.0:3128) {('(Current: ' + cur_https_proxy + ')') if cur_https_proxy is not None else ''}"
)
https_proxy = input("> ").strip()
if https_proxy is None or len(https_proxy) == 0:
https_proxy = cur_https_proxy
https_proxy_username = input(
f"Enter proxy username (skip in case of unauthenticated proxy):\n> "
).strip()
if https_proxy_username is not None and len(https_proxy_username) > 0:
https_proxy_password = getpass("Enter proxy password: \n> ").strip()
while https_proxy_password == "":
print("Proxy password can not be empty... Please try again.\n")
https_proxy_password = getpass("Enter proxy password: \n> ").strip()
AVAILABLE_INPUTS["CORE_HTTPS_PROXY"] = prepare_proxy(
https_proxy,
username=https_proxy_username,
password=https_proxy_password,
)
AVAILABLE_INPUTS["CORE_HTTP_PROXY"] = AVAILABLE_INPUTS["CORE_HTTPS_PROXY"]
print(
"\n\033[1;37mNOTE: These proxy details will be reflected on the Settings > General > Proxy page on Netskope CE UI.\n\033[0;37m"
)
else:
AVAILABLE_INPUTS["CORE_HTTP_PROXY"] = ""
AVAILABLE_INPUTS["CORE_HTTPS_PROXY"] = ""
tenant_name = ""
while True:
tenant_name = input(
"\n> Please enter the Netskope Tenant Name (Exclude .goskope.com)\n(e.g. Enter 'demo' if Netskope Tenant URL is https://demo.goskope.com)\nPlease Enter 'test' if you do not have any Netskope tenant: "
).strip()
if tenant_name == "" or "goskope.com" in tenant_name:
print(
"Tenant name can not be empty. It should be without '.goskope.com'..."
)
else:
break
AVAILABLE_INPUTS["NETSKOPE_TENANT"] = tenant_name
class ClientExceptions(Exception):
pass
class ServerExceptions(Exception):
pass
def handle_http_errors(res):
status_code = res.code
if status_code == 200:
# raise ClientExceptions("Request Timeout Error.")
return
# Client Errors
elif status_code == 400:
raise ClientExceptions("Bad Request Error.")
elif status_code == 401:
raise ClientExceptions("Unauthorized Error.")
elif status_code == 403:
raise ClientExceptions("Forbidden Error.")
elif status_code == 404:
raise ClientExceptions("Not Found Error.")
elif status_code == 408:
raise ClientExceptions("Request Timeout Error.")
# Server Errors
elif status_code == 500:
raise ServerExceptions("Internal Server Error.")
elif status_code == 502:
raise ServerExceptions("Bad Gateway Error.")
elif status_code == 503:
raise ServerExceptions("Service Unavailable Error.")
elif status_code == 504:
raise ServerExceptions("Gateway Timeout Error.")
def connectivity_check_for_analytics():
try:
connectivity = True
print()
url = "https://reporting.netskope.tech/"
req = urllib.request.Request(url)
proxy = None
if AVAILABLE_INPUTS.get("CORE_HTTPS_PROXY", "") != "":
proxy = AVAILABLE_INPUTS.get("CORE_HTTPS_PROXY")
proxies = {}
if proxy is not None:
proxies["https"] = proxy
proxy_support = urllib.request.ProxyHandler(proxies=proxies)
opener = urllib.request.build_opener(proxy_support)
urllib.request.install_opener(opener)
urllib.request.urlopen(req, timeout=60)
except urllib.error.HTTPError as e:
if e.code not in [400, 401, 403]:
connectivity = False
print_warning(f"Error occurred while verifying connectivity to {url}: {e}")
except Exception as e:
connectivity = False
print_warning(f"Error occurred while verifying connectivity to {url}: {e}")
if not connectivity:
print_warning(
"Unable to establish a connection with https://reporting.netskope.tech/. "
"Verify the network connectivity, proxy settings or firewall configurations "
"to address the connectivity issues for enhanced product deployment and administration experience."
)
AVAILABLE_INPUTS["ANALYTICS_SERVER_CONNECTIVITY"] = connectivity
def handle_connectivity(name, url):
try:
req = urllib.request.Request(url)
proxy = None
if AVAILABLE_INPUTS.get("CORE_HTTPS_PROXY", "") != "":
proxy = AVAILABLE_INPUTS.get("CORE_HTTPS_PROXY")
proxies = {}
if proxy is not None:
proxies["https"] = proxy
proxy_support = urllib.request.ProxyHandler(proxies=proxies)
opener = urllib.request.build_opener(proxy_support)
urllib.request.install_opener(opener)
res = urllib.request.urlopen(req, timeout=60)
handle_http_errors(res)
CHECKS[name] = Status.PASS
print_pass(f"Connectivity to {url} verified successfully.")
except ClientExceptions as e:
print_fail(
f"Error occurred while verifying connectivity to {url}: ClientError {e}"
)
CHECKS[name] = Status.FAIL
raise
except ServerExceptions as e:
print_fail(
f"Error occurred while verifying connectivity to {url}: ServerError {e}"
)