forked from sonic-net/sonic-mgmt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqos_sai_base.py
More file actions
2695 lines (2353 loc) · 120 KB
/
Copy pathqos_sai_base.py
File metadata and controls
2695 lines (2353 loc) · 120 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import ipaddress
import json
import logging
import pytest
import re
import yaml
import random
import os
import sys
import six
import copy
import time
import collections
from tests.common.fixtures.ptfhost_utils import ptf_portmap_file # noqa F401
from tests.common.helpers.assertions import pytest_assert, pytest_require
from tests.common.mellanox_data import is_mellanox_device as isMellanoxDevice
from tests.common.cisco_data import is_cisco_device
from tests.common.dualtor.dual_tor_utils import upper_tor_host, lower_tor_host, dualtor_ports, is_tunnel_qos_remap_enabled # noqa F401
from tests.common.dualtor.mux_simulator_control \
import toggle_all_simulator_ports, check_mux_status, validate_check_result # noqa F401
from tests.common.dualtor.constants import UPPER_TOR, LOWER_TOR # noqa F401
from tests.common.utilities import check_qos_db_fv_reference_with_table
from tests.common.fixtures.duthost_utils import dut_qos_maps, separated_dscp_to_tc_map_on_uplink # noqa F401
from tests.common.utilities import wait_until
from tests.ptf_runner import ptf_runner
from tests.common.system_utils import docker # noqa F401
from tests.common.errors import RunAnsibleModuleFail
from tests.common import config_reload
from tests.common.devices.eos import EosHost
logger = logging.getLogger(__name__)
class QosBase:
"""
Common APIs
"""
SUPPORTED_T0_TOPOS = ["t0", "t0-56", "t0-56-po2vlan", "t0-64", "t0-116", "t0-35", "dualtor-56", "dualtor-64",
"dualtor-120", "dualtor", "dualtor-64-breakout", "t0-120", "t0-80", "t0-backend",
"t0-56-o8v48", "t0-8-lag", "t0-standalone-32", "t0-standalone-64", "t0-standalone-128",
"t0-standalone-256", "t0-28"]
SUPPORTED_T1_TOPOS = ["t1-lag", "t1-64-lag", "t1-56-lag", "t1-backend", "t1-28-lag", "t1-32-lag"]
SUPPORTED_PTF_TOPOS = ['ptf32', 'ptf64']
SUPPORTED_ASIC_LIST = ["pac", "gr", "gr2", "gb", "td2", "th", "th2", "spc1", "spc2", "spc3", "spc4", "td3", "th3",
"j2c+", "jr2", "th5"]
BREAKOUT_SKUS = ['Arista-7050-QX-32S']
TARGET_QUEUE_WRED = 3
TARGET_LOSSY_QUEUE_SCHED = 0
TARGET_LOSSLESS_QUEUE_SCHED = 3
buffer_model_initialized = False
buffer_model = None
def isBufferInApplDb(self, dut_asic):
if not self.buffer_model_initialized:
self.buffer_model = dut_asic.run_redis_cmd(
argv=[
"redis-cli", "-n", "4", "hget",
"DEVICE_METADATA|localhost", "buffer_model"
]
)
self.buffer_model_initialized = True
logger.info(
"Buffer model is {}, buffer tables will be fetched from {}".format(
self.buffer_model or "not defined",
"APPL_DB" if self.buffer_model else "CONFIG_DB"
)
)
return self.buffer_model
@pytest.fixture(scope='class', autouse=True)
def dutTestParams(self, duthosts, dut_test_params_qos, tbinfo, get_src_dst_asic_and_duts):
"""
Prepares DUT host test params
Returns:
dutTestParams (dict): DUT host test params
"""
# update router mac
if "t0-backend" in dut_test_params_qos["topo"]:
duthost = get_src_dst_asic_and_duts['src_dut']
dut_test_params_qos["basicParams"]["router_mac"] = duthost.shell(
'sonic-db-cli CONFIG_DB hget "DEVICE_METADATA|localhost" mac')['stdout']
elif dut_test_params_qos["topo"] in self.SUPPORTED_T0_TOPOS:
dut_test_params_qos["basicParams"]["router_mac"] = ''
elif "dualtor" in tbinfo["topo"]["name"]:
# For dualtor qos test scenario, DMAC of test traffic is default vlan interface's MAC address.
# To reduce duplicated code, put "is_dualtor" and "def_vlan_mac" into dutTestParams['basicParams'].
dut_test_params_qos["basicParams"]["is_dualtor"] = True
vlan_cfgs = tbinfo['topo']['properties']['topology']['DUT']['vlan_configs']
if vlan_cfgs and 'default_vlan_config' in vlan_cfgs:
default_vlan_name = vlan_cfgs['default_vlan_config']
if default_vlan_name:
for vlan in vlan_cfgs[default_vlan_name].values():
if 'mac' in vlan and vlan['mac']:
dut_test_params_qos["basicParams"]["def_vlan_mac"] = vlan['mac']
break
pytest_assert(dut_test_params_qos["basicParams"]["def_vlan_mac"] is not None,
"Dual-TOR miss default VLAN MAC address")
else:
try:
duthost = get_src_dst_asic_and_duts['src_dut']
asic = duthost.asic_instance().asic_index
dut_test_params_qos['basicParams']["router_mac"] = duthost.shell(
'sonic-db-cli -n asic{} CONFIG_DB hget "DEVICE_METADATA|localhost" mac'.format(asic))['stdout']
except RunAnsibleModuleFail:
dut_test_params_qos['basicParams']["router_mac"] = duthost.shell(
'sonic-db-cli CONFIG_DB hget "DEVICE_METADATA|localhost" mac')['stdout']
yield dut_test_params_qos
def runPtfTest(self, ptfhost, testCase='', testParams={}, relax=False, pdb=False):
"""
Runs QoS SAI test case on PTF host
Args:
ptfhost (AnsibleHost): Packet Test Framework (PTF)
testCase (str): SAI tests test case name
testParams (dict): Map of test params required by testCase
relax (bool): Relax ptf verify packet requirements (default: False)
Returns:
None
Raises:
RunAnsibleModuleFail if ptf test fails
"""
custom_options = " --disable-ipv6 --disable-vxlan --disable-geneve" \
" --disable-erspan --disable-mpls --disable-nvgre"
# Append a suffix to the logfile name if log_suffix is present in testParams
log_suffix = testParams.get("log_suffix", "")
logfile_suffix = "_{0}".format(log_suffix) if log_suffix else ""
ptf_runner(
ptfhost,
"saitests",
testCase,
platform_dir="ptftests",
params=testParams,
log_file="/tmp/{0}{1}.log".format(testCase, logfile_suffix), # Include suffix in the logfile name,
qlen=10000,
is_python3=True,
relax=relax,
timeout=1850,
socket_recv_size=16384,
custom_options=custom_options,
pdb=pdb
)
class QosSaiBase(QosBase):
"""
QosSaiBase contains collection of pytest fixtures that ready the
testbed for QoS SAI test cases.
"""
def __computeBufferThreshold(self, dut_asic, bufferProfile):
"""
Computes buffer threshold for dynamic threshold profiles
Args:
dut_asic (SonicAsic): Device ASIC Under Test (DUT)
bufferProfile (dict, inout): Map of puffer profile attributes
Returns:
Updates bufferProfile with computed buffer threshold
"""
if self.isBufferInApplDb(dut_asic):
db = "0"
keystr = "BUFFER_POOL_TABLE:"
else:
db = "4"
keystr = "BUFFER_POOL|"
if check_qos_db_fv_reference_with_table(dut_asic):
if six.PY2:
pool = bufferProfile["pool"].encode("utf-8").translate(None, "[]")
else:
pool = bufferProfile["pool"].translate({ord(i): None for i in '[]'})
else:
pool = keystr + bufferProfile["pool"]
bufferSize = int(
dut_asic.run_redis_cmd(
argv=["redis-cli", "-n", db, "HGET", pool, "size"]
)[0]
)
bufferScale = 2 ** float(bufferProfile["dynamic_th"])
bufferScale /= (bufferScale + 1)
bufferProfile.update(
{"static_th": int(
bufferProfile["size"]) + int(bufferScale * bufferSize)}
)
def __compute_buffer_threshold_for_nvidia_device(self, dut_asic, table, port, pg_q_buffer_profile):
"""
Computes buffer threshold for dynamic threshold profiles for nvidia device
Args:
dut_asic (SonicAsic): Device ASIC Under Test (DUT)
table (str): Redis table name
port (str): DUT port alias
pg_q_buffer_profile (dict, inout): Map of pg or q buffer profile attributes
Returns:
Updates bufferProfile with computed buffer threshold
"""
port_table_name = "BUFFER_PORT_EGRESS_PROFILE_LIST_TABLE" if \
table == "BUFFER_QUEUE_TABLE" else "BUFFER_PORT_INGRESS_PROFILE_LIST_TABLE"
db = "0"
port_profile_res = dut_asic.run_redis_cmd(
argv=["redis-cli", "-n", db, "HGET", f"{port_table_name}:{port}", "profile_list"]
)[0]
port_profile_list = port_profile_res.split(",")
port_dynamic_th = ''
for port_profile in port_profile_list:
buffer_pool_name = dut_asic.run_redis_cmd(
argv=["redis-cli", "-n", db, "HGET", f'BUFFER_PROFILE_TABLE:{port_profile}', "pool"]
)[0]
if buffer_pool_name == pg_q_buffer_profile["pool"]:
port_dynamic_th = dut_asic.run_redis_cmd(
argv=["redis-cli", "-n", db, "HGET", f'BUFFER_PROFILE_TABLE:{port_profile}', "dynamic_th"]
)[0]
break
if port_dynamic_th:
def calculate_alpha(dynamic_th):
if dynamic_th == "7":
alpha = 64
else:
alpha = 2 ** float(dynamic_th)
return alpha
pg_q_alpha = calculate_alpha(pg_q_buffer_profile['dynamic_th'])
port_alpha = calculate_alpha(port_dynamic_th)
pool = f'BUFFER_POOL_TABLE:{pg_q_buffer_profile["pool"]}'
buffer_size = int(
dut_asic.run_redis_cmd(
argv=["redis-cli", "-n", db, "HGET", pool, "size"]
)[0]
)
buffer_scale = port_alpha * pg_q_alpha / (port_alpha * pg_q_alpha + pg_q_alpha + 1)
pg_q_max_occupancy = int(buffer_size * buffer_scale)
pg_q_buffer_profile.update(
{"static_th": int(
pg_q_buffer_profile["size"]) + int(pg_q_max_occupancy)}
)
pg_q_buffer_profile["pg_q_alpha"] = pg_q_alpha
pg_q_buffer_profile["port_alpha"] = port_alpha
pg_q_buffer_profile["pool_size"] = buffer_size
else:
raise Exception("Not found port dynamic th")
def __updateVoidRoidParams(self, dut_asic, bufferProfile):
"""
Updates buffer profile with VOID/ROID params
Args:
dut_asic (SonicAsic): Device Under Test (DUT)
bufferProfile (dict, inout): Map of puffer profile attributes
Returns:
Updates bufferProfile with VOID/ROID obtained from Redis db
"""
if check_qos_db_fv_reference_with_table(dut_asic):
if self.isBufferInApplDb(dut_asic):
if six.PY2:
bufferPoolName = bufferProfile["pool"].encode("utf-8").translate(
None, "[]").replace("BUFFER_POOL_TABLE:", '')
else:
bufferPoolName = bufferProfile["pool"].translate(
{ord(i): None for i in '[]'}).replace("BUFFER_POOL_TABLE:", '')
else:
if six.PY2:
bufferPoolName = bufferProfile["pool"].encode("utf-8").translate(
None, "[]").replace("BUFFER_POOL|", '')
else:
bufferPoolName = bufferProfile["pool"].translate(
{ord(i): None for i in '[]'}).replace("BUFFER_POOL|", '')
else:
bufferPoolName = six.text_type(bufferProfile["pool"])
bufferPoolVoid = six.text_type(dut_asic.run_redis_cmd(
argv=[
"redis-cli", "-n", "2", "HGET",
"COUNTERS_BUFFER_POOL_NAME_MAP", bufferPoolName
]
)[0])
bufferProfile.update({"bufferPoolVoid": bufferPoolVoid})
bufferPoolRoid = six.text_type(dut_asic.run_redis_cmd(
argv=["redis-cli", "-n", "1", "HGET", "VIDTORID", bufferPoolVoid]
)[0]).replace("oid:", '')
bufferProfile.update({"bufferPoolRoid": bufferPoolRoid})
def __getBufferProfile(self, request, dut_asic, os_version, table, port, priorityGroup):
"""
Get buffer profile attribute from Redis db
Args:
request (Fixture): pytest request object
dut_asic(SonicAsic): Device Under Test (DUT)
table (str): Redis table name
port (str): DUT port alias
priorityGroup (str): QoS priority group
Returns:
bufferProfile (dict): Map of buffer profile attributes
"""
if table == "BUFFER_QUEUE_TABLE" and dut_asic.sonichost.facts['switch_type'] == 'voq':
# For VoQ chassis, the buffer queues config is based on system port
if dut_asic.sonichost.is_multi_asic:
port = "{}:{}:{}".format(
dut_asic.sonichost.hostname, dut_asic.namespace, port)
else:
port = "{}:Asic0:{}".format(dut_asic.sonichost.hostname, port)
if self.isBufferInApplDb(dut_asic):
db = "0"
keystr = "{0}:{1}:{2}".format(table, port, priorityGroup)
bufkeystr = "BUFFER_PROFILE_TABLE:"
else:
db = "4"
keystr = "{0}|{1}|{2}".format(table, port, priorityGroup)
bufkeystr = "BUFFER_PROFILE|"
if check_qos_db_fv_reference_with_table(dut_asic):
out = dut_asic.run_redis_cmd(argv=["redis-cli", "-n", db, "HGET", keystr, "profile"])[0]
if six.PY2:
bufferProfileName = out.encode("utf-8").translate(None, "[]")
else:
bufferProfileName = out.translate({ord(i): None for i in '[]'})
else:
bufferProfileName = bufkeystr + dut_asic.run_redis_cmd(
argv=["redis-cli", "-n", db, "HGET", keystr, "profile"])[0]
result = dut_asic.run_redis_cmd(
argv=["redis-cli", "-n", db, "HGETALL", bufferProfileName]
)
it = iter(result)
bufferProfile = dict(list(zip(it, it)))
bufferProfile.update({"profileName": bufferProfileName})
# Update profile static threshold value if profile threshold is dynamic
if "dynamic_th" in list(bufferProfile.keys()):
platform_support_nvidia_new_algorithm_cal_buffer_thr = ["x86_64-nvidia_sn5600-r0",
"x86_64-nvidia_sn5400-r0"]
if dut_asic.sonichost.facts['platform'] in platform_support_nvidia_new_algorithm_cal_buffer_thr:
self.__compute_buffer_threshold_for_nvidia_device(dut_asic, table, port, bufferProfile)
else:
self.__computeBufferThreshold(dut_asic, bufferProfile)
if "pg_lossless" in bufferProfileName:
pytest_assert(
"xon" in list(bufferProfile.keys()) and "xoff" in list(
bufferProfile.keys()),
"Could not find xon and/or xoff values for profile '{0}'".format(
bufferProfileName
)
)
if "201811" not in os_version:
self.__updateVoidRoidParams(dut_asic, bufferProfile)
return bufferProfile
def __getSharedHeadroomPoolSize(self, request, dut_asic):
"""
Get shared headroom pool size from Redis db
Args:
request (Fixture): pytest request object
dut_asic (SonicAsic): Device Under Test (DUT)
Returns:
size (str) size of shared headroom pool
None if shared headroom pool isn't enabled
"""
if self.isBufferInApplDb(dut_asic):
db = "0"
keystr = "BUFFER_POOL_TABLE:ingress_lossless_pool"
else:
db = "4"
keystr = "BUFFER_POOL|ingress_lossless_pool"
result = dut_asic.run_redis_cmd(
argv=["redis-cli", "-n", db, "HGETALL", keystr]
)
it = iter(result)
ingressLosslessPool = dict(list(zip(it, it)))
return ingressLosslessPool.get("xoff")
def __getEcnWredParam(self, dut_asic, table, port):
"""
Get ECN/WRED parameters from Redis db
Args:
dut_asic (SonicAsic): Device Under Test (DUT)
table (str): Redis table name
port (str): DUT port alias
Returns:
wredProfile (dict): Map of ECN/WRED attributes
"""
if check_qos_db_fv_reference_with_table(dut_asic):
out = dut_asic.run_redis_cmd(
argv=[
"redis-cli", "-n", "4", "HGET",
"{0}|{1}|{2}".format(table, port, self.TARGET_QUEUE_WRED),
"wred_profile"
]
)[0]
if six.PY2:
wredProfileName = out.encode("utf-8").translate(None, "[]")
else:
wredProfileName = out.translate({ord(i): None for i in '[]'})
else:
wredProfileName = "WRED_PROFILE|" + six.text_type(dut_asic.run_redis_cmd(
argv=[
"redis-cli", "-n", "4", "HGET",
"{0}|{1}|{2}".format(table, port, self.TARGET_QUEUE_WRED),
"wred_profile"
]
)[0])
result = dut_asic.run_redis_cmd(
argv=["redis-cli", "-n", "4", "HGETALL", wredProfileName]
)
it = iter(result)
wredProfile = dict(list(zip(it, it)))
return wredProfile
def __getWatermarkStatus(self, dut_asic):
"""
Get watermark status from Redis db
Args:
dut_asic (SonicAsic): Device Under Test (DUT)
Returns:
watermarkStatus (str): Watermark status
"""
watermarkStatus = six.text_type(dut_asic.run_redis_cmd(
argv=[
"redis-cli", "-n", "4", "HGET",
"FLEX_COUNTER_TABLE|QUEUE_WATERMARK", "FLEX_COUNTER_STATUS"
]
)[0])
return watermarkStatus
def __getSchedulerParam(self, dut_asic, port, queue):
"""
Get scheduler parameters from Redis db
Args:
dut_asic (SonicAsic): Device Under Test (DUT)
port (str): DUT port alias
queue (str): QoS queue
Returns:
SchedulerParam (dict): Map of scheduler parameters
"""
if check_qos_db_fv_reference_with_table(dut_asic):
out = dut_asic.run_redis_cmd(
argv=[
"redis-cli", "-n", "4", "HGET",
"QUEUE|{0}|{1}".format(port, queue), "scheduler"
]
)[0]
if six.PY2:
schedProfile = out.encode("utf-8").translate(None, "[]")
else:
schedProfile = out.translate({ord(i): None for i in '[]'})
else:
if dut_asic.sonichost.facts['switch_type'] == 'voq':
# For VoQ chassis, the scheduler queues config is based on system port
if dut_asic.sonichost.is_multi_asic:
schedProfile = "SCHEDULER|" + six.text_type(dut_asic.run_redis_cmd(
argv=[
"redis-cli", "-n", "4", "HGET",
"QUEUE|{0}|{1}|{2}|{3}"
.format(dut_asic.sonichost.hostname, dut_asic.namespace, port, queue), "scheduler"
]
)[0])
else:
schedProfile = "SCHEDULER|" + six.text_type(dut_asic.run_redis_cmd(
argv=[
"redis-cli", "-n", "4", "HGET",
"QUEUE|{0}|Asic0|{1}|{2}"
.format(dut_asic.sonichost.hostname, port, queue), "scheduler"
]
)[0])
else:
schedProfile = "SCHEDULER|" + six.text_type(dut_asic.run_redis_cmd(
argv=[
"redis-cli", "-n", "4", "HGET",
"QUEUE|{0}|{1}".format(port, queue), "scheduler"
]
)[0])
schedWeight = six.text_type(dut_asic.run_redis_cmd(
argv=["redis-cli", "-n", "4", "HGET", schedProfile, "weight"]
)[0])
return {"schedProfile": schedProfile, "schedWeight": schedWeight}
def __assignTestPortIps(self, mgFacts, topo):
"""
Assign IPs to test ports of DUT host
Args:
mgFacts (dict): Map of DUT minigraph facts
Returns:
dutPortIps (dict): Map of port index to IPs
"""
dutPortIps = {}
if len(mgFacts["minigraph_vlans"]) > 0:
# TODO: handle the case when there are multiple vlans
vlans = iter(mgFacts["minigraph_vlans"])
testVlan = next(vlans)
testVlanMembers = mgFacts["minigraph_vlans"][testVlan]["members"]
# To support t0-56-po2vlan topo, choose the Vlan with physical ports and remove the lag in Vlan members
if topo == 't0-56-po2vlan':
if len(testVlanMembers) == 1:
testVlan = next(vlans)
testVlanMembers = mgFacts["minigraph_vlans"][testVlan]["members"]
for member in testVlanMembers:
if 'PortChannel' in member:
testVlanMembers.remove(member)
break
testVlanIp = None
for vlan in mgFacts["minigraph_vlan_interfaces"]:
if mgFacts["minigraph_vlans"][testVlan]["name"] in vlan["attachto"]:
testVlanIp = ipaddress.ip_address(vlan["addr"]) # noqa F821
break
pytest_assert(testVlanIp, "Failed to obtain vlan IP")
vlan_id = None
if 'type' in mgFacts["minigraph_vlans"][testVlan]:
vlan_type = mgFacts["minigraph_vlans"][testVlan]['type']
if vlan_type is not None and "Tagged" in vlan_type:
vlan_id = mgFacts["minigraph_vlans"][testVlan]['vlanid']
for i in range(len(testVlanMembers)):
portIndex = mgFacts["minigraph_ptf_indices"][testVlanMembers[i]]
portIpMap = {'peer_addr': str(testVlanIp + portIndex + 1)}
if vlan_id is not None:
portIpMap['vlan_id'] = vlan_id
dutPortIps.update({portIndex: portIpMap})
return dutPortIps
@pytest.fixture(scope='module')
def swapSyncd_on_selected_duts(self, request, duthosts, creds, tbinfo, lower_tor_host): # noqa F811
"""
Swap syncd on DUT host
Args:
request (Fixture): pytest request object
duthost (AnsibleHost): Device Under Test (DUT)
Returns:
None
"""
if 'dualtor' in tbinfo['topo']['name']:
dut_list = [lower_tor_host]
else:
dut_list = duthosts.frontend_nodes
swapSyncd = request.config.getoption("--qos_swap_syncd")
public_docker_reg = request.config.getoption("--public_docker_registry")
try:
if swapSyncd:
if public_docker_reg:
new_creds = copy.deepcopy(creds)
new_creds['docker_registry_host'] = new_creds['public_docker_registry_host']
new_creds['docker_registry_username'] = ''
new_creds['docker_registry_password'] = ''
else:
new_creds = creds
for duthost in dut_list:
docker.swap_syncd(duthost, new_creds)
yield
finally:
if swapSyncd:
for duthost in dut_list:
docker.restore_default_syncd(duthost, new_creds)
@pytest.fixture(scope='class', name="select_src_dst_dut_and_asic",
params=["single_asic", "single_dut_multi_asic",
"multi_dut_longlink_to_shortlink",
"multi_dut_shortlink_to_shortlink",
"multi_dut_shortlink_to_longlink"])
def select_src_dst_dut_and_asic(self, duthosts, request, tbinfo, lower_tor_host): # noqa F811
test_port_selection_criteria = request.param
logger.info("test_port_selection_criteria is {}".format(test_port_selection_criteria))
src_dut_index = 0
dst_dut_index = 0
src_asic_index = 0
dst_asic_index = 0
topo = tbinfo["topo"]["name"]
if 'dualtor' in tbinfo['topo']['name']:
# index of lower_tor_host
for a_dut_index in range(len(duthosts)):
if duthosts[a_dut_index] == lower_tor_host:
lower_tor_dut_index = a_dut_index
break
number_of_duts = len(duthosts.frontend_nodes)
is_longlink_list = [False] * number_of_duts
for i in range(number_of_duts):
if self.isLonglink(duthosts.frontend_nodes[i]):
is_longlink_list[i] = True
shortlink_indices = [i for i, longlink in enumerate(is_longlink_list) if not longlink]
duthost = duthosts.frontend_nodes[0]
if test_port_selection_criteria == 'single_asic':
# We should randomly pick a dut from duthosts.frontend_nodes and a random asic in that selected DUT
# for now hard code the first DUT and the first asic
if 'dualtor' in tbinfo['topo']['name']:
src_dut_index = lower_tor_dut_index
elif topo not in (self.SUPPORTED_T0_TOPOS + self.SUPPORTED_T1_TOPOS) and shortlink_indices:
src_dut_index = random.choice(shortlink_indices)
else:
src_dut_index = 0
dst_dut_index = src_dut_index
src_asic_index = 0
dst_asic_index = 0
elif test_port_selection_criteria == "single_dut_multi_asic":
found_multi_asic_dut = False
if topo in self.SUPPORTED_T0_TOPOS or isMellanoxDevice(duthost):
pytest.skip("single_dut_multi_asic is not supported on T0 topologies")
if topo not in self.SUPPORTED_T1_TOPOS and shortlink_indices:
random.shuffle(shortlink_indices)
for idx in shortlink_indices:
a_dut = duthosts.frontend_nodes[idx]
if a_dut.sonichost.is_multi_asic:
src_dut_index = idx
found_multi_asic_dut = True
break
else:
for a_dut_index in range(len(duthosts.frontend_nodes)):
a_dut = duthosts.frontend_nodes[a_dut_index]
if a_dut.sonichost.is_multi_asic:
src_dut_index = a_dut_index
found_multi_asic_dut = True
logger.info("Using dut {} for single_dut_multi_asic testing".format(a_dut.hostname))
break
if not found_multi_asic_dut:
pytest.skip(
"Did not find any frontend node that is multi-asic - so can't run single_dut_multi_asic tests")
dst_dut_index = src_dut_index
src_asic_index = 0
dst_asic_index = 1
else:
# Dealing with multi-dut
if topo in self.SUPPORTED_T0_TOPOS or isMellanoxDevice(duthost):
pytest.skip("multi-dut is not supported on T0 topologies")
elif topo in self.SUPPORTED_T1_TOPOS:
pytest.skip("multi-dut is not supported on T1 topologies")
if (len(duthosts.frontend_nodes)) < 2:
pytest.skip("Don't have 2 frontend nodes - so can't run multi_dut tests")
if test_port_selection_criteria == 'multi_dut_shortlink_to_shortlink':
if is_longlink_list.count(False) < 2:
pytest.skip("Don't have 2 shortlink frontend nodes - so can't run {}"
"tests".format(test_port_selection_criteria))
src_dut_index = is_longlink_list.index(False)
dst_dut_index = is_longlink_list.index(False, src_dut_index + 1)
else:
if is_longlink_list.count(False) == 0 or is_longlink_list.count(True) == 0:
pytest.skip("Don't have longlink or shortlink frontend nodes - so can't"
"run {} tests".format(test_port_selection_criteria))
if test_port_selection_criteria == 'multi_dut_longlink_to_shortlink':
src_dut_index = is_longlink_list.index(True)
dst_dut_index = is_longlink_list.index(False)
else:
src_dut_index = is_longlink_list.index(False)
dst_dut_index = is_longlink_list.index(True)
src_asic_index = 0
dst_asic_index = 0
yield {
"src_dut_index": src_dut_index,
"dst_dut_index": dst_dut_index,
"src_asic_index": src_asic_index,
"dst_asic_index": dst_asic_index
}
@pytest.fixture(scope='class')
def get_src_dst_asic_and_duts(self, duthosts, tbinfo, select_src_dst_dut_and_asic, lower_tor_host): # noqa F811
if 'dualtor' in tbinfo['topo']['name']:
src_dut = lower_tor_host
dst_dut = lower_tor_host
else:
src_dut = duthosts.frontend_nodes[select_src_dst_dut_and_asic["src_dut_index"]]
dst_dut = duthosts.frontend_nodes[select_src_dst_dut_and_asic["dst_dut_index"]]
src_asic = src_dut.asics[select_src_dst_dut_and_asic["src_asic_index"]]
dst_asic = dst_dut.asics[select_src_dst_dut_and_asic["dst_asic_index"]]
all_asics = [src_asic]
if src_asic != dst_asic:
all_asics.append(dst_asic)
all_duts = [src_dut]
if src_dut != dst_dut:
all_duts.append(dst_dut)
rtn_dict = {
"src_asic": src_asic,
"dst_asic": dst_asic,
"src_dut": src_dut,
"dst_dut": dst_dut,
"single_asic_test": (src_dut == dst_dut and src_asic == dst_asic),
"all_asics": all_asics,
"all_duts": all_duts
}
rtn_dict.update(select_src_dst_dut_and_asic)
yield rtn_dict
def __buildTestPorts(self, request, testPortIds, testPortIps, src_port_ids, dst_port_ids,
get_src_dst_asic_and_duts, uplinkPortIds, sysPortMap=None):
"""
Build map of test ports index and IPs
Args:
request (Fixture): pytest request object
testPortIds (list): List of QoS SAI test port IDs
testPortIps (list): List of QoS SAI test port IPs
Returns:
testPorts (dict): Map of test ports index and IPs
sysPortMap (dict): Map of system port IDs and Qos SAI test port IDs
"""
dstPorts = request.config.getoption("--qos_dst_ports")
srcPorts = request.config.getoption("--qos_src_ports")
logging.debug("__buildTestPorts testPortIds: {}, testPortIps: {}, src_port_ids: {}, \
dst_port_ids: {}, get_src_dst_asic_and_duts: {}, uplinkPortIds: {}".format(
testPortIds, testPortIps, src_port_ids, dst_port_ids, get_src_dst_asic_and_duts, uplinkPortIds))
src_dut_port_ids = testPortIds[get_src_dst_asic_and_duts['src_dut_index']]
src_test_port_ids = src_dut_port_ids[get_src_dst_asic_and_duts['src_asic_index']]
dst_dut_port_ids = testPortIds[get_src_dst_asic_and_duts['dst_dut_index']]
dst_test_port_ids = dst_dut_port_ids[get_src_dst_asic_and_duts['dst_asic_index']]
src_dut_port_ips = testPortIps[get_src_dst_asic_and_duts['src_dut_index']]
src_test_port_ips = src_dut_port_ips[get_src_dst_asic_and_duts['src_asic_index']]
dst_dut_port_ips = testPortIps[get_src_dst_asic_and_duts['dst_dut_index']]
dst_test_port_ips = dst_dut_port_ips[get_src_dst_asic_and_duts['dst_asic_index']]
if dstPorts is None:
if dst_port_ids:
pytest_assert(
len(set(dst_test_port_ids).intersection(
set(dst_port_ids))) == len(set(dst_port_ids)),
"Dest port id passed in qos.yml not valid"
)
dstPorts = dst_port_ids
elif len(dst_test_port_ids) >= 4:
dstPorts = [0, 2, 3]
if (get_src_dst_asic_and_duts["src_asic"].sonichost.facts["asic_type"]
in ['cisco-8000']):
dstPorts = [2, 3, 4]
elif len(dst_test_port_ids) == 3:
dstPorts = [0, 2, 2]
else:
dstPorts = [0, 0, 0]
if srcPorts is None:
if src_port_ids:
pytest_assert(
len(set(src_test_port_ids).intersection(
set(src_port_ids))) == len(set(src_port_ids)),
"Source port id passed in qos.yml not valid"
)
# To verify ingress lossless speed/cable-length randomize the source port.
srcPorts = [random.choice(src_port_ids)]
else:
srcPorts = [1]
if (get_src_dst_asic_and_duts["src_asic"].sonichost.facts["hwsku"]
in ["Cisco-8101-O8C48", "Cisco-8102-28FH-DPU-O-T1"]):
srcPorts = [testPortIds[0][0].index(uplinkPortIds[0])]
dstPorts = [testPortIds[0][0].index(x) for x in uplinkPortIds[1:4]]
logging.debug("Test Port dst:{}, src:{}".format(dstPorts, srcPorts))
pytest_assert(len(dst_test_port_ids) >= 1 and len(src_test_port_ids) >= 1, "Provide at least 2 test ports")
logging.debug(
"Test Port IDs:{} IPs:{}".format(testPortIds, testPortIps)
)
logging.debug("Test Port dst:{}, src:{}".format(dstPorts, srcPorts))
pytest_assert(
len(set(dstPorts).intersection(set(srcPorts))) == 0,
"Duplicate destination and source ports '{0}'".format(
set(dstPorts).intersection(set(srcPorts))
)
)
# TODO: Randomize port selection
dstPort = dstPorts[0] if dst_port_ids else dst_test_port_ids[dstPorts[0]]
dstVlan = dst_test_port_ips[dstPort]['vlan_id'] if 'vlan_id' in dst_test_port_ips[dstPort] else None
dstPort2 = dstPorts[1] if dst_port_ids else dst_test_port_ids[dstPorts[1]]
dstVlan2 = dst_test_port_ips[dstPort2]['vlan_id'] if 'vlan_id' in dst_test_port_ips[dstPort2] else None
dstPort3 = dstPorts[2] if dst_port_ids else dst_test_port_ids[dstPorts[2]]
dstVlan3 = dst_test_port_ips[dstPort3]['vlan_id'] if 'vlan_id' in dst_test_port_ips[dstPort3] else None
srcPort = srcPorts[0] if src_port_ids else src_test_port_ids[srcPorts[0]]
srcVlan = src_test_port_ips[srcPort]['vlan_id'] if 'vlan_id' in src_test_port_ips[srcPort] else None
# collecting the system ports associated with dst ports
# In case of PortChannel as dst port, all lag ports will be added to the list
# ex. {dstPort: system_port, dstPort1:system_port1 ...}
dst_all_sys_port = {}
if 'platform_asic' in get_src_dst_asic_and_duts["src_dut"].facts and \
get_src_dst_asic_and_duts["src_dut"].facts['platform_asic'] == 'broadcom-dnx':
sysPorts = sysPortMap[get_src_dst_asic_and_duts['dst_dut_index']][
get_src_dst_asic_and_duts['dst_asic_index']]
for port_id in [dstPort, dstPort2, dstPort3]:
if port_id in sysPorts and port_id not in dst_all_sys_port:
dst_all_sys_port.update({port_id: sysPorts[port_id]['system_port']})
if 'PortChannel' in sysPorts[port_id]['port_type']:
for sport, sysMap in sysPorts.items():
if sysMap['port_type'] == sysPorts[port_id]['port_type'] and sport != port_id:
dst_all_sys_port.update({sport: sysMap['system_port']})
return {
"dst_port_id": dstPort,
"dst_port_ip": dst_test_port_ips[dstPort]['peer_addr'],
"dst_port_vlan": dstVlan,
"dst_port_2_id": dstPort2,
"dst_port_2_ip": dst_test_port_ips[dstPort2]['peer_addr'],
"dst_port_2_vlan": dstVlan2,
'dst_port_3_id': dstPort3,
"dst_port_3_ip": dst_test_port_ips[dstPort3]['peer_addr'],
"dst_port_3_vlan": dstVlan3,
"src_port_id": srcPort,
"src_port_ip": src_test_port_ips[srcPorts[0] if src_port_ids else src_test_port_ids[srcPorts[0]]]["peer_addr"],
"src_port_vlan": srcVlan,
"dst_sys_ports": dst_all_sys_port
}
def __buildPortSpeeds(self, config_facts):
port_speeds = collections.defaultdict(list)
for etp, attr in config_facts['PORT'].items():
port_speeds[attr['speed']].append(etp)
return port_speeds
@pytest.fixture(scope='class', autouse=False)
def configure_ip_on_ptf_intfs(self, ptfhost, get_src_dst_asic_and_duts, tbinfo):
src_dut = get_src_dst_asic_and_duts['src_dut']
src_mgFacts = src_dut.get_extended_minigraph_facts(tbinfo)
topo = tbinfo["topo"]["name"]
# if PTF64 and is Cisco, set ip IP address on eth interfaces of the ptf"
if topo == 'ptf64' and is_cisco_device(src_dut):
minigraph_ip_interfaces = src_mgFacts['minigraph_interfaces']
for entry in minigraph_ip_interfaces:
ptfhost.shell("ip addr add {}/31 dev eth{}".format(
entry['peer_addr'], src_mgFacts["minigraph_ptf_indices"][entry['attachto']])
)
yield
for entry in minigraph_ip_interfaces:
ptfhost.shell("ip addr del {}/31 dev eth{}".format(
entry['peer_addr'], src_mgFacts["minigraph_ptf_indices"][entry['attachto']])
)
return
else:
yield
return
@pytest.fixture(scope='class', autouse=True)
def dutConfig(
self, request, duthosts, configure_ip_on_ptf_intfs, get_src_dst_asic_and_duts,
lower_tor_host, tbinfo, dualtor_ports_for_duts, dut_qos_maps): # noqa F811
"""
Build DUT host config pertaining to QoS SAI tests
Args:
request (Fixture): pytest request object
duthost (AnsibleHost): Device Under Test (DUT)
Returns:
dutConfig (dict): Map of DUT config containing dut interfaces,
test port IDs, test port IPs, and test ports
"""
"""
Below are dictionaries with key being dut_index and value a dictionary with key asic_index
Example for 2 DUTs with 2 asics each
{ 0: { 0: <asic0_value>, 1: <asic1_value>}, 1: { 0: <asic0_value>, 1: <asic1_value> }}
"""
dutPortIps = {}
testPortIps = {}
testPortIds = {}
dualTorPortIndexes = {}
uplinkPortIds = []
uplinkPortIps = []
uplinkPortNames = []
downlinkPortIds = []
downlinkPortIps = []
downlinkPortNames = []
sysPortMap = {}
src_dut_index = get_src_dst_asic_and_duts['src_dut_index']
src_asic_index = get_src_dst_asic_and_duts['src_asic_index']
src_dut = get_src_dst_asic_and_duts['src_dut']
dst_dut = get_src_dst_asic_and_duts['dst_dut']
src_mgFacts = src_dut.get_extended_minigraph_facts(tbinfo)
topo = tbinfo["topo"]["name"]
# LAG ports in T1 TOPO need to be removed in Mellanox devices
if topo in self.SUPPORTED_T0_TOPOS or (topo in self.SUPPORTED_PTF_TOPOS and isMellanoxDevice(src_dut)):
# Only single asic is supported for this scenario, so use src_dut and src_asic - which will be the same
# as dst_dut and dst_asic
pytest_assert(
not src_dut.sonichost.is_multi_asic, "Fixture not supported on T0 multi ASIC"
)
dutLagInterfaces = []
testPortIds[src_dut_index] = {}
for _, lag in src_mgFacts["minigraph_portchannels"].items():
for intf in lag["members"]:
dutLagInterfaces.append(src_mgFacts["minigraph_ptf_indices"][intf])
config_facts = duthosts.config_facts(host=src_dut.hostname, source="running")
port_speeds = self.__buildPortSpeeds(config_facts[src_dut.hostname])
low_speed_portIds = []
if src_dut.facts['hwsku'] in self.BREAKOUT_SKUS and 'backend' not in topo:
for speed, portlist in port_speeds.items():
if int(speed) < 40000:
for portname in portlist:
low_speed_portIds.append(src_mgFacts["minigraph_ptf_indices"][portname])
testPortIds[src_dut_index][src_asic_index] = set(src_mgFacts["minigraph_ptf_indices"][port]
for port in src_mgFacts["minigraph_ports"].keys())
testPortIds[src_dut_index][src_asic_index] -= set(dutLagInterfaces)
testPortIds[src_dut_index][src_asic_index] -= set(low_speed_portIds)
if isMellanoxDevice(src_dut):
# The last port is used for up link from DUT switch
testPortIds[src_dut_index][src_asic_index] -= {len(src_mgFacts["minigraph_ptf_indices"]) - 1}
testPortIds[src_dut_index][src_asic_index] = sorted(testPortIds[src_dut_index][src_asic_index])
pytest_require(len(testPortIds[src_dut_index][src_asic_index]) != 0,
"Skip test since no ports are available for testing")
# get current DUT port IPs
dutPortIps[src_dut_index] = {}
dutPortIps[src_dut_index][src_asic_index] = {}
dualTorPortIndexes[src_dut_index] = {}
dualTorPortIndexes[src_dut_index][src_asic_index] = []
if 'backend' in topo:
intf_map = src_mgFacts["minigraph_vlan_sub_interfaces"]
else:
intf_map = src_mgFacts["minigraph_interfaces"]
use_separated_upkink_dscp_tc_map = separated_dscp_to_tc_map_on_uplink(dut_qos_maps)
for portConfig in intf_map:
intf = portConfig["attachto"].split(".")[0]
if ipaddress.ip_interface(portConfig['peer_addr']).ip.version == 4:
portIndex = src_mgFacts["minigraph_ptf_indices"][intf]
if portIndex in testPortIds[src_dut_index][src_asic_index]:
portIpMap = {'peer_addr': portConfig["peer_addr"]}
if 'vlan' in portConfig:
portIpMap['vlan_id'] = portConfig['vlan']
dutPortIps[src_dut_index][src_asic_index].update({portIndex: portIpMap})
if intf in dualtor_ports_for_duts:
dualTorPortIndexes[src_dut_index][src_asic_index].append(portIndex)
# If the leaf router is using separated DSCP_TO_TC_MAP on uplink/downlink ports.
# we also need to test them separately
# for mellanox device, we run it on t1 topo mocked by ptf32 topo
if use_separated_upkink_dscp_tc_map and isMellanoxDevice(src_dut):
neighName = src_mgFacts["minigraph_neighbors"].get(intf, {}).get("name", "").lower()
if 't0' in neighName:
downlinkPortIds.append(portIndex)
downlinkPortIps.append(portConfig["peer_addr"])
downlinkPortNames.append(intf)
elif 't2' in neighName:
uplinkPortIds.append(portIndex)
uplinkPortIps.append(portConfig["peer_addr"])
uplinkPortNames.append(intf)
if isMellanoxDevice(src_dut):
dualtor_dut_ports = dualtor_ports_for_duts if topo in self.SUPPORTED_PTF_TOPOS else None
testPortIds[src_dut_index][src_asic_index] = self.select_port_ids_for_mellnaox_device(
src_dut, src_mgFacts, testPortIds[src_dut_index][src_asic_index], dualtor_dut_ports)