-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathqos_sai_base.py
More file actions
3452 lines (3011 loc) · 155 KB
/
qos_sai_base.py
File metadata and controls
3452 lines (3011 loc) · 155 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.helpers.counterpoll_helper import ConterpollHelper
from tests.common.helpers.multi_thread_utils import SafeThreadPoolExecutor
from tests.common.mellanox_data import is_mellanox_device as isMellanoxDevice
from tests.common.cisco_data import is_cisco_device, copy_dshell_script_cisco_8000, run_dshell_command
from tests.common.dualtor.dual_tor_common import active_standby_ports # noqa: F401
from tests.common.dualtor.dual_tor_utils import (upper_tor_host, # noqa: F401
lower_tor_host, dualtor_ports, is_tunnel_qos_remap_enabled)
from tests.common.dualtor.mux_simulator_control import (toggle_all_simulator_ports, # noqa: F401
check_mux_status, validate_check_result)
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
from .qos_helpers import dutBufferConfig, disable_voq_watchdog
from tests.common.snappi_tests.qos_fixtures import get_pfcwd_config, reapply_pfcwd
from tests.common.snappi_tests.common_helpers import \
stop_pfcwd, disable_packet_aging, enable_packet_aging
from tests.common.utilities import is_ipv6_only_topology
logger = logging.getLogger(__name__)
class QosBase:
"""
Common APIs
"""
SUPPORTED_T0_TOPOS = [
"t0", "t0-56", "t0-56-po2vlan", "t0-64", "t0-116", "t0-118", "t0-35", "t0-d18u8s4", "dualtor-56", "dualtor-64",
"dualtor-120", "dualtor", "dualtor-64-breakout", "dualtor-aa", "dualtor-aa-56", "dualtor-aa-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", "t0-isolated-d16u16s1", "t0-isolated-d16u16s2",
"t0-isolated-d96u32s2", "t0-isolated-d32u32s2",
"t0-88-o8c80", "t0-f2-d40u8"
]
SUPPORTED_T1_TOPOS = ["t1", "t1-lag", "t1-64-lag", "t1-56-lag", "t1-backend", "t1-28-lag", "t1-32-lag", "t1-48-lag",
"t1-f2-d10u8",
"t1-isolated-d28u1", "t1-isolated-v6-d28u1", "t1-isolated-d56u2", "t1-isolated-v6-d56u2",
"t1-isolated-d56u1-lag", "t1-isolated-v6-d56u1-lag", "t1-isolated-d128", "t1-isolated-d32",
"t1-isolated-d448u15-lag", "t1-isolated-v6-d448u15-lag"]
SUPPORTED_PTF_TOPOS = ['ptf32', 'ptf64']
SUPPORTED_ASIC_LIST = ["pac", "gr", "gr2", "gb", "td2", "th", "th2", "spc1", "spc2", "spc3", "spc4", "spc5",
"td3", "th3", "j2c+", "jr2", "th5", "q3d"]
BREAKOUT_SKUS = ['Arista-7050-QX-32S']
LOW_SPEED_PORT_SKUS = ['Arista-7050CX3-32S-C28S4', 'Arista-7050CX3-32C-C28S4']
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,
lossy_queue_traffic_direction, request):
"""
Prepares DUT host test params
Returns:
dutTestParams (dict): DUT host test params
"""
# update router mac
duthost = get_src_dst_asic_and_duts['src_dut']
dualTor = request.config.getoption("--qos_dual_tor")
dut_mac = duthost.shell('sonic-db-cli CONFIG_DB hget "DEVICE_METADATA|localhost" mac')['stdout']
if "t0-backend" in dut_test_params_qos["topo"]:
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:
if lossy_queue_traffic_direction in ["src_uplink_dst_downlink", "src_downlink_dst_uplink"]:
dut_test_params_qos["basicParams"]["router_mac"] = dut_mac
else:
dut_test_params_qos["basicParams"]["router_mac"] = ''
if "dualtor" in tbinfo["topo"]["name"]:
if dualTor:
# If dualTor is True, the source port is the uplink port with additional lossless PGs.
# The router mac is the dut mac
dut_test_params_qos["basicParams"]["router_mac"] = dut_mac
else:
# If dualTor is False, the source port is the vlan port, need update the mac.
# 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:
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,
skip_pcap=False, test_subdir='py3'):
"""
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)
skip_pcap (bool): Skip pcap file generation to avoid OOM with high packet counts (default: False)
Returns:
None
Raises:
RunAnsibleModuleFail if ptf test fails
"""
ip_type = testParams.get("ip_type", "ipv4")
custom_options = " --disable-vxlan --disable-geneve" \
" --disable-erspan --disable-mpls --disable-nvgre"
if ip_type != "ipv6":
custom_options += " --disable-ipv6"
# 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 ""
# Skip log_file (and thus pcap generation) if skip_pcap is True
log_file = None if skip_pcap else "/tmp/{0}{1}.log".format(testCase, logfile_suffix)
ptf_runner(
ptfhost,
"saitests",
testCase,
platform_dir="ptftests",
params=testParams,
log_file=log_file,
qlen=10000,
is_python3=True,
relax=relax,
timeout=1850,
socket_recv_size=16384,
custom_options=custom_options,
pdb=pdb,
test_subdir=test_subdir
)
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]
port_profile_reserved_size = dut_asic.run_redis_cmd(
argv=["redis-cli", "-n", db, "HGET", f'BUFFER_PROFILE_TABLE:{port_profile}', "size"]
)[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]
)
pg_q_reserved_size = int(port_profile_reserved_size) * pg_q_alpha / (1 + pg_q_alpha)
reserved_size = pg_q_reserved_size if pg_q_reserved_size > int(pg_q_buffer_profile["size"]) \
else int(pg_q_buffer_profile["size"])
if pg_q_buffer_profile['dynamic_th'] == "7" and port_dynamic_th != "7":
buffer_scale = port_alpha / (1 + port_alpha)
else:
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_max_occupancy) + int(reserved_size)}
)
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
logger.info(f'pg_q_buffer_profile: {pg_q_buffer_profile}')
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:
profile_content = dut_asic.run_redis_cmd(argv=["redis-cli", "-n", db, "HGET", keystr, "profile"])
if profile_content:
bufferProfileName = bufkeystr + profile_content[0]
else:
logger.info("No lossless buffer. To compatible the existing case, return dump bufferProfilfe")
dump_buffer_profile = {
"profileName": f"{bufkeystr}pg_lossless_0_0m_profile",
"pool": "ingress_lossless_pool",
"xon": "0",
"xoff": "0",
"size": "0",
"dynamic_th": "0",
"pg_q_alpha": "0",
"port_alpha": "0",
"pool_size": "0",
"static_th": "0"
}
return dump_buffer_profile
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_sn5640-r0",
"x86_64-nvidia_sn5400-r0"]
if dut_asic.sonichost.facts['platform'] in platform_support_nvidia_new_algorithm_cal_buffer_thr \
and self.is_port_alpha_enabled(dut_asic):
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 table == "QUEUE" 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 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, lower_tor_host): # noqa: F811
"""
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']
config_facts = lower_tor_host.config_facts(host=lower_tor_host.hostname, source="running")['ansible_facts']
for i in range(len(testVlanMembers)):
portIndex = mgFacts["minigraph_ptf_indices"][testVlanMembers[i]]
peer_addr = config_facts['MUX_CABLE'][testVlanMembers[i]]['server_ipv4'].split('/')[0] \
if 'dualtor' in topo else testVlanIp + portIndex + 1
portIpMap = {'peer_addr': str(peer_addr)}
if vlan_id is not None:
portIpMap['vlan_id'] = vlan_id
dutPortIps.update({portIndex: portIpMap})
return dutPortIps
def replaceNonExistentPortId(self, availablePortIds, portIds):
'''
if port id of availablePortIds/dst_port_ids is not existing in availablePortIds
replace it with correct one, make sure all port id is valid
e.g.
Given below parameter:
availablePortIds: [0, 2, 4, 6, 8, 10, 16, 18, 20, 22, 24, 26,
28, 30, 32, 34, 36, 38, 44, 46, 48, 50, 52, 54]
portIds: [1, 2, 3, 4, 5, 6, 7, 8, 9]
get result:
portIds: [0, 2, 16, 4, 18, 6, 20, 8, 22]
'''
if len(portIds) > len(availablePortIds):
logger.info('no enough ports for test')
return False
# cache available as free port pool
freePorts = [pid for pid in availablePortIds]
# record invaild port
# and remove valid port from free port pool
invalid = []
for idx, pid in enumerate(portIds):
if pid not in freePorts:
invalid.append(idx)
else:
freePorts.remove(pid)
# replace invalid port from free port pool
for idx in invalid:
portIds[idx] = freePorts.pop(0)
return True
def updateTestPortIdIp(self, dutConfig, get_src_dst_asic_and_duts, qosParams=None):
src_dut_index = get_src_dst_asic_and_duts['src_dut_index']
dst_dut_index = get_src_dst_asic_and_duts['dst_dut_index']
src_asic_index = get_src_dst_asic_and_duts['src_asic_index']
dst_asic_index = get_src_dst_asic_and_duts['dst_asic_index']
src_testPortIds = dutConfig["testPortIds"][src_dut_index][src_asic_index]
dst_testPortIds = dutConfig["testPortIds"][dst_dut_index][dst_asic_index]
testPortIds = src_testPortIds + list(set(dst_testPortIds) - set(src_testPortIds))
portIdNames = []
portIds = []
for idName in dutConfig["testPorts"]:
if re.match(r'(?:src|dst)_port\S+id', idName):
portIdNames.append(idName)
ipName = idName.replace('id', 'ip')
pytest_assert(
ipName in dutConfig["testPorts"], 'Not find {} for {} in dutConfig'.format(ipName, idName))
portIds.append(dutConfig["testPorts"][idName])
has_enough_ports = self.replaceNonExistentPortId(testPortIds, list(portIds))
if not has_enough_ports:
src_dut = get_src_dst_asic_and_duts['src_dut']
is_vs = dutConfig.get('dstDutAsic') == 'vs'
is_t2 = src_dut.facts.get('switch_type') == 'voq'
if is_vs and is_t2:
pytest.skip(
"Not enough test ports for T2 VS platform "
"(need {}, got {}). See: https://github.com/sonic-net/sonic-mgmt/issues/23988".format(
len(portIds), len(testPortIds)))
pytest_assert(False, "No enough test ports")
for idx, idName in enumerate(portIdNames):
dutConfig["testPorts"][idName] = portIds[idx]
ipName = idName.replace('id', 'ip')
if 'src' in ipName:
testPortIps = dutConfig["testPortIps"][src_dut_index][src_asic_index]
else:
testPortIps = dutConfig["testPortIps"][dst_dut_index][dst_asic_index]
dutConfig["testPorts"][ipName] = testPortIps[portIds[idx]]['peer_addr']
if qosParams is not None:
portIdNames = []
portNumbers = []
portIds = []
for idName in qosParams.keys():
if re.match(r'(?:src|dst)_port\S+ids?', idName):
portIdNames.append(idName)
ids = qosParams[idName]
if isinstance(ids, list):
portIds += ids
# if it's port list, record number of pots
portNumbers.append(len(ids))
else:
portIds.append(ids)
# record None to indicate it's just one port
portNumbers.append(None)
pytest_assert(self.replaceNonExistentPortId(testPortIds, portIds), "No enough test ports")
startPos = 0
for idx, idName in enumerate(portIdNames):
if portNumbers[idx] is not None: # port list
qosParams[idName] = [
portId for portId in portIds[startPos:startPos + portNumbers[idx]]]
startPos += portNumbers[idx]
else: # not list, just one port
qosParams[idName] = portIds[startPos]
startPos += 1
logger.debug('updateTestPortIdIp dutConfig["testPorts"]: {}'.format(dutConfig["testPorts"]))
@pytest.fixture(scope='module')
def swapSyncd_on_selected_duts(self, request, duthosts, creds, tbinfo, lower_tor_host, # noqa: F811
core_dump_and_config_check): # noqa: F811
"""
Swap syncd on DUT host
Args:
request (Fixture): pytest request object
duthost (AnsibleHost): Device Under Test (DUT)
Returns:
None
"""
asic_type = duthosts[0].facts["asic_type"]
if 'dualtor' in tbinfo['topo']['name']:
dut_list = [lower_tor_host]
else:
dut_list = duthosts.frontend_nodes
swapSyncd = request.config.getoption("--qos_swap_syncd")
if asic_type == "vs":
logger.info("Swap syncd is not supported on VS platform")
swapSyncd = False
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
with SafeThreadPoolExecutor(max_workers=8) as executor:
for duthost in dut_list:
executor.submit(docker.swap_syncd, duthost, new_creds)
yield
finally:
if swapSyncd:
with SafeThreadPoolExecutor(max_workers=8) as executor:
for duthost in dut_list:
executor.submit(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
src_long_link = False
dst_long_link = False
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)
src_long_link = True
else:
src_dut_index = is_longlink_list.index(False)
dst_dut_index = is_longlink_list.index(True)
dst_long_link = 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,
"src_long_link": src_long_link,
"dst_long_link": dst_long_link
}
@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,
downlinkPortIds=None, is_supported_per_dir=False, lossy_queue_traffic_direction=''):
"""
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))
# Use dynamic key fallback: some platforms (e.g., SPC2 SN3800 t1) may not have
# dut_index=0 as a key in testPortIds/testPortIps dicts
src_dut_idx = get_src_dst_asic_and_duts['src_dut_index']
dst_dut_idx = get_src_dst_asic_and_duts['dst_dut_index']
src_asic_idx = get_src_dst_asic_and_duts['src_asic_index']
dst_asic_idx = get_src_dst_asic_and_duts['dst_asic_index']
if src_dut_idx not in testPortIds:
src_dut_idx = next(iter(testPortIds))
dst_dut_idx = src_dut_idx
if src_asic_idx not in testPortIds[src_dut_idx]:
src_asic_idx = next(iter(testPortIds[src_dut_idx]))
dst_asic_idx = src_asic_idx
src_dut_port_ids = testPortIds[src_dut_idx]
src_test_port_ids = src_dut_port_ids[src_asic_idx]
dst_dut_port_ids = testPortIds[dst_dut_idx]
dst_test_port_ids = dst_dut_port_ids[dst_asic_idx]
src_dut_port_ips = testPortIps[src_dut_idx]
src_test_port_ips = src_dut_port_ips[src_asic_idx]
dst_dut_port_ips = testPortIps[dst_dut_idx]
dst_test_port_ips = dst_dut_port_ips[dst_asic_idx]
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"