forked from uc-cdis/gen3-code-vigil
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgen3_admin_tasks.py
953 lines (900 loc) · 32.8 KB
/
gen3_admin_tasks.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
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
import json
import os
import pytest
import requests
import subprocess
import time
import uuid
from dotenv import load_dotenv
from utils import logger
from utils.jenkins import JenkinsJob
from utils import TEST_DATA_PATH_OBJECT
load_dotenv()
def get_portal_config():
"""Fetch portal config from the GUI"""
if "heal" in pytest.tested_env:
res = requests.get(f"{pytest.root_url}/portal/data/config/gitops.json")
else:
res = requests.get(f"{pytest.root_url}/data/config/gitops.json")
if res.status_code == 200:
return res.json()
else:
raise Exception(
f"Unable to get portal config: status code {res.status_code} - response {res.text}"
)
def get_kube_namespace(hostname: str = ""):
"""
Compute the kubernetes namespace
"""
# Admin VM Deployments
if os.getenv("GEN3_INSTANCE_TYPE") == "ADMINVM_REMOTE":
return hostname.split(".")[0]
# Local Helm Deployments
elif os.getenv("GEN3_INSTANCE_TYPE") == "HELM_LOCAL":
# TODO: Set up the namespace in helm deployment and use it like below. For now just use hostname
# cmd = (
# "kubectl get configmap manifest-global -o json | jq -r '.data.environment'"
# )
# result = subprocess.run(cmd, stdout=subprocess.PIPE, shell=True)
# return result.stdout.decode("utf-8")
return hostname
def get_env_configurations(test_env_namespace: str = ""):
"""
Fetch configs that require adminvm interaction using jenkins.
Returns dict { file name: file contents }
"""
# Admin VM Deployments
if os.getenv("GEN3_INSTANCE_TYPE") == "ADMINVM_REMOTE":
assert test_env_namespace != ""
job = JenkinsJob(
os.getenv("JENKINS_URL"),
os.getenv("JENKINS_USERNAME"),
os.getenv("JENKINS_PASSWORD"),
"ci-only-fetch-configs",
)
params = {"NAMESPACE": test_env_namespace}
build_num = job.build_job(params)
if build_num:
status = job.wait_for_build_completion(build_num)
if status == "Completed":
return {
"manifest.json": job.get_artifact_content(
build_num, "manifest.json"
),
}
else:
job.terminate_build(build_num)
raise Exception("Build timed out. Consider increasing max_duration")
else:
raise Exception("Build number not found")
# Local Helm Deployments
elif os.getenv("GEN3_INSTANCE_TYPE") == "HELM_LOCAL":
cmd = ["kubectl", "get", "configmap", "manifest-global", "-o", "json"]
result = subprocess.run(
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
)
if result.returncode == 0:
jq_command = ["jq", "-r", ".data"]
jq_result = subprocess.run(
jq_command,
input=result.stdout,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
if jq_result.returncode == 0:
return {"manifest.json": '{ "global": ' + jq_result.stdout + "}"}
else:
logger.info(f"Error in jq command: {jq_result.stderr}")
else:
logger.info(f"Error in kubectl command: {result.stderr}")
def run_gen3_command(
command: str, test_env_namespace: str = "", roll_all: bool = False
):
"""
Run gen3 command (e.g., gen3 --help).
Since this requires adminvm interaction we use jenkins.
"""
# Admin VM Deployments
if os.getenv("GEN3_INSTANCE_TYPE") == "ADMINVM_REMOTE":
job = JenkinsJob(
os.getenv("JENKINS_URL"),
os.getenv("JENKINS_USERNAME"),
os.getenv("JENKINS_PASSWORD"),
"ci-only-run-gen3-command",
)
params = {
"NAMESPACE": test_env_namespace,
"COMMAND": command,
}
build_num = job.build_job(params)
if build_num:
status = job.wait_for_build_completion(build_num)
if status == "Completed":
return job.get_build_result(build_num)
else:
job.terminate_build(build_num)
raise Exception("Build timed out. Consider increasing max_duration")
else:
raise Exception("Build number not found")
# Local Helm Deployments
elif os.getenv("GEN3_INSTANCE_TYPE") == "HELM_LOCAL":
pass
def run_gen3_job(
job_name: str,
cmd_line_params: str = "",
test_env_namespace: str = "",
roll_all: bool = False,
):
"""
Run gen3 job (e.g., metadata-aggregate-sync).
Since this requires adminvm interaction we use jenkins.
"""
# Admin VM Deployments
if os.getenv("GEN3_INSTANCE_TYPE") == "ADMINVM_REMOTE":
job = JenkinsJob(
os.getenv("JENKINS_URL"),
os.getenv("JENKINS_USERNAME"),
os.getenv("JENKINS_PASSWORD"),
"ci-only-run-gen3-job",
)
params = {
"NAMESPACE": test_env_namespace,
"JOB_NAME": job_name,
"CMD_LINE_PARAMS": cmd_line_params,
"GEN3_ROLL_ALL": roll_all,
}
build_num = job.build_job(params)
if build_num:
status = job.wait_for_build_completion(build_num)
if status == "Completed":
return job.get_build_result(build_num)
else:
job.terminate_build(build_num)
raise Exception("Build timed out. Consider increasing max_duration")
else:
raise Exception("Build number not found")
# Local Helm Deployments
elif os.getenv("GEN3_INSTANCE_TYPE") == "HELM_LOCAL":
# job_pod = f"{job_name}-{uuid.uuid4()}"
if job_name == "etl":
job_name = "etl-cronjob"
cmd = ["kubectl", "delete", "job", job_name]
result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if not result.returncode == 0:
logger.info(
f"Unable to delete {job_name} - {result.stderr.decode('utf-8')}"
)
cmd = ["kubectl", "create", "job", f"--from=cronjob/{job_name}", job_name]
result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if result.returncode == 0:
logger.info(f"{job_name} job triggered - {result.stdout.decode('utf-8')}")
else:
raise Exception(
f"{job_name} failed to start - {result.stderr.decode('utf-8')}"
)
def fence_delete_expired_clients():
# Admin VM Deployments
if os.getenv("GEN3_INSTANCE_TYPE") == "ADMINVM_REMOTE":
run_gen3_job(
"fence-delete-expired-clients", test_env_namespace=pytest.namespace
)
job_logs = check_job_pod(
"fence-delete-expired-clients",
"gen3job",
test_env_namespace=pytest.namespace,
)
return job_logs["logs.txt"]
# Local Helm Deployments
elif os.getenv("GEN3_INSTANCE_TYPE") == "HELM_LOCAL":
# Delete expired clients
delete_explired_clients_cmd = "kubectl exec -i $(kubectl get pods -l app=fence -o jsonpath='{.items[0].metadata.name}') -- fence-create client-delete-expired"
delete_explired_client_result = subprocess.run(
delete_explired_clients_cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True,
text=True,
timeout=10,
)
if not delete_explired_client_result.returncode == 0:
raise Exception("Unable to delete expired clients.")
return delete_explired_client_result.stdout.strip()
def check_job_pod(
job_name: str,
label_name: str,
test_env_namespace: str = "",
expect_failure: bool = False,
):
# Admin VM Deployments
if os.getenv("GEN3_INSTANCE_TYPE") == "ADMINVM_REMOTE":
job = JenkinsJob(
os.getenv("JENKINS_URL"),
os.getenv("JENKINS_USERNAME"),
os.getenv("JENKINS_PASSWORD"),
"ci-only-check-kube-job-pod",
)
params = {
"NAMESPACE": test_env_namespace,
"JOB_NAME": job_name,
"LABEL_NAME": label_name,
"EXPECT_FAILURE": expect_failure,
}
build_num = job.build_job(params)
if build_num:
status = job.wait_for_build_completion(build_num)
if status == "Completed":
return {"logs.txt": job.get_artifact_content(build_num, "logs.txt")}
else:
job.terminate_build(build_num)
raise Exception("Build timed out. Consider increasing max_duration")
else:
raise Exception("Build number not found")
# Local Helm Deployments
elif os.getenv("GEN3_INSTANCE_TYPE") == "HELM_LOCAL":
# Wait for the job pod to start
cmd = [
"kubectl",
"get",
"pods",
f"--selector=job-name={job_name}",
"-o",
"jsonpath='{.items[0].status.phase}'",
]
i = 0
job_started = False
for i in range(6):
result = subprocess.run(
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
)
if result.stdout.replace("'", "") in [
"Running",
"Succeeded",
"Failed",
"Completed",
]:
job_started = True
break
else:
time.sleep(10)
if job_started is False:
raise Exception(f"Pod failed to start for job {job_name}")
# Wait for the job to complete
cmd = [
"kubectl",
"get",
"job",
job_name,
"-o",
"jsonpath='{.status.conditions[?(@.type==\"Complete\")].status}'",
]
job_completed = False
for i in range(40):
result = subprocess.run(
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
)
if result.stdout.replace("'", "") == "True":
job_completed = True
break
else:
time.sleep(30)
if job_completed is False:
raise Exception(f"Job {job_name} failed to complete in 20 minutes")
def setup_fence_test_clients(
clients_data: str,
test_env_namespace: str = "",
):
"""
Runs jenkins job to create a fence client
Since this requires adminvm interaction we use jenkins.
"""
clients_file_path = TEST_DATA_PATH_OBJECT / "fence_clients" / "clients_creds.txt"
rotated_clients_file_path = (
TEST_DATA_PATH_OBJECT / "fence_clients" / "client_rotate_creds.txt"
)
# Admin VM Deployments
if os.getenv("GEN3_INSTANCE_TYPE") == "ADMINVM_REMOTE":
job = JenkinsJob(
os.getenv("JENKINS_URL"),
os.getenv("JENKINS_USERNAME"),
os.getenv("JENKINS_PASSWORD"),
"ci-only-setup-fence-test-clients",
)
params = {
"NAMESPACE": test_env_namespace,
"CLIENTS_DATA": clients_data,
}
build_num = job.build_job(params)
if build_num:
status = job.wait_for_build_completion(build_num)
if status == "Completed":
with open(clients_file_path, "+a") as outfile:
outfile.write(
job.get_artifact_content(build_num, "clients_creds.txt")
)
with open(rotated_clients_file_path, "+a") as outfile:
outfile.write(
job.get_artifact_content(build_num, "client_rotate_creds.txt")
)
else:
raise Exception("Build number not found")
# Local Helm Deployments
elif os.getenv("GEN3_INSTANCE_TYPE") == "HELM_LOCAL":
hostname = os.getenv("HOSTNAME")
# Get the pod name for fence app
cmd = ["kubectl", "get", "pods", "-l", "app=fence"]
result = subprocess.run(
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
)
if result.returncode == 0:
fence_pod_name = result.stdout.splitlines()[-1].split()[0]
else:
raise Exception("Unable to retrieve fence-deployment pod")
# Create clients
for line in clients_data.split("\n")[1:]:
(
client_name,
username,
client_type,
arborist_policies,
expires_in,
scopes,
) = line.split(",")
logger.info(f"Creating Client: {client_name}")
# Delete existing client if it exists
delete_cmd = [
"kubectl",
"exec",
"-i",
fence_pod_name,
"--",
"fence-create",
"client-delete",
"--client",
client_name,
]
subprocess.run(
delete_cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
create_cmd = [
"kubectl",
"exec",
"-i",
fence_pod_name,
"--",
"fence-create",
]
if arborist_policies:
create_cmd = create_cmd + [
"client-create",
"--policies",
arborist_policies,
]
else:
create_cmd = create_cmd + ["client-create"]
if client_type == "client_credentials":
create_cmd = create_cmd + [
"--client",
client_name,
"--grant-types",
"client_credentials",
]
elif client_type == "implicit":
create_cmd = create_cmd + [
"--client",
client_name,
"--user",
username,
"--urls",
f"https://{hostname}",
"--grant-types",
"implicit",
"--public",
]
elif client_type == "auth_code":
create_cmd = create_cmd + [
"--client",
client_name,
"--user",
username,
"--urls",
f"https://{hostname}",
"--grant-types",
"authorization_code",
]
else:
create_cmd = create_cmd + [
"--client",
client_name,
"--user",
username,
"--urls",
f"https://{hostname}",
]
if expires_in:
create_cmd = create_cmd + ["--expires-in", expires_in]
if scopes:
create_cmd = create_cmd + ["--allowed-scopes"] + scopes.split(" ")
create_result = subprocess.run(
create_cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
timeout=10,
)
if result.returncode == 0:
client_info = create_result.stdout.strip().split("\n")[-1]
else:
raise Exception(
f"Unable to create client for {client_name}. Response: {create_result.stderr.strip()}"
)
with open(clients_file_path, "+a") as outfile:
outfile.write(f"{client_name}:{client_info}\n")
# Rotate Client
rotate_client_list = ["jenkins-client-tester"]
for client in rotate_client_list:
rotate_client_command = [
"kubectl",
"exec",
"-i",
fence_pod_name,
"--",
"fence-create",
"client-rotate",
"--client",
client,
]
rotate_result = subprocess.run(
rotate_client_command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
if rotate_result.returncode == 0:
client_info = rotate_result.stdout.strip().split("\n")[-1]
else:
raise Exception(
f"Unable to create client for {client}. Response: {rotate_result.stderr.strip()}"
)
with open(rotated_clients_file_path, "+a") as outfile:
outfile.write(f"{client}:{client_info}\n")
def delete_fence_client(clients_data: str, test_env_namespace: str = ""):
"""
Runs jenkins job to delete client
Since this requires adminvm interaction we use jenkins.
"""
# Admin VM Deployments
if os.getenv("GEN3_INSTANCE_TYPE") == "ADMINVM_REMOTE":
job = JenkinsJob(
os.getenv("JENKINS_URL"),
os.getenv("JENKINS_USERNAME"),
os.getenv("JENKINS_PASSWORD"),
"ci-only-fence-delete-client",
)
params = {
"NAMESPACE": test_env_namespace,
}
build_num = job.build_job(params)
if build_num:
status = job.wait_for_build_completion(build_num)
if status == "Completed":
return job.get_build_result(build_num)
else:
job.terminate_build(build_num)
raise Exception("Build timed out. Consider increasing max_duration")
else:
raise Exception("Build number not found")
# Local Helm Deployments
elif os.getenv("GEN3_INSTANCE_TYPE") == "HELM_LOCAL":
# Get the pod name for fence app
cmd = ["kubectl", "get", "pods", "-l", "app=fence"]
result = subprocess.run(
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
)
if result.returncode == 0:
fence_pod_name = result.stdout.splitlines()[-1].split()[0]
else:
raise Exception("Unable to retrieve fence-deployment pod")
# Delete clients
for line in clients_data.split("\n")[1:]:
client_name = line.split(",")[0]
logger.info(f"Deleting Client: {client_name}")
# Delete existing client if it exists
delete_cmd = [
"kubectl",
"exec",
"-i",
fence_pod_name,
"--",
"fence-create",
"client-delete",
"--client",
client_name,
]
subprocess.run(
delete_cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
def revoke_arborist_policy(username: str, policy: str, test_env_namespace: str = ""):
"""
Runs jenkins job to revoke arborist policy
Since jenkins job is faster way without too much configuration changes
"""
# Admin VM Deployments
if os.getenv("GEN3_INSTANCE_TYPE") == "ADMINVM_REMOTE":
job = JenkinsJob(
os.getenv("JENKINS_URL"),
os.getenv("JENKINS_USERNAME"),
os.getenv("JENKINS_PASSWORD"),
"ci-only-revoke-arborist-policy",
)
params = {
"NAMESPACE": test_env_namespace,
"USERNAME": username,
"POLICY": policy,
}
build_num = job.build_job(params)
if build_num:
status = job.wait_for_build_completion(build_num)
if status == "Completed":
return job.get_build_result(build_num)
else:
job.terminate_build(build_num)
raise Exception("Build timed out. Consider increasing max_duration")
else:
raise Exception("Build number not found")
# Local Helm Deployments
elif os.getenv("GEN3_INSTANCE_TYPE") == "HELM_LOCAL":
cmd = [
"kubectl",
"get",
"pods",
"-l",
"app=fence",
"-o",
"jsonpath='{.items[0].metadata.name}'",
]
result = subprocess.run(
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
)
if result.returncode == 0:
fence_pod_name = result.stdout.strip().replace("'", "")
else:
raise Exception("Unable to retrieve fence-deployment pod")
cmd = [
"kubectl",
"exec",
"-i",
fence_pod_name,
"--",
"curl",
"-X",
"DELETE",
f"arborist-service/user/{username}/policy/{policy}",
]
result = subprocess.run(
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
)
if not result.returncode == 0:
raise Exception("Unable to revoke arborist policy")
def update_audit_service_logging(audit_logging: str, test_env_namespace: str = ""):
"""
Runs jenkins job to enable/disable audit logging
"""
# Admin VM Deployments
if os.getenv("GEN3_INSTANCE_TYPE") == "ADMINVM_REMOTE":
job = JenkinsJob(
os.getenv("JENKINS_URL"),
os.getenv("JENKINS_USERNAME"),
os.getenv("JENKINS_PASSWORD"),
"ci-only-audit-service-logging",
)
params = {
"AUDIT_LOGGING": audit_logging,
"NAMESPACE": test_env_namespace,
}
build_num = job.build_job(params)
if build_num:
status = job.wait_for_build_completion(build_num)
if status == "Completed":
return True
else:
job.terminate_build(build_num)
raise Exception("Build timed out. Consider increasing max_duration")
else:
raise Exception("Build number not found")
# Local Helm Deployments
elif os.getenv("GEN3_INSTANCE_TYPE") == "HELM_LOCAL":
pass
def mutate_manifest_for_guppy_test(test_env_namespace: str = ""):
"""
Runs jenkins job to point guppy to pre-defined Canine ETL'ed data
"""
# Admin VM Deployments
if os.getenv("GEN3_INSTANCE_TYPE") == "ADMINVM_REMOTE":
job = JenkinsJob(
os.getenv("JENKINS_URL"),
os.getenv("JENKINS_USERNAME"),
os.getenv("JENKINS_PASSWORD"),
"ci-only-mutate-manifest-for-guppy-test",
)
params = {
"NAMESPACE": test_env_namespace,
}
build_num = job.build_job(params)
if build_num:
status = job.wait_for_build_completion(build_num)
if status == "Completed":
return True
else:
job.terminate_build(build_num)
raise Exception("Build timed out. Consider increasing max_duration")
else:
raise Exception("Build number not found")
# Local Helm Deployments
elif os.getenv("GEN3_INSTANCE_TYPE") == "HELM_LOCAL":
pass
def clean_up_indices(test_env_namespace: str = ""):
"""
Runs jenkins job to clean up indices before running the ETL tests
"""
# Admin VM Deployments
if os.getenv("GEN3_INSTANCE_TYPE") == "ADMINVM_REMOTE":
job = JenkinsJob(
os.getenv("JENKINS_URL"),
os.getenv("JENKINS_USERNAME"),
os.getenv("JENKINS_PASSWORD"),
"ci-only-clean-up-indices",
)
params = {"NAMESPACE": test_env_namespace}
build_num = job.build_job(params)
if build_num:
status = job.wait_for_build_completion(build_num, max_duration=300)
if status == "Completed":
return True
else:
job.terminate_build(build_num)
raise Exception("Build timed out. Consider increasing max_duration")
else:
raise Exception("Build number not found")
# Local Helm Deployments
elif os.getenv("GEN3_INSTANCE_TYPE") == "HELM_LOCAL":
pass
def check_indices_after_etl(test_env_namespace: str):
"""
Runs jenkins job to clean up indices before running the ETL tests
"""
# Admin VM Deployments
if os.getenv("GEN3_INSTANCE_TYPE") == "ADMINVM_REMOTE":
job = JenkinsJob(
os.getenv("JENKINS_URL"),
os.getenv("JENKINS_USERNAME"),
os.getenv("JENKINS_PASSWORD"),
"ci-only-check_indices_after_etl",
)
params = {"NAMESPACE": test_env_namespace}
build_num = job.build_job(params)
if build_num:
status = job.wait_for_build_completion(build_num, max_duration=300)
if status == "Completed":
return True
else:
job.terminate_build(build_num)
raise Exception("Build timed out. Consider increasing max_duration")
else:
raise Exception("Build number not found")
# Local Helm Deployments
elif os.getenv("GEN3_INSTANCE_TYPE") == "HELM_LOCAL":
get_alias_cmd = "kubectl get cm etl-mapping -o jsonpath='{.data.etlMapping\\.yaml}' | yq '.mappings[].name' | xargs"
get_alias_result = subprocess.run(
get_alias_cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True,
text=True,
)
if not get_alias_result.returncode == 0:
raise Exception(
f"Unable to get alias. Error: {get_alias_result.stderr.strip()}"
)
for alias_name in get_alias_result.stdout.strip().split(" "):
get_alias_status_cmd = [
"curl",
"-I",
"-s",
f"localhost:9200/_alias/{alias_name}",
]
get_alias_status_result = subprocess.run(
get_alias_status_cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
if not get_alias_status_result.returncode == 0:
raise Exception(
f"Unable to get status code for {alias_name}. Error: {get_alias_status_result.stderr.strip()}"
)
assert (
"200 OK" in get_alias_status_result.stdout.strip()
), f"Expected 200 OK but got {get_alias_status_result.stdout.strip()} for {alias_name}"
logger.info(f"{alias_name} is present")
get_indices_name_cmd = [
"curl",
"-X",
"GET",
"-s",
f"localhost:9200/_alias/{alias_name}",
]
get_indices_name_result = subprocess.run(
get_indices_name_cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
if not get_indices_name_result.returncode == 0:
raise Exception(
f"Unable to get status code for {alias_name}. Error: {get_indices_name_result.stderr.strip()}"
)
data = json.loads(get_indices_name_result.stdout.strip())
indices_name = list(data.keys())[0]
version = indices_name.split("_")[-1]
if version == "1":
logger.info(f"Index version has increased for {alias_name}")
def create_access_token(service, expired, username, test_env_namespace: str = ""):
"""
Roll a give service pod
"""
# Admin VM Deployments
if os.getenv("GEN3_INSTANCE_TYPE") == "ADMINVM_REMOTE":
job = JenkinsJob(
os.getenv("JENKINS_URL"),
os.getenv("JENKINS_USERNAME"),
os.getenv("JENKINS_PASSWORD"),
"ci-only-create-access-token",
)
if expired:
expiration = 1
else:
expiration = 300 # 5 min
params = {
"SERVICE": service,
"EXPIRATION": expiration,
"USERNAME": username,
"NAMESPACE": test_env_namespace,
}
build_num = job.build_job(params)
if build_num:
status = job.wait_for_build_completion(build_num, max_duration=300)
if status == "Completed":
if expired:
time.sleep(expiration)
return job.get_artifact_content(build_num, "access_token.txt")
else:
job.terminate_build(build_num)
raise Exception("Build timed out. Consider increasing max_duration")
else:
raise Exception("Build number not found")
# Local Helm Deployments
elif os.getenv("GEN3_INSTANCE_TYPE") == "HELM_LOCAL":
# Get the pod name for fence app
cmd = ["kubectl", "get", "pods", "-l", "app=fence"]
result = subprocess.run(
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
)
if result.returncode == 0:
fence_pod_name = result.stdout.splitlines()[-1].split()[0]
else:
raise Exception("Unable to retrieve fence-deployment pod")
cmd = [
"kubectl",
"exec",
"-i",
fence_pod_name,
"--",
"fence-create",
"token-create",
"--scopes",
"openid,user,fence,data,credentials,google_service_account,google_credentials",
"--type",
"access_token",
"--exp",
expired,
"--username",
username,
]
result = subprocess.run(
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
)
if result.returncode == 0:
return result.stdout.strip()
else:
raise Exception("Unable to get expired access_token")
def create_link_google_test_buckets(test_env_namespace: str = ""):
"""
Runs jenkins job to execute command for creating and linking Google test buckets
"""
# Admin VM Deployments
if os.getenv("GEN3_INSTANCE_TYPE") == "ADMINVM_REMOTE":
job = JenkinsJob(
os.getenv("JENKINS_URL"),
os.getenv("JENKINS_USERNAME"),
os.getenv("JENKINS_PASSWORD"),
"ci-only-create-link-google-test-buckets",
)
params = {
"NAMESPACE": test_env_namespace,
}
build_num = job.build_job(params)
if build_num:
status = job.wait_for_build_completion(build_num)
if status == "Completed":
return True
else:
job.terminate_build(build_num)
raise Exception("Build timed out. Consider increasing max_duration")
else:
raise Exception("Build number not found")
# Local Helm Deployments
elif os.getenv("GEN3_INSTANCE_TYPE") == "HELM_LOCAL":
pass
def fence_enable_register_users_redirect(test_env_namespace: str = ""):
"""
Runs jenkins job to setup register user redirect on login
"""
# Admin VM Deployments
if os.getenv("GEN3_INSTANCE_TYPE") == "ADMINVM_REMOTE":
job = JenkinsJob(
os.getenv("JENKINS_URL"),
os.getenv("JENKINS_USERNAME"),
os.getenv("JENKINS_PASSWORD"),
"ci-only-fence-enable-user-register-redirect",
)
params = {
"NAMESPACE": test_env_namespace,
}
build_num = job.build_job(params)
if build_num:
status = job.wait_for_build_completion(build_num)
if status == "Completed":
return True
else:
job.terminate_build(build_num)
raise Exception("Build timed out. Consider increasing max_duration")
else:
raise Exception("Build number not found")
# Local Helm Deployments
elif os.getenv("GEN3_INSTANCE_TYPE") == "HELM_LOCAL":
pass
def fence_disable_register_users_redirect(test_env_namespace: str = ""):
"""
Runs jenkins job to disable register user redirect on login
"""
# Admin VM Deployments
if os.getenv("GEN3_INSTANCE_TYPE") == "ADMINVM_REMOTE":
job = JenkinsJob(
os.getenv("JENKINS_URL"),
os.getenv("JENKINS_USERNAME"),
os.getenv("JENKINS_PASSWORD"),
"ci-only-fence-disable-user-register-redirect",
)
params = {
"NAMESPACE": test_env_namespace,
}
build_num = job.build_job(params)
if build_num:
status = job.wait_for_build_completion(build_num)
if status == "Completed":
return True
else:
job.terminate_build(build_num)
raise Exception("Build timed out. Consider increasing max_duration")
else:
raise Exception("Build number not found")
# Local Helm Deployments
elif os.getenv("GEN3_INSTANCE_TYPE") == "HELM_LOCAL":
pass