forked from sonic-net/sonic-mgmt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsai_qos_tests.py
More file actions
executable file
·6318 lines (5601 loc) · 316 KB
/
Copy pathsai_qos_tests.py
File metadata and controls
executable file
·6318 lines (5601 loc) · 316 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
"""
SONiC Dataplane Qos tests
"""
import time
import logging
import ptf.packet as scapy
from scapy.all import Ether, IP
import socket
import sai_base_test
import operator
import sys
import texttable
import math
import os
import macsec # noqa F401
import concurrent.futures
from ptf.testutils import (ptf_ports,
dp_poll,
simple_arp_packet,
send_packet,
simple_tcp_packet,
simple_qinq_tcp_packet,
simple_ip_packet,
simple_ipv4ip_packet,
hex_dump_buffer,
verify_packet_any_port,
port_to_tuple)
from ptf.mask import Mask
from switch import (switch_init,
sai_thrift_create_scheduler_profile,
sai_thrift_clear_all_counters,
sai_thrift_read_port_counters,
port_list,
sai_thrift_read_port_watermarks,
sai_thrift_read_pg_counters,
sai_thrift_read_pg_drop_counters,
sai_thrift_read_pg_shared_watermark,
sai_thrift_read_buffer_pool_watermark,
sai_thrift_read_headroom_pool_watermark,
sai_thrift_read_queue_occupancy,
sai_thrift_read_pg_occupancy,
sai_thrift_read_port_voq_counters,
sai_thrift_get_voq_port_id
)
from switch_sai_thrift.ttypes import (sai_thrift_attribute_value_t,
sai_thrift_attribute_t)
from switch_sai_thrift.sai_headers import SAI_PORT_ATTR_QOS_SCHEDULER_PROFILE_ID
# Counters
# The index number comes from the append order in sai_thrift_read_port_counters
EGRESS_DROP = 0
INGRESS_DROP = 1
PFC_PRIO_0 = 2
PFC_PRIO_1 = 3
PFC_PRIO_2 = 4
PFC_PRIO_3 = 5
PFC_PRIO_4 = 6
PFC_PRIO_5 = 7
PFC_PRIO_6 = 8
PFC_PRIO_7 = 9
TRANSMITTED_OCTETS = 10
TRANSMITTED_PKTS = 11
INGRESS_PORT_BUFFER_DROP = 12
EGRESS_PORT_BUFFER_DROP = 13
RECEIVED_PKTS = 14
RECEIVED_NON_UC_PKTS = 15
TRANSMITTED_NON_UC_PKTS = 16
EGRESS_PORT_QLEN = 17
port_counter_fields = ['OutDiscard', # SAI_PORT_STAT_IF_OUT_DISCARDS
'InDiscard', # SAI_PORT_STAT_IF_IN_DISCARDS
'Pfc0TxPkt', # SAI_PORT_STAT_PFC_0_TX_PKTS
'Pfc1TxPkt', # SAI_PORT_STAT_PFC_1_TX_PKTS
'Pfc2TxPkt', # SAI_PORT_STAT_PFC_2_TX_PKTS
'Pfc3TxPkt', # SAI_PORT_STAT_PFC_3_TX_PKTS
'Pfc4TxPkt', # SAI_PORT_STAT_PFC_4_TX_PKTS
'Pfc5TxPkt', # SAI_PORT_STAT_PFC_5_TX_PKTS
'Pfc6TxPkt', # SAI_PORT_STAT_PFC_6_TX_PKTS
'Pfc7TxPkt', # SAI_PORT_STAT_PFC_7_TX_PKTS
'OutOct', # SAI_PORT_STAT_IF_OUT_OCTETS
'OutUcPkt', # SAI_PORT_STAT_IF_OUT_UCAST_PKTS
'InDropPkt', # SAI_PORT_STAT_IN_DROPPED_PKTS
'OutDropPkt', # SAI_PORT_STAT_OUT_DROPPED_PKTS
'InUcPkt', # SAI_PORT_STAT_IF_IN_UCAST_PKTS
'InNonUcPkt', # SAI_PORT_STAT_IF_IN_NON_UCAST_PKTS
'OutNonUcPkt', # SAI_PORT_STAT_IF_OUT_NON_UCAST_PKTS
'OutQlen'] # SAI_PORT_STAT_IF_OUT_QLEN
queue_counter_field_template = 'Que{}Cnt' # SAI_QUEUE_STAT_PACKETS
# sai_thrift_read_port_watermarks
queue_share_wm_field_template = 'Que{}ShareWm' # SAI_QUEUE_STAT_SHARED_WATERMARK_BYTES
pg_share_wm_field_template = 'Pg{}ShareWm' # SAI_INGRESS_PRIORITY_GROUP_STAT_SHARED_WATERMARK_BYTES
pg_headroom_wm_field_template = 'pg{}HdrmWm' # SAI_INGRESS_PRIORITY_GROUP_STAT_XOFF_ROOM_WATERMARK_BYTES
# sai_thrift_read_pg_counters
pg_counter_field_template = 'Pg{}Cnt' # SAI_INGRESS_PRIORITY_GROUP_STAT_PACKETS
# sai_thrift_read_pg_drop_counters
pg_drop_field_template = 'Pg{}Drop' # SAI_INGRESS_PRIORITY_GROUP_STAT_DROPPED_PACKETS
QUEUE_0 = 0
QUEUE_1 = 1
QUEUE_2 = 2
QUEUE_3 = 3
QUEUE_4 = 4
QUEUE_5 = 5
QUEUE_6 = 6
QUEUE_7 = 7
PG_NUM = 8
QUEUE_NUM = 8
# Constants
STOP_PORT_MAX_RATE = 1
RELEASE_PORT_MAX_RATE = 0
ECN_INDEX_IN_HEADER = 53 # Fits the ptf hex_dump_buffer() parse function
DSCP_INDEX_IN_HEADER = 52 # Fits the ptf hex_dump_buffer() parse function
COUNTER_MARGIN = 2 # Margin for counter check
# Constants for the IP IP DSCP to PG mapping test
DEFAULT_DSCP = 4
DEFAULT_TTL = 64
DEFAULT_ECN = 1
DEFAULT_PKT_COUNT = 10
PG_TOLERANCE = 2
def log_message(message, level='info', to_stderr=False):
if to_stderr:
sys.stderr.write(message + "\n")
log_funcs = {'debug': logging.debug,
'info': logging.info,
'warning': logging.info,
'error': logging.error,
'critical': logging.error}
log_fn = log_funcs.get(level.lower(), logging.info)
log_fn(message)
def read_ptf_counters(dataplane, port):
ptfdev, ptfport = port_to_tuple(port)
rx, tx = dataplane.get_counters(ptfdev, ptfport)
return [rx, tx]
def flat_test_port_ids(hierarchy):
if isinstance(hierarchy, int):
yield hierarchy
elif isinstance(hierarchy, list):
for item in hierarchy:
yield from flat_test_port_ids(item)
elif isinstance(hierarchy, dict):
for value in hierarchy.values():
yield from flat_test_port_ids(value)
class CounterCollector:
'''Collect, compare and display counters for test'''
def __init__(self, ptftest, counter_name):
self.ptftest = ptftest
if 'dst' in self.ptftest.clients and self.ptftest.clients['src'] != self.ptftest.clients['dst']:
# For first revision, tests do not cover chassis device, so not support chassis temporarily
# when tests cover chassi device, will open this feature to chassis device
self.valid = False
else:
self.valid = True
self.steps = []
self.counter_name = counter_name
self.asic_type = ptftest.test_params.get('sonic_asic_type', None)
self.flat_ports = list(flat_test_port_ids(ptftest.test_params.get('test_port_ids', None)))
def collect_counter(self, step_name, step_desc=None, compare=True):
if not self.valid:
return
counter_info = {
'PortCnt': [
port_counter_fields,
lambda _ptftest, _asic_type, _port: sai_thrift_read_port_counters(
_ptftest.clients['src'], _asic_type, port_list['src'][_port]
)[0]
],
'QueCnt': [
[queue_counter_field_template.format(i) for i in range(QUEUE_NUM)],
lambda _ptftest, _asic_type, _port: sai_thrift_read_port_counters(
_ptftest.clients['src'], _asic_type, port_list['src'][_port]
)[1]
],
'QueShareWm': [
[queue_share_wm_field_template.format(i) for i in range(QUEUE_NUM)],
lambda _ptftest, _, _port: sai_thrift_read_port_watermarks(
_ptftest.clients['src'], port_list['src'][_port]
)[0]
],
'PgShareWm': [
[pg_share_wm_field_template.format(i) for i in range(PG_NUM)],
lambda _ptftest, _, _port: sai_thrift_read_port_watermarks(
_ptftest.clients['src'], port_list['src'][_port]
)[1]
],
'PgHdrmWm': [
[pg_headroom_wm_field_template.format(i) for i in range(PG_NUM)],
lambda _ptftest, _, _port: sai_thrift_read_port_watermarks(
_ptftest.clients['src'], port_list['src'][_port]
)[2]
],
'PgCnt': [
[pg_counter_field_template.format(i) for i in range(PG_NUM)],
lambda _ptftest, _, _port: sai_thrift_read_pg_counters(
_ptftest.clients['src'], port_list['src'][_port]
)
],
'PgDrop': [
[pg_drop_field_template.format(i) for i in range(PG_NUM)],
lambda _ptftest, _, _port: sai_thrift_read_pg_drop_counters(
_ptftest.clients['src'], port_list['src'][_port]
)
],
'PtfCnt': [
['rx', 'tx'],
lambda _ptftest, _, _port: read_ptf_counters(
_ptftest.dataplane, _port
)
]
}
if self.counter_name not in counter_info:
return None
counter_fields, query_func = counter_info[self.counter_name]
table = texttable.TextTable(['port'] + counter_fields, attr_name='step', attr_value=step_name)
for port in self.flat_ports:
data = query_func(self.ptftest, self.asic_type, port)
table.add_row([port] + data)
self.steps.append({'table': table, 'name': step_name, 'desc': step_desc})
current = len(self.steps) - 1
if compare:
compare_table = self.__find_table(compare, from_curr_to_prev=current)
merged_table = texttable.TextTable.merge_table(table, compare_table)
log_message('collect_counter {} {}\n{}\n'.format(
self.counter_name,
step_name + '({})'.format(step_desc) if step_desc is not None else '',
merged_table))
def __find_table(self, counter, from_curr_to_prev=False):
if isinstance(counter, str):
return next((s['table'] for s in self.steps if s['name'] == counter), None)
elif isinstance(counter, int) and not isinstance(counter, bool): # True is instance of int, so exclude bool
return self.steps[counter]['table'] if counter in list(range(len(self.steps))) or counter == -1 else None
if from_curr_to_prev:
return self.steps[from_curr_to_prev - 1]['table'] if from_curr_to_prev != 0 else None
return None
def compare_counter(self, changed_counter, base_counter):
if not self.valid:
return
base_table = self.__find_table(base_counter)
changed_table = self.__find_table(changed_counter)
if base_table and changed_table:
merged_table = texttable.TextTable.merge_table(changed_table, base_table)
log_message('compare_counter {} {}~{}\n{}\n'.format(
self.counter_name, base_counter, changed_counter, merged_table))
def initialize_diag_counter(ptftest):
ptftest.counter_collectors = {}
for counter_name in ['PortCnt', 'QueCnt', 'QueShareWm', 'PgShareWm', 'PgHdrmWm', 'PgCnt', 'PgDrop', 'PtfCnt']:
ptftest.counter_collectors[counter_name] = CounterCollector(ptftest, counter_name)
# not need to show counter for init stage
ptftest.counter_collectors[counter_name].collect_counter('init', compare=False)
def capture_diag_counter(ptftest, step_name='run', step_desc=None):
if not hasattr(ptftest, 'counter_collectors') or not ptftest.counter_collectors:
return
for collector in ptftest.counter_collectors.values():
if isinstance(collector, CounterCollector):
collector.collect_counter(step_name, step_desc)
def summarize_diag_counter(ptftest, changed_counter=-1, base_counter=0):
if not hasattr(ptftest, 'counter_collectors') or not ptftest.counter_collectors:
return
for collector in ptftest.counter_collectors.values():
if isinstance(collector, CounterCollector):
collector.compare_counter(changed_counter, base_counter)
def qos_test_assert(ptftest, condition, message=None):
try:
assert condition, message
except AssertionError:
summarize_diag_counter(ptftest)
raise # Re-raise the assertion error to maintain the original assert behavior
def check_leackout_compensation_support(asic, hwsku):
if 'broadcom' in asic.lower():
return True
return False
def get_ip_addr():
val = 1
while True:
val = max(val, (val+1) % 250)
yield "192.0.0.{}".format(val)
def get_tcp_port():
val = 1234
while True:
yield val
val += 10
if val > 65534:
val = 1234
TCP_PORT_GEN = get_tcp_port()
IP_ADDR = get_ip_addr()
def construct_tcp_pkt(pkt_len, dst_mac, src_mac, src_ip, dst_ip, dscp, src_vlan, tcp_sport, tcp_dport, **kwargs):
ecn = kwargs.get('ecn', 1)
ip_id = kwargs.get('ip_id', None)
ttl = kwargs.get('ttl', None)
exp_pkt = kwargs.get('exp_pkt', False)
tos = (dscp << 2) | ecn
pkt_args = {
'pktlen': pkt_len,
'eth_dst': dst_mac,
'eth_src': src_mac,
'ip_src': src_ip,
'ip_dst': dst_ip,
'ip_tos': tos,
'tcp_sport': tcp_sport,
'tcp_dport': tcp_dport
}
if ip_id is not None:
pkt_args['ip_id'] = ip_id
if ttl is not None:
pkt_args['ip_ttl'] = ttl
if src_vlan is not None:
pkt_args['dl_vlan_enable'] = True
pkt_args['vlan_vid'] = int(src_vlan)
pkt_args['vlan_pcp'] = dscp
pkt = simple_tcp_packet(**pkt_args)
if exp_pkt:
masked_exp_pkt = Mask(pkt, ignore_extra_bytes=True)
masked_exp_pkt.set_do_not_care_scapy(scapy.Ether, "dst")
masked_exp_pkt.set_do_not_care_scapy(scapy.Ether, "src")
masked_exp_pkt.set_do_not_care_scapy(scapy.IP, "chksum")
masked_exp_pkt.set_do_not_care_scapy(scapy.IP, "ttl")
masked_exp_pkt.set_do_not_care_scapy(scapy.IP, "len")
masked_exp_pkt.set_do_not_care_scapy(scapy.IP, "len")
if src_vlan is not None:
masked_exp_pkt.set_do_not_care_scapy(scapy.Dot1Q, "vlan")
return masked_exp_pkt
else:
return pkt
def get_multiple_flows(dp, dst_mac, dst_id, dst_ip, src_vlan, dscp, ecn, ttl,
pkt_len, src_details, packets_per_port=1, check_actual_dst_id=True):
'''
Returns a dict of format:
src_id : [list of (pkt, exp_pkt) pairs that go to the given dst_id]
'''
def get_rx_port_pkt(dp, src_port_id, pkt, exp_pkt):
send_packet(dp, src_port_id, pkt, 1)
result = dp.dataplane.poll(
device_number=0, exp_pkt=exp_pkt, timeout=3)
if isinstance(result, dp.dataplane.PollFailure):
dp.fail("Expected packet was not received. Received on port:{} {}".format(
result.port, result.format()))
return result.port
print("Need : {} flows total, {} sources, {} packets per port".format(
len(src_details)*packets_per_port, len(src_details), packets_per_port))
all_pkts = {}
for src_tuple in src_details:
num_of_pkts = 0
while (num_of_pkts < packets_per_port):
attempts = 0
while (attempts < 20):
ip_Addr = next(IP_ADDR)
pkt_args = {
'ip_ecn': ecn,
'ip_ttl': ttl,
'pktlen': pkt_len,
'eth_dst': dst_mac or dp.dataplane.get_mac(0, dst_id),
'eth_src': dp.dataplane.get_mac(0, src_tuple[0]),
'ip_src': ip_Addr,
'ip_dst': dst_ip,
'ip_dscp': dscp,
'tcp_sport': 1234,
'tcp_dport': next(TCP_PORT_GEN)}
if src_vlan:
pkt_args.update({'dl_vlan_enable': True})
pkt_args.update({'vlan_vid': int(src_vlan)})
pkt = simple_tcp_packet(**pkt_args)
masked_exp_pkt = Mask(pkt, ignore_extra_bytes=True)
masked_exp_pkt.set_do_not_care_scapy(scapy.Ether, "dst")
masked_exp_pkt.set_do_not_care_scapy(scapy.Ether, "src")
masked_exp_pkt.set_do_not_care_scapy(scapy.IP, "chksum")
masked_exp_pkt.set_do_not_care_scapy(scapy.IP, "ttl")
masked_exp_pkt.set_do_not_care_scapy(scapy.IP, "len")
if src_vlan is not None:
masked_exp_pkt.set_do_not_care_scapy(scapy.Dot1Q, "vlan")
try:
all_pkts[src_tuple[0]]
except KeyError:
all_pkts[src_tuple[0]] = []
if check_actual_dst_id is False:
actual_dst_id = dst_id
else:
actual_dst_id = get_rx_port_pkt(dp, src_tuple[0], pkt, masked_exp_pkt)
if actual_dst_id == dst_id:
all_pkts[src_tuple[0]].append((pkt, masked_exp_pkt, dst_id))
num_of_pkts += 1
break
else:
attempts += 1
if attempts > 20:
# We exceeded the number of attempts to get a
# packet for this particular dest port. This
# means the packets are going to a different port
# consistently. Lets use that other port as dest
# port.
print("Warn: The packets are not going to the dst_port_id.")
all_pkts[src_tuple[0]].append((
pkt, masked_exp_pkt, actual_dst_id))
return all_pkts
def dynamically_compensate_leakout(
thrift_client, asic_type, counter_checker, check_port, check_field,
base, ptf_test, compensate_port, compensate_pkt, max_retry):
prev = base
time.sleep(1.5)
curr, _ = counter_checker(thrift_client, asic_type, check_port)
leakout_num = curr[check_field] - prev[check_field]
retry = 0
num = 0
while leakout_num > 0 and retry < max_retry:
send_packet(ptf_test, compensate_port, compensate_pkt, leakout_num)
num += leakout_num
prev = curr
curr, _ = counter_checker(thrift_client, asic_type, check_port)
leakout_num = curr[check_field] - prev[check_field]
retry += 1
sys.stderr.write('Compensate {} packets to port {}, and retry {} times\n'.format(
num, compensate_port, retry))
return num
def construct_ip_pkt(pkt_len, dst_mac, src_mac, src_ip, dst_ip, dscp, src_vlan, **kwargs):
ecn = kwargs.get('ecn', 1)
ip_id = kwargs.get('ip_id', None)
ttl = kwargs.get('ttl', None)
exp_pkt = kwargs.get('exp_pkt', False)
tos = (dscp << 2) | ecn
pkt_args = {
'pktlen': pkt_len,
'eth_dst': dst_mac,
'eth_src': src_mac,
'ip_src': src_ip,
'ip_dst': dst_ip,
'ip_tos': tos
}
if ip_id is not None:
pkt_args['ip_id'] = ip_id
if ttl is not None:
pkt_args['ip_ttl'] = ttl
if src_vlan is not None:
pkt_args['dl_vlan_enable'] = True
pkt_args['vlan_vid'] = int(src_vlan)
pkt_args['vlan_pcp'] = dscp
pkt = simple_ip_packet(**pkt_args)
if exp_pkt:
masked_exp_pkt = Mask(pkt, ignore_extra_bytes=True)
masked_exp_pkt.set_do_not_care_scapy(scapy.Ether, "dst")
masked_exp_pkt.set_do_not_care_scapy(scapy.Ether, "src")
masked_exp_pkt.set_do_not_care_scapy(scapy.IP, "chksum")
masked_exp_pkt.set_do_not_care_scapy(scapy.IP, "ttl")
masked_exp_pkt.set_do_not_care_scapy(scapy.IP, "len")
masked_exp_pkt.set_do_not_care_scapy(scapy.IP, "len")
if src_vlan is not None:
masked_exp_pkt.set_do_not_care_scapy(scapy.Dot1Q, "vlan")
return masked_exp_pkt
else:
return pkt
def construct_arp_pkt(eth_dst, eth_src, arp_op, src_ip, dst_ip, hw_dst, src_vlan):
pkt_args = {
'eth_dst': eth_dst,
'eth_src': eth_src,
'arp_op': arp_op,
'ip_snd': src_ip,
'ip_tgt': dst_ip,
'hw_snd': eth_src,
'hw_tgt': hw_dst
}
if src_vlan is not None:
pkt_args['vlan_vid'] = int(src_vlan)
pkt_args['vlan_pcp'] = 0
pkt = simple_arp_packet(**pkt_args)
return pkt
def get_rx_port(dp, device_number, src_port_id, dst_mac, dst_ip, src_ip, src_vlan=None):
ip_id = 0xBABE
src_port_mac = dp.dataplane.get_mac(device_number, src_port_id)
pkt = construct_ip_pkt(64, dst_mac, src_port_mac,
src_ip, dst_ip, 0, src_vlan, ip_id=ip_id)
# Send initial packet for any potential ARP resolution, which may cause the LAG
# destination to change. Can occur especially when running tests in isolation on a
# first test attempt.
send_packet(dp, src_port_id, pkt, 1)
# Observed experimentally this sleep needs to be at least 0.02 seconds. Setting higher.
time.sleep(1)
send_packet(dp, src_port_id, pkt, 1)
masked_exp_pkt = construct_ip_pkt(
48, dst_mac, src_port_mac, src_ip, dst_ip, 0, src_vlan, ip_id=ip_id, exp_pkt=True)
pre_result = dp.dataplane.poll(
device_number=0, exp_pkt=masked_exp_pkt, timeout=3)
result = dp.dataplane.poll(
device_number=0, exp_pkt=masked_exp_pkt, timeout=3)
if pre_result.port != result.port:
logging.debug("During get_rx_port, corrected LAG destination from {} to {}".format(
pre_result.port, result.port))
if isinstance(result, dp.dataplane.PollFailure):
dp.fail("Expected packet was not received. Received on port:{} {}".format(
result.port, result.format()))
return result.port
def get_counter_names(sonic_version):
ingress_counters = [INGRESS_DROP]
egress_counters = [EGRESS_DROP]
if '201811' not in sonic_version:
ingress_counters.append(INGRESS_PORT_BUFFER_DROP)
egress_counters.append(EGRESS_PORT_BUFFER_DROP)
return ingress_counters, egress_counters
def fill_leakout_plus_one(
test_case, src_port_id, dst_port_id, pkt, queue, asic_type,
pkts_num_egr_mem=None):
# Attempts to queue 1 packet while compensating for a varying packet leakout.
# Returns whether 1 packet was successfully enqueued.
if pkts_num_egr_mem is not None:
if test_case.clients['dst'] != test_case.clients['src']:
fill_egress_plus_one(
test_case, src_port_id, pkt, queue,
asic_type, int(pkts_num_egr_mem))
return
if asic_type in ['cisco-8000']:
queue_counters_base = sai_thrift_read_queue_occupancy(
test_case.dst_client, "dst", dst_port_id)
max_packets = 2000
for packet_i in range(max_packets):
send_packet(test_case, src_port_id, pkt, 1)
queue_counters = sai_thrift_read_queue_occupancy(
test_case.clients['dst'], "dst", dst_port_id)
if queue_counters[queue] > queue_counters_base[queue]:
print("fill_leakout_plus_one: Success, sent %d packets, "
"queue occupancy bytes rose from %d to %d" % (
packet_i + 1,
queue_counters_base[queue], queue_counters[queue]),
file=sys.stderr)
return True
raise RuntimeError(
"fill_leakout_plus_one: Fail: src_port_id:{}"
" dst_port_id:{}, pkt:{}, queue:{}".format(
src_port_id, dst_port_id, pkt.__repr__()[0:180], queue))
return False
def fill_egress_plus_one(test_case, src_port_id, pkt, queue, asic_type, pkts_num_egr_mem):
# Attempts to enqueue 1 packet while compensating for a varying packet leakout and egress queues.
# pkts_num_egr_mem is the number of packets in full egress queues, to provide an initial filling boost
# Returns whether 1 packet is successfully enqueued.
if asic_type not in ['cisco-8000']:
return False
pg_cntrs_base = sai_thrift_read_pg_occupancy(
test_case.src_client, port_list['src'][src_port_id])
send_packet(test_case, src_port_id, pkt, pkts_num_egr_mem)
max_packets = 1000
for packet_i in range(max_packets):
send_packet(test_case, src_port_id, pkt, 1)
pg_cntrs = sai_thrift_read_pg_occupancy(
test_case.src_client, port_list['src'][src_port_id])
if pg_cntrs[queue] > pg_cntrs_base[queue]:
print("fill_egress_plus_one: Success, sent %d packets, SQ occupancy bytes rose from %d to %d" % (
pkts_num_egr_mem + packet_i + 1, pg_cntrs_base[queue], pg_cntrs[queue]), file=sys.stderr)
return True
raise RuntimeError("fill_egress_plus_one: Failure, sent %d packets, SQ occupancy bytes rose from %d to %d" % (
pkts_num_egr_mem + max_packets, pg_cntrs_base[queue], pg_cntrs[queue]))
def overflow_egress(test_case, src_port_id, pkt, queue, asic_type):
# Attempts to queue 1 packet while compensating for a varying packet
# leakout and egress queues. Returns pkts_num_egr_mem: number of packets
# short of filling egress memory and leakout.
# Returns extra_bytes_occupied:
# extra number of bytes occupied in source port
pkts_num_egr_mem = 0
extra_bytes_occupied = 0
if asic_type not in ['cisco-8000']:
return pkts_num_egr_mem, extra_bytes_occupied
pg_cntrs_base = sai_thrift_read_pg_occupancy(
test_case.src_client, port_list['src'][src_port_id])
max_cycles = 1000
for cycle_i in range(max_cycles):
send_packet(test_case, src_port_id, pkt, 1000)
pg_cntrs = sai_thrift_read_pg_occupancy(
test_case.src_client, port_list['src'][src_port_id])
if pg_cntrs[queue] > pg_cntrs_base[queue]:
print("get_pkts_num_egr_mem: Success, sent %d packets, "
"SQ occupancy bytes rose from %d to %d" % (
(cycle_i + 1) * 1000, pg_cntrs_base[queue],
pg_cntrs[queue]), file=sys.stderr)
pkts_num_egr_mem = cycle_i * 1000
extra_bytes_occupied = pg_cntrs[queue] - pg_cntrs_base[queue]
print("overflow_egress:pkts_num_egr_mem:{}, extra_bytes_occupied:{}".format(
pkts_num_egr_mem, extra_bytes_occupied))
return pkts_num_egr_mem, extra_bytes_occupied
raise RuntimeError("Couldn't overflow the egress memory after 1000 iterations.")
def get_peer_addresses(data):
def get_peer_addr(data, addr):
if isinstance(data, dict) and 'peer_addr' in data:
addr.add(data['peer_addr'])
elif isinstance(data, dict):
for val in data.values():
get_peer_addr(val, addr)
addresses = set()
get_peer_addr(data, addresses)
return list(addresses)
class ARPpopulate(sai_base_test.ThriftInterfaceDataPlane):
def setUp(self):
sai_base_test.ThriftInterfaceDataPlane.setUp(self)
time.sleep(5)
switch_init(self.clients)
# Parse input parameters
self.router_mac = self.test_params['router_mac']
self.dst_port_id = int(self.test_params['dst_port_id'])
self.dst_port_ip = self.test_params['dst_port_ip']
self.dst_port_mac = self.dataplane.get_mac(0, self.dst_port_id)
self.dst_vlan = self.test_params['dst_port_vlan']
self.src_port_id = int(self.test_params['src_port_id'])
self.src_port_ip = self.test_params['src_port_ip']
self.src_port_mac = self.dataplane.get_mac(0, self.src_port_id)
self.src_vlan = self.test_params['src_port_vlan']
self.dst_port_2_id = int(self.test_params['dst_port_2_id'])
self.dst_port_2_ip = self.test_params['dst_port_2_ip']
self.dst_port_2_mac = self.dataplane.get_mac(0, self.dst_port_2_id)
self.dst_vlan_2 = self.test_params['dst_port_2_vlan']
self.dst_port_3_id = int(self.test_params['dst_port_3_id'])
self.dst_port_3_ip = self.test_params['dst_port_3_ip']
self.dst_port_3_mac = self.dataplane.get_mac(0, self.dst_port_3_id)
self.dst_vlan_3 = self.test_params['dst_port_3_vlan']
self.test_port_ids = self.test_params.get("testPortIds", None)
self.test_port_ips = self.test_params.get("testPortIps", None)
self.src_dut_index = self.test_params['src_dut_index']
self.src_asic_index = self.test_params.get('src_asic_index', None)
self.dst_dut_index = self.test_params['dst_dut_index']
self.dst_asic_index = self.test_params.get('dst_asic_index', None)
self.testbed_type = self.test_params['testbed_type']
def tearDown(self):
sai_base_test.ThriftInterfaceDataPlane.tearDown(self)
def runTest(self):
# ARP Populate
# Ping only required for testports
if 't2' in self.testbed_type:
src_is_multi_asic = self.test_params['src_is_multi_asic']
dst_is_multi_asic = self.test_params['dst_is_multi_asic']
dst_port_ips = [self.dst_port_ip, self.dst_port_2_ip, self.dst_port_3_ip]
for ip in dst_port_ips:
if dst_is_multi_asic:
stdOut, stdErr, retValue = self.exec_cmd_on_dut(self.dst_server_ip,
self.test_params['dut_username'],
self.test_params['dut_password'],
'sudo ip netns exec asic{} ping -q -c 3 {}'.format(
self.dst_asic_index, ip))
assert ' 0% packet loss' in stdOut[3], "Ping failed for IP:'{}' on asic '{}' on Dut '{}'".format(
ip, self.dst_asic_index, self.dst_server_ip)
else:
stdOut, stdErr, retValue = self.exec_cmd_on_dut(self.dst_server_ip,
self.test_params['dut_username'],
self.test_params['dut_password'],
'ping -q -c 3 {}'.format(ip))
assert ' 0% packet loss' in stdOut[3], "Ping failed for IP:'{}' on Dut '{}'".format(
ip, self.dst_server_ip)
if src_is_multi_asic:
stdOut, stdErr, retValue = self.exec_cmd_on_dut(self.src_server_ip, self.test_params['dut_username'],
self.test_params['dut_password'],
'sudo ip netns exec asic{} ping -q -c 3 {}'.format(
self.src_asic_index, self.src_port_ip))
assert ' 0% packet loss' in stdOut[3], "Ping failed for IP:'{}' on asic '{}' on Dut '{}'".format(
self.src_port_ip, self.src_asic_index, self.src_server_ip)
else:
stdOut, stdErr, retValue = self.exec_cmd_on_dut(self.src_server_ip, self.test_params['dut_username'],
self.test_params['dut_password'],
'ping -q -c 3 {}'.format(self.src_port_ip))
assert ' 0% packet loss' in stdOut[3], "Ping failed for IP:'{}' on Dut '{}'".format(
self.src_port_ip, self.src_server_ip)
else:
arpreq_pkt = construct_arp_pkt('ff:ff:ff:ff:ff:ff', self.src_port_mac,
1, self.src_port_ip, '192.168.0.1', '00:00:00:00:00:00', self.src_vlan)
send_packet(self, self.src_port_id, arpreq_pkt)
arpreq_pkt = construct_arp_pkt('ff:ff:ff:ff:ff:ff', self.dst_port_mac,
1, self.dst_port_ip, '192.168.0.1', '00:00:00:00:00:00', self.dst_vlan)
send_packet(self, self.dst_port_id, arpreq_pkt)
arpreq_pkt = construct_arp_pkt('ff:ff:ff:ff:ff:ff', self.dst_port_2_mac, 1,
self.dst_port_2_ip, '192.168.0.1', '00:00:00:00:00:00', self.dst_vlan_2)
send_packet(self, self.dst_port_2_id, arpreq_pkt)
arpreq_pkt = construct_arp_pkt('ff:ff:ff:ff:ff:ff', self.dst_port_3_mac, 1,
self.dst_port_3_ip, '192.168.0.1', '00:00:00:00:00:00', self.dst_vlan_3)
send_packet(self, self.dst_port_3_id, arpreq_pkt)
for dut_i in self.test_port_ids:
for asic_i in self.test_port_ids[dut_i]:
for dst_port_id in self.test_port_ids[dut_i][asic_i]:
dst_port_ip = self.test_port_ips[dut_i][asic_i][dst_port_id]
dst_port_mac = self.dataplane.get_mac(0, dst_port_id)
arpreq_pkt = construct_arp_pkt('ff:ff:ff:ff:ff:ff', dst_port_mac,
1, dst_port_ip['peer_addr'], '192.168.0.1',
'00:00:00:00:00:00', None)
send_packet(self, dst_port_id, arpreq_pkt)
# ptf don't know the address of neighbor, use ping to learn relevant arp entries instead of send arp request
if self.test_port_ips:
ips = [ip for ip in get_peer_addresses(self.test_port_ips)]
if ips:
cmd = 'for ip in {}; do ping -c 4 -i 0.2 -W 1 -q $ip > /dev/null 2>&1 & done'.format(' '.join(ips))
self.exec_cmd_on_dut(self.server, self.test_params['dut_username'],
self.test_params['dut_password'], cmd)
time.sleep(8)
class ARPpopulatePTF(sai_base_test.ThriftInterfaceDataPlane):
def runTest(self):
# ARP Populate
index = 0
for port in ptf_ports():
arpreq_pkt = simple_arp_packet(
eth_dst='ff:ff:ff:ff:ff:ff',
eth_src=self.dataplane.get_mac(port[0], port[1]),
arp_op=1,
ip_snd='10.0.0.%d' % (index * 2 + 1),
ip_tgt='10.0.0.%d' % (index * 2),
hw_snd=self.dataplane.get_mac(port[0], port[1]),
hw_tgt='ff:ff:ff:ff:ff:ff')
send_packet(self, port[1], arpreq_pkt)
index += 1
class ReleaseAllPorts(sai_base_test.ThriftInterfaceDataPlane):
def runTest(self):
switch_init(self.clients)
asic_type = self.test_params['sonic_asic_type']
for target, a_client in self.clients.items():
self.sai_thrift_port_tx_enable(a_client, asic_type, list(port_list[target].keys()), target=target)
# DSCP to queue mapping
class DscpMappingPB(sai_base_test.ThriftInterfaceDataPlane):
def get_port_id(self, client, port_name):
sai_port_id = client.sai_thrift_get_port_id_by_front_port(
port_name
)
print("Port name {}, SAI port id {}".format(
port_name, sai_port_id
), file=sys.stderr)
return sai_port_id
def runTest(self):
switch_init(self.clients)
router_mac = self.test_params['router_mac']
dst_port_id = int(self.test_params['dst_port_id'])
dst_port_ip = self.test_params['dst_port_ip']
dst_port_mac = self.dataplane.get_mac(0, dst_port_id)
src_port_id = int(self.test_params['src_port_id'])
src_port_ip = self.test_params['src_port_ip']
src_port_mac = self.dataplane.get_mac(0, src_port_id)
dual_tor_scenario = self.test_params.get('dual_tor_scenario', None)
dual_tor = self.test_params.get('dual_tor', None)
leaf_downstream = self.test_params.get('leaf_downstream', None)
asic_type = self.test_params['sonic_asic_type']
tc_to_dscp_count_map = self.test_params.get('tc_to_dscp_count_map', None)
exp_ip_id = 101
exp_ttl = 63
pkt_dst_mac = router_mac if router_mac != '' else dst_port_mac
print("dst_port_id: %d, src_port_id: %d" %
(dst_port_id, src_port_id), file=sys.stderr)
# in case dst_port_id is part of LAG, find out the actual dst port
# for given IP parameters
dst_port_id = get_rx_port(
self, 0, src_port_id, pkt_dst_mac, dst_port_ip, src_port_ip
)
print("actual dst_port_id: %d" % (dst_port_id), file=sys.stderr)
print("dst_port_mac: %s, src_port_mac: %s, src_port_ip: %s, dst_port_ip: %s" % (
dst_port_mac, src_port_mac, src_port_ip, dst_port_ip), file=sys.stderr)
print("port list {}".format(port_list), file=sys.stderr)
# Get a snapshot of counter values
# Destination port on a backend ASIC is provide as a port name
test_dst_port_name = self.test_params.get("test_dst_port_name")
sai_dst_port_id = None
if test_dst_port_name is not None:
sai_dst_port_id = self.get_port_id(self.dst_client, test_dst_port_name)
else:
sai_dst_port_id = port_list['dst'][dst_port_id]
time.sleep(10)
# port_results is not of our interest here
port_results, queue_results_base = sai_thrift_read_port_counters(self.dst_client, asic_type, sai_dst_port_id)
masic = self.clients['src'] != self.clients['dst']
# DSCP Mapping test
try:
ip_ttl = exp_ttl + 1 if router_mac != '' else exp_ttl
# TTL changes on multi ASIC platforms,
# add 2 for additional backend and frontend routing
ip_ttl = ip_ttl if test_dst_port_name is None else ip_ttl + 2
if asic_type in ["cisco-8000"] and masic:
ip_ttl = ip_ttl + 1 if masic else ip_ttl
for dscp in range(0, 64):
tos = (dscp << 2)
tos |= 1
pkt = simple_ip_packet(pktlen=64,
eth_dst=pkt_dst_mac,
eth_src=src_port_mac,
ip_src=src_port_ip,
ip_dst=dst_port_ip,
ip_tos=tos,
ip_id=exp_ip_id,
ip_ttl=ip_ttl)
send_packet(self, src_port_id, pkt, 1)
print("dscp: %d, calling send_packet()" %
(tos >> 2), file=sys.stderr)
cnt = 0
dscp_received = False
while not dscp_received:
result = self.dataplane.poll(
device_number=0, port_number=dst_port_id, timeout=3)
if isinstance(result, self.dataplane.PollFailure):
self.fail("Expected packet was not received on port %d. Total received: %d.\n%s" % (
dst_port_id, cnt, result.format()))
recv_pkt = scapy.Ether(result.packet)
cnt += 1
# Verify dscp flag
try:
if (recv_pkt.payload.tos == tos and
recv_pkt.payload.src == src_port_ip and
recv_pkt.payload.dst == dst_port_ip and
recv_pkt.payload.ttl == exp_ttl and
recv_pkt.payload.id == exp_ip_id):
dscp_received = True
print("dscp: %d, total received: %d" %
(tos >> 2, cnt), file=sys.stderr)
except AttributeError:
print("dscp: %d, total received: %d, attribute error!" % (
tos >> 2, cnt), file=sys.stderr)
continue
# Read Counters
time.sleep(3)
port_results, queue_results = sai_thrift_read_port_counters(self.dst_client, asic_type, sai_dst_port_id)
print(list(map(operator.sub, queue_results,
queue_results_base)), file=sys.stderr)
# dual_tor_scenario: represents whether the device is deployed into a dual ToR scenario
# dual_tor: represents whether the source and
# destination ports are configured with additional lossless queues
# According to SONiC configuration all dscp are classified to queue 1 except:
# Normal scenario Dual ToR scenario Leaf router with separated DSCP_TO_TC_MAP # noqa E501
# All ports Normal ports Ports with additional lossless queues downstream (source is T2) upstream (source is T0) # noqa E501
# dscp 8 -> queue 0 queue 0 queue 0 queue 0 queue 0 # noqa E501
# dscp 5 -> queue 2 queue 1 queue 1 queue 1 queue 1 # noqa E501
# dscp 3 -> queue 3 queue 3 queue 3 queue 3 queue 3 # noqa E501
# dscp 4 -> queue 4 queue 4 queue 4 queue 4 queue 4 # noqa E501
# dscp 46 -> queue 5 queue 5 queue 5 queue 5 queue 5 # noqa E501
# dscp 48 -> queue 6 queue 7 queue 7 queue 7 queue 7 # noqa E501
# dscp 2 -> queue 1 queue 1 queue 2 queue 1 queue 2 # noqa E501
# dscp 6 -> queue 1 queue 1 queue 6 queue 1 queue 6 # noqa E501
# rest 56 dscps -> queue 1
# So for the 64 pkts sent the mapping should be the following:
# queue 1 56 + 2 = 58 56 + 3 = 59 56 + 1 = 57 59 57 # noqa E501
# queue 2/6 1 0 1 0 0 # noqa E501
# queue 3/4 1 1 1 1 1 # noqa E501
# queue 5 1 1 1 1 1 # noqa E501
# queue 7 0 1 1 1 1 # noqa E501
if tc_to_dscp_count_map:
for tc in tc_to_dscp_count_map.keys():
if tc == 7:
# LAG ports can have LACP packets on queue 7, hence using >= comparison
assert (queue_results[tc] >= tc_to_dscp_count_map[tc] + queue_results_base[tc])
else:
assert (queue_results[tc] == tc_to_dscp_count_map[tc] + queue_results_base[tc])
else:
assert (queue_results[QUEUE_0] == 1 + queue_results_base[QUEUE_0])
assert (queue_results[QUEUE_3] == 1 + queue_results_base[QUEUE_3])
assert (queue_results[QUEUE_4] == 1 + queue_results_base[QUEUE_4])
assert (queue_results[QUEUE_5] == 1 + queue_results_base[QUEUE_5])
if dual_tor or (dual_tor_scenario is False) or (leaf_downstream is False):
assert (queue_results[QUEUE_2] == 1 +
queue_results_base[QUEUE_2])
assert (queue_results[QUEUE_6] == 1 +
queue_results_base[QUEUE_6])
else:
assert (queue_results[QUEUE_2] == queue_results_base[QUEUE_2])
assert (queue_results[QUEUE_6] == queue_results_base[QUEUE_6])
if dual_tor_scenario:
if (dual_tor is False) or leaf_downstream:
assert (queue_results[QUEUE_1] ==
59 + queue_results_base[QUEUE_1])
else:
assert (queue_results[QUEUE_1] ==
57 + queue_results_base[QUEUE_1])
# LAG ports can have LACP packets on queue 7, hence using >= comparison
assert (queue_results[QUEUE_7] >= 1 +
queue_results_base[QUEUE_7])
else:
assert (queue_results[QUEUE_1] == 58 +
queue_results_base[QUEUE_1])
# LAG ports can have LACP packets on queue 7, hence using >= comparison
assert (queue_results[QUEUE_7] >= queue_results_base[QUEUE_7])
finally:
print("END OF TEST", file=sys.stderr)
# DOT1P to queue mapping
class Dot1pToQueueMapping(sai_base_test.ThriftInterfaceDataPlane):
def runTest(self):
switch_init(self.clients)
# Parse input parameters
router_mac = self.test_params['router_mac']
print("router_mac: %s" % (router_mac), file=sys.stderr)
dst_port_id = int(self.test_params['dst_port_id'])
dst_port_ip = self.test_params['dst_port_ip']
dst_port_mac = self.dataplane.get_mac(0, dst_port_id)
src_port_id = int(self.test_params['src_port_id'])
src_port_ip = self.test_params['src_port_ip']
src_port_mac = self.dataplane.get_mac(0, src_port_id)
print("dst_port_id: %d, src_port_id: %d" %