-
Notifications
You must be signed in to change notification settings - Fork 0
/
IxL_RestApi.py
1822 lines (1474 loc) · 81.7 KB
/
IxL_RestApi.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
from __future__ import absolute_import, print_function
import requests
import json
import sys
import pprint
import time
import subprocess
import os
import re
import datetime
import platform
class IxLoadRestApiException(Exception):
def __init__(self, msg=None):
showErrorMsg = '\nIxLoadRestApiException error: {0}\n\n'.format(msg)
print(showErrorMsg)
if Main.enableDebugLogFile:
with open(Main.debugLogFile, 'a') as restLogFile:
restLogFile.write(showErrorMsg)
class Main():
debugLogFile = None
enableDebugLogFile = False
def __init__(self, apiServerIp, apiServerIpPort, useHttps=False, apiKey=None, verifySsl=False, deleteSession=True,
osPlatform='windows', generateRestLogFile='ixLoad_testLog.txt', pollStatusInterval=1, robotFrameworkStdout=False, keystackObj=None):
"""
Description
Initialize the class variables
Parameters
apiServerIp: <str>: The IP address of the IxLoad API server.
apiServerIpPort: <str>: The API server port. Default = 8080.
apiKey: <str>: The apiKey to use for authentication. You only need this if you
enabled "enabled authentication on IxLoadGateway" during installation.
Then, get the apiKey from IxLoad GUI, Preferences, General, API-Key.
osPlatform: <str>: windows or linux
deleteSession: <bool>: True = Delete the session after test is done.
generateRestLogFile: <bool>: True = generate a complete log file.
Filename = ixLoadRestApiLog.txt
robotFrameworkStdout: <bool>: True = Display print statements on stdout.
pollStatusInterval: <int>: Defaults = 1 second.
The delay time in seconds to poll for operation status like
starting a new session, load config file, graceful shutdown, getting stats, etc.
"""
from requests.exceptions import ConnectionError
from requests.packages.urllib3.connection import HTTPConnection
# Disable SSL warnings
requests.packages.urllib3.disable_warnings()
# Disable non http connections.
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
self.keystackObj = keystackObj
self.osPlatform = osPlatform
if apiServerIpPort in [8443, '8443']:
httpHead = 'https'
else:
httpHead = 'http'
self.apiVersion = 'v0'
self.apiServerIp = apiServerIp
self.deleteSession = deleteSession
self.httpHeader = '{0}://{1}:{2}'.format(httpHead, apiServerIp, apiServerIpPort)
self.jsonHeader = {'content-type': 'application/json'}
self.verifySsl = verifySsl
self.generateRestLogFile = generateRestLogFile
self.robotFrameworkStdout = robotFrameworkStdout
self.testResults = None ;# This is set in pollStatsAndCheckStatResults()
self.pollStatusInterval = pollStatusInterval
Main.debugLogFile = self.generateRestLogFile
Main.enableDebugLogFile = self.generateRestLogFile
if apiKey:
self.apiKey = apiKey
self.jsonHeader.update({'X-Api-Key': self.apiKey})
if self.robotFrameworkStdout:
from robot.libraries.BuiltIn import _Misc
self.robotLogger = _Misc()
# GenerateRestLogFile could be a filename or boolean
# If True, create default log file name: restApiLog.txt
self.restLogFile = None
if generateRestLogFile:
# Default the log file name since user didn't provide a log file name.
self.restLogFile = 'ixLoad_testLog.txt'
Main.debugLogFile = self.restLogFile
# User provided a log file name.
if type(generateRestLogFile) is not None:
self.restLogFile = generateRestLogFile
# Instantiate a new log file here.
open(self.restLogFile, 'w').close()
def getApiVersion(self, connection):
return connection.url.split("/")[-1]
# CONNECT
def connect(self, ixLoadVersion=None, sessionId=None, timeout=90):
"""
For new session, provide the ixLoadVersion.
If connecting to an existing session, provide the sessionId
"""
self.ixLoadVersion = ixLoadVersion
# http://10.219.x.x:8080/api/v0/sessions
if sessionId is None:
response = self.post(self.httpHeader+'/api/{}/sessions'.format(self.apiVersion), data=({'ixLoadVersion': ixLoadVersion}))
response = requests.get(self.httpHeader+'/api/{}/sessions'.format(self.apiVersion), verify=self.verifySsl)
try:
sessionId = response.json()[-1]['sessionId']
except:
raise IxLoadRestApiException('connect failed. No sessionId created')
self.sessionId = str(sessionId)
self.sessionIdUrl = '{}/api/{}/sessions/{}'.format(self.httpHeader, self.apiVersion, self.sessionId)
# Start operations
if ixLoadVersion is not None:
response = self.post(self.sessionIdUrl+'/operations/start')
self.logInfo('\n\n', timestamp=False)
counter = 0
while True:
response = self.get(self.sessionIdUrl)
currentStatus = response.json()['isActive']
self.logInfo('\tCurrentStatus: {0}'.format(currentStatus), timestamp=False)
if counter <= timeout and currentStatus != True:
self.logInfo('\tWait {0}/{1} seconds'.format(counter, timeout), timestamp=False)
time.sleep(self.pollStatusInterval)
counter += self.pollStatusInterval
continue
if counter <= timeout and currentStatus == True:
break
if counter >= timeout and currentStatus != True:
raise IxLoadRestApiException('New session ID failed to become active')
def logInfo(self, msg, end='\n', timestamp=True):
"""
Description
An internal function to print info to stdout
Parameters
msg: (str): The message to print.
"""
currentTime = self.getTime()
if timestamp:
msg = '\n' + currentTime + ': ' + msg
if self.keystackObj:
self.keystackObj.logInfo(msg, includeTimestamp=True)
else:
# No timestamp and no newline are mainly for verifying states and status
msg = msg
if self.keystackObj:
self.keystackObj.logInfo(msg, includeTimestamp=False)
#print('{0}'.format(msg), end=end)
if self.generateRestLogFile:
with open(self.restLogFile, 'a') as restLogFile:
restLogFile.write(msg+end)
if self.robotFrameworkStdout:
self.robotLogger.log_to_console(msg)
def getTime(self):
"""
Returns: 13:31:44.083426
"""
dateAndTime = str(datetime.datetime.now()).split(' ')
return dateAndTime[1]
def logError(self, msg, end='\n', timestamp=True):
"""
Description
An internal function to print error to stdout.
Parameter
msg: (str): The message to print.
"""
currentTime = self.getTime()
if timestamp:
msg = '\n{0}: Error: {1}'.format(currentTime, msg)
if self.keystackObj:
self.keystackObj.logInfo(msg, includeTimestamp=True)
else:
# No timestamp and no newline are mainly for verifying states and status
msg = '\nError: {0}'.format(msg)
if self.keystackObj:
self.keystackObj.logInfo(msg, includeTimestamp=False)
#print('{0}'.format(msg), end=end)
if self.generateRestLogFile:
with open(self.restLogFile, 'a') as restLogFile:
restLogFile.write('Error: '+msg+end)
if self.robotFrameworkStdout:
self.robotStdout.log_to_console(msg)
self.keystackObj.logInfo(msg)
def get(self, restApi, data={}, silentMode=False, downloadStream=False, ignoreError=False):
"""
Description
A HTTP GET function to send REST APIs.
Parameters
restApi: The REST API URL.
data: The data payload for the URL.
silentMode: True or False. To display URL, data and header info.
ignoreError: True or False. If False, the response will be returned.
"""
if silentMode is False:
self.logInfo('\n\tGET: {0}\n\tHEADERS: {1}'.format(restApi, self.jsonHeader))
try:
if downloadStream:
response = requests.get(restApi, headers=self.jsonHeader, stream=True, verify=self.verifySsl, allow_redirects=True)
else:
response = requests.get(restApi, headers=self.jsonHeader, verify=self.verifySsl, allow_redirects=True)
if silentMode is False:
self.logInfo('\tSTATUS CODE: %s' % response.status_code, timestamp=False)
if not str(response.status_code).startswith('2'):
if ignoreError == False:
raise IxLoadRestApiException('http GET error:{0}\n'.format(response.text))
return response
except requests.exceptions.RequestException as errMsg:
raise IxLoadRestApiException('http GET error: {0}\n'.format(errMsg))
def post(self, restApi, data={}, headers=None, silentMode=False, ignoreError=False):
"""
Description
A HTTP POST function to mainly used to create or start operations.
Parameters
restApi: The REST API URL.
data: The data payload for the URL.
headers: The special header to use for the URL.
silentMode: True or False. To display URL, data and header info.
noDataJsonDumps: True or False. If True, use json dumps. Else, accept the data as-is.
ignoreError: True or False. If False, the response will be returned. No exception will be raised.
"""
if headers != None:
originalJsonHeader = self.jsonHeader
self.jsonHeader = headers
data = json.dumps(data)
if silentMode == False:
self.logInfo('\n\tPOST: {0}\n\tDATA: {1}\n\tHEADERS: {2}'.format(restApi, data, self.jsonHeader))
try:
response = requests.post(restApi, data=data, headers=self.jsonHeader, verify=self.verifySsl)
# 200 or 201
if silentMode == False:
self.logInfo('\tSTATUS CODE: %s' % response.status_code, timestamp=False)
if not str(response.status_code).startswith('2'):
if ignoreError == False:
raise IxLoadRestApiException('http POST error: {0}\n'.format(response.text))
# Change it back to the original json header
if headers != None:
self.jsonHeader = originalJsonHeader
return response
except requests.exceptions.RequestException as errMsg:
raise IxLoadRestApiException('http POST error: {0}\n'.format(errMsg))
def patch(self, restApi, data={}, silentMode=False):
"""
Description
A HTTP PATCH function to modify configurations.
Parameters
restApi: The REST API URL.
data: The data payload for the URL.
silentMode: True or False. To display URL, data and header info.
"""
if silentMode == False:
self.logInfo('\n\tPATCH: {0}\n\tDATA: {1}\n\tHEADERS: {2}'.format(restApi, data, self.jsonHeader))
try:
response = requests.patch(restApi, data=json.dumps(data), headers=self.jsonHeader, verify=self.verifySsl)
if silentMode == False:
self.logInfo('\tSTATUS CODE: %s' % response.status_code, timestamp=False)
if not str(response.status_code).startswith('2'):
self.logError('Patch error:')
raise IxLoadRestApiException('http PATCH error: {0}\n'.format(response.text))
return response
except requests.exceptions.RequestException as errMsg:
raise IxLoadRestApiException('http PATCH error: {0}\n'.format(errMsg))
def delete(self, restApi, data={}, headers=None, silentMode=False):
"""
Description
A HTTP DELETE function to delete the session.
For Linux API server only.
Parameters
restApi: The REST API URL.
data: The data payload for the URL.
headers: The header to use for the URL.
"""
if headers != None:
self.jsonHeader = headers
if silentMode == False:
self.logInfo('\n\tDELETE: {0}\n\tDATA: {1}\n\tHEADERS: {2}'.format(restApi, data, self.jsonHeader))
try:
response = requests.delete(restApi, data=json.dumps(data), headers=self.jsonHeader, verify=self.verifySsl)
self.logInfo('\tSTATUS CODE: %s' % response.status_code, timestamp=False)
if not str(response.status_code).startswith('2'):
raise IxLoadRestApiException('http DELETE error: {0}\n'.format(response.text))
return response
except requests.exceptions.RequestException as errMsg:
raise IxLoadRestApiException('http DELETE error: {0}\n'.format(errMsg))
# VERIFY OPERATION START
def verifyStatus(self, url, timeout=120):
counter = 0
while True:
response = self.get(url)
#print('\n\tverifyStatus:', response.json())
if 'status' in response.json():
currentStatus = response.json()['status']
elif 'state' in response.json():
currentStatus = response.json()['state']
if currentStatus == 'Error':
errorMessage = 'Operation failed'
if 'message' in response.json():
errorMessage = response.json()['message']
raise IxLoadRestApiException('verifyStatus failed: {}'.format(errorMessage))
else:
raise IxLoadRestApiException('verifyStatus failed: No status and no state in json response')
if currentStatus == 'Error' and 'error' in response.json():
errorMessage = response.json()['error']
raise IxLoadRestApiException('Operation failed: {0}'.format(errorMessage))
if counter <= timeout and currentStatus not in ['Successful']:
self.logInfo('\tCurrent status: {0}. Wait {1}/{2} seconds...'.format(currentStatus, counter, timeout),
timestamp=False)
time.sleep(self.pollStatusInterval)
counter += self.pollStatusInterval
continue
if counter <= timeout and currentStatus in ['Successful']:
return
if counter >= timeout and currentStatus not in ['Successful']:
raise IxLoadRestApiException('Operation failed: {0}'.format(url))
def extractDataModelToFile(self, extractToFilename='dataModel.txt', timeout=120):
"""
Extract the configuration's data model to a file.
"""
url = self.sessionIdUrl + '/ixload/operations/extractDataModelToFile'
if self.osPlatform == 'linux':
response = self.post(url, data={'fullPath': '/mnt/ixload-share/{}'.format(extractToFilename)})
else:
response = self.post(url, data={'fullPath': 'c:\\Results\\{}'.format(extractToFilename)})
operationsId = response.headers['location']
self.verifyStatus(self.httpHeader+operationsId, timeout=timeout)
# LOAD CONFIG FILE
def loadConfigFile(self, rxfFile, uploadConfigFile=None):
"""
Load the IxLoad .rxf config file on the gateway server.
If the config file does not exists on the gateway server, upload
the saved .rxf config file to the IxLoad Gateway server using parameter
uploadConfigFile.
Parameters
rxfFile <str>: Where is the full path .rxf file stored in the IxLoad gateway server.
Windows Ex: 'C:\\Results\\$rxfFile'
# Ignore if using Linux Gateway. Will always use /mnt/ixload-share as the default path.
Linux Gateway Ex: '/mnt/ixload-share/$rxfFile'
uploadConfigFile <None|str>: Default to None.
The local host full path to the .rxf file to upload.
"""
if uploadConfigFile:
self.uploadFile(localPathAndFilename=uploadConfigFile, ixLoadSvrPathAndFilename=rxfFile)
loadTestUrl = self.sessionIdUrl + '/ixLoad/test/operations/loadTest/'
response = self.post(loadTestUrl, data={'fullPath': rxfFile})
# http://x.x.x.x:8080/api/v0/sessions/42/ixLoad/test/operations/loadTest/0
operationsId = response.headers['Location']
status = self.verifyStatus(self.httpHeader + operationsId)
def importCrfFile(self, crfFile, localCrfFileToUpload=None):
"""
1> Upload the local crfFile to the gateway server.
2> Import the .crf config file, which will decompress the .rxf and .tst file.
Parameters
crfFile: The crfFile path either on the gateway server already or the path to put on the gateway server.
If path is c:\\VoIP\\config.crf, then this method will add a timestamp folder in
c:\\VoIP -> c:\\VoIP\\12-14-36-944630\\config.crf
localCrfFileToUpload: If the .crf file is located in a remote Linux, provide the path.
Example: /home/hgee/config.crf
"""
timestampFolder = str(self.getTime()).replace(':', '-').replace('.', '-')
if self.osPlatform == 'windows':
filename = crfFile.split('\\')[-1]
pathOnServer = crfFile.split('\\')[:-1]
if self.osPlatform == 'linux':
filename = crfFile.split('/')[-1]
pathOnServer = crfFile.split('/')[:-1]
pathOnServer = [x for x in pathOnServer if x != '']
pathOnServer.append(timestampFolder) ;# [c:, VoIP, 13-08-28-041835]
self.importConfigPath = pathOnServer
# To delete these timestamp folders after the test is done.
if self.osPlatform == 'linux':
self.importConfigPath = '/'.join(self.importConfigPath)
if self.osPlatform == 'windows':
self.importConfigPath = '\\'.join(self.importConfigPath)
pathOnServer.append(filename) ;# [c:, VoIP, 13-08-28-041835, VoLTE_S1S11_1UE_2APNs_8.50.crf]
if self.osPlatform == 'windows':
pathOnServer = '\\'.join(pathOnServer) ;# c:\\VoIP\\13-08-28-041835\\VoLTE_S1S11_1UE_2APNs_8.50.crf
srcFile = pathOnServer
if self.osPlatform == 'linux':
pathOnServer = '/'.join(pathOnServer) ;# /mnt/ixload-share/13-08-28-041835/VoLTE_S1S11_1UE_2APNs_8.50.crf
pathOnServer = '/'+pathOnServer
srcFile = pathOnServer
self.uploadFile(localCrfFileToUpload, pathOnServer)
destRxf = srcFile.replace('crf', 'rxf')
loadTestUrl = self.sessionIdUrl + '/ixLoad/test/operations/importConfig/'
self.logInfo('\nimportConfig: srcFile: {} destRxf: {}'.format(srcFile, destRxf))
response = self.post(loadTestUrl, data={'srcFile': srcFile, 'destRxf': destRxf})
operationsId = response.headers['Location']
status = self.verifyStatus(self.httpHeader+operationsId)
def deleteImportConfigFolder(self):
try:
sshClient = ConnectSSH(host, username, password)
sshClient.ssh()
stdout = sshClient.enterCommand('rm -rf /mnt/ixload-share/Results/17-12-20-089862')
print(stdout)
except paramiko.ssh_exception.NoValidConnectionsError as errMsg:
print('\nSSH connection failed: {}'.format(errMsg))
def configLicensePreferences(self, licenseServerIp, licenseModel='Subscription Mode'):
"""
licenseModel = 'Subscription Mode' or 'Perpetual Mode'
"""
self.patch(self.sessionIdUrl+'/ixLoad/preferences',
data = {'licenseServer': licenseServerIp, 'licenseModel': licenseModel})
def setPreferences(self, params):
"""
Use the IxLoad API browser for parameters
Example usage:
params = {'enableRestStatViewsCsvLogging': True, 'enableL23RestStatViews': True}
"""
self.patch(self.sessionIdUrl+'/ixLoad/preferences', data=params)
def refreshConnection(self, locationUrl):
url = self.httpHeader+locationUrl+'/operations/refreshConnection'
response = self.post(url)
self.verifyStatus(self.httpHeader + response.headers['location'])
def addNewChassis(self, chassisIpList):
"""
Add a chassis to connect to. If you have multiple chassis's, put them
in a list.
Parameter
chassisIp: <list>: One or more chassis IP addresses in a list.
"""
if type(chassisIpList) == str:
chassisIpList = chassisIpList.split(' ')
self.logInfo('addNewChassis: {}'.format(chassisIpList))
for chassisIp in chassisIpList:
# Verify if chassisIp exists. If exists, no need to add new chassis.
url = self.sessionIdUrl+'/ixLoad/chassisChain/chassisList'
response = self.get(url)
for eachChassisIp in response.json():
if eachChassisIp['name'] == chassisIp:
self.logInfo('\naddNewChassis: Chassis Ip exists in config. No need to add new chassis')
objectId = eachChassisIp['objectID']
# /api/v0/sessions/10/ixLoad/chassisChain/chassisList/1/docs
return eachChassisIp['id'], eachChassisIp['links'][0]['href'].replace('/docs', '')
self.logInfo('addNewChassis: Chassis IP does not exists')
self.logInfo('addNewChassis: Adding new chassisIP: %s:\nURL: %s' % (chassisIp, url))
self.logInfo('addNewChassis: Server synchronous blocking state. Please wait a few seconds ...')
response = self.post(url, data = {"name": chassisIp})
objectId = response.headers['Location'].split('/')[-1]
# /api/v0/sessions/2/ixLoad/chassisChain/chassisList/0
locationUrl = response.headers['Location']
self.logInfo('\nAddNewChassis: locationUrl: %s' % locationUrl)
url = self.httpHeader+locationUrl
self.logInfo('\nAdded new chassisIp Object to chainList: %s' % url)
response = self.get(url)
newChassisId = response.json()['id']
self.logInfo('\naddNewChassis: New Chassis ID: %s' % newChassisId)
self.refreshConnection(locationUrl=locationUrl)
self.waitForChassisIpToConnect(locationUrl=locationUrl)
return newChassisId,locationUrl
def waitForChassisIpToConnect(self, locationUrl):
timeout = 60
for counter in range(1,timeout+1):
response = self.get(self.httpHeader+locationUrl, ignoreError=True)
self.logInfo('waitForChassisIpToConnect response: {}'.format(response.json()))
if 'status' in response.json() and 'Request made on a locked resource' in response.json()['status']:
self.logInfo('API server response: Request made on a locked resource. Retrying %s/%d secs' % (counter, timeout))
time.sleep(1)
continue
status = response.json()['isConnected']
self.logInfo('waitForChassisIpToConnect: Status: %s' % (status), timestamp=False)
if status == False or status == None:
self.logInfo('Wait %s/%d secs' % (counter, timeout), timestamp=False)
time.sleep(1)
if status == True:
self.logInfo('Chassis is connected', timestamp=False)
break
if counter == timeout:
if status == False or status == None:
self.deleteSessionId()
raise IxLoadRestApiException("Chassis failed to get connected")
def assignPorts(self, communityPortListDict):
'''
Usage:
chassisId = Pass in the chassis ID.
If you reassign chassis ID, you must pass in
the new chassis ID number.
communityPortListDict should be passed in as a dictionary
with Community Names mapping to ports in a tuplie list.
communityPortListDict = {
'Traffic0@CltNetwork_0': [(chassisId,1,1)],
'SvrTraffic0@SvrNetwork_0': [(chassisId,2,1)]
}
'''
communityListUrl = self.sessionIdUrl+'/ixLoad/test/activeTest/communityList/'
communityList = self.get(communityListUrl)
failedToAddList = []
communityNameNotFoundList = []
for eachCommunity in communityList.json():
# eachCommunity are client side or server side
currentCommunityObjectId = str(eachCommunity['objectID'])
currentCommunityName = eachCommunity['name']
if currentCommunityName not in communityPortListDict:
self.logInfo('\nNo such community name found: %s' % currentCommunityName)
self.logInfo('\tYour stated communityPortList are: %s' % communityPortListDict, timestamp=False)
communityNameNotFoundList.append(currentCommunityName)
return 1
for eachTuplePort in communityPortListDict[currentCommunityName]:
chassisId,cardId,portId = eachTuplePort
params = {'chassisId':chassisId, 'cardId':cardId, 'portId':portId}
self.logInfo('\nAssignPorts: {0}: {1}'.format(eachTuplePort, params))
url = communityListUrl+str(currentCommunityObjectId)+'/network/portList'
response = self.post(url, data=params, ignoreError=True)
if response.status_code != 201:
failedToAddList.append((chassisId,cardId,portId))
if failedToAddList == []:
return 0
else:
raise IxLoadRestApiException('Failed to add ports:', failedToAddList)
def assignChassisAndPorts(self, communityPortListDict):
"""
Assign ports.
Parameter
communityPortListDict: <list>: A list of community ports. Example shown below.
Usage:
NOTE: Traffic#@Network# are the names from your configuration.
You must know what they are.
If all the ports are in the same chassis:
communityPortList = {
'chassisIp': '192.168.70.128',
'Traffic1@Network1': [(1,1)],
'Traffic2@Network2': [(2,1)]
}
restObj.assignChassisAndPorts([communityPortList])
If ports are on different chassis, create two dicts.
communityPortList1 = {
'chassisIp': '192.168.70.128',
'Traffic1@Network1': [(1,1)]
}
communityPortList2 = {
'chassisIp': '192.168.70.129',
'Traffic2@Network2': [(1,1),
}
restObj.assignChassisAndPorts([communityPortList1, communityPortList2])
"""
if type(communityPortListDict) == dict:
# Make this updated API backward compatible by passing in one dict versus a list.
communityPortListDict = [communityPortListDict]
for communityPorts in communityPortListDict:
# Assign Chassis
chassisIp = communityPorts['chassisIp']
newChassisId, locationUrl = self. addNewChassis(chassisIp)
self.logInfo('assignChassisAndPorts: To new chassis: %s' % locationUrl, timestamp=False)
# Assign Ports
communityListUrl = self.sessionIdUrl+'/ixLoad/test/activeTest/communityList/'
communityList = self.get(communityListUrl)
self.refreshConnection(locationUrl=locationUrl)
self.waitForChassisIpToConnect(locationUrl=locationUrl)
failedToAddList = []
communityNameNotFoundList = []
for eachCommunity in communityList.json():
currentCommunityObjectId = str(eachCommunity['objectID'])
currentCommunityName = eachCommunity['name']
if currentCommunityName not in communityPorts:
continue
if communityNameNotFoundList == []:
for eachTuplePort in communityPorts[currentCommunityName]:
# Going to ignore user input chassisId. When calling addNewChassis(),
# it will verify for chassisIp exists. If exists, it will return the
# right chassisID.
cardId,portId = eachTuplePort
params = {"chassisId":int(newChassisId), "cardId":cardId, "portId":portId}
url = communityListUrl+str(currentCommunityObjectId)+'/network/portList'
self.logInfo('assignChassisAndPorts URL: %s' % url, timestamp=False)
self.logInfo('assignChassisAndPorts Params: %s' % json.dumps(params), timestamp=False)
response = self.post(url, data=params, ignoreError=True)
if response.status_code != 201:
portAlreadyConnectedMatch = re.search('.*has already been assigned.*', response.json()['error'])
if portAlreadyConnectedMatch:
self.logInfo('%s/%s is already assigned' % (cardId,portId), timestamp=False)
else:
failedToAddList.append((newChassisId,cardId,portId))
self.logInfo('\nassignChassisAndPorts failed: %s' % response.text)
if communityNameNotFoundList != []:
raise IxLoadRestApiException
if failedToAddList != []:
if self.deleteSession:
self.abortActiveTest()
raise IxLoadRestApiException('Failed to add ports to chassisIp %s: %s:' % (chassisIp, failedToAddList))
def enableForceOwnership(self, enable=True, enableResetPorts=True):
url = self.sessionIdUrl+'/ixLoad/test/activeTest'
#response = self.patch(url, data={'enableForceOwnership': True})
response = self.patch(url, data={'enableForceOwnership': enable,
'enableResetPorts': enableResetPorts})
def getStatNames(self):
statsUrl = self.sessionIdUrl+'/ixLoad/stats'
self.logInfo('\ngetStatNames: %s\n' % statsUrl)
response = self.get(statsUrl)
for eachStatName in response.json()['links']:
self.logInfo('\t%s' % eachStatName['href'], timestamp=False)
return response.json()
def disableAllStats(self, configuredStats):
configuredStats = self.sessionIdUrl + '/' +configuredStats
response = self.patch(configuredStats, data={"enabled":False})
def enableConfiguredStats(self, configuredStats, statNameList):
'''
Notes: Filter queries
.../configuredStats will re-enable all stats
.../configuredStats/15 will only enable the stat with object id = 15
.../configuredStats?filter="objectID le 10" will only enable stats with object id s lower or equal to 10
.../configuredStats?filter="caption eq FTP" will only enable stats that contain FTP in their caption name
'''
for eachStatName in statNameList:
configuredStats = configuredStats + '?filter="caption eq %s"' % eachStatName
self.logInfo('\nEnableConfiguredStats: %s' % configuredStats)
response = self.patch(configuredStats, data={"enabled": True})
def showTestLogs(self, showContinuously=False, interval=5):
"""
Show all test logs.
Parameters
showContinuously <bool>: True=Show logs continuously. False=Show once and return.
interval <int>: The wait time in seconds between each pull.
"""
testLogUrl = self.sessionIdUrl+'/ixLoad/test/logs'
while True:
response = self.get(testLogUrl)
for eachLogEntry in response.json():
self.logInfo('\t{time}: Severity:{severity} ModuleName:{moduleName} {message}'.format(
time=eachLogEntry['timeStamp'],
severity=eachLogEntry['severity'],
moduleName=eachLogEntry['moduleName'],
message=eachLogEntry['message']),
timestamp=False)
if showContinuously:
self.logInfo('showTestLogs: Wait {} seconds'.format(interval))
time.sleep(interval)
else:
break
def runTraffic(self):
runTestUrl = self.sessionIdUrl+'/ixLoad/test/operations/runTest'
response = self.post(runTestUrl)
operationsId = response.headers['Location']
self.verifyStatus(self.httpHeader+operationsId, timeout=300)
def getTestStatus(self, operationsId):
'''
status = "Not Started|In Progress|successful"
state = "executing|finished"
'''
testStatusUrl = self.sessionIdUrl+'/ixLoad/test/operations/runTest/'+str(operationsId)
response = self.get(testStatusUrl)
return response
def getActiveTestCurrentState(self, silentMode=False):
# currentState: Configuring, Starting Run, Running, Stopping Run, Cleaning, Unconfigured
url = self.sessionIdUrl+'/ixLoad/test/activeTest'
response = self.get(url, silentMode=silentMode)
if response.status_code == 200:
return response.json()['currentState']
def getStats(self, statUrl):
response = self.get(statUrl, silentMode=True)
return response
def getTestResults(self):
"""
To get test results, you must call pollStatsAndCheckStats() from the script.
Test results are set in pollStatsAndCheckStatResults()
HTTPClient
Passed: TCP Connections Established
Passed: HTTP Simulated Users
Passed: HTTP Connections
Passed: HTTP Transactions
Passed: HTTP Connection Attempts
HTTPServer
Passed: TCP Connections Established
Passed: TCP Connection Requests Failed
Result: Passed|Failed
Return
A dictionary of all the statNames and passed/failed results
"""
if self.testResults is None:
return
finalResult = 'Passed'
self.logInfo('\nTest result for each statistic:\n{}'.format('-'*31), timestamp=False)
for statType in self.testResults.keys():
if statType == 'result':
continue
self.logInfo('\n{}'.format(statType), timestamp=False)
if isinstance((self.testResults[statType]), dict):
for statName,result in self.testResults[statType].items():
self.logInfo('\t{}: {}'.format(result, statName), timestamp=False)
if result == 'Failed':
finalResult = 'Failed'
self.testResults['result'] = finalResult
self.logInfo('\nFinal Result: {}'.format(finalResult), timestamp=False)
return self.testResults
def pollStatsAndCheckStatResults(self, statsDict=None, pollStatInterval=2, csvFile=False,
csvEnableFileTimestamp=True, csvFilePrependName=None, exitAfterPollingIteration=None):
'''
Get run time stats and evaluate the stats with an operator and the expected value.
Due to stats going through ramp up and ramp down, stats will fluctuate.
Once the stat hits and maintains the expected threshold value, the stat is marked as passed.
If evaluating stats at run time is not what you need, use PollStats() instead shown.
statsDict =
This API will poll stats based on the dictionary statsDict that you passed in.
Example how statsDict should look like:
Example:
# operator options: <, >, <=, >=
statsDict = {
'HTTPClient': [{'caption': 'TCP Connections Established', 'operator': '>', 'expect': 60},
{'caption': 'HTTP Simulated Users', 'operator': None, 'expect': None},
{'caption': 'HTTP Connections', 'operator': '>=', 'expect': 300},
{'caption': 'HTTP Transactions', 'operator': '>', 'expect': 190},
{'caption': 'HTTP Connection Attempts', 'operator': '>', 'expect': 300}
],
'HTTPServer': [{'caption': 'TCP Connections Established', 'operator': '>', 'expect': 1000},
{'caption': 'TCP Connection Requests Failed', 'operator': '<', 'expect': 1}
]
}
The exact name of the above stats could be found in the API browser or by doing a ScriptGen on the GUI.
If doing by ScriptGen, do a wordsearch for "statlist". Copy and Paste the stats that you want.
csvFile: To enable or disable recording stats on csv file: True or False
csvEnableFileTimestamp: To append a timestamp on the csv file so they don't overwrite each other: True or False
csvFilePrependName: To prepend a name of your choice to the csv file for visual identification and if you need
to restart the test, a new csv file will be created. Prepending a name will group the csv files.
exitAfterPollingIteration: Stop polling for stats after the specified iteration.
Default = None, which polls for stats until the test is done.
An iteration means a cycle of all the stats.
'''
self.testResults = dict()
# Make all stats as failed. If stat hits the expected value,
# then result is changed to passed.
self.testResults['result'] = 'Failed'
for statType in statsDict.keys():
self.testResults[statType] = dict()
for captionMetas in statsDict[statType]:
# CAPTION: {'caption': 'TCP Connections Established', 'operator': '>', 'expect': 60}
self.testResults[statType].update({captionMetas['caption']: 'Failed'})
import operator
# Not going to handle = and != because the intention is to handle hitting and maintaining the expected threshold only
operators = {'>': operator.gt,
'<': operator.lt,
#'=': operator.eq,
#'!=': operator.ne,
'<=': operator.le,
'>=': operator.ge
}
versionMatch = re.match('([0-9]+\.[0-9]+)', self.ixLoadVersion)
if float(versionMatch.group(1)) < float(8.5):
# If ixLoad version is < 8.50, there is no rest api to download stats.
# Default to creating csv stats from real time stats.
csvFile = True
if csvFile:
import csv
csvFilesDict = {}
for key in statsDict.keys():
fileName = key
fileName = fileName.replace("(", '_')
fileName = fileName.replace(")", '_')
if csvFilePrependName:
fileName = csvFilePrependName+'_'+fileName
csvFilesDict[key] = {}
if csvEnableFileTimestamp:
import datetime
timestamp = datetime.datetime.now().strftime('%H%M%S')
fileName = '{}_{}'.format(fileName, timestamp)
fileName = fileName+'.csv'
csvFilesDict[key]['filename'] = fileName
csvFilesDict[key]['columnNameList'] = []
csvFilesDict[key]['fileObj'] = open(fileName, 'w')
csvFilesDict[key]['csvObj'] = csv.writer(csvFilesDict[key]['fileObj'])
# Create the csv top row column name list
for statType in statsDict.keys():
for captionMetas in statsDict[statType]:
csvFilesDict[statType]['columnNameList'].append(captionMetas['caption'])
csvFilesDict[statType]['csvObj'].writerow(csvFilesDict[statType]['columnNameList'])
waitForRunningStatusCounter = 0
waitForRunningStatusCounterExit = 120
pollStatCounter = 0
while True:
currentState = self.getActiveTestCurrentState(silentMode=True)
self.logInfo('ActiveTest current status: %s. ' % currentState)
if currentState == 'Running':
if statsDict == None:
time.sleep(1)
continue
# statType: HTTPClient or HTTPServer (Just a example using HTTP.)
# statNameList: transaction success, transaction failures, ...
for statType in statsDict.keys():
self.logInfo('\n%s:' % statType, timestamp=False)
statUrl = self.sessionIdUrl+'/ixLoad/stats/'+statType+'/values'
response = self.getStats(statUrl)
highestTimestamp = 0
# Each timestamp & statnames: values
for eachTimestamp,valueList in response.json().items():
if eachTimestamp == 'error':
raise IxLoadRestApiException('pollStats error: Probable cause: Misconfigured stat names to retrieve.')
if int(eachTimestamp) > highestTimestamp:
highestTimestamp = int(eachTimestamp)
if highestTimestamp == 0:
time.sleep(3)
continue
if csvFile:
csvFilesDict[statType]['rowValueList'] = []
# Get the interested stat names only
for captionMetas in statsDict[statType]:
# HTTPServer: [{'caption': 'TCP Connections Established', 'operator': '>', 'expect': 1000},
# {'caption': 'TCP Connection Requests Failed', 'operator': '=', 'expect': 0}]
statName = captionMetas['caption']
if statName in response.json()[str(highestTimestamp)]:
statValue = response.json()[str(highestTimestamp)][statName]
if statValue == "N/A" or statValue == "":
continue
self.logInfo('\t%s: %s' % (statName, statValue), timestamp=False)
if csvFile:
csvFilesDict[statType]['rowValueList'].append(statValue)
# Verify passed/failed objectives
if captionMetas['operator'] is not None or captionMetas['expect'] is not None:
op = operators.get(captionMetas['operator'])
# Check user defined operator for expectation
# Example: operator.ge(3,3)
if op(int(statValue), int(captionMetas['expect'])) == False:
if self.testResults[statType][statName] == 'Failed':
self.logInfo('\t\tThreshold not reached: Expecting: {}{}\n'.format(captionMetas['operator'], int(captionMetas['expect'])), timestamp=False)
if self.testResults[statType][statName] == 'Passed':
self.logInfo('\t\tThreshold reached and sustaining: Expecting: {}{}\n'.format(captionMetas['operator'], int(captionMetas['expect'])), timestamp=False)
if op(int(statValue), int(captionMetas['expect'])) == True:
if self.testResults[statType][statName] == 'Failed':
self.logInfo('\t\tThreshold reached: Expecting: {}{}\n'.format(captionMetas['operator'], int(captionMetas['expect'])), timestamp=False)
if self.testResults[statType][statName] == 'Passed':
self.logInfo('\t\tThreshold reached and sustaining: Expecting: {}{}\n'.format(captionMetas['operator'], int(captionMetas['expect'])), timestamp=False)
self.testResults[statType].update({statName: 'Passed'})
else:
self.logInfo('\t\tNo expectation defined\n', timestamp=False)
else: