-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroce_preflight_checks.py
3608 lines (3189 loc) · 163 KB
/
roce_preflight_checks.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
"""RoCEv2 Preflight Checks
Copyright (C) Keysight Technologies, Inc - All Rights Reserved.
THE CONTENTS OF THIS PROJECT ARE PROPRIETARY AND CONFIDENTIAL.
UNAUTHORIZED COPYING, TRANSFERRING OR REPRODUCTION OF THE CONTENTS OF THIS
PROJECT, VIA ANY MEDIUM IS STRICTLY PROHIBITED.
The receipt or possession of the source code and/or any parts thereof does not
convey or imply any right to use them for any purpose other than the purpose
for which they were provided to you.
The software is provided "AS IS", without warranty of any kind, express or
implied, including but not limited to the warranties of merchantability,
fitness for a particular purpose and non infringement. In no event shall the
authors or copyright holders be liable for any claim, damages or other
liability, whether in an action of contract, tort or otherwise, arising from,
out of or in connection with the software or the use or other dealings in the
software.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
USAGES:
- python3.10 kccb.py --config ../demo/8ports_ipv4.yml --ixnetwork-host <ip>
# To emulate RoCEv2 traffic using Traffic Item. User must set port_mode to nrz
# in yml config file. This will automatically use Traffic Item.
# chassis:
# port_mode: 4x100-nrz
"""
import json
import yaml
import jsonschema
from types import SimpleNamespace
import logging
import time
from typing import List
import pandas
import statistics
import argparse
import os
import ixnetwork_restpy
from requests.adapters import HTTPAdapter
import pluggy
import random
import signal
import sys
import traceback
from datetime import datetime
import paramiko
import re
from tabulate import tabulate
import io
from pprint import pprint
try:
import benchmark_spec
import benchmark_plugin
except:
pass
# Release notes:
# - Fixed bug: Make script to run prechecks with and without rocev2 stack
# - Check typeOfTest. If it's all_to_all and pfc_incast precheck is enabled, abort the script with error.
# - Close the test session if passed
# - Added Yaml config param serdesType for M chassis type
VERSION="1.0.7"
class ConnectSSH:
"""
SSH to the chassis CLI
"""
def __init__(self, mainObj, host, username, password, pkeyFile=None, port=22, timeout=10):
self.host = host
self.username = username
self.password = password
self.pkey = None
self.port = port
self.timeout = timeout
self.mainObj = mainObj
if pkeyFile:
# Convert the pkey file into a string
pkeyFileOpen = open(pkeyFile)
pkeyContents = pkeyFileOpen.read()
pkeyFileOpen.close()
pkeyString = io.StringIO.StringIO(pkeyContents)
self.pkey = paramiko.RSAKey.from_private_key(pkeyString)
try:
self.sshClient = paramiko.SSHClient()
self.sshClient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.sshClient.connect(hostname=self.host,
username=self.username,
password=self.password,
port=self.port, pkey=self.pkey,
timeout=self.timeout)
self.mainObj._logger.info(f'\nSuccessfully connected to chassis: {host}')
except paramiko.SSHException:
raise Exception(f'\nSSH Failed to connect to the chassis: {host} username:{self.username} password:{self.password}')
except TimeoutError as errMsg:
self.mainObj._precheckSetupTasks['License Check'].update({'result': 'Failed',
'msg': self.mainObj.wrapText(f'Connecting to chassis CLI: {host}', width=300)})
raise Exception(f'License check: Connecting to chassis: {host}: {errMsg}')
def enterCommand(self, command, commandInput=None):
stdin, stdout, stderr = self.sshClient.exec_command(command)
while not stdout.channel.exit_status_ready() and not stdout.channel.recv_ready():
time.sleep(1)
stdoutString = stdout.readlines()
stderrString = stderr.readlines()
return stdoutString, stderrString
def close(self):
self.sshClient.close()
class CustomHTTPAdapter(HTTPAdapter):
def __init__(self, logger):
self._logger = logger
super().__init__()
def send(self, *args, **kwargs):
import requests
# If initial request fails, retry up to three times
saved = None
for attempt in range(4):
if saved is not None:
self._logger.info(f"Retry {attempt} of {saved.request.url}")
try:
return super().send(*args, **kwargs)
except requests.exceptions.ConnectionError as e:
self._logger.info(f"Requests connection error: {e}")
saved = e
continue
raise saved
class KCCB:
def __init__(self, optional_args: List[str] = None):
self._session_assistant = None
self._ixnetwork = None
self._dest_macs = {}
self._iterations = 1
self._ip_type = None
self._frame_overhead = None
self._link_speed = None
self._show_burst_timing = True
# v1 is for ports in NRZ mode and using regular Traffic Item to
# emulate RoCEv2 traffic
self._v1 = False
self._setup_prechecks()
self._setup_logger()
self._parse_args(optional_args)
self._setYamlConfigDefaults()
self._validate_config()
self._register_plugin()
self._includeRoceV2NgpfStack = False
self._expiredLicenses = []
self._isRocev2LicenseExists = False
self._typeOfChassis = None
# SPEED_10G, SPEED_25G, SPEED_40G, SPEED_50G, SPEED_100G, SPEED_200G, SPEED_400G, SPEED_800G
self._linkSpeed = self._config.layer1_profiles[0].link_speed
if self._args.validate is True:
exit(0)
def run(self):
try:
self.portUpDeltaTime = 0
self.startTime = time.perf_counter()
self.portSetupStartTime = time.perf_counter()
self._connect()
self._verifyLicenses()
if self._args.no_reset_ports is False:
self._setup_ports()
self._setup_layer1()
self._wait_for_linkup()
self.portUpDeltaTime = time.perf_counter() - self.portSetupStartTime
if self._v1:
self._setup_control_plane()
self._start_control_plane_v1()
self._run_test_v1()
self.cleanup()
else:
self._run_test()
self.overallTestTime = time.perf_counter() - self.startTime
self.showTimeMeasurements()
except Exception as e:
self._logger.error(traceback.format_exc(None, e))
#self._logger.error(e)
self._precheckSetupReport()
def _setYamlConfigDefaults(self):
"""
Set default Yaml config parameter values.
Read user Yaml config file input and overwrite parameter values
"""
self._all_hosts = []
with open(self._args.config) as fileObj:
ymlConfigs = yaml.safe_load(fileObj)
for host in ymlConfigs['hosts']:
self._all_hosts.append(host['name'])
self._precheckSelectionsDict = {'prechecks': {'license_check': True,
'check_connectivity': False,
'setup_ports': False,
'setup_layer1': False,
'check_link_state': False,
'configure_interfaces': False,
'arp_gateways': False,
'ping_mesh': False,
'apply_rocev2_traffic': False,
'pfc_incast': False
}}
self._yamlTestNames = {'tests': [{'profile_name': 'RoCEv2-Preflight-Checks'}]}
self._yamlTestProfileDefaults = {'test_profiles': [{'name': 'RoCEv2-Preflight-Checks',
'typeOfTest': 'all_to_all',
'enableDcqcn': True,
'start': 1073741824,
'end': 1073741824,
'queue_pairs_per_flow': 0,
'bufferSize': 131072,
'hosts': [],
'skip_flows': [[]],
'step': 2,
'tos': 225,
'hosts': self._all_hosts}]}
self._yamlLayer1ProfileDefaults = {'layer1_profiles': [{'name': 'layer1',
'auto_negotiate': False,
'ieee_defaults': False,
'link_speed': 'SPEED_400G',
'link_training': False,
'rs_fec': True,
'hosts': self._all_hosts,
'flow_control': {'ieee_802_1qbb': {'pfc_class_1': 2}}
}]}
def _setup_prechecks(self):
self._prechecks = False
self._precheckSetupTasks = {'Check connectivity to traffic agents': {'result': 'Skipped', 'msg': None},
'License Check': {'result': 'Skipped', 'msg': None},
'Setup Ports': {'result': 'Skipped', 'msg': None},
'Setup L1 Configs': {'result': 'Skipped', 'msg': None},
'Check Link State': {'result': 'Skipped', 'msg': None},
'Configure Interfaces': {'result': 'Skipped', 'msg': None},
'Start Protocols': {'result': 'Skipped', 'msg': None},
'ARP Gateways': {'result': 'Skipped', 'msg': None},
'Ping Mesh': {'result': 'Skipped', 'msg': None},
'Apply RoCEv2 Traffic': {'result': 'Skipped', 'msg': None},
'PFC Incast': {'result': 'Skipped', 'msg': None}}
def _precheckSetupReport(self):
"""
Generate a tabulated report
"""
if self._prechecks is False:
return
self._precheckSetupHeaders = ['Tasks', 'Results', 'Messages']
self._precheckSetupFile = 'precheck_setup_result.txt'
finalResult = 'passed'
precheckTaskList = []
for task, result in self._precheckSetupTasks.items():
if result['result'] == 'Failed':
finalResult = 'failed'
precheckTaskList.append((task, result['result'], result['msg']))
table = tabulate(precheckTaskList, headers=self._precheckSetupHeaders, tablefmt='fancy_grid')
with io.open(self._precheckSetupFile, 'w', encoding="utf-8") as outFile:
outFile.write(table)
print(table)
if finalResult == 'passed':
self.cleanup()
def _verifyLicenses(self):
"""
SSH into the chassis, enter "show licenses" and verify if any license are about to expire in
less than 15 days and if any license has expired.
"""
if self._prechecks and self._config.prechecks.license_check is False:
self._precheckSetupTasks['License Check'].update({'result': 'Disabled: Skippped'})
raise Exception('License check is disabled. Skipping.')
try:
try:
# S400GD-16P-QDD+FAN+NRZ+ROCEV2: Parse out the first letter for S or M type of AresOne
chassisCardDescription = self._ixnetwork.AvailableHardware.find()[0].Chassis.find()[0].Card.find()[0].Description
self._logger.info(f'Type of chassis: {chassisCardDescription}')
except Exception as errMsg:
errorMsg = f'Chassis/Card is down: {self._config.chassis.primary_chassis_ip}'
self._precheckSetupTasks['License Check'].update({'result': 'Failed', 'msg': self.wrapText(errorMsg, width=300)})
raise Exception(errorMsg)
# S400GD-16P-QDD+FAN+NRZ+ROCEV2
# M400GD-16P-QDD+FAN+NRZ+ROCEV2
# 800GE-8P-QDD-M+RoCEV2
self._typeOfChassis = chassisCardDescription
if hasattr(self._config, 'chassis') and hasattr(self._config.chassis, 'chassis_chain'):
if self._config.chassis.chassis_chain:
primaryChassisIp = self._config.chassis.primary_chassis_ip
else:
sys.exit(f'\nError: The Yaml config file requires key chassis.chassis_chain and primary_chassis_ip. Please update the Yaml config file')
sshClient = ConnectSSH(mainObj=self, host=primaryChassisIp, username=self._args.ixnetwork_uid, password=self._args.ixnetwork_pwd)
output = sshClient.enterCommand('show licenses')
licenseDateFormat = '%d-%b-%Y'
today = datetime.now()
# Format: 25-Jun-2024
todayObj = today.strftime(licenseDateFormat)
licensesInChassis = []
licenseWarnings = ''
for line in output[0]:
if 'IxNetwork RoCEv2' in line:
#8706-639B-1D6F-DA22 | Keysight IxNetwork RoCEv2 Lossless Ethernet Test Package for AresONE-S 400GE and AresONE-M 800GE fixed chassis models | IxNetwork | 1 | 930-2208-01 | 27-Jul-2024 | 27-Jul-2024
#regexMatch = re.search('.+\\| +Keysight IxNetwork RoCEv2.+\\| +IxNetwork +\\| +[0-9]+ +\\| +[^ ]+ +\\| +([^ ]+) +\\| +.+', line.strip())
self._isRocev2LicenseExists = True
regexMatch = re.search('.+\\|\s+(.+)\\| +([^ ]+) +\\| +[0-9]+ +\\| +([^ ]+) +\\| +([^ ]+) +\\| +.+', line.strip())
if regexMatch:
# 27-Jul-2024
productDescription = regexMatch.group(1).strip()
product = regexMatch.group(2).strip()
partNumber = regexMatch.group(3).strip()
expireDate = regexMatch.group(4)
# 2024-07-27
licenseDateObj = datetime.strptime(expireDate, licenseDateFormat).date()
# 70 days, 0:00:00
dateDelta = (licenseDateObj - today.date()).days
print(f'\nProduct: {product} ProductNumber: {partNumber}')
print(f'\tDescr: {productDescription}')
if dateDelta < 0:
print(f'\tExpired: {dateDelta} days ago')
self._expiredLicenses.append((product, partNumber, dateDelta))
else:
# Duplicate licensess could exists. 1 could be expired and 1 could be valid.
for index, expiredLicense in enumerate(self._expiredLicenses):
expiredProductDescription = expiredLicense[0]
if productDescription == expiredProductDescription:
self._expiredLicenses.pop(index)
break
if dateDelta < 15:
print(f'\tWARNING!! {dateDelta} more days until expiration date')
licenseWarnings += f'{product}:{partNumber}: Expires in {dateDelta} days\n'
else:
print(f'\tLicense is valid: {dateDelta} more days until expiration date')
if len(self._expiredLicenses) > 0:
errorMsg = ''
for expiredLicense in self._expiredLicenses:
errorMsg += f'{expiredLicense[0]}:{expiredLicense[1]}: Expired {expiredLicense[2]} days ago\n\n'
errorMsg += 'Scroll up for more details'
self._precheckSetupTasks['License Check'].update({'result': 'Expired Licenses', 'msg': self.wrapText(errorMsg, width=300)})
raise Exception('License verification failed')
else:
if licenseWarnings:
self._precheckSetupTasks['License Check'].update({'result': 'Passed', 'msg': self.wrapText(licenseWarnings, width=300)})
else:
self._precheckSetupTasks['License Check'].update({'result': 'Passed'})
print()
except Exception as errMsg:
self._precheckSetupTasks['License Check'].update({'result': 'Failed', 'msg': self.wrapText(str(errMsg), width=300)})
raise Exception(errMsg)
def wrapText(self, text: str, width: int=50):
"""
Wrap long text in a tabulated table cell
"""
newText = ''
start = 0
maxWords = width
while True:
getText = text[start:maxWords].strip()
if not getText:
break
newText += f'{getText}\n'
maxWords += width
start += width
return newText
def showTimeMeasurements(self):
'''
Use cmd line arg --show_time to show time measurements at the end of the test
'''
if self._args.show_time:
print(f'\n\nPort setup time: {self.portUpDeltaTime}')
if hasattr(self._config.chassis, 'port_mode'):
print(f'Change port mode time: {self.changePortModeTime}')
if self._v1 is False:
print(f'RoCEv2 NGPF setup time: {self.createRocev2NgpfDeltaTime}')
print(f'RoCEv2 NGPF endpoints setup time: {self.configRocev2EndpointsDelta}')
print(f'Start All Protocols UP time: {self.startAllProtocolTime}')
print(f'Create RoCEv2 traffic time: {self.createRocev2Traffic}')
print(f'Apply Traffic time: {self.applyTrafficTime}')
print(f'Getting stats time: {self.getStats}')
print(f'Overall Test time: {self.overallTestTime}\n\n')
def cleanup(self):
# Windows IxNetwork
if '-useAPIServer' not in self._ixnetwork.Globals.CommandArgs:
return
# IxNetwork Web Edition
if '-useAPIServer' in self._ixnetwork.Globals.CommandArgs and self._args.no_close_session:
return
try:
self._ixnetwork.NewConfig()
except Exception as e:
self._logger.error(e)
self._logger.info(self._config)
raise e
if self._session_assistant is not None:
self._session_assistant.Session.remove()
def _register_plugin(self):
try:
self._plugin_manager = pluggy.PluginManager("benchmark")
self._plugin_manager.add_hookspecs(benchmark_spec)
self._plugin_manager.register(benchmark_plugin.Plugin())
except:
pass
def _setup_logger(self):
self._logger = logging.getLogger("kccb")
self._logger.setLevel(logging.INFO)
if (
len(
[
handler
for handler in self._logger.handlers
if handler.name == "console"
]
)
== 0
):
sh = logging.StreamHandler()
sh.name = "console"
sh.setLevel(logging.INFO)
formatter = logging.Formatter(
"%(asctime)s [%(name)s] [%(levelname)s] %(message)s"
)
sh.setFormatter(formatter)
self._logger.addHandler(sh)
self._logger.info(f"Version = {VERSION}")
def _parse_args(self, optional_args):
parser = argparse.ArgumentParser(
formatter_class=argparse.RawTextHelpFormatter,
)
parser.add_argument(
"--ixnetwork-host",
help="Address of the host running IxNetwork (default is first chassis)",
required=False,
)
parser.add_argument(
"--ixnetwork-uid",
help="User name for the IxNetwork host",
default="admin",
)
parser.add_argument(
"--ixnetwork-pwd",
help="Password for the IxNetwork host",
default="admin",
)
parser.add_argument(
"--ixnetwork-debug",
help="Flag to enable debug level tracing on the IxNetwork host (default is info)",
action="store_true",
)
parser.add_argument(
"--ixnetwork-session-name",
help="Name for the IxNetwork session (e.g. your username, default is RoCEv2)",
required=False,
)
parser.add_argument(
"--output-dir",
help="Directory that will hold all result artifacts",
default="./results",
)
parser.add_argument(
"--validate",
help="Flag to only validate the configuration and exit",
action="store_true",
)
parser.add_argument(
"--ixnetwork-rest-port",
help="IxNetwork Rest API listening port",
required=False,
default=None
)
parser.add_argument(
"--show-time",
help="Show at the end of the test how long each IxNetwork setup/action took",
action="store_true",
required=False,
)
parser.add_argument(
"--no-reset-ports",
help="Don't reset ports.",
required=False,
action="store_true"
)
parser.add_argument(
"--no-close-session",
help="Don't close the IxNetwork test session",
action="store_true",
required=False,
)
parser.add_argument(
"--config",
help="Test configuration file in yaml format (required)\n\n"
+ "Example Configuration\n"
+ "---------------------\n"
+ "chain: [10.36.67.37] # list of chassis, first chassis will be the primary chassis if more than one chassis in the chain\n"
+ "hosts: # list of hosts in the test\n"
+ "- name: Host1.1 # logical name of the host\n"
+ " address: 32.0.1.2 # emulated address of the host (v4/v6)\n"
+ " prefix: 24 # prefix of emulated address host\n"
+ " gateway: 32.0.1.1 # gateway address (v4/v6)\n"
+ " additional_addresses: 0 # number of additional emulated addresses (min=0 max=32)\n"
+ " location: 10.36.67.37;1;1 # physical chassis;card;port of the hardware test port \n"
+ "layer1_profiles: # list of layer1 profiles\n"
+ "- name: layer1 # logical name of the layer1 profile\n"
+ " hosts: [Host1.1] # list of hosts in the layer1 profile\n"
+ " link_speed: SPEED_100G # the speed of the port (SPEED_100G | SPEED_200G | SPEED_400G | SPEED_800G)\n"
+ " auto_negotiate: true # enable/disable auto negotiation\n"
+ " ieee_defaults: false # true overrides auto_negotiate, link_training, rs_fec values for gigabit ethernet interfaces\n"
+ " link_training: false # enable/disable gigabit ethernet link training\n"
+ " rs_fec: true # enable/disable gigabit ethernet reed solomon forward error correction\n"
+ " tx_clock_adjust_ppm: 0 # adjust transmit line clock (-100 to 100 parts per million, default 0)\n"
+ " flow_control: # flow control settings\n"
+ " ieee_802_1qbb: # priority based flow control settings\n"
+ " pfc_class_1: 0 # pause traffic when receiving PFC pause frames with this class\n"
+ "test_profiles: # list of AI/ML tests\n"
+ "- name: all_to_all # logical name of the test\n"
+ " hosts: [Host1.1] # list of hosts in the test\n"
+ " start: 32 # the data size at which the test will start\n"
+ " step: 2 # the factor at which the data size will be increased\n"
+ " end: 134217728 # the data size after which the test will end\n"
+ " ethernet_mtu: 1500 # the system will derive the infiniband mtu based on the ethernet mtu\n"
+ " skip_flows: # skip flows within each list of hosts\n"
+ " - [Host1.1 Host1.2] # list of hosts (can have more than one list), skip flows between these hosts\n"
+ " burst: # make each flow bursty (optional)\n"
+ " packets_per_burst: 32 # number of packets per burst\n"
+ " burst_rate_percent: 99 # frame rate during burst, as a percentage of line rate\n"
+ " total_rate_percent: 70.0 # total frame rate across flows, as a percentage of line rate\n"
+ " burst_offset_percent: 100 # offset between bursts for different flows from the same tx host, as a percentage of burst tx time (default 100)\n"
+ " host_offset_percent: 0 # offset between tx start times for each host, as a percentage of burst tx time (default 0)\n"
+ " host_offset_ns: 0 # offset between tx start times for each host, in nanoseconds (default 0)\n"
+ " delayed_start: false # wait for destination to start before sending flow (default false)\n"
+ " send_pfc: # send PFC pause/resume frames with pfc_class_1 (optional)\n"
+ " hosts: [Host1.1] # list of hosts which send PFC frames\n"
+ " interval_us: 10 # interval between PFC frames sent by each host\n"
+ " pause_count: 1 # number of PFC pause frames sent on each cycle\n"
+ " resume_count: 2 # number of PFC resume frames sent on each cycle\n"
+ " ecn_capable: true # set ECN-Capable Transport(0) in IP header, default true\n"
+ "tests: # list of test profiles that will be run\n"
+ " profile_name: all_to_all # name of a test profile\n",
required=True,
)
if optional_args is None:
self._args = parser.parse_args()
else:
self._args = parser.parse_args(optional_args)
def _validate_config(self):
schema = {
"type": "object",
"required": [
"chassis",
"hosts",
"layer1_profiles",
"test_profiles",
"tests",
],
"properties": {
"chassis": {
"type": "object",
"items": {
"type": "object",
"required": [
"chassis_chain",
"primary_chassis_ip",
"port_mode"
],
"properties": {
"chassis_chain": {"type": "array"},
"primary_chassis_ip": {"type": "string"},
"port_mode": {"type": "string"}
}
}
},
"hosts": {
"type": "array",
"minItems": 2,
"items": {
"type": "object",
"required": [
"name",
"location",
"address",
"prefix",
],
"properties": {
"name": {"type": "string"},
"location": {"type": "string"},
"address": {"type": "string"},
"gateway": {"type": "string"},
"prefix": {"type": "integer"},
"additional_addresses": {
"type": "integer",
"default": 0,
},
},
},
},
"layer1_profiles": {
"type": "array",
"items": {
"type": "object",
"required": [
"name",
"hosts",
"link_speed",
"rs_fec",
"auto_negotiate",
"link_training",
"flow_control",
],
"properties": {
"name": {"type": "string"},
"hosts": {
"type": "array",
"items": {"type": "string"},
},
"link_speed": {
"type": "string",
"enum": ["SPEED_10G", "SPEED_25G", "SPEED_40G", "SPEED_50G", "SPEED_100G", "SPEED_200G", "SPEED_400G", "SPEED_800G"],
},
"rs_fec": {"type": "boolean"},
"auto_negotiate": {"type": "boolean"},
"ieee_defaults": {"type": "boolean"},
"link_training": {"type": "boolean"},
"tx_clock_adjust_ppm": {
"type": "integer",
"minimum": -100,
"maximum": 100
},
"flow_control": {
"type": "object",
"required": ["ieee_802_1qbb"],
"properties": {
"ieee_802_1qbb": {
"type": "object",
"required": ["pfc_class_1"],
"properties": {
"pfc_class_1": {
"type": "integer",
"minimum": 0,
"maximum": 7,
}
},
}
},
},
},
},
},
"test_profiles": {
"type": "array",
"items": {
"type": "object",
"required": [
"name",
"hosts",
"start",
"end",
"step",
"ethernet_mtu",
"queue_pairs_per_flow",
"bufferSize",
"enableDcqcn",
"typeOfTest"
],
"properties": {
"name": {"type": "string"},
"hosts": {
"type": "array",
"items": {"type": "string"},
},
"start": {"type": "integer"},
"end": {"type": "integer"},
"step": {"type": "integer"},
"ethernet_mtu": {"type": "integer"},
"tos": {"type": "integer", "default": "0"},
"queue_pairs_per_flow": {"type": "integer", "default": 0},
"typeOfTest": {"type": "string", "default": "all_to_all"},
"enableDcqcn": {"type": "boolean", "default": True},
"bufferSize": {"type": "integer", "default": 131072},
"skip_flows": {
"type": "array",
"items": {
"type": "array",
"items": {"type": "string"},
},
},
"restrict_flows": {
"type": "array",
"items": {
"type": "array",
"items": {"type": "string"},
},
},
"burst": {
"type": "object",
"required": [
"packets_per_burst",
"burst_rate_percent",
"total_rate_percent",
],
"packets_per_burst": {"type": "integer"},
"burst_rate_percent": {"type": "number"},
"total_rate_percent": {"type": "number"},
"burst_offset_percent": {"type": "integer"},
"host_offset_percent": {"type": "integer"},
"host_offset_ns": {"type": "integer"},
"delayed_start": {"type": "boolean"},
},
"send_pfc": {
"type": "object",
"required": [
"hosts",
"interval_us",
"pause_count",
"resume_count",
],
"hosts": {
"type": "array",
"items": {"type": "string"}
},
"interval_us": {"type": "integer"},
"pause_count": {"type": "integer"},
"resume_count": {"type": "integer"},
},
"ecn_capable": {"type": "boolean"},
},
},
},
"tests": {
"type": "array",
"items": {
"type": "object",
"required": ["profile_name"],
"properties": {
"profile_name": {"type": "string"},
},
},
},
},
}
with open(self._args.config) as fp:
yamlConfigs = yaml.safe_load(fp)
config_dict = self._precheckSelectionsDict
config_dict.update(self._yamlTestNames)
config_dict.update(self._yamlTestProfileDefaults)
config_dict.update(self._yamlLayer1ProfileDefaults)
if 'prechecks' in yamlConfigs:
self._prechecks = True
for key, value in yamlConfigs['prechecks'].items():
if key in config_dict['prechecks']:
if config_dict['prechecks'][key] != value:
config_dict['prechecks'][key] = value
else:
config_dict['prechecks'][key] = value
if 'chassis' in yamlConfigs:
config_dict['chassis'] = yamlConfigs['chassis']
if 'hosts' in yamlConfigs:
config_dict['hosts'] = yamlConfigs['hosts']
if 'tests' in yamlConfigs:
for index, runTestProfileNamesDict in enumerate(yamlConfigs['tests']):
defaultRunTestProfileNamesDict = {}
for key, value in runTestProfileNamesDict.items():
if 0 <= index < len(config_dict['tests']):
defaultRunTestProfileNamesDict = config_dict['tests'][index]
defaultRunTestProfileNamesDict[key] = value
if 0 <= index < len(config_dict['tests']):
config_dict['tests'].pop(index)
config_dict['tests'].insert(index, defaultRunTestProfileNamesDict)
if 'test_profiles' in yamlConfigs:
for index, testProfileDict in enumerate(yamlConfigs['test_profiles']):
defaultTestProfileDict = {}
for key, value in testProfileDict.items():
if 0 <= index < len(config_dict['test_profiles']):
defaultTestProfileDict = config_dict['test_profiles'][index]
defaultTestProfileDict[key] = value
if 0 <= index < len(config_dict['test_profiles']):
config_dict['test_profiles'].pop(index)
config_dict['test_profiles'].insert(index, defaultTestProfileDict)
if 'layer1_profiles' in yamlConfigs:
for index, layer1ProfileDict in enumerate(yamlConfigs['layer1_profiles']):
defaultLayer1ProfileDict = {}
for key, value in layer1ProfileDict.items():
if 0 <= index < len(config_dict['layer1_profiles']):
defaultLayer1ProfileDict = config_dict['layer1_profiles'][index]
defaultLayer1ProfileDict[key] = value
if 0 <= index < len(config_dict['layer1_profiles']):
config_dict['layer1_profiles'].pop(index)
config_dict['layer1_profiles'].insert(index, defaultLayer1ProfileDict)
jsonschema.validate(config_dict, schema)
for layer1_profile in config_dict["layer1_profiles"]:
self._validate_foreign_keys(
"hosts", config_dict["hosts"], layer1_profile["hosts"]
)
for test_profile in config_dict["test_profiles"]:
self._validate_foreign_keys(
"hosts", config_dict["hosts"], test_profile["hosts"]
)
if "skip_flows" in test_profile:
for host_list in test_profile["skip_flows"]:
self._validate_foreign_keys(
"hosts", config_dict["hosts"], host_list
)
if "restrict_flows" in test_profile:
for host_list in test_profile["restrict_flows"]:
self._validate_foreign_keys(
"hosts", config_dict["hosts"], host_list
)
if "send_pfc" in test_profile:
self._validate_foreign_keys(
"hosts", config_dict["hosts"], test_profile["send_pfc"]["hosts"]
)
self._validate_foreign_keys(
"test_profiles",
config_dict["test_profiles"],
[test["profile_name"] for test in config_dict["tests"]],
)
self._config = json.loads(
json.dumps(config_dict),
object_hook=lambda d: SimpleNamespace(**d),
)
# If ixnetwork-host was not passed as an argument, use chassis address
if self._args.ixnetwork_host is None:
self._args.ixnetwork_host = self._config.hosts[0].location.split(";")[0]
self._logger.info(f"Validated {self._args.config} configuration")
def _validate_foreign_keys(self, node_name, nodes, foreign_key_values):
for foreign_key_value in foreign_key_values:
if foreign_key_value not in [node["name"] for node in nodes]:
raise ValueError(
f"{foreign_key_value} not present in {node_name}[:].name"
)
def _run_test_v1(self):
'''
This is the original function that uses Traffic Item to create RoCEv2 traffic
'''
for test in self._config.tests:
self._summary_data = []
self._application_data = []
self._host_data = []
self._test_profile = self._get_test_profile(test.profile_name)
self._setup_flows_v1(self._test_profile)
self._setup_pfc_flows(self._test_profile)
self._logger.info(
f"Begin {self._test_profile.name} test: {len(self._test_profile.hosts)} hosts,"
+ f" datasize {self._test_profile.start}B to {self._test_profile.end}B, step factor {self._test_profile.step},"
+ f" infiniband mtu {self._infiniband_mtu}"
+ f" tos {self._test_profile.tos}"
)
traffic_items = self._traffic.TrafficItem.find()
traffic_items.Generate()
data_size = self._test_profile.start
while data_size <= self._test_profile.end:
self._size = data_size
self._logger.info(f"Sending {self._size} bytes...")
self._set_data_size_properties_v1(self._test_profile)
self._traffic.Apply()
self._start_hw_flows_v1()
self._get_hw_statistics_v1()
self._logger.info(
"Run results:\n" + self.get_summary_data().to_string()
)
data_size = data_size * self._test_profile.step
self._write_artifacts()
self._logger.info(f"End {self._test_profile.name} test")
def _run_test(self):
'''
This function uses the new IxNetwork RoCEv2 implementation
'''
self._summary_data = []
self._application_data = []
self._host_data = []
for test in self._config.tests:
self._logger.info(f'Running test name: {test.profile_name}')
self._test_profile = [test_profile for test_profile in self._config.test_profiles if test_profile.name == test.profile_name][0]
data_size = self._test_profile.start
self._ethernet_mtu = self._test_profile.ethernet_mtu
if self._test_profile.queue_pairs_per_flow > 0:
# This value will get replaced in setup_control if test_profile.queue_pairs_per_flow == 0
self._total_queue_pairs_per_flow = self._test_profile.queue_pairs_per_flow
if self._prechecks and self._config.prechecks.pfc_incast and self._test_profile.typeOfTest == 'all_to_all':
errMsg = f'Precheck pfc_incast=True and test_profiles.typeOfTest="all_to_all".\ntypeOfTest needs to be "incast" if pfc_incast=True\nif pfc_incast=False, typeOfTest could be incast or all_to_all.\nNot sure what test to run.'
self._precheckSetupTasks['PFC Incast'].update({'result': 'Failed', 'msg': self.wrapText(errMsg, width=300)})
raise Exception(errMsg)
while data_size <= self._test_profile.end:
# Variables inside this while loop are used in _setup_control_plane.
# So calling _setup_control_plane() must come after these variable settings.
#
# If the required size is a multiple of 128MB, use 128MB as the buffer length.
# If not, check whether it's a multiple of 64MB, 32MB, and so on.
self._size = data_size
sizePerDestination = self._size / len(self._config.hosts)
# 134,217,728: max buffer size is around 220MB (less than 256MB, the next power of 2)
# So using 128MB that fits our max buffer size
# 1024*1024=1MB, 1024*1024*1024=1GB
# threshold = 134,217,728
threshold = 128 * (1024 * 1024)
if self._test_profile.queue_pairs_per_flow == 0:
# Automatically calculate bufferSize for users
while True:
if sizePerDestination >= threshold and sizePerDestination % threshold == 0:
self._bufferSize = threshold / (1024 * 1024)
self._bufferSizeUnit = 'mb'
self._burstCount = sizePerDestination / threshold
break
else:
threshold = threshold / 2
if threshold < (1024 * 1024):
self._bufferSize = sizePerDestination
self._bufferSizeUnit = 'byte'
self._burstCount = 1
break
else:
self._bufferSize = self._test_profile.bufferSize
if len(str(self._bufferSize)) > 6:
self._bufferSizeUnit = 'mb'