forked from hpe-storage/hpe3par_test_automation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhpe_3par_kubernetes_manager.py
2867 lines (2520 loc) · 121 KB
/
hpe_3par_kubernetes_manager.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
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
import pytest
import yaml
from kubernetes import client, config
from time import sleep
from hpe3parclient.client import HPE3ParClient
from kubernetes.stream import stream
import paramiko
import os
import json
from hpe3parclient.exceptions import HTTPNotFound
import base64
import datetime
import logging
import globals
import inspect
config.load_kube_config()
k8s_storage_v1 = client.StorageV1Api()
k8s_core_v1 = client.CoreV1Api()
k8s_extn_apps_v1 = client.ExtensionsV1beta1Api()
k8s_api_extn_v1 = client.ApiextensionsV1beta1Api()
k8s_rbac_auth_v1 = client.RbacAuthorizationV1Api()
k8s_apps_v1 = client.AppsV1Api()
timeout = 180
def hpe_create_sc_object(yml):
try:
resp = k8s_storage_v1.create_storage_class(body=yml)
logging.getLogger().debug("Storage Class created. status=%s" % resp.metadata.name)
# print("Storage Class created. status=%s" % resp.metadata.name)
return resp
except client.rest.ApiException as e:
#print("Exception :: %s" % e)
logging.getLogger().error("Exception :: %s" % e)
#logging.error("Exception :: %s" % e)
raise e
def hpe_create_secret_object(yml):
try:
#namespace = "default"
namespace = globals.namespace
if 'namespace' in yml.get('metadata'):
namespace = yml.get('metadata')['namespace']
resp = obj = k8s_core_v1.create_namespaced_secret(namespace=namespace, body=yml)
# print("Secret %s created" % resp.metadata.name)
logging.getLogger().debug("Secret %s created" % resp.metadata.name)
return resp
except client.rest.ApiException as e:
#print("Exception while creating secret:: %s" % e)
logging.getLogger().error("Exception while creating secret:: %s" % e)
#logging.error("Exception while creating secret:: %s" % e)
raise e
def hpe_create_pvc_object(yml):
try:
#namespace = "default" # kept namespace default else snapshot crd fails to find pvc
namespace = globals.namespace
if 'namespace' in yml.get('metadata'):
namespace = yml.get('metadata')['namespace']
pvc = k8s_core_v1.create_namespaced_persistent_volume_claim(namespace=namespace, body=yml)
# print("PVC created. status=%s" % pvc.status.phase)
return pvc
except client.rest.ApiException as e:
#print("Exception :: %s" % e)
logging.getLogger().error("Exception while creating pvc :: %s" % e)
raise e
def hpe_create_pod_object(yml):
try:
#namespace = "default"
namespace = globals.namespace
if 'namespace' in yml.get('metadata'):
namespace = yml.get('metadata')['namespace']
pod = k8s_core_v1.create_namespaced_pod(namespace=namespace, body=yml)
return pod
except client.rest.ApiException as e:
#print("Exception :: %s" % e)
logging.getLogger().error("Exception while creating pod :: %s" % e)
raise e
def hpe_connect_pod_container(name, command):
try:
namespace = globals.namespace
api_response = stream(k8s_core_v1.connect_get_namespaced_pod_exec, name=name,namespace=namespace,command=command, stderr=True, stdin=False, stdout=True, tty=False)
return api_response
except client.rest.ApiException as e:
logging.getLogger().error("Exception while connecting to pod :: %s" % e)
raise e
def hpe_create_dep_object(yml):
try:
#namespace = "default"
namespace = globals.namespace
if 'namespace' in yml.get('metadata'):
namespace = yml.get('metadata')['namespace']
dep = k8s_apps_v1.create_namespaced_deployment(namespace=namespace, body=yml)
return dep
except client.rest.ApiException as e:
#print("Exception :: %s" % e)
logging.getLogger().error("Exception while creating deployment:: %s" % e)
raise e
def hpe_delete_dep_object(name, namespace):
try:
dep = k8s_apps_v1.delete_namespaced_deployment(name, namespace=namespace)
# print("PVC created. status=%s" % pvc.status.phase)
logging.getLogger().debug("Deployment %s deleted" % name)
return dep
except client.rest.ApiException as e:
#print("Exception :: %s" % e)
logging.getLogger().error("Exception while deleting deployment :: %s" % e)
raise e
def hpe_get_dep_object(name, namespace):
dep = None
try:
dep = k8s_apps_v1.read_namespaced_deployment(name, namespace=namespace)
# print("PVC created. status=%s" % pvc.status.phase)
logging.getLogger().debug("Get deployment %s" % name)
except client.rest.ApiException as e:
#print("Exception :: %s" % e)
logging.getLogger().error("Exception in get deployment:: %s" % e)
raise e
finally:
return dep
def hpe_read_pvc_object(pvc_name, namespace):
try:
pvc = k8s_core_v1.read_namespaced_persistent_volume_claim(pvc_name, namespace=namespace)
return pvc
except client.rest.ApiException as e:
#print("Exception :: %s" % e)
logging.getLogger().error("Exception :: %s" % e)
raise e
def hpe_delete_pvc_object_by_name(pvc_name):
try:
namespace = globals.namespace
pvc = k8s_core_v1.delete_namespaced_persistent_volume_claim(pvc_name, namespace=namespace)
except client.rest.ApiException as e:
#print("Exception while deleting pvc:: %s" % e)
logging.getLogger().error("Exception :: %s" % e)
raise e
def hpe_delete_secret_object_by_name(secret_name, namespace):
try:
secret = k8s_core_v1.delete_namespaced_secret(secret_name, namespace=namespace)
except client.rest.ApiException as e:
#print("Exception while deleting secret:: %s" % e)
logging.getLogger().error("Exception :: %s" % e)
raise e
def hpe_get_secret_object_by_name(secret_name, namespace, raise_error=False):
secret = None
try:
secret = k8s_core_v1.read_namespaced_secret(secret_name, namespace=namespace)
except client.rest.ApiException as e:
if raise_error:
#print("Exception while getting secret:: %s" % e)
logging.getLogger().error("Exception while getting secret:: %s" % e)
raise e
return secret
def hpe_delete_sc_object_by_name(sc_name):
try:
pvc = k8s_storage_v1.delete_storage_class(sc_name)
except client.rest.ApiException as e:
#print("Exception while deleting sc:: %s" % e)
logging.getLogger().error("Exception while deleting sc:: %s" % e)
raise e
def hpe_delete_pod_object_by_name(pod_name, namespace):
try:
pvc = k8s_core_v1.delete_namespaced_pod(pod_name, namespace=namespace)
except client.rest.ApiException as e:
#print("Exception while deleting sc:: %s" % e)
logging.getLogger().error("Exception while deleting pod:: %s" % e)
raise e
def hpe_list_pvc_objects(namespace):
try:
pvc_list = k8s_core_v1.list_namespaced_persistent_volume_claim(namespace=namespace)
return pvc_list
except client.rest.ApiException as e:
#print("Exception :: %s" % e)
logging.getLogger().error("Exception :: %s" % e)
raise e
def hpe_list_pvc_objects_names(namespace):
try:
pvc_names = []
pvc_list = hpe_list_pvc_objects(namespace)
for pvc in pvc_list.items:
pvc_names.append(pvc.metadata.name)
return pvc_names
except client.rest.ApiException as e:
#print("Exception :: %s" % e)
logging.getLogger().error("Exception :: %s" % e)
raise e
def hpe_list_deployment_objects(namespace):
try:
dep_list = k8s_apps_v1.list_namespaced_deployment(namespace=namespace)
return dep_list
except client.rest.ApiException as e:
#print("Exception :: %s" % e)
logging.getLogger().error("Exception :: %s" % e)
raise e
def hpe_list_deployment_objects_names(namespace):
try:
dep_names = []
dep_list = hpe_list_deployment_objects(namespace)
for dep in dep_list.items:
dep_names.append(dep.metadata.name)
return dep_names
except client.rest.ApiException as e:
#print("Exception :: %s" % e)
logging.getLogger().error("Exception :: %s" % e)
raise e
def hpe_list_statefulset_objects(namespace):
try:
set_list = k8s_apps_v1.list_namespaced_stateful_set(namespace=namespace)
return set_list
except client.rest.ApiException as e:
logging.getLogger().error("Exception :: %s" % e)
raise e
def hpe_list_statefulset_objects_names(namespace):
try:
set_names = []
set_list = hpe_list_statefulset_objects(namespace)
for set in set_list.items:
set_names.append(set.metadata.name)
return set_names
except client.rest.ApiException as e:
logging.getLogger().error("Exception :: %s" % e)
raise e
def hpe_list_sc_objects():
try:
sc_list = k8s_storage_v1.list_storage_class()
return sc_list
except client.rest.ApiException as e:
#print("Exception :: %s" % e)
logging.getLogger().error("Exception :: %s" % e)
raise e
def hpe_list_sc_objects_names():
try:
sc_names = []
sc_list = hpe_list_sc_objects()
for sc in sc_list.items:
sc_names.append(sc.metadata.name)
return sc_names
except client.rest.ApiException as e:
#print("Exception :: %s" % e)
logging.getLogger().error("Exception :: %s" % e)
raise e
def hpe_list_secret_objects(namespace):
try:
secret_list = k8s_core_v1.list_namespaced_secret(namespace=namespace)
return secret_list
except client.rest.ApiException as e:
#print("Exception :: %s" % e)
logging.getLogger().error("Exception :: %s" % e)
raise e
def hpe_list_secret_objects_names(namespace):
try:
secret_names = []
secret_list = hpe_list_secret_objects(namespace=namespace)
for secret in secret_list.items:
secret_names.append(secret.metadata.name)
return secret_names
except client.rest.ApiException as e:
#print("Exception :: %s" % e)
logging.getLogger().error("Exception :: %s" % e)
raise e
def hpe_list_pod_objects(namespace, **kwargs):
try:
# print("kwargs :: keys :: %s,\n values :: %s" % (kwargs.keys(), kwargs.values()))
# print("value :: %s " % kwargs['label'])
# pod_list = k8s_core_v1.list_namespaced_pod(namespace=namespace, label_selector=kwargs['label'])
pod_list = k8s_core_v1.list_namespaced_pod(namespace=namespace)
return pod_list
except client.rest.ApiException as e:
#print("Exception :: %s" % e)
logging.getLogger().error("Exception :: %s" % e)
raise e
def hpe_list_pod_objects_names(namespace):
try:
pod_names = []
pod_list = hpe_list_pod_objects(namespace=namespace)
#print("=============== Listing all pods in default namespace::START")
for pod in pod_list.items:
pod_names.append(pod.metadata.name)
#print("########### %s " %pod)
#print("=============== Listing all pods in default namespace::END")
return pod_names
except client.rest.ApiException as e:
#print("Exception :: %s" % e)
logging.getLogger().error("Exception :: %s" % e)
raise e
def hpe_list_node_objects():
try:
node_list = k8s_core_v1.list_node()
return node_list
except client.rest.ApiException as e:
#print("Exception :: %s" % e)
logging.getLogger().error("Exception :: %s" % e)
raise e
def check_if_deleted(timeout, name, kind, namespace):
time = 0
flag = True
# print("timeout :: %s" % timeout)
# print("name :: %s" % name)
# print("kind :: %s" % kind)
while True:
if kind == 'PVC':
obj_list = hpe_list_pvc_objects_names(namespace=namespace)
elif kind == 'SC':
obj_list = hpe_list_sc_objects_names()
elif kind == 'Secret':
obj_list = hpe_list_secret_objects_names(namespace=namespace)
elif kind == 'Pod':
obj_list = hpe_list_pod_objects_names(namespace=namespace)
elif kind == 'Crd':
obj_list = hpe_list_crds()
elif kind == 'Deploy':
obj_list = hpe_list_deployment_objects_names(namespace=namespace)
elif kind == 'StatefulSet':
obj_list = hpe_list_statefulset_objects_names(namespace=namespace)
else:
#print("Not a supported kind")
logging.getLogger().info("Not a supported kind")
flag = False
break
# print(obj_list)
print(".", end='', flush=True)
if name not in obj_list:
break
if int(time) > int(timeout):
caller_fun = inspect.stack()[2][3]
logging.getLogger().info("caller_fun :: %s" % caller_fun)
if caller_fun != 'cleanup':
#print("\n%s not yet deleted. Taking longer than expected..." % kind)
logging.getLogger().info("%s %s not yet deleted. Taking longer than expected..." % (kind, name))
flag = False
break
time += 1
sleep(1)
return flag
def read_array_prop(yml):
try:
HPE3PAR_IP = None
HPE3PAR_USERNAME = None
HPE3PAR_PWD = None
#PROTOCOL = None
with open(yml) as f:
elements = list(yaml.safe_load_all(f))
print(elements)
logging.getLogger().debug(elements)
for el in elements:
logging.getLogger().debug(el)
logging.getLogger().debug("======== kind :: %s " % str(el.get('kind')))
#print(el)
#print("======== kind :: %s " % str(el.get('kind')))
if str(el.get('kind')) == "Secret":
HPE3PAR_IP = el['stringData']['backend']
HPE3PAR_USERNAME = el['stringData']['username']
HPE3PAR_PWD = el['data']['password']
"""if str(el.get('kind')) == "StorageClass":
PROTOCOL = el['parameters']['accessProtocol']
# remoteCopyGroup = el['parameters']['remoteCopyGroup']"""
#print("HPE3PAR_IP :: %s, HPE3PAR_USERNAME :: %s, HPE3PAR_PWD :: %s" % (HPE3PAR_IP, HPE3PAR_USERNAME, HPE3PAR_PWD))
return HPE3PAR_IP, HPE3PAR_USERNAME, HPE3PAR_PWD#, PROTOCOL
except Exception as e:
#print("Exception while verifying on 3par :: %s" % e)
logging.getLogger().error("Exception while verifying on 3par :: %s" % e)
raise e
def read_protocol(yml):
try:
PROTOCOL = None
with open(yml) as f:
elements = list(yaml.safe_load_all(f))
#print(elements)
logging.getLogger().debug(elements)
for el in elements:
#print(el)
#print("======== kind :: %s " % str(el.get('kind')))
logging.getLogger().debug(el)
logging.getLogger().debug("======== kind :: %s " % str(el.get('kind')))
if str(el.get('kind')) == "StorageClass":
PROTOCOL = el['parameters']['accessProtocol']
# remoteCopyGroup = el['parameters']['remoteCopyGroup']
#print("HPE3PAR_IP :: %s, HPE3PAR_USERNAME :: %s, HPE3PAR_PWD :: %s" % (HPE3PAR_IP, HPE3PAR_USERNAME, HPE3PAR_PWD))
return PROTOCOL
except Exception as e:
#print("Exception while verifying on 3par :: %s" % e)
logging.getLogger().error("Exception while verifying on 3par :: %s" % e)
raise e
def _hpe_get_3par_client_login(HPE3PAR_API_URL, HPE3PAR_IP, HPE3PAR_USERNAME, HPE3PAR_PWD):
# Login to 3Par array and initialize connection for WSAPI calls
hpe_3par_cli = HPE3ParClient(HPE3PAR_API_URL, False, False, None, True)
hpe_3par_cli.login(HPE3PAR_USERNAME, HPE3PAR_PWD)
hpe_3par_cli.setSSHOptions(HPE3PAR_IP, HPE3PAR_USERNAME, HPE3PAR_PWD)
return hpe_3par_cli
def check_event(kind, name):
try:
event_list = k8s_core_v1.list_event_for_all_namespaces()
status = None
message = None
if kind == 'pvc':
k8s_kind = 'PersistentVolumeClaim'
completion_status = ['ProvisioningSucceeded', 'ProvisioningFailed']
if kind == 'pod':
k8s_kind = 'Pod'
completion_status = ['SucceededMount', 'FailedMount', 'FailedScheduling', 'Mount']
for event in event_list.items:
if event.involved_object.kind == k8s_kind and event.involved_object.name == name:
if event.reason in completion_status:
status = event.reason
message = event.message
break
return status, message
except Exception as e:
#print("Exception while fetching events for %s,%s :: %s" % (kind, name, e))
logging.getLogger().error("Exception while fetching events for %s,%s :: %s" % (kind, name, e))
raise e
def check_status(timeout_set, name, kind, status, namespace):
time = 0
flag = True
logging.getLogger().info("timeout_set :: %s" % timeout_set)
logging.getLogger().info("name :: %s" % name)
logging.getLogger().info("kind :: %s" % kind)
logging.getLogger().info("status :: %s" % status)
logging.getLogger().info("namespace :: %s" % namespace)
if timeout_set is None or timeout_set <= 0:
timeout_set = 300
if kind == 'deployment':
logging.getLogger().info("Checking if deployment %s has created pods..." % name)
elif kind == 'StatefulSet':
logging.getLogger().info("Checking if StatefulSet %s has all replicas ready..." % name)
else:
logging.getLogger().info("Checking for %s %s to come in %s state..." % (kind, name, status))
while True:
obj = ""
if kind == 'pv':
obj = k8s_core_v1.read_persistent_volume(name)
elif kind == 'pvc':
obj = k8s_core_v1.read_namespaced_persistent_volume_claim(name, namespace)
elif kind == 'pod':
obj = k8s_core_v1.read_namespaced_pod(name, namespace)
elif kind == 'deployment':
obj = k8s_apps_v1.read_namespaced_deployment(name, namespace)
#print(obj)
logging.getLogger().debug(obj)
elif kind == 'StatefulSet':
obj = k8s_apps_v1.read_namespaced_stateful_set(name, namespace)
else:
#print("\nNot a supported kind")
logging.getLogger().info("Not a supported kind")
flag = False
break
# print("obj.status.phase :: %s" % obj.status.phase)
print(".", end='', flush=True)
if kind == 'deployment':
replica_total = 0
replica_avail = 0
if obj.status.replicas is not None:
replica_total = obj.status.replicas
if obj.status.available_replicas is not None:
replica_avail = obj.status.available_replicas
if replica_total == replica_avail and replica_total > 0:
break
elif kind == 'StatefulSet':
replica_total = 0
replica_current = 0
if obj.status.replicas is not None:
replica_total = obj.status.replicas
if obj.status.current_replicas is not None:
replica_current = obj.status.current_replicas
if replica_total == replica_current and replica_total > 0:
break
else:
if obj.status.phase == status:
break
if int(time) > int(timeout_set):
if kind == 'deployment' or kind == 'StatefulSet':
#print("\nDeployment %s check failed. Taking longer than expected..." % name)
logging.getLogger().info("%s %s check failed. Taking longer than expected..." % (kind, name))
else:
#print("\n%s not yet in %s state. Taking longer than expected..." % (kind, status))
logging.getLogger().info("%s not yet in %s state. Taking longer than expected..." % (kind, status))
# print("obj :: %s" % obj)
logging.getLogger().debug("obj :: %s" % obj)
flag = False
break
time += 1
sleep(1)
if flag is True:
if kind == 'deployment' or kind == 'StatefulSet':
#print("\nDeployment %s check done, took %s" % (name, str(datetime.timedelta(0, time))))
#logging.getLogger().info("Deployment %s check done, took %s" % (name, str(datetime.timedelta(0, time))))
logging.getLogger().info("%s %s check done, took %s" % (kind, name, str(datetime.timedelta(0, time))))
else:
print("\n%s has come to %s state!!! It took %s seconds" % (kind, status, str(datetime.timedelta(0, time))))
logging.getLogger().info("%s has come to %s state!!! It took %s seconds" % (kind, status, str(datetime.timedelta(0, time))))
return flag, obj
def hpe_get_pod(pod_name, namespace):
try:
return k8s_core_v1.read_namespaced_pod(pod_name,namespace=namespace)
except Exception as e:
#print("Exception :: %s" % e)
logging.getLogger().error("Exception :: %s" % e)
raise e
def get_host_from_array(hpe3par_cli, host_name):
try:
logging.getLogger().info("\nFetching host details from array for %s " % host_name)
hpe3par_host = globals.hpe3par_cli.getHost(host_name)
logging.getLogger().info("Host details from array :: %s " % hpe3par_host)
return hpe3par_host
except Exception as e:
logging.getLogger().error("Exception %s while fetching host details from array for %s " % (e, host_name))
def verify_host_properties(hpe3par_host, **kwargs):
logging.getLogger().info("In verify_host_properties()")
encoding = "latin-1"
logging.getLogger().info("kwargs[chapUser] :: %s " % kwargs['chapUser'])
logging.getLogger().info("kwargs[chapPwd] :: %s " % kwargs['chapPassword'])
try:
if 'chapUser' in kwargs:
if hpe3par_host['initiatorChapEnabled'] == True:
if hpe3par_host['initiatorChapName'] == kwargs['chapUser'] and (base64.b64decode(hpe3par_host['initiatorEncryptedChapSecret'])).decode(encoding) == kwargs['chapPassword']:
return True
else:
return False
return True
except Exception as e:
logging.getLogger().error("Exception while verifying host properties %s " % e)
def get_command_output(node_name, command, password=None):
try:
logging.getLogger().info("Executing command...")
ssh_client = paramiko.SSHClient()
# print("ssh client %s " % ssh_client)
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# print("host key set")
logging.getLogger().info("node_name = %s, command = %s " % (node_name, command))
if globals.platform == 'os':
if password is not None:
ssh_client.connect(hostname=node_name, username='core', password=password)
else:
ssh_client.connect(hostname=node_name, username='core')
else:
if password is not None:
ssh_client.connect(hostname=node_name, password=password)
else:
ssh_client.connect(hostname=node_name)
# ssh_client.connect(node_name, username='vagrant', password='vagrant', key_filename='/home/vagrant/.ssh/id_rsa')
# ssh_client.connect(node_name, username='vagrant', password='vagrant', look_for_keys=False, allow_agent=False)
logging.getLogger().info("connected...")
# execute command and get output
stdin,stdout,stderr=ssh_client.exec_command(command)
logging.getLogger().info("stderr :: %s" % stderr.read())
#logging.getLogger().info("stdout :: %s " % stdout.read())
command_output = []
while True:
line = stdout.readline()
if not line:
break
command_output.append(str(line).strip())
#print(line)
logging.getLogger().debug(line)
# command_output = stdout.read()
# print("stdin :: " % stdin.readlines())
# print("stderr :: %s" % stderr.read())
ssh_client.close()
return command_output
except Exception as e:
logging.getLogger().error("Exception while ssh %s " % e)
def get_command_output_string(command):
try:
#logging.getLogger().info(command)
stream = os.popen(command)
#logging.getLogger().info(stream)
output = stream.read()
#logging.getLogger().info(output)
return output
except Exception as e:
#print("Exception while executing command %s " % e)
logging.getLogger().error("Exception while executing command %s " % e)
def hpe_list_crds():
try:
crd_names = []
crd_list = k8s_api_extn_v1.list_custom_resource_definition()
for crd in crd_list.items:
crd_names.append(crd.metadata.name)
return crd_names
except Exception as e:
#print("Exception while listing crd(s) %s " % e)
logging.getLogger().error("Exception while listing crd(s) %s " % e)
def get_node_crd(node_name):
try:
logging.getLogger().info("\nReading CRD for %s " % node_name)
command = "kubectl get hpenodeinfos %s -o json" % node_name
result = get_command_output_string(command)
crd = json.loads(result)
# print(crd)
return crd
except Exception as e:
logging.getLogger().error("Exception %s while fetching crd for node %s " % (e, node_name))
def verify_node_crd_chap(crd_name, **kwargs):
try:
logging.getLogger().info("Verifying chap details in node crd")
encoding = "utf-8"
flag = False
crd = get_node_crd(crd_name)
logging.getLogger().info("crd :: %s " % crd)
if crd is not None:
if 'chapUser' in kwargs:
assert crd['spec']['chapUser'] == kwargs['chapUser']
assert (base64.b64decode(crd['spec']['chapPassword'])).decode(encoding) == kwargs['chapPassword']
flag = True
return flag
return flag
except Exception as e:
logging.getLogger().error("Exception %s while verifying node CRD :: %s" % (e, crd_name))
raise e
def create_crd(yml, crd_name):
try:
logging.getLogger().info("Creating crd %s ..." % crd_name)
if globals.platform == 'os':
command = "oc create -f " + yml
else:
command = "kubectl create -f " + yml
output = get_command_output_string(command)
logging.getLogger().info(output)
if str(output).startswith(crd_name) and str(output).endswith("created\n"):
return True
else:
return False
except Exception as e:
logging.getLogger().error("Exception while creating crd %s :: %s" % (crd_name, e))
raise e
def hpe_delete_crd(yml, crd_name):
try:
logging.getLogger().info("Deleting crd %s ..." % crd_name)
if globals.platform == 'os':
command = "oc delete -f " + yml
else:
command = "kubectl delete -f " + yml
output = get_command_output_string(command)
logging.getLogger().info(output)
if str(output).startswith(crd_name) and str(output).endswith("deleted\n"):
return True
else:
return False
except Exception as e:
logging.getLogger().error("Exception while deleting crd %s " % e)
def hpe_read_sa(sa_name, sa_namespace):
try:
obj = k8s_core_v1.read_namespaced_service_account(sa_name, sa_namespace)
return obj
except Exception as e:
#print("Exception while reading sa %s " % e)
logging.getLogger().error("Exception while reading sa %s " % e)
def hpe_create_sa(yml, sa_namespace):
try:
k8s_core_v1.create_namespaced_service_account(sa_namespace, yml)
except Exception as e:
#print("Exception while creating sa %s " % e)
logging.getLogger().error("Exception while creating sa %s " % e)
def hpe_read_cluster_role(name):
try:
obj = k8s_rbac_auth_v1.read_cluster_role(name)
return obj
except Exception as e:
#print("Exception while reading cluster role %s " % e)
logging.getLogger().error("Exception while reading cluster role %s " % e)
def hpe_create_cluster_role(yml):
try:
k8s_rbac_auth_v1.create_cluster_role(yml)
except Exception as e:
#print("Exception while creating cluster role %s " % e)
logging.getLogger().error("Exception while creating cluster role %s " % e)
def hpe_read_cluster_role_binding(name):
try:
obj = k8s_rbac_auth_v1.read_cluster_role_binding(name)
return obj
except Exception as e:
#print("Exception while reading cluster role binding %s " % e)
logging.getLogger().error("Exception while reading cluster role binding %s " % e)
def hpe_create_cluster_role_binding(yml):
try:
k8s_rbac_auth_v1.create_cluster_role_binding(yml)
except Exception as e:
#print("Exception while creating cluster role binding %s " % e)
logging.getLogger().error("Exception while creating cluster role binding %s " % e)
def hpe_read_role(name, namespace):
try:
obj = k8s_rbac_auth_v1.read_namespaced_role(name, namespace)
return obj
except Exception as e:
#print("Exception while reading sa %s " % e)
logging.getLogger().error("Exception while reading sa %s " % e)
def hpe_create_role(yml, namespace):
try:
k8s_rbac_auth_v1.create_namespaced_role(namespace, yml)
except Exception as e:
#print("Exception while creating sa %s " % e)
logging.getLogger().error("Exception while creating sa %s " % e)
def hpe_read_role_binding(name, namespace):
try:
obj = k8s_core_v1.read_namespaced_role_binding(name, namespace)
return obj
except Exception as e:
#print("Exception while reading sa %s " % e)
logging.getLogger().error("Exception while reading sa %s " % e)
def hpe_create_role_binding(yml, namespace):
try:
k8s_core_v1.create_namespaced_role_binding(namespace, yml)
except Exception as e:
#print("Exception while creating sa %s " % e)
logging.getLogger().error("Exception while creating sa %s " % e)
def hpe_read_statefulset(name, namespace):
try:
obj = k8s_apps_v1.read_namespaced_stateful_set(name, namespace)
return obj
except Exception as e:
logging.getLogger().error("Exception while reading statefulset %s " % e)
def hpe_create_statefulset(yml):
try:
namespace = globals.namespace
if 'namespace' in yml.get('metadata'):
namespace = yml.get('metadata')['namespace']
statefulset = k8s_apps_v1.create_namespaced_stateful_set(namespace, yml)
return statefulset
except Exception as e:
logging.getLogger().error("Exception while creating statefulset %s " % e)
def create_statefulset(yml):
obj = None
with open(yml) as f:
elements = list(yaml.safe_load_all(f))
for el in elements:
logging.getLogger().debug("======== kind :: %s " % str(el.get('kind')))
if str(el.get('kind')) == "StatefulSet":
logging.getLogger().info("Creating StatefulSet...")
obj = hpe_create_statefulset(el)
logging.getLogger().info("StatefulSet %s created." % obj.metadata.name)
return obj
def create_sc(yml):
obj = None
with open(yml) as f:
elements = list(yaml.safe_load_all(f))
for el in elements:
# print("======== kind :: %s " % str(el.get('kind')))
logging.getLogger().debug("======== kind :: %s " % str(el.get('kind')))
if str(el.get('kind')) == "StorageClass":
# print("PersistentVolume YAML :: %s" % el)
#print("\nCreating StorageClass...")
logging.getLogger().info("Creating StorageClass...")
if el['parameters']['accessProtocol'] != globals.access_protocol:
logging.getLogger().info("accessProtocol value from command line and yaml does not match. %s will be used for the test" % globals.access_protocol)
el['parameters']['accessProtocol'] = globals.access_protocol
obj = hpe_create_sc_object(el)
#print("\nStorageClass %s created." % obj.metadata.name)
logging.getLogger().info("StorageClass %s created." % obj.metadata.name)
return obj
def create_pvc(yml):
obj = None
with open(yml) as f:
elements = list(yaml.safe_load_all(f))
for el in elements:
# print("======== kind :: %s " % str(el.get('kind')))
logging.getLogger().debug("======== kind :: %s " % str(el.get('kind')))
if str(el.get('kind')) == "PersistentVolumeClaim":
# print("PersistentVolume YAML :: %s" % el)
#print("\nCreating PersistentVolumeClaim...")
logging.getLogger().info("Creating PersistentVolumeClaim...")
obj = hpe_create_pvc_object(el)
#print("\nPersistentVolumeClaim %s created." % obj.metadata.name)
logging.getLogger().info("PersistentVolumeClaim %s created." % obj.metadata.name)
return obj
def create_pod(yml):
obj = None
with open(yml) as f:
elements = list(yaml.safe_load_all(f))
for el in elements:
# print("======== kind :: %s " % str(el.get('kind')))
logging.getLogger().debug("======== kind :: %s " % str(el.get('kind')))
if str(el.get('kind')) == "Pod":
# print("Pod YAML :: %s" % el)
#print("\nCreating Pod...")
logging.getLogger().info("\nCreating Pod...")
obj = hpe_create_pod_object(el)
#print("\nPod %s created." % obj.metadata.name)
logging.getLogger().info("\nPod %s created." % obj.metadata.name)
return obj
def create_secret(yml, namespace):
obj = None
with open(yml) as f:
elements = list(yaml.safe_load_all(f))
for el in elements:
# print("======== kind :: %s " % str(el.get('kind')))
logging.getLogger().debug("======== kind :: %s " % str(el.get('kind')))
if str(el.get('kind')) == "Secret":
# print("PersistentVolume YAML :: %s" % el)
logging.getLogger().info("\nCreating Secret...")
logging.getLogger().info(el)
#print("\nCreating Secret...")
#print(el)
obj = hpe_create_secret_object(el)
logging.getLogger().info("\nSecret %s created." % obj.metadata.name)
#print("\nSecret %s created." % obj.metadata.name)
return obj
def get_pvc_crd(pvc_name):
try:
# print("\nReading CRD for %s " % pvc_name)
if globals.platform == 'os':
command = "oc get hpevolumeinfos %s -o json" % pvc_name
else:
command = "kubectl get hpevolumeinfos %s -o json" % pvc_name
result = get_command_output_string(command)
crd = json.loads(result)
# print(crd)
return crd
except Exception as e:
#print("Exception %s while fetching crd for pvc %s " % (e, pvc_name))
logging.getLogger().error("Exception %s while fetching crd for pvc %s " % (e, pvc_name))
def get_pvc_volume(pvc_crd):
vol_name = pvc_crd["spec"]["record"]["Name"]
#print("\nPVC %s has volume %s on array" % (pvc_crd["spec"]["uuid"], vol_name))
logging.getLogger().info("PVC %s has volume %s on array" % (pvc_crd["spec"]["uuid"], vol_name))
return vol_name
def get_pvc_editable_properties(pvc_crd):
vol_name = pvc_crd["spec"]["record"]["Name"]
vol_usrCpg = pvc_crd["spec"]["record"]["Cpg"]
vol_snpCpg = pvc_crd["spec"]["record"]["SnapCpg"]
vol_desc = pvc_crd["spec"]["record"]["Description"]
vol_compression = pvc_crd["spec"]["record"]["Compression"]
vol_provType = pvc_crd["spec"]["record"]["ProvisioningType"]
logging.getLogger().info("Getting mutator properties from crd, name::%s cpg::%s snpCpg::%s desc::%s compr::%s provType::%s" % (vol_name, vol_usrCpg, vol_snpCpg, vol_desc, vol_compression, vol_provType))
return vol_name, vol_usrCpg, vol_snpCpg, vol_provType, vol_desc, vol_compression
def get_volume_from_array(hpe3par_cli, volume_name):
try:
# print("\nFetching volume from array for %s " % volume_name)
hpe3par_volume = hpe3par_cli.getVolume(volume_name)
# print("Volume from array :: %s " % hpe3par_volume)
return hpe3par_volume
except Exception as e:
logging.getLogger().error("Exception %s while fetching volume from array for %s " % (e, volume_name))
def get_volume_set_from_array(hpe3par_cli, volume_set_name):
try:
# print("\nFetching volume set from array for %s " % volume_set_name)
hpe3par_volume_set = hpe3par_cli.getVolumeSet(volume_set_name)
return hpe3par_volume_set
except Exception as e:
logging.getLogger().error("Exception %s while fetching volume from array for %s " % (e, volume_set_name))
def get_volume_sets_from_array(hpe3par_cli):
try:
# print("\nFetching volume set from array for %s " % volume_set_name)
hpe3par_volume_set = hpe3par_cli.getVolumeSets()
return hpe3par_volume_set
except Exception as e:
logging.getLogger().error("Exception %s while fetching volume from array for %s " % (e, volume_set_name))
def verify_volume_properties(hpe3par_volume, **kwargs):