-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLoadCoreLib.py
executable file
·2210 lines (1791 loc) · 104 KB
/
LoadCoreLib.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
"""
LoadCoreLib.py
DESCRIPTION:
A framework that executes LoadCore .json config files, reconfiguration if necessary,
start test, get stat, download results and generate a test_summary.yml report.
This framework reads a Yaml file that contains information on which .json file to load and
which KPIs to analyze at runtime.
Each Yaml file represents a test case. You could put all Yaml files in
a folder and state the folder for the perameter -testcases and this will run all
Yaml testcase files inside the folder.
RESULTS FOLDER:
Each test gets its own top-level results folder with a timestamp: Ex: KeysightTestResults_<timestamp>.
- Each test case gets its own result folder
- Each test has a test_summary.yml file, CSV and JSON KPI results and log file
- mainDebugLog
PARAMETERS:
-env: Details on IP addresses, login credentials, global variables
-testcases: A folder of yaml files. This script will run all yaml files in a folder.
You could pass in more than one folder and you could mix folders and individual yaml files.
RECONFIGURATION:
To modify configurations, create a python file and store all individual reconfigurations
in its own function. This main script will pass the main object to the reconfiguration file
in order to call functions in LoadCoreMWAssistant.py.
Look at this for sample: ReconfigureLoadCoreFiles/reconfigLoadCore.py
In the testcase yaml file, all configurations go in the configs field:
configs:
reconfigureLoadCoreFiles:
- /path/ReconfigurationScripts/reconfigLoadCore.py
# Configuration details to support calling reassignAgents()
agentsDict:
ran: 172.16.1.14
nrf: 172.16.1.14
udm: 172.16.1.14
pcf: 172.16.1.14
udr: 172.16.1.14
smf: 172.16.1.14
upf: 172.16.1.14
amf: 172.16.1.14
ausf: 172.16.1.14
nssf: 172.16.1.14
dn:
- agent: 172.16.1.41
n6: ens33
# Configuration details to support calling changeNetworkSettings()
changeNetworkSettings: [{agentIp: 172.16.1.14, interface: ens33, portCapture: True},
{agentIp: 172.16.1.41, interface: ens33, portCapture: True}
]
"""
import requests, sys, os, json, time, platform, re, yaml, subprocess, traceback
import datetime, shutil
from pprint import pformat, pprint
from keystackUtilities import readJson, writeToJson, getTimestamp, getDictItemFromList, makeFolder
# 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)
class Logger():
def logMsg(self, msgType, msg, includeTimestamp=True):
"""
Print message to stdout and append the message to a log file.
Parameter
msgType <str>: info|debug|error
msg <str>: The message for stdout.
"""
if includeTimestamp:
timestamp = str(datetime.datetime.now()).split(' ')[1]
stdout = f'\n{timestamp}: [{msgType}]: {msg}'
else:
stdout = msg
print(stdout)
self.writeToLogFile(msg=f'{stdout}\n', logType='a')
def logInfo(self, msg, includeTimestamp=True):
self.logMsg('info', msg, includeTimestamp=includeTimestamp)
def logWarning(self, msg):
self.logMsg('warning', msg)
def logDebug(self, msg):
self.logMsg('debug', msg)
def logError(self, msg):
self.logMsg('error', msg)
raise Exception(f'Aborting test: {msg}')
# Note: self.debugLogFile is set in class MW()
def writeToLogFile(self, msg, logType='a'):
if self.debugLogFile:
with open(self.debugLogFile, logType) as logFile:
logFile.write(msg)
class Requests(Logger):
def get_requests(self):
if self.httpv2:
s = requests.Session()
s.mount(self.baseurl, HTTP20Adapter())
s.verify = False
return s
else:
return requests
def get(self, url, params=None, headers=None, stream=False):
if self.debugMode == False:
self.logInfo(f'\nGET: {self.baseurl}{url}\nPARAMS: {params}')
else:
self.logInfo(f'\nGET: {self.baseurl}{url}\nPARAMS: {params}\nHEADERS: {headers}')
response = self.get_requests().get('%s%s' % (self.baseurl, url), params=params, headers=headers, verify=False,
stream=stream)
self.logInfo(f'STATUS: {response.status_code}', includeTimestamp=False)
return response
def getInfoFromURL(self, url, params=None, headers=None):
self.logInfo(f'\nGetInforFromUrl: {self.baseurl}{url}\nPARAMS: {params}')
return self.get_requests().get('%s' % url, params=params, headers=headers, verify=False)
def put(self, url, data, headers=None):
if self.debugMode == False:
self.logInfo(f'\nPUT: {self.baseurl}{url}\nDATA: {data}')
else:
self.logInfo(f'\nPUT: {self.baseurl}{url}\nDATA: {data}\nHEADERS: {headers}')
response = self.get_requests().put('%s%s' % (self.baseurl, url), data=(None if data is None else json.dumps(data)),
headers=headers, verify=False)
self.logInfo(f'STATUS: {response.status_code}', includeTimestamp=False)
return response
def putText(self, url, data, headers=None):
self.logInfo(f'\nPUTTEXT: {self.baseurl}{url}\nDATA: {data}')
return self.get_requests().put('%s%s' % (self.baseurl, url), data=data, headers=headers, verify=False)
def post(self, url, data=None, headers=None):
if self.debugMode == False:
self.logInfo(f'\nPOST: {self.baseurl}{url}\nDATA: {json.dumps(data)}\nHEADERS: {headers}')
else:
self.logInfo(f'\nPOST: {self.baseurl}{url}\nDATA: {json.dumps(data)}')
response = self.get_requests().post('%s%s' % (self.baseurl, url), data=(None if data is None else json.dumps(data)),
headers=headers, verify=False)
self.logInfo(f'STATUS: {response.status_code}', includeTimestamp=False)
return response
def patch(self, url, data, headers=None):
if self.debugMode == False:
self.logInfo(f'\nPATCH: {self.baseurl}{url}\nDATA: {data}')
else:
self.logInfo(f'\nPATCH: {self.baseurl}{url}\nDATA: {data}\nHEADERS: {headers}')
response = self.get_requests().patch('%s%s' % (self.baseurl, url),
data=(None if data is None else json.dumps(data)), headers=headers,
verify=False)
self.logInfo(f'STATUS: {response.status_code}', includeTimestamp=False)
return response
def delete(self, url, headers=None):
self.logInfo(f'\nDELETE: {self.baseurl}{url}')
response = self.get_requests().delete('%s%s' % (self.baseurl, url), headers=headers, verify=False)
self.logInfo(f'STATUS: {response.status_code}', includeTimestamp=False)
return response
def post_archive(self, url, data=None, headers=None):
headers["Content-Type"] = "application/zip"
return self.get_requests().post('%s%s' % (self.baseurl, url), data=(None if data is None else data),
headers=headers, verify=False)
def getS3(self, url, params=None, headers=None, stream=False):
if MW.debugMode == False:
self.logInfo(f'\nGET-AWS-S3: {url}\nPARAMS: {params}')
else:
self.logInfo(f'\nGET-AWS-S3: {url}\nPARAMS: {params}\nHEADERS: {headers}')
response = self.get_requests().get(url, params=params, headers=headers, verify=False, stream=stream)
self.logInfo(f'STATUS: {response.status_code}', includeTimestamp=False)
return response
def putS3(self, url, data, headers=None):
self.logInfo(f'\nPUT-AWS-S3: {url}\nDATA: {data}\nHEADERS: {headers}')
response = self.get_requests().put(url, data=data, headers=headers, verify=False)
self.logInfo(f'STATUS: {response.status_code}', includeTimestamp=False)
return response
class Utils(Requests):
def getTimestamp(self):
today = datetime.datetime.now()
return today.strftime("%m-%d-%Y-%H:%M:%S")
def waitForState(self, what, equalToWhat, timeout):
while timeout > 0:
try:
self.logInfo(f'Utils:waitForState: what={what} equalToWhat={equalToWhat}')
if what != equalToWhat:
self.logError('Utils:waitForState: %s != %s'.format(what, equalToWhat))
return True
except:
timeout -= 0.2
time.sleep(0.2)
else:
print("Timed out after %s seconds" % (10 - timeout))
return False
def createFolder(self, fullPath):
"""
Create a folder if it doesn't exists
Parameter
fullPath <str>: The full path and the folder name
"""
if not os.path.exists(fullPath):
#os.makedirs(fullPath)
makeFolder(fullPath)
def convertCsvFileToJsonFile(self, csvFilePath, jsonFilePath):
import csv
jsonArray = []
#read csv file
with open(csvFilePath, encoding='utf-8') as csvf:
#load csv file data using csv library's dictionary reader
#csvReader = csv.DictReader(csvf)
csvReader = csv.reader(csvf)
#convert each csv row into python dict
for row in csvReader:
#add this python dict to json array
jsonArray.append(row)
#convert python jsonArray to JSON String and write to file
try:
with open(jsonFilePath, 'w', encoding='utf-8') as jsonf:
jsonString = json.dumps(jsonArray, indent=4)
jsonf.write(jsonString)
os.chmod(jsonFilePath, 0o774)
return True
except Exception as errMsg:
self.logWarning(f'convertCsvFileToJson failed: {errMsg}')
return False
def readCsvFile(self, csvFile):
import csv
with open(csvFile, mode='r', encoding='utf-8-sig') as file:
csvContents = csv.DictReader(file)
csvData = dict()
for row in csvContents:
csvData[row['Test No']] = dict()
for key,value in row.items():
if key == '':
continue
#print(f'key={key} value={value}')
valueList = []
for eachValue in value.split('\n'):
if eachValue == '':
continue
valueList.append(eachValue)
csvData[row['Test No']].update({key: valueList})
return csvData
class LoadCoreLicense(Logger):
def __init__(self, licenseServerIp, port='7443', user='admin', password='admin', testcaseLogFile=None):
self.licsenseServerIp = f'{licenseServerIp}:{port}'
self.user = user
self.password = password
self.urlBase = f'https://{licenseServerIp}:{port}'
self.headers = {'Content-Type': 'application/x-www-form-urlencoded'}
self.session = requests.session()
# For Logger
self.debugLogFile = testcaseLogFile
# LoadCore license server doesn't return a token to use for future REST execution.
# It uses persistant cookie. The requests.session() will hold the sesssion
try:
self.connect()
except Exception as errMsg:
raise Exception(errMsg)
def get(self, url, params=None, verify=False):
self.logInfo(f'\nGET URL: {url}', includeTimestamp=False)
self.logInfo(f'PARAMS: {params}', includeTimestamp=False)
self.logInfo(f'HEADERS: {self.headers}', includeTimestamp=False)
try:
response = self.session.request('GET', url, params=params, headers=self.headers, verify=verify)
except Exception as errMsg:
raise Exception(f'LoadCoreLicense GET: {errMsg}')
if response.status_code != 200:
raise Exception(f'LoadCoreLicense() GET: Failed.')
return response
def post(self, url, data=None, verify=False):
self.logInfo(f'\nPOST URL: {url}', includeTimestamp=False)
self.logInfo(f'DATA: {data}', includeTimestamp=False)
self.logInfo(f'HEADERS: {self.headers}', includeTimestamp=False)
try:
response = self.session.request('POST', url, data=data, headers=self.headers, verify=verify)
except Exception as errMsg:
raise Exception(f'LoadCoreLicense POST: {errMsg}')
if response.status_code != 200:
raise Exception(f'LoadCoreLicense() POST: Failed.')
return response
def connect(self):
url = f'{self.urlBase}/rest/license/login'
data = {'userid': self.user, 'password': self.password}
try:
self.post(url, data)
except Exception as errMsg:
return errMsg
def getLicenseDetails(self):
response = self.get(f'{self.urlBase}/rest/license/floatingStats')
return response
def showLicenseDetails(self):
response = self.getLicenseDetails()
pprint(response.json()['payload']['floatingFeatureStats'])
def checkForLicenses(self, requiredLicenses):
"""
login to license server to get license avaialability
POST https://<ip>:7443/rest/license/login data={'userid': 'admin', 'password': 'admin'}
GET https://<ip>:7443/rest/license/floatingStats check the installedCount, availableCount.
"""
response = self.getLicenseDetails()
licenseFailures = []
if response.status_code == 200 and requiredLicenses:
for eachRequiredLicense in requiredLicenses:
licenseFeatureName = list(eachRequiredLicense.keys())[0]
requiredLicenseCount = list(eachRequiredLicense.values())[0]
for eachLicense in response.json()['payload']['floatingFeatureStats']:
if eachLicense['featureName'] == licenseFeatureName:
availableCount = int(eachLicense['availableCount'])
installedCount = int(eachLicense['installedCount'])
self.logInfo(f'\nLoadCore license is available: {eachLicense["featureName"]} available:{availableCount} installedCount={installedCount}')
if availableCount == 0:
licenseFailures.append({'RequiredLicenseFeatureName':licenseFeatureName,
'RequiredCount': requiredLicenseCount,
'availableCount': availableCount,
'installedCount': installedCount})
return licenseFailures
class MW(Utils):
# These variables are for Logger and LoadCoreAssistantException
debugMode = False
debugLogFile = None
def __init__(self, host='localhost', port=443, username='admin', password='admin',
authToken=None, licenseServer=None, protocol='https', login=True,
enablehttp2=False, logLevel='debug', debugMode=False, testcaseLogFile=None,
testcaseResultsFolder=None, testcaseName=None, keystackObj=None):
"""
This class works in conjunction with runLoadCore.py
Parameters
testcasesLogFile <str>: A testcase log file must be created already. Full path to the log file name.
testcaseResultsFolder <str>: Full path to the folder for all result files to be stored.
testcaseName <str>: Used for naming the PDF report and CSV file.
login <bool>: Sometimes a LoadCore private build has no login. In this case, don't abort test if connection failed
"""
self.keystackObj = keystackObj
self.host = host
self.port = port
self.protocol = protocol
self.process = None
self.baseurl = '%s://%s:%d' % (self.protocol, self.host, self.port)
self.httpv2 = enablehttp2
self.licenseServer = licenseServer
self.licenseServerType = keystackObj.moduleProperties['envParams']['licenseServerType']
self.logLevel = logLevel
self.sessionId = None
self.username = username
self.password = password
self.connectedSuccessfully = False
if login:
# Sometimes a LoadCore private build has no login.
# In this case, don't abort test if connection failed
apiKey = self.getToken()
else:
self.connectedSuccessfully = True
apiKey = None
self.headers = {'authorization': apiKey}
self.debugMode = debugMode
self.debugLogFile = testcaseLogFile
self.testcaseResultsFolder = testcaseResultsFolder
self.testcaseName = testcaseName
self.testId = None
def getToken(self):
try:
apiPath = '/auth/realms/keysight/protocol/openid-connect/token'
self.headers = {'Content-Type': 'application/x-www-form-urlencoded'}
payload = { "grant_type" : "password", "username" : self.username, "password": self.password, "client_id": "clt-wap" }
# use requests.post because payload is not json format as it is used in self.post()
response = requests.post(self.baseurl + apiPath, data=payload, headers=self.headers, verify=False)
print('auth_token: {}'.format(response.json()['access_token']))
self.connectedSuccessfully = True
except Exception as e:
self.logError(f'getToken: Connecting to Loadcore MW failed: {self.baseurl}')
return None
return response.json()["access_token"]
def newSession(self, configName=None, configID=None, configJson=None, configArchive=None,
statusCode=201, sessionType='fullCore'):
"""
:param configName:
:param configID: specify a configID to create a new config and load the config with configID
:param config: config in json format that will be uploaded and attached to the new session
:return: new session ID
"""
if sessionType == "fullCore":
configType = "wireless-fullcore-config"
if (configName == None and configJson == None and configID == None and configArchive == None):
self.config = {"ConfigUrl": configType}
elif configID != None:
self.config = {"ConfigUrl": configID}
elif (configName != None):
# in this case create a new config by loading a specified config name
self.config = self.selectConfig(configName)
uploadedConfig = self.uploadConfig(config=self.config)
self.config = {"ConfigUrl": uploadedConfig[0]['id']}
elif (configJson != None):
uploadedConfig = self.uploadConfig(config=configJson)
self.config = {"ConfigUrl": uploadedConfig[0]['id']}
elif configArchive != None:
uploadedConfig = self.uploadConfig(configArchive=configArchive)
self.config = {"ConfigUrl": uploadedConfig[0]['id']}
else:
self.logError("NewSession: Unhandled case")
response = self.post('/api/v2/sessions', self.config, headers=self.headers)
if response.status_code == 201:
self.logDebug(pformat(response.json()))
self.sessionId = response.json()[0]['id']
if 'wireless' not in self.sessionId:
self.logError('Failed to create new session: {}'.format(self.sessionId))
return response
else:
self.logError(f'newSession failed. Connecting to MW status code={response.status_code}')
def deleteSession(self, statusCode=204):
if self.sessionId is None:
return
response = self.delete('/api/v2/sessions/{0}'.format(self.sessionId), headers=self.headers)
# print response
assert response.status_code == statusCode
if '200' in str(response.status_code):
assert (True if self.sessionId not in self.getAllSessions() else False)
return response
elif '204' in str(response.status_code):
assert (True if self.sessionId not in self.getAllSessions() else False)
return response
else:
self.logDebug(pformat(response))
return response.status_code
def getAllSessions(self):
response = self.get('/api/v2/sessions', headers=self.headers)
assert response.status_code == 200
sessions = []
for item in response.json():
sessions.append(item['id'])
return sessions
def getSessionInfo(self, status_code=200):
response = self.get('/api/v2/sessions/{0}'.format(self.sessionId), headers=self.headers)
assert response.status_code == status_code
return response.json()
def getSessionStatus(self):
response = self.get('/api/v2/sessions/{0}/test'.format(self.sessionId), headers=self.headers)
assert response.status_code == 200
return response.json()['status']
def isSessionStarted(self):
response = self.get('/api/v2/sessions/{0}/test'.format(self.sessionId), headers=self.headers)
assert response.status_code == 200
return True if response.json()['status'] == 'Started' else False
def pickExistingSession(self, wildcard):
try:
self.assertGreater(self.newSessionID, 0)
return self.newSessionID
except:
allSessions = self.getAllSessions()
for session in allSessions:
if wildcard in session:
return session
def uploadConfig(self, config=None, configArchive=None, statusCode=201):
"""
:param config: in json format
:return:
"""
currentTestcase = self.keystackObj.moduleSummaryData['currentlyRunning']
if config != None:
response = self.post('/api/v2/configs', data=config, headers=self.headers)
# self.logger.debug(pformat(response.content))
#self.logger.debug(pformat(response.reason))
#self.testcase.assertEquals(response.status_code, statusCode)
return response.json()
if configArchive != None:
with open(configArchive, 'rb') as f:
# Replace f here
if 'modifyLoadCoreJsonConfigs' in self.keystackObj.testcaseDict[currentTestcase]:
# read the loadcore json config in memory and replace
# zip: /opt/KeystackTests/Modules/LoadCore/ExportedConfigs/sample_fullCore.zip
for eachChange in self.keystackObj.testcaseDict[currentTestcase]['modifyLoadCoreJsonConfigs']:
try:
f.update(eachChange)
except Exception as errMsg:
raise Exception(f'uploadConfig(): Modifying json config failed: {errMsg}')
response = self.post_archive('/api/v2/configs',data=f, headers=self.headers)
# self.logger.debug(pformat(response.content))
#self.logger.debug(pformat(response.reason))
#self.testcase.assertEquals(response.status_code, statusCode)
self.configId = response.json()[0]['id']
return response.json()
def getUploadedConfig(self, configID, statusCode=200):
response = self.get('/api/v2/configs/{0}'.format(configID), headers=self.headers)
#assert response.status_code == statusCode
if response.status_code != statusCode:
self.logError(f'getUploadedConfig failed: {response.json()["message"]}')
return response.json()
def getAllAgents(self):
"""
:return: a list of agents
"""
response = self.get('/api/v2/agents', headers=self.headers)
#assert response.status_code == 200
if response.status_code != 200:
self.logError(f'getAllAgents failed: {response.json()["message"]}')
return response.json()
def getAgentInfo(self, agentID):
response = self.get('/api/v2/agents/{0}'.format(agentID), headers=self.headers)
if response.status_code != 200:
self.logError(f'getAgentInfo failed: {response.json()["message"]}')
if len(response.json()['id']) > 0:
return response.json()
else:
return None
def getAgentIP(self, agentID):
response = self.getAgentInfo(agentID)
return response['IP']
def rebootAgents(self, agentIdList=None):
"""
Reboot a list of agent IDs.
Parameters
agentIdList <list>: {"agents":[{"agentId":"<agent-id>"}]}
"""
if agentIdList is None:
agentIdList = []
allAgentInfo = self.getAllAgents()
for agent in allAgentInfo:
agentId = agent['id']
agentInfo = self.getAgentInfo(agentId)
agentIp = agentInfo['IP']
if 'agents' in self.keystackObj.moduleProperties['envParams'] and \
agentIp in self.keystackObj.moduleProperties['envParams']['agents']:
agentIdList.append({"agentId": agentId})
else:
continue
self.logInfo(f'rebootAgents: {agentIdList}')
response = self.post(url='/api/v2/agents/operations/reboot', data={"agents": agentIdList}, headers=self.headers)
if response.status_code != 202:
self.logError(f'Rebooting agents failed on LoadCore MW with status code {response.status_code}: {response.json()["message"]}')
# After rebooting agents, need to wait for agent operation status == SUCCESS
operationStatusUrl = '/api/v2/agents/operations/reboot/{}'.format(response.json()['id'])
counter = 0
timeout = 160
while True:
response = self.get(operationStatusUrl, headers=self.headers)
status = response.json()['state']
if counter < timeout and status != 'SUCCESS':
self.logInfo(f'rebootAgents: Waiting for reboot status=SUCCESS. Current status={status}. {counter}/{timeout} seconds')
counter += 1
time.sleep(1)
if counter < timeout and status == 'SUCCESS':
break
if counter == timeout and status != 'SUCCESS':
self.logDebug(f'rebootAgents: Waited {counter}/{timeout} seconds. Reboot status = {status}.')
# If using LoadCore on a laptop for development, agents take longer to reboot because of limited resources.
# The MW timeout is 5 seconds short. Agents actually might've booted successfully.
# Solution: Call verifyAllAgentsStatusUp(). If agents go from OFFLINE state to the STOPPED state, then they're up.
if self.verifyAllAgentsStatusUp() == True:
break
def verifyAllAgentsStatusUp(self):
"""
Before starting the test, verify if the agents are in the STOPPED status.
If not, reboot them and verify for STOPPED status.
Raise an exception to abort the test if the agents are not in the STOPPED status.
"""
agentIdRebootList = []
allAgentInfo = self.getAllAgents()
allAgents = []
for agent in allAgentInfo:
agentId = agent['id']
agentInfo = self.getAgentInfo(agentId)
if 'agents' in self.keystackObj.moduleProperties['envParams']:
# The middleware could have many agents attached, but not all agents are
# for this test environment. We only care for agents relevant for the test.
if agentInfo['IP'] not in self.keystackObj.moduleProperties['envParams']['agents']:
#self.logInfo(f'Discovered agent {agentInfo["IP"]}, but it is not part of this test environment. Excluding verification')
continue
# For the below while loop
allAgents.append(agentInfo['IP'])
self.logInfo(f'verifyAllAgentsStatusUp: Agent {agentInfo["IP"]} current status: {agentInfo["Status"]}')
if agentInfo['Status'] != "STOPPED":
agentIdRebootList.append({"agentId": agentId})
if len(agentIdRebootList) == 0:
# rebootAgents() could be calling this function and expecting a return value
# of True to indicate that all agents are up.
return True
if agentIdRebootList:
timeout = 150
counter = 0
self.logInfo(f'verifyAllAgentsStatusUp: Total agents in LoadCore: {allAgents}')
while True:
counter += 1
allAgentInfo = self.getAllAgents()
for agent in allAgentInfo:
agentId = agent['id']
agentIp = agentInfo['IP']
agentInfo = self.getAgentInfo(agentId)
if agentIp in allAgents:
if agentInfo['Status'] == "STOPPED" and counter < timeout:
self.logInfo(f'Agent {agentIp} is up')
index = allAgents.index(agentIp)
allAgents.pop(index)
if len(allAgents) == 0:
self.logInfo('verifyAllAgentsStatusUp: All agents are up and ready for testing')
return True
self.logInfo(f'verifyAllAgentsStatusUp: {counter}/{timeout} secs: status={agentInfo["Status"]} Waiting for remaining agents: {allAgents}')
time.sleep(1)
if agentInfo['Status'] != "STOPPED" and counter < timeout:
self.logInfo(f'verifyAllAgentsStatusUp: {counter}/{timeout} secs: Agent={agentIp}: {agentInfo["Status"]}')
time.sleep(1)
continue
if agentInfo['Status'] != "STOPPED" and len(allAgents) != 0 and counter == timeout:
self.logError(f'verifyAllAgentsStatusUp: {counter}/{timeout} secs: Some agents are not ready for testing. Please troubleshoot the following agents: {allAgents}')
def getSessionConfig(self, statusCode=200):
response = self.get('/api/v2/sessions/{0}/config?include=all'.format(self.sessionId), headers=self.headers)
assert response.status_code == statusCode
return response.json()
def selectConfig(self, configName):
# Don't force people to put their config files in this folder structure
# configFileName = 'configs/{0}.json'.format(configName)
if '.json' in configName:
configFileName = configName
else:
configFileName = '{0}.json'.format(configName)
self.logInfo('Selected config file to load: {}'.format(configFileName))
assert os.path.isfile(configFileName)
file = open(configFileName)
config = file.read()
file.close()
configJson = json.loads(config)
return configJson
def setSessionConfig(self, config, statusCode=200):
self.headers.update({'Content-Type': 'application/json',
'Accept': '*/*',
'Cache-Control': 'no-cache',
'Host': '{0}'.format(self.host),
'Accept-Encoding': 'gzip, deflate',
'Referer': 'http://{0}/api/v2/sessions'.format(self.host),
'Postman-Token': '009256e4-5703-4564-8526-adfe3567fecd',
'User-Agent': 'PostmanRuntime/7.16.3',
'Connection': 'keep-alive'})
if 'configData' in config:
config = config['configData']['Config']
response = self.put('/api/v2/sessions/{0}/config/config'.format(self.sessionId), data=config,
headers=self.headers)
self.logDebug(pformat(response.content))
self.logDebug(pformat(response.reason))
assert response.status_code == statusCode
#self.configId = response.json()['config-id']
try:
return response.json()
except:
return response
def startTest(self, result='SUCCESS', wait=90, statusCode=202):
response = self.post('/api/v2/sessions/{0}/test-run/operations/start'.format(self.sessionId), headers=self.headers)
self.logDebug(pformat(response.content))
self.logDebug(pformat(response.json()))
assert response.status_code == statusCode
waitTime = wait
rest_url = '/api/v2/sessions/{0}/test-run/operations/start/{1}'.format(self.sessionId, response.json()['id'])
retry = 0
while wait > 0:
state = self.get(rest_url, headers=self.headers)
# self.logDebug(pformat(state))
# self.logDebug(pformat(state.content))
if state.json()['state'] == result:
self.testId = self.getTestId()
return state.json()
if 'state' not in state.json():
# The MW did not include the "state" in the JSON data. Show LoadCore team.
self.logError(testcaseResultFolder=self.testcaseResultsFolder,
msg=f'GET for /api/v2/sessions/{self.sessionId}/test-run/operation/start/{response.json()["id"]} was called, but the MW did not include the state in the json response. The json response: {state.json()}')
break
if 'message' in state.json():
mwMessage = state.json()['message']
else:
mwMessage = None
if state.json()['state'] == 'ERROR':
if retry == 0:
# NOTE: This is a workaround in case the agent fails to start traffic due to a race condition.
# Reboot the agents and retest
warningMsg = f'Start traffic failed with ERROR state. LoadCore MW message: {mwMessage}'
self.logWarning(warningMsg)
self.keystackObj.logWarning(msg=warningMsg)
if self.verifyLicenseSettings() == False:
warningMsg = f'startTest: The license server type somehow got reverted. Resetting it back to {self.licenseServerType}'
self.logWarning(warningMsg)
self.keystackObj.logWarning(msg=warningMsg)
self.setLicenseServer()
self.checkSessionState(status="STOPPED")
self.rebootAgents()
self.verifyAllAgentsStatusUp()
# In case rebooting agemts reverted the license type, lets verify it to make sure.
if self.verifyLicenseSettings() == False:
warningMsg = f'startTest: The license server type somehow got reverted. Resetting it back to {self.licenseServerType}'
self.logWarning(warningMsg)
self.keystackObj.logWarning(msg=warningMsg)
self.setLicenseServer()
retry = 1
response = self.post('/api/v2/sessions/{0}/test-run/operations/start'.format(self.sessionId), headers=self.headers)
self.logDebug(pformat(response.content))
self.logDebug(pformat(response.json()))
assert response.status_code == statusCode
wait = waitTime
rest_url = '/api/v2/sessions/{0}/test-run/operations/start/{1}'.format(self.sessionId, response.json()['id'])
else:
if 'The test ended and was cleaned up' in state.json()['message']:
# The test ended and was cleaned up. Check the session's test details for more information.
# Need to hard reboot agents
# Ignore this message
self.logError(state.json()['message'])
else:
# break when start goes to ERROR state
self.logError(state.json()['message'])
wait -= 1
time.sleep(2)
self.logDebug(pformat(state.json()))
else:
# Getting here means that Loadore MW did not state an ERROR in the json response
# But still need to reboot the agents and retest one more time
if retry == 0:
# NOTE: This is a workaround in case the agent fails to start traffic due to a race condition.
# Reboot the agents and retest
self.keystackObj.logWarning('Start traffic failed to start within 90secs. Reboot agents and retest ...')
self.stopTest()
self.checkSessionState(status="STOPPED")
if self.verifyLicenseSettings() == False:
self.keystackObj.logWarning(f'startTest: The license server type got reverted. Resetting it back to {self.licenseServerType}')
self.setLicenseServer()
self.rebootAgents()
self.verifyAllAgentsStatusUp()
if self.verifyLicenseSettings() == False:
self.logWarning(f'startTest: The license server type somehow got reverted. Resetting it back to {self.licenseServerType}')
self.setLicenseServer()
retry = 1
response = self.post('/api/v2/sessions/{0}/test-run/operations/start'.format(self.sessionId), headers=self.headers)
self.logDebug(pformat(response.content))
self.logDebug(pformat(response.json()))
assert response.status_code == statusCode
wait = waitTime
rest_url = '/api/v2/sessions/{0}/test-run/operations/start/{1}'.format(self.sessionId, response.json()['id'])
else:
msg='Test failed to start in {} sec'.format(waitTime)
self.logError(msg)
# if state is ERROR, stop the test and print the error message.
#assert (False, msg='State: {} - Error MSG: {}'.format(state.json()['state'], state.json()['message']))
msg = 'startTraffic: State: {} - Error MSG: {}'.format(state.json()['state'], state.json()['message'])
self.logError(msg)
def stopTest(self, result='SUCCESS', wait=40, statusCode=202):
response = self.post('/api/v2/sessions/{0}/test-run/operations/stop'.format(self.sessionId), headers=self.headers)
self.logDebug(pformat(response.content))
self.logDebug(pformat(response.status_code))
assert response.status_code == statusCode
rest_url = '/api/v2/sessions/{0}/test-run/operations/stop/{1}'.format(self.sessionId, response.json()['id'])
while wait > 0:
try:
state = self.get(rest_url, headers=self.headers)
# self.logDebug(pformat(state))
# self.logDebug(pformat(state.content))
if state.json()['state'] == result:
return state.json()
if state.json()['state'] == 'ERROR': # break when start goes to ERROR state
break
wait -= 1
time.sleep(2)
self.logDebug(pformat(state.json()))
except:
return response.json()
else:
#assert(False, msg='Test failed to stop')
msg='Test failed to stop'
self.logError(msg)
# if state is ERROR, stop the test and print the error message.
#assert(False, msg='State: {} - Error MSG: {}'.format(state.json()['state'], state.json()['message']))
msg = 'State: {} - Error MSG: {}'.format(state.json()['state'], state.json()['message'])
self.logError(msg)
def modifySessionState(self, state='STOPPED'):
"""
Modify a session's state.
Mostly used on a stucked session in the "Test is Stopping" state.
To get out of a stucked state, modify the state to 'STOPPED' and then call deleteSession().
"""
data = {'status': state}
response = self.patch('/api/v2/sessions/{0}/test'.format(self.sessionId), data=data, headers=self.headers)
if response.status_code != 204:
self.logError(f'Failed to modify session state: {state}')
def checkSessionState(self, status, waitTime=300):
"""
Check the status of a state for up to the waitTime.
"""
elapsedTime = 0
testResponse = self.get('/api/v2/sessions/{0}/test'.format(self.sessionId), headers=self.headers)
while elapsedTime < waitTime and testResponse.json()['status'] != status:
try:
testResponse = self.get('/api/v2/sessions/{0}/test'.format(self.sessionId), headers=self.headers)
except ConnectionError as e:
break
time.sleep(5)
elapsedTime += 5
if testResponse.json()['status'] == False:
# logError will raise an exception
self.logError('The test failed to start')
return True if testResponse.json()['status'] == status else False
def verifyLicenseSettings(self):
self.logInfo(f'verifyLicenseSettings ...')
response = self.get('/api/v2/globalsettings', headers=self.headers)
self.logInfo(f'verifyLicenseSettings: The middleware license is set to: {response.json()["licenseServer"]} type={response.json()["licenseType"]}. Expecting: {self.licenseServer} {self.licenseServerType}')
if response.json()["licenseServer"].strip() != self.licenseServer.strip():
self.logError(f'verifyLicenseSettings: Expecting license server IP: {self.licenseServer}. Got {response.json()["licenseServer"]}')
if response.json()["licenseType"].strip() != self.licenseServerType.strip():
self.logError(f'verifyLicenseSettings: Expecting: license server type: {self.licenseServerType}. Got {response.json()["licenseType"]}')
def setLicenseServer(self):
"""
license server types:
vLM: Old <= 1.5 external license server
ExternalKCOS: External license server
KCOS: Embeded license server
"""
self.logInfo(f'setLicenseServer: type:{self.licenseServerType} licenseServer:{self.licenseServer}')
payload = {"licenseServer": self.licenseServer, "licenseType": self.licenseServerType}
response = self.put('/api/v2/globalsettings', payload, headers=self.headers)
self.verifyLicenseSettings()
def getTestId(self, statusCode=200):
response = self.get('/api/v2/sessions/{0}/test'.format(self.sessionId), headers=self.headers)
assert response.status_code == statusCode
return response.json()['testId']
def getAllStats(self, statName, statusCode=200):
response = self.get('/api/v2/results/{0}/stats/{1}'.format(self.testId, statName), headers=self.headers)
if response.status_code != statusCode:
self.logWarning(f'getAllStats Error: {response.json()}')
return None
col = {}
statList = []
if response.json()['columns'] == None:
# Stats not ready. Ready None.
return None
if response.json()['columns'][0] == "timestamp":
try: