-
Notifications
You must be signed in to change notification settings - Fork 0
/
IxUtils.py
1700 lines (1589 loc) · 91.8 KB
/
IxUtils.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
'''
IxUtils is a suppoting module of Ixload HL Library.
'''
import json
from sre_constants import SUCCESS
import time
#import pysftp
import ftplib
import requests
import yaml
import os
import re
import copy
import csv
ACTION_STATE_FINISHED = 'finished'
ACTION_STATUS_SUCCESSFUL = 'Successful'
ACTION_STATUS_ERROR = 'Error'
ACTION_STATUS_UNCONFIGURED = 'Unconfigured'
#version 1.0
class IxUtils(object):
'''
IxUtils consist of supporting module for IXload HL library.
'''
def __init__(self):
self.connection = ""
self.session_url = ""
self.current_time = time.strftime("%H%M%S")
def strip_api_and_version_from_url(self, url):
'''
#remove the slash (if any) at the beginning of the url
'''
if url[0] == '/':
url = url[1:]
url_elements = url.split('/')
if 'api' in url:
#strip the api/v0 part of the url
url_elements = url_elements[2:]
return '/'.join(url_elements)
def wait_for_action_to_finish(self, reply_obj, action_url, rt_handle):
'''
This method waits for an action to finish executing. after a POST request is sent in order to start an action,
The HTTP reply will contain, in the header, a 'location' field, that contains an URL.
The action URL contains the status of the action. we perform a GET on that URL every 0.5 seconds until the action finishes with a success.
If the action fails, we will throw an error and print the action's error message.
Args:
- reply_obj the reply object holding the location
- rt_handle - the url pointing to the operation
'''
action_result_url = reply_obj.headers.get('location')
if action_result_url:
action_result_url = self.strip_api_and_version_from_url(action_result_url)
action_finished = False
while not action_finished:
action_status_obj = rt_handle.invoke('http_get', url=action_result_url)
if action_status_obj.state == ACTION_STATE_FINISHED:
if action_status_obj.status == ACTION_STATUS_SUCCESSFUL:
action_finished = True
else:
error_msg = "Error while executing action '%s'." % action_url
if action_status_obj.status == ACTION_STATUS_ERROR:
error_msg += action_status_obj.error
raise Exception(error_msg)
else:
time.sleep(0.1)
def perform_generic_operation(self, rt_handle, url, payload_dict):
'''
This will perform a generic operation on the given url, it will wait for it to finish.
Args:
- url is the address of where the operation will be performed
- payload_dict is the python dict with the parameters for the operation
'''
data = json.dumps(payload_dict)
reply = rt_handle.invoke('http_post', url=url, data=data)
if not reply.ok:
raise Exception(reply.text)
self.wait_for_action_to_finish(reply, url, rt_handle)
return reply
def perform_generic_patch_operation(self, rt_handle, url, payload_dict):
'''
This will perform a generic operation on the given url, it will wait for it to finish.
Args:
- url is the address of where the operation will be performed
- payload_dict is the python dict with the parameters for the operation
'''
data = json.dumps(payload_dict)
reply = rt_handle.invoke('http_patch', url=url, data=data)
if not reply.ok:
raise Exception(reply.text)
responce = rt_handle.invoke('http_get', url=url, data=data)
key = list(payload_dict.keys())[0]
iteration = 1
while(iteration <= 3):
if str(responce[0][key]).lower() == str(payload_dict[key]).lower():
return reply
else:
time.sleep(5)
iteration = iteration + 1
raise Exception("Update on the url %s is failed" %url)
def perform_generic_patch(self, rt_handle, url, payload_dict):
'''
This will perform a generic PATCH method on a given url
Args:
- url is the address of where the operation will be performed
- payload_dict is the python dict with the parameters for the operation
'''
data = json.dumps(payload_dict)
reply = rt_handle.invoke('http_patch', url=url, data=data)
if not reply.ok:
raise Exception(reply.text)
return reply
def perform_generic_post(self, rt_handle, list_url, payload_dict):
'''
This will perform a generic POST method on a given url
Args:
- url is the address of where the operation will be performed
- payload_dict is the python dict with the parameters for the operation
'''
data = json.dumps(payload_dict)
reply = rt_handle.invoke('http_post', url=list_url, data=data)
if not reply.ok:
raise Exception(reply.text)
try:
new_obj_path = reply.headers['location']
except:
raise Exception("Location header is not present. Please check if the action was created successfully.")
new_obj_id = new_obj_path.split('/')[-1]
return new_obj_id
def perform_generic_delete(self, rt_handle, list_url, payload_dict):
'''
This will perform a generic DELETE method on a given url
Args:
- url is the address of where the operation will be performed
- payload_dict is the python dict with the parameters for the operation
'''
data = json.dumps(payload_dict)
reply = rt_handle.invoke('http_delete', url=list_url, data=data)
if not reply.ok:
raise Exception(reply.text)
return reply
def downloadResource(self, rt_handle, downloadFolder, localPath, zipName=None, timeout=80):
'''
This method is used to download an entire folder as an archive or any type of file without changing it's format.
Args:
- connection is the connection object that manages the HTTP data transfers between the client and the REST API
- downloadFolder is the folder were the archive/file will be saved
- localPath is the local path on the machine that holds the IxLoad instance
- zipName is the name that archive will take, this parameter is mandatory only for folders, if you want to download a file this parameter is not used.
'''
downloadResourceUrl = rt_handle.connection.url + "/downloadResource"
downloadFolder = downloadFolder.replace("\\\\", "\\")
localPath = localPath.replace("\\", "/")
parameters = { "localPath": localPath, "zipName": zipName }
downloadResourceReply = rt_handle.invoke('httpRequest2', method="GET", url=downloadResourceUrl, params= parameters, downloadStream=True, timeout =timeout)
if not downloadResourceReply.ok:
raise Exception("Error on executing GET request on url %s: %s" % (downloadResourceUrl, downloadResourceReply.text))
if not zipName:
zipName = localPath.split("/")[-1]
elif zipName.split(".")[-1] != "zip":
zipName = zipName + ".zip"
downloadFile = '/'.join([downloadFolder, zipName])
#rt_handle.log("Downloading resource to %s..." % (downloadFile))
try:
with open(downloadFile, 'wb') as fileHandle:
for chunk in downloadResourceReply.iter_content(chunk_size=1024):
fileHandle.write(chunk)
except IOError as e:
raise Exception("Download resource failed. Could not open or create file, please check path and/or permissions. Received IO error: %s" % str(e))
except Exception as e:
raise Exception('Download resource failed. Received the following error:\n %s' % str(e))
else:
return ("Download resource finished.")
def release_configs(self, rt_handle, session_url):
start_run_url = "%s/ixload/test/operations/abortAndReleaseConfigWaitFinish" % (session_url)
data = {}
self.perform_generic_operation(rt_handle, start_run_url, data)
def uploadFile(self, rt_handle, session_url, fileName, uploadPath, overwrite=True):
headers = {'Content-Type': 'multipart/form-data'}
params = {"overwrite": overwrite, "uploadPath": uploadPath}
url = "%s/resources" % (rt_handle.connection.url)
result = {}
try:
start_run_url = "%s/ixload/test/operations/abortAndReleaseConfigWaitFinish" % (session_url)
data = {}
self.perform_generic_operation(rt_handle, start_run_url, data)
with open(fileName, 'rb') as f:
response = requests.post(url, data=f, params=params, headers=headers, verify=False)
result["status"] = int(response.ok)
if response.ok is not True:
result["error"] = response.text
raise Exception('POST operation failed with %s' % response.text)
except requests.exceptions.ConnectionError as e:
result["error"] = str(e)
raise Exception(
'Upload file failed. Received connection error. One common cause for this error is the size of the file to be uploaded.'
' The web server sets a limit of 1GB for the uploaded file size. Received the following error: %s' % str(e)
)
except IOError as e:
result["error"] = str(e)
raise Exception('Upload file failed. Received IO error: %s' % str(e))
except Exception as e:
result["error"] = str(e)
raise Exception('Upload file failed. Received the following error:\n %s' % str(e))
else:
result["error"] = ""
return result
def load_repository(self, rt_handle, session_url, rxf_file_path):
'''
This method will perform a POST request to load a repository.
Args.
- rt_handle is the address of the session to load the rxf for
- rxf_file_path is the local rxf path on the machine that holds the IxLoad instance
'''
load_test_url = "%s/ixload/test/operations/loadTest" % (session_url)
data = {"fullPath": rxf_file_path}
self.perform_generic_operation(rt_handle, load_test_url, data)
def sftp_load_config(self, server, username, password, localpath, remote_path):
'''
sftp_load_config will save the config from one machine to another using sftp protocol.
'''
try:
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
with pysftp.Connection(host=server, username=username, password=password, cnopts=cnopts) as sftp:
sftp.put(localpath, remote_path)
return 1
except Exception as err:
raise Exception('FTP transfer failed \n {}'.format(err))
def apply_config(self, rt_handle, session_url, force=0):
'''
This method is used to start the currently loaded test. After starting the 'Start Test' action, wait for the action to complete.
Args:
- session_url is the address of the session that should run the test.
'''
if force:
apply_config_url = "%s/ixload/test/operations/applyConfiguration" % (session_url)
data = {}
#self.perform_generic_post(rt_handle, apply_config_url, data)
self.perform_generic_operation(rt_handle, apply_config_url, data)
apply_config_url = "%s/ixload/test/operations/applyConfiguration" % (session_url)
data = {}
self.perform_generic_post(rt_handle, apply_config_url, data)
#self.perform_generic_operation(rt_handle, apply_config_url, data)
def run_test(self, rt_handle, session_url):
'''
This method is used to start the currently loaded test. After starting the 'Start Test' action, wait for the action to complete.
Args:
- session_url is the address of the session that should run the test.
'''
apply_config_url = "%s/ixload/test/operations/applyConfiguration" % (session_url)
data = {}
self.perform_generic_operation(rt_handle, apply_config_url, data)
start_run_url = "%s/ixload/test/operations/runTest" % (session_url)
data = {}
run_stats = self.perform_generic_operation(rt_handle, start_run_url, data)
return run_stats
def stop_traffic(self, rt_handle, session_url):
'''
This method is used to start the currently loaded test. After starting the 'Start Test' action, wait for the action to complete.
Args:
- session_url is the address of the session that should run the test.
'''
apply_config_url = "%s/ixload/test/operations/gracefulStopRun" % (session_url)
data = {}
self.perform_generic_operation(rt_handle, apply_config_url, data)
start_run_url = "%s/ixload/test/operations/abortAndReleaseConfigWaitFinish" % (session_url)
data = {}
run_stats = self.perform_generic_operation(rt_handle, start_run_url, data)
return run_stats
def delete_session(self, rt_handle, session_url):
'''
This method is used to delete an existing session.
Args:
- session_url is the address of the seession to delete
'''
delete_params = {}
self.perform_generic_delete(rt_handle, session_url, delete_params)
def get_test_current_state(self, rt_handle, session_url):
'''
This method gets the test current state. (for example - running, unconfigured, ..)
Args:
- session_url is the address of the session that should run the test.
'''
active_test_url = "%s/ixload/test/activeTest" % (session_url)
test_obj = rt_handle.invoke('http_get', url=active_test_url)
return test_obj.currentState
def poll_stats(self, rt_handle, session_url, watched_stats_dict, polling_interval, duration):
'''
This method is used to poll the stats. Polling stats is per request but this method does a continuous poll.
Args:
- session_url is the address of the session that should run the test
- watched_stats_dict these are the stats that are being monitored
- polling_interval the polling interval is 4 by default but can be overridden.
'''
stats_source_list = list(watched_stats_dict.keys())
stats_dict = {}
collected_timestamps = {} # format { stats_source : [2000, 4000, ...] }
test_is_running = True
for stats_source in stats_source_list[:]:
stats_source_url = "%s/ixload/stats/%s/values" % (session_url, stats_source)
stats_source_reply = rt_handle.invoke('http_request', method="GET", url=stats_source_url)
if stats_source_reply.status_code != 200:
stats_source_list.remove(stats_source)
stats_value = []
stats_dict = {}
if polling_interval == 0 and duration == 0:
for stats_source in stats_source_list:
values_url = "%s/ixload/stats/%s/values" % (session_url, stats_source)
values_obj = rt_handle.invoke('http_get', url=values_url)
values_dict = values_obj.get_options()
new_time_stamps = [int(timestamp) for timestamp in values_dict.keys() if timestamp not in collected_timestamps.get(stats_source, [])]
new_time_stamps.sort(reverse=True)
for timestamp in new_time_stamps:
time_stamp_str = str(timestamp)
collected_timestamps.setdefault(stats_source, []).append(time_stamp_str)
time_stamp_dict = stats_dict.setdefault(stats_source, {}).setdefault(timestamp, {})
for caption, value in values_dict[time_stamp_str].get_options().items():
if caption in watched_stats_dict[stats_source]:
stats_value.append(value)
time_stamp_dict[caption] = value
test_is_running = False
return time_stamp_dict
elif polling_interval != 0 and duration == 0:
retrieving_stats = watched_stats_dict[stats_source]
time_stamp_dict = {}
for stats in retrieving_stats:
time_stamp_dict[stats] = []
while test_is_running:
#self.set_polling_interval(rt_handle, session_url, polling_interval)
for stats_source in stats_source_list:
values_url = "%s/ixload/stats/%s/values" % (session_url, stats_source)
values_obj = rt_handle.invoke('http_get', url=values_url)
values_dict = values_obj.get_options()
new_time_stamps = [int(timestamp) for timestamp in values_dict.keys() if timestamp not in collected_timestamps.get(stats_source, [])]
new_time_stamps.sort()
# return new_time_stamps
stats_dict1 = watched_stats_dict[stats_source]
for stats in stats_dict1:
for timestamp in new_time_stamps:
time_stamp_str = str(timestamp)
collected_timestamps.setdefault(stats_source, []).append(time_stamp_str)
for caption, value in values_dict[time_stamp_str].get_options().items():
if caption == stats:
time_stamp_dict[stats].append(value)
test_is_running = self.get_test_current_state(rt_handle, session_url) == "Running"
return time_stamp_dict
elif duration != 0:
retrieving_stats = watched_stats_dict[stats_source]
time_stamp_dict = {}
for stats in retrieving_stats:
time_stamp_dict[stats] = []
dur = duration/60
t_end = time.time() + 60 * dur
while time.time() < t_end:
for stats_source in stats_source_list:
values_url = "%s/ixload/stats/%s/values" % (session_url, stats_source)
values_obj = rt_handle.invoke('http_get', url=values_url)
values_dict = values_obj.get_options()
new_time_stamps = [int(timestamp) for timestamp in values_dict.keys() if timestamp not in collected_timestamps.get(stats_source, [])]
new_time_stamps.sort(reverse=True)
time_stamp_str = str(new_time_stamps[0])
stats_dict1 = watched_stats_dict[stats_source]
for stats in stats_dict1:
for timestamp in new_time_stamps:
time_stamp_str = str(timestamp)
collected_timestamps.setdefault(stats_source, []).append(time_stamp_str)
for caption, value in values_dict[time_stamp_str].get_options().items():
if caption == stats:
time_stamp_dict[stats].append(value)
return time_stamp_dict
def get_port_details(self, rt_handle, session_url, kwargs):
'''
'''
chassis_id, card_id, port_id = kwargs['port'].split("/")
card_id = str(chassis_id)+"."+str(card_id)
card_url = "%s/ixload/chassisChain/chassisList/%s/cardList" % (session_url, chassis_id)
card_list = rt_handle.invoke('http_get', url=card_url)
for card in card_list:
if card_id in card['name']:
card_id = card['objectID']
port_list_url = "%s/ixload/chassisChain/chassisList/%s/cardList/%s/portList" % (session_url, chassis_id, card_id)
port_list = rt_handle.invoke('http_get', url=port_list_url)
for port_l in port_list:
if port_l['portId'] == int(port_id):
object_id = port_l['objectID']
port_url = "%s/%s/" % (port_list_url, object_id)
port_details = rt_handle.invoke('http_get', url=port_url, option=1)
return port_details['managementIp']
def polling_interval_test(self, rt_handle, session_url, interval, file_name, aggregation_type=None): # added argument for aggregation type
'''
'''
poll_url = "%s/ixload/preferences" % (session_url)
data = {"enableRestStatViewsCsvLogging": "True", "enableL23RestStatViews":"True", "saveDataModelSnapshot":"True"}
self.perform_generic_patch(rt_handle, poll_url, data)
if interval:
poll_url = "%s/ixload/test/activeTest" % (session_url)
data = {"csvInterval":interval}
self.perform_generic_patch(rt_handle, poll_url, data)
poll_ur = "%s/ixload/test" % (session_url)
if file_name == None:
file_name = 'C:\\ProgramData\\Ixia\\IxLoadGateway'
data1 = {"outputDir": "true", "runResultDirFull": file_name}
self.perform_generic_patch(rt_handle, poll_ur, data1)
if aggregation_type:
name = self.get_role_name(rt_handle, session_url)
config_url = "%s/ixload/stats/%s/configuredStats" % (session_url, name)
data = {"aggregationType": aggregation_type}
self.perform_generic_patch(rt_handle, config_url, data)
def get_role_name(self, rt_handle, session_url):
'''
This method is used to get the commandList url for a provided agent name.
Args:
- session_url is the address of the session that should run the test
- agent_name is the agent name for which the commandList address is provided
'''
community_list_url = "%s/ixload/test/activeTest/communityList" % session_url
community_list = rt_handle.invoke('http_get', url=community_list_url)
for community in community_list:
activity_list_url = "%s/%s/activityList" % (community_list_url, community['objectID'])
activity_list = rt_handle.invoke('http_get', url=activity_list_url)
for activity in activity_list:
if activity['role'] == "Client":
role = activity['protocol']+activity['role']
return role
def report_config(self, rt_handle, session_url, file_name):
'''
'''
pre_url = "%s/ixload/preferences" % (session_url)
data = {"enableL23RestStatViews": "True", "enableRestStatViewsCsvLogging": "True"}
self.perform_generic_patch(rt_handle, pre_url, data)
report_url = "%s/ixload/test/operations/generateRestReport" % (session_url)
data = {"reportFile": file_name}
run_stats = self.perform_generic_operation(rt_handle, report_url, data)
return run_stats
# self.perform_generic_post(rt_handle, report_url, data)
def csv_stats (self, rt_handle, stats_return, read_file, write_file, parse = None):
'''
'''
a = []
with open(read_file, 'r') as csv_file:
csv_reader = csv.reader(csv_file)
for lines in csv_reader:
a.append(lines)
#del a[0:10]
#del a[1:3]
#return (read_file, write_file)
with open(write_file, 'w', newline='') as csv_file:
writer = csv.writer(csv_file)
for i in range(len(a)):
writer.writerow(a[i])
if parse:
with open(write_file, 'w', newline='') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(a[0])
del a[0]
for i in range(len(a)):
if "SU" in a[i]:
writer.writerow(a[i])
for key in stats_return.keys():
with open(write_file, 'r') as csv_file:
csv_reader = csv.DictReader(csv_file)
for lines in csv_reader:
stats_return[key].append(lines[key])
return stats_return
def get_dut_mandatory_args(self, kwargs):
'''
get_mandatory_args will the return mandatory arguemnts.
'''
arg_dict = {}
if "mode" in kwargs.keys():
arg_dict['mode'] = kwargs['mode']
if kwargs["mode"] == "create":
if "no_of_dut" in kwargs.keys():
arg_dict['no_of_dut'] = kwargs['no_of_dut']
kwargs.pop('no_of_dut')
else:
raise Exception('no_of_dut not found, no_of_dut is mandatory argument')
if "type" not in kwargs.keys():
raise Exception('type not found, type is mandatory argument')
if kwargs["mode"] == "modify":
if "type" not in kwargs.keys():
raise Exception('type not found, type is mandatory argument')
if "dut_name" not in kwargs.keys():
raise Exception('dut_name not found, dut_name is mandatory argument')
if kwargs["mode"] == "delete" :
if "dut_name" not in kwargs.keys():
raise Exception('dut_name not found, dut_name is mandatory argument')
kwargs.pop('mode')
else:
raise Exception('mode not found, mode is mandatory argument')
return (arg_dict, kwargs)
def get_dut_range_args(self, dut_args, kwargs):
'''
get the dut config arguments
'''
args_list = [{"ServerLoadBalancer":['enable', 'tos', 'vip']},
{"PacketSwitch": ['vlanUniqueCount', 'firstIp', 'vlanEnable', 'vlanId', 'innerVlanEnable',
'ipIncrStep', 'ipType', 'vlanIncrStep', 'vlanCount', 'ipCount', 'protocol', 'portRanges']},
{"VirtualDut": ['vlanUniqueCount', 'firstIp', 'vlanEnable', 'vlanId', 'innerVlanEnable',
'ipIncrStep', 'ipType', 'vlanIncrStep', 'vlanCount', 'ipCount', 'protocol', 'portRanges']}]
ret_dict = {}
for list in args_list:
for key,value in list.items():
if key == dut_args['type']:
for item in value:
if item in kwargs.keys():
ret_dict[item] = kwargs[item]
kwargs.pop(item)
return (ret_dict)
def get_dut_config_args(self, dut_args, kwargs):
'''
get the dut config arguments
'''
args_list = [{"ServerLoadBalancer":['enableDirectServerReturn', 'serverNetwork']},
{"Firewall": ['ipAddress']}, {"ExternalServer": ['ipAddress']}]
ret_dict = {}
for arg_list in args_list:
for key,value in arg_list.items():
if key == dut_args['type']:
for item in value:
if item in kwargs.keys():
ret_dict[item] = kwargs[item]
kwargs.pop(item)
return (ret_dict, kwargs)
def get_dut_args(self, kwargs):
'''
get the dut config arguments
'''
args_list = ['type', 'comment']
ret_dict = {}
if "type" in kwargs.keys():
ret_dict['type'] = kwargs['type']
if "comment" in kwargs.keys():
ret_dict['comment'] = kwargs['comment']
return (ret_dict, kwargs)
def add_dut(self, rt_handle, session_url, dut_args, kwargs):
'''
add dut dict to dutList config
'''
dut_list_url = "%s/ixload/test/activeTest/dutList" % session_url
self.perform_generic_post(rt_handle, dut_list_url, dut_args)
dut_list = rt_handle.invoke('http_get', url=dut_list_url)
return dut_list[-1]
def edit_dut(self, rt_handle, session_url, kwargs):
flag = False
dut_list_url = "%s/ixload/test/activeTest/dutList" % session_url
dut_list = rt_handle.invoke('http_get', url=dut_list_url)
for dut in dut_list:
if dut['name'] == kwargs['dut_name']:
flag = True
dut_url = "%s/%s/" % (dut_list_url, dut['objectID'])
dut_args, kwargs = self.get_dut_args(kwargs)
if dut_args:
self.perform_generic_patch(rt_handle, dut_url, dut_args)
config_args, kwargs = self.get_dut_config_args(dut_args, kwargs)
dut_config_url = "%s/%s/dutConfig" % (dut_list_url, dut['objectID'])
if config_args:
self.perform_generic_patch(rt_handle, dut_config_url, config_args)
if dut_args['type'] == "ServerLoadBalancer":
range_args = self.get_dut_range_args(dut_args, kwargs)
if range_args:
dut_range_url = "%s/slbRangeList" % (dut_config_url)
self.perform_generic_patch(rt_handle, dut_range_url, range_args)
if dut_args['type'] == "VirtualDut":
network_args, kwargs = self.get_args("nr_", kwargs)
range_args = self.get_dut_range_args(dut_args, network_args)
if range_args:
dut_range_url = "%s/networkRangeList" % (dut_config_url)
self.perform_generic_patch(rt_handle, dut_range_url, range_args)
protocol_args, kwargs = self.get_args("ppr_", kwargs)
range_args = self.get_dut_range_args(dut_args, protocol_args)
if range_args:
dut_range_url = "%s/protocolPortRangeList" % (dut_config_url)
dut_protocol_list = rt_handle.invoke('http_get', url=dut_range_url)
if len(dut_protocol_list) == 0:
self.perform_generic_post(rt_handle, dut_range_url, range_args)
else:
for protocol_range in dut_protocol_list:
protocol_url = "%s/%s" % (dut_range_url, protocol_range['objectID'])
dut_protocol=self.perform_generic_patch(rt_handle, protocol_url, range_args)
if dut_args['type'] == "PacketSwitch":
onr_network_args, kwargs = self.get_args("onr_", kwargs)
range_args = self.get_dut_range_args(dut_args, onr_network_args)
if range_args:
dut_range_url = "%s/originateNetworkRangeList" % (dut_config_url)
self.perform_generic_patch(rt_handle, dut_range_url, range_args)
tnr_network_args, kwargs = self.get_args("tnr_", kwargs)
range_args=self.get_dut_range_args(dut_args, tnr_network_args)
if range_args:
dut_range_url = "%s/terminateNetworkRangeList" % (dut_config_url)
self.perform_generic_patch(rt_handle, dut_range_url, range_args)
opr_protocol_args, kwargs = self.get_args("opr_", kwargs)
range_args = self.get_dut_range_args(dut_args, opr_protocol_args)
if range_args:
dut_range_url = "%s/originateProtocolPortRangeList" % (dut_config_url)
dut_protocol_list = rt_handle.invoke('http_get', url=dut_range_url)
if len(dut_protocol_list)==0:
self.perform_generic_post(rt_handle, dut_range_url, range_args)
else:
for protocol_range in dut_protocol_list:
protocol_url = "%s/%s" %(dut_range_url, protocol_range['objectID'])
dut_protocol=self.perform_generic_patch(rt_handle, protocol_url, range_args)
tpr_protocol_args, kwargs = self.get_args("tpr_", kwargs)
range_args= self.get_dut_range_args(dut_args, tpr_protocol_args)
if range_args:
dut_range_url = "%s/terminateProtocolPortRangeList" % (dut_config_url)
dut_protocol_list = rt_handle.invoke('http_get', url=dut_range_url)
if len(dut_protocol_list)==0:
self.perform_generic_post(rt_handle, dut_range_url, range_args)
else:
for protocol_range in dut_protocol_list:
protocol_url = "%s/%s" %(dut_range_url, protocol_range['objectID'])
dut_protocol=self.perform_generic_patch(rt_handle, protocol_url, range_args)
if not flag:
raise Exception("Dut name- %s not found, cannot be modified"%(kwargs['dut_name']))
def delete_dut(self, rt_handle, session_url, dut_name):
'''
delete the given dut from the dutList config
'''
flag = False
dut_list_url = "%s/ixload/test/activeTest/dutList" % session_url
dut_list = rt_handle.invoke('http_get', url=dut_list_url)
for dut in dut_list:
if dut_name == dut['name']:
flag = True
payload = {}
dut_url = "%s/%s/" % (dut_list_url, dut['objectID'])
self.perform_generic_delete(rt_handle, dut_url, payload)
if not flag:
raise Exception( "Dut name- %s not found, cannot be deleted"%(dut_name))
def add_dut_config(self, rt_handle, session_url, dut, kwargs):
dut_url = "%s/ixload/test/activeTest/dutList" % session_url
config_args, kwargs = self.get_dut_config_args(dut, kwargs)
dut_config_url = "%s/%s/dutConfig" % (dut_url, dut['objectID'])
self.perform_generic_patch(rt_handle, dut_config_url, config_args)
if dut['type'] == "ServerLoadBalancer":
range_args = self.get_dut_range_args(dut, kwargs)
if range_args:
dut_range_url = "%s/slbRangeList" % (dut_config_url)
self.perform_generic_patch(rt_handle, dut_range_url, range_args)
if dut['type'] == "VirtualDut":
network_args, kwargs = self.get_args("nr_", kwargs)
range_args = self.get_dut_range_args(dut, network_args)
if range_args:
dut_range_url = "%s/networkRangeList" % (dut_config_url)
self.perform_generic_patch(rt_handle, dut_range_url, range_args)
protocol_args, kwargs = self.get_args("ppr_", kwargs)
range_args = self.get_dut_range_args(dut, protocol_args)
if range_args:
dut_range_url = "%s/protocolPortRangeList" % (dut_config_url)
self.perform_generic_post(rt_handle, dut_range_url, range_args)
if dut['type'] == "PacketSwitch":
origin_network_args, kwargs = self.get_args("onr_", kwargs)
range_args = self.get_dut_range_args(dut, origin_network_args)
if range_args:
dut_range_url = "%s/originateNetworkRangeList" % (dut_config_url)
self.perform_generic_patch(rt_handle, dut_range_url, range_args)
terminate_network_args, kwargs = self.get_args("tnr_", kwargs)
range_args = self.get_dut_range_args(dut, terminate_network_args)
if range_args:
dut_range_url = "%s/terminateNetworkRangeList" % (dut_config_url)
self.perform_generic_patch(rt_handle, dut_range_url, range_args)
origin_protocol_args, kwargs = self.get_args("opr_", kwargs)
range_args = self.get_dut_range_args(dut, origin_protocol_args)
if range_args:
dut_range_url = "%s/originateProtocolPortRangeList" % (dut_config_url)
self.perform_generic_post(rt_handle, dut_range_url, range_args)
terminate_protocol_args, kwargs = self.get_args("tpr_", kwargs)
range_args = self.get_dut_range_args(dut, terminate_protocol_args)
if range_args:
dut_range_url = "%s/terminateProtocolPortRangeList" % (dut_config_url)
self.perform_generic_post(rt_handle, dut_range_url, range_args)
def configure_dut(self, rt_handle, session_url, kwargs):
'''
Create or modify or delete the DUT config
'''
mand_args, kwargs = self.get_dut_mandatory_args(kwargs)
if mand_args['mode'] == "create":
for dut in range(mand_args['no_of_dut']):
dut_args, kwargs = self.get_dut_args(kwargs)
dut= self.add_dut(rt_handle, session_url, dut_args, kwargs)
self.add_dut_config(rt_handle, session_url, dut, kwargs)
if mand_args['mode'] == "modify":
self.edit_dut(rt_handle, session_url, kwargs)
if mand_args['mode'] == "delete":
self.delete_dut(rt_handle, session_url, kwargs['dut_name'])
def save_rxf(self, rt_handle, session_url, rxf_file_path):
'''
This method saves the current rxf to the disk of the machine on which the IxLoad instance is running.
Args:
- session_url is the address of the session to save the rxf for
- rxf_file_path is the location where to save the rxf on the machine that holds the IxLoad instance
'''
save_rxf_url = "%s/ixload/test/operations/saveAs" % (session_url)
data = {"fullPath":rxf_file_path, "overWrite": 1}
self.perform_generic_operation(rt_handle, save_rxf_url, data)
def ftp_load_config(self, server, username, password, filepath):
'''
This method performs ftp from script server tp APP server
'''
try:
session = ftplib.FTP(server, username, password)
except Exception as err:
raise Exception('Could establish FTP session\n {}'.format(err))
try:
filename = filepath.split("/")[-1]
file_to_open = open(filepath, 'rb')
session.storbinary('STOR {}'.format(filename), file_to_open)
file_to_open .close()
session.quit()
return 1
except Exception as err:
raise Exception('FTP transfer failed \n {}'.format(err))
def ftp_save_config(self, server, username, password, filename):
'''
This method performs ftp from APP server to script server
'''
try:
session = ftplib.FTP(server, username, password)
except Exception as err:
raise Exception('Could establish FTP session\n {}'.format(err))
try:
session.retrbinary("RETR " + filename, open(filename, 'wb').write)
session.quit()
return 1
except Exception as err:
raise Exception('FTP transfer failed \n {}'.format(err))
def sftp_save_config(self, server, username, password, localpath, remote_path):
'''
sftp_save_config will save the config from one machine to another using sftp protocol.
'''
try:
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
with pysftp.Connection(host=server, username=username, password=password, cnopts=cnopts) as sftp:
sftp.get(localpath, remote_path)
return 1
except Exception as err:
raise Exception('SFTP transfer failed \n {}'.format(err))
def clear_chassis_list(self, rt_handle, session_url):
'''
This method is used to clear the chassis list. After execution no chassis should be available in the chassis_listl.
Args:
- session_url is the address of the session that should run the test
'''
chassis_list_url = "%s/ixload/chassischain/chassisList" % session_url
delete_params = {}
self.perform_generic_delete(rt_handle, chassis_list_url, delete_params)
def add_chassis_list(self, rt_handle, session_url, chassis_listl):
'''
This method is used to add one or more chassis to the chassis list.
Args:
- session_url is the address of the session that should run the test
- chassis_listl is the list of chassis that will be added to the chassis chain.
'''
chassis_list_url = "%s/ixload/chassisChain/chassisList" % (session_url)
for chassis_name in chassis_listl:
data = {"name": chassis_name}
chassis_id = self.perform_generic_post(rt_handle, chassis_list_url, data)
refresh_connection_url = "%s/%s/operations/refreshConnection" % (chassis_list_url, chassis_id)
self.perform_generic_operation(rt_handle, refresh_connection_url, {})
return refresh_connection_url
def reboot_ports(self, rt_handle, session_url, port):
chassis_id, card_id, port_id = port[0].split("/")
card_id = str(chassis_id)+"."+str(card_id)
card_url = "%s/ixload/chassisChain/chassisList/%s/cardList" % (session_url, chassis_id)
card_list = rt_handle.invoke('http_get', url=card_url)
for card in card_list:
if card_id in card['name']:
card_id = card['objectID']
port_list_url = "%s/ixload/chassisChain/chassisList/%s/cardList/%s/portList" % (session_url, chassis_id, card_id)
port_list = rt_handle.invoke('http_get', url=port_list_url)
for port_l in port_list:
if port_l['portId'] == int(port_id):
object_id = port_l['objectID']
port_url = "%s/%s/operations/reboot/" % (port_list_url, object_id)
self.perform_generic_operation(rt_handle, port_url, {})
return
def assign_ports(self, rt_handle, session_url, port_list_per_community):
'''
This method is used to assign ports from a connected chassis to the required NetTraffics.
Args:
- session_url is the address of the session that should run the test
- port_list_per_community is the dictionary mapping NetTraffics to ports (format -> { community name : [ port list ] })
'''
active_test_url = "%s/ixload/test/activeTest" % session_url
data = {"enableForceOwnership": "true"}
self.perform_generic_patch(rt_handle, active_test_url, data)
community_list_url = "%s/ixload/test/activeTest/communityList" % session_url
community_list = rt_handle.invoke('http_get', url=community_list_url)
value = []
port_list_for_community1 = copy.deepcopy(port_list_per_community)
for key in port_list_for_community1.keys():
name = self.get_community_name(rt_handle, key)
port_list_per_community[name] = port_list_for_community1[key]
for community in community_list:
port_list_for_community = port_list_per_community.get(community["name"])
port_list_url = "%s/%s/network/portList" % (community_list_url, community["objectID"])
value.append(community)
if port_list_for_community is not None:
for port in port_list_for_community:
chassis_id, card_id, port_id = [int(num) for num in port.split("/")]
param_dict = {"chassisId": chassis_id, "cardId": card_id, "portId": port_id}
self.perform_generic_post(rt_handle, port_list_url, param_dict)
# apply_config_url = "%s/ixload/test/operations/applyConfiguration" % (session_url)
# data = {}
# self.perform_generic_operation(rt_handle, apply_config_url, data)
return value
def get_objective_type(self, rt_handle, session_url):
'''
This method gets the test configured user objective type(simluted user, connectionpersecond.
Args:
- session_url is the address of the session that should run the test.
'''
active_test_url = "%s/ixload/test/activeTest/communityList" % (session_url)
test_obj = rt_handle.invoke('http_get', url=active_test_url)
for obj in test_obj:
if obj['activeRole'] == "Client":
return obj['userObjectiveType']
def configure_time_line(self, rt_handle, session_url, time_line_dict):
'''
configure_time_line will configure the test timeline objectives.
'''
for item in time_line_dict.keys():
time_line_list_url = "%s/ixload/test/activeTest/timelineList" % session_url
test_obj = rt_handle.invoke('http_get', url=time_line_list_url)
time_line_list_url = "%s/%s" % (time_line_list_url, test_obj[0]['objectID'])
data = {item:time_line_dict[item]}
self.perform_generic_patch(rt_handle, time_line_list_url, data)
def get_timeline_args(self, value_dict):
'''
get_timeline_args will return timeline argument.
'''
ret_dict = {}
activity_list = ["rampUpType", "rampUpValue", "offlineTime", "rampDownTime", "standbyTime", "rampDownValue", "rampUpInterval", "iterations",
"rampUpTime", "sustainTime", "timelineType", "name"]
for key in value_dict:
if activity_list.count(key):
ret_dict[key] = value_dict[key]
for key in activity_list:
if key in value_dict.keys():
value_dict.pop(key)
return (ret_dict, value_dict)
def get_mandatory_args(self, kwargs):
'''
get_mandatory_args will the return mandatory arguemnts.
'''
arg_dict = {}
if "mode" in kwargs.keys():
arg_dict['mode'] = kwargs['mode']
kwargs.pop('mode')
else:
raise Exception('mode not found, mode is mandatory argument')
if "role" in kwargs.keys():
arg_dict['role'] = kwargs['role']
kwargs.pop('role')
else:
raise Exception('role not found, role is mandatory argument')
# if "network_name" in kwargs.keys():
# arg_dict['network_name'] = kwargs['network_name']
# kwargs.pop('network_name')
# else:
# raise Exception('network_name not found, network_name is a mandatory argument')
return (arg_dict, kwargs)
def get_mandatory_command_args(self, kwargs): #NewChange
'''
get_mandatory_command_args will the return mandatory arguemnts.
'''
arg_dict = {}
if "mode" in kwargs.keys():
arg_dict['mode'] = kwargs['mode']
kwargs.pop('mode')
else:
raise Exception('mode not found, mode is mandatory argument')
if "agent_name" in kwargs.keys():
arg_dict['agent_name'] = kwargs['agent_name']
kwargs.pop('agent_name')
else:
raise Exception('agent_name not found, agent_name is mandatory argument')
if "commandName" in kwargs.keys():
arg_dict['commandName'] = kwargs['commandName']
kwargs.pop('commandName')
else:
raise Exception('commandName not found, commandName is mandatory argument')
return (arg_dict, kwargs)
def get_mandatory_client_args(self, kwargs):
'''
get_mandatory_args will the return mandatory arguemnts.
'''
arg_dict = {}
if "mode" in kwargs.keys():
arg_dict['mode'] = kwargs['mode']
kwargs.pop('mode')
else:
raise Exception('mode not found, mode is mandatory argument')
if "agentName" in kwargs.keys():
arg_dict['agentName'] = kwargs['agentName']
kwargs.pop('agentName')
else:
raise Exception('role not found, role is mandatory argument')
# if "network_name" in kwargs.keys():
# arg_dict['network_name'] = kwargs['network_name']
# kwargs.pop('network_name')
# else:
# raise Exception('network_name not found, network_name is a mandatory argument')
return (arg_dict, kwargs)
def add_communities(self, rt_handle, session_url, community_option_list):
'''
add_communities will add community as HTTP client or server.
'''
community_list_url = "%s/ixload/test/activeTest/communityList" % session_url
for community_option_dict in community_option_list:
self.perform_generic_post(rt_handle, community_list_url, community_option_dict)
community_list_url = "%s/ixload/test/activeTest/communityList" % session_url
community_list = rt_handle.invoke('http_get', url=community_list_url)
return community_list[-1]
def add_activities_updated(self, rt_handle, session_url, activity_list_per_community, community_list):
'''
add_activities_updated will add the activities to the test.
'''
community_list_url = "%s/ixload/test/activeTest/communityList" % session_url
for communivt_name, activity_list in activity_list_per_community.items():
if community_list is None:
raise Exception('Community %s cannot be found.' % communivt_name)
activity_list_url = "%s/%s/activityList" % (community_list_url, community_list['objectID'])
network_list_url = "%s/%s/network" % (community_list_url, community_list['objectID'])
traffic_list_url = "%s/%s/traffic" % (community_list_url, community_list['objectID'])
for activity_type in activity_list:
options = {}
options.update({'protocolAndType': activity_type})
self.perform_generic_post(rt_handle, activity_list_url, options)
self.change_name(rt_handle, network_list_url, communivt_name.split("@")[0])
self.change_name(rt_handle, traffic_list_url, communivt_name.split("@")[-1])
return activity_list_url