-
Notifications
You must be signed in to change notification settings - Fork 753
/
Copy pathtest_vrf.py
1752 lines (1398 loc) · 68.9 KB
/
test_vrf.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sys
import time
import threading
import yaml
import json
import random
import logging
import tempfile
import traceback
from collections import OrderedDict
from natsort import natsorted
from netaddr import IPNetwork
from six.moves import queue
import pytest
from tests.common.fixtures.ptfhost_utils import copy_ptftests_directory # noqa F401
from tests.common.fixtures.ptfhost_utils import change_mac_addresses # noqa F401
from tests.common.storage_backend.backend_utils import skip_test_module_over_backend_topologies # noqa F401
from tests.ptf_runner import ptf_runner
from tests.common.utilities import wait_until
from tests.common.reboot import reboot
from tests.common.helpers.assertions import pytest_assert
"""
During vrf testing, a vrf basic configuration need to be setup before any tests,
and cleanup after all tests. Both of the two tasks should be called only once.
A module-scoped fixture `setup_vrf` is added to accompilsh the setup/cleanup tasks.
We want to use ansible_adhoc/tbinfo fixtures during the setup/cleanup stages, but
1. Injecting fixtures to xunit-style setup/teardown functions is not support by
[now](https://github.com/pytest-dev/pytest/issues/5289).
2. Calling a fixture function directly is deprecated.
So, we prefer a fixture rather than xunit-style setup/teardown functions.
"""
pytestmark = [
pytest.mark.topology('t0')
]
logger = logging.getLogger(__name__)
# global variables
g_vars = {}
PTF_TEST_PORT_MAP = '/root/ptf_test_port_map.json'
PORTCHANNEL_TEMP_NAME = 'PortChannel10{}'
PORTCHANNEL_TEMP_1 = PORTCHANNEL_TEMP_NAME.format(1)
PORTCHANNEL_TEMP_2 = PORTCHANNEL_TEMP_NAME.format(2)
# helper functions
def get_vlan_members(vlan_name, cfg_facts):
tmp_member_list = []
for m in list(cfg_facts['VLAN_MEMBER'].keys()):
v, port = m.split('|')
if vlan_name == v:
tmp_member_list.append(port)
return natsorted(tmp_member_list)
def get_pc_members(portchannel_name, cfg_facts):
tmp_member_list = []
for m in list(cfg_facts['PORTCHANNEL_MEMBER'].keys()):
pc, port = m.split('|')
if portchannel_name == pc:
tmp_member_list.append(port)
return natsorted(tmp_member_list)
def get_intf_ips(interface_name, cfg_facts):
prefix_to_intf_table_map = {
'Vlan': 'VLAN_INTERFACE',
'PortChannel': 'PORTCHANNEL_INTERFACE',
'Ethernet': 'INTERFACE',
'Loopback': 'LOOPBACK_INTERFACE'
}
intf_table_name = None
ip_facts = {
'ipv4': [],
'ipv6': []
}
for pfx, t_name in list(prefix_to_intf_table_map.items()):
if pfx in interface_name:
intf_table_name = t_name
break
if intf_table_name is None:
return ip_facts
for intf in cfg_facts[intf_table_name]:
if '|' in intf:
if_name, ip = intf.split('|')
if if_name == interface_name:
ip = IPNetwork(ip)
if ip.version == 4:
ip_facts['ipv4'].append(ip)
else:
ip_facts['ipv6'].append(ip)
return ip_facts
def get_cfg_facts(duthost):
# return config db contents(running-config)
tmp_facts = json.loads(duthost.shell(
"sonic-cfggen -d --print-data")['stdout'])
port_name_list_sorted = natsorted(list(tmp_facts['PORT'].keys()))
port_index_map = {}
for idx, val in enumerate(port_name_list_sorted):
port_index_map[val] = idx
tmp_facts['config_port_indices'] = port_index_map
return tmp_facts
def get_vrf_intfs(cfg_facts):
intf_tables = ['INTERFACE', 'PORTCHANNEL_INTERFACE',
'VLAN_INTERFACE', 'LOOPBACK_INTERFACE']
vrf_intfs = {}
for table in intf_tables:
for intf, attrs in list(cfg_facts.get(table, {}).items()):
if '|' not in intf:
vrf = attrs['vrf_name']
if vrf not in vrf_intfs:
vrf_intfs[vrf] = {}
vrf_intfs[vrf][intf] = get_intf_ips(intf, cfg_facts)
return vrf_intfs
def get_vrf_ports(cfg_facts):
'''
:return: vrf_member_port_indices, vrf_intf_member_port_indices
'''
vlan_member = list(cfg_facts['VLAN_MEMBER'].keys())
pc_member = list(cfg_facts['PORTCHANNEL_MEMBER'].keys())
member = vlan_member + pc_member
vrf_intf_member_port_indices = {}
vrf_member_port_indices = {}
vrf_intfs = get_vrf_intfs(cfg_facts)
for vrf, intfs in list(vrf_intfs.items()):
vrf_intf_member_port_indices[vrf] = {}
vrf_member_port_indices[vrf] = []
for intf in intfs:
vrf_intf_member_port_indices[vrf][intf] = natsorted(
[cfg_facts['config_port_indices'][m.split('|')[1]] for m in [
m for m in member if intf in m]]
)
vrf_member_port_indices[vrf].extend(
vrf_intf_member_port_indices[vrf][intf])
vrf_member_port_indices[vrf] = natsorted(vrf_member_port_indices[vrf])
return vrf_intf_member_port_indices, vrf_member_port_indices
def ex_ptf_runner(ptf_runner, exc_queue, **kwargs):
'''
With this simple warpper function, we could use a Queue to store the
exception infos and check it later in main thread.
Example:
refer to test 'test_vrf_swss_warm_reboot'
'''
try:
ptf_runner(**kwargs)
except Exception:
exc_queue.put(sys.exc_info())
def finalize_warmboot(duthost, comp_list=None, retry=30, interval=5):
'''
Check if componets finish warmboot(reconciled).
'''
DEFAULT_COMPONENT_LIST = ['orchagent', 'neighsyncd']
EXP_STATE = 'reconciled'
comp_list = comp_list or DEFAULT_COMPONENT_LIST
# wait up to $retry * $interval secs
for _ in range(retry):
for comp in comp_list:
state = duthost.shell('/usr/bin/redis-cli -n 6 hget "WARM_RESTART_TABLE|{}" state'.format(
comp), module_ignore_errors=True)['stdout']
logger.info("{} : {}".format(comp, state))
if EXP_STATE == state:
comp_list.remove(comp)
if len(comp_list) == 0:
break
time.sleep(interval)
logger.info("Slept {} seconds!".format(interval))
return comp_list
def check_interface_status(duthost, up_ports):
intf_facts = duthost.interface_facts(up_ports=up_ports)['ansible_facts']
if len(intf_facts['ansible_interface_link_down_ports']) != 0:
logger.info("Some ports went down: {} ...".format(
intf_facts['ansible_interface_link_down_ports']))
return False
return True
def check_bgp_peer_state(duthost, vrf, peer_ip, expected_state):
peer_info = json.loads(duthost.shell(
"vtysh -c 'show bgp vrf {} neighbors {} json'".format(vrf, peer_ip))['stdout'])
logger.debug("Vrf {} bgp peer {} infos: {}".format(
vrf, peer_ip, peer_info))
try:
peer_state = peer_info[peer_ip].get('bgpState', 'Unknown')
except Exception:
peer_state = 'Unknown'
if peer_state != expected_state:
logger.info("Vrf {} bgp peer {} is {}, exptected {}!".format(
vrf, peer_ip, peer_state, expected_state))
return False
return True
def check_bgp_facts(duthost, cfg_facts):
result = {}
for neigh in cfg_facts['BGP_NEIGHBOR']:
if '|' not in neigh:
vrf = 'default'
peer_ip = neigh
else:
vrf, peer_ip = neigh.split('|')
result[(vrf, peer_ip)] = check_bgp_peer_state(
duthost, vrf, peer_ip, expected_state='Established')
return all(result.values())
def setup_vrf_cfg(duthost, localhost, cfg_facts):
'''
setup vrf configuration on dut before test suite
'''
# FIXME
# For vrf testing, we should create a new vrf topology
# might named to be 't0-vrf', deploy with minigraph templates.
#
# But currently vrf related schema does not properly define in minigraph.
# So we generate and deploy vrf basic configuration with a vrf jinja2 template,
# later should move to minigraph or a better way(VRF and BGP cli).
from copy import deepcopy
cfg_t0 = deepcopy(cfg_facts)
cfg_t0.pop('config_port_indices', None)
# get members from Vlan1000, and move half of them to Vlan2000 in vrf basic cfg
ports = get_vlan_members('Vlan1000', cfg_facts)
vlan_ports = {'Vlan1000': ports[:len(ports)/2],
'Vlan2000': ports[len(ports)/2:]}
extra_vars = {'cfg_t0': cfg_t0,
'vlan_ports': vlan_ports}
duthost.host.options['variable_manager'].extra_vars.update(extra_vars)
duthost.template(src="vrf/vrf_config_db.j2",
dest="/tmp/config_db_vrf.json")
duthost.shell("cp /tmp/config_db_vrf.json /etc/sonic/config_db.json")
reboot(duthost, localhost)
def setup_vlan_peer(duthost, ptfhost, cfg_facts):
'''
setup vlan peer ip addresses on peer port(ptf).
Example:
vid local-port peer-port peer-macvlan-dev peer-namespace peer-ip
Vlan1000 Ethernet1 eth1 e1mv1 ns1000 192.168.0.2/21
FC00:192::2/117
Vlan2000 Ethernet13 eth13 e13mv1 ns2000 192.168.0.2/21
FC00:192::2/117
'''
vlan_peer_ips = {}
vlan_peer_vrf2ns_map = {}
for vlan in list(cfg_facts['VLAN'].keys()):
ns = 'ns' + vlan.strip('Vlan')
vrf = cfg_facts['VLAN_INTERFACE'][vlan]['vrf_name']
vlan_peer_vrf2ns_map[vrf] = ns
vlan_port = get_vlan_members(vlan, cfg_facts)[0]
vlan_peer_port = cfg_facts['config_port_indices'][vlan_port]
# deploy peer namespace on ptf
ptfhost.shell("ip netns add {}".format(ns))
# bind port to namespace
ptfhost.shell("ip link add e{}mv1 link eth{} type macvlan mode bridge".format(
vlan_peer_port, vlan_peer_port))
ptfhost.shell("ip link set e{}mv1 netns {}".format(vlan_peer_port, ns))
ptfhost.shell(
"ip netns exec {} ip link set dev e{}mv1 up".format(ns, vlan_peer_port))
# setup peer ip on ptf
if (vrf, vlan_peer_port) not in vlan_peer_ips:
vlan_peer_ips[(vrf, vlan_peer_port)] = {'ipv4': [], 'ipv6': []}
vlan_ips = get_intf_ips(vlan, cfg_facts)
for ver, ips in list(vlan_ips.items()):
for ip in ips:
neigh_ip = IPNetwork("{}/{}".format(ip.ip+1, ip.prefixlen))
ptfhost.shell("ip netns exec {} ip address add {} dev e{}mv1".format(
ns, neigh_ip, vlan_peer_port))
# ping to trigger neigh resolving
ping_cmd = 'ping' if neigh_ip.version == 4 else 'ping6'
duthost.shell("{} -I {} {} -c 1 -f -W1".format(ping_cmd,
vrf, neigh_ip.ip), module_ignore_errors=True)
vlan_peer_ips[(vrf, vlan_peer_port)][ver].append(neigh_ip)
return vlan_peer_ips, vlan_peer_vrf2ns_map
def cleanup_vlan_peer(ptfhost, vlan_peer_vrf2ns_map):
for vrf, ns in list(vlan_peer_vrf2ns_map.items()):
ptfhost.shell("ip netns del {}".format(ns))
def gen_vrf_fib_file(vrf, tbinfo, ptfhost, render_file, dst_intfs=None,
limited_podset_number=10, limited_tor_number=10):
dst_intfs = dst_intfs if dst_intfs else get_default_vrf_fib_dst_intfs(
vrf, tbinfo)
extra_vars = {
'testbed_type': tbinfo['topo']['name'],
'props': g_vars['props'],
'intf_member_indices': g_vars['vrf_intf_member_port_indices'][vrf],
'dst_intfs': dst_intfs,
'limited_podset_number': limited_podset_number,
'limited_tor_number': limited_tor_number
}
ptfhost.host.options['variable_manager'].extra_vars.update(extra_vars)
ptfhost.template(src="vrf/vrf_fib.j2", dest=render_file)
def get_default_vrf_fib_dst_intfs(vrf, tbinfo):
'''
Get default vrf fib destination interfaces(PortChannels) according to the given vrf.
The test configuration is dynamic and can work with 4 and 8 PCs as the number of VMs.
The first half of PCs are related to Vrf1 and the second to Vrf2.
'''
dst_intfs = []
vms_num = len(tbinfo['topo']['properties']['topology']['VMs'])
if vrf == 'Vrf1':
dst_intfs_range = list(range(1, int(vms_num / 2) + 1))
else:
dst_intfs_range = list(range(int(vms_num / 2) + 1, vms_num + 1))
for intfs_num in dst_intfs_range:
dst_intfs.append(PORTCHANNEL_TEMP_NAME.format(intfs_num))
return dst_intfs
def gen_vrf_neigh_file(vrf, ptfhost, render_file):
extra_vars = {
'intf_member_indices': g_vars['vrf_intf_member_port_indices'][vrf],
'intf_ips': g_vars['vrf_intfs'][vrf]
}
ptfhost.host.options['variable_manager'].extra_vars.update(extra_vars)
ptfhost.template(src="vrf/vrf_neigh.j2", dest=render_file)
def gen_specific_neigh_file(dst_ips, dst_ports, render_file, ptfhost):
dst_ports = [str(port) for port_list in dst_ports for port in port_list]
tmp_file = tempfile.NamedTemporaryFile()
for ip in dst_ips:
tmp_file.write('{} [{}]\n'.format(ip, ' '.join(dst_ports)))
tmp_file.flush()
ptfhost.copy(src=tmp_file.name, dest=render_file)
# For dualtor
def get_dut_enabled_ptf_ports(tbinfo, hostname):
dut_index = str(tbinfo['duts_map'][hostname])
ptf_ports = set(tbinfo['topo']['ptf_map'][dut_index].values())
disabled_ports = set()
if dut_index in tbinfo['topo']['ptf_map_disabled']:
disabled_ports = set(
tbinfo['topo']['ptf_map_disabled'][dut_index].values())
return ptf_ports - disabled_ports
# For dualtor
def get_dut_vlan_ptf_ports(mg_facts):
ports = set()
for vlan in mg_facts['minigraph_vlans']:
for member in mg_facts['minigraph_vlans'][vlan]['members']:
ports.add(mg_facts['minigraph_port_indices'][member])
return ports
def check_vlan_members(duthost, member1, member2, exp_count):
out1 = duthost.shell(
"redis-cli -n 6 keys 'VLAN_MEMBER_TABLE|*|{}' | wc -l".format(member1))['stdout']
out2 = duthost.shell(
"redis-cli -n 6 keys 'VLAN_MEMBER_TABLE|*|{}' | wc -l".format(member2))['stdout']
added = int(out1) + int(out2)
if added >= exp_count * 2:
logger.info('All vlan members added')
return True
logger.info('Not all vlan members are added, {} when expected => {}'.format(
added, (exp_count * 2)))
return False
# fixtures
@pytest.fixture(scope="module")
def dut_facts(duthosts, rand_one_dut_hostname):
duthost = duthosts[rand_one_dut_hostname]
return duthost.facts
@pytest.fixture(scope="module")
def cfg_facts(duthosts, rand_one_dut_hostname):
duthost = duthosts[rand_one_dut_hostname]
return get_cfg_facts(duthost)
def restore_config_db(localhost, duthost, ptfhost):
# In case something went wrong in previous reboot, wait until the DUT is accessible to ensure that
# the `mv /etc/sonic/config_db.json.bak /etc/sonic/config_db.json` is executed on DUT.
# If the DUT is still inaccessible after timeout, we may have already lose the DUT. Something sad happened.
localhost.wait_for(host=g_vars["dut_ip"],
port=22,
state='started',
search_regex='OpenSSH_[\\w\\.]+ Debian',
timeout=180) # Similiar approach to increase the chance that the next line get executed.
duthost.shell("mv /etc/sonic/config_db.json.bak /etc/sonic/config_db.json")
reboot(duthost, localhost)
if 'vlan_peer_vrf2ns_map' in g_vars:
cleanup_vlan_peer(ptfhost, g_vars['vlan_peer_vrf2ns_map'])
@pytest.fixture(scope="module", autouse=True)
def setup_vrf(tbinfo, duthosts, rand_one_dut_hostname, ptfhost, localhost,
skip_test_module_over_backend_topologies): # noqa F811
duthost = duthosts[rand_one_dut_hostname]
# backup config_db.json
duthost.shell("mv /etc/sonic/config_db.json /etc/sonic/config_db.json.bak")
# Setup global variables
global g_vars
try:
# Setup dut
g_vars["dut_ip"] = duthost.host.options["inventory_manager"].get_host(
duthost.hostname).vars["ansible_host"]
# Don't care about 'pmon' and 'lldp' here
duthost.critical_services = [
"swss", "syncd", "database", "teamd", "bgp"]
cfg_t0 = get_cfg_facts(duthost) # generate cfg_facts for t0 topo
setup_vrf_cfg(duthost, localhost, cfg_t0)
# Generate cfg_facts for t0-vrf topo, should not use cfg_facts fixture here. Otherwise, the cfg_facts
# fixture will be executed before setup_vrf and will have the original non-VRF config facts.
cfg_facts = get_cfg_facts(duthost)
duthost.shell("sonic-clear arp")
duthost.shell("sonic-clear nd")
duthost.shell("sonic-clear fdb all")
with open("../ansible/vars/topo_{}.yml".format(tbinfo['topo']['name']), 'r') as fh:
g_vars['topo_properties'] = yaml.safe_load(fh)
g_vars['props'] = g_vars['topo_properties']['configuration_properties']['common']
g_vars['vlan_peer_ips'], g_vars['vlan_peer_vrf2ns_map'] = setup_vlan_peer(
duthost, ptfhost, cfg_facts)
g_vars['vrf_intfs'] = get_vrf_intfs(cfg_facts)
g_vars['vrf_intf_member_port_indices'], g_vars['vrf_member_port_indices'] = get_vrf_ports(
cfg_facts)
except Exception as e:
# Ensure that config_db is restored.
# If exception is raised in setup, the teardown code won't be executed. That's why we need to capture
# exception and do cleanup here in setup part (code before 'yield').
logger.error("Exception raised in setup: {}".format(repr(e)))
logger.error(json.dumps(
traceback.format_exception(*sys.exc_info()), indent=2))
restore_config_db(localhost, duthost, ptfhost)
# Setup failed. There is no point to continue running the cases.
# If this line is hit, script execution will stop here
pytest.fail("VRF testing setup failed")
# --------------------- Testing -----------------------
yield
# --------------------- Teardown -----------------------
restore_config_db(localhost, duthost, ptfhost)
@pytest.fixture
def partial_ptf_runner(request, ptfhost, tbinfo):
def _partial_ptf_runner(testname, **kwargs):
params = {'testbed_type': tbinfo['topo']['name'],
'ptf_test_port_map': PTF_TEST_PORT_MAP
}
params.update(kwargs)
ptf_runner(host=ptfhost,
testdir="ptftests",
platform_dir="ptftests",
testname=testname,
params=params,
socket_recv_size=16384,
log_file="/tmp/{}.{}.log".format(request.cls.__name__, request.function.__name__),
is_python3=True)
return _partial_ptf_runner
@pytest.fixture(scope="module")
def mg_facts(duthosts, rand_one_dut_hostname, tbinfo):
duthost = duthosts[rand_one_dut_hostname]
mg_facts = duthost.get_extended_minigraph_facts(tbinfo)
return mg_facts
# For dualtor
@pytest.fixture(scope='module')
def vlan_mac(duthosts, rand_one_dut_hostname):
duthost = duthosts[rand_one_dut_hostname]
config_facts = duthost.config_facts(
host=duthost.hostname, source='running')['ansible_facts']
dut_vlan_mac = None
for vlan in list(config_facts.get('VLAN', {}).values()):
if 'mac' in vlan:
logger.debug('Found VLAN mac')
dut_vlan_mac = vlan['mac']
break
if not dut_vlan_mac:
logger.debug('No VLAN mac, use default router_mac')
dut_vlan_mac = duthost.facts['router_mac']
return dut_vlan_mac
@pytest.fixture(scope="module", autouse=True)
def ptf_test_port_map(tbinfo, duthosts, mg_facts, ptfhost, rand_one_dut_hostname, vlan_mac):
duthost = duthosts[rand_one_dut_hostname]
ptf_test_port_map = {}
enabled_ptf_ports = get_dut_enabled_ptf_ports(tbinfo, duthost.hostname)
vlan_ptf_ports = get_dut_vlan_ptf_ports(mg_facts)
for port in enabled_ptf_ports:
if port in vlan_ptf_ports:
target_mac = vlan_mac
else:
target_mac = duthost.facts['router_mac']
ptf_test_port_map[str(port)] = {
'target_dut': 0,
'target_dest_mac': target_mac,
'target_src_mac': duthost.facts['router_mac']
}
ptfhost.copy(content=json.dumps(ptf_test_port_map), dest=PTF_TEST_PORT_MAP)
@pytest.fixture()
def disable_swss_warm_boot_flag(duthosts, rand_one_dut_hostname):
yield
duthost = duthosts[rand_one_dut_hostname]
swss_flag = duthost.shell(
"sonic-db-cli STATE_DB HGET 'WARM_RESTART_ENABLE_TABLE|swss' 'enable'")['stdout']
if swss_flag == 'true':
duthost.shell("config warm_restart disable swss")
# tests
class TestVrfCreateAndBind():
def test_vrf_in_kernel(self, duthosts, rand_one_dut_hostname, cfg_facts):
duthost = duthosts[rand_one_dut_hostname]
# verify vrf in kernel
res = duthost.shell("ip link show type vrf | grep Vrf")
for vrf in list(cfg_facts['VRF'].keys()):
assert vrf in res['stdout'], "%s should be created in kernel!" % vrf
for vrf, intfs in list(g_vars['vrf_intfs'].items()):
for intf in intfs:
res = duthost.shell("ip link show %s" % intf)
assert vrf in res['stdout'], "The master dev of interface %s should be %s !" % (
intf, vrf)
def test_vrf_in_appl_db(self, duthosts, rand_one_dut_hostname, cfg_facts):
duthost = duthosts[rand_one_dut_hostname]
# verify vrf in app_db
for vrf in list(cfg_facts['VRF'].keys()):
res = duthost.shell("redis-cli -n 0 keys VRF_TABLE:%s" % vrf)
assert vrf in res['stdout'], "%s should be added in APPL_DB!" % vrf
for vrf, intfs in list(g_vars['vrf_intfs'].items()):
for intf in intfs:
res = duthost.shell(
"redis-cli -n 0 hgetall \"INTF_TABLE:%s\"" % intf)
assert vrf in res['stdout'], "The vrf of interface %s should be %s !" % (
intf, vrf)
def test_vrf_in_asic_db(self, duthosts, rand_one_dut_hostname, cfg_facts):
duthost = duthosts[rand_one_dut_hostname]
# verify vrf in asic_db
# plus default virtual router
vrf_count = len(list(cfg_facts['VRF'].keys())) + 1
res = duthost.shell("redis-cli -n 1 keys *VIRTUAL_ROUTER*")
assert len(res['stdout_lines']) == vrf_count
class TestVrfNeigh():
def test_ping_lag_neigh(self, duthosts, rand_one_dut_hostname, cfg_facts):
duthost = duthosts[rand_one_dut_hostname]
for neigh in cfg_facts['BGP_NEIGHBOR']:
if '|' not in neigh:
continue
vrf, neigh_ip = neigh.split('|')
if IPNetwork(neigh_ip).version == 4:
ping_cmd = 'ping'
else:
ping_cmd = 'ping6'
cmd = "{} {} -I {} -c 3 -f".format(ping_cmd, neigh_ip, vrf)
duthost.shell(cmd)
def test_ping_vlan_neigh(self, duthosts, rand_one_dut_hostname):
duthost = duthosts[rand_one_dut_hostname]
for (vrf, _), neigh_ips in list(g_vars['vlan_peer_ips'].items()):
for ver, ips in list(neigh_ips.items()):
ping_cmd = 'ping' if ver == 'ipv4' else 'ping6'
for ip in ips:
duthost.shell(
"{} {} -c 3 -I {} -f".format(ping_cmd, ip.ip, vrf))
def test_vrf1_neigh_ip_fwd(self, ptfhost, partial_ptf_runner):
gen_vrf_neigh_file('Vrf1', ptfhost, render_file="/tmp/vrf1_neigh.txt")
partial_ptf_runner(
testname="vrf_test.FwdTest",
fib_info_files=["/tmp/vrf1_neigh.txt"],
src_ports=g_vars['vrf_member_port_indices']['Vrf1']
)
def test_vrf2_neigh_ip_fwd(self, ptfhost, partial_ptf_runner):
gen_vrf_neigh_file('Vrf2', ptfhost, render_file="/tmp/vrf2_neigh.txt")
partial_ptf_runner(
testname="vrf_test.FwdTest",
fib_info_files=["/tmp/vrf2_neigh.txt"],
src_ports=g_vars['vrf_member_port_indices']['Vrf2']
)
class TestVrfFib():
@pytest.fixture(scope="class", autouse=True)
def setup_fib_test(self, ptfhost, tbinfo):
gen_vrf_fib_file('Vrf1', tbinfo, ptfhost,
render_file='/tmp/vrf1_fib.txt')
gen_vrf_fib_file('Vrf2', tbinfo, ptfhost,
render_file='/tmp/vrf2_fib.txt')
def test_show_bgp_summary(self, duthosts, rand_one_dut_hostname, cfg_facts):
duthost = duthosts[rand_one_dut_hostname]
props = g_vars['props']
route_count = props['podset_number'] * \
props['tor_number'] * props['tor_subnet_number']
for vrf in cfg_facts['VRF']:
bgp_summary_string = duthost.shell(
"vtysh -c 'show bgp vrf {} summary json'".format(vrf))['stdout']
bgp_summary = json.loads(bgp_summary_string)
for info in bgp_summary:
for peer, attr in list(bgp_summary[info]['peers'].items()):
prefix_count = attr['pfxRcd']
# skip ipv6 peers under 'ipv4Unicast' and compare only ipv4 peers under 'ipv4Unicast',
# and ipv6 peers under 'ipv6Unicast'
if info == "ipv4Unicast" and attr['idType'] == 'ipv6':
continue
else:
assert int(prefix_count) == route_count, "%s should received %s route prefixs!" % (
peer, route_count)
def test_vrf1_fib(self, partial_ptf_runner):
partial_ptf_runner(
testname="vrf_test.FibTest",
fib_info_files=["/tmp/vrf1_fib.txt"],
src_ports=g_vars['vrf_member_port_indices']['Vrf1']
)
def test_vrf2_fib(self, partial_ptf_runner):
partial_ptf_runner(
testname="vrf_test.FibTest",
fib_info_files=["/tmp/vrf2_fib.txt"],
src_ports=g_vars['vrf_member_port_indices']['Vrf2']
)
class TestVrfIsolation():
@pytest.fixture(scope="class", autouse=True)
def setup_vrf_isolation(self, ptfhost, tbinfo):
gen_vrf_fib_file('Vrf1', tbinfo, ptfhost,
render_file='/tmp/vrf1_fib.txt')
gen_vrf_fib_file('Vrf2', tbinfo, ptfhost,
render_file='/tmp/vrf2_fib.txt')
gen_vrf_neigh_file('Vrf1', ptfhost, render_file="/tmp/vrf1_neigh.txt")
gen_vrf_neigh_file('Vrf2', ptfhost, render_file="/tmp/vrf2_neigh.txt")
def test_neigh_isolate_vrf1_from_vrf2(self, partial_ptf_runner):
# send packets from Vrf1
partial_ptf_runner(
testname="vrf_test.FwdTest",
fib_info_files=["/tmp/vrf2_neigh.txt"],
pkt_action='drop',
src_ports=g_vars['vrf_intf_member_port_indices']['Vrf1']['Vlan1000']
)
def test_neigh_isolate_vrf2_from_vrf1(self, partial_ptf_runner):
# send packets from Vrf2
partial_ptf_runner(
testname="vrf_test.FwdTest",
fib_info_files=["/tmp/vrf1_neigh.txt"],
pkt_action='drop',
src_ports=g_vars['vrf_intf_member_port_indices']['Vrf2']['Vlan2000']
)
def test_fib_isolate_vrf1_from_vrf2(self, partial_ptf_runner):
# send packets from Vrf1
partial_ptf_runner(
testname="vrf_test.FibTest",
fib_info_files=["/tmp/vrf2_fib.txt"],
pkt_action='drop',
src_ports=g_vars['vrf_intf_member_port_indices']['Vrf1']['Vlan1000']
)
def test_fib_isolate_vrf2_from_vrf1(self, partial_ptf_runner):
# send packets from Vrf2
partial_ptf_runner(
testname="vrf_test.FibTest",
fib_info_files=["/tmp/vrf1_fib.txt"],
pkt_action='drop',
src_ports=g_vars['vrf_intf_member_port_indices']['Vrf2']['Vlan2000']
)
class TestVrfAclRedirect():
c_vars = {}
@pytest.fixture(scope="class", autouse=True)
def is_redirect_supported(self, duthosts, rand_one_dut_hostname):
"""
Check if switch supports acl redirect_action, if not then skip test cases
"""
duthost = duthosts[rand_one_dut_hostname]
acl_stage_cap = duthost.shell(
'redis-cli -n 6 hget "ACL_STAGE_CAPABILITY_TABLE|INGRESS" action_list')['stdout']
if "REDIRECT_ACTION" not in acl_stage_cap:
pytest.skip("Switch does not support ACL REDIRECT_ACTION, supported actions {}".format(
acl_stage_cap))
@pytest.fixture(scope="class", autouse=True)
def setup_acl_redirect(self, duthosts, rand_one_dut_hostname, cfg_facts, tbinfo):
duthost = duthosts[rand_one_dut_hostname]
# -------- Setup ----------
# make sure neighs from Vlan2000 are resolved
vlan_peer_port = g_vars['vrf_intf_member_port_indices']['Vrf2']['Vlan2000'][0]
vlan_neigh_ip = g_vars['vlan_peer_ips'][(
'Vrf2', vlan_peer_port)]['ipv4'][0]
duthost.shell("ping {} -I {} -c 3 -f".format(vlan_neigh_ip.ip, 'Vrf2'))
vrf_intf_ports = g_vars['vrf_intf_member_port_indices']
src_ports = [vrf_intf_ports['Vrf1']['Vlan1000'][0]]
dst_ports = [vrf_intf_ports['Vrf1'][PORTCHANNEL_TEMP_1]]
pc1_intf_ips = get_intf_ips(PORTCHANNEL_TEMP_1, cfg_facts)
pc1_v4_neigh_ips = [str(ip.ip+1) for ip in pc1_intf_ips['ipv4']]
pc1_v6_neigh_ips = [str(ip.ip+1) for ip in pc1_intf_ips['ipv6']]
pc2_if_ips = get_intf_ips(PORTCHANNEL_TEMP_2, cfg_facts)
pc2_v4_neigh_ips = [(PORTCHANNEL_TEMP_2, str(ip.ip+1))
for ip in pc2_if_ips['ipv4']]
pc2_v6_neigh_ips = [(PORTCHANNEL_TEMP_2, str(ip.ip+1))
for ip in pc2_if_ips['ipv6']]
pc_vrf2_if_name = PORTCHANNEL_TEMP_NAME.format(
len(tbinfo['topo']['properties']['topology']['VMs']))
pc_vrf2_if_ips = get_intf_ips(pc_vrf2_if_name, cfg_facts)
pc_vrf2_v4_neigh_ips = [(pc_vrf2_if_name, str(ip.ip+1))
for ip in pc_vrf2_if_ips['ipv4']]
pc_vrf2_v6_neigh_ips = [(pc_vrf2_if_name, str(ip.ip+1))
for ip in pc_vrf2_if_ips['ipv6']]
redirect_dst_ips = pc2_v4_neigh_ips + pc_vrf2_v4_neigh_ips
redirect_dst_ipv6s = pc2_v6_neigh_ips + pc_vrf2_v6_neigh_ips
redirect_dst_ports = []
redirect_dst_ports.append(vrf_intf_ports['Vrf1'][PORTCHANNEL_TEMP_2])
redirect_dst_ports.append(vrf_intf_ports['Vrf2'][pc_vrf2_if_name])
self.c_vars['src_ports'] = src_ports
self.c_vars['dst_ports'] = dst_ports
self.c_vars['redirect_dst_ports'] = redirect_dst_ports
self.c_vars['pc1_v4_neigh_ips'] = pc1_v4_neigh_ips
self.c_vars['pc1_v6_neigh_ips'] = pc1_v6_neigh_ips
# load acl redirect configuration
extra_vars = {
'src_port': get_vlan_members('Vlan1000', cfg_facts)[0],
'redirect_dst_ips': redirect_dst_ips,
'redirect_dst_ipv6s': redirect_dst_ipv6s
}
duthost.host.options['variable_manager'].extra_vars.update(extra_vars)
duthost.template(src="vrf/vrf_acl_redirect.j2",
dest="/tmp/vrf_acl_redirect.json")
duthost.shell("config load -y /tmp/vrf_acl_redirect.json")
# -------- Testing ----------
yield
# -------- Teardown ----------
duthost.shell(
"redis-cli -n 4 del 'ACL_RULE|VRF_ACL_REDIRECT_V4|rule1'")
duthost.shell(
"redis-cli -n 4 del 'ACL_RULE|VRF_ACL_REDIRECT_V6|rule1'")
duthost.shell("redis-cli -n 4 del 'ACL_TABLE|VRF_ACL_REDIRECT_V4'")
duthost.shell("redis-cli -n 4 del 'ACL_TABLE|VRF_ACL_REDIRECT_V6'")
def test_origin_ports_recv_no_pkts_v4(self, partial_ptf_runner, ptfhost):
# verify origin dst ports should not receive packets any more
gen_specific_neigh_file(self.c_vars['pc1_v4_neigh_ips'], self.c_vars['dst_ports'],
'/tmp/pc01_neigh_ipv4.txt', ptfhost)
partial_ptf_runner(
testname="vrf_test.FwdTest",
pkt_action='drop',
src_ports=self.c_vars['src_ports'],
fib_info_files=['/tmp/pc01_neigh_ipv4.txt']
)
def test_origin_ports_recv_no_pkts_v6(self, partial_ptf_runner, ptfhost):
# verify origin dst ports should not receive packets any more
gen_specific_neigh_file(self.c_vars['pc1_v6_neigh_ips'], self.c_vars['dst_ports'],
'/tmp/pc01_neigh_ipv6.txt', ptfhost)
partial_ptf_runner(
testname="vrf_test.FwdTest",
pkt_action='drop',
src_ports=self.c_vars['src_ports'],
fib_info_files=['/tmp/pc01_neigh_ipv6.txt']
)
def test_redirect_to_new_ports_v4(self, partial_ptf_runner, ptfhost):
# verify redicect ports should receive packets
gen_specific_neigh_file(self.c_vars['pc1_v4_neigh_ips'], self.c_vars['redirect_dst_ports'],
'/tmp/redirect_pc01_neigh_ipv4.txt', ptfhost)
partial_ptf_runner(
testname="vrf_test.FwdTest",
src_ports=self.c_vars['src_ports'],
test_balancing=True,
balancing_test_times=1000,
balancing_test_ratio=1.0, # test redirect balancing
fib_info_files=['/tmp/redirect_pc01_neigh_ipv4.txt']
)
def test_redirect_to_new_ports_v6(self, partial_ptf_runner, ptfhost):
# verify redicect ports should receive packets
gen_specific_neigh_file(self.c_vars['pc1_v6_neigh_ips'], self.c_vars['redirect_dst_ports'],
'/tmp/redirect_pc01_neigh_ipv6.txt', ptfhost)
partial_ptf_runner(
testname="vrf_test.FwdTest",
src_ports=self.c_vars['src_ports'],
test_balancing=True,
balancing_test_times=1000,
balancing_test_ratio=1.0, # test redirect balancing
fib_info_files=['/tmp/redirect_pc01_neigh_ipv6.txt']
)
class TestVrfLoopbackIntf():
c_vars = {}
announce_prefix = '10.10.10.0/26'
@pytest.fixture(scope="class", autouse=True)
def setup_vrf_loopback(self, duthosts, rand_one_dut_hostname, ptfhost, cfg_facts, tbinfo):
duthost = duthosts[rand_one_dut_hostname]
# -------- Setup ----------
lb0_ip_facts = get_intf_ips('Loopback0', cfg_facts)
vlan1000_ip_facts = get_intf_ips('Vlan1000', cfg_facts)
lb2_ip_facts = get_intf_ips('Loopback2', cfg_facts)
vlan2000_ip_facts = get_intf_ips('Vlan2000', cfg_facts)
self.c_vars['lb0_ip_facts'] = lb0_ip_facts
self.c_vars['lb2_ip_facts'] = lb2_ip_facts
self.c_vars['vlan1000_ip_facts'] = vlan1000_ip_facts
self.c_vars['vlan2000_ip_facts'] = vlan2000_ip_facts
# deploy routes to loopback
for ver, ips in list(lb0_ip_facts.items()):
for vlan_ip in vlan1000_ip_facts[ver]:
nexthop = vlan_ip.ip
break
for ip in ips:
ptfhost.shell("ip netns exec {} ip route add {} nexthop via {} ".format(
g_vars['vlan_peer_vrf2ns_map']['Vrf1'], ip, nexthop))
for ver, ips in list(lb2_ip_facts.items()):
for vlan_ip in vlan2000_ip_facts[ver]:
nexthop = vlan_ip.ip
break
for ip in ips:
ptfhost.shell("ip netns exec {} ip route add {} nexthop via {} ".format(
g_vars['vlan_peer_vrf2ns_map']['Vrf2'], ip, nexthop))
duthost.shell("sysctl -w net.ipv6.ip_nonlocal_bind=1")
# -------- Testing ----------
yield
# -------- Teardown ----------
# routes on ptf could be flushed when remove vrfs
duthost.shell("sysctl -w net.ipv6.ip_nonlocal_bind=0")
def test_ping_vrf1_loopback(self, ptfhost, duthosts, rand_one_dut_hostname):
duthost = duthosts[rand_one_dut_hostname]
for ver, ips in list(self.c_vars['lb0_ip_facts'].items()):
for ip in ips:
if ip.version == 4:
# FIXME Within a vrf, currently ping(4) does not support using
# an ip of loopback intface as source(it complains 'Cannot assign
# requested address'). An alternative is ping the loopback address
# from ptf
ptfhost.shell("ip netns exec {} ping {} -c 3 -f -W2".format(
g_vars['vlan_peer_vrf2ns_map']['Vrf1'], ip.ip))
else:
neigh_ip6 = self.c_vars['vlan1000_ip_facts']['ipv6'][0].ip + 1
duthost.shell(
"ping6 {} -I Vrf1 -I {} -c 3 -f -W2".format(neigh_ip6, ip.ip))
def test_ping_vrf2_loopback(self, ptfhost, duthosts, rand_one_dut_hostname):
duthost = duthosts[rand_one_dut_hostname]
for ver, ips in list(self.c_vars['lb2_ip_facts'].items()):
for ip in ips:
if ip.version == 4:
# FIXME Within a vrf, currently ping(4) does not support using
# an ip of loopback intface as source(it complains 'Cannot assign
# requested address'). An alternative is ping the loopback address
# from ptf
ptfhost.shell("ip netns exec {} ping {} -c 3 -f -W2".format(
g_vars['vlan_peer_vrf2ns_map']['Vrf2'], ip.ip))
else: